code
stringlengths
2
1.05M
import React from 'react' import { Step, Stepper, StepButton, StepContent } from 'material-ui/Stepper' import RaisedButton from 'material-ui/RaisedButton' import FlatButton from 'material-ui/FlatButton' import Introduction from './introduction' import Create from './create' import Review from './review' import { generateCrossword } from '../../actions/crosswordactions' class Flow extends React.Component { constructor(props) { super(props) this.state = { stepIndex: 0 } } handleNext() { const {stepIndex} = this.state if (stepIndex < 2) { this.setState({stepIndex: stepIndex + 1}) } } handlePrev() { const {stepIndex} = this.state if (stepIndex > 0) { this.setState({stepIndex: stepIndex - 1}) } } generate() { generateCrossword() } render() { return ( <div style={{ margin: 20 }}> <Stepper activeStep={this.state.stepIndex} linear={false} orientation="vertical" > <Step> <StepButton onTouchTap={() => this.setState({stepIndex: 0})}> Introduction </StepButton> <StepContent> <Introduction handleNext={this.handleNext.bind(this)} /> </StepContent> </Step> <Step> <StepButton onTouchTap={() => this.setState({stepIndex: 1})}> Create a crossword puzzle </StepButton> <StepContent> <Create handleNext={this.handleNext.bind(this)} handlePrev={this.handlePrev.bind(this)} generate={this.generate.bind(this)} /> </StepContent> </Step> <Step> <StepButton onTouchTap={() => this.setState({stepIndex: 2})}> Review crossword puzzle </StepButton> <StepContent> <Review handlePrev={this.handlePrev.bind(this)} generate={this.generate.bind(this)} /> </StepContent> </Step> </Stepper> </div> ) } } export default Flow
const colBase = { width: '100%', display: 'block', position: 'relative' }; const style = { body: { fontFamily: 'Arial', fontSize: '18px', color: '#514a54', height: '100%' }, wrapper: { minHeight: '100%', height: 'auto !important', margin: '0px 25px -63px' }, header: { position: 'relative', textAlign: 'center', fontSize: '45px', padding: '15px', fontWeight: 'bold' }, intro: { textAlign: 'center', paddingBottom: '20px', fontSize: '15px' }, push: { height: '63px' }, colText: Object.assign({ backgroundColor: '#514a54', //#644f6d color: 'white' }, colBase), colDefault: Object.assign({ // backgroundColor: 'white' }, colBase), colReportTitle: { marginTop: '20px' }, textarea: { width: '100%', height: '200px', zIndex: 1, position: 'relative', backgroundColor: 'transparent', transition: '100ms background-color', color: 'white', border: 'none', margin: '5px 0px 1px 0px', fontSize: '18px', fontFamily: 'Arial', resize: 'none', outline: 'none', overflow: 'auto' }, highlight: { position: 'absolute', left: '2px', right: '5px', top: '7px', bottom: '8px', height: 'initial !important', color: 'transparent', overflow: 'hidden', transition: '100ms opacity', whiteSpace: 'pre-wrap', wordWrap: 'break-word' }, highlightInner: { boxSizing: 'border-box', width: '100%', height: '100%', overflow: 'hidden', lineHeight: 1.2, } }; export default style;
(function (global) { // map tells the System loader where to look for things var map = { 'app': 'app', // 'dist', '@angular': 'node_modules/@angular', 'rxjs': 'node_modules/rxjs', '@angular/router': 'node_modules/@angular/router', 'photoswipe': 'node_modules/photoswipe/dist/photoswipe.js', 'photoswipe-ui-default': 'node_modules/photoswipe/dist/photoswipe-ui-default.js', }; // packages tells the System loader how to load when no filename and/or no extension var packages = { 'app': { main: 'main.js', defaultExtension: 'js' }, 'rxjs': { defaultExtension: 'js' }, '@angular/router': { main: 'index.js', defaultExtension: 'js' } }; var ngPackageNames = [ 'common', 'compiler', 'core', 'http', 'platform-browser', 'platform-browser-dynamic', 'router', 'upgrade' ]; var paths = { //'jquery': 'content/scripts/jquery-2.2.4.min.js' }; // Individual files (~300 requests): function packIndex(pkgName) { packages['@angular/' + pkgName] = { main: 'index.js', defaultExtension: 'js' }; } // Bundled (~40 requests): function packUmd(pkgName) { packages['@angular/' + pkgName] = { main: '/bundles/' + pkgName + '.umd.js', defaultExtension: 'js' }; } // Most environments should use UMD; some (Karma) need the individual index files var setPackageConfig = System.packageWithIndex ? packIndex : packUmd; // Add package entries for angular packages ngPackageNames.forEach(setPackageConfig); var config = { map: map, packages: packages, paths: paths }; System.config(config); })(this);
export const ic_image_aspect_ratio_twotone = {"viewBox":"0 0 24 24","children":[{"name":"path","attribs":{"d":"M0 0h24v24H0z","fill":"none"},"children":[]},{"name":"path","attribs":{"d":"M4 18h16V6H4v12zm10-8h2v2h-2v-2zm0 4h2v2h-2v-2zm-4-4h2v2h-2v-2zm-4 0h2v2H6v-2z","opacity":".3"},"children":[]},{"name":"path","attribs":{"d":"M14 10h2v2h-2zm0 4h2v2h-2zm-8-4h2v2H6zm4 0h2v2h-2zm10-6H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm0 14H4V6h16v12z"},"children":[]}]};
version https://git-lfs.github.com/spec/v1 oid sha256:db6470beeed99d04165b8374950bd20d084c72732e6ee7b091a0616953f72c49 size 195076
/* eslint-env node, mocha */ const should = require('chai').should(); const mongoose = require('mongoose'); mongoose.Promise = Promise; const getModel = require('../lib/model'); const mongoHost = process.env.MONGO_HOST || '127.0.0.1'; let connection; let JobModel; before((done) => { connection = mongoose.createConnection(`mongodb://${mongoHost}/monq_test`); connection.on('error', console.error.bind(console)); connection.once('open', () => { JobModel = getModel(connection, 'Job'); done(); }); }); after((done) => { connection.db.dropDatabase((err) => { if (err) { return done(err); } connection.close(done); }); }); afterEach((done) => { JobModel.collection.drop(() => { delete connection.models.Job; done(); }); }); describe('JobModel', () => { it('should have some props', () => { JobModel.should.have.property('collection'); JobModel.should.have.property('schema'); JobModel.should.have.property('db'); JobModel.should.have.property('model'); JobModel.should.have.property('modelName'); JobModel.should.have.property('base'); }); it('should sucess create record', (done) => { const job = new JobModel({ queue: 'queue', name: 'test', status: 'queued', enqueued: new Date() }); job.save(assert); function assert(err, result) { should.not.exist(err); result.should.have.property('queue', 'queue'); result.should.have.property('name', 'test'); done(); } }); });
/** * Created by nuintun on 2015/12/4. * See: https://github.com/rsms/js-lru */ 'use strict'; /** * A doubly linked list-based Least Recently Used (LRU) cache. Will keep most * recently used items while discarding least recently used items when its limit * is reached. * * Licensed under MIT. Copyright (c) 2010 Rasmus Andersson <http://hunch.se/> * See README.md for details. * * Illustration of the design: * * entry entry entry entry * ______ ______ ______ ______ * | head |.newer => | |.newer => | |.newer => | tail | * | A | | B | | C | | D | * |______| <= older.|______| <= older.|______| <= older.|______| * * removed <-- <-- <-- <-- <-- <-- <-- <-- <-- <-- <-- added */ function LRUCache(limit){ // Current size of the cache. (Read-only). this.size = 0; // Maximum number of items this cache can hold. this.limit = limit; this._keymap = {}; } /** * Put <value> into the cache associated with <key>. Returns the entry which was * removed to make room for the new entry. Otherwise undefined is returned * (i.e. if there was enough room already). */ LRUCache.prototype.put = function (key, value){ var entry = { key: key, value: value }; // Note: No protection agains replacing, and thus orphan entries. By design. this._keymap[key] = entry; if (this.tail) { // link previous tail to the new tail (entry) this.tail.newer = entry; entry.older = this.tail; } else { // we're first in -- yay this.head = entry; } // add new entry to the end of the linked list -- it's now the freshest entry. this.tail = entry; if (this.size === this.limit) { // we hit the limit -- remove the head return this.shift(); } else { // increase the size counter this.size++; } }; /** * Purge the least recently used (oldest) entry from the cache. Returns the * removed entry or undefined if the cache was empty. * * If you need to perform any form of finalization of purged items, this is a * good place to do it. Simply override/replace this function: * * var c = new LRUCache(123); * c.shift = function() { * var entry = LRUCache.prototype.shift.call(this); * doSomethingWith(entry); * return entry; * } */ LRUCache.prototype.shift = function (){ // todo: handle special case when limit === 1 var entry = this.head; if (entry) { if (this.head.newer) { this.head = this.head.newer; this.head.older = undefined; } else { this.head = undefined; } // Remove last strong reference to <entry> and remove links from the purged // entry being returned: entry.newer = entry.older = undefined; // delete is slow, but we need to do this to avoid uncontrollable growth: delete this._keymap[entry.key]; } return entry; }; /** * Get and register recent use of <key>. Returns the value associated with <key> * or undefined if not in cache. */ LRUCache.prototype.get = function (key, returnEntry){ // First, find our cache entry var entry = this._keymap[key]; // Not cached. Sorry. if (entry === undefined) { return; } // As <key> was found in the cache, register it as being requested recently if (entry === this.tail) { // Already the most recenlty used entry, so no need to update the list return returnEntry ? entry : entry.value; } // HEAD--------------TAIL // <.older .newer> // <--- add direction -- // A B C <D> E if (entry.newer) { if (entry === this.head) { this.head = entry.newer; } // C <-- E. entry.newer.older = entry.older; } // C. --> E if (entry.older) { entry.older.newer = entry.newer; } // D --x entry.newer = undefined; // D. --> E entry.older = this.tail; // E. <-- D if (this.tail) { this.tail.newer = entry; } this.tail = entry; return returnEntry ? entry : entry.value; }; // ---------------------------------------------------------------------------- // Following code is optional and can be removed without breaking the core // functionality. /** * Check if <key> is in the cache without registering recent use. Feasible if * you do not want to chage the state of the cache, but only "peek" at it. * Returns the entry associated with <key> if found, or undefined if not found. */ LRUCache.prototype.find = function (key){ return this._keymap[key]; }; /** * Update the value of entry with <key>. Returns the old value, or undefined if * entry was not in the cache. */ LRUCache.prototype.set = function (key, value){ var oldvalue, entry = this.get(key, true); if (entry) { oldvalue = entry.value; entry.value = value; } else { oldvalue = this.put(key, value); if (oldvalue) { oldvalue = oldvalue.value; } } return oldvalue; }; /** * Remove entry <key> from cache and return its value. Returns undefined if not * found. */ LRUCache.prototype.remove = function (key){ var entry = this._keymap[key]; if (!entry) { return; } delete this._keymap[entry.key]; // need to do delete unfortunately if (entry.newer && entry.older) { // relink the older entry with the newer entry entry.older.newer = entry.newer; entry.newer.older = entry.older; } else if (entry.newer) { // remove the link to us entry.newer.older = undefined; // link the newer entry to head this.head = entry.newer; } else if (entry.older) { // remove the link to us entry.older.newer = undefined; // link the newer entry to head this.tail = entry.older; } else {// if(entry.older === undefined && entry.newer === undefined) { this.head = this.tail = undefined; } this.size--; return entry.value; }; /** Removes all entries */ LRUCache.prototype.removeAll = function (){ // This should be safe, as we never expose strong refrences to the outside this.head = this.tail = undefined; this.size = 0; this._keymap = {}; }; /** * Return an array containing all keys of entries stored in the cache object, in * arbitrary order. */ if (typeof Object.keys === 'function') { LRUCache.prototype.keys = function (){ return Object.keys(this._keymap); }; } else { LRUCache.prototype.keys = function (){ var keys = []; for (var k in this._keymap) { if (this._keymap.hasOwnProperty(k)) { keys.push(k); } } return keys; }; } /** * Call `fun` for each entry. Starting with the newest entry if `desc` is a true * value, otherwise starts with the oldest (head) enrty and moves towards the * tail. * * `fun` is called with 3 arguments in the context `context`: * `fun.call(context, Object key, Object value, LRUCache self)` */ LRUCache.prototype.forEach = function (fun, context, desc){ var entry; if (context === true) { desc = true; context = undefined; } else if (typeof context !== 'object') { context = this; } if (desc) { entry = this.tail; while (entry) { fun.call(context, entry.key, entry.value, this); entry = entry.older; } } else { entry = this.head; while (entry) { fun.call(context, entry.key, entry.value, this); entry = entry.newer; } } }; /** Returns a JSON (array) representation */ LRUCache.prototype.toJSON = function (){ var s = []; var entry = this.head; while (entry) { s.push({ key: entry.key.toJSON(), value: entry.value.toJSON() }); entry = entry.newer; } return s; }; /** Returns a String representation */ LRUCache.prototype.toString = function (){ var s = ''; var entry = this.head; while (entry) { s += String(entry.key) + ':' + entry.value; entry = entry.newer; if (entry) { s += ' < '; } } return s; };
/** * Created by Administrator on 2015/12/2. */ 'use strict'; require(['app'],function(app){ app.constant("referinURL", "/user/reset"); app.controller("forgetCtr", ["$scope","$state" ,"$rootScope","$http", "referinURL", "loocha", function ($scope, $state, $rootScope, $http, referinURL, loocha) { $scope.$on("$includeContentLoaded",function(){ /*setTimeout(function(){ $("input").placeholder(); },500);*/ }); $scope.user = { username: "", password: "", mobile: "", newpassword: "", code: "", img: "" }; getCodes(); $scope.repeat = function () { getCodes(); }; function getCodes() { $http.get(loocha+"/user/code?time=" + new Date().getTime()).success(function(data){ $scope.user.img = data; }); } $scope.showRegistered = function () { $rootScope.isShowLogin = false; $rootScope.isShowRegistered = true; $rootScope.isShowForget = false; }; $scope.referin = function () { var param = {}; param.name = $scope.user.username; param.password = $scope.user.password; param.newpassword = $scope.user.newpassword; param.code = $scope.user.code; var tramsform = function(data){ return $.param(data); }; $http.post(loocha+referinURL,param,{ headers:{'Content-type':'application/x-www-form-urlencoded; charset=UTF-8'}, transformRequest:tramsform }).success(function(data){ if(data.status == 2){ alert('用户不存在'); }else if(data.status == 4||data.status == 6){ alert('验证码错误'); }else if(data.status == 0){ alert('修改成功'); $state.go('login'); //window.location.href="#/login"; } }); }; $scope.showlogin = function () { $rootScope.isShowLogin = true; $rootScope.isShowRegistered = false; $rootScope.isShowForget = false; }; }]); });
'use strict'; var path = require('path'); var assert = require('yeoman-assert'); var app = require(path.resolve('generators/app')); // var helpers = require('yeoman-test'); describe('generator-swanky:app', function () { // before(function (done) { // helpers.run(path.join(__dirname, '../generators/app')) // .withPrompts({someAnswer: true}) // .on('end', done); // }); it('creates package.json file', function () { // assert.file([ // 'package.json' // ]); assert.equal(1, 1); }); });
/*! Chosen, a Select Box Enhancer for jQuery and Prototype by Patrick Filler for Harvest, http://getharvest.com Version 1.6.1 Full source at https://github.com/harvesthq/chosen Copyright (c) 2011-2016 Harvest http://getharvest.com MIT License, https://github.com/harvesthq/chosen/blob/master/LICENSE.md This file is generated by `grunt build`, do not edit it by hand. */ (function() { var $, AbstractChosen, Chosen, SelectParser, _ref, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; SelectParser = (function() { function SelectParser() { this.options_index = 0; this.parsed = []; } SelectParser.prototype.add_node = function(child) { if (child.nodeName.toUpperCase() === "OPTGROUP") { return this.add_group(child); } else { return this.add_option(child); } }; SelectParser.prototype.add_group = function(group) { var group_position, option, _i, _len, _ref, _results; group_position = this.parsed.length; this.parsed.push({ array_index: group_position, group: true, label: this.escapeExpression(group.label), title: group.title ? group.title : void 0, children: 0, disabled: group.disabled, classes: group.className }); _ref = group.childNodes; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { option = _ref[_i]; _results.push(this.add_option(option, group_position, group.disabled)); } return _results; }; SelectParser.prototype.add_option = function(option, group_position, group_disabled) { if (option.nodeName.toUpperCase() === "OPTION") { if (option.text !== "") { if (group_position != null) { this.parsed[group_position].children += 1; } this.parsed.push({ array_index: this.parsed.length, options_index: this.options_index, value: option.value, text: option.text, html: option.innerHTML, title: option.title ? option.title : void 0, selected: option.selected, disabled: group_disabled === true ? group_disabled : option.disabled, group_array_index: group_position, group_label: group_position != null ? this.parsed[group_position].label : null, classes: option.className, style: option.style.cssText }); } else { this.parsed.push({ array_index: this.parsed.length, options_index: this.options_index, empty: true }); } return this.options_index += 1; } }; SelectParser.prototype.escapeExpression = function(text) { var map, unsafe_chars; if ((text == null) || text === false) { return ""; } if (!/[\&\<\>\"\'\`]/.test(text)) { return text; } map = { "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#x27;", "`": "&#x60;" }; unsafe_chars = /&(?!\w+;)|[\<\>\"\'\`]/g; return text.replace(unsafe_chars, function(chr) { return map[chr] || "&amp;"; }); }; return SelectParser; })(); SelectParser.select_to_array = function(select) { var child, parser, _i, _len, _ref; parser = new SelectParser(); _ref = select.childNodes; for (_i = 0, _len = _ref.length; _i < _len; _i++) { child = _ref[_i]; parser.add_node(child); } return parser.parsed; }; AbstractChosen = (function() { function AbstractChosen(form_field, options) { this.form_field = form_field; this.options = options != null ? options : {}; if (!AbstractChosen.browser_is_supported()) { return; } this.is_multiple = this.form_field.multiple; this.set_default_text(); this.set_default_values(); this.setup(); this.set_up_html(); this.register_observers(); this.on_ready(); } AbstractChosen.prototype.set_default_values = function() { var _this = this; this.click_test_action = function(evt) { return _this.test_active_click(evt); }; this.activate_action = function(evt) { return _this.activate_field(evt); }; this.active_field = false; this.mouse_on_container = false; this.results_showing = false; this.result_highlighted = null; this.allow_single_deselect = (this.options.allow_single_deselect != null) && (this.form_field.options[0] != null) && this.form_field.options[0].text === "" ? this.options.allow_single_deselect : false; this.disable_search_threshold = this.options.disable_search_threshold || 0; this.disable_search = this.options.disable_search || false; this.enable_split_word_search = this.options.enable_split_word_search != null ? this.options.enable_split_word_search : true; this.group_search = this.options.group_search != null ? this.options.group_search : true; this.search_contains = this.options.search_contains || false; this.single_backstroke_delete = this.options.single_backstroke_delete != null ? this.options.single_backstroke_delete : true; this.max_selected_options = this.options.max_selected_options || Infinity; this.inherit_select_classes = this.options.inherit_select_classes || false; this.display_selected_options = this.options.display_selected_options != null ? this.options.display_selected_options : true; this.display_disabled_options = this.options.display_disabled_options != null ? this.options.display_disabled_options : true; this.include_group_label_in_selected = this.options.include_group_label_in_selected || false; this.max_shown_results = this.options.max_shown_results || Number.POSITIVE_INFINITY; return this.case_sensitive_search = this.options.case_sensitive_search || false; }; AbstractChosen.prototype.set_default_text = function() { if (this.form_field.getAttribute("data-placeholder")) { this.default_text = this.form_field.getAttribute("data-placeholder"); } else if (this.is_multiple) { this.default_text = this.options.placeholder_text_multiple || this.options.placeholder_text || AbstractChosen.default_multiple_text; } else { this.default_text = this.options.placeholder_text_single || this.options.placeholder_text || AbstractChosen.default_single_text; } return this.results_none_found = this.form_field.getAttribute("data-no_results_text") || this.options.no_results_text || AbstractChosen.default_no_result_text; }; AbstractChosen.prototype.choice_label = function(item) { if (this.include_group_label_in_selected && (item.group_label != null)) { return "<b class='group-name'>" + item.group_label + "</b>" + item.html; } else { return item.html; } }; AbstractChosen.prototype.mouse_enter = function() { return this.mouse_on_container = true; }; AbstractChosen.prototype.mouse_leave = function() { return this.mouse_on_container = false; }; AbstractChosen.prototype.input_focus = function(evt) { var _this = this; if (this.is_multiple) { if (!this.active_field) { return setTimeout((function() { return _this.container_mousedown(); }), 50); } } else { if (!this.active_field) { return this.activate_field(); } } }; AbstractChosen.prototype.input_blur = function(evt) { var _this = this; if (!this.mouse_on_container) { this.active_field = false; return setTimeout((function() { return _this.blur_test(); }), 100); } }; AbstractChosen.prototype.results_option_build = function(options) { var content, data, data_content, shown_results, _i, _len, _ref; content = ''; shown_results = 0; _ref = this.results_data; for (_i = 0, _len = _ref.length; _i < _len; _i++) { data = _ref[_i]; data_content = ''; if (data.group) { data_content = this.result_add_group(data); } else { data_content = this.result_add_option(data); } if (data_content !== '') { shown_results++; content += data_content; } if (options != null ? options.first : void 0) { if (data.selected && this.is_multiple) { this.choice_build(data); } else if (data.selected && !this.is_multiple) { this.single_set_selected_text(this.choice_label(data)); } } if (shown_results >= this.max_shown_results) { break; } } return content; }; AbstractChosen.prototype.result_add_option = function(option) { var classes, option_el; if (!option.search_match) { return ''; } if (!this.include_option_in_results(option)) { return ''; } classes = []; if (!option.disabled && !(option.selected && this.is_multiple)) { classes.push("active-result"); } if (option.disabled && !(option.selected && this.is_multiple)) { classes.push("disabled-result"); } if (option.selected) { classes.push("result-selected"); } if (option.group_array_index != null) { classes.push("group-option"); } if (option.classes !== "") { classes.push(option.classes); } option_el = document.createElement("li"); option_el.className = classes.join(" "); option_el.style.cssText = option.style; option_el.setAttribute("data-option-array-index", option.array_index); option_el.innerHTML = option.search_text; if (option.title) { option_el.title = option.title; } return this.outerHTML(option_el); }; AbstractChosen.prototype.result_add_group = function(group) { var classes, group_el; if (!(group.search_match || group.group_match)) { return ''; } if (!(group.active_options > 0)) { return ''; } classes = []; classes.push("group-result"); if (group.classes) { classes.push(group.classes); } group_el = document.createElement("li"); group_el.className = classes.join(" "); group_el.innerHTML = group.search_text; if (group.title) { group_el.title = group.title; } return this.outerHTML(group_el); }; AbstractChosen.prototype.results_update_field = function() { this.set_default_text(); if (!this.is_multiple) { this.results_reset_cleanup(); } this.result_clear_highlight(); this.results_build(); if (this.results_showing) { return this.winnow_results(); } }; AbstractChosen.prototype.reset_single_select_options = function() { var result, _i, _len, _ref, _results; _ref = this.results_data; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { result = _ref[_i]; if (result.selected) { _results.push(result.selected = false); } else { _results.push(void 0); } } return _results; }; AbstractChosen.prototype.results_toggle = function() { if (this.results_showing) { return this.results_hide(); } else { return this.results_show(); } }; AbstractChosen.prototype.results_search = function(evt) { if (this.results_showing) { return this.winnow_results(); } else { return this.results_show(); } }; AbstractChosen.prototype.winnow_results = function() { var escapedSearchText, option, regex, results, results_group, searchText, startpos, text, zregex, _i, _len, _ref; this.no_results_clear(); results = 0; searchText = this.get_search_text(); escapedSearchText = searchText.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); zregex = new RegExp(escapedSearchText, 'i'); regex = this.get_search_regex(escapedSearchText); _ref = this.results_data; for (_i = 0, _len = _ref.length; _i < _len; _i++) { option = _ref[_i]; option.search_match = false; results_group = null; if (this.include_option_in_results(option)) { if (option.group) { option.group_match = false; option.active_options = 0; } if ((option.group_array_index != null) && this.results_data[option.group_array_index]) { results_group = this.results_data[option.group_array_index]; if (results_group.active_options === 0 && results_group.search_match) { results += 1; } results_group.active_options += 1; } option.search_text = option.group ? option.label : option.html; if (!(option.group && !this.group_search)) { option.search_match = this.search_string_match(option.search_text, regex); if (option.search_match && !option.group) { results += 1; } if (option.search_match) { if (searchText.length) { startpos = option.search_text.search(zregex); text = option.search_text.substr(0, startpos + searchText.length) + '</em>' + option.search_text.substr(startpos + searchText.length); option.search_text = text.substr(0, startpos) + '<em>' + text.substr(startpos); } if (results_group != null) { results_group.group_match = true; } } else if ((option.group_array_index != null) && this.results_data[option.group_array_index].search_match) { option.search_match = true; } } } } this.result_clear_highlight(); if (results < 1 && searchText.length) { this.update_results_content(""); return this.no_results(searchText); } else { this.update_results_content(this.results_option_build()); return this.winnow_results_set_highlight(); } }; AbstractChosen.prototype.get_search_regex = function(escaped_search_string) { var regex_anchor, regex_flag; regex_anchor = this.search_contains ? "" : "^"; regex_flag = this.case_sensitive_search ? "" : "i"; return new RegExp(regex_anchor + escaped_search_string, regex_flag); }; AbstractChosen.prototype.search_string_match = function(search_string, regex) { var part, parts, _i, _len; if (regex.test(search_string)) { return true; } else if (this.enable_split_word_search && (search_string.indexOf(" ") >= 0 || search_string.indexOf("[") === 0)) { parts = search_string.replace(/\[|\]/g, "").split(" "); if (parts.length) { for (_i = 0, _len = parts.length; _i < _len; _i++) { part = parts[_i]; if (regex.test(part)) { return true; } } } } }; AbstractChosen.prototype.choices_count = function() { var option, _i, _len, _ref; if (this.selected_option_count != null) { return this.selected_option_count; } this.selected_option_count = 0; _ref = this.form_field.options; for (_i = 0, _len = _ref.length; _i < _len; _i++) { option = _ref[_i]; if (option.selected) { this.selected_option_count += 1; } } return this.selected_option_count; }; AbstractChosen.prototype.choices_click = function(evt) { evt.preventDefault(); if (!(this.results_showing || this.is_disabled)) { return this.results_show(); } }; AbstractChosen.prototype.keyup_checker = function(evt) { var stroke, _ref; stroke = (_ref = evt.which) != null ? _ref : evt.keyCode; this.search_field_scale(); switch (stroke) { case 8: if (this.is_multiple && this.backstroke_length < 1 && this.choices_count() > 0) { return this.keydown_backstroke(); } else if (!this.pending_backstroke) { this.result_clear_highlight(); return this.results_search(); } break; case 13: evt.preventDefault(); if (this.results_showing) { return this.result_select(evt); } break; case 27: if (this.results_showing) { this.results_hide(); } return true; case 9: case 38: case 40: case 16: case 91: case 17: case 18: break; default: return this.results_search(); } }; AbstractChosen.prototype.clipboard_event_checker = function(evt) { var _this = this; return setTimeout((function() { return _this.results_search(); }), 50); }; AbstractChosen.prototype.container_width = function() { if (this.options.width != null) { return this.options.width; } else { return "" + this.form_field.offsetWidth + "px"; } }; AbstractChosen.prototype.include_option_in_results = function(option) { if (this.is_multiple && (!this.display_selected_options && option.selected)) { return false; } if (!this.display_disabled_options && option.disabled) { return false; } if (option.empty) { return false; } return true; }; AbstractChosen.prototype.search_results_touchstart = function(evt) { this.touch_started = true; return this.search_results_mouseover(evt); }; AbstractChosen.prototype.search_results_touchmove = function(evt) { this.touch_started = false; return this.search_results_mouseout(evt); }; AbstractChosen.prototype.search_results_touchend = function(evt) { if (this.touch_started) { return this.search_results_mouseup(evt); } }; AbstractChosen.prototype.outerHTML = function(element) { var tmp; if (element.outerHTML) { return element.outerHTML; } tmp = document.createElement("div"); tmp.appendChild(element); return tmp.innerHTML; }; AbstractChosen.browser_is_supported = function() { if ("Microsoft Internet Explorer" === window.navigator.appName) { return document.documentMode >= 8; } if (/iP(od|hone)/i.test(window.navigator.userAgent) || /IEMobile/i.test(window.navigator.userAgent) || /Windows Phone/i.test(window.navigator.userAgent) || /BlackBerry/i.test(window.navigator.userAgent) || /BB10/i.test(window.navigator.userAgent) || /Android.*Mobile/i.test(window.navigator.userAgent)) { return false; } return true; }; AbstractChosen.default_multiple_text = "Select Some Options"; AbstractChosen.default_single_text = "Select an Option"; AbstractChosen.default_no_result_text = "No results match"; return AbstractChosen; })(); $ = jQuery; $.fn.extend({ chosen: function(options) { if (!AbstractChosen.browser_is_supported()) { return this; } return this.each(function(input_field) { var $this, chosen; $this = $(this); chosen = $this.data('chosen'); if (options === 'destroy') { if (chosen instanceof Chosen) { chosen.destroy(); } return; } if (!(chosen instanceof Chosen)) { $this.data('chosen', new Chosen(this, options)); } }); } }); Chosen = (function(_super) { __extends(Chosen, _super); function Chosen() { _ref = Chosen.__super__.constructor.apply(this, arguments); return _ref; } Chosen.prototype.setup = function() { this.form_field_jq = $(this.form_field); this.current_selectedIndex = this.form_field.selectedIndex; return this.is_rtl = this.form_field_jq.hasClass("chosen-rtl"); }; Chosen.prototype.set_up_html = function() { var container_classes, container_props; container_classes = ["chosen-container"]; container_classes.push("chosen-container-" + (this.is_multiple ? "multi" : "single")); if (this.inherit_select_classes && this.form_field.className) { container_classes.push(this.form_field.className); } if (this.is_rtl) { container_classes.push("chosen-rtl"); } container_props = { 'class': container_classes.join(' '), 'style': "width: " + (this.container_width()) + ";", 'title': this.form_field.title }; if (this.form_field.id.length) { container_props.id = this.form_field.id.replace(/[^\w]/g, '_') + "_chosen"; } this.container = $("<div />", container_props); if (this.is_multiple) { this.container.html('<ul class="chosen-choices"><li class="search-field"><input type="text" value="' + this.default_text + '" class="default" autocomplete="off" style="width:25px;" /></li></ul><div class="chosen-drop"><ul class="chosen-results"></ul></div>'); } else { this.container.html('<a class="chosen-single chosen-default"><span>' + this.default_text + '</span><div><b></b></div></a><div class="chosen-drop"><div class="chosen-search"><input type="text" autocomplete="off" /></div><ul class="chosen-results"></ul></div>'); } this.form_field_jq.hide().after(this.container); this.dropdown = this.container.find('div.chosen-drop').first(); this.search_field = this.container.find('input').first(); this.search_results = this.container.find('ul.chosen-results').first(); this.search_field_scale(); this.search_no_results = this.container.find('li.no-results').first(); if (this.is_multiple) { this.search_choices = this.container.find('ul.chosen-choices').first(); this.search_container = this.container.find('li.search-field').first(); } else { this.search_container = this.container.find('div.chosen-search').first(); this.selected_item = this.container.find('.chosen-single').first(); } this.results_build(); this.set_tab_index(); return this.set_label_behavior(); }; Chosen.prototype.on_ready = function() { return this.form_field_jq.trigger("chosen:ready", { chosen: this }); }; Chosen.prototype.register_observers = function() { var _this = this; this.container.bind('touchstart.chosen', function(evt) { _this.container_mousedown(evt); return evt.preventDefault(); }); this.container.bind('touchend.chosen', function(evt) { _this.container_mouseup(evt); return evt.preventDefault(); }); this.container.bind('mousedown.chosen', function(evt) { _this.container_mousedown(evt); }); this.container.bind('mouseup.chosen', function(evt) { _this.container_mouseup(evt); }); this.container.bind('mouseenter.chosen', function(evt) { _this.mouse_enter(evt); }); this.container.bind('mouseleave.chosen', function(evt) { _this.mouse_leave(evt); }); this.search_results.bind('mouseup.chosen', function(evt) { _this.search_results_mouseup(evt); }); this.search_results.bind('mouseover.chosen', function(evt) { _this.search_results_mouseover(evt); }); this.search_results.bind('mouseout.chosen', function(evt) { _this.search_results_mouseout(evt); }); this.search_results.bind('mousewheel.chosen DOMMouseScroll.chosen', function(evt) { _this.search_results_mousewheel(evt); }); this.search_results.bind('touchstart.chosen', function(evt) { _this.search_results_touchstart(evt); }); this.search_results.bind('touchmove.chosen', function(evt) { _this.search_results_touchmove(evt); }); this.search_results.bind('touchend.chosen', function(evt) { _this.search_results_touchend(evt); }); this.form_field_jq.bind("chosen:updated.chosen", function(evt) { _this.results_update_field(evt); }); this.form_field_jq.bind("chosen:activate.chosen", function(evt) { _this.activate_field(evt); }); this.form_field_jq.bind("chosen:open.chosen", function(evt) { _this.container_mousedown(evt); }); this.form_field_jq.bind("chosen:close.chosen", function(evt) { _this.input_blur(evt); }); this.search_field.bind('blur.chosen', function(evt) { _this.input_blur(evt); }); this.search_field.bind('keyup.chosen', function(evt) { _this.keyup_checker(evt); }); this.search_field.bind('keydown.chosen', function(evt) { _this.keydown_checker(evt); }); this.search_field.bind('focus.chosen', function(evt) { _this.input_focus(evt); }); this.search_field.bind('cut.chosen', function(evt) { _this.clipboard_event_checker(evt); }); this.search_field.bind('paste.chosen', function(evt) { _this.clipboard_event_checker(evt); }); if (this.is_multiple) { return this.search_choices.bind('click.chosen', function(evt) { _this.choices_click(evt); }); } else { return this.container.bind('click.chosen', function(evt) { evt.preventDefault(); }); } }; Chosen.prototype.destroy = function() { $(this.container[0].ownerDocument).unbind("click.chosen", this.click_test_action); if (this.search_field[0].tabIndex) { this.form_field_jq[0].tabIndex = this.search_field[0].tabIndex; } this.container.remove(); this.form_field_jq.removeData('chosen'); return this.form_field_jq.show(); }; Chosen.prototype.search_field_disabled = function() { this.is_disabled = this.form_field_jq[0].disabled; if (this.is_disabled) { this.container.addClass('chosen-disabled'); this.search_field[0].disabled = true; if (!this.is_multiple) { this.selected_item.unbind("focus.chosen", this.activate_action); } return this.close_field(); } else { this.container.removeClass('chosen-disabled'); this.search_field[0].disabled = false; if (!this.is_multiple) { return this.selected_item.bind("focus.chosen", this.activate_action); } } }; Chosen.prototype.container_mousedown = function(evt) { if (!this.is_disabled) { if (evt && evt.type === "mousedown" && !this.results_showing) { evt.preventDefault(); } if (!((evt != null) && ($(evt.target)).hasClass("search-choice-close"))) { if (!this.active_field) { if (this.is_multiple) { this.search_field.val(""); } $(this.container[0].ownerDocument).bind('click.chosen', this.click_test_action); this.results_show(); } else if (!this.is_multiple && evt && (($(evt.target)[0] === this.selected_item[0]) || $(evt.target).parents("a.chosen-single").length)) { evt.preventDefault(); this.results_toggle(); } return this.activate_field(); } } }; Chosen.prototype.container_mouseup = function(evt) { if (evt.target.nodeName === "ABBR" && !this.is_disabled) { return this.results_reset(evt); } }; Chosen.prototype.search_results_mousewheel = function(evt) { var delta; if (evt.originalEvent) { delta = evt.originalEvent.deltaY || -evt.originalEvent.wheelDelta || evt.originalEvent.detail; } if (delta != null) { evt.preventDefault(); if (evt.type === 'DOMMouseScroll') { delta = delta * 40; } return this.search_results.scrollTop(delta + this.search_results.scrollTop()); } }; Chosen.prototype.blur_test = function(evt) { if (!this.active_field && this.container.hasClass("chosen-container-active")) { return this.close_field(); } }; Chosen.prototype.close_field = function() { $(this.container[0].ownerDocument).unbind("click.chosen", this.click_test_action); this.active_field = false; this.results_hide(); this.container.removeClass("chosen-container-active"); this.clear_backstroke(); this.show_search_field_default(); return this.search_field_scale(); }; Chosen.prototype.activate_field = function() { this.container.addClass("chosen-container-active"); this.active_field = true; this.search_field.val(this.search_field.val()); return this.search_field.focus(); }; Chosen.prototype.test_active_click = function(evt) { var active_container; active_container = $(evt.target).closest('.chosen-container'); if (active_container.length && this.container[0] === active_container[0]) { return this.active_field = true; } else { return this.close_field(); } }; Chosen.prototype.results_build = function() { this.parsing = true; this.selected_option_count = null; this.results_data = SelectParser.select_to_array(this.form_field); if (this.is_multiple) { this.search_choices.find("li.search-choice").remove(); } else if (!this.is_multiple) { this.single_set_selected_text(); if (this.disable_search || this.form_field.options.length <= this.disable_search_threshold) { this.search_field[0].readOnly = true; this.container.addClass("chosen-container-single-nosearch"); } else { this.search_field[0].readOnly = false; this.container.removeClass("chosen-container-single-nosearch"); } } this.update_results_content(this.results_option_build({ first: true })); this.search_field_disabled(); this.show_search_field_default(); this.search_field_scale(); return this.parsing = false; }; Chosen.prototype.result_do_highlight = function(el) { var high_bottom, high_top, maxHeight, visible_bottom, visible_top; if (el.length) { this.result_clear_highlight(); this.result_highlight = el; this.result_highlight.addClass("highlighted"); maxHeight = parseInt(this.search_results.css("maxHeight"), 10); visible_top = this.search_results.scrollTop(); visible_bottom = maxHeight + visible_top; high_top = this.result_highlight.position().top + this.search_results.scrollTop(); high_bottom = high_top + this.result_highlight.outerHeight(); if (high_bottom >= visible_bottom) { return this.search_results.scrollTop((high_bottom - maxHeight) > 0 ? high_bottom - maxHeight : 0); } else if (high_top < visible_top) { return this.search_results.scrollTop(high_top); } } }; Chosen.prototype.result_clear_highlight = function() { if (this.result_highlight) { this.result_highlight.removeClass("highlighted"); } return this.result_highlight = null; }; Chosen.prototype.results_show = function() { if (this.is_multiple && this.max_selected_options <= this.choices_count()) { this.form_field_jq.trigger("chosen:maxselected", { chosen: this }); return false; } this.container.addClass("chosen-with-drop"); this.results_showing = true; this.search_field.focus(); this.search_field.val(this.search_field.val()); this.winnow_results(); return this.form_field_jq.trigger("chosen:showing_dropdown", { chosen: this }); }; Chosen.prototype.update_results_content = function(content) { return this.search_results.html(content); }; Chosen.prototype.results_hide = function() { if (this.results_showing) { this.result_clear_highlight(); this.container.removeClass("chosen-with-drop"); this.form_field_jq.trigger("chosen:hiding_dropdown", { chosen: this }); } return this.results_showing = false; }; Chosen.prototype.set_tab_index = function(el) { var ti; if (this.form_field.tabIndex) { ti = this.form_field.tabIndex; this.form_field.tabIndex = -1; return this.search_field[0].tabIndex = ti; } }; Chosen.prototype.set_label_behavior = function() { var _this = this; this.form_field_label = this.form_field_jq.parents("label"); if (!this.form_field_label.length && this.form_field.id.length) { this.form_field_label = $("label[for='" + this.form_field.id + "']"); } if (this.form_field_label.length > 0) { return this.form_field_label.bind('click.chosen', function(evt) { if (_this.is_multiple) { return _this.container_mousedown(evt); } else { return _this.activate_field(); } }); } }; Chosen.prototype.show_search_field_default = function() { if (this.is_multiple && this.choices_count() < 1 && !this.active_field) { this.search_field.val(this.default_text); return this.search_field.addClass("default"); } else { this.search_field.val(""); return this.search_field.removeClass("default"); } }; Chosen.prototype.search_results_mouseup = function(evt) { var target; target = $(evt.target).hasClass("active-result") ? $(evt.target) : $(evt.target).parents(".active-result").first(); if (target.length) { this.result_highlight = target; this.result_select(evt); return this.search_field.focus(); } }; Chosen.prototype.search_results_mouseover = function(evt) { var target; target = $(evt.target).hasClass("active-result") ? $(evt.target) : $(evt.target).parents(".active-result").first(); if (target) { return this.result_do_highlight(target); } }; Chosen.prototype.search_results_mouseout = function(evt) { if ($(evt.target).hasClass("active-result" || $(evt.target).parents('.active-result').first())) { return this.result_clear_highlight(); } }; Chosen.prototype.choice_build = function(item) { var choice, close_link, _this = this; choice = $('<li />', { "class": "search-choice" }).html("<span>" + (this.choice_label(item)) + "</span>"); if (item.disabled) { choice.addClass('search-choice-disabled'); } else { close_link = $('<a />', { "class": 'search-choice-close', 'data-option-array-index': item.array_index }); close_link.bind('click.chosen', function(evt) { return _this.choice_destroy_link_click(evt); }); choice.append(close_link); } return this.search_container.before(choice); }; Chosen.prototype.choice_destroy_link_click = function(evt) { evt.preventDefault(); evt.stopPropagation(); if (!this.is_disabled) { return this.choice_destroy($(evt.target)); } }; Chosen.prototype.choice_destroy = function(link) { if (this.result_deselect(link[0].getAttribute("data-option-array-index"))) { this.show_search_field_default(); if (this.is_multiple && this.choices_count() > 0 && this.search_field.val().length < 1) { this.results_hide(); } link.parents('li').first().remove(); return this.search_field_scale(); } }; Chosen.prototype.results_reset = function() { this.reset_single_select_options(); this.form_field.options[0].selected = true; this.single_set_selected_text(); this.show_search_field_default(); this.results_reset_cleanup(); this.form_field_jq.trigger("change"); if (this.active_field) { return this.results_hide(); } }; Chosen.prototype.results_reset_cleanup = function() { this.current_selectedIndex = this.form_field.selectedIndex; return this.selected_item.find("abbr").remove(); }; Chosen.prototype.result_select = function(evt) { var high, item; if (this.result_highlight) { high = this.result_highlight; this.result_clear_highlight(); if (this.is_multiple && this.max_selected_options <= this.choices_count()) { this.form_field_jq.trigger("chosen:maxselected", { chosen: this }); return false; } if (this.is_multiple) { high.removeClass("active-result"); } else { this.reset_single_select_options(); } high.addClass("result-selected"); item = this.results_data[high[0].getAttribute("data-option-array-index")]; item.selected = true; this.form_field.options[item.options_index].selected = true; this.selected_option_count = null; if (this.is_multiple) { this.choice_build(item); } else { this.single_set_selected_text(this.choice_label(item)); } if (!((evt.metaKey || evt.ctrlKey) && this.is_multiple)) { this.results_hide(); } this.show_search_field_default(); if (this.is_multiple || this.form_field.selectedIndex !== this.current_selectedIndex) { this.form_field_jq.trigger("change", { 'selected': this.form_field.options[item.options_index].value }); } this.current_selectedIndex = this.form_field.selectedIndex; evt.preventDefault(); return this.search_field_scale(); } }; Chosen.prototype.single_set_selected_text = function(text) { if (text == null) { text = this.default_text; } if (text === this.default_text) { this.selected_item.addClass("chosen-default"); } else { this.single_deselect_control_build(); this.selected_item.removeClass("chosen-default"); } return this.selected_item.find("span").html(text); }; Chosen.prototype.result_deselect = function(pos) { var result_data; result_data = this.results_data[pos]; if (!this.form_field.options[result_data.options_index].disabled) { result_data.selected = false; this.form_field.options[result_data.options_index].selected = false; this.selected_option_count = null; this.result_clear_highlight(); if (this.results_showing) { this.winnow_results(); } this.form_field_jq.trigger("change", { deselected: this.form_field.options[result_data.options_index].value }); this.search_field_scale(); return true; } else { return false; } }; Chosen.prototype.single_deselect_control_build = function() { if (!this.allow_single_deselect) { return; } if (!this.selected_item.find("abbr").length) { this.selected_item.find("span").first().after("<abbr class=\"search-choice-close\"></abbr>"); } return this.selected_item.addClass("chosen-single-with-deselect"); }; Chosen.prototype.get_search_text = function() { return $('<div/>').text($.trim(this.search_field.val())).html(); }; Chosen.prototype.winnow_results_set_highlight = function() { var do_high, selected_results; selected_results = !this.is_multiple ? this.search_results.find(".result-selected.active-result") : []; do_high = selected_results.length ? selected_results.first() : this.search_results.find(".active-result").first(); if (do_high != null) { return this.result_do_highlight(do_high); } }; Chosen.prototype.no_results = function(terms) { var no_results_html; no_results_html = $('<li class="no-results">' + this.results_none_found + ' "<span></span>"</li>'); no_results_html.find("span").first().html(terms); this.search_results.append(no_results_html); return this.form_field_jq.trigger("chosen:no_results", { chosen: this }); }; Chosen.prototype.no_results_clear = function() { return this.search_results.find(".no-results").remove(); }; Chosen.prototype.keydown_arrow = function() { var next_sib; if (this.results_showing && this.result_highlight) { next_sib = this.result_highlight.nextAll("li.active-result").first(); if (next_sib) { return this.result_do_highlight(next_sib); } } else { return this.results_show(); } }; Chosen.prototype.keyup_arrow = function() { var prev_sibs; if (!this.results_showing && !this.is_multiple) { return this.results_show(); } else if (this.result_highlight) { prev_sibs = this.result_highlight.prevAll("li.active-result"); if (prev_sibs.length) { return this.result_do_highlight(prev_sibs.first()); } else { if (this.choices_count() > 0) { this.results_hide(); } return this.result_clear_highlight(); } } }; Chosen.prototype.keydown_backstroke = function() { var next_available_destroy; if (this.pending_backstroke) { this.choice_destroy(this.pending_backstroke.find("a").first()); return this.clear_backstroke(); } else { next_available_destroy = this.search_container.siblings("li.search-choice").last(); if (next_available_destroy.length && !next_available_destroy.hasClass("search-choice-disabled")) { this.pending_backstroke = next_available_destroy; if (this.single_backstroke_delete) { return this.keydown_backstroke(); } else { return this.pending_backstroke.addClass("search-choice-focus"); } } } }; Chosen.prototype.clear_backstroke = function() { if (this.pending_backstroke) { this.pending_backstroke.removeClass("search-choice-focus"); } return this.pending_backstroke = null; }; Chosen.prototype.keydown_checker = function(evt) { var stroke, _ref1; stroke = (_ref1 = evt.which) != null ? _ref1 : evt.keyCode; this.search_field_scale(); if (stroke !== 8 && this.pending_backstroke) { this.clear_backstroke(); } switch (stroke) { case 8: this.backstroke_length = this.search_field.val().length; break; case 9: if (this.results_showing && !this.is_multiple) { this.result_select(evt); } this.mouse_on_container = false; break; case 13: if (this.results_showing) { evt.preventDefault(); } break; case 32: if (this.disable_search) { evt.preventDefault(); } break; case 38: evt.preventDefault(); this.keyup_arrow(); break; case 40: evt.preventDefault(); this.keydown_arrow(); break; } }; Chosen.prototype.search_field_scale = function() { var div, f_width, h, style, style_block, styles, w, _i, _len; if (this.is_multiple) { h = 0; w = 0; style_block = "position:absolute; left: -1000px; top: -1000px; display:none;"; styles = ['font-size', 'font-style', 'font-weight', 'font-family', 'line-height', 'text-transform', 'letter-spacing']; for (_i = 0, _len = styles.length; _i < _len; _i++) { style = styles[_i]; style_block += style + ":" + this.search_field.css(style) + ";"; } div = $('<div />', { 'style': style_block }); div.text(this.search_field.val()); $('body').append(div); w = div.width() + 25; div.remove(); f_width = this.container.outerWidth(); if (w > f_width - 10) { w = f_width - 10; } return this.search_field.css({ 'width': w + 'px' }); } }; return Chosen; })(AbstractChosen); }).call(this); // var config = { // '.chosen-select' : {}, // '.chosen-select-deselect' : {allow_single_deselect:true}, // '.chosen-select-no-single' : {disable_search_threshold:10}, // '.chosen-select-no-results': {no_results_text:'Oops, nothing found!'}, // '.chosen-select-width' : {width:"95%"} // } // for (var selector in config) { // $(selector).chosen(config[selector]); // }
import CoSelect from './select'; import CoOption from './option'; export { CoSelect, CoOption };
import React from 'react'; import { mount } from 'enzyme'; import toJson from 'enzyme-to-json'; import { ThemeProvider } from 'styled-components'; import { theme } from 'mcs-lite-theme'; import DataChannelAdapter from '../DataChannelAdapter'; it('should render HEX_DISPLAY correctly with default value to empty', () => { const wrapper = mount( <ThemeProvider theme={theme}> <DataChannelAdapter dataChannelProps={{ id: 'id', type: 'HEX_DISPLAY', values: {}, format: {}, }} eventHandler={() => {}} /> </ThemeProvider>, ); const tree = toJson(wrapper.find(DataChannelAdapter)); expect(tree).toMatchSnapshot(); }); it('should render HEX_DISPLAY correctly with value', () => { const wrapper = mount( <ThemeProvider theme={theme}> <DataChannelAdapter dataChannelProps={{ id: 'id', type: 'HEX_DISPLAY', values: { value: 'michaelhsu' }, format: {}, }} eventHandler={() => {}} /> </ThemeProvider>, ); const tree = toJson(wrapper.find(DataChannelAdapter)); expect(tree).toMatchSnapshot(); }); it('should render HEX_DISPLAY correctly with empty string', () => { const wrapper = mount( <ThemeProvider theme={theme}> <DataChannelAdapter dataChannelProps={{ id: 'id', type: 'HEX_DISPLAY', values: { value: '' }, format: {}, }} eventHandler={() => {}} /> </ThemeProvider>, ); const tree = toJson(wrapper.find(DataChannelAdapter)); expect(tree).toMatchSnapshot(); });
import React from 'react'; import {mount} from 'enzyme'; import ResponsiveMenu from '../src/ResponsiveMenu'; describe('ResponsiveMenu', () => { it('should render without throwing an error', () => { expect(mount( <ResponsiveMenu> <ResponsiveMenu.Item text="Test 1" icon="calendar"/> <ResponsiveMenu.Item text="Test 2" icon="calendar"/> </ResponsiveMenu>, )).toMatchSnapshot(); }); // it('should respond to changes', () => { // const mockOnChange = jest.fn(); // // const wrapper = mount( // <RadioGroup onChange={mockOnChange}> // <Form.Radio label="ABC" value="abc"/> // <Form.Radio label="DEF" value="def"/> // </RadioGroup>, // ); // const u = wrapper.find('.ui.radio.checkbox').first(); // u.simulate('click'); // // expect(mockOnChange.mock.calls.length).toBe(1); // expect(mockOnChange.mock.calls[0][0]).toEqual('abc'); // }); });
'use strict'; // Development specific configuration // ================================== module.exports = { // MongoDB connection options mongo: { uri: 'mongodb://localhost/teamanalyzer-dev' }, seedDB: true };
(function($){ $.fn.popupWindow = function(instanceSettings){ return this.each(function(){ $(this).click(function(){ $.fn.popupWindow.defaultSettings = { centerBrowser:0, // center window over browser window? {1 (YES) or 0 (NO)}. overrides top and left centerScreen:0, // center window over entire screen? {1 (YES) or 0 (NO)}. overrides top and left height:500, // sets the height in pixels of the window. left:0, // left position when the window appears. location:0, // determines whether the address bar is displayed {1 (YES) or 0 (NO)}. menubar:0, // determines whether the menu bar is displayed {1 (YES) or 0 (NO)}. resizable:0, // whether the window can be resized {1 (YES) or 0 (NO)}. Can also be overloaded using resizable. scrollbars:0, // determines whether scrollbars appear on the window {1 (YES) or 0 (NO)}. status:0, // whether a status line appears at the bottom of the window {1 (YES) or 0 (NO)}. width:500, // sets the width in pixels of the window. windowName:null, // name of window set from the name attribute of the element that invokes the click windowURL:null, // url used for the popup top:0, // top position when the window appears. toolbar:0, // determines whether a toolbar (includes the forward and back buttons) is displayed {1 (YES) or 0 (NO)}. suppressEvent: true }; settings = $.extend({}, $.fn.popupWindow.defaultSettings, instanceSettings || {}); var windowFeatures = 'height=' + settings.height + ',width=' + settings.width + ',toolbar=' + settings.toolbar + ',scrollbars=' + settings.scrollbars + ',status=' + settings.status + ',resizable=' + settings.resizable + ',location=' + settings.location + ',menuBar=' + settings.menubar; settings.windowName = this.name || settings.windowName; settings.windowURL = this.href || settings.windowURL; var centeredY,centeredX; if(settings.centerBrowser){ if ($.browser.msie) {//hacked together for IE browsers centeredY = (window.screenTop - 120) + ((((document.documentElement.clientHeight + 120)/2) - (settings.height/2))); centeredX = window.screenLeft + ((((document.body.offsetWidth + 20)/2) - (settings.width/2))); }else{ centeredY = window.screenY + (((window.outerHeight/2) - (settings.height/2))); centeredX = window.screenX + (((window.outerWidth/2) - (settings.width/2))); } window.open(settings.windowURL, settings.windowName, windowFeatures+',left=' + centeredX +',top=' + centeredY).focus(); }else if(settings.centerScreen){ centeredY = (screen.height - settings.height)/2; centeredX = (screen.width - settings.width)/2; window.open(settings.windowURL, settings.windowName, windowFeatures+',left=' + centeredX +',top=' + centeredY).focus(); }else{ window.open(settings.windowURL, settings.windowName, windowFeatures+',left=' + settings.left +',top=' + settings.top).focus(); } return !settings.suppressEvent; }); }); }; })(jQuery);
import Qty, { isQty } from "./constructor.js"; import { PREFIX_VALUES, OUTPUT_MAP, UNITY_ARRAY } from "./definitions.js"; import { assign, compareArray, isNumber, isString, round } from "./utils.js"; import NestedMap from "./nested-map.js"; /** * Default formatter * * @param {number} scalar - scalar value * @param {string} units - units as string * * @returns {string} formatted result */ function defaultFormatter(scalar, units) { return (scalar + " " + units).trim(); } /** * * Configurable Qty default formatter * * @type {function} * * @param {number} scalar * @param {string} units * * @returns {string} formatted result */ Qty.formatter = defaultFormatter; assign(Qty.prototype, { // returns the 'unit' part of the Unit object without the scalar units: function() { if (this._units !== undefined) { return this._units; } var numIsUnity = compareArray(this.numerator, UNITY_ARRAY); var denIsUnity = compareArray(this.denominator, UNITY_ARRAY); if (numIsUnity && denIsUnity) { this._units = ""; return this._units; } var numUnits = stringifyUnits(this.numerator); var denUnits = stringifyUnits(this.denominator); this._units = numUnits + (denIsUnity ? "" : ("/" + denUnits)); return this._units; }, /** * Stringifies the quantity * Deprecation notice: only units parameter is supported. * * @param {(number|string|Qty)} targetUnitsOrMaxDecimalsOrPrec - * target units if string, * max number of decimals if number, * passed to #toPrec before converting if Qty * * @param {number=} maxDecimals - Maximum number of decimals of * formatted output * * @returns {string} reparseable quantity as string */ toString: function(targetUnitsOrMaxDecimalsOrPrec, maxDecimals) { var targetUnits; if (isNumber(targetUnitsOrMaxDecimalsOrPrec)) { targetUnits = this.units(); maxDecimals = targetUnitsOrMaxDecimalsOrPrec; } else if (isString(targetUnitsOrMaxDecimalsOrPrec)) { targetUnits = targetUnitsOrMaxDecimalsOrPrec; } else if (isQty(targetUnitsOrMaxDecimalsOrPrec)) { return this.toPrec(targetUnitsOrMaxDecimalsOrPrec).toString(maxDecimals); } var out = this.to(targetUnits); var outScalar = maxDecimals !== undefined ? round(out.scalar, maxDecimals) : out.scalar; out = (outScalar + " " + out.units()).trim(); return out; }, /** * Format the quantity according to optional passed target units * and formatter * * @param {string} [targetUnits=current units] - * optional units to convert to before formatting * * @param {function} [formatter=Qty.formatter] - * delegates formatting to formatter callback. * formatter is called back with two parameters (scalar, units) * and should return formatted result. * If unspecified, formatting is delegated to default formatter * set to Qty.formatter * * @example * var roundingAndLocalizingFormatter = function(scalar, units) { * // localize or limit scalar to n max decimals for instance * // return formatted result * }; * var qty = Qty('1.1234 m'); * qty.format(); // same units, default formatter => "1.234 m" * qty.format("cm"); // converted to "cm", default formatter => "123.45 cm" * qty.format(roundingAndLocalizingFormatter); // same units, custom formatter => "1,2 m" * qty.format("cm", roundingAndLocalizingFormatter); // convert to "cm", custom formatter => "123,4 cm" * * @returns {string} quantity as string */ format: function(targetUnits, formatter) { if (arguments.length === 1) { if (typeof targetUnits === "function") { formatter = targetUnits; targetUnits = undefined; } } formatter = formatter || Qty.formatter; var targetQty = this.to(targetUnits); return formatter.call(this, targetQty.scalar, targetQty.units()); } }); var stringifiedUnitsCache = new NestedMap(); /** * Returns a string representing a normalized unit array * * @param {string[]} units Normalized unit array * @returns {string} String representing passed normalized unit array and * suitable for output * */ function stringifyUnits(units) { var stringified = stringifiedUnitsCache.get(units); if (stringified) { return stringified; } var isUnity = compareArray(units, UNITY_ARRAY); if (isUnity) { stringified = "1"; } else { stringified = simplify(getOutputNames(units)).join("*"); } // Cache result stringifiedUnitsCache.set(units, stringified); return stringified; } function getOutputNames(units) { var unitNames = [], token, tokenNext; for (var i = 0; i < units.length; i++) { token = units[i]; tokenNext = units[i + 1]; if (PREFIX_VALUES[token]) { unitNames.push(OUTPUT_MAP[token] + OUTPUT_MAP[tokenNext]); i++; } else { unitNames.push(OUTPUT_MAP[token]); } } return unitNames; } function simplify(units) { // this turns ['s','m','s'] into ['s2','m'] var unitCounts = units.reduce(function(acc, unit) { var unitCounter = acc[unit]; if (!unitCounter) { acc.push(unitCounter = acc[unit] = [unit, 0]); } unitCounter[1]++; return acc; }, []); return unitCounts.map(function(unitCount) { return unitCount[0] + (unitCount[1] > 1 ? unitCount[1] : ""); }); }
// VCE Project - Separator class // // A simple class to store input/output information and apply // various transformations to simulate a separation unit operation. // // Requires: // - vce_utils.js // - vce_math.js // // Andrew D. McGuire 2019 // a.mcguire227@gmail.com //---------------------------------------------------------- function Separator(options, debug) { /* Initialise the separator. */ // set some defaults var default_options = { x : null, y : null, z : null, L : null, V : null, F : null, T : null, P : null, A : null, components : [] }; var options = utils.merge_options(default_options, options); // initialise separator attributes this.x = options.x; this.y = options.y; this.z = options.z; this.L = options.L; this.V = options.V; this.F = options.F; this.T = options.T; this.P = options.P; this.A = options.A; this.components = options.components; this.debug = debug; this.K = getK(this.T, this.P, this.A, this.debug); // Separator methods this.solve_PTZF = function() { // Solve for/assing all computable attributes given pressure, // temp, feed comp and feed flowrate using the Rachford-Rice // method. if (this.debug) { console.log("vce_seperator.js: running solve_PTZF on sep =", this);}; var beta_solution = vce_math.solver.newtonsMethod(RachfordRiceBeta,0.5,[this.z,this.K]); var beta = beta_solution[1]; if (this.debug) { console.log("vce_seperator.js: beta_solution = ", beta_solution);}; if (beta > 1) { this.V = this.F; this.L = this.F - this.V; this.x = vce_math.null_1d(this.components.length); this.y = this.z; } else if (beta < 0) { this.V = 0.0; this.L = this.F; this.x = this.z; this.y = vce_math.null_1d(this.components.length);; } else { this.V = beta*this.F; this.L = this.F - this.V; this.x = getX(this.z,this.K,beta); this.y = getY(this.x,this.K); } if (this.debug) { console.log("vce_seperator.js: post solve_PTZF object = ", this) }; }; this.updateP = function(P) { this.P = P; this.K = getK(this.T, this.P, this.A, this.debug); }; this.updateT = function(T) { this.T = T; this.K = getK(this.T, this.P, this.A, this.debug) }; ; } // end of Separator class function RachfordRiceBeta(beta, args) { // Wrapper function for RachfordRiceSum // that ensure it has a fixed number of args // args = [z,k] return RachfordRiceSum(beta, args[0], args[1]); } function RachfordRiceElem(zi,Ki,beta) { /* Compute a single term of the rachford Rice sum args: beta - vapour liquid split (float) zi - feed composition point Ki - component equilibrium constant */ var result = zi*(Ki-1)/(1+beta*(Ki-1)); return result; }; function RachfordRiceSum(beta,z,K) { /* Compute Rachford Rice sum http://folk.ntnu.no/skoge/bok/mer/flash_english_edition_2009 args: beta - vapour liquid split (float) z - feed composition array K - component equilibrium constant array */ var result = 0.0; var arrayLength = z.length; for (var i = 0; i < arrayLength; i++) { result = result + RachfordRiceElem(z[i],K[i],beta); }; return result; }; function P_Antoine(T,coeffs) { // Return the pressue in bar based on Antoine coefficients where // T is in [K] // http://ddbonline.ddbst.com/AntoineCalculation/ // AntoineCalculationCGI.exe?component=Ethanol var A = coeffs[0]; var B = coeffs[1]; var C = coeffs[2]; var exponent = A - (B/(C+T)); return Math.pow(10,exponent); }; function P_Antoine_Alt(T,coeffs) { // Return the pressue in bar based on // alternative vap pressure equation var A = coeffs[0]; var B = coeffs[1]; var C = coeffs[2]; var D = coeffs[3]; var E = coeffs[4]; var exponent = A + (B/T) + C*Math.log(T) + D*Math.pow(T,E); return Math.exp(exponent)/101325.0; }; function getK(T, P, A, debug=false) { K = []; for (var i = 0; i < A.values.length; i++) { if (A.eqns[i] === 1) { K[i] = P_Antoine(T,A.values[i])/P; } else if (A.eqns[i] === 2) { K[i] = P_Antoine_Alt(T,A.values[i])/P; } else if (A.eqns[i] === 3) { K[i] = P_Antoine(T,A.values[i])/(760.0*P); } else { console.log("Error: vce_seperator.getK: unknown saturation pressure equation requested"); }; }; if (debug) {console.log("K = ", K)}; return K; }; function getY(x,K) { // Generate the vapour composition array var y = []; var arrayLength = x.length; for (var i = 0; i < arrayLength; i++) { y[i] = K[i]*x[i]; }; return y; }; function getX(z,K,beta) { // Generate the liquid composition array var x = []; var arrayLength = z.length; for (var i = 0; i < arrayLength; i++) { x[i] = z[i]/(1+beta*(K[i]-1)); }; return x; };
version https://git-lfs.github.com/spec/v1 oid sha256:8d946e97cf8f4a6f79bc9306de2f5ed7df38d23dde8056d5a7552bc68f317707 size 2571
$(function(){ window.requestAnimFrame = (function(){ return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function( callback ){ window.setTimeout(callback, 1000 / 60); }; })(); var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var W = window.innerWidth, H = window.innerHeight; canvas.width = W; canvas.height = H; var max = 20; var cubes = []; function clear(){ ctx.fillStyle = "rgba(0,0,0,0.1)"; ctx.fillRect (0, 0, W, H); } canvas.onmousemove = function(e){ midPointX = e.pageX; midPointY = e.pageY; } canvas.onclick = function (){ changeDirection(); } function createCube(){ this.x = Math.random() * (W/2) + (W/4); this.y = Math.random() * (H/1.5) + (H/6); this.w = Math.random() * 10; this.h = Math.random() * 10; this.draw = function() { ctx.fillStyle = "rgb(255,255,255)"; ctx.beginPath(); ctx.arc(this.x, this.y, 25, 0, 2 * Math.PI, false); ctx.fill(); } } function changeDirection(){ for (var i = 0; i < cubes.length; i++) { c = cubes[i]; c.vx= -1 + (Math.random()*2); c.yy= -1 + (Math.random()*2); }; } for (var i = 0; i < max; i++) { cubes.push(new createCube()); }; function draw(){ clear(); for (var i = 0; i < cubes.length; i++) { c = cubes[i]; /*c.x+= c.vx; c.y+= c.vy;*/ c.draw(); }; } function anim(){ draw(); requestAnimFrame(anim); } anim(); });
import * as React from 'react'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import { chainPropTypes, visuallyHidden } from '@mui/utils'; import { unstable_composeClasses as composeClasses } from '@mui/base'; import useTheme from '../styles/useTheme'; import { capitalize, useForkRef, useIsFocusVisible, useControlled, unstable_useId as useId, } from '../utils'; import Star from '../internal/svg-icons/Star'; import StarBorder from '../internal/svg-icons/StarBorder'; import useThemeProps from '../styles/useThemeProps'; import styled, { slotShouldForwardProp } from '../styles/styled'; import ratingClasses, { getRatingUtilityClass } from './ratingClasses'; function clamp(value, min, max) { if (value < min) { return min; } if (value > max) { return max; } return value; } function getDecimalPrecision(num) { const decimalPart = num.toString().split('.')[1]; return decimalPart ? decimalPart.length : 0; } function roundValueToPrecision(value, precision) { if (value == null) { return value; } const nearest = Math.round(value / precision) * precision; return Number(nearest.toFixed(getDecimalPrecision(precision))); } const useUtilityClasses = (ownerState) => { const { classes, size, readOnly, disabled, emptyValueFocused, focusVisible } = ownerState; const slots = { root: [ 'root', `size${capitalize(size)}`, disabled && 'disabled', focusVisible && 'focusVisible', readOnly && 'readyOnly', ], label: ['label', 'pristine'], labelEmptyValue: [emptyValueFocused && 'labelEmptyValueActive'], icon: ['icon'], iconEmpty: ['iconEmpty'], iconFilled: ['iconFilled'], iconHover: ['iconHover'], iconFocus: ['iconFocus'], iconActive: ['iconActive'], decimal: ['decimal'], visuallyHidden: ['visuallyHidden'], }; return composeClasses(slots, getRatingUtilityClass, classes); }; const RatingRoot = styled('span', { name: 'MuiRating', slot: 'Root', overridesResolver: (props, styles) => { const { ownerState } = props; return [ { [`& .${ratingClasses.visuallyHidden}`]: styles.visuallyHidden }, styles.root, styles[`size${capitalize(ownerState.size)}`], ownerState.readOnly && styles.readOnly, ]; }, })(({ theme, ownerState }) => ({ display: 'inline-flex', // Required to position the pristine input absolutely position: 'relative', fontSize: theme.typography.pxToRem(24), color: '#faaf00', cursor: 'pointer', textAlign: 'left', WebkitTapHighlightColor: 'transparent', [`&.${ratingClasses.disabled}`]: { opacity: theme.palette.action.disabledOpacity, pointerEvents: 'none', }, [`&.${ratingClasses.focusVisible} .${ratingClasses.iconActive}`]: { outline: '1px solid #999', }, [`& .${ratingClasses.visuallyHidden}`]: visuallyHidden, ...(ownerState.size === 'small' && { fontSize: theme.typography.pxToRem(18), }), ...(ownerState.size === 'large' && { fontSize: theme.typography.pxToRem(30), }), ...(ownerState.readOnly && { pointerEvents: 'none', }), })); const RatingLabel = styled('label', { name: 'MuiRating', slot: 'Label', overridesResolver: (props, styles) => styles.label, })(({ ownerState }) => ({ cursor: 'inherit', ...(ownerState.emptyValueFocused && { top: 0, bottom: 0, position: 'absolute', outline: '1px solid #999', width: '100%', }), })); const RatingIcon = styled('span', { name: 'MuiRating', slot: 'Icon', overridesResolver: (props, styles) => { const { ownerState } = props; return [ styles.icon, ownerState.iconEmpty && styles.iconEmpty, ownerState.iconFilled && styles.iconFilled, ownerState.iconHover && styles.iconHover, ownerState.iconFocus && styles.iconFocus, ownerState.iconActive && styles.iconActive, ]; }, })(({ theme, ownerState }) => ({ // Fit wrapper to actual icon size. display: 'flex', transition: theme.transitions.create('transform', { duration: theme.transitions.duration.shortest, }), // Fix mouseLeave issue. // https://github.com/facebook/react/issues/4492 pointerEvents: 'none', ...(ownerState.iconActive && { transform: 'scale(1.2)', }), ...(ownerState.iconEmpty && { color: theme.palette.action.disabled, }), })); const RatingDecimal = styled('span', { name: 'MuiRating', slot: 'Decimal', shouldForwardProp: (prop) => slotShouldForwardProp(prop) && prop !== 'iconActive', overridesResolver: (props, styles) => { const { iconActive } = props; return [styles.decimal, iconActive && styles.iconActive]; }, })(({ iconActive }) => ({ position: 'relative', ...(iconActive && { transform: 'scale(1.2)', }), })); function IconContainer(props) { const { value, ...other } = props; return <span {...other} />; } IconContainer.propTypes = { value: PropTypes.number.isRequired, }; function RatingItem(props) { const { classes, disabled, emptyIcon, focus, getLabelText, highlightSelectedOnly, hover, icon, IconContainerComponent, isActive, itemValue, labelProps, name, onBlur, onChange, onClick, onFocus, readOnly, ownerState, ratingValue, ratingValueRounded, } = props; const isFilled = highlightSelectedOnly ? itemValue === ratingValue : itemValue <= ratingValue; const isHovered = itemValue <= hover; const isFocused = itemValue <= focus; const isChecked = itemValue === ratingValueRounded; const id = useId(); const container = ( <RatingIcon as={IconContainerComponent} value={itemValue} className={clsx(classes.icon, { [classes.iconEmpty]: !isFilled, [classes.iconFilled]: isFilled, [classes.iconHover]: isHovered, [classes.iconFocus]: isFocused, [classes.iconActive]: isActive, })} ownerState={{ ...ownerState, iconEmpty: !isFilled, iconFilled: isFilled, iconHover: isHovered, iconFocus: isFocused, iconActive: isActive, }} > {emptyIcon && !isFilled ? emptyIcon : icon} </RatingIcon> ); if (readOnly) { return <span {...labelProps}>{container}</span>; } return ( <React.Fragment> <RatingLabel ownerState={{ ...ownerState, emptyValueFocused: undefined }} htmlFor={id} {...labelProps} > {container} <span className={classes.visuallyHidden}>{getLabelText(itemValue)}</span> </RatingLabel> <input className={classes.visuallyHidden} onFocus={onFocus} onBlur={onBlur} onChange={onChange} onClick={onClick} disabled={disabled} value={itemValue} id={id} type="radio" name={name} checked={isChecked} /> </React.Fragment> ); } RatingItem.propTypes = { classes: PropTypes.object.isRequired, disabled: PropTypes.bool.isRequired, emptyIcon: PropTypes.node, focus: PropTypes.number.isRequired, getLabelText: PropTypes.func.isRequired, highlightSelectedOnly: PropTypes.bool.isRequired, hover: PropTypes.number.isRequired, icon: PropTypes.node, IconContainerComponent: PropTypes.elementType.isRequired, isActive: PropTypes.bool.isRequired, itemValue: PropTypes.number.isRequired, labelProps: PropTypes.object, name: PropTypes.string, onBlur: PropTypes.func.isRequired, onChange: PropTypes.func.isRequired, onClick: PropTypes.func.isRequired, onFocus: PropTypes.func.isRequired, ownerState: PropTypes.object.isRequired, ratingValue: PropTypes.number, ratingValueRounded: PropTypes.number, readOnly: PropTypes.bool.isRequired, }; const defaultIcon = <Star fontSize="inherit" />; const defaultEmptyIcon = <StarBorder fontSize="inherit" />; function defaultLabelText(value) { return `${value} Star${value !== 1 ? 's' : ''}`; } const Rating = React.forwardRef(function Rating(inProps, ref) { const props = useThemeProps({ name: 'MuiRating', props: inProps }); const { className, defaultValue = null, disabled = false, emptyIcon = defaultEmptyIcon, emptyLabelText = 'Empty', getLabelText = defaultLabelText, highlightSelectedOnly = false, icon = defaultIcon, IconContainerComponent = IconContainer, max = 5, name: nameProp, onChange, onChangeActive, onMouseLeave, onMouseMove, precision = 1, readOnly = false, size = 'medium', value: valueProp, ...other } = props; const name = useId(nameProp); const [valueDerived, setValueState] = useControlled({ controlled: valueProp, default: defaultValue, name: 'Rating', }); const valueRounded = roundValueToPrecision(valueDerived, precision); const theme = useTheme(); const [{ hover, focus }, setState] = React.useState({ hover: -1, focus: -1, }); let value = valueRounded; if (hover !== -1) { value = hover; } if (focus !== -1) { value = focus; } const { isFocusVisibleRef, onBlur: handleBlurVisible, onFocus: handleFocusVisible, ref: focusVisibleRef, } = useIsFocusVisible(); const [focusVisible, setFocusVisible] = React.useState(false); const rootRef = React.useRef(); const handleFocusRef = useForkRef(focusVisibleRef, rootRef); const handleRef = useForkRef(handleFocusRef, ref); const handleMouseMove = (event) => { if (onMouseMove) { onMouseMove(event); } const rootNode = rootRef.current; const { right, left } = rootNode.getBoundingClientRect(); const { width } = rootNode.firstChild.getBoundingClientRect(); let percent; if (theme.direction === 'rtl') { percent = (right - event.clientX) / (width * max); } else { percent = (event.clientX - left) / (width * max); } let newHover = roundValueToPrecision(max * percent + precision / 2, precision); newHover = clamp(newHover, precision, max); setState((prev) => prev.hover === newHover && prev.focus === newHover ? prev : { hover: newHover, focus: newHover, }, ); setFocusVisible(false); if (onChangeActive && hover !== newHover) { onChangeActive(event, newHover); } }; const handleMouseLeave = (event) => { if (onMouseLeave) { onMouseLeave(event); } const newHover = -1; setState({ hover: newHover, focus: newHover, }); if (onChangeActive && hover !== newHover) { onChangeActive(event, newHover); } }; const handleChange = (event) => { let newValue = event.target.value === '' ? null : parseFloat(event.target.value); // Give mouse priority over keyboard // Fix https://github.com/mui/material-ui/issues/22827 if (hover !== -1) { newValue = hover; } setValueState(newValue); if (onChange) { onChange(event, newValue); } }; const handleClear = (event) => { // Ignore keyboard events // https://github.com/facebook/react/issues/7407 if (event.clientX === 0 && event.clientY === 0) { return; } setState({ hover: -1, focus: -1, }); setValueState(null); if (onChange && parseFloat(event.target.value) === valueRounded) { onChange(event, null); } }; const handleFocus = (event) => { handleFocusVisible(event); if (isFocusVisibleRef.current === true) { setFocusVisible(true); } const newFocus = parseFloat(event.target.value); setState((prev) => ({ hover: prev.hover, focus: newFocus, })); }; const handleBlur = (event) => { if (hover !== -1) { return; } handleBlurVisible(event); if (isFocusVisibleRef.current === false) { setFocusVisible(false); } const newFocus = -1; setState((prev) => ({ hover: prev.hover, focus: newFocus, })); }; const [emptyValueFocused, setEmptyValueFocused] = React.useState(false); const ownerState = { ...props, defaultValue, disabled, emptyIcon, emptyLabelText, emptyValueFocused, focusVisible, getLabelText, icon, IconContainerComponent, max, precision, readOnly, size, }; const classes = useUtilityClasses(ownerState); return ( <RatingRoot ref={handleRef} onMouseMove={handleMouseMove} onMouseLeave={handleMouseLeave} className={clsx(classes.root, className)} ownerState={ownerState} role={readOnly ? 'img' : null} aria-label={readOnly ? getLabelText(value) : null} {...other} > {Array.from(new Array(max)).map((_, index) => { const itemValue = index + 1; const ratingItemProps = { classes, disabled, emptyIcon, focus, getLabelText, highlightSelectedOnly, hover, icon, IconContainerComponent, name, onBlur: handleBlur, onChange: handleChange, onClick: handleClear, onFocus: handleFocus, ratingValue: value, ratingValueRounded: valueRounded, readOnly, ownerState, }; const isActive = itemValue === Math.ceil(value) && (hover !== -1 || focus !== -1); if (precision < 1) { const items = Array.from(new Array(1 / precision)); return ( <RatingDecimal key={itemValue} className={clsx(classes.decimal, { [classes.iconActive]: isActive })} ownerState={ownerState} iconActive={isActive} > {items.map(($, indexDecimal) => { const itemDecimalValue = roundValueToPrecision( itemValue - 1 + (indexDecimal + 1) * precision, precision, ); return ( <RatingItem key={itemDecimalValue} {...ratingItemProps} // The icon is already displayed as active isActive={false} itemValue={itemDecimalValue} labelProps={{ style: items.length - 1 === indexDecimal ? {} : { width: itemDecimalValue === value ? `${(indexDecimal + 1) * precision * 100}%` : '0%', overflow: 'hidden', position: 'absolute', }, }} /> ); })} </RatingDecimal> ); } return ( <RatingItem key={itemValue} {...ratingItemProps} isActive={isActive} itemValue={itemValue} /> ); })} {!readOnly && !disabled && ( <RatingLabel className={clsx(classes.label, classes.labelEmptyValue)} ownerState={ownerState} > <input className={classes.visuallyHidden} value="" id={`${name}-empty`} type="radio" name={name} checked={valueRounded == null} onFocus={() => setEmptyValueFocused(true)} onBlur={() => setEmptyValueFocused(false)} onChange={handleChange} /> <span className={classes.visuallyHidden}>{emptyLabelText}</span> </RatingLabel> )} </RatingRoot> ); }); Rating.propTypes /* remove-proptypes */ = { // ----------------------------- Warning -------------------------------- // | These PropTypes are generated from the TypeScript type definitions | // | To update them edit the d.ts file and run "yarn proptypes" | // ---------------------------------------------------------------------- /** * Override or extend the styles applied to the component. */ classes: PropTypes.object, /** * @ignore */ className: PropTypes.string, /** * The default value. Use when the component is not controlled. * @default null */ defaultValue: PropTypes.number, /** * If `true`, the component is disabled. * @default false */ disabled: PropTypes.bool, /** * The icon to display when empty. * @default <StarBorder fontSize="inherit" /> */ emptyIcon: PropTypes.node, /** * The label read when the rating input is empty. * @default 'Empty' */ emptyLabelText: PropTypes.node, /** * Accepts a function which returns a string value that provides a user-friendly name for the current value of the rating. * This is important for screen reader users. * * For localization purposes, you can use the provided [translations](/guides/localization/). * @param {number} value The rating label's value to format. * @returns {string} * @default function defaultLabelText(value) { * return `${value} Star${value !== 1 ? 's' : ''}`; * } */ getLabelText: PropTypes.func, /** * If `true`, only the selected icon will be highlighted. * @default false */ highlightSelectedOnly: PropTypes.bool, /** * The icon to display. * @default <Star fontSize="inherit" /> */ icon: PropTypes.node, /** * The component containing the icon. * @default function IconContainer(props) { * const { value, ...other } = props; * return <span {...other} />; * } */ IconContainerComponent: PropTypes.elementType, /** * Maximum rating. * @default 5 */ max: PropTypes.number, /** * The name attribute of the radio `input` elements. * This input `name` should be unique within the page. * Being unique within a form is insufficient since the `name` is used to generated IDs. */ name: PropTypes.string, /** * Callback fired when the value changes. * @param {React.SyntheticEvent} event The event source of the callback. * @param {number|null} value The new value. */ onChange: PropTypes.func, /** * Callback function that is fired when the hover state changes. * @param {React.SyntheticEvent} event The event source of the callback. * @param {number} value The new value. */ onChangeActive: PropTypes.func, /** * @ignore */ onMouseLeave: PropTypes.func, /** * @ignore */ onMouseMove: PropTypes.func, /** * The minimum increment value change allowed. * @default 1 */ precision: chainPropTypes(PropTypes.number, (props) => { if (props.precision < 0.1) { return new Error( [ 'MUI: The prop `precision` should be above 0.1.', 'A value below this limit has an imperceptible impact.', ].join('\n'), ); } return null; }), /** * Removes all hover effects and pointer events. * @default false */ readOnly: PropTypes.bool, /** * The size of the component. * @default 'medium' */ size: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([ PropTypes.oneOf(['small', 'medium', 'large']), PropTypes.string, ]), /** * The system prop that allows defining system overrides as well as additional CSS styles. */ sx: PropTypes.oneOfType([ PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object, ]), /** * The rating value. */ value: PropTypes.number, }; export default Rating;
(function() { $(function() { /* toy.js 可扩展的webApp开发库 @author 史泓 @version 0.1 */ var Toy; Toy = (function() { function Toy() {} /* toyInit toy库的事件初始化函数 @param Array fnarray 事件委托程序对象模型,包含了绑定事件对应的handel @example t.toyInit() */ Toy.prototype.toyInit = function(fnmodal, cssmodal, controls) { var a, b, c, d, earray, earrays, ecssmodal, efn, ename, erange, fnreg, reg, self, _effect, _eleCom, _getEle, _testFn; _effect = void 0; earrays = earray = []; ename = erange = erange = ecssmodal = ''; efn = _effect = self = a = b = c = d = void 0; reg = /\[.+\]/g; fnreg = /\w+[^\[\]]/; _testFn = function(p) { return $.fn[p] !== void 0; }; _eleCom = function(a, ele) { var t; b = a.split('='); c = b[0]; d = b[1]; if (_testFn(c)) { if (d !== void 0) { t = $.fn[c].call(ele, d); } } else { if (c !== 'this') { t = $(c); } else { t = ele; } } return t; }; _getEle = function(cm, ele) { var aa, ct, t, _i, _len; if (cm.ele !== void 0) { ct = cm.ele; } a = ct.split('/'); if (a.length > 1) { for (_i = 0, _len = a.length; _i < _len; _i++) { aa = a[_i]; t = _eleCom(aa); } } else { t = _eleCom(a[0], ele); } if (_testFn(ct)) { t = $.fn[ct].call(ele, null); } else { t = $(t, ct); } return t; }; _effect = function(cssm, self) { var add, cm, ele, key, r, t, toggle, _results; _results = []; for (key in cssm) { cm = cssm[key]; ele = $(self); t = _getEle(cm, ele); if (cm.toggle !== void 0) { toggle = cm.toggle; t.toggleClass(toggle); } if (cm.add !== void 0) { add = cm.add; t.addClass(add); } if (cm.remove !== void 0) { r = cm.remove; _results.push(t.removeClass(r)); } else { _results.push(void 0); } } return _results; }; $('[event]').each(function() { earrays = $(this).attr('event').split(','); self = this; return earrays.forEach(function(ele) { var cssm, ehandel; earray = ele.split('=>'); a = earray[1].split('|'); if (a[0].indexOf('[') !== -1) { b = a[0].match(reg)[0]; c = b.length - 2; d = a[0].match(fnreg); erange = b.substr(1, c); } else { erange = null; } ename = earray[0]; efn = fnmodal[d[0]]; if (d[0] === 'effect') { cssm = cssmodal[a[1]]; return $(self).on(ename, erange, function() { var that; that = this; return _effect(cssm, that); }); } else { ehandel = efn; return $(self).on(ename, erange, function() { return ehandel($(this)); }); } }); }); if (controls !== void 0) { return $('[eventCtrl]'); } }; Toy.prototype.validation = function(context, speed) { var ele, vcount, vdesc, vele, verror, vreg, vresult, vtext, _i, _len; vcount = 0; vresult = false; vele = $('[valid]', context); verror = $('.error', context); for (_i = 0, _len = vele.length; _i < _len; _i++) { ele = vele[_i]; vreg = new RegExp($(ele).attr('valid'), 'g'); vdesc = $(ele).attr('validinfo'); vtext = $(ele).val(); if (vreg.test(vtext) !== true) { verror.text(vdesc); dc(verror, false); break; } vcount++; } if (vcount === vele.length) { vresult = true; } vele.parent().off().on('focus', 'input', function() { return dc(verror, true); }); return vresult; }; return Toy; })(); return this.t = new Toy(); }); }).call(this);
(function() { module('Provider Fallback'); function qioConn() { return new QuickIo(QuickIoServer + ':55441'); } asyncTest('fallback to http', 3, function() { var qio = qioConn(); equal($('iframe').length, 0); qio.on('/open', function() { var $iframe = $('iframe'); equal($iframe.length, 1); ok($iframe.eq(0).attr('src').indexOf('/iframe?instance') != -1); qio.close(); start(); }); }); })();
'use strict'; const hooks = require('./hooks'); var conn_arr = {client:'pg',connection:'postgres://postgres@localhost/calender'} //var db = knex(conn_arr); class Service { constructor(options) { this.options = options || {}; this.db = require('knex')({client: 'pg',connection:'postgres://postgres@localhost/calender'}); } find(params) { return Promise.resolve([]); } get(id, params) { return this.db.raw('SELECT c_id,name,takes_class_recurring.at_time FROM class_recurring INNER JOIN takes_class_recurring using (c_id)\ INNER JOIN student using (usn)WHERE usn ilike ? ORDER BY class_recurring.at_time;',[id]) .then((d)=>d.rows); } create(data, params) { if(Array.isArray(data)) { return Promise.all(data.map(current => this.create(current))); } return Promise.resolve(data); } update(id, data, params) { return Promise.resolve(data); } patch(id, data, params) { return Promise.resolve(data); } remove(id, params) { return Promise.resolve({ id }); } } module.exports = function(){ const app = this; // Initialize our service with any options it requires app.use('/student_classes', new Service()); // Get our initialize service to that we can bind hooks const student_classesService = app.service('/student_classes'); // Set up our before hooks student_classesService.before(hooks.before); // Set up our after hooks student_classesService.after(hooks.after); }; module.exports.Service = Service;
var gulp = require('gulp'), del = require('del'), config = require('../../config').clean.development; /** * Delete folders and files */ gulp.task('clean', function() { return del([config.src + '/**/*']).then(paths => { console.log('Deleted files and folders:\n', paths.join('\n')); }); });
'use strict'; const should = require('should'); const createBoundIssueExtractor = require('../../../core/services/boundIssueExtractor'); describe('Bound Issue Extractor', () => { const boundIssueExtractor = createBoundIssueExtractor(); context('Interface', () => { it('should have the "extract" method', () => { boundIssueExtractor.extract.should.be.a.Function(); }); }); context('Behaviour', () => { it('should return null if the input string is empty', () => { should.not.exist(boundIssueExtractor.extract('')); }); it('should return null if the input is null', () => { should.not.exist(boundIssueExtractor.extract(null)); }); it('should return the issue number (Closes #issue)', () => { const input = 'Closes #1234'; boundIssueExtractor.extract(input).should.be.eql('1234'); }); it('should return the issue number (Fixes #issue)', () => { const input = 'Fixes #1234'; boundIssueExtractor.extract(input).should.be.eql('1234'); }); it('should return the issue number (Fixed #issue)', () => { const input = 'Fixed #1234'; boundIssueExtractor.extract(input).should.be.eql('1234'); }); it('should return the issue number (Fix #issue)', () => { const input = 'Fix #1234'; boundIssueExtractor.extract(input).should.be.eql('1234'); }); it('should return the issue number (Close #issue)', () => { const input = 'Close #1234'; boundIssueExtractor.extract(input).should.be.eql('1234'); }); it('should return the issue number (Closed #issue)', () => { const input = 'Closed #1234'; boundIssueExtractor.extract(input).should.be.eql('1234'); }); it('should return the issue number (Resolve #issue)', () => { const input = 'Resolve #1234'; boundIssueExtractor.extract(input).should.be.eql('1234'); }); it('should return the issue number (Resolves #issue)', () => { const input = 'Resolves #1234'; boundIssueExtractor.extract(input).should.be.eql('1234'); }); it('should return the issue number (Resolved #issue)', () => { const input = 'Resolved #1234'; boundIssueExtractor.extract(input).should.be.eql('1234'); }); it('should find the issue in the middle of the text', () => { const input = 'This is a dummy text\nFixes #1234\nThis is a dummy text'; boundIssueExtractor.extract(input).should.be.eql('1234'); }); it('should find the issue if it is concated with punctuation marks', () => { const input = 'This is a dummy text\nFixes #1234.\nThis is a dummy text'; boundIssueExtractor.extract(input).should.be.eql('1234'); }); it('should not return any issue ("Fixes any text #1234")', () => { const input = 'Fixes any text #1234'; should.not.exist(boundIssueExtractor.extract(input)); }); }); });
/* Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'pagebreak', 'sl', { alt: 'Prelom Strani', toolbar: 'Vstavi prelom strani' } );
'use strict'; // Call the packages const express = require('express'); const app = express(); const bodyParser = require('body-parser'); const morgan = require('morgan'); const mongoose = require('mongoose'); const db = mongoose.connection; const config = require('./config'); const path = require('path'); // App configuration // Use body parser, so we can grab information from POST requests app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); // Configure our app to handle CORS requests app.use((req, res, next) => { res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Access-Control-Allow-Methods', 'GET, POST'); res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type, Authorization'); next(); }); // Log all requests to the console app.use(morgan('dev')); // DB connection handlers db.on('error', (error) => { console.error('mongoose connection: ERROR'); throw new Error(error); }); mongoose.connection.on('open', () => { console.error('mongoose connection: OPEN'); }); // Connect to our database mongoose.connect(config.database); // Set static files location app.use(express.static(__dirname + '/public')); // API routes const apiRoutes = require('./app/routes/api')(app, express); app.use('/api', apiRoutes); // Main catchall route app.get('*', (req, res) => { res.sendFile(path.join(__dirname + '/public/app/templates/index.html')); }); // Start the server app.listen(config.port, () => { console.log(`Server running at http://${config.hostname}:${config.port}/`); });
// Client code Meteor.subscribe('groups'); Groups = new Mongo.Collection("groups"); Template.body.created = function () { if (Accounts._verifyEmailToken) { Accounts.verifyEmail(Accounts._verifyEmailToken, function (err) { if (err != null) { if (err.message = 'Verify email link expired [403]') { console.log('Sorry, this verification link has expired'); } } else { console.log('Thank you! Your email address has been verified.'); } }); } }; Template.body.helpers({ userScore: function () { // return user's score return Meteor.user().score; } }); Template.controls.helpers({ isAdmin: function () { return Meteor.user().groupAdmin; }, show: function () { return Session.get("showMenu"); } }); Template.controls.events({ 'click .toggle-menu': function (event) { Session.set("showMenu",event.target.checked); } }); Template.leaderboard.helpers({ writer: function () { // return all user's attributes for leaderboard // if user is not in any group, return all users not in groups // otherwise, return users in currently selected group if (!Meteor.user().groupId) return Meteor.users.find({groupId: null}, {fields: {displayName: 1, subs: 1, rejs: 1, accs: 1, wds: 1, score: 1}, sort: {score: -1}}); return Meteor.users.find({groups: {$elemMatch: {gid:Meteor.user().groupId}}}, {fields: {username: 1, displayName: 1, subs: 1, rejs: 1, accs: 1, wds: 1, score: 1}, sort: {score: -1}}); }, isAdmin: function (writer) { if (Meteor.users.findOne({username: writer}).groupAdmin) return "*"; return ""; } }); Template.showAdmin.events({ 'click .toggle-admin': function (event) { Session.set("showAdmin", event.target.checked); } }); Template.changeDisplayName.helpers({ change: function () { return (Session.get("showChange")); } }); Template.changeDisplayName.events({ 'click .toggle-change': function (event) { Session.set("showChange", event.target.checked); }, 'submit .newName': function (event) { var name = event.target.name.value; Meteor.call("setDisplayName", name); } }); Template.groupAdmin.helpers({ show: function (){ return (Session.get("showAdmin")); }, writer: function () { // Return list of users, excluding current user, for dropdown menu return Meteor.users.find({groups: {$elemMatch: {gid:Meteor.user().groupId}}, username: {$ne: Meteor.user().username}}, {fields: {username: 1, groupAdmin: 1}, sort: {username: 1}}); } }); Template.groupAdmin.events({ 'change .members': function (event, template) { // Set Session variable id to _id attribute of user to be manipulated by admin var name = template.find('.members').value; var id = Meteor.users.findOne({username: name})._id; // log for debugging // console.log(name); // console.log(id); Session.set('manipId', id); Session.set('manipName', name); }, 'click .makeAdmin': function () { if (confirm("Make " + Session.get('manipName') + " a group admin?")) Meteor.call("makeAdmin", Session.get('manipId'), true); }, 'click .kick': function () { if (confirm("Remove " + Session.get('manipName') + " from group? User may re-join group unless group secret is changed.")) Meteor.call("leaveGroup", Session.get('manipId')); } }); Template.groupSelect.helpers({ group: function () { Meteor.call("groupStrap"); // Call to bootstrap users created before multi-group feature added return Meteor.user().groups; } }); Template.groupSelect.events({ 'change .groups': function (event, template) { var gid = template.find('.groups').value; Meteor.call("switchGroup", Meteor.userId(), gid); } }); Template.changeName.events({ 'submit .groupName': function (event) { var name = event.target.name.value; Meteor.call("changeGroupName", name); } }); Template.changeSecret.events({ 'submit .groupSecret': function (event) { var oldSecret = event.target.old.value; var encOld = CryptoJS.MD5(oldSecret).toString(); var newSecret = event.target.new.value; var confSecret = event.target.confirm.value; if (newSecret === confSecret) { var encNew = CryptoJS.MD5(newSecret).toString(); Meteor.call("changeGroupSecret", encOld, encNew); } } }); Template.userGroup.helpers({ inGroup: function () { // Return true if user is in a group if (Meteor.user().groupId === null) { return false; } return true; }, groupName: function () { // Returns group name return Groups.findOne(Meteor.user().groupId, {fields: {groupDescription: 1}}); }, }); Template.groupAction.events({ 'click input[type=radio]': function (event) { var task = $('input[name=group-select]:checked').val(); Session.set('action', task); } }); Template.joinGroup.events({ 'submit .joinGroup': function (event) { var group = event.target.groupName.value; var secret = event.target.groupSecret.value; var enc = CryptoJS.MD5(secret).toString(); Meteor.call("joinGroup", group, false, enc); } }); Template.newGroup.events({ 'submit .createGroup': function (event) { var group = event.target.groupName.value; var desc = event.target.groupDescription.value; var secret = event.target.groupSecret.value; var conf = event.target.secretConfirm.value; if (! Groups.findOne({groupId: group})) { if (conf === secret) { var enc = CryptoJS.MD5(secret).toString(); Meteor.call("createGroup", group, desc, enc); Meteor.call("joinGroup", group, true, enc); } } } }); Template.groupAction.helpers({ join: function () { if (Session.equals('action', "join")) return true; return false; }, create: function () { if (Session.equals('action', "create")) return true; return false; } }); Template.leaveGroup.events({ 'click .leave': function () { // console.log(Meteor.user().groupAdmin); if (Groups.findOne(Meteor.user().groupId).members === 1) { if (confirm("You are the last member of this group. Leaving this group will result in its deletion. Continue?")) { var gid = Meteor.user().groupId; Meteor.call("leaveGroup", Meteor.userId()); Meteor.call("removeGroup", gid); } } else if ((Meteor.user().groupAdmin === true) && (Groups.findOne(Meteor.user().groupId).admins < 2)) { alert("You are the only admin for this group. Please grant admin rights to another member before leaving the group."); } else { if (confirm("Are you sure you want to leave your group?") && confirm("Are you really sure?")) { Meteor.call("leaveGroup", Meteor.userId()); } } } }); Template.leaveGroup.helpers({ inGroup: function () { // Return true if user is in a group if (Meteor.user().groupId === null) { return false; } return true; } }); Template.trophy.helpers({ leading: function () { // Return true if current user has highest score // tropy template displays trophy for user with highest score // // Will display trophy to multiple users who share high score // even though leaderboard will still rank one above others if (!Meteor.user().groupId) { if (Meteor.userId() === Meteor.users.findOne({groupId: null}, {fields: {_id: 1}, sort: {score: -1}})._id) { return true; } else { return false; } }else if (Meteor.userId() === Meteor.users.findOne({groups: {$elemMatch: {gid: Meteor.user().groupId}}}, {fields: {_id: 1}, sort: {score: -1}})._id) { return true; } else { return false; } } }); Template.userStats.helpers({ // helpers to access user stats userSubs: function () { var id = Meteor.user().username; return Meteor.user().subs; }, userRejections: function () { return Meteor.user().rejs; }, userAccept: function () { return Meteor.user().accs; }, userWithdraw: function () { return Meteor.user().wds; }, userScore: function () { return Meteor.user().score; } }); /// Trying chart.js but so far not working Template.statBar.rendered = function () { drawChart(); }; function drawChart() { var responseChart = document.getElementById("responseChart").getContext("2d"); var responseData = [ { value: Meteor.user().subs, color: "#666666", highlight: "#999999", label: "Submissions" }, { value: Meteor.user().rejs, color: "#ff0000", highlight: "#cc0000", label: "Rejections" }, { value: Meteor.user().accs, color: "#00ff00", highlight: "#00cc00", label: "Acceptances" }, { value: Meteor.user().wds, color: "#0000ff", highlight: "#0000cc", label: "Withdrawals" } ]; var responsePie = new Chart(responseChart).Pie(responseData, { animateScale: true }); }; Template.statBar.helpers({ rejWidth: function () { var total = Meteor.user().rejs + Meteor.user().accs + Meteor.user().wds; return ((Meteor.user().rejs / total) * 100); }, nonRejWidth: function () { var percent = accWidth() + wdWidth(); return (percent); }, accWidth: function () { var total = Meteor.user().rejs + Meteor.user().accs + Meteor.user().wds; return ((Meteor.user().accs / total) * 100); }, wdWidth: function () { var total = Meteor.user().rejs + Meteor.user().accs + Meteor.user().wds; return ((Meteor.user().wds / total) * 100); } }); /// statUpdate Template.statUpdate.events({ 'click .subPlus': function () { // increment user submission Meteor.call("incSubs"); }, 'click .subMinus': function () { // Only decrement submissions if it would not take submission number below total number of responses var responses = Meteor.user().rejs + Meteor.user().accs + Meteor.user().wds; if (Meteor.user().subs > responses) { if (Meteor.user().subs > 0) { // Confirm before removing submission if (confirm('Remove submission?')) { Meteor.call("decSubs"); } } } }, 'click .rejPlus': function () { // increment user rejection only if sum of responses is less than number of submissions var responses = Meteor.user().rejs + Meteor.user().accs + Meteor.user().wds; if (responses < Meteor.user().subs) { Meteor.call("incRejs"); } }, 'click .rejMinus': function () { if (Meteor.user().rejs > 0) { // Confirm before removing rejection if (confirm('Remove rejection?')) { Meteor.call("decRejs"); } } }, 'click .accPlus': function () { // increment user acceptance only if sum of responses is less than number of submissions var responses = Meteor.user().rejs + Meteor.user().accs + Meteor.user().wds; if (responses < Meteor.user().subs) { Meteor.call("incAccs"); } }, 'click .accMinus': function () { if (Meteor.user().accs > 0) { // Confirm before removing acceptance if (confirm('Remove acceptance?')) { Meteor.call("decAccs"); } } }, 'click .wdPlus': function () { // increment user withdrawals only if sum of responses is less than number of submissions var responses = Meteor.user().rejs + Meteor.user().accs + Meteor.user().wds; if (responses < Meteor.user().subs) { Meteor.call("incWds"); } }, 'click .wdMinus': function () { if (Meteor.user().wds > 0) { // Confirm before removing withdrawal if (confirm('Remove withdrawal?')) { Meteor.call("decWds"); } } } }); Accounts.ui.config({ passwordSignupFields: "USERNAME_AND_EMAIL" }); Deps.autorun(function() { Meteor.subscribe('userData'); Meteor.subscribe('userScores'); });
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery //= require jquery_ujs //= require turbolinks //= require_tree . // TODO: Google Pagespeed // Minify JavaScript // Compacting JavaScript code can save many bytes of data and speed up downloading, parsing, and execution time. // Minify JavaScript for the following resources to reduce their size by 48KiB (50% reduction). // Minifying http://d14ky878s1t2ku.cloudfront.net/…44066e0c569bcdfae05d7d28287d229497547.js could save 48KiB (50% reduction) after compression.
var compareApp = angular.module('compareApp', ['ngRoute']); compareApp.config( function( $routeProvider ){ $routeProvider .when( "/compare", {redirect:'/url'} ) .when( "/url", {action: 'url'} ) .when( "/file", {action:'file'} ) .otherwise( {action: "file"} ); }); compareApp.controller('MainCtrl', function ($scope, $route, $routeParams, $q, $http, $filter) { var resembleTestConfig = { errorColor: {red: 255, green: 0, blue: 255}, errorType: 'movement', transparency: 0.1, largeImageThreshold: 1200 }; var defaultMisMatchThreshold = 1; //A TEST PAIR ARE TWO IMAGE OBJECTS PLUS THEIR META DATA WHICH WILL BE COMPARED BY RESEMBLE $scope.testPairs = []; $scope.testPairsCompleted = 0; $scope.passedCount = 0; $scope.testDuration = 0; $scope.testIsRunning = true; $scope.detailFilterOptions = ['failed','passed','all','none']; $scope.statusFilter = 'none'; $scope.displayOnStatusFilter = function(o){ if(o.processing)return false; //console.log($scope.statusFilter,o) if($scope.statusFilter=='all'){ return true; }else if($scope.statusFilter=='failed'){ if(!o.passed){return true;} }else if($scope.statusFilter=='passed'){ if(o.passed){return true;} }else{ return false; } }; var testPairObj = function(a,b,c,o){ this.a={src:a||'',srcClass:'reference'}, this.b={src:b||'',srcClass:'test'}, this.c={src:c||'',srcClass:'diff'}, this.report=null; this.processing=true; this.passed=false; this.meta = o; this.meta.misMatchThreshold = (o && o.misMatchThreshold && o.misMatchThreshold >= 0) ? o.misMatchThreshold : defaultMisMatchThreshold; }; $scope.$on("$routeChangeSuccess", function( $currentRoute, $previousRoute ){ $scope.params = JSON.stringify($routeParams,null,2); $scope.action = $route.current.action; if($scope.action=='url') $scope.runUrlConfig($routeParams); else $scope.runFileConfig($routeParams); }); //TAKES PARAMETERS FROM URL AND RUNS IMG DIFF TEST $scope.runUrlConfig = function(params){ console.log(params); $scope.testPairs.push(new testPairObj('../'+params.a, '../'+params.b, null)); $scope.compareTestPair($scope.testPairs[0]); }; //READS CONFIG FROM FILE AND RUNS IMG DIFF TEST $scope.runFileConfig = function(params){ $http.get('./config.json') .success(function(data, status) { console.log('got data!',status,data); // data.testPairs.forEach(function(o,i,a){ // $scope.testPairs.push(new testPairObj('../'+o.local_reference, '../'+o.local_test, null, o)); // }); // $scope.compareTestPairs($scope.testPairs); if (status == 200){ $scope.renderData(data); } }) .error(function(data, status) { console.log('config file operation failed '+status); }); }; $scope.renderData = function(data){ $scope.data = data; $scope.allTest = data.passed.concat(data.failed); //$scope.$digest(); }; //LOOPS THROUGH TEST PAIR CONFIG AND CALLS compareTestPair(testPair) ON EACH ONE $scope.compareTestPairs = function compareTestPairs(testPairs){ var startTs = new Date(); async.eachLimit( testPairs ,1 ,function(testPair,cb){ $scope.compareTestPair(testPair,function(o){ if(o.passed)$scope.passedCount++; $scope.testPairsCompleted++; $scope.testDuration = (new Date()-startTs); $scope.$digest(); cb(); }); } ,function(){ $scope.testIsRunning = false; if($scope.passedCount == $scope.testPairsCompleted) $scope.statusFilter='passed'; else $scope.statusFilter='failed'; $scope.$digest(); } ); }; //TEST AN INDIVIDUAL testPair OBJECT. UPDATES THE OBJECT WITH RESULTS AND THEN RETURNS THE OBJECT WITH THE CALLBACK $scope.compareTestPair = function compareTestPair(testPair,cb){ testPair.processing=true; resemble.outputSettings(resembleTestConfig); var diff = resemble(testPair.a.src).compareTo(testPair.b.src).onComplete(function(diffData){ testPair.report = JSON.stringify(diffData,null,2); testPair.c.src = diffData.getImageDataUrl(); testPair.processing=false; testPair.passed=(diffData.isSameDimensions && diffData.misMatchPercentage<testPair.meta.misMatchThreshold)?true:false; if(cb)cb(testPair); }); };//scope.compareTestPair() });
/* eslint no-unused-expressions: "off" */ /* eslint-env mocha */ 'use strict'; const chai = require('chai'); const parser = require('../src/parser/parser.js'); const nodes = require('../src/parser/nodes.js'); const expect = chai.expect; describe('Parser', () => { it('can parse simple text', () => { const results = parser.parse('some text'); const expected = [ new nodes.TextNode('some text', { first_line: results[0].lineNum }), ]; expect(results).to.deep.equal(expected); }); it('can parse a jump', () => { const results = parser.parse('[[optiondest]]'); const expected = [ new nodes.JumpNode('optiondest', { first_line: results[0].lineNum }), ]; expect(results).to.deep.equal(expected); }); it('can parse a named option', () => { const results = parser.parse('[[option text|optiondest]]'); const expected = [ new nodes.LinkNode('option text', 'optiondest', { first_line: results[0].lineNum }), ]; expect(results).to.deep.equal(expected); }); it('can parse several named options', () => { const results = parser.parse('[[text1|dest1]][[text2|dest2]]\n[[text3|dest3]]'); const expected = [ new nodes.LinkNode('text1', 'dest1', { first_line: results[0].lineNum }), new nodes.LinkNode('text2', 'dest2', { first_line: results[1].lineNum }), new nodes.LinkNode('text3', 'dest3', { first_line: results[2].lineNum }), ]; expect(results).to.deep.equal(expected); }); it('can parse some text followed by an option', () => { const results = parser.parse('some text [[text1|dest1]]'); const expected = [ new nodes.TextNode('some text ', { first_line: results[0].lineNum }), new nodes.LinkNode('text1', 'dest1', { first_line: results[1].lineNum }), ]; expect(results).to.deep.equal(expected); }); it('can parse some text followed by a newline and an option', () => { const results = parser.parse('some text\n[[text1|dest1]]'); const expected = [ new nodes.TextNode('some text', { first_line: results[0].lineNum }), new nodes.LinkNode('text1', 'dest1', { first_line: results[1].lineNum }), ]; expect(results).to.deep.equal(expected); }); it('can parse some text followed by a newline and a command', () => { const results = parser.parse('some text\n<<commandtext>>'); const expected = [ new nodes.TextNode('some text', { first_line: results[0].lineNum }), new nodes.CommandNode('commandtext', { first_line: results[1].lineNum }), ]; expect(results).to.deep.equal(expected); }); it('can parse a simple assignment', () => { const results = parser.parse('<<set $testvar = 5>>'); const expected = [ new nodes.SetVariableEqualToNode('testvar', new nodes.NumericLiteralNode('5')), ]; expect(results).to.deep.equal(expected); }); it('can parse an assignment involving arithmetic', () => { const results = parser.parse('<<set $testvar = -4.3 - (1 + 2) * 3.1 / 5>>'); const expected = [ new nodes.SetVariableEqualToNode( 'testvar', new nodes.ArithmeticExpressionMinusNode( new nodes.NumericLiteralNode('-4.3'), new nodes.ArithmeticExpressionDivideNode( new nodes.ArithmeticExpressionMultiplyNode( new nodes.ArithmeticExpressionNode( new nodes.ArithmeticExpressionAddNode( new nodes.NumericLiteralNode('1'), new nodes.NumericLiteralNode('2'))), new nodes.NumericLiteralNode('3.1')), new nodes.NumericLiteralNode('5')))), ]; expect(results).to.deep.equal(expected); }); it('can parse a shortcut command', () => { const results = parser.parse('text\n-> shortcut1\n\tText1\n-> shortcut2\n\tText2\nmore text'); const expected = [ new nodes.TextNode('text', { first_line: 1 }), new nodes.DialogOptionNode('shortcut1', [new nodes.TextNode('Text1', { first_line: 3 })], { first_line: 2 }), new nodes.DialogOptionNode('shortcut2', [new nodes.TextNode('Text2', { first_line: 5 })], { first_line: 4 }), new nodes.TextNode('more text', { first_line: 6 }), ]; expect(results).to.deep.equal(expected); }); it('can parse nested shortcut commands', () => { const results = parser.parse('text\n-> shortcut1\n\tText1\n\t-> nestedshortcut1\n\t\tNestedText1\n\t-> nestedshortcut2\n\t\tNestedText2\n-> shortcut2\n\tText2\nmore text'); const expected = [ new nodes.TextNode('text', { first_line: 1 }), new nodes.DialogOptionNode('shortcut1', [ new nodes.TextNode('Text1', { first_line: 3 }), new nodes.DialogOptionNode('nestedshortcut1', [ new nodes.TextNode('NestedText1', { first_line: 5 }), ], { first_line: 4 }), new nodes.DialogOptionNode('nestedshortcut2', [ new nodes.TextNode('NestedText2', { first_line: 7 }), ], { first_line: 6 }), ], { first_line: 2 }), new nodes.DialogOptionNode('shortcut2', [new nodes.TextNode('Text2', { first_line: 9 })], { first_line: 8 }), new nodes.TextNode('more text', { first_line: 10 }), ]; expect(results).to.deep.equal(expected); }); it('correctly ignores a double newline', () => { const results = parser.parse('some text\n\n<<commandtext>>'); const expected = [ new nodes.TextNode('some text', { first_line: results[0].lineNum }), new nodes.CommandNode('commandtext', { first_line: results[1].lineNum }), ]; expect(results).to.deep.equal(expected); }); it('correctly ignores a bunch of newlines', () => { const results = parser.parse('some text\n\n\n\n\n\n<<commandtext>>\n'); const expected = [ new nodes.TextNode('some text', { first_line: results[0].lineNum }), new nodes.CommandNode('commandtext', { first_line: results[1].lineNum }), ]; expect(results).to.deep.equal(expected); }); });
const statuses = ["online", "idle", "invisible", "dnd"]; module.exports = { roles: ["[admin]"], descr: "Cambia el estado del bot.", exec: (message, args) => { if(statuses.includes(args[1])) { global.bot.user.setStatus(args[1]); } else { message.author.sendEmbed({ description: "El estado debe ser `online`, `idle`, `invisible` o `dnd` (do not disturb).", color: 2527667 }); } message.delete(); } }
'use strict'; angular.module('myApp.blog.services', []).factory('postService', function() { return { posts : [ { id : 1, title : 'Simple title1', content : 'Sample content...', permalink : 'simple-title1', author : 'Sandeep', datePublished : '2012-04-04' }, { id : 2, title : 'Simple title2', content : 'Sample content...', permalink : 'simple-title2', author : 'Sandeep', datePublished : '2012-05-04' }, { id : 3, title : 'Simple title3', content : 'Sample content...', permalink : 'simple-title3', author : 'Sandeep', datePublished : '2012-06-04' }, { id : 4, title : 'Simple title4', content : 'Sample content...', permalink : 'simple-title4', author : 'Sandeep', datePublished : '2012-07-04' } ], getAll : function() { return this.posts; }, getPostById : function(id) { for ( var i in this.posts) { if (this.posts[i].id == id) { return this.posts[i]; } } }, } });
function Tile(state) { this.ratio = window.devicePixelRatio || 1; this.n = state.n; this.isball = state.isball; this.istile = state.istile; } Tile.prototype.getState = function() { return { x: this.x, y: this.y, width: this.width, height: this.height }; } Tile.prototype.updateState = function(state) { this.x = state.x * this.ratio; this.y = state.y * this.ratio; this.width = state.width * this.ratio; this.height = state.height * this.ratio; }; Tile.prototype.addBall = function() { this.isball = true; } Tile.prototype.removeBall = function() { this.isball = false; } Tile.prototype.serialize = function() { return { n: this.n, isball: this.isball, istile: this.istile }; };
// // Implements a simple client for emitting OML measurements. // var net = require('net'); var os = require('os'); var _ = require('underscore'); DEFAULTS = { host: 'localhost', port: 4030, }; var Sock = null; // set by init() var NoOp = false; // Skip OML when --oml-noop is set // Initialise the OML framework. // // @param opts host // @param opts port // @param opts domain // @param opts sender_id // @param opts app_name // // @returns true if successful, false otherwise (need a better solution to signal errors) // module.exports.init = function(opts, cfgFunc) { if (Sock) return true; if (! opts) { opts = {}; }; NoOp = (opts.noop == true); parseArgv(opts); if (cfgFunc && _.isFunction(cfgFunc)) { cfgFunc(); } if (NoOp) { return true; } Sock = connect(opts); return true; }; function parseArgv(opts) { var argv = process.argv; for (var i = 0; i < argv.length; i++) { var p = argv[i]; var consume = 0; if (p.indexOf("--oml-id") == 0) { opts.id = argv[i + 1]; consume = 2; } else if (p.indexOf("--oml-domain") == 0) { opts.domain = argv[i + 1]; consume = 2; } else if (p.indexOf("--oml-collect") == 0) { opts.collect = argv[i + 1]; consume = 2; } else if (p.indexOf("--oml-noop") == 0) { NoOp = true; consume = 1; } else if (p.indexOf("--oml-config") == 0) { opts.config = argv[i + 1]; consume = 2; } else if (p.indexOf("--oml-help") == 0) { console.log("OML options:\n"); console.log("\t--oml-id id Name to identify this app instance"); console.log("\t--oml-domain DOMAIN Name of experimental domain"); console.log("\t--oml-collect URI URI of server to send measurements to [file:-]"); console.log("\t--oml-noop Do not collect measurements"); console.log("\t--oml-config FILE File holding OML configuration parameters"); console.log("\t--oml-help Show this message"); process.exit(0); } if (consume > 0) { argv.splice(i, consume); i--; } } if (NoOp) { return true; }; if (! opts.collect) { opts.collect = 'file:-'; } var uri = opts.collect.split(":"); switch (uri.length) { case 1: opts.uri = ['tcp', uri[0], DEFAULTS.port]; break; case 2: p = uri[0]; if (p.indexOf("tcp") == 0 || p.indexOf("file") == 0) { opts.uri = [p, uri[1], (p.indexOf("tcp") == 0) ? DEFAULTS.port : null]; } else { opts.uri = ['tcp', uri[0], uri[1]]; } break; case 3: p = uri[0]; if (! (p.indexOf("tcp") == 0 || p.indexOf("file") == 0)) { module.exports.logger.fatal("Wrong format for OML options '--oml-collect URI', should be 'tcp|file:name[:port]'"); } opts.uri = uri; break; // OK default: module.exports.logger.fatal("Wrong format for OML options '--oml-collect URI', should be 'tcp|file:name[:port]'"); } if (! opts.id) { opts.id = os.hostname() + '-' + process.pid; } } function connect(opts) { var my = {}; var schemaCount = 0; var startTime = Math.floor((new Date()).getTime() / 1000); var schemas = []; // store all schema definitions in case of reconnect var domain = opts.domain || 'unknown_domain'; var senderId = opts.id; var appName = opts.appName || 'unknown_app'; my.write = function(msg) { return out.write(msg); }; my.writeln = function(msg) { return out.write(msg + "\n"); }; my.registerSchema = function(name, schema) { var schemaId = (schemaCount += 1); var qName = appName + '_' + name; var colDescr = _.map(schema, function(col) { return col[0] + ':' + col[1]; }); // 1 generator_sin label:string phase:double value:double var schemaDescr = schemaId + " " + qName + " " + colDescr.join(' '); // ts schemaId seqNo key val l = [0, 0, schemaId, '.', 'schema', schemaDescr]; var s = l.join('\t'); schemas.push(s); my.writeln(s); return schemaId; }; my.ts = function() { return (new Date()).getTime() / 1000 - startTime; }; // INIT var connected = false; var connection = null; var unsentChunk = null; // holding chunk while re-establishing connection var doneCbk = null; // Call after consuming unsentChunk var out = null; function startConnection() { var uri = opts.uri; var host = uri[1]; var port = uri[2]; module.exports.logger.debug("Connecting to '" + host + ':' + port + "'."); connection = net.connect({host: host, port: port}, function() { module.exports.logger.info('client connected'); connected = true; sendHeader(connection); if (unsentChunk) { connection.write(unsentChunk); unsentChunk = null; doneCbk(); } }); connection.writeln = function(msg) { return connection.write(msg + "\n"); }; connection.on('error', function(err) { module.exports.logger.warn('client error - ' + err); connected = false; setTimeout(startConnection, 1000); }); connection.on('end', function() { module.exports.logger.info('client disconnected'); connected = false; setTimeout(startConnection, 1000); }); out = new require('stream').Writable({decodeStrings: false}); out._write = function(chunk, encoding, done) { //console.log('_WRITE(' + connected + ') ' + chunk); if (connected) { connection.write(chunk); done(); } else { unsentChunk = chunk; doneCbk = done; } }; }; function openFile(uri) { var path = uri[1]; if (path == '-') { out = {}; out.write = function(str) { console.log(str); }; out = process.stdout; } else { out = require('fs').createWriteStream(path); } sendHeader(my); } function sendHeader(out) { out.writeln("protocol: 4"); out.writeln("content: text"); out.writeln("domain: " + domain); out.writeln("start-time: " + startTime); out.writeln("sender-id: " + senderId); out.writeln("app-name: " + appName); out.writeln("schema: 0 _experiment_metadata subject:string key:string value:string"); out.write("\n"); _.each(schemas, function(s) { out.writeln(s); }); } (opts.uri.indexOf("tcp") == 0) ? startConnection(opts.uri) : openFile(opts.uri); return my; }; // Supported types in schema // module.exports.T = { int32: 'int32', uint32: 'uint32', int64: 'int64', uint64: 'uint64', double: 'double', string: 'string', blob: 'blob', guid: 'guid', bool: 'bool' }; function noop_f() {}; module.exports.mp = function(name, schema) { if (NoOp) { return noop_f; }; if (! Sock) return new Error("OML: Call 'init' first"); var streamId = Sock.registerSchema(name, schema); var schemaTypes = _.map(schema, function(col) { return col[1]; }); var seqNo = 0; function my() { var m = [Sock.ts(), streamId, seqNo += 1]; //console.log("S>>>> " + m); for (var i = 0; i < arguments.length; i++) { var val = arguments[i]; switch(schemaTypes[i]) { case 'string': val = val.replace(/\\/g, '\\\\').replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/\t/g, '\\t'); break; case 'bool': val = val ? 'T' : 'F'; break; case 'blob': val = new Buffer(val).toString('base64'); break; } //console.log("VAL: " + val); //console.log("m: " + m); //m.push(val); m[i + 3] = val; if (m[i + 3] != val) { // This is a VERY weird bug where only on the first time through appending a // value actually ends up as the first element module.exports.logger.info("BUG: Array", m); m[i + 3] = val; // let's try again if (m[i + 3] != val) { module.exports.logger.warn("BUG: Can't fix Array", m); return true; } m[0] = Sock.ts(); } //console.log("N>>>> " + m + '----' + m[0]); } var row = m.join("\t"); //console.log(">>>> " + m); return Sock.writeln(row); }; return my; }; module.exports.logger = function() { var my = {}; my.debug = function(msg) { console.log('DEBUG(oml): ' + msg); }; my.info = function(msg) { console.log(' INFO(oml): ' + msg); }; my.warn = function(msg) { console.log(' WARN(oml): ' + msg); }; my.error = function(msg) { console.log('ERROR(oml): ' + msg); }; my.fatal = function(msg) { console.log('FATAL(oml): ' + msg); process.exit(1); }; return my; }();
'use strict'; /* Directives */ angular.module('chapelcoWeatherApp.directives', []). directive('appVersion', ['version', function(version) { return function(scope, elm, attrs) { elm.text(version); }; }]);
export { default } from './lib/simple';
require('newrelic'); var express = require('express'), http = require('http'), path = require('path'), hogan = require('hogan-express'), util = require('util'), app = express(), config = require('./config'), server = require('http').createServer(app), azure = require('azure'), io = require('socket.io').listen(server); process.env.AZURE_SERVICEBUS_NAMESPACE = config.azureNamespace; process.env.AZURE_SERVICEBUS_ACCESS_KEY = config.azureAccessKey; var serviceBusService = azure.createServiceBusService(); // Added to create Topic / subscrition serviceBusService.createTopicIfNotExists(config.messageTopic,function(error){ if(!error){ // Topic was created or exists console.log('topic created or exists: ' + config.messageTopic ); } }); var currentSockets = []; app.configure(function() { app.set('port', process.env.PORT || 3000); app.engine('mustache', hogan); app.set('view engine', 'mustache'); app.set('layout', __dirname + '/views/layout'); app.use(express.favicon()); app.use(express.logger('dev')); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(app.router); app.use(express.static(path.join(__dirname, 'public'))); }); app.configure('development', function() { app.use(express.errorHandler()); }); app.get('/', function(req, res) { res.render('index', { title: 'Express' }); }); // Handle 'connection' events io.sockets.on('connection', function(socket) { socket.emit('fromServer', { message: 'Connected! There are now ' + io.sockets.clients().length + ' clients connected.' }); currentSockets.push(socket); //setInterval(function() { sendSampleMessage(socket) }, 5000); socket.on('message', function(data) { socket.emit('message', { message: 'I sent: ' + data.message }); socket.broadcast.emit('message', { message: data.message }); }); }); server.listen(app.get('port'), function() { console.log("Express server listening on port " + app.get('port')); }); function sendSampleMessage(socket) { var msg = sample.getSample(); socket.emit('fromServer', { message: msg }); } function getMessage() { if(currentSockets.length > 0) { serviceBusService.receiveSubscriptionMessage(config.messageTopic, config.subName, function(error, receivedMessage) { if(!error) { for(var i = currentSockets.length - 1; i >= 0; i--) { console.log("[" + i + "] writing " + receivedMessage.content ); currentSockets[i].emit('fromServer', { message: receivedMessage.customProperties }); }; } else { console.log("Error recieving message"); console.log(error); } getMessage(); }); } else { setTimeout(getMessage, 5000); } } getMessage();
// Generated on 2014-12-17 using // generator-webapp 0.5.1 'use strict'; // # Globbing // to only match one level down: // 'test/spec/{,*/}*.js' // If you want to recursively match all subfolders, use: // 'test/spec/**/*.js' var noCache = require("connect-nocache")(); module.exports = function(grunt) { // Load grunt tasks automatically require('load-grunt-tasks')(grunt, { pattern: ['grunt-*', '!grunt-template-jasmine-requirejs'] }); // Configurable paths var config = { webApp: 'webapp', app: '..', dist: 'webapp/dist', dev: 'webapp/dev' }; // Define the configuration for all the tasks grunt.initConfig({ // Project settings config: config, // Make sure code styles are up to par and there are no obvious mistakes jshint: { options: { jshintrc: '.jshintrc', reporter: require('jshint-stylish') }, all: [ '*.js', '*.json', '<%= config.webApp %>/**/*.js', '<%= config.webApp %>/**/*.json' ] }, watch: { js: { files: ['<%= jshint.all %>'], tasks: ['jshint'], options: { livereload: true } }, sass: { files: ['<%= config.webApp %>/styles/**/*.scss', '<%= config.webApp %>/components/**/*.scss'], tasks: ['sass:dev'] } }, connect: { options: { port: 8000, base: "./", middleware: function (connect, options) { return [noCache, connect.static(options.base[0])]; } }, temp: {}, persist: { options: { keepalive: true, open: "http://localhost:8000/_SpecRunner.html" } } }, // Empties folders to start fresh clean: { dist: { files: [{ dot: true, src: [ '<%= config.dist %>/*', '!<%= config.dist %>/.git*' ] }] }, dev: { files: [{ dot: true, src: [ '<%= config.dev %>/*', '!<%= config.dev %>/.git*' ] }] } }, // Mocha testing framework configuration options mocha: { all: { options: { run: true, urls: ['http://<%= connect.test.options.hostname %>:<%= connect.test.options.port %>/'] } } }, // Compiles Sass to CSS and generates necessary files if requested sass: { options: { style: 'compressed', loadPath: ['bower_components/bootstrap-sass-official/assets/stylesheets/', 'bower_components/fontawesome/scss/'], trace: true }, dist: { files: [{ '<%= config.webApp %>/dist/css/main.css': '<%= config.webApp %>/styles/dist.scss', }, { expand: true, src: ["<%= config.webApp %>/components/**/*.scss"], dest: "./", ext: ".css" }] }, dev: { options: { }, files: [{ '<%= config.webApp %>/dev/css/main.css': '<%= config.webApp %>/styles/main.scss', '<%= config.webApp %>/dev/css/bootstrap.css': '<%= config.webApp %>/styles/bootstrap-custom.scss', '<%= config.webApp %>/dev/css/fontawesome.css': '<%= config.webApp %>/styles/fontawesome-custom.scss' }, { expand: true, src: ["<%= config.webApp %>/components/**/*.scss"], dest: "./", ext: ".css" }] } }, nodemon: { dev: { script: './bin/www', options: { args: ['NODE_ENV=development'] } } }, shell: { run: { command: 'set NODE_ENV=production && node ./bin/www' }, rundev: { command: 'set NODE_ENV=development && nodemon ./bin/www' }, rundebug: { command: 'set NODE_ENV=development && nodemon --debug-brk ./bin/www' } }, jasmine: { test: { options: { host: "http://localhost:8000/", specs: ["webapp/spec-main.js","webapp/**/*spec.js"], keepRunner: true, template: require("grunt-template-jasmine-requirejs"), templateOptions: { requireConfig: require("./webapp/config") } } } } }); grunt.registerTask('serve', 'start the server and preview your webApp, --allow-remote for remote access', function(target) { if (grunt.option('allow-remote')) { grunt.config.set('connect.options.hostname', '0.0.0.0'); } if (target === 'dist') { return grunt.task.run(['build', 'connect:dist:keepalive']); } grunt.task.run([ 'jshint', 'clean:dist', 'sass:dist', 'connect:livereload', 'watch' ]); }); grunt.registerTask('server', function(target) { grunt.log.warn('The `server` task has been deprecated. Use `grunt serve` to start a server.'); grunt.task.run([target ? ('serve:' + target) : 'serve']); }); grunt.registerTask('test', function(target) { if (target !== 'watch') { } grunt.task.run([ 'connect:test', 'mocha' ]); }); grunt.registerTask('build', [ 'jshint', 'clean:dist', 'sass:dist' ]); grunt.registerTask('build:dev', [ 'jshint', 'clean:dev', 'sass:dev' ]); grunt.registerTask('default', [ 'build:dev' ]); grunt.registerTask('nodemon', [ 'nodemon:dev' ]); grunt.registerTask('run', ['build','shell:run']); grunt.registerTask('run-dev', ['build:dev','shell:rundev']); grunt.registerTask('run-debug', ['build:dev', 'shell:rundebug']); grunt.registerTask('test', ['jshint', "jasmine:test:build", "connect:persist"]); grunt.registerTask('test:headless', ["connect:temp", "jasmine"]); };
(function () { "use strict"; function CustomerMyProfileComponent(safeDigest, $scope, bidderStore, bidStore, profileStore, weddingActions, weddingCollection, weddingStore) { var self = this; self.onInit = function () { self.profile = profileStore.currentProfile; self.weddings = weddingCollection.createInstance({ data: weddingStore.weddingsByProfile, bids: bidStore.byProfile, bidders: bidderStore.items, profiles: profileStore.items }).items; if (self.weddings.length > 0 && weddingStore.currentWedding) { if (weddingStore.currentWedding) { for (var i = 0; i < self.weddings.length; i++) { if (self.weddings[i].id === weddingStore.currentWedding.id) { self.currentWedding = self.weddings[i]; } } } } if (self.weddings.length > 0 && !weddingStore.currentWedding) weddingActions.select({ wedding: self.weddings[0] }); }; self.storeOnChange = function () { self.onInit(); }; return self; } CustomerMyProfileComponent.canActivate = function () { return ["$q", "invokeAsync", "bidderActions", "bidActions", "bidStore", "profileActions", "weddingActions", function ($q, invokeAsync, bidderActions, bidActions, bidStore, profileActions, weddingActions) { var deferred = $q.defer(); $q.all([ invokeAsync(bidActions.getAllByCurrentProfile), invokeAsync(weddingActions.getAllByCurrentProfile) ]).then(function (results) { var promises = []; for (var i = 0; i < bidStore.byProfile.length; i++) { promises.push($q.all([ invokeAsync({ action: bidderActions.getByBidId, params: { bidId: bidStore.byProfile[i].id } }), invokeAsync({ action: profileActions.getByBidId, params: { bidId: bidStore.byProfile[i].id } }) ])); } $q.all(promises).then(function () { deferred.resolve(); }); }); return deferred.promise; }]; }; ngX.Component({ component: CustomerMyProfileComponent, route: "/customer/myprofile", providers: [ "safeDigest", "$scope", "bidderStore", "bidStore", "profileStore", "weddingActions", "weddingCollection", "weddingStore" ], template: [ "<div class='customerMyProfile viewComponent'>", " <div> ", " <h1>{{ vm.profile.firstname }} {{ vm.profile.lastname }}</h1><br/><br/>", " </div> ", " <div> ", " <div class='customerMyProfile-list'> ", " <h1>Weddings</h1>", " <wedding-item wedding='wedding' data-ng-repeat='wedding in vm.weddings'></wedding-item> ", " </div>", " <div class='customerMyProfile-detail'> ", " <wedding-detail wedding='vm.currentWedding'></wedding-detail>", " </div>", " <div style='clear:both;'></div> ", "</div>" ], styles: [ " .customerMyProfile { ", " width:100%; ", " min-height:100%; ", " display:block; ", " position:relative; ", " } ", " .customerMyProfile-list, .customerMyProfile-detail { ", " width:50%; ", " position:relative; ", " float:left; ", " } " ] }); })();
import forEach from 'tui-code-snippet/collection/forEach'; import Submenu from '@/ui/submenuBase'; import templateHtml from '@/ui/template/submenu/crop'; import { assignmentForDestroy } from '@/util'; /** * Crop ui class * @class * @ignore */ class Crop extends Submenu { constructor(subMenuElement, { locale, makeSvgIcon, menuBarPosition, usageStatistics }) { super(subMenuElement, { locale, name: 'crop', makeSvgIcon, menuBarPosition, templateHtml, usageStatistics, }); this.status = 'active'; this._els = { apply: this.selector('.tie-crop-button .apply'), cancel: this.selector('.tie-crop-button .cancel'), preset: this.selector('.tie-crop-preset-button'), }; this.defaultPresetButton = this._els.preset.querySelector('.preset-none'); } /** * Destroys the instance. */ destroy() { this._removeEvent(); assignmentForDestroy(this); } /** * Add event for crop * @param {Object} actions - actions for crop * @param {Function} actions.crop - crop action * @param {Function} actions.cancel - cancel action * @param {Function} actions.preset - draw rectzone at a predefined ratio */ addEvent(actions) { const apply = this._applyEventHandler.bind(this); const cancel = this._cancelEventHandler.bind(this); const cropzonePreset = this._cropzonePresetEventHandler.bind(this); this.eventHandler = { apply, cancel, cropzonePreset, }; this.actions = actions; this._els.apply.addEventListener('click', apply); this._els.cancel.addEventListener('click', cancel); this._els.preset.addEventListener('click', cropzonePreset); } /** * Remove event * @private */ _removeEvent() { this._els.apply.removeEventListener('click', this.eventHandler.apply); this._els.cancel.removeEventListener('click', this.eventHandler.cancel); this._els.preset.removeEventListener('click', this.eventHandler.cropzonePreset); } _applyEventHandler() { this.actions.crop(); this._els.apply.classList.remove('active'); } _cancelEventHandler() { this.actions.cancel(); this._els.apply.classList.remove('active'); } _cropzonePresetEventHandler(event) { const button = event.target.closest('.tui-image-editor-button.preset'); if (button) { const [presetType] = button.className.match(/preset-[^\s]+/); this._setPresetButtonActive(button); this.actions.preset(presetType); } } /** * Executed when the menu starts. */ changeStartMode() { this.actions.modeChange('crop'); } /** * Returns the menu to its default state. */ changeStandbyMode() { this.actions.stopDrawingMode(); this._setPresetButtonActive(); } /** * Change apply button status * @param {Boolean} enableStatus - apply button status */ changeApplyButtonStatus(enableStatus) { if (enableStatus) { this._els.apply.classList.add('active'); } else { this._els.apply.classList.remove('active'); } } /** * Set preset button to active status * @param {HTMLElement} button - event target element * @private */ _setPresetButtonActive(button = this.defaultPresetButton) { forEach(this._els.preset.querySelectorAll('.preset'), (presetButton) => { presetButton.classList.remove('active'); }); if (button) { button.classList.add('active'); } } } export default Crop;
import React from 'react' import Helmet from "react-helmet"; export default class AboutPage extends React.Component { render() { return ( <div> <Helmet title='About' /> <p>What <em>is</em> this site about?</p> </div> ) } }
Ext.define('sisprod.model.CriteriaGroupModel', { extend: 'Ext.data.Model', require: [ 'Ext.data.Model' ], fields:[ {name: 'idCriteriaGroup', type: 'int', visible: false}, {name: 'criteriaGroupName', type: 'string', visible: true}, {name: 'criteriaGroupOrder', type: 'int', visible: true} ], idProperty: 'idCriteriaGroup' });
import { LIKE_POINT, COMMENT_POINT, POST_POINT, POST, LIKE, COMMENT, MAX_OUTPUT } from './constants'; class Feed { constructor(currentUserId) { this.currentUserId = currentUserId; this.key = {}; this.info = []; } add({ user, type }) { let score; const { id, name, link, picture: { data: { url } } } = user; if (id === this.currentUserId) { return; } if (type === COMMENT) { score = COMMENT_POINT; } else if (type === POST) { score = POST_POINT; } else { score = LIKE_POINT; } if (id in this.key) { // existed this.info[this.key[id]].score += score; this.info[this.key[id]][type] += 1; } else { // new this.key[id] = this.info.length; this.info.push({ id, name, score, url, link, POST: type === POST ? 1 : 0, LIKE: type === LIKE ? 1 : 0, COMMENT: type === COMMENT ? 1 : 0 }); } } // sort and only output first 25 items sortByScore = () => this.info.sort((a, b) => b.score - a.score).slice(0, MAX_OUTPUT); set userId(currentUserId) { this.currentUserId = currentUserId; } } export default Feed;
const bcrypt = require('bcrypt-nodejs'); const crypto = require('crypto'); const mongoose = require('mongoose'); const userSchema = new mongoose.Schema({ email: { type: String, unique: true }, username: { type: String, unique: true }, password: String, passwordResetToken: String, passwordResetExpires: Date, facebook: String, twitter: String, google: String, github: String, instagram: String, linkedin: String, steam: String, tokens: Array, profile: { name: String, gender: String, location: String, picture: String } }, { timestamps: true }); /** * Password hash middleware. */ userSchema.pre('save', function save(next) { const user = this; if (!user.isModified('password')) { return next(); } bcrypt.genSalt(10, (err, salt) => { if (err) { return next(err); } bcrypt.hash(user.password, salt, null, (err, hash) => { if (err) { return next(err); } user.password = hash; next(); }); }); }); /** * Helper method for validating user's password. */ userSchema.methods.comparePassword = function comparePassword(candidatePassword, cb) { bcrypt.compare(candidatePassword, this.password, (err, isMatch) => { cb(err, isMatch); }); }; /** * Helper method for getting user's gravatar. */ userSchema.methods.gravatar = function gravatar(size) { if (!size) { size = 200; } if (!this.email) { return `https://gravatar.com/avatar/?s=${size}&d=retro`; } const md5 = crypto.createHash('md5').update(this.email).digest('hex'); return `https://gravatar.com/avatar/${md5}?s=${size}&d=retro`; }; const User = mongoose.model('User', userSchema); module.exports = User;
describe('Thermostat', function() { var thermostat; beforeEach(function() { jasmine.getFixtures().fixturesPath = '.'; loadFixtures('index2.html'); thermostat = new Thermostat(); }); xit('displays default temperature', function(){ expect('#thermostat').toContainText(thermostat.defaultTemperature); }); it('increases temperature with up button', function(){ $(".thermostat.up").click(); expect('#thermostat').toContainText(thermostat.defaultTemperature + 1); }); it('decreases temperature with down button', function(){ $(".thermostat.down").click(); expect('#thermostat').toContainText(thermostat.defaultTemperature -1); }); it('resets temperature with reset button', function(){ $(".thermostat.reset").click(); expect('#thermostat').toContainText(thermostat.defaultTemperature); }); it('can have power saving mode on', function() { for(var i = 0; i < 6; i++) { $(".thermostat.up").click(); } expect('#thermostat').toContainText(thermostat.ecoModeOnMaxTemp); }); it('can have power saving mode off', function() { $('.switch-input').click(); for(var i = 0; i < 13; i++) { $(".thermostat.up").click(); } expect('#thermostat').toContainText(thermostat.ecoModeOffMaxTemp); }); it('can have the green class', function() { for(var i = 0; i < 3; i++) { $(".thermostat.down").click(); } expect('#thermostat').toHaveClass('green'); }); it('can have the orange class', function() { $(".thermostat.up").click(); expect('#thermostat').toHaveClass('orange'); }); it('can have the red class', function() { for(var i = 0; i < 5; i++) { $(".thermostat.up").click(); } expect('#thermostat').toHaveClass('red'); }); }); describe('Ajax', function() { var thermostat; beforeEach(function() { jasmine.getFixtures().fixturesPath = '.'; loadFixtures('index2.html'); thermostat = new Thermostat(); }); it('will call the weather API', function() { spyOn($, 'ajax'); $('.city.form').trigger({type: 'keypress', which: 13}); expect($.ajax).toHaveBeenCalled(); }); it('can display the city', function() { spyOn($, 'ajax'); var APIResponse = {'main': {'temp': 18}, 'name': 'London'}; $('.city.form').val('London'); $('section').trigger({type: 'keypress', which: 13}); $.ajax.calls.mostRecent().args[0].success(APIResponse); expect($.ajax).toHaveBeenCalled(); expect('.city.name').toContainText('London'); }); it('can display the temperature1', function() { jasmine.Ajax.install(); var APIResponse = {'main': {'temp': 18}}; jasmine.Ajax.stubRequest('http://api.openweathermap.org/data/2.5/weather?q=London&units=metric').andReturn({ success: $('.city.temp').html(Math.round(APIResponse.main.temp)) }); $('.city.form').val('London'); $('.city.form').trigger({type: 'keypress', which: 13}); expect('.city.temp').toContainHtml('18'); jasmine.Ajax.uninstall(); }); it('can display the temperature2', function() { spyOn($, 'ajax'); var APIResponse = {'main': {'temp': 18}}; $('.city.form').val('London'); $('.city.form').trigger({type: 'keypress', which: 13}); $.ajax.calls.mostRecent().args[0].success(APIResponse); expect($.ajax).toHaveBeenCalled(); expect('.city.temp').toContainText('18'); }); it('can display the temperature3', function() { var APIResponse = {'main': {'temp': 18}}; spyOn($, 'ajax').and.callFake(function(fakeajax) { fakeajax.success(APIResponse); }); $('.city.form').val('London'); $('.city.form').trigger({type: 'keypress', which: 13}); expect($.ajax).toHaveBeenCalled(); expect('.city.temp').toContainText('18'); }); it("sends a post request of the temperature when user press increase", function() { spyOn($, 'ajax'); $('.thermostat.up').click(); expect($.ajax.calls.mostRecent().args[0].url).toEqual("http://127.0.0.1:9292/temperature"); expect($.ajax.calls.mostRecent().args[0].data).toEqual({current_temp: thermostat.defaultTemperature + 1}); }); it("sends a post request of the temperature when user press decrease", function() { spyOn($, 'ajax'); $('.thermostat.down').click(); expect($.ajax.calls.mostRecent().args[0].url).toEqual("http://127.0.0.1:9292/temperature"); expect($.ajax.calls.mostRecent().args[0].data).toEqual({current_temp: thermostat.defaultTemperature - 1}); }); it("sends a post request of the temperature when user press reset", function() { spyOn($, 'ajax'); $('.thermostat.reset').click(); expect($.ajax.calls.mostRecent().args[0].url).toEqual('http://127.0.0.1:9292/temperature'); expect($.ajax.calls.mostRecent().args[0].data).toEqual({current_temp: thermostat.defaultTemperature}); }); }); describe('Ajax', function() { var thermostat = new Thermostat(); it('receives a get request of the previous temperature', function() { jasmine.getFixtures().fixturesPath = '.'; spyOn($, 'getJSON'); loadFixtures('index2.html'); expect($.getJSON).toHaveBeenCalled(); expect($.getJSON.calls.mostRecent().args[0]).toEqual('http://127.0.0.1:9292/temperature/' + thermostat.defaultTemperature); }); it('displays the previous temperature', function() { jasmine.getFixtures().fixturesPath = '.'; var APIResponse = {temperature : 24}; spyOn($, 'getJSON'); loadFixtures('index2.html'); expect($.getJSON).toHaveBeenCalled(); $.getJSON.calls.mostRecent().args[1](APIResponse); expect('#thermostat').toContainText('24'); }); });
module.exports = function(tag) { var template = 'partials/article-home.md'; var articles = this.pages('articles', 'date'); var html = '', to = articles.length; for(var i=0; i<to; i++) { var article = articles[i]; var tags = article.get('tags'); if(tags && tags.indexOf(tag) >= 0) { html += this.template(template, { title: article.get('title'), preface: article.get('preface'), link: this.linkto(article), date: article.get('date'), tags: article.get('tags').join(', ') }); } } return html; }
define([ "./core", "./var/indexOf", "./traversing/var/rneedsContext", "./core/init", "./traversing/findFilter", "./selector" ], function (jQuery, indexOf, rneedsContext) { var rparentsprev = /^(?:parents|prev(?:Until|All))/, // Methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.extend({ dir: function (elem, dir, until) { var matched = [], truncate = until !== undefined; while ((elem = elem[dir]) && elem.nodeType !== 9) { if (elem.nodeType === 1) { if (truncate && jQuery(elem).is(until)) { break; } matched.push(elem); } } return matched; }, sibling: function (n, elem) { var matched = []; for (; n; n = n.nextSibling) { if (n.nodeType === 1 && n !== elem) { matched.push(n); } } return matched; } }); jQuery.fn.extend({ has: function( target ) { var targets = jQuery( target, this ), l = targets.length; return this.filter(function () { var i = 0; for ( ; i < l; i++ ) { if (jQuery.contains(this, targets[i])) { return true; } } }); }, closest: function( selectors, context ) { var cur, i = 0, l = this.length, matched = [], pos = rneedsContext.test(selectors) || typeof selectors !== "string" ? jQuery(selectors, context || this.context) : 0; for (; i < l; i++) { for (cur = this[i]; cur && cur !== context; cur = cur.parentNode) { // Always skip document fragments if (cur.nodeType < 11 && (pos ? pos.index(cur) > -1 : // Don't pass non-elements to Sizzle cur.nodeType === 1 && jQuery.find.matchesSelector(cur, selectors))) { matched.push(cur); break; } } } return this.pushStack(matched.length > 1 ? jQuery.unique(matched) : matched); }, // Determine the position of an element within the set index: function( elem ) { // No argument, return index in parent if ( !elem ) { return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1; } // Index in selector if ( typeof elem === "string" ) { return indexOf.call( jQuery( elem ), this[ 0 ] ); } // Locate the position of the desired element return indexOf.call( this, // If it receives a jQuery object, the first element is used elem.jquery ? elem[ 0 ] : elem ); }, add: function( selector, context ) { return this.pushStack( jQuery.unique( jQuery.merge( this.get(), jQuery( selector, context ) ) ) ); }, addBack: function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter(selector) ); } }); function sibling( cur, dir ) { while ((cur = cur[dir]) && cur.nodeType !== 1) { } return cur; } jQuery.each({ parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return jQuery.dir(elem, "parentNode"); }, parentsUntil: function( elem, i, until ) { return jQuery.dir(elem, "parentNode", until); }, next: function( elem ) { return sibling( elem, "nextSibling" ); }, prev: function( elem ) { return sibling( elem, "previousSibling" ); }, nextAll: function( elem ) { return jQuery.dir(elem, "nextSibling"); }, prevAll: function( elem ) { return jQuery.dir(elem, "previousSibling"); }, nextUntil: function( elem, i, until ) { return jQuery.dir(elem, "nextSibling", until); }, prevUntil: function( elem, i, until ) { return jQuery.dir(elem, "previousSibling", until); }, siblings: function( elem ) { return jQuery.sibling(( elem.parentNode || {} ).firstChild, elem); }, children: function( elem ) { return jQuery.sibling(elem.firstChild); }, contents: function( elem ) { return elem.contentDocument || jQuery.merge( [], elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var matched = jQuery.map( this, fn, until ); if ( name.slice( -5 ) !== "Until" ) { selector = until; } if ( selector && typeof selector === "string" ) { matched = jQuery.filter( selector, matched ); } if ( this.length > 1 ) { // Remove duplicates if ( !guaranteedUnique[ name ] ) { jQuery.unique(matched); } // Reverse order for parents* and prev-derivatives if ( rparentsprev.test( name ) ) { matched.reverse(); } } return this.pushStack( matched ); }; }); return jQuery; });
var stream = require('stream'); if (!Array.isArray) { Array.isArray = function(arg) { return Object.prototype.toString.call(arg) === '[object Array]'; }; } module.exports = function(options){ var defaultOptions = { caseSensitive: false, searchKeys: [] }; options = options || {}; for (var opt in defaultOptions){ if (defaultOptions.hasOwnProperty(opt) && !options.hasOwnProperty(opt)){ options[opt] = defaultOptions[opt]; } } return function(filter, obj){ if(typeof obj === 'object'){ if(Array.isArray(obj)){ var res = []; for(var i = 0; i < obj.length; i++){ if(search(options, filter, obj[i], null)) res.push(obj[i]); } return res; }else{ return search(options, filter, obj, null); } }else if(obj === undefined){ //given no object to search assume stream Mode var searchTransform = new stream.Transform( { objectMode: true } ); searchTransform._transform = function (chunk, encoding, done) { if(search(options, filter, chunk, null)) this.push(chunk); done(); }; searchTransform._flush = function (done) { done(); }; return searchTransform; } throw new Error('First argument must be an array or object to search'); }; }; var search = function(options, filter, obj, objKey){ if(isTestableType(obj)){ //if search keys are specified and there's an objKey from higher level object search //make sure it's a key that's good if( options.searchKeys.length > 0 && objKey != null && !arrayContains(objKey, options.searchKeys) ){ return false; } return testValue(options, filter, obj); } else if(typeof obj === 'object'){ if(Array.isArray(obj)){ if(obj.length === 0) return false; //return true for any array value that matches passing down the object key for(var i = 0; i < obj.length; i++){ if(search(options, filter, obj[i], objKey)){ return true; } } }else{ //search every k/v pair for(var key in obj){ var value = obj[key]; //test value here if applicable to prevent an extra layer of recursion if(isTestableType(value)){ //check to see if the search keys has this key to check //but only if the value is a testable type to allow for nested keys if(options.searchKeys.length > 0 ){ if(!arrayContains(key, options.searchKeys)){ continue; } } if(testValue(options, filter, value)){ return true; } }else if( //recurse for other kinds of objects search(options, filter, value, key) ){ return true; } } return false; } }else{ return false; } }; var isTestableType = function(value){ switch(typeof value){ case 'boolean': case 'number': case 'string': return true; default: return false; } }; var testValue = function(options, filter, obj){ if(filter instanceof RegExp){ return filter.test(obj + ''); }else{ if(!options.caseSensitive){ return (obj + '').toLowerCase().indexOf(filter.toLowerCase()) > -1; } return (obj + '').indexOf(filter) > -1; } }; var arrayContains = function(needle, haystack){ for(var sk = 0; sk < haystack.length; sk++){ if(haystack[sk] === needle){ return true; } } return false; };
/* * QUnit - A JavaScript Unit Testing Framework * * http://docs.jquery.com/QUnit * * Copyright (c) 2009 John Resig, Jörn Zaefferer * Dual licensed under the MIT (MIT-LICENSE.txt) * and GPL (GPL-LICENSE.txt) licenses. */ (function(window) { var QUnit = { // Initialize the configuration options init: function() { config = { stats: { all: 0, bad: 0 }, moduleStats: { all: 0, bad: 0 }, started: +new Date, blocking: false, autorun: false, assertions: [], filters: [], queue: [] }; var tests = id("qunit-tests"), banner = id("qunit-banner"), result = id("qunit-testresult"); if ( tests ) { tests.innerHTML = ""; } if ( banner ) { banner.className = ""; } if ( result ) { result.parentNode.removeChild( result ); } }, // call on start of com.liutao.demo.com.elead.ppm.module test to prepend name to all tests module: function(name, testEnvironment) { config.currentModule = name; synchronize(function() { if ( config.currentModule ) { QUnit.moduleDone( config.currentModule, config.moduleStats.bad, config.moduleStats.all ); } config.currentModule = name; config.moduleTestEnvironment = testEnvironment; config.moduleStats = { all: 0, bad: 0 }; QUnit.moduleStart( name, testEnvironment ); }); }, asyncTest: function(testName, expected, callback) { if ( arguments.length === 2 ) { callback = expected; expected = 0; } QUnit.test(testName, expected, callback, true); }, test: function(testName, expected, callback, async) { var name = testName, testEnvironment, testEnvironmentArg; if ( arguments.length === 2 ) { callback = expected; expected = null; } // is 2nd argument a testEnvironment? if ( expected && typeof expected === 'object') { testEnvironmentArg = expected; expected = null; } if ( config.currentModule ) { name = config.currentModule + " com.liutao.demo.com.elead.ppm.module: " + name; } if ( !validTest(name) ) { return; } synchronize(function() { QUnit.testStart( testName ); testEnvironment = extend({ setup: function() {}, teardown: function() {} }, config.moduleTestEnvironment); if (testEnvironmentArg) { extend(testEnvironment,testEnvironmentArg); } // allow utility functions to access the current test environment QUnit.current_testEnvironment = testEnvironment; config.assertions = []; config.expected = expected; try { if ( !config.pollution ) { saveGlobal(); } testEnvironment.setup.call(testEnvironment); } catch(e) { QUnit.ok( false, "Setup failed on " + name + ": " + e.message ); } if ( async ) { QUnit.stop(); } try { callback.call(testEnvironment); } catch(e) { fail("Test " + name + " died, exception and test follows", e, callback); QUnit.ok( false, "Died on test #" + (config.assertions.length + 1) + ": " + e.message ); // else next test will carry the responsibility saveGlobal(); // Restart the tests if they're blocking if ( config.blocking ) { start(); } } }); synchronize(function() { try { checkPollution(); testEnvironment.teardown.call(testEnvironment); } catch(e) { QUnit.ok( false, "Teardown failed on " + name + ": " + e.message ); } try { QUnit.reset(); } catch(e) { fail("reset() failed, following Test " + name + ", exception and reset fn follows", e, reset); } if ( config.expected && config.expected != config.assertions.length ) { QUnit.ok( false, "Expected " + config.expected + " assertions, but " + config.assertions.length + " were run" ); } var good = 0, bad = 0, tests = id("qunit-tests"); config.stats.all += config.assertions.length; config.moduleStats.all += config.assertions.length; if ( tests ) { var ol = document.createElement("ol"); ol.style.display = "none"; for ( var i = 0; i < config.assertions.length; i++ ) { var assertion = config.assertions[i]; var li = document.createElement("li"); li.className = assertion.result ? "pass" : "fail"; li.appendChild(document.createTextNode(assertion.message || "(no message)")); ol.appendChild( li ); if ( assertion.result ) { good++; } else { bad++; config.stats.bad++; config.moduleStats.bad++; } } var b = document.createElement("strong"); b.innerHTML = name + " <b style='color:black;'>(<b class='fail'>" + bad + "</b>, <b class='pass'>" + good + "</b>, " + config.assertions.length + ")</b>"; addEvent(b, "click", function() { var next = b.nextSibling, display = next.style.display; next.style.display = display === "none" ? "block" : "none"; }); addEvent(b, "dblclick", function(e) { var target = e && e.target ? e.target : window.event.srcElement; if ( target.nodeName.toLowerCase() === "strong" ) { var text = "", node = target.firstChild; while ( node.nodeType === 3 ) { text += node.nodeValue; node = node.nextSibling; } text = text.replace(/(^\s*|\s*$)/g, ""); if ( window.location ) { window.location.href = window.location.href.match(/^(.+?)(\?.*)?$/)[1] + "?" + encodeURIComponent(text); } } }); var li = document.createElement("li"); li.className = bad ? "fail" : "pass"; li.appendChild( b ); li.appendChild( ol ); tests.appendChild( li ); if ( bad ) { var toolbar = id("qunit-testrunner-toolbar"); if ( toolbar ) { toolbar.style.display = "block"; id("qunit-filter-pass").disabled = null; id("qunit-filter-missing").disabled = null; } } } else { for ( var i = 0; i < config.assertions.length; i++ ) { if ( !config.assertions[i].result ) { bad++; config.stats.bad++; config.moduleStats.bad++; } } } QUnit.testDone( testName, bad, config.assertions.length ); if ( !window.setTimeout && !config.queue.length ) { done(); } }); if ( window.setTimeout && !config.doneTimer ) { config.doneTimer = window.setTimeout(function(){ if ( !config.queue.length ) { done(); } else { synchronize( done ); } }, 13); } }, /** * Specify the number of expected assertions to gurantee that failed test (no assertions are run at all) don't slip through. */ expect: function(asserts) { config.expected = asserts; }, /** * Asserts true. * @example ok( "asdfasdf".length > 5, "There must be at least 5 chars" ); */ ok: function(a, msg) { QUnit.log(a, msg); config.assertions.push({ result: !!a, message: msg }); }, /** * Checks that the first two arguments are equal, with an optional message. * Prints out both actual and expected values. * * Prefered to ok( actual == expected, message ) * * @example equal( format("Received {0} bytes.", 2), "Received 2 bytes." ); * * @param Object actual * @param Object expected * @param String message (optional) */ equal: function(actual, expected, message) { push(expected == actual, actual, expected, message); }, notEqual: function(actual, expected, message) { push(expected != actual, actual, expected, message); }, deepEqual: function(a, b, message) { push(QUnit.equiv(a, b), a, b, message); }, notDeepEqual: function(a, b, message) { push(!QUnit.equiv(a, b), a, b, message); }, strictEqual: function(actual, expected, message) { push(expected === actual, actual, expected, message); }, notStrictEqual: function(actual, expected, message) { push(expected !== actual, actual, expected, message); }, start: function() { // A slight delay, to avoid any current callbacks if ( window.setTimeout ) { window.setTimeout(function() { if ( config.timeout ) { clearTimeout(config.timeout); } config.blocking = false; process(); }, 13); } else { config.blocking = false; process(); } }, stop: function(timeout) { config.blocking = true; if ( timeout && window.setTimeout ) { config.timeout = window.setTimeout(function() { QUnit.ok( false, "Test timed out" ); QUnit.start(); }, timeout); } }, /** * Resets the test setup. Useful for tests that modify the DOM. */ reset: function() { if ( window.jQuery ) { jQuery("#main").html( config.fixture ); jQuery.event.global = {}; jQuery.ajaxSettings = extend({}, config.ajaxSettings); } }, /** * Trigger an event on an element. * * @example triggerEvent( document.body, "click" ); * * @param DOMElement elem * @param String type */ triggerEvent: function( elem, type, event ) { if ( document.createEvent ) { event = document.createEvent("MouseEvents"); event.initMouseEvent(type, true, true, elem.ownerDocument.defaultView, 0, 0, 0, 0, 0, false, false, false, false, 0, null); elem.dispatchEvent( event ); } else if ( elem.fireEvent ) { elem.fireEvent("on"+type); } }, // Safe object type checking is: function( type, obj ) { return Object.prototype.toString.call( obj ) === "[object "+ type +"]"; }, // Logging callbacks done: function(failures, total) {}, log: function(result, message) {}, testStart: function(name) {}, testDone: function(name, failures, total) {}, moduleStart: function(name, testEnvironment) {}, moduleDone: function(name, failures, total) {} }; // Backwards compatibility, deprecated QUnit.equals = QUnit.equal; QUnit.same = QUnit.deepEqual; // Maintain internal state var config = { // The queue of tests to run queue: [], // block until document ready blocking: true }; // Load paramaters (function() { var location = window.location || { search: "", protocol: "file:" }, GETParams = location.search.slice(1).split('&'); for ( var i = 0; i < GETParams.length; i++ ) { GETParams[i] = decodeURIComponent( GETParams[i] ); if ( GETParams[i] === "noglobals" ) { GETParams.splice( i, 1 ); i--; config.noglobals = true; } else if ( GETParams[i].search('=') > -1 ) { GETParams.splice( i, 1 ); i--; } } // restrict modules/tests by get parameters config.filters = GETParams; // Figure out if we're running the tests from a server or not QUnit.isLocal = !!(location.protocol === 'file:'); })(); // Expose the API as global variables, unless an 'exports' // object exists, in that case we assume we're in CommonJS if ( typeof exports === "undefined" || typeof require === "undefined" ) { extend(window, QUnit); window.QUnit = QUnit; } else { extend(exports, QUnit); exports.QUnit = QUnit; } if ( typeof document === "undefined" || document.readyState === "complete" ) { config.autorun = true; } addEvent(window, "load", function() { // Initialize the config, saving the execution queue var oldconfig = extend({}, config); QUnit.init(); extend(config, oldconfig); config.blocking = false; var userAgent = id("qunit-userAgent"); if ( userAgent ) { userAgent.innerHTML = navigator.userAgent; } var toolbar = id("qunit-testrunner-toolbar"); if ( toolbar ) { toolbar.style.display = "none"; var filter = document.createElement("input"); filter.type = "checkbox"; filter.id = "qunit-filter-pass"; filter.disabled = true; addEvent( filter, "click", function() { var li = document.getElementsByTagName("li"); for ( var i = 0; i < li.length; i++ ) { if ( li[i].className.indexOf("pass") > -1 ) { li[i].style.display = filter.checked ? "none" : ""; } } }); toolbar.appendChild( filter ); var label = document.createElement("label"); label.setAttribute("for", "qunit-filter-pass"); label.innerHTML = "Hide passed tests"; toolbar.appendChild( label ); var missing = document.createElement("input"); missing.type = "checkbox"; missing.id = "qunit-filter-missing"; missing.disabled = true; addEvent( missing, "click", function() { var li = document.getElementsByTagName("li"); for ( var i = 0; i < li.length; i++ ) { if ( li[i].className.indexOf("fail") > -1 && li[i].innerHTML.indexOf('missing test - untested code is broken code') > - 1 ) { li[i].parentNode.parentNode.style.display = missing.checked ? "none" : "block"; } } }); toolbar.appendChild( missing ); label = document.createElement("label"); label.setAttribute("for", "qunit-filter-missing"); label.innerHTML = "Hide missing tests (untested code is broken code)"; toolbar.appendChild( label ); } var main = id('main'); if ( main ) { config.fixture = main.innerHTML; } if ( window.jQuery ) { config.ajaxSettings = window.jQuery.ajaxSettings; } QUnit.start(); }); function done() { if ( config.doneTimer && window.clearTimeout ) { window.clearTimeout( config.doneTimer ); config.doneTimer = null; } if ( config.queue.length ) { config.doneTimer = window.setTimeout(function(){ if ( !config.queue.length ) { done(); } else { synchronize( done ); } }, 13); return; } config.autorun = true; // Log the last com.liutao.demo.com.elead.ppm.module results if ( config.currentModule ) { QUnit.moduleDone( config.currentModule, config.moduleStats.bad, config.moduleStats.all ); } var banner = id("qunit-banner"), tests = id("qunit-tests"), html = ['Tests completed in ', +new Date - config.started, ' milliseconds.<br/>', '<span class="passed">', config.stats.all - config.stats.bad, '</span> tests of <span class="total">', config.stats.all, '</span> passed, <span class="failed">', config.stats.bad,'</span> failed.'].join(''); if ( banner ) { banner.className = (config.stats.bad ? "qunit-fail" : "qunit-pass"); } if ( tests ) { var result = id("qunit-testresult"); if ( !result ) { result = document.createElement("p"); result.id = "qunit-testresult"; result.className = "result"; tests.parentNode.insertBefore( result, tests.nextSibling ); } result.innerHTML = html; } QUnit.done( config.stats.bad, config.stats.all ); } function validTest( name ) { var i = config.filters.length, run = false; if ( !i ) { return true; } while ( i-- ) { var filter = config.filters[i], not = filter.charAt(0) == '!'; if ( not ) { filter = filter.slice(1); } if ( name.indexOf(filter) !== -1 ) { return !not; } if ( not ) { run = true; } } return run; } function push(result, actual, expected, message) { message = message || (result ? "okay" : "failed"); QUnit.ok( result, result ? message + ": " + expected : message + ", expected: " + QUnit.jsDump.parse(expected) + " result: " + QUnit.jsDump.parse(actual) ); } function synchronize( callback ) { config.queue.push( callback ); if ( config.autorun && !config.blocking ) { process(); } } function process() { while ( config.queue.length && !config.blocking ) { config.queue.shift()(); } } function saveGlobal() { config.pollution = []; if ( config.noglobals ) { for ( var key in window ) { config.pollution.push( key ); } } } function checkPollution( name ) { var old = config.pollution; saveGlobal(); var newGlobals = diff( old, config.pollution ); if ( newGlobals.length > 0 ) { ok( false, "Introduced global variable(s): " + newGlobals.join(", ") ); config.expected++; } var deletedGlobals = diff( config.pollution, old ); if ( deletedGlobals.length > 0 ) { ok( false, "Deleted global variable(s): " + deletedGlobals.join(", ") ); config.expected++; } } // returns a new Array with the elements that are in a but not in b function diff( a, b ) { var result = a.slice(); for ( var i = 0; i < result.length; i++ ) { for ( var j = 0; j < b.length; j++ ) { if ( result[i] === b[j] ) { result.splice(i, 1); i--; break; } } } return result; } function fail(message, exception, callback) { if ( typeof console !== "undefined" && console.error && console.warn ) { console.error(message); console.error(exception); console.warn(callback.toString()); } else if ( window.opera && opera.postError ) { opera.postError(message, exception, callback.toString); } } function extend(a, b) { for ( var prop in b ) { a[prop] = b[prop]; } return a; } function addEvent(elem, type, fn) { if ( elem.addEventListener ) { elem.addEventListener( type, fn, false ); } else if ( elem.attachEvent ) { elem.attachEvent( "on" + type, fn ); } else { fn(); } } function id(name) { return !!(typeof document !== "undefined" && document && document.getElementById) && document.getElementById( name ); } // Test for equality any JavaScript type. // Discussions and reference: http://philrathe.com/articles/equiv // Test suites: http://philrathe.com/tests/equiv // Author: Philippe Rathé <prathe@gmail.com> QUnit.equiv = function () { var innerEquiv; // the real equiv function var callers = []; // stack to decide between skip/abort functions // Determine what is o. function hoozit(o) { if (QUnit.is("String", o)) { return "string"; } else if (QUnit.is("Boolean", o)) { return "boolean"; } else if (QUnit.is("Number", o)) { if (isNaN(o)) { return "nan"; } else { return "number"; } } else if (typeof o === "undefined") { return "undefined"; // consider: typeof null === object } else if (o === null) { return "null"; // consider: typeof [] === object } else if (QUnit.is( "Array", o)) { return "array"; // consider: typeof new Date() === object } else if (QUnit.is( "Date", o)) { return "date"; // consider: /./ instanceof Object; // /./ instanceof RegExp; // typeof /./ === "function"; // => false in IE and Opera, // true in FF and Safari } else if (QUnit.is( "RegExp", o)) { return "regexp"; } else if (typeof o === "object") { return "object"; } else if (QUnit.is( "Function", o)) { return "function"; } else { return undefined; } } // Call the o related callback with the given arguments. function bindCallbacks(o, callbacks, args) { var prop = hoozit(o); if (prop) { if (hoozit(callbacks[prop]) === "function") { return callbacks[prop].apply(callbacks, args); } else { return callbacks[prop]; // or undefined } } } var callbacks = function () { // for string, boolean, number and null function useStrictEquality(b, a) { if (b instanceof a.constructor || a instanceof b.constructor) { // to catch short annotaion VS 'new' annotation of a declaration // e.g. var i = 1; // var j = new Number(1); return a == b; } else { return a === b; } } return { "string": useStrictEquality, "boolean": useStrictEquality, "number": useStrictEquality, "null": useStrictEquality, "undefined": useStrictEquality, "nan": function (b) { return isNaN(b); }, "date": function (b, a) { return hoozit(b) === "date" && a.valueOf() === b.valueOf(); }, "regexp": function (b, a) { return hoozit(b) === "regexp" && a.source === b.source && // the regex itself a.global === b.global && // and its modifers (gmi) ... a.ignoreCase === b.ignoreCase && a.multiline === b.multiline; }, // - skip when the property is a method of an instance (OOP) // - abort otherwise, // initial === would have catch identical references anyway "function": function () { var caller = callers[callers.length - 1]; return caller !== Object && typeof caller !== "undefined"; }, "array": function (b, a) { var i; var len; // b could be an object literal here if ( ! (hoozit(b) === "array")) { return false; } len = a.length; if (len !== b.length) { // safe and faster return false; } for (i = 0; i < len; i++) { if ( ! innerEquiv(a[i], b[i])) { return false; } } return true; }, "object": function (b, a) { var i; var eq = true; // unless we can proove it var aProperties = [], bProperties = []; // collection of strings // comparing constructors is more strict than using instanceof if ( a.constructor !== b.constructor) { return false; } // stack constructor before traversing properties callers.push(a.constructor); for (i in a) { // be strict: don't ensures hasOwnProperty and go deep aProperties.push(i); // collect a's properties if ( ! innerEquiv(a[i], b[i])) { eq = false; } } callers.pop(); // unstack, we are done for (i in b) { bProperties.push(i); // collect b's properties } // Ensures identical properties name return eq && innerEquiv(aProperties.sort(), bProperties.sort()); } }; }(); innerEquiv = function () { // can take multiple arguments var args = Array.prototype.slice.apply(arguments); if (args.length < 2) { return true; // end transition } return (function (a, b) { if (a === b) { return true; // catch the most you can } else if (a === null || b === null || typeof a === "undefined" || typeof b === "undefined" || hoozit(a) !== hoozit(b)) { return false; // don't lose time with error prone cases } else { return bindCallbacks(a, callbacks, [b, a]); } // apply transition with (1..n) arguments })(args[0], args[1]) && arguments.callee.apply(this, args.splice(1, args.length -1)); }; return innerEquiv; }(); /** * jsDump * Copyright (c) 2008 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com * Licensed under BSD (http://www.opensource.org/licenses/bsd-license.php) * Date: 5/15/2008 * @projectDescription Advanced and extensible data dumping for Javascript. * @version 1.0.0 * @author Ariel Flesler * @link {http://flesler.blogspot.com/2008/05/jsdump-pretty-dump-of-any-javascript.html} */ QUnit.jsDump = (function() { function quote( str ) { return '"' + str.toString().replace(/"/g, '\\"') + '"'; }; function literal( o ) { return o + ''; }; function join( pre, arr, post ) { var s = jsDump.separator(), base = jsDump.indent(), inner = jsDump.indent(1); if ( arr.join ) arr = arr.join( ',' + s + inner ); if ( !arr ) return pre + post; return [ pre, inner + arr, base + post ].join(s); }; function array( arr ) { var i = arr.length, ret = Array(i); this.up(); while ( i-- ) ret[i] = this.parse( arr[i] ); this.down(); return join( '[', ret, ']' ); }; var reName = /^function (\w+)/; var jsDump = { parse:function( obj, type ) { //type is used mostly internally, you can fix a (custom)type in advance var parser = this.parsers[ type || this.typeOf(obj) ]; type = typeof parser; return type == 'function' ? parser.call( this, obj ) : type == 'string' ? parser : this.parsers.error; }, typeOf:function( obj ) { var type; if ( obj === null ) { type = "null"; } else if (typeof obj === "undefined") { type = "undefined"; } else if (QUnit.is("RegExp", obj)) { type = "regexp"; } else if (QUnit.is("Date", obj)) { type = "date"; } else if (QUnit.is("Function", obj)) { type = "function"; } else if (QUnit.is("Array", obj)) { type = "array"; } else if (QUnit.is("Window", obj) || QUnit.is("global", obj)) { type = "window"; } else if (QUnit.is("HTMLDocument", obj)) { type = "document"; } else if (QUnit.is("HTMLCollection", obj) || QUnit.is("NodeList", obj)) { type = "nodelist"; } else if (/^\[object HTML/.test(Object.prototype.toString.call( obj ))) { type = "node"; } else { type = typeof obj; } return type; }, separator:function() { return this.multiline ? this.HTML ? '<br />' : '\n' : this.HTML ? '&nbsp;' : ' '; }, indent:function( extra ) {// extra can be a number, shortcut for increasing-calling-decreasing if ( !this.multiline ) return ''; var chr = this.indentChar; if ( this.HTML ) chr = chr.replace(/\t/g,' ').replace(/ /g,'&nbsp;'); return Array( this._depth_ + (extra||0) ).join(chr); }, up:function( a ) { this._depth_ += a || 1; }, down:function( a ) { this._depth_ -= a || 1; }, setParser:function( name, parser ) { this.parsers[name] = parser; }, // The next 3 are exposed so you can use them quote:quote, literal:literal, join:join, // _depth_: 1, // This is the list of parsers, to modify them, use jsDump.setParser parsers:{ window: '[Window]', document: '[Document]', error:'[ERROR]', //when no parser is found, shouldn't happen unknown: '[Unknown]', 'null':'null', undefined:'undefined', 'function':function( fn ) { var ret = 'function', name = 'name' in fn ? fn.name : (reName.exec(fn)||[])[1];//functions never have name in IE if ( name ) ret += ' ' + name; ret += '('; ret = [ ret, this.parse( fn, 'functionArgs' ), '){'].join(''); return join( ret, this.parse(fn,'functionCode'), '}' ); }, array: array, nodelist: array, arguments: array, object:function( map ) { var ret = [ ]; this.up(); for ( var key in map ) ret.push( this.parse(key,'key') + ': ' + this.parse(map[key]) ); this.down(); return join( '{', ret, '}' ); }, node:function( node ) { var open = this.HTML ? '&lt;' : '<', close = this.HTML ? '&gt;' : '>'; var tag = node.nodeName.toLowerCase(), ret = open + tag; for ( var a in this.DOMAttrs ) { var val = node[this.DOMAttrs[a]]; if ( val ) ret += ' ' + a + '=' + this.parse( val, 'attribute' ); } return ret + close + open + '/' + tag + close; }, functionArgs:function( fn ) {//function calls it internally, it's the arguments part of the function var l = fn.length; if ( !l ) return ''; var args = Array(l); while ( l-- ) args[l] = String.fromCharCode(97+l);//97 is 'a' return ' ' + args.join(', ') + ' '; }, key:quote, //object calls it internally, the key part of an item in a map functionCode:'[code]', //function calls it internally, it's the content of the function attribute:quote, //node calls it internally, it's an html attribute value string:quote, date:quote, regexp:literal, //regex number:literal, 'boolean':literal }, DOMAttrs:{//attributes to dump from nodes, name=>realName id:'id', name:'name', 'class':'className' }, HTML:true,//if true, entities are escaped ( <, >, \t, space and \n ) indentChar:' ',//indentation unit multiline:true //if true, items in a collection, are separated by a \n, else just a space. }; return jsDump; })(); })(this);
'use strict'; // Use applicaion configuration module to register a new module ApplicationConfiguration.registerModule('entity-classifications');
F("collections", F.Component.extend({ afterRender: function(cb) { var self = this; self.$("#btn-createCollection").click(function(){ var colName = self.$("#input-colName").val().trim(); if (!colName) return; MONGRES.client.createCollection(F.env.conn, F.env.db, colName, function(){ self.load(); }); }); self.$(".btn-remove").click(function(){ var res = confirm("are you sure ?"); if (!res) return; var colName = $(this).closest(".collection").data("id"); MONGRES.client.dropCollection(F.env.conn, F.env.db, colName, function(){ self.load(); }); }); cb(); }, getData: function(callback) { var self = this; F.require( "conn/" + F.env.conn + "/db/" + F.env.db + "/col", function(data){ if (data && data.err) { return Fractal.next("connect"); } data = data.map(function(v){ return { name: v.name.replace(F.env.db + ".", "") }; }); self.data = { collections: data, removable: function() { return this.name !== "system.indexes"; } }; callback(); } ); } }));
'use strict'; var assert = require('assert'); var net = require('net'); var _ = require('lodash'); var async = require('async'); var bitcore = require('bitcore-lib'); var bitcoreNode = require('bitcore-node'); var log = bitcoreNode.log; var lmdb = require('node-lmdb'); var BlockFilter = require('./block-filter'); var Config = require('./config'); var db = require('./db'); var messages = require('./messages'); var models = require('./models'); var utils = require('./utils'); function WriterWorker(options) { this.db = null; this.stopping = false; this.syncing = false; this.blockFilter = null; this.walletBlock = null; this._server = null; this._initOptions(options); this._initClients(); this._initQueue(options); } WriterWorker.DEFAULT_MAX_WORK_QUEUE = 16; WriterWorker.DEFAULT_PRUNE_DEPTH = 4032; WriterWorker.prototype._initOptions = function(options) { this.network = bitcore.Networks.get(options.network); assert(this.network, '"network" is an expected option, please specify "livenet", "testnet" or "regtest"'); assert(options.bitcoinHeight >= 0, '"bitcoinHeight" is expected'); assert(options.bitcoinHash, '"bitcoinHash" is expected'); assert(options.clientsConfig && options.clientsConfig.length > 0, '"clientsConfig" is expected'); assert(options.listen, '"listen" is expected'); this.listen = options.listen; this.bitcoinHeight = options.bitcoinHeight; this.bitcoinHash = options.bitcoinHash; this.pruneDepth = options.pruneDepth || WriterWorker.DEFAULT_PRUNE_DEPTH; this.clientsConfig = options.clientsConfig; this.config = new Config({ network: options.network, path: options.configPath }); }; WriterWorker.prototype._initClients = function() { var clients = utils.getClients(this.clientsConfig); utils.setClients(this, clients); }; WriterWorker.prototype._tryAllClients = function(func, options, callback) { if(_.isFunction(options)) { callback = options; options = {}; } utils.tryAllClients(this, func, options, callback); }; WriterWorker.prototype._initQueue = function(options) { var self = this; this.methodsMap = this._getMethodsMap(); this.maxWorkQueue = options.maxWorkQueue || WriterWorker.DEFAULT_MAX_WORK_QUEUE; this.queue = async.priorityQueue(function(task, callback) { self._queueWorkerIterator(task, callback); }, 1); }; WriterWorker.prototype._loadLatestWalletBlock = function(callback) { var self = this; var txn = this.db.env.beginTxn({readOnly: true}); var cursor = new lmdb.Cursor(txn, this.db.blocks); var found = cursor.goToLast(); if (found === null) { // we will create the wallet later callback(); } else { cursor.getCurrentBinary(function(key, value) { self.walletBlock = models.WalletBlock.fromBuffer(key, value); self.blockFilter = new BlockFilter({ network: self.network, addressFilter: self.walletBlock.addressFilter }); cursor.close(); txn.abort(); callback(); }); } }; WriterWorker.prototype._setupDatabase = function(callback) { var self = this; var dbPath = self.config.getDatabasePath(); async.series([ function(next) { utils.setupDirectory(dbPath, next); }, function(next) { self.db = db.open(dbPath); next(); } ], callback); }; WriterWorker.prototype._startListener = function(callback) { var self = this; // TODO handle EADDRINUSE this._server = net.createServer(function(socket) { socket.on('data', messages.parser(function(msg) { var task = msg.task; task.socket = socket; var priority = msg.priority || 10; if (self.queue.length() >= self.maxWorkQueue) { return self._sendResponse(socket, task.id, { message: 'Work queue depth exceeded' }); } self.queue.push(task, priority); })); }); this._server.on('error', function(err) { log.error(err); }); this._server.listen(self.listen, function() { callback(); }); }; WriterWorker.prototype.start = function(callback) { var self = this; async.series([ function(next) { var appPath = self.config.getApplicationPath(); utils.setupDirectory(appPath, next); }, function(next) { self._setupDatabase(next); }, function(next) { self._loadLatestWalletBlock(next); }, function(next) { self._startListener(next); } ], callback); }; WriterWorker.prototype._initWalletBlock = function() { if (!this.walletBlock) { // Needed for the first wallet creation only var height = this.bitcoinHeight; var blockHash = this.bitcoinHash; this.walletBlock = models.WalletBlock.create(height, blockHash); this.blockFilter = new BlockFilter({ network: this.network, addressFilter: this.walletBlock.addressFilter }); return this.walletBlock; } return false; }; WriterWorker.prototype.stop = function(callback) { this.stopping = true; if (this._server) { this._server.close(); } if (this.db) { db.close(this.db); setImmediate(callback); } else { setImmediate(callback); } }; WriterWorker.prototype._getMethodsMap = function() { return { sync: { fn: this.sync, args: 1 }, importWalletAddresses: { fn: this.importWalletAddresses, args: 2 }, saveTransaction: { fn: this.saveTransaction, args: 2 }, createWallet: { fn: this.createWallet, args: 1 } }; }; WriterWorker.prototype._sendResponse = function(socket, id, error, result) { if (socket) { var msg = messages.encodeReaderMessage(id, error, result); socket.write(msg); } else { if (error) { log.error('Write task error:', error); } else { log.info('Completed write task: ' + id); } } }; WriterWorker.prototype._queueWorkerIterator = function(task, next) { var self = this; if (this.methodsMap[task.method]) { var params = task.params; if (!params || !params.length) { params = []; } if (params.length !== this.methodsMap[task.method].args) { var error = {message: 'Expected ' + this.methodsMap[task.method].args + ' parameter(s)'}; self._sendResponse(task.socket, task.id, error); return next(); } var callback = function(err, result) { if (err && err.deferrable && !task.deferred) { task.deferred = true; self.queue.push(task, 100); log.info('Deferring task id: ' + task.id + ', ' + 'method: ' + task.method + ', error: ' + err.message); next(); } else { var error = err ? {message: err.message}: null; self._sendResponse(task.socket, task.id, error, result); next(); } }; params = params.concat(callback); this.methodsMap[task.method].fn.apply(this, params); } else { self._sendResponse(task.socket, task.id, {message: 'Method Not Found'}); next(); } }; WriterWorker.prototype._addUTXO = function(txn, walletId, utxoData) { assert(utxoData.satoshis >= 0); assert(utxoData.height >= 0); assert(utxoData.txid); assert(utxoData.index >= 0); assert(utxoData.address); var utxo = models.WalletUTXO.create(walletId, utxoData); txn.putBinary(this.db.utxos, utxo.getKey(), utxo.getValue()); var utxoSat = models.WalletUTXOBySatoshis.create(walletId, utxoData); txn.putBinary(this.db.utxosBySatoshis, utxoSat.getKey(), utxoSat.getValue()); var utxoHeight = models.WalletUTXOByHeight.create(walletId, utxoData); txn.putBinary(this.db.utxosByHeight, utxoHeight.getKey(), utxoHeight.getValue()); }; WriterWorker.prototype._undoAddUTXO = function(txn, walletId, utxoData) { assert(utxoData.satoshis >= 0); assert(utxoData.height >= 0); assert(utxoData.txid); assert(utxoData.index >= 0); assert(utxoData.address); var utxo = models.WalletUTXO.create(walletId, utxoData); txn.del(this.db.utxos, utxo.getKey()); var utxoSat = models.WalletUTXOBySatoshis.create(walletId, utxoData); txn.del(this.db.utxosBySatoshis, utxoSat.getKey()); var utxoHeight = models.WalletUTXOByHeight.create(walletId, utxoData); txn.del(this.db.utxosByHeight, utxoHeight.getKey()); }; WriterWorker.prototype._removeUTXO = function(txn, walletId, delta, spentOutputs) { var utxoKey = models.WalletUTXO.getKey(walletId, delta.prevtxid, delta.prevout); var utxoBuffer = txn.getBinary(this.db.utxos, utxoKey); assert(utxoBuffer, '"utxo" could not be found'); var utxo = models.WalletUTXO.fromBuffer(utxoKey, utxoBuffer, this.network); // Keep track of spent utxos removed to be able to undo this action spentOutputs[utxoKey.toString('hex')] = utxo.toObject(); txn.del(this.db.utxos, utxoKey); var satKey = models.WalletUTXOBySatoshis.getKey(walletId, utxo.satoshis, delta.prevtxid, delta.prevout); txn.del(this.db.utxosBySatoshis, satKey); var heightKey = models.WalletUTXOByHeight.getKey(walletId, utxo.height, delta.prevtxid, delta.prevout); txn.del(this.db.utxosByHeight, heightKey); }; WriterWorker.prototype._undoRemoveUTXO = function(txn, walletId, delta, spentOutputs) { var utxoKey = models.WalletUTXO.getKey(walletId, delta.prevtxid, delta.prevout); assert(spentOutputs[utxoKey.toString('hex')], 'undo information not available to restore utxo'); var utxo = models.WalletUTXO.create(walletId, spentOutputs[utxoKey.toString('hex')]); txn.putBinary(this.db.utxos, utxoKey, utxo.getValue()); var utxoData = utxo.toObject(); assert(utxoData.satoshis >= 0); assert(utxoData.height >= 0); assert(utxoData.txid); assert(utxoData.index >= 0); assert(utxoData.address); txn.putBinary(this.db.utxos, utxo.getKey(), utxo.getValue()); var utxoSat = models.WalletUTXOBySatoshis.create(walletId, utxoData); txn.putBinary(this.db.utxosBySatoshis, utxoSat.getKey(), utxoSat.getValue()); var utxoHeight = models.WalletUTXOByHeight.create(walletId, utxoData); txn.putBinary(this.db.utxosByHeight, utxoHeight.getKey(), utxoHeight.getValue()); }; WriterWorker.prototype._connectUTXO = function(txn, walletId, height, transaction, delta, spentOutputs) { if (delta.satoshis > 0) { var utxoData = { satoshis: delta.satoshis, height: height, txid: transaction.txid, index: delta.index, address: delta.address }; this._addUTXO(txn, walletId, utxoData); } else { assert(delta.satoshis <= 0); this._removeUTXO(txn, walletId, delta, spentOutputs); } }; WriterWorker.prototype._disconnectUTXO = function(txn, walletId, height, transaction, delta, spentOutputs) { if (delta.satoshis > 0) { var utxoData = { satoshis: delta.satoshis, height: height, txid: transaction.txid, index: delta.index, address: delta.address }; this._undoAddUTXO(txn, walletId, utxoData); } else { assert(delta.satoshis <= 0); this._undoRemoveUTXO(txn, walletId, delta, spentOutputs); } }; /** * This will insert txids into txn. Does not modify the current wallet * reference, but the arguments passed into the function. * @param {Object} txn - Database transaction * @param {Object} wallets - An object to hold updated wallets * @param {Object} data * @param {Object} data.blockHeight - The block height of deltas * @param {String} data.address - The base58 encoded hex string * @param {String} data.deltas - The deltas for the address as returned from block handler * @param {Function} callback * @param {} */ WriterWorker.prototype._connectTransaction = function(txn, wallets, height, transaction, spentOutputs, callback) { var self = this; function applyDelta(delta) { // Make sure that the address exists in the wallet (false positives from bloom filter) var key = models.WalletAddressMap.getKey(delta.address, self.network); var buffer = txn.getBinary(self.db.addressesMap, key); if (!buffer) { return; } var walletIds = utils.splitBuffer(buffer, 32); walletIds.forEach(function(walletId) { var satoshisDelta = 0; // update txid var txid = models.WalletTxid.create(walletId, height, transaction.index, transaction.txid); txn.putBinary(self.db.txids, txid.getKey(), txid.getValue()); // sum the satoshis satoshisDelta += delta.satoshis; // update the utxo self._connectUTXO(txn, walletId, height, transaction, delta, spentOutputs); // update wallet balance var walletKey = walletId.toString('hex'); if (!wallets[walletKey]) { var walletBuffer = txn.getBinary(self.db.wallets, walletId); var wallet = models.Wallet.fromBuffer(walletId, walletBuffer); wallets[walletKey] = wallet; } wallets[walletKey].addBalance(satoshisDelta); }); } transaction.inputs.forEach(applyDelta); transaction.outputs.forEach(applyDelta); callback(); }; WriterWorker.prototype._pruneWalletBlocks = function(callback) { /* jshint maxstatements: 30 */ var txn = this.db.env.beginTxn(); var self = this; var cursor = new lmdb.Cursor(txn, this.db.blocks); var found = cursor.goToLast(); if (found === null) { return abort(); } var currentHeight; var pruneHeight = 0; cursor.getCurrentBinary(function(key, value) { var walletBlock = models.WalletBlock.fromBuffer(key, value); pruneHeight = Math.max(0, walletBlock.height - self.pruneDepth); log.info('Pruning wallet blocks from height', pruneHeight); }); var pruneKey = models.WalletBlock.getKey(pruneHeight); found = cursor.goToKey(pruneKey); if (found === null) { var prev = cursor.goToPrev(); if (prev === null) { return abort(); } cursor.getCurrentBinary(function(key, value) { var block = models.WalletBlock.fromBuffer(key, value); if (block.height < pruneHeight) { currentHeight = block.height; prune(); } else { abort(); } }); } else { currentHeight = pruneHeight; prune(); } function prune() { log.info('Pruning wallet block at height', currentHeight); cursor.del(); var prev = cursor.goToPrev(); if (prev !== null) { cursor.getCurrentBinary(function(key, value) { var block = models.WalletBlock.fromBuffer(key, value); currentHeight = block.height; if (block.height < pruneHeight) { setImmediate(prune); } else { log.info('Previous block not less than prune height'); commit(); } }); } else { log.info('No previous block found to prune'); commit(); } } function abort() { cursor.close(); txn.abort(); callback(); } function commit() { cursor.close(); txn.commit(); self.db.env.sync(callback); } }; /** * This will commit any changes to the database and update the * current wallet reference to this data. * * @param {Object} txn - Transaction with changes * @param {Object} wallets - An object with updated wallets * @param {Block} block - The block being commited * @param {Function} callback */ WriterWorker.prototype._connectBlockCommit = function(txn, wallets, block, spentOutputs, callback) { var self = this; // Prevent in memory modifications until we know the changes // have been persisted to disk, so that the method can be reattempted without // causing state issues var walletBlock = this.walletBlock.clone(); // Update the latest status of the blocks walletBlock.blockHash = new Buffer(block.hash, 'hex'); walletBlock.height = block.height; // Keep the deltas applied with this block so that we can undo the action later if needed // and record which outputs were spent and removed so we can reverse the action later. walletBlock.deltas = block.deltas; walletBlock.spentOutputs = spentOutputs; txn.putBinary(this.db.blocks, walletBlock.getKey(), walletBlock.getValue()); // Update all of the wallets for (var key in wallets) { var wallet = wallets[key]; txn.putBinary(self.db.wallets, wallet.getKey(), wallet.getValue()); } txn.commit(); this.db.env.sync(function(err) { if (err) { return callback(err); } self.walletBlock = walletBlock; self.blockFilter = new BlockFilter({ network: self.network, addressFilter: self.walletBlock.addressFilter }); log.info('Block ' + self.walletBlock.blockHash.toString('hex') + ' connected to wallets at height ' + self.walletBlock.height); self._pruneWalletBlocks(function(err) { if (err) { log.error(err); } callback(); }); }); }; /** * This will take a block and parse it for addresses that apply to this wallet * and update the database with the new transactions. * @param {Block} block * @param {Function} callback */ WriterWorker.prototype._connectBlock = function(block, callback) { var self = this; var transactions = this.blockFilter.filterDeltas(block); var txn = this.db.env.beginTxn(); var wallets = {}; var spentOutputs = {}; async.eachSeries(transactions, function(transaction, next) { self._connectTransaction(txn, wallets, block.height, transaction, spentOutputs, next); }, function(err) { if (err) { txn.abort(); return callback(err); } self._connectBlockCommit(txn, wallets, block, spentOutputs, callback); }); }; WriterWorker.prototype._disconnectTransaction = function(txn, wallets, height, transaction, spentOutputs) { var self = this; function removeDelta(delta) { // Make sure that the address exists in the wallet (false positives from bloom filter) var key = models.WalletAddressMap.getKey(delta.address, self.network); var buffer = txn.getBinary(self.db.addressesMap, key); if (!buffer) { return; } var walletIds = utils.splitBuffer(buffer, 32); walletIds.forEach(function(walletId) { var satoshisDelta = 0; // remove the txid for this wallet, there may be several deltas that reference // this same txid, and as such each will remove the txid, however after the // first removal the following attempts will get an error because it's already // been removed, we can handle this error and continue var txid = models.WalletTxid.create(walletId, height, transaction.index, transaction.txid); try { txn.del(self.db.txids, txid.getKey()); } catch(e) { if (!e.message.match(/^MDB_NOTFOUND/)) { throw e; } } // restore the previous balance satoshisDelta -= delta.satoshis; // restore the utxos values self._disconnectUTXO(txn, walletId, height, transaction, delta, spentOutputs); // update wallet balance var walletKey = walletId.toString('hex'); if (!wallets[walletKey]) { var walletBuffer = txn.getBinary(self.db.wallets, walletId); var wallet = models.Wallet.fromBuffer(walletId, walletBuffer); wallets[walletKey] = wallet; } wallets[walletKey].addBalance(satoshisDelta); }); } transaction.inputs.forEach(removeDelta); transaction.outputs.forEach(removeDelta); }; WriterWorker.prototype._disconnectBlockCommit = function(txn, wallets, walletBlock, callback) { var self = this; var blockKey = models.WalletBlock.getKey(walletBlock.height - 1); var blockValue = txn.getBinary(this.db.blocks, blockKey); assert(blockValue, 'could not disconnect tip, previous wallet block not found'); var prevWalletBlock = models.WalletBlock.fromBuffer(blockKey, blockValue); // Update all of the wallets for (var key in wallets) { var wallet = wallets[key]; txn.putBinary(self.db.wallets, wallet.getKey(), wallet.getValue()); } txn.commit(); this.db.env.sync(function(err) { if (err) { return callback(err); } self.walletBlock = prevWalletBlock; self.blockFilter = new BlockFilter({ network: self.network, addressFilter: self.walletBlock.addressFilter }); log.info('Block ' + walletBlock.blockHash.toString('hex') + ' disconnected from wallet at height ' + walletBlock.height); callback(); }); }; WriterWorker.prototype._disconnectTip = function(callback) { var self = this; var txn = this.db.env.beginTxn(); var walletBlock = this.walletBlock.clone(); var wallets = {}; walletBlock.deltas.forEach(function(transaction) { self._disconnectTransaction(txn, wallets, walletBlock.height, transaction, walletBlock.spentOutputs); }); self._disconnectBlockCommit(txn, wallets, walletBlock, callback); }; WriterWorker.prototype._maybeGetBlockHash = function(blockArg, callback) { var self = this; if (_.isNumber(blockArg) || (blockArg.length < 40 && /^[0-9]+$/.test(blockArg))) { self._tryAllClients(function(client, done) { client.getBlockHash(blockArg, function(err, response) { if (err) { return done(utils.wrapRPCError(err)); } done(null, response.result); }); }, callback); } else { callback(null, blockArg); } }; WriterWorker.prototype._getBlockDeltas = function(blockArg, callback) { var self = this; function queryBlock(err, blockhash) { if (err) { return callback(err); } self._tryAllClients(function(client, done) { client.getBlockDeltas(blockhash, function(err, response) { if (err) { return done(utils.wrapRPCError(err)); } done(null, response.result); }); }, callback); } self._maybeGetBlockHash(blockArg, queryBlock); }; /** * This will either add the next block to the wallet or will remove the current * block tip in the event of a reorganization. * @param {Number} height - The current height * @param {Function} callback */ WriterWorker.prototype._updateTip = function(height, callback) { var self = this; self._getBlockDeltas(height + 1, function(err, blockDeltas) { if (err) { return callback(err); } var prevHash = blockDeltas.previousblockhash; if (prevHash === self.walletBlock.blockHash.toString('hex')) { // This block appends to the current chain tip and we can // immediately add it to the chain and create indexes. self._connectBlock(blockDeltas, function(err) { if (err) { return callback(err); } // TODO send event? callback(); }); } else { // This block doesn't progress the current tip, so we'll attempt // to rewind the chain to the common ancestor of the block and // then we can resume syncing. log.warn('Reorg detected! Current tip: ' + self.walletBlock.blockHash.toString('hex')); self._disconnectTip(function(err) { if (err) { return callback(err); } log.warn('Disconnected current tip. New tip is ' + self.walletBlock.blockHash.toString('hex')); callback(); }); } }); }; /** * This function will continously update the block tip of the chain until it matches * the bitcoin height. */ WriterWorker.prototype.sync = function(options, callback) { // Update the current state of bitcoind chain assert(options.bitcoinHeight >= 0, '"bitcoinHeight" is expected'); assert(options.bitcoinHash, '"bitcoinHash" is expected'); this.bitcoinHeight = options.bitcoinHeight; this.bitcoinHash = options.bitcoinHash; var self = this; if (self.syncing || self.stopping || !self.walletBlock) { return callback(); } log.info('Starting sync, height: ' + this.walletBlock.height + ' hash:', this.walletBlock.blockHash.toString('hex')); self.syncing = true; var height; async.whilst(function() { if (self.stopping) { return false; } height = self.walletBlock.height; return height < self.bitcoinHeight; }, function(done) { self._updateTip(height, done); }, function(err) { self.syncing = false; if (err) { log.error('Unable to sync:', err.stack); return callback(err); } log.info('Finished sync, height: ' + self.walletBlock.height + ' hash:', self.walletBlock.blockHash.toString('hex')); callback(); }); }; WriterWorker.prototype._addAddressesToWalletTxid = function(txn, walletId, delta) { var txid = models.WalletTxid.create(walletId, delta.height, delta.blockindex, delta.txid); txn.putBinary(this.db.txids, txid.getKey(), txid.getValue()); try { // Flush any imported/cached transactions with this txid txn.del(this.db.txs, models.WalletTransaction.getKey(walletId, delta.txid)); } catch(err) { // noop } }; /* jshint maxparams:7 */ WriterWorker.prototype._addAddressesToWallet = function(txn, walletBlock, walletId, wallet, newAddresses, callback) { var self = this; log.info('Adding addresses to wallet: ', walletId.toString('hex')); var addresses = newAddresses.map(function(a) { return a.address.toString(); }); // split the large query into smaller queries as it's possible // to reach a maximum string length in the responses assert(walletBlock.height >= 0, 'walletBlock "height" property is expected to be a number'); var rangeMax = Math.max(walletBlock.height, 2); var ranges = utils.splitRange(1, rangeMax, 25000); var queries = []; for (var i = 0; i < ranges.length; i++) { queries.push({ addresses: addresses, start: ranges[i][0], end: ranges[i][1], chainInfo: true }); } var lastHash; var lastHeight; async.eachSeries(queries, function(query, next) { self.clients.getAddressDeltas(query, function(err, response) { if (err) { return next(utils.wrapRPCError(err)); } // find the balance delta and new transactions var balanceDelta = 0; var deltas = response.result.deltas; // Keep track of the last block lastHash = response.result.end.hash; lastHeight = response.result.end.height; for (var i = 0; i < deltas.length; i++) { var delta = deltas[i]; balanceDelta += delta.satoshis; // add the txid self._addAddressesToWalletTxid(txn, walletId, delta); } // update wallet balance wallet.balance += balanceDelta; // update bloom filters with new address for (var j = 0; j < newAddresses.length; j++) { var hashBuffer = newAddresses[j].address.hashBuffer; walletBlock.addressFilter.insert(hashBuffer); wallet.addressFilter.insert(hashBuffer); } next(); }); }, function(err) { if (err) { return callback(err); } // Verify that the hash of the chain from the results matches what we expect if (lastHash !== walletBlock.blockHash.toString('hex')) { return callback(new Error('Unexpected chain hash from address deltas')); } callback(); }); }; /* jshint maxparams:7 */ WriterWorker.prototype._commitWalletAddresses = function(txn, walletBlock, walletId, wallet, newAddresses, callback) { /* jshint maxstatements:20 */ log.info('Commiting addresses to wallet: ', walletId.toString('hex')); var self = this; for (var i = 0; i < newAddresses.length; i++) { // Update the address var walletAddress = newAddresses[i]; txn.putBinary(this.db.addresses, walletAddress.getKey(), walletAddress.getValue()); // Update the address map var key = models.WalletAddressMap.getKey(walletAddress.address, this.network); var value = txn.getBinary(this.db.addressesMap, key); var addressMap; if (value) { addressMap = models.WalletAddressMap.fromBuffer(key, value, this.network); addressMap.insert(walletId); } else { addressMap = models.WalletAddressMap.create(walletAddress.address, [walletId], this.network); } txn.putBinary(this.db.addressesMap, addressMap.getKey(), addressMap.getValue()); } // Update the wallet txn.putBinary(this.db.wallets, wallet.getKey(), wallet.getValue()); // Update the wallet block txn.putBinary(this.db.blocks, walletBlock.getKey(), walletBlock.getValue()); // Commit the changes txn.commit(); this.db.env.sync(function(err) { if (err) { return callback(err); } self.walletBlock = walletBlock; self.blockFilter = new BlockFilter({ network: self.network, addressFilter: self.walletBlock.addressFilter }); callback(); }); }; WriterWorker.prototype._filterNewAddresses = function(txn, walletAddresses) { var self = this; var newAddresses = walletAddresses.filter(function(address) { var buffer = txn.getBinary(self.db.addresses, address.getKey()); if (!buffer) { return true; } else { return false; } }); return newAddresses; }; WriterWorker.prototype._queueSyncTask = function(height, hash) { assert(bitcore.util.js.isNaturalNumber(height), '"height" is expected to be a natural number'); assert(bitcore.util.js.isHexa(hash), '"hash" is expected to be a hexa string'); assert(hash.length === 64, '"hash" length is expected to be 64'); var taskId = utils.getTaskId(); var task = { id: taskId, method: 'sync', params: [{ bitcoinHeight: height, bitcoinHash: hash }] }; this.queue.push(task, 0); }; WriterWorker.prototype._addUTXOSToWallet = function(txn, walletBlock, walletId, newAddresses, callback) { var self = this; log.info('Adding utxos to wallet: ', walletId.toString('hex')); var addresses = newAddresses.map(function(a) { return a.address.toString(); }); this.clients.getAddressUtxos({ addresses: addresses, chainInfo: true }, function(err, response) { if (err) { return callback(utils.wrapRPCError(err)); } var result = response.result.utxos; if (response.result.hash === walletBlock.blockHash.toString('hex')) { for (var i = 0; i < result.length; i++) { var utxo = result[i]; var utxoData = { height: utxo.height, address: utxo.address, txid: utxo.txid, index: utxo.outputIndex, satoshis: utxo.satoshis }; self._addUTXO(txn, walletId, utxoData); } } else { if (response.result.height > walletBlock.height) { // Queue a sync task as we need to catch up first self._queueSyncTask(response.result.height, response.result.hash); // Give back an error with deferrable flag set to try this task once again var error = new Error('Unexpected greater chain tip height from bitcoind query'); error.deferrable = true; return callback(error); } return callback(new Error('Unexpected chain tip hash from address utxos bitcoind query')); } callback(); }); }; /** * Will import an address and key pair into the wallet and will keep track * of the balance and transactions. * @param {Array} addresses - Array of base58 encoded addresses */ WriterWorker.prototype.importWalletAddresses = function(walletId, addresses, callback) { /* jshint maxstatements: 25 */ var self = this; walletId = utils.toHexBuffer(walletId); if (self.syncing) { return callback(new Error('Sync or import in progress')); } self.syncing = true; if (!this.walletBlock) { self.syncing = false; return callback(new Error('Wallet does not exist, missing wallet block')); } // Prevent in memory modifications until we know the changes // have been persisted to disk. var walletBlock = this.walletBlock.clone(); var txn = this.db.env.beginTxn(); var buffer = txn.getBinary(this.db.wallets, walletId); if (!buffer) { self.syncing = false; txn.abort(); return callback(new Error('Wallet does not exist')); } var wallet = models.Wallet.fromBuffer(walletId, buffer); var walletAddresses = addresses.map(function(address) { return models.WalletAddress(walletId, address); }); var newAddresses = self._filterNewAddresses(txn, walletAddresses); if (newAddresses.length === 0) { self.syncing = false; txn.abort(); return callback(null, newAddresses); } async.series([ function(next) { // TODO If getaddressdeltas response includes prevTxId and prevOut for spending // deltas, we will not need to make a seperate RPC call to bitcoind to retrieve // the current UTXO state for the addresses. self._addUTXOSToWallet(txn, walletBlock, walletId, newAddresses, next); }, function(next) { self._addAddressesToWallet(txn, walletBlock, walletId, wallet, newAddresses, next); }, function(next) { self._commitWalletAddresses(txn, walletBlock, walletId, wallet, newAddresses, next); } ], function(err) { self.syncing = false; if (err) { txn.abort(); return callback(err); } callback(null, newAddresses); }); }; /** * Saves a transaction to the database * * @param {Object} transaction - The transaction object (response from verbose getrawtransaction) * @param {Function} callback */ WriterWorker.prototype.saveTransaction = function(walletId, transaction, callback) { var self = this; var walletTransaction = models.WalletTransaction.create(walletId, transaction); var txn = this.db.env.beginTxn(); var value = walletTransaction.getValue(); txn.putBinary(self.db.txs, walletTransaction.getKey(), value); txn.commit(); this.db.env.sync(function(err) { if (err) { return callback(err); } callback(); }); }; /** * Creates a new wallet by walletId. If an existing wallet exists with the walletId * the existing wallet will be returned as the response. * * @param {Object} walletObj - Object representing the wallet * @param {Function} callback */ WriterWorker.prototype.createWallet = function(walletId, callback) { var txn = this.db.env.beginTxn(); // Create the initial wallet block if it doesn't exist var walletBlock = this._initWalletBlock(); if (walletBlock) { txn.putBinary(this.db.blocks, walletBlock.getKey(), walletBlock.getValue()); } var wallet = models.Wallet.create(walletId); var key = wallet.getKey(); var buffer = txn.getBinary(this.db.wallets, key); if (buffer) { txn.abort(); return callback(); } else { txn.putBinary(this.db.wallets, key, wallet.getValue()); txn.commit(); } this.db.env.sync(function(err) { if (err) { return callback(err); } callback(null, walletId); }); }; /* istanbul ignore next */ if (require.main === module) { process.title = 'bwdb-writer'; var options = JSON.parse(process.argv[2]); var worker = new WriterWorker(options); worker.start(function(err) { if (err) { throw err; } process.send('ready'); }); process.on('SIGINT', function() { worker.stop(function(err) { if (err) { throw err; } process.exit(0); }); }); } module.exports = WriterWorker;
const { babelMain, babelTest } = require('./config/presets') module.exports = { env: { development: { presets: babelTest.presets }, test: { presets: babelTest.presets }, production: { presets: babelMain.presets, plugins: babelMain.plugins } } }
import * as mortgage from './mortgage'; document.getElementById('calcBtn').addEventListener('click', () => { let principal = document.getElementById("principal").value; let years = document.getElementById("years").value; let rate = document.getElementById("rate").value; let {monthlyPayment, monthlyRate, amortization} = mortgage.calculateAmortization(principal, years, rate); //console.log('monthlyPayment ', monthlyPayment); document.getElementById("monthlyPayment").innerHTML = monthlyPayment.toFixed(2); document.getElementById("monthlyRate").innerHTML = (monthlyRate * 100).toFixed(2); amortization.forEach(month => console.log(month)); let html = ""; amortization.forEach( (year, index) => html += ` <tr> <td>${index + 1}</td> <td class="currency">${Math.round(year.principalY)}</td> <td class="stretch"> <div class="flex"> <div class="bar principal" style="flex:${year.principalY};-webkit-flex:${year.principalY}"> </div> <div class="bar interest" style="flex:${year.interestY};-webkit-flex:${year.interestY}"> </div> </div> </td> <td class="currency left">${Math.round(year.interestY)}</td> <td class="currency">${Math.round(year.balance)}</td> </tr> `); document.getElementById("amortization").innerHTML = html; });
function mean (array) { return array.reduce((acc, value) => acc + value, 0) / array.length } module.exports = mean
(function (app) { 'use strict'; app.registerModule('groups', ['core']);// The core module is required for special route handling; see /core/client/config/core.client.routes app.registerModule('groups.routes', ['ui.router', 'core.routes']); app.registerModule('groups.services'); }(ApplicationConfiguration));
var moveForward = { canMove: true, transforms: { file: 0, rank: 1 }, postMoveAction: { action: function (piece, state, board) { var move = state.moveHistory.slice(-1)[0]; if (move.to.rank !== 1 && move.to.rank !== 8) return; var promotionNotation = (move.options || "q").toLowerCase(); var promotionPiece = board.pieces.filter(function (p) { return p.notation === promotionNotation; })[0]; if (!promotionPiece) { promotionPiece = board.pieces.filter(function (p) { return p.notation === "q"; })[0]; } piece.canQueen = false; piece.canSpawn = true; piece.movement = promotionPiece.movement; piece.notation = promotionPiece.notation; piece.postMoveFunctions = promotionPiece.postMoveFunctions; piece.value = promotionPiece.value; piece.name = promotionPiece.name; } } }; var firstMove = { canMove: true, transforms: { file: 0, rank: 2 }, preCondition: function (piece, boardState) { return boardState.moveHistory.filter(function (m) { return m.piece.id === piece.id; }).length === 0; }, postMoveAction: { action: function (piece, state, board) { var coordBehindPawn = piece.getRelativeDestination({ file: 0, rank: -1 }); var squareBehindPawn = board.getSquare(coordBehindPawn, state); squareBehindPawn.tags["enpassant"] = true; state.postMoveFunctions.push({ moveNumber: state.moveNumber + 1, action: function (piece, innerState, innerBoard) { var sq = innerBoard.getSquare({ file: coordBehindPawn.file, rank: coordBehindPawn.rank }, innerState); delete sq.tags["enpassant"]; } }); } } }; var leftCapture = { canCapture: true, transforms: { file: 1, rank: 1 } }; var rightCapture = { canCapture: true, transforms: { file: -1, rank: 1 } }; var leftEnpassant = { canCapture: true, transforms: { file: -1, rank: 1 }, preCondition: enpassantPreMove({ file: -1, rank: 1 }), postMoveAction: { action: enpassantPostMove } }; var rightEnpassant = { canCapture: true, transforms: { file: 1, rank: 1 }, preCondition: enpassantPreMove({ file: 1, rank: 1 }), postMoveAction: { action: enpassantPostMove } }; function enpassantPreMove(dir) { return function (piece, state, board) { var coord = piece.getRelativeDestination(dir); var sq = board.getSquare(coord, state); if (!sq) return false; return !!sq.tags["enpassant"]; }; } function enpassantPostMove(piece, state, board) { var coord = piece.getRelativeDestination({ file: 0, rank: -1 }); var square = board.getSquare(coord, state); state.capturedPieces.push(square.piece); square.piece = null; } var pawn = { notation: "p", name: "Pawn", movement: [moveForward, firstMove, leftCapture, rightCapture, leftEnpassant, rightEnpassant], canQueen: true, canSpawn: false, value: 1 }; module.exports = pawn; //# sourceMappingURL=pawn.js.map
/******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { /** * Created by flftfqwxf on 16/5/27. */ //var subtract = require("subtract"); __webpack_require__(1) //require('style!css!sass!./a.scss') /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { // style-loader: Adds some css to the DOM by adding a <style> tag // load the styles var content = __webpack_require__(2); if(typeof content === 'string') content = [[module.id, content, '']]; // add the styles to the DOM var update = __webpack_require__(4)(content, {}); if(content.locals) module.exports = content.locals; // Hot Module Replacement if(false) { // When the styles change, update the <style> tags if(!content.locals) { module.hot.accept("!!./../../node_modules/css-loader/index.js!./../../node_modules/sass-loader/index.js!./a.scss", function() { var newContent = require("!!./../../node_modules/css-loader/index.js!./../../node_modules/sass-loader/index.js!./a.scss"); if(typeof newContent === 'string') newContent = [[module.id, newContent, '']]; update(newContent); }); } // When the module is disposed, remove the <style> tags module.hot.dispose(function() { update(); }); } /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { exports = module.exports = __webpack_require__(3)(); // imports // module exports.push([module.id, "body {\n background: #f00; }\n body .a {\n color: #000; }\n", ""]); // exports /***/ }, /* 3 */ /***/ function(module, exports) { /* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ // css base code, injected by the css-loader module.exports = function() { var list = []; // return the list of modules as css string list.toString = function toString() { var result = []; for(var i = 0; i < this.length; i++) { var item = this[i]; if(item[2]) { result.push("@media " + item[2] + "{" + item[1] + "}"); } else { result.push(item[1]); } } return result.join(""); }; // import a list of modules into the list list.i = function(modules, mediaQuery) { if(typeof modules === "string") modules = [[null, modules, ""]]; var alreadyImportedModules = {}; for(var i = 0; i < this.length; i++) { var id = this[i][0]; if(typeof id === "number") alreadyImportedModules[id] = true; } for(i = 0; i < modules.length; i++) { var item = modules[i]; // skip already imported module // this implementation is not 100% perfect for weird media query combinations // when a module is imported multiple times with different media queries. // I hope this will never occur (Hey this way we have smaller bundles) if(typeof item[0] !== "number" || !alreadyImportedModules[item[0]]) { if(mediaQuery && !item[2]) { item[2] = mediaQuery; } else if(mediaQuery) { item[2] = "(" + item[2] + ") and (" + mediaQuery + ")"; } list.push(item); } } }; return list; }; /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { /* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ var stylesInDom = {}, memoize = function(fn) { var memo; return function () { if (typeof memo === "undefined") memo = fn.apply(this, arguments); return memo; }; }, isOldIE = memoize(function() { return /msie [6-9]\b/.test(window.navigator.userAgent.toLowerCase()); }), getHeadElement = memoize(function () { return document.head || document.getElementsByTagName("head")[0]; }), singletonElement = null, singletonCounter = 0, styleElementsInsertedAtTop = []; module.exports = function(list, options) { if(false) { if(typeof document !== "object") throw new Error("The style-loader cannot be used in a non-browser environment"); } options = options || {}; // Force single-tag solution on IE6-9, which has a hard limit on the # of <style> // tags it will allow on a page if (typeof options.singleton === "undefined") options.singleton = isOldIE(); // By default, add <style> tags to the bottom of <head>. if (typeof options.insertAt === "undefined") options.insertAt = "bottom"; var styles = listToStyles(list); addStylesToDom(styles, options); return function update(newList) { var mayRemove = []; for(var i = 0; i < styles.length; i++) { var item = styles[i]; var domStyle = stylesInDom[item.id]; domStyle.refs--; mayRemove.push(domStyle); } if(newList) { var newStyles = listToStyles(newList); addStylesToDom(newStyles, options); } for(var i = 0; i < mayRemove.length; i++) { var domStyle = mayRemove[i]; if(domStyle.refs === 0) { for(var j = 0; j < domStyle.parts.length; j++) domStyle.parts[j](); delete stylesInDom[domStyle.id]; } } }; } function addStylesToDom(styles, options) { for(var i = 0; i < styles.length; i++) { var item = styles[i]; var domStyle = stylesInDom[item.id]; if(domStyle) { domStyle.refs++; for(var j = 0; j < domStyle.parts.length; j++) { domStyle.parts[j](item.parts[j]); } for(; j < item.parts.length; j++) { domStyle.parts.push(addStyle(item.parts[j], options)); } } else { var parts = []; for(var j = 0; j < item.parts.length; j++) { parts.push(addStyle(item.parts[j], options)); } stylesInDom[item.id] = {id: item.id, refs: 1, parts: parts}; } } } function listToStyles(list) { var styles = []; var newStyles = {}; for(var i = 0; i < list.length; i++) { var item = list[i]; var id = item[0]; var css = item[1]; var media = item[2]; var sourceMap = item[3]; var part = {css: css, media: media, sourceMap: sourceMap}; if(!newStyles[id]) styles.push(newStyles[id] = {id: id, parts: [part]}); else newStyles[id].parts.push(part); } return styles; } function insertStyleElement(options, styleElement) { var head = getHeadElement(); var lastStyleElementInsertedAtTop = styleElementsInsertedAtTop[styleElementsInsertedAtTop.length - 1]; if (options.insertAt === "top") { if(!lastStyleElementInsertedAtTop) { head.insertBefore(styleElement, head.firstChild); } else if(lastStyleElementInsertedAtTop.nextSibling) { head.insertBefore(styleElement, lastStyleElementInsertedAtTop.nextSibling); } else { head.appendChild(styleElement); } styleElementsInsertedAtTop.push(styleElement); } else if (options.insertAt === "bottom") { head.appendChild(styleElement); } else { throw new Error("Invalid value for parameter 'insertAt'. Must be 'top' or 'bottom'."); } } function removeStyleElement(styleElement) { styleElement.parentNode.removeChild(styleElement); var idx = styleElementsInsertedAtTop.indexOf(styleElement); if(idx >= 0) { styleElementsInsertedAtTop.splice(idx, 1); } } function createStyleElement(options) { var styleElement = document.createElement("style"); styleElement.type = "text/css"; insertStyleElement(options, styleElement); return styleElement; } function createLinkElement(options) { var linkElement = document.createElement("link"); linkElement.rel = "stylesheet"; insertStyleElement(options, linkElement); return linkElement; } function addStyle(obj, options) { var styleElement, update, remove; if (options.singleton) { var styleIndex = singletonCounter++; styleElement = singletonElement || (singletonElement = createStyleElement(options)); update = applyToSingletonTag.bind(null, styleElement, styleIndex, false); remove = applyToSingletonTag.bind(null, styleElement, styleIndex, true); } else if(obj.sourceMap && typeof URL === "function" && typeof URL.createObjectURL === "function" && typeof URL.revokeObjectURL === "function" && typeof Blob === "function" && typeof btoa === "function") { styleElement = createLinkElement(options); update = updateLink.bind(null, styleElement); remove = function() { removeStyleElement(styleElement); if(styleElement.href) URL.revokeObjectURL(styleElement.href); }; } else { styleElement = createStyleElement(options); update = applyToTag.bind(null, styleElement); remove = function() { removeStyleElement(styleElement); }; } update(obj); return function updateStyle(newObj) { if(newObj) { if(newObj.css === obj.css && newObj.media === obj.media && newObj.sourceMap === obj.sourceMap) return; update(obj = newObj); } else { remove(); } }; } var replaceText = (function () { var textStore = []; return function (index, replacement) { textStore[index] = replacement; return textStore.filter(Boolean).join('\n'); }; })(); function applyToSingletonTag(styleElement, index, remove, obj) { var css = remove ? "" : obj.css; if (styleElement.styleSheet) { styleElement.styleSheet.cssText = replaceText(index, css); } else { var cssNode = document.createTextNode(css); var childNodes = styleElement.childNodes; if (childNodes[index]) styleElement.removeChild(childNodes[index]); if (childNodes.length) { styleElement.insertBefore(cssNode, childNodes[index]); } else { styleElement.appendChild(cssNode); } } } function applyToTag(styleElement, obj) { var css = obj.css; var media = obj.media; if(media) { styleElement.setAttribute("media", media) } if(styleElement.styleSheet) { styleElement.styleSheet.cssText = css; } else { while(styleElement.firstChild) { styleElement.removeChild(styleElement.firstChild); } styleElement.appendChild(document.createTextNode(css)); } } function updateLink(linkElement, obj) { var css = obj.css; var sourceMap = obj.sourceMap; if(sourceMap) { // http://stackoverflow.com/a/26603875 css += "\n/*# sourceMappingURL=data:application/json;base64," + btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap)))) + " */"; } var blob = new Blob([css], { type: "text/css" }); var oldSrc = linkElement.href; linkElement.href = URL.createObjectURL(blob); if(oldSrc) URL.revokeObjectURL(oldSrc); } /***/ } /******/ ]);
import{W as e,s as t,h as i,w as r}from"./index-a1fc4272.js";import{f as s}from"./browser-fixes-ad0e4ba1.js";export default class extends e{init(){this.props.src=e=>{this.load(e)},this.props.loading=e=>{this.ref&&this.ref!==this.host&&t(this.ref,"loading",e)},super.init()}connected(){[...this.host.querySelectorAll("img:not([src])")].forEach((e=>{e.parentNode.removeChild(e)}))}load(e){const{host:o}=this;if(!(e=e&&e.trim())||e===this.cachedSrc)return;this.cachedSrc=e;let a=o.querySelector("img")||i("img");return t(a,"loading",o.getAttribute("loading")),a.src=e,a.alt="",this.ref=a,a.parentNode||o.appendChild(a),s(o),a.onerror=()=>{this.removeChild(a);const t=i("nu-icon");t.setAttribute("name","image"),o.appendChild(t),r("image not loaded",e)},e}}
// Find posts where name equals argument // HTTP API // http://localhost:3000/functions/loadPostsByName?name=joe // GraphQL // { // loadPostsByName(name: "joe") { // id // rev // name // } // } module.exports = (ctx, args, parent) => { //Logging to output ctx.log(args.name); //Using PouchDB within your functions ctx.pouchdb('gettingstarted') .find({ selector: {name: args.name} }) .then(data => ctx.success(data.docs.map(toPost))); }; function toPost(doc){ doc.id = doc._id; doc.rev = doc._rev; return doc; }
search_result['643']=["topic_0000000000000159.html","PostVacancyStageController.RetrieveStageList Method",""];
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), Schema = mongoose.Schema; /** * Order enquiry form Schema */ var OrderEnquiryFormSchema = new Schema({ enquiryNo: { type: Number, default: '', required: 'Please fill Order enquiry number', trim: false }, enquiryDate: { type: Date, default: '', required: 'Please fill Order enquiry date', trim: false }, buyerName: { type: String, default: '', required: 'Please fill Order enquiry buyer name', trim: true }, styleName: { type: String, default: '', required: 'Please fill Order enquiry style name', trim: true }, styleNo: { type: Number, default: '', required: 'Please fill Order enquiry style number', trim: false }, orderQuantity: { type: Number, default: '', required: 'Please fill Order quantity', trim: false }, samplingRequiredQty: { type: Number, default: '', required: 'Please fill sampling required quantity', trim: false }, costingRequiredDate: { type: Date, default: '', required: 'Please fill costing required date', trim: false }, samplingRequiredDate: { type: Date, default: '', required: 'Please fill sampling required date', trim: false }, created: { type: Date, default: Date.now }, user: { type: Schema.ObjectId, ref: 'User' } }); mongoose.model('OrderEnquiryForm', OrderEnquiryFormSchema);
import winston from 'winston' import expressWinston from 'express-winston' import { isProd } from 'shared/env' const ERROR_MSG_500 = 'Internal server error' export default [ function handleNotFound(req, res, next) { res.status(404).send('NotFound') }, expressWinston.errorLogger({ transports: [ new winston.transports.Console({ json: true, colorize: true }) ] }), function handleInternalError(err, req, res, next) { res.status(500).send(isProd ? ERROR_MSG_500 : err.message || ERROR_MSG_500) } ]
/** * Module dependencies */ var Sails = require('../../../lib').Sails; describe('Pubsub hook', function (){ describe('loading a Sails app', function (){ describe('without ORM hook', function (){ var app = Sails(); it('should fail', function (done){ app.load({ globals: false, log: {level: 'silent'}, loadHooks: ['moduleloader','userconfig','pubsub'] }, function (err){ if (err) { return done(); } return done(new Error('Should have failed to load the pubsub hook w/o the `orm` hook.')); }); }); after(app.lower); }); describe('without sockets hook', function (){ var app = Sails(); it('should fail', function (done){ app.load({ globals: false, log: {level: 'silent'}, loadHooks: ['moduleloader','userconfig','orm', 'pubsub'] }, function (err){ if (err) { return done(); } return done(new Error('Should have failed to load the pubsub hook w/o the `sockets` hook.')); }); }); after(app.lower); }); describe('without http hook', function (){ var app = Sails(); it('should fail', function (done){ app.load({ globals: false, log: {level: 'silent'}, loadHooks: ['moduleloader','userconfig','orm', 'sockets', 'pubsub'] }, function (err){ if (err) { return done(); } return done(new Error('Should have failed to load the pubsub hook w/o the `http` hook.')); }); }); after(app.lower); }); describe('with `orm` and `sockets` hooks', function (){ var app = Sails(); it('should load successfully', function (done){ app.load({ globals: false, log: {level: 'warn'}, loadHooks: ['moduleloader','userconfig','orm', 'http', 'sockets', 'pubsub'] }, function (err){ if (err) { return done(err); } return done(); }); }); after(app.lower); }); }); });
search_result['1814']=["topic_0000000000000467_events--.html","tlece_UserSetting Events",""];
search_result['3233']=["topic_00000000000007C0_attached_props--.html","ApplicantDetailResponseDto Attached Properties",""];
/** * Create a constant object. * * @method createConstants * @public * * @param {String} constants The constants to be converted. * @return {Object} an key/value constant object */ export default function (...constants:Object):Object { return constants.reduce((accumulator:Object, constant:string):Object => { accumulator[constant] = constant; return accumulator; }, {}); }
var vsmApp = angular.module('vsmApp'); vsmApp.service('StockQuotesService', ['$http','$q','$log','$rootScope', function ($http, $q, $log, $rootScope) { this.getStockLists = function(){ var deferred = $q.defer(), actionUrl = 'stockList/'; actionUrl = $rootScope.getFinalURL(actionUrl); $http.get(actionUrl,{}) .success(function (json) { deferred.resolve(json); }).error(function(msg, code) { deferred.reject(msg); $log.error(msg, code); }); return deferred.promise; }; this.getAllCurrentQuotes = function(){ var deferred = $q.defer(), actionUrl = 'stockListAllCurrentQuotes/'; actionUrl = $rootScope.getFinalURL(actionUrl); $http.get(actionUrl,{}) .success(function (quotesJSON) { deferred.resolve(quotesJSON); }).error(function(msg, code) { deferred.reject(msg); $log.error(msg, code); }); return deferred.promise; }; this.getCurrentQuote = function(symbol){ var deferred = $q.defer(), actionUrl = 'stockListCurrentQuotes?stockSymbol='; actionUrl = $rootScope.getFinalURL(actionUrl); $http.get(actionUrl+symbol,{}) .success(function (quotesJSON) { deferred.resolve(quotesJSON); }).error(function(msg, code) { deferred.reject(msg); $log.error(msg, code); }); return deferred.promise; }; this.getHistoricalStockLists = function(ticker){ var deferred = $q.defer(), actionUrl = 'stockListHistory?stockSymbol='; actionUrl = $rootScope.getFinalURL(actionUrl); $http.get(actionUrl+ticker,{}) .success(function (json) { deferred.resolve(json); }).error(function(msg, code) { deferred.reject(msg); $log.error(msg, code); }); return deferred.promise; }; this.reducedHistoricalData = function(historicalData, count){ var length = historicalData.length; return historicalData.slice(length - count, length); }; this.getMyLeagues = function(){ var deferred = $q.defer(); var actionUrl = 'userLeaguesList/'; actionUrl = $rootScope.getFinalURL(actionUrl); $http.get(actionUrl,{}) .success(function (json) { deferred.resolve(json); }).error(function(msg, code) { deferred.reject(msg); $log.error(msg, code); }); return deferred.promise; }; this.getMyPortfolio = function(leagueId){ var deferred = $q.defer(); var actionUrl = 'myPortfolio?leagueId='; actionUrl = $rootScope.getFinalURL(actionUrl); $http.post(actionUrl+leagueId,{}) .success(function (json) { deferred.resolve(json); }).error(function(msg, code) { deferred.reject(msg); $log.error(msg, code); }); return deferred.promise; }; this.getMyRecentTrades = function(leagueId){ var deferred = $q.defer(); var actionUrl = 'myRecentTrades?leagueId='; actionUrl = $rootScope.getFinalURL(actionUrl); $http.get(actionUrl+leagueId,{}) .success(function (json) { deferred.resolve(json); }).error(function(msg, code) { deferred.reject(msg); $log.error(msg, code); }); return deferred.promise; }; }]);
import fs from 'fs'; import url from 'url'; import path from 'path'; import mkdirp from 'mkdirp'; import request from 'request'; import Log from '../utils/log'; const log = new Log('WORKER-' + process.argv.slice(2)[0]); let wouldExit = false; let config, task, id , fileName, localPath, sourceUrl, targetDir, folder; let targets = {}; process.on('message', (m) => { if (m.new) { task = m.new; config = m.config; initTask(); } else if (m.exit) { process.exit(); } }); function initTask() { if (isNaN(task['retry'])) { task['retry'] = 0; } id = task.id; const defaultName = id + path.extname(url.parse(task.content.src).pathname); fileName = task.content.file_name || defaultName; config.targets.forEach((val) => { targets[val.target] = val; }); folder = task.content.folder ? `/${task.content.folder}/` : '/'; targetDir = targets.local.path + folder; localPath = targetDir + fileName; sourceUrl = task.content.src; mkdirp(targetDir, download); } function download () { try { const stream = request(sourceUrl, { timeout: 10000, headers: { 'User-Agent': `Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.69 Safari/537.36 QQBrowser/9.0.2617.400` } }).on('error', (err) => { process.send({ fail: task, error: err }); }).pipe(fs.createWriteStream(localPath)).on('finish', () => { process.send({ fin: task }); }); } catch (e) { process.send({ fail: task, error: e }); } }
// TypeIt by Alex MacArthur - https://typeitjs.com var isArray = (thing) => Array.isArray(thing); var asArray = (value) => { return isArray(value) ? value : [value]; }; const Queue = function(initialItems) { const add = function(steps) { _queue = _queue.concat(asArray(steps)); return this; }; const set = function(index, item) { _queue[index] = item; }; const reset = function() { _queue = _queue.map((item) => { delete item.done; return item; }); }; const getItems = () => _queue.filter((i) => !i.done); const markDone = (index) => { _queue[index].done = true; }; let _queue = []; add(initialItems); return { add, set, reset, getItems, markDone }; }; var toArray = (val) => { return Array.from(val); }; var createTextNode = (content) => { return document.createTextNode(content); }; const expandTextNodes = (element) => { [...element.childNodes].forEach((child) => { if (child.nodeValue) { [...child.nodeValue].forEach((c) => { child.parentNode.insertBefore(createTextNode(c), child); }); child.remove(); return; } expandTextNodes(child); }); return element; }; var getParsedBody = (content) => { let doc = document.implementation.createHTMLDocument(); doc.body.innerHTML = content; return expandTextNodes(doc.body); }; const DATA_ATTRIBUTE = "data-typeit-id"; const CURSOR_CLASS = "ti-cursor"; const START = "START"; const END = "END"; const DEFAULT_STATUSES = { started: false, completed: false, frozen: false, destroyed: false }; const DEFAULT_OPTIONS = { breakLines: true, cursor: true, cursorChar: "|", cursorSpeed: 1e3, deleteSpeed: null, html: true, lifeLike: true, loop: false, loopDelay: 750, nextStringDelay: 750, speed: 100, startDelay: 250, startDelete: false, strings: [], waitUntilVisible: false, beforeString: () => { }, afterString: () => { }, beforeStep: () => { }, afterStep: () => { }, afterComplete: () => { } }; function walkElementNodes(element, shouldReverse = false) { const walker = document.createTreeWalker(element, NodeFilter.SHOW_ALL, { acceptNode: (node) => { var _a; return ((_a = node == null ? void 0 : node.classList) == null ? void 0 : _a.contains(CURSOR_CLASS)) ? NodeFilter.FILTER_REJECT : NodeFilter.FILTER_ACCEPT; } }); let nextNode; let nodes = []; while (nextNode = walker.nextNode()) { nextNode.originalParent = nextNode.parentNode; nodes.push(nextNode); } return shouldReverse ? nodes.reverse() : nodes; } function chunkStringAsHtml(string) { return walkElementNodes(getParsedBody(string)); } function maybeChunkStringAsHtml(str, asHtml = true) { return asHtml ? chunkStringAsHtml(str) : toArray(str).map(createTextNode); } var createElement = (el) => { return document.createElement(el); }; var appendStyleBlock = (styles, id = "") => { let styleBlock = createElement("style"); styleBlock.id = id; styleBlock.appendChild(createTextNode(styles)); document.head.appendChild(styleBlock); }; const isNumber = (value) => { return Number.isInteger(value); }; const select = (selector, element = document, all = false) => { return element[`querySelector${all ? "All" : ""}`](selector); }; var isInput = (el) => { return "value" in el; }; const getAllChars = (element) => { if (isInput(element)) { return toArray(element.value); } return walkElementNodes(element, true).filter((c) => !(c.childNodes.length > 0)); }; const calculateStepsToSelector = (selector, element, to = START) => { let isMovingToLast = new RegExp(END, "i").test(to); let selectedElement = selector ? select(selector, element) : element; let selectedElementNodes = walkElementNodes(selectedElement, true); let selectedElementFirstChild = selectedElementNodes[0]; let selectedElementLastChild = selectedElementNodes[selectedElementNodes.length - 1]; let isMovingToEndOfRootElement = isMovingToLast && !selector; let childIndex = isMovingToEndOfRootElement ? 0 : getAllChars(element).findIndex((character) => { return character.isSameNode(isMovingToLast ? selectedElementFirstChild : selectedElementLastChild); }); if (isMovingToLast) childIndex--; return childIndex + 1; }; var calculateCursorSteps = ({ el, move, cursorPos, to }) => { if (isNumber(move)) { return move * -1; } let childIndex = calculateStepsToSelector(move, el, to); return childIndex - cursorPos; }; var calculateDelay = (delayArg) => { if (!isArray(delayArg)) { delayArg = [delayArg / 2, delayArg / 2]; } return delayArg; }; var randomInRange = (value, range2) => { return Math.abs(Math.random() * (value + range2 - (value - range2)) + (value - range2)); }; let range = (val) => val / 2; function calculatePace(options) { let { speed, deleteSpeed, lifeLike } = options; deleteSpeed = deleteSpeed !== null ? deleteSpeed : speed / 3; return lifeLike ? [ randomInRange(speed, range(speed)), randomInRange(deleteSpeed, range(deleteSpeed)) ] : [speed, deleteSpeed]; } var destroyTimeouts = (timeouts) => { timeouts.forEach((timeout) => clearTimeout(timeout)); return []; }; var generateHash = () => { return Math.random().toString().substring(2, 9); }; var fireWhenVisible = (element, func) => { let observer = new IntersectionObserver((entries, observer2) => { entries.forEach((entry) => { if (entry.isIntersecting) { func(); observer2.unobserve(element); } }); }, { threshold: 1 }); observer.observe(element); }; const handleFunctionalArg = (arg) => { return typeof arg === "function" ? arg() : arg; }; const isBodyElement = (node) => (node == null ? void 0 : node.tagName) === "BODY"; const insertIntoElement = (originalTarget, character) => { if (isInput(originalTarget)) { originalTarget.value = `${originalTarget.value}${character.textContent}`; return; } character.innerHTML = ""; let target = isBodyElement(character.originalParent) ? originalTarget : character.originalParent || originalTarget; target.insertBefore(character, select("." + CURSOR_CLASS, target) || null); }; const updateCursorPosition = (steps, cursorPosition, printedCharacters) => { return Math.min(Math.max(cursorPosition + steps, 0), printedCharacters.length); }; var merge = (originalObj, newObj) => { return Object.assign({}, originalObj, newObj); }; var removeNode = (node) => { if (!node) return; const nodeParent = node.parentNode; const nodeToRemove = nodeParent.childNodes.length > 1 ? node : nodeParent; nodeToRemove.remove(); }; var repositionCursor = (element, allChars, newCursorPosition) => { let nodeToInsertBefore = allChars[newCursorPosition - 1]; let cursor = select(`.${CURSOR_CLASS}`, element); element = (nodeToInsertBefore == null ? void 0 : nodeToInsertBefore.parentNode) || element; element.insertBefore(cursor, nodeToInsertBefore || null); }; function selectorToElement(thing) { return typeof thing === "string" ? select(thing) : thing; } const isNonVoidElement = (el) => /<(.+)>(.*?)<\/(.+)>/.test(el.outerHTML); const wait = async (callback, delay, timeouts) => { return new Promise((resolve) => { const cb = async () => { await callback(); resolve(); }; timeouts.push(setTimeout(cb, delay)); }); }; const cursorFontStyles = { "font-family": "", "font-weight": "", "font-size": "", "font-style": "", "line-height": "", color: "", "margin-left": "-.125em", "margin-right": ".125em" }; const setCursorStyles = (id, options, element) => { let rootSelector = `[${DATA_ATTRIBUTE}='${id}']`; let cursorSelector = `${rootSelector} .${CURSOR_CLASS}`; let computedStyles = getComputedStyle(element); let customProperties = Object.entries(cursorFontStyles).reduce((accumulator, [item, value]) => { return `${accumulator} ${item}: var(--ti-cursor-${item}, ${value || computedStyles[item]});`; }, ""); appendStyleBlock(`@keyframes blink-${id} { 0% {opacity: 0} 49% {opacity: 0} 50% {opacity: 1} } ${cursorSelector} { display: inline; letter-spacing: -1em; ${customProperties} animation: blink-${id} ${options.cursorSpeed / 1e3}s infinite; } ${cursorSelector}.with-delay { animation-delay: 500ms; } ${cursorSelector}.disabled { animation: none; }`, id); }; function TypeIt(element, options = {}) { const _wait = async (callback, delay, silent = false) => { if (_statuses.frozen) { await new Promise((resolve) => { this.unfreeze = () => { _statuses.frozen = false; resolve(); }; }); } silent || await _opts.beforeStep(this); await wait(callback, delay, _timeouts); silent || await _opts.afterStep(this); }; const _elementIsInput = () => isInput(_element); const _getPace = (index) => calculatePace(_opts)[index]; const _getAllChars = () => getAllChars(_element); const _getActionPace = (instant, paceIndex = 0) => { return instant ? _getPace(paceIndex) : 0; }; const _maybeAppendPause = (opts = {}) => { let delay = opts["delay"]; delay && _queue.add(() => _pause(delay)); }; const _queueAndReturn = (steps, opts) => { _queue.add(steps); _maybeAppendPause(opts); return this; }; const _generateTemporaryOptionQueueItems = (newOptions = {}) => { return [ () => _options(newOptions), () => _options(_opts) ]; }; const _addSplitPause = (items) => { let delay = _opts.nextStringDelay; _queue.add([ () => _pause(delay[0]), ...items, () => _pause(delay[1]) ]); }; const _setUpCursor = () => { if (_elementIsInput()) { return; } let cursor = createElement("span"); cursor.className = CURSOR_CLASS; if (!_shouldRenderCursor) { cursor.style.visibility = "hidden"; return cursor; } cursor.innerHTML = getParsedBody(_opts.cursorChar).innerHTML; return cursor; }; const _attachCursor = async () => { !_elementIsInput() && _element.appendChild(_cursor); _shouldRenderCursor && setCursorStyles(_id, _opts, _element); }; const _disableCursorBlink = (shouldDisable) => { if (_shouldRenderCursor) { _cursor.classList.toggle("disabled", shouldDisable); _cursor.classList.toggle("with-delay", !shouldDisable); } }; const _generateQueue = () => { let strings = _opts.strings.filter((string) => !!string); strings.forEach((string, index) => { let chars = maybeChunkStringAsHtml(string, _opts.html); _queue.add(() => _type({ chars })); if (index + 1 === strings.length) { return; } const splitPauseArgs = [ _opts.breakLines ? () => _type({ chars: [createElement("BR")], silent: true }) : () => _delete({ num: chars.length }) ]; _addSplitPause(splitPauseArgs); }); }; const _prepLoop = async (delay) => { _cursorPosition && await _move({ value: _cursorPosition }); _queue.reset(); _queue.set(0, () => _pause(delay)); await _delete({ num: null }); }; const _maybePrependHardcodedStrings = (strings) => { let existingMarkup = _element.innerHTML; if (!existingMarkup) { return strings; } _element.innerHTML = ""; if (_opts.startDelete) { _element.innerHTML = existingMarkup; expandTextNodes(_element); _addSplitPause([ () => _delete({ num: null }) ]); return strings; } let hardCodedStrings = existingMarkup.trim().split(/<br(?:\s*?)(?:\/)?>/); return hardCodedStrings.concat(strings); }; const _fire = async () => { _statuses.started = true; let queueItems = _queue.getItems(); try { for (let i = 0; i < queueItems.length; i++) { await queueItems[i](); _queue.markDone(i); _disableCursorBlink(false); } _statuses.completed = true; await _opts.afterComplete(this); if (!_opts.loop) { throw ""; } let delay = _opts.loopDelay; _wait(async () => { await _prepLoop(delay[0]); _fire(); }, delay[1]); } catch (e) { } return this; }; const _pause = (time = 0) => { return _wait(() => { }, time); }; const _move = async ({ value, to = START, instant = false }) => { _disableCursorBlink(true); let numberOfSteps = calculateCursorSteps({ el: _element, move: value, cursorPos: _cursorPosition, to }); let moveCursor = () => { _cursorPosition = updateCursorPosition(numberOfSteps < 0 ? -1 : 1, _cursorPosition, _getAllChars()); repositionCursor(_element, _getAllChars(), _cursorPosition); }; await _wait(async () => { for (let i = 0; i < Math.abs(numberOfSteps); i++) { instant ? moveCursor() : await _wait(moveCursor, _getPace(0)); } }, _getActionPace(instant)); }; const _type = ({ chars, silent = false, instant = false }) => { _disableCursorBlink(true); return _wait(async () => { const insert = (character) => insertIntoElement(_element, character); silent || await _opts.beforeString(chars, this); for (let char of chars) { instant || isNonVoidElement(char) ? insert(char) : await _wait(() => insert(char), _getPace(0)); } silent || await _opts.afterString(chars, this); }, _getActionPace(instant), true); }; const _options = async (opts) => { _opts = merge(_opts, opts); return; }; const _empty = async () => { if (_elementIsInput()) { _element.value = ""; return; } _getAllChars().forEach((n) => { removeNode(n); }); return; }; const _delete = async ({ num = null, instant = false, to = START }) => { _disableCursorBlink(true); await _wait(async () => { let rounds = isNumber(num) || _elementIsInput() ? num : calculateCursorSteps({ el: _element, move: num, cursorPos: _cursorPosition, to }); const deleteIt = () => { let allChars = _getAllChars(); if (!allChars.length) return; if (_elementIsInput()) { _element.value = _element.value.slice(0, -1); } else { removeNode(allChars[_cursorPosition]); } }; for (let i = 0; i < rounds; i++) { instant ? deleteIt() : await _wait(deleteIt, _getPace(1)); } }, _getActionPace(instant, 1)); if (num === null && _getAllChars().length - 1 > 0) { await _delete({ num: null }); } }; this.break = function(actionOpts) { return _queueAndReturn(() => _type({ chars: [createElement("BR")], silent: true }), actionOpts); }; this.delete = function(numCharacters = null, actionOpts = {}) { numCharacters = handleFunctionalArg(numCharacters); let bookEndQueueItems = _generateTemporaryOptionQueueItems(actionOpts); let num = numCharacters; let { instant, to } = actionOpts; return _queueAndReturn([ bookEndQueueItems[0], () => _delete({ num, instant, to }), bookEndQueueItems[1] ], actionOpts); }; this.empty = function(actionOpts = {}) { return _queueAndReturn(_empty, actionOpts); }; this.exec = function(func, actionOpts) { let bookEndQueueItems = _generateTemporaryOptionQueueItems(actionOpts); return _queueAndReturn([bookEndQueueItems[0], func, bookEndQueueItems[1]], actionOpts); }; this.move = function(movementArg, actionOpts = {}) { movementArg = handleFunctionalArg(movementArg); let bookEndQueueItems = _generateTemporaryOptionQueueItems(actionOpts); let { instant, to } = actionOpts; let moveArgs = { value: movementArg === null ? "" : movementArg, to, instant }; return _queueAndReturn([ bookEndQueueItems[0], () => _move(moveArgs), bookEndQueueItems[1] ], actionOpts); }; this.options = function(opts) { opts = handleFunctionalArg(opts); return _queueAndReturn(() => _options(opts), opts); }; this.pause = function(milliseconds, actionOpts = {}) { return _queueAndReturn(() => _pause(handleFunctionalArg(milliseconds)), actionOpts); }; this.type = function(string, actionOpts = {}) { string = handleFunctionalArg(string); let bookEndQueueItems = _generateTemporaryOptionQueueItems(actionOpts); let chars = maybeChunkStringAsHtml(string, _opts.html); let { instant } = actionOpts; let itemsToQueue = [ bookEndQueueItems[0], () => _type({ chars, instant }), bookEndQueueItems[1] ]; return _queueAndReturn(itemsToQueue, actionOpts); }; this.is = function(key) { return _statuses[key]; }; this.destroy = function(shouldRemoveCursor = true) { _timeouts = destroyTimeouts(_timeouts); handleFunctionalArg(shouldRemoveCursor) && removeNode(_cursor); _statuses.destroyed = true; }; this.freeze = function() { _statuses.frozen = true; }; this.unfreeze = function() { }; this.reset = function() { !this.is("destroyed") && this.destroy(); _queue.reset(); _cursorPosition = 0; for (let property in _statuses) { _statuses[property] = false; } _element[_elementIsInput() ? "value" : "innerHTML"] = ""; return this; }; this.go = function() { if (_statuses.started) { return this; } _attachCursor(); if (!_opts.waitUntilVisible) { _fire(); return this; } fireWhenVisible(_element, _fire.bind(this)); return this; }; this.getQueue = () => _queue; this.getOptions = () => _opts; this.updateOptions = (options2) => _options(options2); this.getElement = () => _element; let _element = selectorToElement(element); let _timeouts = []; let _cursorPosition = 0; let _statuses = merge({}, DEFAULT_STATUSES); let _opts = merge(DEFAULT_OPTIONS, options); _opts = merge(_opts, { html: !_elementIsInput() && _opts.html, nextStringDelay: calculateDelay(_opts.nextStringDelay), loopDelay: calculateDelay(_opts.loopDelay) }); let _id = generateHash(); let _queue = Queue([() => _pause(_opts.startDelay)]); _element.dataset.typeitId = _id; appendStyleBlock(`[${DATA_ATTRIBUTE}]:before {content: '.'; display: inline-block; width: 0; visibility: hidden;}`); let _shouldRenderCursor = _opts.cursor && !_elementIsInput(); let _cursor = _setUpCursor(); _opts.strings = _maybePrependHardcodedStrings(asArray(_opts.strings)); if (_opts.strings.length) { _generateQueue(); } } export { TypeIt as default };
import"./index-cc7d787a.js";import{F as t}from"./formatter-b76b37f7.js";import{n as r}from"./number-ef2d228a.js";export default class extends t{static get formatter(){return r}}
/*! * DevExtreme (dx.messages.tr.js) * Version: 21.2.5 (build 22033-1237) * Build date: Wed Feb 02 2022 * * Copyright (c) 2012 - 2022 Developer Express Inc. ALL RIGHTS RESERVED * Read about DevExtreme licensing here: https://js.devexpress.com/Licensing/ */ "use strict"; ! function(root, factory) { if ("function" === typeof define && define.amd) { define((function(require) { factory(require("devextreme/localization")) })) } else if ("object" === typeof module && module.exports) { factory(require("devextreme/localization")) } else { factory(DevExpress.localization) } }(0, (function(localization) { localization.loadMessages({ tr: { Yes: "Evet", No: "Hay\u0131r", Cancel: "\u0130ptal", Clear: "Temizle", Done: "Tamam", Loading: "Y\xfckleniyor...", Select: "Se\xe7...", Search: "Ara", Back: "Geri", OK: "Tamam", "dxCollectionWidget-noDataText": "G\xf6sterilecek bilgi yok", "validation-required": "Zorunlu", "validation-required-formatted": "{0} gerekli", "validation-numeric": "De\u011fer bir say\u0131 olmal\u0131", "validation-numeric-formatted": "{0} bir say\u0131 olmal\u0131", "validation-range": "De\u011fer aral\u0131k d\u0131\u015f\u0131nda", "validation-range-formatted": "{0} aral\u0131k d\u0131\u015f\u0131nda", "validation-stringLength": "De\u011ferin uzunlu\u011fu do\u011fru de\u011fil", "validation-stringLength-formatted": "{0} uzunlu\u011fu do\u011fru de\u011fil", "validation-custom": "De\u011fer ge\xe7ersiz", "validation-custom-formatted": "{0} ge\xe7ersiz", "validation-compare": "De\u011ferler e\u015fle\u015fmiyor", "validation-compare-formatted": "{0} e\u015fle\u015fmiyor", "validation-pattern": "De\u011fer kal\u0131pla e\u015fle\u015fmiyor", "validation-pattern-formatted": "{0} kal\u0131pla e\u015fle\u015fmiyor", "validation-email": "E-posta ge\xe7ersiz", "validation-email-formatted": "{0} ge\xe7ersiz", "validation-mask": "De\u011fer ge\xe7ersiz", "dxLookup-searchPlaceholder": "Minimum karakter say\u0131s\u0131: {0}", "dxList-pullingDownText": "Yenilemek i\xe7in a\u015fa\u011f\u0131ya \xe7ekin...", "dxList-pulledDownText": "Yenilemek i\xe7in b\u0131rak\u0131n...", "dxList-refreshingText": "Yenileniyor...", "dxList-pageLoadingText": "Y\xfckleniyor...", "dxList-nextButtonText": "Daha", "dxList-selectAll": "T\xfcm\xfcn\xfc Se\xe7", "dxListEditDecorator-delete": "Sil", "dxListEditDecorator-more": "Daha", "dxScrollView-pullingDownText": "Yenilemek i\xe7in a\u015fa\u011f\u0131ya \xe7ekin...", "dxScrollView-pulledDownText": "Yenilemek i\xe7in b\u0131rak\u0131n...", "dxScrollView-refreshingText": "Yenileniyor...", "dxScrollView-reachBottomText": "Y\xfckleniyor...", "dxDateBox-simulatedDataPickerTitleTime": "Saat se\xe7", "dxDateBox-simulatedDataPickerTitleDate": "Tarih se\xe7", "dxDateBox-simulatedDataPickerTitleDateTime": "Tarih ve saati se\xe7in", "dxDateBox-validation-datetime": "De\u011fer bir tarih veya saat olmal\u0131d\u0131r", "dxFileUploader-selectFile": "Dosya se\xe7", "dxFileUploader-dropFile": "veya Dosyay\u0131 buraya b\u0131rak\u0131n", "dxFileUploader-bytes": "bytes", "dxFileUploader-kb": "kb", "dxFileUploader-Mb": "Mb", "dxFileUploader-Gb": "Gb", "dxFileUploader-upload": "Y\xfckleme", "dxFileUploader-uploaded": "Y\xfcklenen", "dxFileUploader-readyToUpload": "Y\xfcklemeye haz\u0131r", "dxFileUploader-uploadAbortedMessage": "TODO", "dxFileUploader-uploadFailedMessage": "Y\xfckleme ba\u015far\u0131s\u0131z", "dxFileUploader-invalidFileExtension": "Dosya t\xfcr\xfcne izin verilmiyor", "dxFileUploader-invalidMaxFileSize": "Dosya \xe7ok b\xfcy\xfck", "dxFileUploader-invalidMinFileSize": "Dosya \xe7ok k\xfc\xe7\xfck", "dxRangeSlider-ariaFrom": "\u0130tibaren", "dxRangeSlider-ariaTill": "Kadar", "dxSwitch-switchedOnText": "A\xe7\u0131k", "dxSwitch-switchedOffText": "Kapal\u0131", "dxForm-optionalMark": "iste\u011fe ba\u011fl\u0131", "dxForm-requiredMessage": "{0} gerekli", "dxNumberBox-invalidValueMessage": "De\u011fer bir say\u0131 olmal\u0131", "dxNumberBox-noDataText": "Veri yok", "dxDataGrid-columnChooserTitle": "S\xfctun Se\xe7ici", "dxDataGrid-columnChooserEmptyText": "S\xfctunu gizlemek i\xe7in buraya s\xfcr\xfckleyin", "dxDataGrid-groupContinuesMessage": "Bir sonraki sayfada devam ediyor", "dxDataGrid-groupContinuedMessage": "\xd6nceki sayfadan devam", "dxDataGrid-groupHeaderText": "Bu S\xfctuna G\xf6re Grupla", "dxDataGrid-ungroupHeaderText": "Grubu Kald\u0131r", "dxDataGrid-ungroupAllText": "T\xfcm Gruplar\u0131 Kald\u0131r", "dxDataGrid-editingEditRow": "D\xfczenle", "dxDataGrid-editingSaveRowChanges": "Kaydet", "dxDataGrid-editingCancelRowChanges": "\u0130ptal", "dxDataGrid-editingDeleteRow": "Sil", "dxDataGrid-editingUndeleteRow": "Silme", "dxDataGrid-editingConfirmDeleteMessage": "Bu kayd\u0131 silmek istedi\u011finize emin misiniz?", "dxDataGrid-validationCancelChanges": "De\u011fi\u015fiklikleri iptal et", "dxDataGrid-groupPanelEmptyText": "Bu s\xfctuna g\xf6re gruplamak i\xe7in bir s\xfctun ba\u015fl\u0131\u011f\u0131n\u0131 buraya s\xfcr\xfckleyin", "dxDataGrid-noDataText": "Veri yok", "dxDataGrid-searchPanelPlaceholder": "Arama...", "dxDataGrid-filterRowShowAllText": "(T\xfcm\xfc)", "dxDataGrid-filterRowResetOperationText": "S\u0131f\u0131rla", "dxDataGrid-filterRowOperationEquals": "E\u015fittir", "dxDataGrid-filterRowOperationNotEquals": "E\u015fit de\u011fil", "dxDataGrid-filterRowOperationLess": "Daha k\xfc\xe7\xfck", "dxDataGrid-filterRowOperationLessOrEquals": "Daha k\xfc\xe7\xfck veya e\u015fit", "dxDataGrid-filterRowOperationGreater": "Daha b\xfcy\xfck", "dxDataGrid-filterRowOperationGreaterOrEquals": "Daha b\xfcy\xfck veya e\u015fit", "dxDataGrid-filterRowOperationStartsWith": "\u0130le ba\u015flar", "dxDataGrid-filterRowOperationContains": "\u0130\xe7eren", "dxDataGrid-filterRowOperationNotContains": "\u0130\xe7ermeyen", "dxDataGrid-filterRowOperationEndsWith": "\u0130le biten", "dxDataGrid-filterRowOperationBetween": "Aras\u0131nda", "dxDataGrid-filterRowOperationBetweenStartText": "Ba\u015fla", "dxDataGrid-filterRowOperationBetweenEndText": "Biti\u015f", "dxDataGrid-applyFilterText": "Filtre uygula", "dxDataGrid-trueText": "evet", "dxDataGrid-falseText": "hay\u0131r", "dxDataGrid-sortingAscendingText": "Artan S\u0131ralama", "dxDataGrid-sortingDescendingText": "Azalan S\u0131ralama", "dxDataGrid-sortingClearText": "S\u0131ralamay\u0131 Temizle", "dxDataGrid-editingSaveAllChanges": "De\u011fi\u015fiklikleri Kaydet", "dxDataGrid-editingCancelAllChanges": "De\u011fi\u015fiklikleri iptal et", "dxDataGrid-editingAddRow": "Sat\u0131r ekle", "dxDataGrid-summaryMin": "Min: {0}", "dxDataGrid-summaryMinOtherColumn": "{1} min: {0}", "dxDataGrid-summaryMax": "Max: {0}", "dxDataGrid-summaryMaxOtherColumn": "{1} max: {0}", "dxDataGrid-summaryAvg": "Ort: {0}", "dxDataGrid-summaryAvgOtherColumn": "{1} ortalamas\u0131: {0}", "dxDataGrid-summarySum": "Top: {0}", "dxDataGrid-summarySumOtherColumn": "{1} toplam\u0131: {0}", "dxDataGrid-summaryCount": "Toplam: {0}", "dxDataGrid-columnFixingFix": "Sabitle", "dxDataGrid-columnFixingUnfix": "\xc7\xf6z", "dxDataGrid-columnFixingLeftPosition": "Sola", "dxDataGrid-columnFixingRightPosition": "Sa\u011fa", "dxDataGrid-exportTo": "D\u0131\u015fa aktar", "dxDataGrid-exportToExcel": "Excel dosyas\u0131na aktar", "dxDataGrid-exporting": "D\u0131\u015fa Aktar...", "dxDataGrid-excelFormat": "Excel dosyas\u0131", "dxDataGrid-selectedRows": "Se\xe7ili sat\u0131rlar", "dxDataGrid-exportSelectedRows": "Se\xe7ili sat\u0131rlar\u0131 aktar", "dxDataGrid-exportAll": "T\xfcm verileri d\u0131\u015fa aktar", "dxDataGrid-headerFilterEmptyValue": "(Blanks)", "dxDataGrid-headerFilterOK": "Tamam", "dxDataGrid-headerFilterCancel": "\u0130ptal", "dxDataGrid-ariaColumn": "S\xfctun", "dxDataGrid-ariaValue": "Veri", "dxDataGrid-ariaFilterCell": "Filtre h\xfccresi", "dxDataGrid-ariaCollapse": "Daralt", "dxDataGrid-ariaExpand": "Geni\u015flet", "dxDataGrid-ariaDataGrid": "Tablo", "dxDataGrid-ariaSearchInGrid": "Tabloda ara", "dxDataGrid-ariaSelectAll": "Hepsini se\xe7", "dxDataGrid-ariaSelectRow": "Sat\u0131r\u0131 se\xe7", "dxDataGrid-filterBuilderPopupTitle": "Filtre Olu\u015fturucu", "dxDataGrid-filterPanelCreateFilter": "Filtre Olu\u015ftur", "dxDataGrid-filterPanelClearFilter": "Temizle", "dxDataGrid-filterPanelFilterEnabledHint": "Filtreyi etkinle\u015ftir", "dxTreeList-ariaTreeList": "A\u011fa\xe7 listesi", "dxTreeList-editingAddRowToNode": "Ekle", "dxPager-infoText": "Sayfa {0} / {1} ({2} veri)", "dxPager-pagesCountText": "aras\u0131nda", "dxPager-pageSizesAllText": "T\xfcm\xfc", "dxPivotGrid-grandTotal": "Genel Toplam", "dxPivotGrid-total": "{0} Toplam", "dxPivotGrid-fieldChooserTitle": "Alan Se\xe7ici", "dxPivotGrid-showFieldChooser": "Alan Se\xe7iciyi G\xf6ster", "dxPivotGrid-expandAll": "T\xfcm\xfcn\xfc Geni\u015flet", "dxPivotGrid-collapseAll": "T\xfcm\xfcn\xfc Daralt", "dxPivotGrid-sortColumnBySummary": '"{0}" Bu S\xfctuna G\xf6re S\u0131rala', "dxPivotGrid-sortRowBySummary": '"{0}" Bu Sat\u0131ra G\xf6re S\u0131rala', "dxPivotGrid-removeAllSorting": "T\xfcm S\u0131ralamalar\u0131 Kald\u0131r", "dxPivotGrid-dataNotAvailable": "N/A", "dxPivotGrid-rowFields": "Sat\u0131r Alanlar\u0131", "dxPivotGrid-columnFields": "S\xfctun Alanlar\u0131", "dxPivotGrid-dataFields": "Veri Alanlar\u0131", "dxPivotGrid-filterFields": "Filtre Alanlar\u0131", "dxPivotGrid-allFields": "T\xfcm Alanlar", "dxPivotGrid-columnFieldArea": "S\xfctun Alanlar\u0131n\u0131 Buraya B\u0131rak", "dxPivotGrid-dataFieldArea": "Veri Alanlar\u0131n\u0131 Buraya B\u0131rak", "dxPivotGrid-rowFieldArea": "Sat\u0131r Alanlar\u0131n\u0131 Buraya B\u0131rak", "dxPivotGrid-filterFieldArea": "Filtre Alanlar\u0131n\u0131 Buraya B\u0131rak", "dxScheduler-editorLabelTitle": "Konu", "dxScheduler-editorLabelStartDate": "Ba\u015flang\u0131\xe7 Tarihi", "dxScheduler-editorLabelEndDate": "Biti\u015f Tarihi", "dxScheduler-editorLabelDescription": "A\xe7\u0131klama", "dxScheduler-editorLabelRecurrence": "Tekrar", "dxScheduler-openAppointment": "Randevu A\xe7", "dxScheduler-recurrenceNever": "Asla", "dxScheduler-recurrenceMinutely": "Minutely", "dxScheduler-recurrenceHourly": "Hourly", "dxScheduler-recurrenceDaily": "G\xfcnl\xfck", "dxScheduler-recurrenceWeekly": "Haftal\u0131k", "dxScheduler-recurrenceMonthly": "Ayl\u0131k", "dxScheduler-recurrenceYearly": "Y\u0131ll\u0131k", "dxScheduler-recurrenceRepeatEvery": "Her tekrarla", "dxScheduler-recurrenceRepeatOn": "Tekrarla", "dxScheduler-recurrenceEnd": "Tekrar\u0131 bitir", "dxScheduler-recurrenceAfter": "Sonra", "dxScheduler-recurrenceOn": "\u0130le", "dxScheduler-recurrenceRepeatMinutely": "minute(s)", "dxScheduler-recurrenceRepeatHourly": "hour(s)", "dxScheduler-recurrenceRepeatDaily": "g\xfcnler", "dxScheduler-recurrenceRepeatWeekly": "haftalar", "dxScheduler-recurrenceRepeatMonthly": "aylar", "dxScheduler-recurrenceRepeatYearly": "y\u0131llar", "dxScheduler-switcherDay": "G\xfcn", "dxScheduler-switcherWeek": "Hafta", "dxScheduler-switcherWorkWeek": "\xc7al\u0131\u015fma Haftas\u0131", "dxScheduler-switcherMonth": "Ay", "dxScheduler-switcherAgenda": "Ajanda", "dxScheduler-switcherTimelineDay": "Zaman \xc7izelgesi G\xfcn\xfc", "dxScheduler-switcherTimelineWeek": "Zaman \xc7izelgesi Haftas\u0131", "dxScheduler-switcherTimelineWorkWeek": "Zaman \xc7izelgesi \xc7al\u0131\u015fma Haftas\u0131", "dxScheduler-switcherTimelineMonth": "TZaman \xc7izelgesi \xc7al\u0131\u015fma Ay\u0131", "dxScheduler-recurrenceRepeatOnDate": "tarihinde", "dxScheduler-recurrenceRepeatCount": "olaylar", "dxScheduler-allDay": "T\xfcm g\xfcn", "dxScheduler-confirmRecurrenceEditMessage": "Yaln\u0131zca bu randevuyu veya t\xfcm diziyi d\xfczenlemek ister misiniz?", "dxScheduler-confirmRecurrenceDeleteMessage": "Yaln\u0131zca bu randevuyu veya t\xfcm diziyi silmek istiyor musunuz?", "dxScheduler-confirmRecurrenceEditSeries": "Serileri d\xfczenle", "dxScheduler-confirmRecurrenceDeleteSeries": "Serileri sil", "dxScheduler-confirmRecurrenceEditOccurrence": "Randevuyu d\xfczenle", "dxScheduler-confirmRecurrenceDeleteOccurrence": "Randevuyu sil", "dxScheduler-noTimezoneTitle": "Saat dilimi yok", "dxScheduler-moreAppointments": "{0} daha", "dxCalendar-todayButtonText": "Bug\xfcn", "dxCalendar-ariaWidgetName": "Takvim", "dxColorView-ariaRed": "K\u0131rm\u0131z\u0131", "dxColorView-ariaGreen": "Ye\u015fil", "dxColorView-ariaBlue": "Mavi", "dxColorView-ariaAlpha": "\u015eeffafl\u0131k", "dxColorView-ariaHex": "Renk kodu", "dxTagBox-selected": "{0} se\xe7ili", "dxTagBox-allSelected": "T\xfcm\xfc se\xe7ildi ({0})", "dxTagBox-moreSelected": "{0} daha", "vizExport-printingButtonText": "Yazd\u0131r", "vizExport-titleMenuText": "D\u0131\u015fa Aktar/Yazd\u0131r", "vizExport-exportButtonText": "{0} dosya", "dxFilterBuilder-and": "Ve", "dxFilterBuilder-or": "Veya", "dxFilterBuilder-notAnd": "De\u011fil Ve", "dxFilterBuilder-notOr": "De\u011fil Veya", "dxFilterBuilder-addCondition": "Ko\u015ful Ekle", "dxFilterBuilder-addGroup": "Grup Ekle", "dxFilterBuilder-enterValueText": "<de\u011fer gir>", "dxFilterBuilder-filterOperationEquals": "E\u015fit", "dxFilterBuilder-filterOperationNotEquals": "E\u015fit de\u011fil", "dxFilterBuilder-filterOperationLess": "Daha k\xfc\xe7\xfck", "dxFilterBuilder-filterOperationLessOrEquals": "Daha k\xfc\xe7\xfck veya e\u015fit", "dxFilterBuilder-filterOperationGreater": "Daha b\xfcy\xfck", "dxFilterBuilder-filterOperationGreaterOrEquals": "Daha b\xfcy\xfck veya e\u015fit", "dxFilterBuilder-filterOperationStartsWith": "\u0130le ba\u015flar", "dxFilterBuilder-filterOperationContains": "\u0130\xe7erir", "dxFilterBuilder-filterOperationNotContains": "\u0130\xe7ermez", "dxFilterBuilder-filterOperationEndsWith": "\u0130le biter", "dxFilterBuilder-filterOperationIsBlank": "Bo\u015f", "dxFilterBuilder-filterOperationIsNotBlank": "Bo\u015f de\u011fil", "dxFilterBuilder-filterOperationBetween": "Aras\u0131nda", "dxFilterBuilder-filterOperationAnyOf": "Herhangi biri", "dxFilterBuilder-filterOperationNoneOf": "Hi\xe7biri", "dxHtmlEditor-dialogColorCaption": "Yaz\u0131 Tipi Rengini De\u011fi\u015ftir", "dxHtmlEditor-dialogBackgroundCaption": "Arka Plan Rengini De\u011fi\u015ftir", "dxHtmlEditor-dialogLinkCaption": "Link Ekle", "dxHtmlEditor-dialogLinkUrlField": "URL", "dxHtmlEditor-dialogLinkTextField": "Metin", "dxHtmlEditor-dialogLinkTargetField": "Linki yeni pencerede a\xe7", "dxHtmlEditor-dialogImageCaption": "Resim Ekle", "dxHtmlEditor-dialogImageUrlField": "URL", "dxHtmlEditor-dialogImageAltField": "Alternatif metin", "dxHtmlEditor-dialogImageWidthField": "Geni\u015flik (px)", "dxHtmlEditor-dialogImageHeightField": "Y\xfckseklik (px)", "dxHtmlEditor-dialogInsertTableRowsField": "!TODO", "dxHtmlEditor-dialogInsertTableColumnsField": "!TODO", "dxHtmlEditor-dialogInsertTableCaption": "!TODO", "dxHtmlEditor-heading": "Ba\u015fl\u0131k", "dxHtmlEditor-normalText": "Normal metin", "dxHtmlEditor-background": "TODO", "dxHtmlEditor-bold": "TODO", "dxHtmlEditor-color": "TODO", "dxHtmlEditor-font": "TODO", "dxHtmlEditor-italic": "TODO", "dxHtmlEditor-link": "TODO", "dxHtmlEditor-image": "TODO", "dxHtmlEditor-size": "TODO", "dxHtmlEditor-strike": "TODO", "dxHtmlEditor-subscript": "TODO", "dxHtmlEditor-superscript": "TODO", "dxHtmlEditor-underline": "TODO", "dxHtmlEditor-blockquote": "TODO", "dxHtmlEditor-header": "TODO", "dxHtmlEditor-increaseIndent": "TODO", "dxHtmlEditor-decreaseIndent": "TODO", "dxHtmlEditor-orderedList": "TODO", "dxHtmlEditor-bulletList": "TODO", "dxHtmlEditor-alignLeft": "TODO", "dxHtmlEditor-alignCenter": "TODO", "dxHtmlEditor-alignRight": "TODO", "dxHtmlEditor-alignJustify": "TODO", "dxHtmlEditor-codeBlock": "TODO", "dxHtmlEditor-variable": "TODO", "dxHtmlEditor-undo": "TODO", "dxHtmlEditor-redo": "TODO", "dxHtmlEditor-clear": "TODO", "dxHtmlEditor-insertTable": "TODO", "dxHtmlEditor-insertHeaderRow": "TODO", "dxHtmlEditor-insertRowAbove": "TODO", "dxHtmlEditor-insertRowBelow": "TODO", "dxHtmlEditor-insertColumnLeft": "TODO", "dxHtmlEditor-insertColumnRight": "TODO", "dxHtmlEditor-deleteColumn": "TODO", "dxHtmlEditor-deleteRow": "TODO", "dxHtmlEditor-deleteTable": "TODO", "dxHtmlEditor-cellProperties": "TODO", "dxHtmlEditor-tableProperties": "TODO", "dxHtmlEditor-insert": "TODO", "dxHtmlEditor-delete": "TODO", "dxHtmlEditor-border": "TODO", "dxHtmlEditor-style": "TODO", "dxHtmlEditor-width": "TODO", "dxHtmlEditor-height": "TODO", "dxHtmlEditor-borderColor": "TODO", "dxHtmlEditor-tableBackground": "TODO", "dxHtmlEditor-dimensions": "TODO", "dxHtmlEditor-alignment": "TODO", "dxHtmlEditor-horizontal": "TODO", "dxHtmlEditor-vertical": "TODO", "dxHtmlEditor-paddingVertical": "TODO", "dxHtmlEditor-paddingHorizontal": "TODO", "dxHtmlEditor-pixels": "TODO", "dxHtmlEditor-list": "TODO", "dxHtmlEditor-ordered": "TODO", "dxHtmlEditor-bullet": "TODO", "dxHtmlEditor-align": "TODO", "dxHtmlEditor-center": "TODO", "dxHtmlEditor-left": "TODO", "dxHtmlEditor-right": "TODO", "dxHtmlEditor-indent": "TODO", "dxHtmlEditor-justify": "TODO", "dxFileManager-errorNoAccess": "Eri\u015fim reddedildi. \u0130\u015flem tamamlanam\u0131yor.", "dxFileManager-errorDirectoryExistsFormat": "Klas\xf6r '{0}' zaten var.", "dxFileManager-errorFileExistsFormat": "Dosya '{0}' zaten var.", "dxFileManager-errorFileNotFoundFormat": "Dosya '{0}' bulunamad\u0131", "dxFileManager-errorDefault": "Belirtilmemi\u015f hata.", "dxFileManager-newDirectoryName": "TODO", "dxFileManager-rootDirectoryName": "TODO", "dxFileManager-errorDirectoryNotFoundFormat": "TODO", "dxFileManager-errorWrongFileExtension": "TODO", "dxFileManager-errorMaxFileSizeExceeded": "TODO", "dxFileManager-errorInvalidSymbols": "TODO", "dxFileManager-errorDirectoryOpenFailed": "TODO", "dxDiagram-categoryGeneral": "TODO", "dxDiagram-categoryFlowchart": "TODO", "dxDiagram-categoryOrgChart": "TODO", "dxDiagram-categoryContainers": "TODO", "dxDiagram-categoryCustom": "TODO", "dxDiagram-commandExportToSvg": "TODO", "dxDiagram-commandExportToPng": "TODO", "dxDiagram-commandExportToJpg": "TODO", "dxDiagram-commandUndo": "TODO", "dxDiagram-commandRedo": "TODO", "dxDiagram-commandFontName": "TODO", "dxDiagram-commandFontSize": "TODO", "dxDiagram-commandBold": "TODO", "dxDiagram-commandItalic": "TODO", "dxDiagram-commandUnderline": "TODO", "dxDiagram-commandTextColor": "TODO", "dxDiagram-commandLineColor": "TODO", "dxDiagram-commandFillColor": "TODO", "dxDiagram-commandAlignLeft": "TODO", "dxDiagram-commandAlignCenter": "TODO", "dxDiagram-commandAlignRight": "TODO", "dxDiagram-commandConnectorLineType": "TODO", "dxDiagram-commandConnectorLineStraight": "TODO", "dxDiagram-commandConnectorLineOrthogonal": "TODO", "dxDiagram-commandConnectorLineStart": "TODO", "dxDiagram-commandConnectorLineEnd": "TODO", "dxDiagram-commandConnectorLineNone": "TODO", "dxDiagram-commandConnectorLineArrow": "TODO", "dxDiagram-commandFullscreen": "TODO", "dxDiagram-commandUnits": "TODO", "dxDiagram-commandPageSize": "TODO", "dxDiagram-commandPageOrientation": "TODO", "dxDiagram-commandPageOrientationLandscape": "TODO", "dxDiagram-commandPageOrientationPortrait": "TODO", "dxDiagram-commandPageColor": "TODO", "dxDiagram-commandShowGrid": "TODO", "dxDiagram-commandSnapToGrid": "TODO", "dxDiagram-commandGridSize": "TODO", "dxDiagram-commandZoomLevel": "TODO", "dxDiagram-commandAutoZoom": "TODO", "dxDiagram-commandFitToContent": "TODO", "dxDiagram-commandFitToWidth": "TODO", "dxDiagram-commandAutoZoomByContent": "TODO", "dxDiagram-commandAutoZoomByWidth": "TODO", "dxDiagram-commandSimpleView": "TODO", "dxDiagram-commandCut": "TODO", "dxDiagram-commandCopy": "TODO", "dxDiagram-commandPaste": "TODO", "dxDiagram-commandSelectAll": "TODO", "dxDiagram-commandDelete": "TODO", "dxDiagram-commandBringToFront": "TODO", "dxDiagram-commandSendToBack": "TODO", "dxDiagram-commandLock": "TODO", "dxDiagram-commandUnlock": "TODO", "dxDiagram-commandInsertShapeImage": "TODO", "dxDiagram-commandEditShapeImage": "TODO", "dxDiagram-commandDeleteShapeImage": "TODO", "dxDiagram-commandLayoutLeftToRight": "TODO", "dxDiagram-commandLayoutRightToLeft": "TODO", "dxDiagram-commandLayoutTopToBottom": "TODO", "dxDiagram-commandLayoutBottomToTop": "TODO", "dxDiagram-unitIn": "TODO", "dxDiagram-unitCm": "TODO", "dxDiagram-unitPx": "TODO", "dxDiagram-dialogButtonOK": "TODO", "dxDiagram-dialogButtonCancel": "TODO", "dxDiagram-dialogInsertShapeImageTitle": "TODO", "dxDiagram-dialogEditShapeImageTitle": "TODO", "dxDiagram-dialogEditShapeImageSelectButton": "TODO", "dxDiagram-dialogEditShapeImageLabelText": "TODO", "dxDiagram-uiExport": "TODO", "dxDiagram-uiProperties": "TODO", "dxDiagram-uiSettings": "TODO", "dxDiagram-uiShowToolbox": "TODO", "dxDiagram-uiSearch": "TODO", "dxDiagram-uiStyle": "TODO", "dxDiagram-uiLayout": "TODO", "dxDiagram-uiLayoutTree": "TODO", "dxDiagram-uiLayoutLayered": "TODO", "dxDiagram-uiDiagram": "TODO", "dxDiagram-uiText": "TODO", "dxDiagram-uiObject": "TODO", "dxDiagram-uiConnector": "TODO", "dxDiagram-uiPage": "TODO", "dxDiagram-shapeText": "TODO", "dxDiagram-shapeRectangle": "TODO", "dxDiagram-shapeEllipse": "TODO", "dxDiagram-shapeCross": "TODO", "dxDiagram-shapeTriangle": "TODO", "dxDiagram-shapeDiamond": "TODO", "dxDiagram-shapeHeart": "TODO", "dxDiagram-shapePentagon": "TODO", "dxDiagram-shapeHexagon": "TODO", "dxDiagram-shapeOctagon": "TODO", "dxDiagram-shapeStar": "TODO", "dxDiagram-shapeArrowLeft": "TODO", "dxDiagram-shapeArrowUp": "TODO", "dxDiagram-shapeArrowRight": "TODO", "dxDiagram-shapeArrowDown": "TODO", "dxDiagram-shapeArrowUpDown": "TODO", "dxDiagram-shapeArrowLeftRight": "TODO", "dxDiagram-shapeProcess": "TODO", "dxDiagram-shapeDecision": "TODO", "dxDiagram-shapeTerminator": "TODO", "dxDiagram-shapePredefinedProcess": "TODO", "dxDiagram-shapeDocument": "TODO", "dxDiagram-shapeMultipleDocuments": "TODO", "dxDiagram-shapeManualInput": "TODO", "dxDiagram-shapePreparation": "TODO", "dxDiagram-shapeData": "TODO", "dxDiagram-shapeDatabase": "TODO", "dxDiagram-shapeHardDisk": "TODO", "dxDiagram-shapeInternalStorage": "TODO", "dxDiagram-shapePaperTape": "TODO", "dxDiagram-shapeManualOperation": "TODO", "dxDiagram-shapeDelay": "TODO", "dxDiagram-shapeStoredData": "TODO", "dxDiagram-shapeDisplay": "TODO", "dxDiagram-shapeMerge": "TODO", "dxDiagram-shapeConnector": "TODO", "dxDiagram-shapeOr": "TODO", "dxDiagram-shapeSummingJunction": "TODO", "dxDiagram-shapeContainerDefaultText": "TODO", "dxDiagram-shapeVerticalContainer": "TODO", "dxDiagram-shapeHorizontalContainer": "TODO", "dxDiagram-shapeCardDefaultText": "TODO", "dxDiagram-shapeCardWithImageOnLeft": "TODO", "dxDiagram-shapeCardWithImageOnTop": "TODO", "dxDiagram-shapeCardWithImageOnRight": "TODO", "dxGantt-dialogTitle": "TODO", "dxGantt-dialogStartTitle": "TODO", "dxGantt-dialogEndTitle": "TODO", "dxGantt-dialogProgressTitle": "TODO", "dxGantt-dialogResourcesTitle": "TODO", "dxGantt-dialogResourceManagerTitle": "TODO", "dxGantt-dialogTaskDetailsTitle": "TODO", "dxGantt-dialogEditResourceListHint": "TODO", "dxGantt-dialogEditNoResources": "TODO", "dxGantt-dialogButtonAdd": "TODO", "dxGantt-contextMenuNewTask": "TODO", "dxGantt-contextMenuNewSubtask": "TODO", "dxGantt-contextMenuDeleteTask": "TODO", "dxGantt-contextMenuDeleteDependency": "TODO", "dxGantt-dialogTaskDeleteConfirmation": "TODO", "dxGantt-dialogDependencyDeleteConfirmation": "TODO", "dxGantt-dialogResourcesDeleteConfirmation": "TODO", "dxGantt-dialogConstraintCriticalViolationMessage": "TODO", "dxGantt-dialogConstraintViolationMessage": "TODO", "dxGantt-dialogCancelOperationMessage": "TODO", "dxGantt-dialogDeleteDependencyMessage": "TODO", "dxGantt-dialogMoveTaskAndKeepDependencyMessage": "TODO", "dxGantt-undo": "TODO", "dxGantt-redo": "TODO", "dxGantt-expandAll": "TODO", "dxGantt-collapseAll": "TODO", "dxGantt-addNewTask": "TODO", "dxGantt-deleteSelectedTask": "TODO", "dxGantt-zoomIn": "TODO", "dxGantt-zoomOut": "TODO", "dxGantt-fullScreen": "TODO", "dxGantt-quarter": "TODO", "dxGantt-sortingAscendingText": "Artan S\u0131ralama", "dxGantt-sortingDescendingText": "Azalan S\u0131ralama", "dxGantt-sortingClearText": "S\u0131ralamay\u0131 Temizle", "dxGantt-showResources": "TODO", "dxGantt-showDependencies": "TODO", "dxGantt-dialogStartDateValidation": "TODO", "dxGantt-dialogEndDateValidation": "TODO" } }) }));
/**! Qoopido.nucleus 3.2.8 | http://nucleus.qoopido.com | (c) 2020 Dirk Lueth */ !function(){"use strict";provide(["/demand/pledge","../../css/property"],(function(e,r){var t=e.defer(),n=r("transform");return n?t.resolve(n):t.reject(),t.pledge}))}(); //# sourceMappingURL=transform.js.map
/*!! * @atlassian/aui - Atlassian User Interface Framework * @version v7.7.1 * @link https://docs.atlassian.com/aui/latest/ * @license SEE LICENSE IN LICENSE.md * @author Atlassian Pty Ltd. */ // src/js-vendor/jquery/jquery-ui/jquery.ui.datepicker.js (typeof window === 'undefined' ? global : window).__e655bb43386f55b60b05dd9efffb834d = (function () { var module = { exports: {} }; var exports = module.exports; /*! * jQuery UI Datepicker 1.8.24 * * Copyright 2012, AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * http://docs.jquery.com/UI/Datepicker * * Depends: * jquery.ui.core.js */ (function( $, undefined ) { $.extend($.ui, { datepicker: { version: "1.8.24" } }); var PROP_NAME = 'datepicker'; var dpuuid = new Date().getTime(); var instActive; /* Date picker manager. Use the singleton instance of this class, $.datepicker, to interact with the date picker. Settings for (groups of) date pickers are maintained in an instance object, allowing multiple different settings on the same page. */ function Datepicker() { this.debug = false; // Change this to true to start debugging this._curInst = null; // The current instance in use this._keyEvent = false; // If the last event was a key event this._disabledInputs = []; // List of date picker inputs that have been disabled this._datepickerShowing = false; // True if the popup picker is showing , false if not this._inDialog = false; // True if showing within a "dialog", false if not this._mainDivId = 'ui-datepicker-div'; // The ID of the main datepicker division this._inlineClass = 'ui-datepicker-inline'; // The name of the inline marker class this._appendClass = 'ui-datepicker-append'; // The name of the append marker class this._triggerClass = 'ui-datepicker-trigger'; // The name of the trigger marker class this._dialogClass = 'ui-datepicker-dialog'; // The name of the dialog marker class this._disableClass = 'ui-datepicker-disabled'; // The name of the disabled covering marker class this._unselectableClass = 'ui-datepicker-unselectable'; // The name of the unselectable cell marker class this._currentClass = 'ui-datepicker-current-day'; // The name of the current day marker class this._dayOverClass = 'ui-datepicker-days-cell-over'; // The name of the day hover marker class this.regional = []; // Available regional settings, indexed by language code this.regional[''] = { // Default regional settings closeText: 'Done', // Display text for close link prevText: 'Prev', // Display text for previous month link nextText: 'Next', // Display text for next month link currentText: 'Today', // Display text for current month link monthNames: ['January','February','March','April','May','June', 'July','August','September','October','November','December'], // Names of months for drop-down and formatting monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], // For formatting dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], // For formatting dayNamesShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], // For formatting dayNamesMin: ['Su','Mo','Tu','We','Th','Fr','Sa'], // Column headings for days starting at Sunday weekHeader: 'Wk', // Column header for week of the year dateFormat: 'mm/dd/yy', // See format options on parseDate firstDay: 0, // The first day of the week, Sun = 0, Mon = 1, ... isRTL: false, // True if right-to-left language, false if left-to-right showMonthAfterYear: false, // True if the year select precedes month, false for month then year yearSuffix: '' // Additional text to append to the year in the month headers }; this._defaults = { // Global defaults for all the date picker instances showOn: 'focus', // 'focus' for popup on focus, // 'button' for trigger button, or 'both' for either showAnim: 'fadeIn', // Name of jQuery animation for popup showOptions: {}, // Options for enhanced animations defaultDate: null, // Used when field is blank: actual date, // +/-number for offset from today, null for today appendText: '', // Display text following the input box, e.g. showing the format buttonText: '...', // Text for trigger button buttonImage: '', // URL for trigger button image buttonImageOnly: false, // True if the image appears alone, false if it appears on a button hideIfNoPrevNext: false, // True to hide next/previous month links // if not applicable, false to just disable them navigationAsDateFormat: false, // True if date formatting applied to prev/today/next links gotoCurrent: false, // True if today link goes back to current selection instead changeMonth: false, // True if month can be selected directly, false if only prev/next changeYear: false, // True if year can be selected directly, false if only prev/next yearRange: 'c-10:c+10', // Range of years to display in drop-down, // either relative to today's year (-nn:+nn), relative to currently displayed year // (c-nn:c+nn), absolute (nnnn:nnnn), or a combination of the above (nnnn:-n) showOtherMonths: false, // True to show dates in other months, false to leave blank selectOtherMonths: false, // True to allow selection of dates in other months, false for unselectable showWeek: false, // True to show week of the year, false to not show it calculateWeek: this.iso8601Week, // How to calculate the week of the year, // takes a Date and returns the number of the week for it shortYearCutoff: '+10', // Short year values < this are in the current century, // > this are in the previous century, // string value starting with '+' for current year + value minDate: null, // The earliest selectable date, or null for no limit maxDate: null, // The latest selectable date, or null for no limit duration: 'fast', // Duration of display/closure beforeShowDay: null, // Function that takes a date and returns an array with // [0] = true if selectable, false if not, [1] = custom CSS class name(s) or '', // [2] = cell title (optional), e.g. $.datepicker.noWeekends beforeShow: null, // Function that takes an input field and // returns a set of custom settings for the date picker onSelect: null, // Define a callback function when a date is selected onChangeMonthYear: null, // Define a callback function when the month or year is changed onClose: null, // Define a callback function when the datepicker is closed numberOfMonths: 1, // Number of months to show at a time showCurrentAtPos: 0, // The position in multipe months at which to show the current month (starting at 0) stepMonths: 1, // Number of months to step back/forward stepBigMonths: 12, // Number of months to step back/forward for the big links altField: '', // Selector for an alternate field to store selected dates into altFormat: '', // The date format to use for the alternate field constrainInput: true, // The input is constrained by the current date format showButtonPanel: false, // True to show button panel, false to not show it autoSize: false, // True to size the input for the date format, false to leave as is disabled: false // The initial disabled state }; $.extend(this._defaults, this.regional['']); this.dpDiv = bindHover($('<div id="' + this._mainDivId + '" class="ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all"></div>')); } $.extend(Datepicker.prototype, { /* Class name added to elements to indicate already configured with a date picker. */ markerClassName: 'hasDatepicker', //Keep track of the maximum number of rows displayed (see #7043) maxRows: 4, /* Debug logging (if enabled). */ log: function () { if (this.debug) console.log.apply('', arguments); }, // TODO rename to "widget" when switching to widget factory _widgetDatepicker: function() { return this.dpDiv; }, /* Override the default settings for all instances of the date picker. @param settings object - the new settings to use as defaults (anonymous object) @return the manager object */ setDefaults: function(settings) { extendRemove(this._defaults, settings || {}); return this; }, /* Attach the date picker to a jQuery selection. @param target element - the target input field or division or span @param settings object - the new settings to use for this date picker instance (anonymous) */ _attachDatepicker: function(target, settings) { // check for settings on the control itself - in namespace 'date:' var inlineSettings = null; for (var attrName in this._defaults) { var attrValue = target.getAttribute('date:' + attrName); if (attrValue) { inlineSettings = inlineSettings || {}; try { inlineSettings[attrName] = eval(attrValue); } catch (err) { inlineSettings[attrName] = attrValue; } } } var nodeName = target.nodeName.toLowerCase(); var inline = (nodeName == 'div' || nodeName == 'span'); if (!target.id) { this.uuid += 1; target.id = 'dp' + this.uuid; } var inst = this._newInst($(target), inline); inst.settings = $.extend({}, settings || {}, inlineSettings || {}); if (nodeName == 'input') { this._connectDatepicker(target, inst); } else if (inline) { this._inlineDatepicker(target, inst); } }, /* Create a new instance object. */ _newInst: function(target, inline) { var id = target[0].id.replace(/([^A-Za-z0-9_-])/g, '\\\\$1'); // escape jQuery meta chars return {id: id, input: target, // associated target selectedDay: 0, selectedMonth: 0, selectedYear: 0, // current selection drawMonth: 0, drawYear: 0, // month being drawn inline: inline, // is datepicker inline or not dpDiv: (!inline ? this.dpDiv : // presentation div bindHover($('<div class="' + this._inlineClass + ' ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all"></div>')))}; }, /* Attach the date picker to an input field. */ _connectDatepicker: function(target, inst) { var input = $(target); inst.append = $([]); inst.trigger = $([]); if (input.hasClass(this.markerClassName)) return; this._attachments(input, inst); input.addClass(this.markerClassName).keydown(this._doKeyDown). keypress(this._doKeyPress).keyup(this._doKeyUp). bind("setData.datepicker", function(event, key, value) { inst.settings[key] = value; }).bind("getData.datepicker", function(event, key) { return this._get(inst, key); }); this._autoSize(inst); $.data(target, PROP_NAME, inst); //If disabled option is true, disable the datepicker once it has been attached to the input (see ticket #5665) if( inst.settings.disabled ) { this._disableDatepicker( target ); } }, /* Make attachments based on settings. */ _attachments: function(input, inst) { var appendText = this._get(inst, 'appendText'); var isRTL = this._get(inst, 'isRTL'); if (inst.append) inst.append.remove(); if (appendText) { inst.append = $('<span class="' + this._appendClass + '">' + appendText + '</span>'); input[isRTL ? 'before' : 'after'](inst.append); } input.unbind('focus', this._showDatepicker); if (inst.trigger) inst.trigger.remove(); var showOn = this._get(inst, 'showOn'); if (showOn == 'focus' || showOn == 'both') // pop-up date picker when in the marked field input.focus(this._showDatepicker); if (showOn == 'button' || showOn == 'both') { // pop-up date picker when button clicked var buttonText = this._get(inst, 'buttonText'); var buttonImage = this._get(inst, 'buttonImage'); inst.trigger = $(this._get(inst, 'buttonImageOnly') ? $('<img/>').addClass(this._triggerClass). attr({ src: buttonImage, alt: buttonText, title: buttonText }) : $('<button type="button"></button>').addClass(this._triggerClass). html(buttonImage == '' ? buttonText : $('<img/>').attr( { src:buttonImage, alt:buttonText, title:buttonText }))); input[isRTL ? 'before' : 'after'](inst.trigger); inst.trigger.click(function() { if ($.datepicker._datepickerShowing && $.datepicker._lastInput == input[0]) $.datepicker._hideDatepicker(); else if ($.datepicker._datepickerShowing && $.datepicker._lastInput != input[0]) { $.datepicker._hideDatepicker(); $.datepicker._showDatepicker(input[0]); } else $.datepicker._showDatepicker(input[0]); return false; }); } }, /* Apply the maximum length for the date format. */ _autoSize: function(inst) { if (this._get(inst, 'autoSize') && !inst.inline) { var date = new Date(2009, 12 - 1, 20); // Ensure double digits var dateFormat = this._get(inst, 'dateFormat'); if (dateFormat.match(/[DM]/)) { var findMax = function(names) { var max = 0; var maxI = 0; for (var i = 0; i < names.length; i++) { if (names[i].length > max) { max = names[i].length; maxI = i; } } return maxI; }; date.setMonth(findMax(this._get(inst, (dateFormat.match(/MM/) ? 'monthNames' : 'monthNamesShort')))); date.setDate(findMax(this._get(inst, (dateFormat.match(/DD/) ? 'dayNames' : 'dayNamesShort'))) + 20 - date.getDay()); } inst.input.attr('size', this._formatDate(inst, date).length); } }, /* Attach an inline date picker to a div. */ _inlineDatepicker: function(target, inst) { var divSpan = $(target); if (divSpan.hasClass(this.markerClassName)) return; divSpan.addClass(this.markerClassName).append(inst.dpDiv). bind("setData.datepicker", function(event, key, value){ inst.settings[key] = value; }).bind("getData.datepicker", function(event, key){ return this._get(inst, key); }); $.data(target, PROP_NAME, inst); this._setDate(inst, this._getDefaultDate(inst), true); this._updateDatepicker(inst); this._updateAlternate(inst); //If disabled option is true, disable the datepicker before showing it (see ticket #5665) if( inst.settings.disabled ) { this._disableDatepicker( target ); } // Set display:block in place of inst.dpDiv.show() which won't work on disconnected elements // http://bugs.jqueryui.com/ticket/7552 - A Datepicker created on a detached div has zero height inst.dpDiv.css( "display", "block" ); }, /* Pop-up the date picker in a "dialog" box. @param input element - ignored @param date string or Date - the initial date to display @param onSelect function - the function to call when a date is selected @param settings object - update the dialog date picker instance's settings (anonymous object) @param pos int[2] - coordinates for the dialog's position within the screen or event - with x/y coordinates or leave empty for default (screen centre) @return the manager object */ _dialogDatepicker: function(input, date, onSelect, settings, pos) { var inst = this._dialogInst; // internal instance if (!inst) { this.uuid += 1; var id = 'dp' + this.uuid; this._dialogInput = $('<input type="text" id="' + id + '" style="position: absolute; top: -100px; width: 0px;"/>'); this._dialogInput.keydown(this._doKeyDown); $('body').append(this._dialogInput); inst = this._dialogInst = this._newInst(this._dialogInput, false); inst.settings = {}; $.data(this._dialogInput[0], PROP_NAME, inst); } extendRemove(inst.settings, settings || {}); date = (date && date.constructor == Date ? this._formatDate(inst, date) : date); this._dialogInput.val(date); this._pos = (pos ? (pos.length ? pos : [pos.pageX, pos.pageY]) : null); if (!this._pos) { var browserWidth = document.documentElement.clientWidth; var browserHeight = document.documentElement.clientHeight; var scrollX = document.documentElement.scrollLeft || document.body.scrollLeft; var scrollY = document.documentElement.scrollTop || document.body.scrollTop; this._pos = // should use actual width/height below [(browserWidth / 2) - 100 + scrollX, (browserHeight / 2) - 150 + scrollY]; } // move input on screen for focus, but hidden behind dialog this._dialogInput.css('left', (this._pos[0] + 20) + 'px').css('top', this._pos[1] + 'px'); inst.settings.onSelect = onSelect; this._inDialog = true; this.dpDiv.addClass(this._dialogClass); this._showDatepicker(this._dialogInput[0]); if ($.blockUI) $.blockUI(this.dpDiv); $.data(this._dialogInput[0], PROP_NAME, inst); return this; }, /* Detach a datepicker from its control. @param target element - the target input field or division or span */ _destroyDatepicker: function(target) { var $target = $(target); var inst = $.data(target, PROP_NAME); if (!$target.hasClass(this.markerClassName)) { return; } var nodeName = target.nodeName.toLowerCase(); $.removeData(target, PROP_NAME); if (nodeName == 'input') { inst.append.remove(); inst.trigger.remove(); $target.removeClass(this.markerClassName). unbind('focus', this._showDatepicker). unbind('keydown', this._doKeyDown). unbind('keypress', this._doKeyPress). unbind('keyup', this._doKeyUp); } else if (nodeName == 'div' || nodeName == 'span') $target.removeClass(this.markerClassName).empty(); }, /* Enable the date picker to a jQuery selection. @param target element - the target input field or division or span */ _enableDatepicker: function(target) { var $target = $(target); var inst = $.data(target, PROP_NAME); if (!$target.hasClass(this.markerClassName)) { return; } var nodeName = target.nodeName.toLowerCase(); if (nodeName == 'input') { target.disabled = false; inst.trigger.filter('button'). each(function() { this.disabled = false; }).end(). filter('img').css({opacity: '1.0', cursor: ''}); } else if (nodeName == 'div' || nodeName == 'span') { var inline = $target.children('.' + this._inlineClass); inline.children().removeClass('ui-state-disabled'); inline.find("select.ui-datepicker-month, select.ui-datepicker-year"). removeAttr("disabled"); } this._disabledInputs = $.map(this._disabledInputs, function(value) { return (value == target ? null : value); }); // delete entry }, /* Disable the date picker to a jQuery selection. @param target element - the target input field or division or span */ _disableDatepicker: function(target) { var $target = $(target); var inst = $.data(target, PROP_NAME); if (!$target.hasClass(this.markerClassName)) { return; } var nodeName = target.nodeName.toLowerCase(); if (nodeName == 'input') { target.disabled = true; inst.trigger.filter('button'). each(function() { this.disabled = true; }).end(). filter('img').css({opacity: '0.5', cursor: 'default'}); } else if (nodeName == 'div' || nodeName == 'span') { var inline = $target.children('.' + this._inlineClass); inline.children().addClass('ui-state-disabled'); inline.find("select.ui-datepicker-month, select.ui-datepicker-year"). attr("disabled", "disabled"); } this._disabledInputs = $.map(this._disabledInputs, function(value) { return (value == target ? null : value); }); // delete entry this._disabledInputs[this._disabledInputs.length] = target; }, /* Is the first field in a jQuery collection disabled as a datepicker? @param target element - the target input field or division or span @return boolean - true if disabled, false if enabled */ _isDisabledDatepicker: function(target) { if (!target) { return false; } for (var i = 0; i < this._disabledInputs.length; i++) { if (this._disabledInputs[i] == target) return true; } return false; }, /* Retrieve the instance data for the target control. @param target element - the target input field or division or span @return object - the associated instance data @throws error if a jQuery problem getting data */ _getInst: function(target) { try { return $.data(target, PROP_NAME); } catch (err) { throw 'Missing instance data for this datepicker'; } }, /* Update or retrieve the settings for a date picker attached to an input field or division. @param target element - the target input field or division or span @param name object - the new settings to update or string - the name of the setting to change or retrieve, when retrieving also 'all' for all instance settings or 'defaults' for all global defaults @param value any - the new value for the setting (omit if above is an object or to retrieve a value) */ _optionDatepicker: function(target, name, value) { var inst = this._getInst(target); if (arguments.length == 2 && typeof name == 'string') { return (name == 'defaults' ? $.extend({}, $.datepicker._defaults) : (inst ? (name == 'all' ? $.extend({}, inst.settings) : this._get(inst, name)) : null)); } var settings = name || {}; if (typeof name == 'string') { settings = {}; settings[name] = value; } if (inst) { if (this._curInst == inst) { this._hideDatepicker(); } var date = this._getDateDatepicker(target, true); var minDate = this._getMinMaxDate(inst, 'min'); var maxDate = this._getMinMaxDate(inst, 'max'); extendRemove(inst.settings, settings); // reformat the old minDate/maxDate values if dateFormat changes and a new minDate/maxDate isn't provided if (minDate !== null && settings['dateFormat'] !== undefined && settings['minDate'] === undefined) inst.settings.minDate = this._formatDate(inst, minDate); if (maxDate !== null && settings['dateFormat'] !== undefined && settings['maxDate'] === undefined) inst.settings.maxDate = this._formatDate(inst, maxDate); this._attachments($(target), inst); this._autoSize(inst); this._setDate(inst, date); this._updateAlternate(inst); this._updateDatepicker(inst); } }, // change method deprecated _changeDatepicker: function(target, name, value) { this._optionDatepicker(target, name, value); }, /* Redraw the date picker attached to an input field or division. @param target element - the target input field or division or span */ _refreshDatepicker: function(target) { var inst = this._getInst(target); if (inst) { this._updateDatepicker(inst); } }, /* Set the dates for a jQuery selection. @param target element - the target input field or division or span @param date Date - the new date */ _setDateDatepicker: function(target, date) { var inst = this._getInst(target); if (inst) { this._setDate(inst, date); this._updateDatepicker(inst); this._updateAlternate(inst); } }, /* Get the date(s) for the first entry in a jQuery selection. @param target element - the target input field or division or span @param noDefault boolean - true if no default date is to be used @return Date - the current date */ _getDateDatepicker: function(target, noDefault) { var inst = this._getInst(target); if (inst && !inst.inline) this._setDateFromField(inst, noDefault); return (inst ? this._getDate(inst) : null); }, /* Handle keystrokes. */ _doKeyDown: function(event) { var inst = $.datepicker._getInst(event.target); var handled = true; var isRTL = inst.dpDiv.is('.ui-datepicker-rtl'); inst._keyEvent = true; if ($.datepicker._datepickerShowing) switch (event.keyCode) { case 9: $.datepicker._hideDatepicker(); handled = false; break; // hide on tab out case 13: var sel = $('td.' + $.datepicker._dayOverClass + ':not(.' + $.datepicker._currentClass + ')', inst.dpDiv); if (sel[0]) $.datepicker._selectDay(event.target, inst.selectedMonth, inst.selectedYear, sel[0]); var onSelect = $.datepicker._get(inst, 'onSelect'); if (onSelect) { var dateStr = $.datepicker._formatDate(inst); // trigger custom callback onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]); } else $.datepicker._hideDatepicker(); return false; // don't submit the form break; // select the value on enter case 27: $.datepicker._hideDatepicker(); break; // hide on escape case 33: $.datepicker._adjustDate(event.target, (event.ctrlKey ? -$.datepicker._get(inst, 'stepBigMonths') : -$.datepicker._get(inst, 'stepMonths')), 'M'); break; // previous month/year on page up/+ ctrl case 34: $.datepicker._adjustDate(event.target, (event.ctrlKey ? +$.datepicker._get(inst, 'stepBigMonths') : +$.datepicker._get(inst, 'stepMonths')), 'M'); break; // next month/year on page down/+ ctrl case 35: if (event.ctrlKey || event.metaKey) $.datepicker._clearDate(event.target); handled = event.ctrlKey || event.metaKey; break; // clear on ctrl or command +end case 36: if (event.ctrlKey || event.metaKey) $.datepicker._gotoToday(event.target); handled = event.ctrlKey || event.metaKey; break; // current on ctrl or command +home case 37: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, (isRTL ? +1 : -1), 'D'); handled = event.ctrlKey || event.metaKey; // -1 day on ctrl or command +left if (event.originalEvent.altKey) $.datepicker._adjustDate(event.target, (event.ctrlKey ? -$.datepicker._get(inst, 'stepBigMonths') : -$.datepicker._get(inst, 'stepMonths')), 'M'); // next month/year on alt +left on Mac break; case 38: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, -7, 'D'); handled = event.ctrlKey || event.metaKey; break; // -1 week on ctrl or command +up case 39: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, (isRTL ? -1 : +1), 'D'); handled = event.ctrlKey || event.metaKey; // +1 day on ctrl or command +right if (event.originalEvent.altKey) $.datepicker._adjustDate(event.target, (event.ctrlKey ? +$.datepicker._get(inst, 'stepBigMonths') : +$.datepicker._get(inst, 'stepMonths')), 'M'); // next month/year on alt +right break; case 40: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, +7, 'D'); handled = event.ctrlKey || event.metaKey; break; // +1 week on ctrl or command +down default: handled = false; } else if (event.keyCode == 36 && event.ctrlKey) // display the date picker on ctrl+home $.datepicker._showDatepicker(this); else { handled = false; } if (handled) { event.preventDefault(); event.stopPropagation(); } }, /* Filter entered characters - based on date format. */ _doKeyPress: function(event) { var inst = $.datepicker._getInst(event.target); if ($.datepicker._get(inst, 'constrainInput')) { var chars = $.datepicker._possibleChars($.datepicker._get(inst, 'dateFormat')); var chr = String.fromCharCode(event.charCode == undefined ? event.keyCode : event.charCode); return event.ctrlKey || event.metaKey || (chr < ' ' || !chars || chars.indexOf(chr) > -1); } }, /* Synchronise manual entry and field/alternate field. */ _doKeyUp: function(event) { var inst = $.datepicker._getInst(event.target); if (inst.input.val() != inst.lastVal) { try { var date = $.datepicker.parseDate($.datepicker._get(inst, 'dateFormat'), (inst.input ? inst.input.val() : null), $.datepicker._getFormatConfig(inst)); if (date) { // only if valid $.datepicker._setDateFromField(inst); $.datepicker._updateAlternate(inst); $.datepicker._updateDatepicker(inst); } } catch (err) { $.datepicker.log(err); } } return true; }, /* Pop-up the date picker for a given input field. If false returned from beforeShow event handler do not show. @param input element - the input field attached to the date picker or event - if triggered by focus */ _showDatepicker: function(input) { input = input.target || input; if (input.nodeName.toLowerCase() != 'input') // find from button/image trigger input = $('input', input.parentNode)[0]; if ($.datepicker._isDisabledDatepicker(input) || $.datepicker._lastInput == input) // already here return; var inst = $.datepicker._getInst(input); if ($.datepicker._curInst && $.datepicker._curInst != inst) { $.datepicker._curInst.dpDiv.stop(true, true); if ( inst && $.datepicker._datepickerShowing ) { $.datepicker._hideDatepicker( $.datepicker._curInst.input[0] ); } } var beforeShow = $.datepicker._get(inst, 'beforeShow'); var beforeShowSettings = beforeShow ? beforeShow.apply(input, [input, inst]) : {}; if(beforeShowSettings === false){ //false return; } extendRemove(inst.settings, beforeShowSettings); inst.lastVal = null; $.datepicker._lastInput = input; $.datepicker._setDateFromField(inst); if ($.datepicker._inDialog) // hide cursor input.value = ''; if (!$.datepicker._pos) { // position below input $.datepicker._pos = $.datepicker._findPos(input); $.datepicker._pos[1] += input.offsetHeight; // add the height } var isFixed = false; $(input).parents().each(function() { isFixed |= $(this).css('position') == 'fixed'; return !isFixed; }); if (isFixed && $.browser.opera) { // correction for Opera when fixed and scrolled $.datepicker._pos[0] -= document.documentElement.scrollLeft; $.datepicker._pos[1] -= document.documentElement.scrollTop; } var offset = {left: $.datepicker._pos[0], top: $.datepicker._pos[1]}; $.datepicker._pos = null; //to avoid flashes on Firefox inst.dpDiv.empty(); // determine sizing offscreen inst.dpDiv.css({position: 'absolute', display: 'block', top: '-1000px'}); $.datepicker._updateDatepicker(inst); // fix width for dynamic number of date pickers // and adjust position before showing offset = $.datepicker._checkOffset(inst, offset, isFixed); inst.dpDiv.css({position: ($.datepicker._inDialog && $.blockUI ? 'static' : (isFixed ? 'fixed' : 'absolute')), display: 'none', left: offset.left + 'px', top: offset.top + 'px'}); if (!inst.inline) { var showAnim = $.datepicker._get(inst, 'showAnim'); var duration = $.datepicker._get(inst, 'duration'); var postProcess = function() { var cover = inst.dpDiv.find('iframe.ui-datepicker-cover'); // IE6- only if( !! cover.length ){ var borders = $.datepicker._getBorders(inst.dpDiv); cover.css({left: -borders[0], top: -borders[1], width: inst.dpDiv.outerWidth(), height: inst.dpDiv.outerHeight()}); } }; inst.dpDiv.zIndex($(input).zIndex()+1); $.datepicker._datepickerShowing = true; if ($.effects && $.effects[showAnim]) inst.dpDiv.show(showAnim, $.datepicker._get(inst, 'showOptions'), duration, postProcess); else inst.dpDiv[showAnim || 'show']((showAnim ? duration : null), postProcess); if (!showAnim || !duration) postProcess(); if (inst.input.is(':visible') && !inst.input.is(':disabled')) inst.input.focus(); $.datepicker._curInst = inst; } }, /* Generate the date picker content. */ _updateDatepicker: function(inst) { var self = this; self.maxRows = 4; //Reset the max number of rows being displayed (see #7043) var borders = $.datepicker._getBorders(inst.dpDiv); instActive = inst; // for delegate hover events inst.dpDiv.empty().append(this._generateHTML(inst)); this._attachHandlers(inst); var cover = inst.dpDiv.find('iframe.ui-datepicker-cover'); // IE6- only if( !!cover.length ){ //avoid call to outerXXXX() when not in IE6 cover.css({left: -borders[0], top: -borders[1], width: inst.dpDiv.outerWidth(), height: inst.dpDiv.outerHeight()}) } inst.dpDiv.find('.' + this._dayOverClass + ' a').mouseover(); var numMonths = this._getNumberOfMonths(inst); var cols = numMonths[1]; var width = 17; inst.dpDiv.removeClass('ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4').width(''); if (cols > 1) inst.dpDiv.addClass('ui-datepicker-multi-' + cols).css('width', (width * cols) + 'em'); inst.dpDiv[(numMonths[0] != 1 || numMonths[1] != 1 ? 'add' : 'remove') + 'Class']('ui-datepicker-multi'); inst.dpDiv[(this._get(inst, 'isRTL') ? 'add' : 'remove') + 'Class']('ui-datepicker-rtl'); if (inst == $.datepicker._curInst && $.datepicker._datepickerShowing && inst.input && // #6694 - don't focus the input if it's already focused // this breaks the change event in IE inst.input.is(':visible') && !inst.input.is(':disabled') && inst.input[0] != document.activeElement) inst.input.focus(); // deffered render of the years select (to avoid flashes on Firefox) if( inst.yearshtml ){ var origyearshtml = inst.yearshtml; setTimeout(function(){ //assure that inst.yearshtml didn't change. if( origyearshtml === inst.yearshtml && inst.yearshtml ){ inst.dpDiv.find('select.ui-datepicker-year:first').replaceWith(inst.yearshtml); } origyearshtml = inst.yearshtml = null; }, 0); } }, /* Retrieve the size of left and top borders for an element. @param elem (jQuery object) the element of interest @return (number[2]) the left and top borders */ _getBorders: function(elem) { var convert = function(value) { return {thin: 1, medium: 2, thick: 3}[value] || value; }; return [parseFloat(convert(elem.css('border-left-width'))), parseFloat(convert(elem.css('border-top-width')))]; }, /* Check positioning to remain on screen. */ _checkOffset: function(inst, offset, isFixed) { var dpWidth = inst.dpDiv.outerWidth(); var dpHeight = inst.dpDiv.outerHeight(); var inputWidth = inst.input ? inst.input.outerWidth() : 0; var inputHeight = inst.input ? inst.input.outerHeight() : 0; var viewWidth = document.documentElement.clientWidth + (isFixed ? 0 : $(document).scrollLeft()); var viewHeight = document.documentElement.clientHeight + (isFixed ? 0 : $(document).scrollTop()); offset.left -= (this._get(inst, 'isRTL') ? (dpWidth - inputWidth) : 0); offset.left -= (isFixed && offset.left == inst.input.offset().left) ? $(document).scrollLeft() : 0; offset.top -= (isFixed && offset.top == (inst.input.offset().top + inputHeight)) ? $(document).scrollTop() : 0; // now check if datepicker is showing outside window viewport - move to a better place if so. offset.left -= Math.min(offset.left, (offset.left + dpWidth > viewWidth && viewWidth > dpWidth) ? Math.abs(offset.left + dpWidth - viewWidth) : 0); offset.top -= Math.min(offset.top, (offset.top + dpHeight > viewHeight && viewHeight > dpHeight) ? Math.abs(dpHeight + inputHeight) : 0); return offset; }, /* Find an object's position on the screen. */ _findPos: function(obj) { var inst = this._getInst(obj); var isRTL = this._get(inst, 'isRTL'); while (obj && (obj.type == 'hidden' || obj.nodeType != 1 || $.expr.filters.hidden(obj))) { obj = obj[isRTL ? 'previousSibling' : 'nextSibling']; } var position = $(obj).offset(); return [position.left, position.top]; }, /* Hide the date picker from view. @param input element - the input field attached to the date picker */ _hideDatepicker: function(input) { var inst = this._curInst; if (!inst || (input && inst != $.data(input, PROP_NAME))) return; if (this._datepickerShowing) { var showAnim = this._get(inst, 'showAnim'); var duration = this._get(inst, 'duration'); var postProcess = function() { $.datepicker._tidyDialog(inst); }; if ($.effects && $.effects[showAnim]) inst.dpDiv.hide(showAnim, $.datepicker._get(inst, 'showOptions'), duration, postProcess); else inst.dpDiv[(showAnim == 'slideDown' ? 'slideUp' : (showAnim == 'fadeIn' ? 'fadeOut' : 'hide'))]((showAnim ? duration : null), postProcess); if (!showAnim) postProcess(); this._datepickerShowing = false; var onClose = this._get(inst, 'onClose'); if (onClose) onClose.apply((inst.input ? inst.input[0] : null), [(inst.input ? inst.input.val() : ''), inst]); this._lastInput = null; if (this._inDialog) { this._dialogInput.css({ position: 'absolute', left: '0', top: '-100px' }); if ($.blockUI) { $.unblockUI(); $('body').append(this.dpDiv); } } this._inDialog = false; } }, /* Tidy up after a dialog display. */ _tidyDialog: function(inst) { inst.dpDiv.removeClass(this._dialogClass).unbind('.ui-datepicker-calendar'); }, /* Close date picker if clicked elsewhere. */ _checkExternalClick: function(event) { if (!$.datepicker._curInst) return; var $target = $(event.target), inst = $.datepicker._getInst($target[0]); if ( ( ( $target[0].id != $.datepicker._mainDivId && $target.parents('#' + $.datepicker._mainDivId).length == 0 && !$target.hasClass($.datepicker.markerClassName) && !$target.closest("." + $.datepicker._triggerClass).length && $.datepicker._datepickerShowing && !($.datepicker._inDialog && $.blockUI) ) ) || ( $target.hasClass($.datepicker.markerClassName) && $.datepicker._curInst != inst ) ) $.datepicker._hideDatepicker(); }, /* Adjust one of the date sub-fields. */ _adjustDate: function(id, offset, period) { var target = $(id); var inst = this._getInst(target[0]); if (this._isDisabledDatepicker(target[0])) { return; } this._adjustInstDate(inst, offset + (period == 'M' ? this._get(inst, 'showCurrentAtPos') : 0), // undo positioning period); this._updateDatepicker(inst); }, /* Action for current link. */ _gotoToday: function(id) { var target = $(id); var inst = this._getInst(target[0]); if (this._get(inst, 'gotoCurrent') && inst.currentDay) { inst.selectedDay = inst.currentDay; inst.drawMonth = inst.selectedMonth = inst.currentMonth; inst.drawYear = inst.selectedYear = inst.currentYear; } else { var date = new Date(); inst.selectedDay = date.getDate(); inst.drawMonth = inst.selectedMonth = date.getMonth(); inst.drawYear = inst.selectedYear = date.getFullYear(); } this._notifyChange(inst); this._adjustDate(target); }, /* Action for selecting a new month/year. */ _selectMonthYear: function(id, select, period) { var target = $(id); var inst = this._getInst(target[0]); inst['selected' + (period == 'M' ? 'Month' : 'Year')] = inst['draw' + (period == 'M' ? 'Month' : 'Year')] = parseInt(select.options[select.selectedIndex].value,10); this._notifyChange(inst); this._adjustDate(target); }, /* Action for selecting a day. */ _selectDay: function(id, month, year, td) { var target = $(id); if ($(td).hasClass(this._unselectableClass) || this._isDisabledDatepicker(target[0])) { return; } var inst = this._getInst(target[0]); inst.selectedDay = inst.currentDay = $('a', td).html(); inst.selectedMonth = inst.currentMonth = month; inst.selectedYear = inst.currentYear = year; this._selectDate(id, this._formatDate(inst, inst.currentDay, inst.currentMonth, inst.currentYear)); }, /* Erase the input field and hide the date picker. */ _clearDate: function(id) { var target = $(id); var inst = this._getInst(target[0]); this._selectDate(target, ''); }, /* Update the input field with the selected date. */ _selectDate: function(id, dateStr) { var target = $(id); var inst = this._getInst(target[0]); dateStr = (dateStr != null ? dateStr : this._formatDate(inst)); if (inst.input) inst.input.val(dateStr); this._updateAlternate(inst); var onSelect = this._get(inst, 'onSelect'); if (onSelect) onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]); // trigger custom callback else if (inst.input) inst.input.trigger('change'); // fire the change event if (inst.inline) this._updateDatepicker(inst); else { this._hideDatepicker(); this._lastInput = inst.input[0]; if (typeof(inst.input[0]) != 'object') inst.input.focus(); // restore focus this._lastInput = null; } }, /* Update any alternate field to synchronise with the main field. */ _updateAlternate: function(inst) { var altField = this._get(inst, 'altField'); if (altField) { // update alternate field too var altFormat = this._get(inst, 'altFormat') || this._get(inst, 'dateFormat'); var date = this._getDate(inst); var dateStr = this.formatDate(altFormat, date, this._getFormatConfig(inst)); $(altField).each(function() { $(this).val(dateStr); }); } }, /* Set as beforeShowDay function to prevent selection of weekends. @param date Date - the date to customise @return [boolean, string] - is this date selectable?, what is its CSS class? */ noWeekends: function(date) { var day = date.getDay(); return [(day > 0 && day < 6), '']; }, /* Set as calculateWeek to determine the week of the year based on the ISO 8601 definition. @param date Date - the date to get the week for @return number - the number of the week within the year that contains this date */ iso8601Week: function(date) { var checkDate = new Date(date.getTime()); // Find Thursday of this week starting on Monday checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay() || 7)); var time = checkDate.getTime(); checkDate.setMonth(0); // Compare with Jan 1 checkDate.setDate(1); return Math.floor(Math.round((time - checkDate) / 86400000) / 7) + 1; }, /* Parse a string value into a date object. See formatDate below for the possible formats. @param format string - the expected format of the date @param value string - the date in the above format @param settings Object - attributes include: shortYearCutoff number - the cutoff year for determining the century (optional) dayNamesShort string[7] - abbreviated names of the days from Sunday (optional) dayNames string[7] - names of the days from Sunday (optional) monthNamesShort string[12] - abbreviated names of the months (optional) monthNames string[12] - names of the months (optional) @return Date - the extracted date value or null if value is blank */ parseDate: function (format, value, settings) { if (format == null || value == null) throw 'Invalid arguments'; value = (typeof value == 'object' ? value.toString() : value + ''); if (value == '') return null; var shortYearCutoff = (settings ? settings.shortYearCutoff : null) || this._defaults.shortYearCutoff; shortYearCutoff = (typeof shortYearCutoff != 'string' ? shortYearCutoff : new Date().getFullYear() % 100 + parseInt(shortYearCutoff, 10)); var dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort; var dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames; var monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort; var monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames; var year = -1; var month = -1; var day = -1; var doy = -1; var literal = false; // Check whether a format character is doubled var lookAhead = function(match) { var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) == match); if (matches) iFormat++; return matches; }; // Extract a number from the string value var getNumber = function(match) { var isDoubled = lookAhead(match); var size = (match == '@' ? 14 : (match == '!' ? 20 : (match == 'y' && isDoubled ? 4 : (match == 'o' ? 3 : 2)))); var digits = new RegExp('^\\d{1,' + size + '}'); var num = value.substring(iValue).match(digits); if (!num) throw 'Missing number at position ' + iValue; iValue += num[0].length; return parseInt(num[0], 10); }; // Extract a name from the string value and convert to an index var getName = function(match, shortNames, longNames) { var names = $.map(lookAhead(match) ? longNames : shortNames, function (v, k) { return [ [k, v] ]; }).sort(function (a, b) { return -(a[1].length - b[1].length); }); var index = -1; $.each(names, function (i, pair) { var name = pair[1]; if (value.substr(iValue, name.length).toLowerCase() == name.toLowerCase()) { index = pair[0]; iValue += name.length; return false; } }); if (index != -1) return index + 1; else throw 'Unknown name at position ' + iValue; }; // Confirm that a literal character matches the string value var checkLiteral = function() { if (value.charAt(iValue) != format.charAt(iFormat)) throw 'Unexpected literal at position ' + iValue; iValue++; }; var iValue = 0; for (var iFormat = 0; iFormat < format.length; iFormat++) { if (literal) if (format.charAt(iFormat) == "'" && !lookAhead("'")) literal = false; else checkLiteral(); else switch (format.charAt(iFormat)) { case 'd': day = getNumber('d'); break; case 'D': getName('D', dayNamesShort, dayNames); break; case 'o': doy = getNumber('o'); break; case 'm': month = getNumber('m'); break; case 'M': month = getName('M', monthNamesShort, monthNames); break; case 'y': year = getNumber('y'); break; case '@': var date = new Date(getNumber('@')); year = date.getFullYear(); month = date.getMonth() + 1; day = date.getDate(); break; case '!': var date = new Date((getNumber('!') - this._ticksTo1970) / 10000); year = date.getFullYear(); month = date.getMonth() + 1; day = date.getDate(); break; case "'": if (lookAhead("'")) checkLiteral(); else literal = true; break; default: checkLiteral(); } } if (iValue < value.length){ throw "Extra/unparsed characters found in date: " + value.substring(iValue); } if (year == -1) year = new Date().getFullYear(); else if (year < 100) year += new Date().getFullYear() - new Date().getFullYear() % 100 + (year <= shortYearCutoff ? 0 : -100); if (doy > -1) { month = 1; day = doy; do { var dim = this._getDaysInMonth(year, month - 1); if (day <= dim) break; month++; day -= dim; } while (true); } var date = this._daylightSavingAdjust(new Date(year, month - 1, day)); if (date.getFullYear() != year || date.getMonth() + 1 != month || date.getDate() != day) throw 'Invalid date'; // E.g. 31/02/00 return date; }, /* Standard date formats. */ ATOM: 'yy-mm-dd', // RFC 3339 (ISO 8601) COOKIE: 'D, dd M yy', ISO_8601: 'yy-mm-dd', RFC_822: 'D, d M y', RFC_850: 'DD, dd-M-y', RFC_1036: 'D, d M y', RFC_1123: 'D, d M yy', RFC_2822: 'D, d M yy', RSS: 'D, d M y', // RFC 822 TICKS: '!', TIMESTAMP: '@', W3C: 'yy-mm-dd', // ISO 8601 _ticksTo1970: (((1970 - 1) * 365 + Math.floor(1970 / 4) - Math.floor(1970 / 100) + Math.floor(1970 / 400)) * 24 * 60 * 60 * 10000000), /* Format a date object into a string value. The format can be combinations of the following: d - day of month (no leading zero) dd - day of month (two digit) o - day of year (no leading zeros) oo - day of year (three digit) D - day name short DD - day name long m - month of year (no leading zero) mm - month of year (two digit) M - month name short MM - month name long y - year (two digit) yy - year (four digit) @ - Unix timestamp (ms since 01/01/1970) ! - Windows ticks (100ns since 01/01/0001) '...' - literal text '' - single quote @param format string - the desired format of the date @param date Date - the date value to format @param settings Object - attributes include: dayNamesShort string[7] - abbreviated names of the days from Sunday (optional) dayNames string[7] - names of the days from Sunday (optional) monthNamesShort string[12] - abbreviated names of the months (optional) monthNames string[12] - names of the months (optional) @return string - the date in the above format */ formatDate: function (format, date, settings) { if (!date) return ''; var dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort; var dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames; var monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort; var monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames; // Check whether a format character is doubled var lookAhead = function(match) { var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) == match); if (matches) iFormat++; return matches; }; // Format a number, with leading zero if necessary var formatNumber = function(match, value, len) { var num = '' + value; if (lookAhead(match)) while (num.length < len) num = '0' + num; return num; }; // Format a name, short or long as requested var formatName = function(match, value, shortNames, longNames) { return (lookAhead(match) ? longNames[value] : shortNames[value]); }; var output = ''; var literal = false; if (date) for (var iFormat = 0; iFormat < format.length; iFormat++) { if (literal) if (format.charAt(iFormat) == "'" && !lookAhead("'")) literal = false; else output += format.charAt(iFormat); else switch (format.charAt(iFormat)) { case 'd': output += formatNumber('d', date.getDate(), 2); break; case 'D': output += formatName('D', date.getDay(), dayNamesShort, dayNames); break; case 'o': output += formatNumber('o', Math.round((new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime() - new Date(date.getFullYear(), 0, 0).getTime()) / 86400000), 3); break; case 'm': output += formatNumber('m', date.getMonth() + 1, 2); break; case 'M': output += formatName('M', date.getMonth(), monthNamesShort, monthNames); break; case 'y': output += (lookAhead('y') ? date.getFullYear() : (date.getYear() % 100 < 10 ? '0' : '') + date.getYear() % 100); break; case '@': output += date.getTime(); break; case '!': output += date.getTime() * 10000 + this._ticksTo1970; break; case "'": if (lookAhead("'")) output += "'"; else literal = true; break; default: output += format.charAt(iFormat); } } return output; }, /* Extract all possible characters from the date format. */ _possibleChars: function (format) { var chars = ''; var literal = false; // Check whether a format character is doubled var lookAhead = function(match) { var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) == match); if (matches) iFormat++; return matches; }; for (var iFormat = 0; iFormat < format.length; iFormat++) if (literal) if (format.charAt(iFormat) == "'" && !lookAhead("'")) literal = false; else chars += format.charAt(iFormat); else switch (format.charAt(iFormat)) { case 'd': case 'm': case 'y': case '@': chars += '0123456789'; break; case 'D': case 'M': return null; // Accept anything case "'": if (lookAhead("'")) chars += "'"; else literal = true; break; default: chars += format.charAt(iFormat); } return chars; }, /* Get a setting value, defaulting if necessary. */ _get: function(inst, name) { return inst.settings[name] !== undefined ? inst.settings[name] : this._defaults[name]; }, /* Parse existing date and initialise date picker. */ _setDateFromField: function(inst, noDefault) { if (inst.input.val() == inst.lastVal) { return; } var dateFormat = this._get(inst, 'dateFormat'); var dates = inst.lastVal = inst.input ? inst.input.val() : null; var date, defaultDate; date = defaultDate = this._getDefaultDate(inst); var settings = this._getFormatConfig(inst); try { date = this.parseDate(dateFormat, dates, settings) || defaultDate; } catch (event) { this.log(event); dates = (noDefault ? '' : dates); } inst.selectedDay = date.getDate(); inst.drawMonth = inst.selectedMonth = date.getMonth(); inst.drawYear = inst.selectedYear = date.getFullYear(); inst.currentDay = (dates ? date.getDate() : 0); inst.currentMonth = (dates ? date.getMonth() : 0); inst.currentYear = (dates ? date.getFullYear() : 0); this._adjustInstDate(inst); }, /* Retrieve the default date shown on opening. */ _getDefaultDate: function(inst) { return this._restrictMinMax(inst, this._determineDate(inst, this._get(inst, 'defaultDate'), new Date())); }, /* A date may be specified as an exact value or a relative one. */ _determineDate: function(inst, date, defaultDate) { var offsetNumeric = function(offset) { var date = new Date(); date.setDate(date.getDate() + offset); return date; }; var offsetString = function(offset) { try { return $.datepicker.parseDate($.datepicker._get(inst, 'dateFormat'), offset, $.datepicker._getFormatConfig(inst)); } catch (e) { // Ignore } var date = (offset.toLowerCase().match(/^c/) ? $.datepicker._getDate(inst) : null) || new Date(); var year = date.getFullYear(); var month = date.getMonth(); var day = date.getDate(); var pattern = /([+-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g; var matches = pattern.exec(offset); while (matches) { switch (matches[2] || 'd') { case 'd' : case 'D' : day += parseInt(matches[1],10); break; case 'w' : case 'W' : day += parseInt(matches[1],10) * 7; break; case 'm' : case 'M' : month += parseInt(matches[1],10); day = Math.min(day, $.datepicker._getDaysInMonth(year, month)); break; case 'y': case 'Y' : year += parseInt(matches[1],10); day = Math.min(day, $.datepicker._getDaysInMonth(year, month)); break; } matches = pattern.exec(offset); } return new Date(year, month, day); }; var newDate = (date == null || date === '' ? defaultDate : (typeof date == 'string' ? offsetString(date) : (typeof date == 'number' ? (isNaN(date) ? defaultDate : offsetNumeric(date)) : new Date(date.getTime())))); newDate = (newDate && newDate.toString() == 'Invalid Date' ? defaultDate : newDate); if (newDate) { newDate.setHours(0); newDate.setMinutes(0); newDate.setSeconds(0); newDate.setMilliseconds(0); } return this._daylightSavingAdjust(newDate); }, /* Handle switch to/from daylight saving. Hours may be non-zero on daylight saving cut-over: > 12 when midnight changeover, but then cannot generate midnight datetime, so jump to 1AM, otherwise reset. @param date (Date) the date to check @return (Date) the corrected date */ _daylightSavingAdjust: function(date) { if (!date) return null; date.setHours(date.getHours() > 12 ? date.getHours() + 2 : 0); return date; }, /* Set the date(s) directly. */ _setDate: function(inst, date, noChange) { var clear = !date; var origMonth = inst.selectedMonth; var origYear = inst.selectedYear; var newDate = this._restrictMinMax(inst, this._determineDate(inst, date, new Date())); inst.selectedDay = inst.currentDay = newDate.getDate(); inst.drawMonth = inst.selectedMonth = inst.currentMonth = newDate.getMonth(); inst.drawYear = inst.selectedYear = inst.currentYear = newDate.getFullYear(); if ((origMonth != inst.selectedMonth || origYear != inst.selectedYear) && !noChange) this._notifyChange(inst); this._adjustInstDate(inst); if (inst.input) { inst.input.val(clear ? '' : this._formatDate(inst)); } }, /* Retrieve the date(s) directly. */ _getDate: function(inst) { var startDate = (!inst.currentYear || (inst.input && inst.input.val() == '') ? null : this._daylightSavingAdjust(new Date( inst.currentYear, inst.currentMonth, inst.currentDay))); return startDate; }, /* Attach the onxxx handlers. These are declared statically so * they work with static code transformers like Caja. */ _attachHandlers: function(inst) { var stepMonths = this._get(inst, 'stepMonths'); var id = '#' + inst.id.replace( /\\\\/g, "\\" ); inst.dpDiv.find('[data-handler]').map(function () { var handler = { prev: function () { window['DP_jQuery_' + dpuuid].datepicker._adjustDate(id, -stepMonths, 'M'); }, next: function () { window['DP_jQuery_' + dpuuid].datepicker._adjustDate(id, +stepMonths, 'M'); }, hide: function () { window['DP_jQuery_' + dpuuid].datepicker._hideDatepicker(); }, today: function () { window['DP_jQuery_' + dpuuid].datepicker._gotoToday(id); }, selectDay: function () { window['DP_jQuery_' + dpuuid].datepicker._selectDay(id, +this.getAttribute('data-month'), +this.getAttribute('data-year'), this); return false; }, selectMonth: function () { window['DP_jQuery_' + dpuuid].datepicker._selectMonthYear(id, this, 'M'); return false; }, selectYear: function () { window['DP_jQuery_' + dpuuid].datepicker._selectMonthYear(id, this, 'Y'); return false; } }; $(this).bind(this.getAttribute('data-event'), handler[this.getAttribute('data-handler')]); }); }, /* Generate the HTML for the current state of the date picker. */ _generateHTML: function(inst) { var today = new Date(); today = this._daylightSavingAdjust( new Date(today.getFullYear(), today.getMonth(), today.getDate())); // clear time var isRTL = this._get(inst, 'isRTL'); var showButtonPanel = this._get(inst, 'showButtonPanel'); var hideIfNoPrevNext = this._get(inst, 'hideIfNoPrevNext'); var navigationAsDateFormat = this._get(inst, 'navigationAsDateFormat'); var numMonths = this._getNumberOfMonths(inst); var showCurrentAtPos = this._get(inst, 'showCurrentAtPos'); var stepMonths = this._get(inst, 'stepMonths'); var isMultiMonth = (numMonths[0] != 1 || numMonths[1] != 1); var currentDate = this._daylightSavingAdjust((!inst.currentDay ? new Date(9999, 9, 9) : new Date(inst.currentYear, inst.currentMonth, inst.currentDay))); var minDate = this._getMinMaxDate(inst, 'min'); var maxDate = this._getMinMaxDate(inst, 'max'); var drawMonth = inst.drawMonth - showCurrentAtPos; var drawYear = inst.drawYear; if (drawMonth < 0) { drawMonth += 12; drawYear--; } if (maxDate) { var maxDraw = this._daylightSavingAdjust(new Date(maxDate.getFullYear(), maxDate.getMonth() - (numMonths[0] * numMonths[1]) + 1, maxDate.getDate())); maxDraw = (minDate && maxDraw < minDate ? minDate : maxDraw); while (this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1)) > maxDraw) { drawMonth--; if (drawMonth < 0) { drawMonth = 11; drawYear--; } } } inst.drawMonth = drawMonth; inst.drawYear = drawYear; var prevText = this._get(inst, 'prevText'); prevText = (!navigationAsDateFormat ? prevText : this.formatDate(prevText, this._daylightSavingAdjust(new Date(drawYear, drawMonth - stepMonths, 1)), this._getFormatConfig(inst))); var prev = (this._canAdjustMonth(inst, -1, drawYear, drawMonth) ? '<a class="ui-datepicker-prev ui-corner-all" data-handler="prev" data-event="click"' + ' title="' + prevText + '"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'e' : 'w') + '">' + prevText + '</span></a>' : (hideIfNoPrevNext ? '' : '<a class="ui-datepicker-prev ui-corner-all ui-state-disabled" title="'+ prevText +'"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'e' : 'w') + '">' + prevText + '</span></a>')); var nextText = this._get(inst, 'nextText'); nextText = (!navigationAsDateFormat ? nextText : this.formatDate(nextText, this._daylightSavingAdjust(new Date(drawYear, drawMonth + stepMonths, 1)), this._getFormatConfig(inst))); var next = (this._canAdjustMonth(inst, +1, drawYear, drawMonth) ? '<a class="ui-datepicker-next ui-corner-all" data-handler="next" data-event="click"' + ' title="' + nextText + '"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'w' : 'e') + '">' + nextText + '</span></a>' : (hideIfNoPrevNext ? '' : '<a class="ui-datepicker-next ui-corner-all ui-state-disabled" title="'+ nextText + '"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'w' : 'e') + '">' + nextText + '</span></a>')); var currentText = this._get(inst, 'currentText'); var gotoDate = (this._get(inst, 'gotoCurrent') && inst.currentDay ? currentDate : today); currentText = (!navigationAsDateFormat ? currentText : this.formatDate(currentText, gotoDate, this._getFormatConfig(inst))); var controls = (!inst.inline ? '<button type="button" class="ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all" data-handler="hide" data-event="click">' + this._get(inst, 'closeText') + '</button>' : ''); var buttonPanel = (showButtonPanel) ? '<div class="ui-datepicker-buttonpane ui-widget-content">' + (isRTL ? controls : '') + (this._isInRange(inst, gotoDate) ? '<button type="button" class="ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all" data-handler="today" data-event="click"' + '>' + currentText + '</button>' : '') + (isRTL ? '' : controls) + '</div>' : ''; var firstDay = parseInt(this._get(inst, 'firstDay'),10); firstDay = (isNaN(firstDay) ? 0 : firstDay); var showWeek = this._get(inst, 'showWeek'); var dayNames = this._get(inst, 'dayNames'); var dayNamesShort = this._get(inst, 'dayNamesShort'); var dayNamesMin = this._get(inst, 'dayNamesMin'); var monthNames = this._get(inst, 'monthNames'); var monthNamesShort = this._get(inst, 'monthNamesShort'); var beforeShowDay = this._get(inst, 'beforeShowDay'); var showOtherMonths = this._get(inst, 'showOtherMonths'); var selectOtherMonths = this._get(inst, 'selectOtherMonths'); var calculateWeek = this._get(inst, 'calculateWeek') || this.iso8601Week; var defaultDate = this._getDefaultDate(inst); var html = ''; for (var row = 0; row < numMonths[0]; row++) { var group = ''; this.maxRows = 4; for (var col = 0; col < numMonths[1]; col++) { var selectedDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, inst.selectedDay)); var cornerClass = ' ui-corner-all'; var calender = ''; if (isMultiMonth) { calender += '<div class="ui-datepicker-group'; if (numMonths[1] > 1) switch (col) { case 0: calender += ' ui-datepicker-group-first'; cornerClass = ' ui-corner-' + (isRTL ? 'right' : 'left'); break; case numMonths[1]-1: calender += ' ui-datepicker-group-last'; cornerClass = ' ui-corner-' + (isRTL ? 'left' : 'right'); break; default: calender += ' ui-datepicker-group-middle'; cornerClass = ''; break; } calender += '">'; } calender += '<div class="ui-datepicker-header ui-widget-header ui-helper-clearfix' + cornerClass + '">' + (/all|left/.test(cornerClass) && row == 0 ? (isRTL ? next : prev) : '') + (/all|right/.test(cornerClass) && row == 0 ? (isRTL ? prev : next) : '') + this._generateMonthYearHeader(inst, drawMonth, drawYear, minDate, maxDate, row > 0 || col > 0, monthNames, monthNamesShort) + // draw month headers '</div><table class="ui-datepicker-calendar"><thead>' + '<tr>'; var thead = (showWeek ? '<th class="ui-datepicker-week-col">' + this._get(inst, 'weekHeader') + '</th>' : ''); for (var dow = 0; dow < 7; dow++) { // days of the week var day = (dow + firstDay) % 7; thead += '<th' + ((dow + firstDay + 6) % 7 >= 5 ? ' class="ui-datepicker-week-end"' : '') + '>' + '<span title="' + dayNames[day] + '">' + dayNamesMin[day] + '</span></th>'; } calender += thead + '</tr></thead><tbody>'; var daysInMonth = this._getDaysInMonth(drawYear, drawMonth); if (drawYear == inst.selectedYear && drawMonth == inst.selectedMonth) inst.selectedDay = Math.min(inst.selectedDay, daysInMonth); var leadDays = (this._getFirstDayOfMonth(drawYear, drawMonth) - firstDay + 7) % 7; var curRows = Math.ceil((leadDays + daysInMonth) / 7); // calculate the number of rows to generate var numRows = (isMultiMonth ? this.maxRows > curRows ? this.maxRows : curRows : curRows); //If multiple months, use the higher number of rows (see #7043) this.maxRows = numRows; var printDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1 - leadDays)); for (var dRow = 0; dRow < numRows; dRow++) { // create date picker rows calender += '<tr>'; var tbody = (!showWeek ? '' : '<td class="ui-datepicker-week-col">' + this._get(inst, 'calculateWeek')(printDate) + '</td>'); for (var dow = 0; dow < 7; dow++) { // create date picker days var daySettings = (beforeShowDay ? beforeShowDay.apply((inst.input ? inst.input[0] : null), [printDate]) : [true, '']); var otherMonth = (printDate.getMonth() != drawMonth); var unselectable = (otherMonth && !selectOtherMonths) || !daySettings[0] || (minDate && printDate < minDate) || (maxDate && printDate > maxDate); tbody += '<td class="' + ((dow + firstDay + 6) % 7 >= 5 ? ' ui-datepicker-week-end' : '') + // highlight weekends (otherMonth ? ' ui-datepicker-other-month' : '') + // highlight days from other months ((printDate.getTime() == selectedDate.getTime() && drawMonth == inst.selectedMonth && inst._keyEvent) || // user pressed key (defaultDate.getTime() == printDate.getTime() && defaultDate.getTime() == selectedDate.getTime()) ? // or defaultDate is current printedDate and defaultDate is selectedDate ' ' + this._dayOverClass : '') + // highlight selected day (unselectable ? ' ' + this._unselectableClass + ' ui-state-disabled': '') + // highlight unselectable days (otherMonth && !showOtherMonths ? '' : ' ' + daySettings[1] + // highlight custom dates (printDate.getTime() == currentDate.getTime() ? ' ' + this._currentClass : '') + // highlight selected day (printDate.getTime() == today.getTime() ? ' ui-datepicker-today' : '')) + '"' + // highlight today (if different) ((!otherMonth || showOtherMonths) && daySettings[2] ? ' title="' + daySettings[2] + '"' : '') + // cell title (unselectable ? '' : ' data-handler="selectDay" data-event="click" data-month="' + printDate.getMonth() + '" data-year="' + printDate.getFullYear() + '"') + '>' + // actions (otherMonth && !showOtherMonths ? '&#xa0;' : // display for other months (unselectable ? '<span class="ui-state-default">' + printDate.getDate() + '</span>' : '<a class="ui-state-default' + (printDate.getTime() == today.getTime() ? ' ui-state-highlight' : '') + (printDate.getTime() == currentDate.getTime() ? ' ui-state-active' : '') + // highlight selected day (otherMonth ? ' ui-priority-secondary' : '') + // distinguish dates from other months '" href="#">' + printDate.getDate() + '</a>')) + '</td>'; // display selectable date printDate.setDate(printDate.getDate() + 1); printDate = this._daylightSavingAdjust(printDate); } calender += tbody + '</tr>'; } drawMonth++; if (drawMonth > 11) { drawMonth = 0; drawYear++; } calender += '</tbody></table>' + (isMultiMonth ? '</div>' + ((numMonths[0] > 0 && col == numMonths[1]-1) ? '<div class="ui-datepicker-row-break"></div>' : '') : ''); group += calender; } html += group; } html += buttonPanel + ($.browser.msie && parseInt($.browser.version,10) < 7 && !inst.inline ? '<iframe src="javascript:false;" class="ui-datepicker-cover" frameborder="0"></iframe>' : ''); inst._keyEvent = false; return html; }, /* Generate the month and year header. */ _generateMonthYearHeader: function(inst, drawMonth, drawYear, minDate, maxDate, secondary, monthNames, monthNamesShort) { var changeMonth = this._get(inst, 'changeMonth'); var changeYear = this._get(inst, 'changeYear'); var showMonthAfterYear = this._get(inst, 'showMonthAfterYear'); var html = '<div class="ui-datepicker-title">'; var monthHtml = ''; // month selection if (secondary || !changeMonth) monthHtml += '<span class="ui-datepicker-month">' + monthNames[drawMonth] + '</span>'; else { var inMinYear = (minDate && minDate.getFullYear() == drawYear); var inMaxYear = (maxDate && maxDate.getFullYear() == drawYear); monthHtml += '<select class="ui-datepicker-month" data-handler="selectMonth" data-event="change">'; for (var month = 0; month < 12; month++) { if ((!inMinYear || month >= minDate.getMonth()) && (!inMaxYear || month <= maxDate.getMonth())) monthHtml += '<option value="' + month + '"' + (month == drawMonth ? ' selected="selected"' : '') + '>' + monthNamesShort[month] + '</option>'; } monthHtml += '</select>'; } if (!showMonthAfterYear) html += monthHtml + (secondary || !(changeMonth && changeYear) ? '&#xa0;' : ''); // year selection if ( !inst.yearshtml ) { inst.yearshtml = ''; if (secondary || !changeYear) html += '<span class="ui-datepicker-year">' + drawYear + '</span>'; else { // determine range of years to display var years = this._get(inst, 'yearRange').split(':'); var thisYear = new Date().getFullYear(); var determineYear = function(value) { var year = (value.match(/c[+-].*/) ? drawYear + parseInt(value.substring(1), 10) : (value.match(/[+-].*/) ? thisYear + parseInt(value, 10) : parseInt(value, 10))); return (isNaN(year) ? thisYear : year); }; var year = determineYear(years[0]); var endYear = Math.max(year, determineYear(years[1] || '')); year = (minDate ? Math.max(year, minDate.getFullYear()) : year); endYear = (maxDate ? Math.min(endYear, maxDate.getFullYear()) : endYear); inst.yearshtml += '<select class="ui-datepicker-year" data-handler="selectYear" data-event="change">'; for (; year <= endYear; year++) { inst.yearshtml += '<option value="' + year + '"' + (year == drawYear ? ' selected="selected"' : '') + '>' + year + '</option>'; } inst.yearshtml += '</select>'; html += inst.yearshtml; inst.yearshtml = null; } } html += this._get(inst, 'yearSuffix'); if (showMonthAfterYear) html += (secondary || !(changeMonth && changeYear) ? '&#xa0;' : '') + monthHtml; html += '</div>'; // Close datepicker_header return html; }, /* Adjust one of the date sub-fields. */ _adjustInstDate: function(inst, offset, period) { var year = inst.drawYear + (period == 'Y' ? offset : 0); var month = inst.drawMonth + (period == 'M' ? offset : 0); var day = Math.min(inst.selectedDay, this._getDaysInMonth(year, month)) + (period == 'D' ? offset : 0); var date = this._restrictMinMax(inst, this._daylightSavingAdjust(new Date(year, month, day))); inst.selectedDay = date.getDate(); inst.drawMonth = inst.selectedMonth = date.getMonth(); inst.drawYear = inst.selectedYear = date.getFullYear(); if (period == 'M' || period == 'Y') this._notifyChange(inst); }, /* Ensure a date is within any min/max bounds. */ _restrictMinMax: function(inst, date) { var minDate = this._getMinMaxDate(inst, 'min'); var maxDate = this._getMinMaxDate(inst, 'max'); var newDate = (minDate && date < minDate ? minDate : date); newDate = (maxDate && newDate > maxDate ? maxDate : newDate); return newDate; }, /* Notify change of month/year. */ _notifyChange: function(inst) { var onChange = this._get(inst, 'onChangeMonthYear'); if (onChange) onChange.apply((inst.input ? inst.input[0] : null), [inst.selectedYear, inst.selectedMonth + 1, inst]); }, /* Determine the number of months to show. */ _getNumberOfMonths: function(inst) { var numMonths = this._get(inst, 'numberOfMonths'); return (numMonths == null ? [1, 1] : (typeof numMonths == 'number' ? [1, numMonths] : numMonths)); }, /* Determine the current maximum date - ensure no time components are set. */ _getMinMaxDate: function(inst, minMax) { return this._determineDate(inst, this._get(inst, minMax + 'Date'), null); }, /* Find the number of days in a given month. */ _getDaysInMonth: function(year, month) { return 32 - this._daylightSavingAdjust(new Date(year, month, 32)).getDate(); }, /* Find the day of the week of the first of a month. */ _getFirstDayOfMonth: function(year, month) { return new Date(year, month, 1).getDay(); }, /* Determines if we should allow a "next/prev" month display change. */ _canAdjustMonth: function(inst, offset, curYear, curMonth) { var numMonths = this._getNumberOfMonths(inst); var date = this._daylightSavingAdjust(new Date(curYear, curMonth + (offset < 0 ? offset : numMonths[0] * numMonths[1]), 1)); if (offset < 0) date.setDate(this._getDaysInMonth(date.getFullYear(), date.getMonth())); return this._isInRange(inst, date); }, /* Is the given date in the accepted range? */ _isInRange: function(inst, date) { var minDate = this._getMinMaxDate(inst, 'min'); var maxDate = this._getMinMaxDate(inst, 'max'); return ((!minDate || date.getTime() >= minDate.getTime()) && (!maxDate || date.getTime() <= maxDate.getTime())); }, /* Provide the configuration settings for formatting/parsing. */ _getFormatConfig: function(inst) { var shortYearCutoff = this._get(inst, 'shortYearCutoff'); shortYearCutoff = (typeof shortYearCutoff != 'string' ? shortYearCutoff : new Date().getFullYear() % 100 + parseInt(shortYearCutoff, 10)); return {shortYearCutoff: shortYearCutoff, dayNamesShort: this._get(inst, 'dayNamesShort'), dayNames: this._get(inst, 'dayNames'), monthNamesShort: this._get(inst, 'monthNamesShort'), monthNames: this._get(inst, 'monthNames')}; }, /* Format the given date for display. */ _formatDate: function(inst, day, month, year) { if (!day) { inst.currentDay = inst.selectedDay; inst.currentMonth = inst.selectedMonth; inst.currentYear = inst.selectedYear; } var date = (day ? (typeof day == 'object' ? day : this._daylightSavingAdjust(new Date(year, month, day))) : this._daylightSavingAdjust(new Date(inst.currentYear, inst.currentMonth, inst.currentDay))); return this.formatDate(this._get(inst, 'dateFormat'), date, this._getFormatConfig(inst)); } }); /* * Bind hover events for datepicker elements. * Done via delegate so the binding only occurs once in the lifetime of the parent div. * Global instActive, set by _updateDatepicker allows the handlers to find their way back to the active picker. */ function bindHover(dpDiv) { var selector = 'button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a'; return dpDiv.bind('mouseout', function(event) { var elem = $( event.target ).closest( selector ); if ( !elem.length ) { return; } elem.removeClass( "ui-state-hover ui-datepicker-prev-hover ui-datepicker-next-hover" ); }) .bind('mouseover', function(event) { var elem = $( event.target ).closest( selector ); if ($.datepicker._isDisabledDatepicker( instActive.inline ? dpDiv.parent()[0] : instActive.input[0]) || !elem.length ) { return; } elem.parents('.ui-datepicker-calendar').find('a').removeClass('ui-state-hover'); elem.addClass('ui-state-hover'); if (elem.hasClass('ui-datepicker-prev')) elem.addClass('ui-datepicker-prev-hover'); if (elem.hasClass('ui-datepicker-next')) elem.addClass('ui-datepicker-next-hover'); }); } /* jQuery extend now ignores nulls! */ function extendRemove(target, props) { $.extend(target, props); for (var name in props) if (props[name] == null || props[name] == undefined) target[name] = props[name]; return target; }; /* Determine whether an object is an array. */ function isArray(a) { return (a && (($.browser.safari && typeof a == 'object' && a.length) || (a.constructor && a.constructor.toString().match(/\Array\(\)/)))); }; /* Invoke the datepicker functionality. @param options string - a command, optionally followed by additional parameters or Object - settings for attaching new datepicker functionality @return jQuery object */ $.fn.datepicker = function(options){ /* Verify an empty collection wasn't passed - Fixes #6976 */ if ( !this.length ) { return this; } /* Initialise the date picker. */ if (!$.datepicker.initialized) { $(document).mousedown($.datepicker._checkExternalClick). find('body').append($.datepicker.dpDiv); $.datepicker.initialized = true; } var otherArgs = Array.prototype.slice.call(arguments, 1); if (typeof options == 'string' && (options == 'isDisabled' || options == 'getDate' || options == 'widget')) return $.datepicker['_' + options + 'Datepicker']. apply($.datepicker, [this[0]].concat(otherArgs)); if (options == 'option' && arguments.length == 2 && typeof arguments[1] == 'string') return $.datepicker['_' + options + 'Datepicker']. apply($.datepicker, [this[0]].concat(otherArgs)); return this.each(function() { typeof options == 'string' ? $.datepicker['_' + options + 'Datepicker']. apply($.datepicker, [this].concat(otherArgs)) : $.datepicker._attachDatepicker(this, options); }); }; $.datepicker = new Datepicker(); // singleton instance $.datepicker.initialized = false; $.datepicker.uuid = new Date().getTime(); $.datepicker.version = "1.8.24"; // Workaround for #4055 // Add another global to avoid noConflict issues with inline event handlers window['DP_jQuery_' + dpuuid] = $; })(jQuery); return module.exports; }).call(this); // src/js/aui/date-picker.js (typeof window === 'undefined' ? global : window).__3ae5ebef5a8a8e3966bd34269cda1292 = (function () { var module = { exports: {} }; var exports = module.exports; 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _jquery = __ce09c80fb835cb76cda82f0f0d4a1ea3; var _jquery2 = _interopRequireDefault(_jquery); __e655bb43386f55b60b05dd9efffb834d; var _log = __5cedb2bf0c96530c8ee1c2fdf05590cb; var logger = _interopRequireWildcard(_log); var _browser = __be1f1b4b3186372d22f47d92fb181b20; var _globalize = __2bc1a6edbc312083fbf11f878f780e28; var _globalize2 = _interopRequireDefault(_globalize); var _inlineDialog = __7c1d4371a15e5f9e83dad7086d95ab8c; var _inlineDialog2 = _interopRequireDefault(_inlineDialog); var _keyCode = __4850ac7f6e93ba35f83ca6803a088772; var _keyCode2 = _interopRequireDefault(_keyCode); var _i18n = __6e5c1a3f5afadc2fe31a54c52b7091ab; var _i18n2 = _interopRequireDefault(_i18n); 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; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var datePickerCounter = 0; function DatePicker(field, options) { var datePicker; var initPolyfill; var $field; var datePickerUUID; var parentPopup; datePicker = {}; datePickerUUID = datePickerCounter++; // --------------------------------------------------------------------- // fix up arguments ---------------------------------------------------- // --------------------------------------------------------------------- $field = (0, _jquery2.default)(field); $field.attr('data-aui-dp-uuid', datePickerUUID); options = _jquery2.default.extend(undefined, DatePicker.prototype.defaultOptions, options); // --------------------------------------------------------------------- // expose arguments with getters --------------------------------------- // --------------------------------------------------------------------- datePicker.getField = function () { return $field; }; datePicker.getOptions = function () { return options; }; // --------------------------------------------------------------------- // exposed methods ----------------------------------------------------- // --------------------------------------------------------------------- initPolyfill = function initPolyfill() { var calendar; var handleDatePickerFocus; var handleFieldBlur; var handleFieldFocus; var handleFieldUpdate; var initCalendar; var isSuppressingShow; var isTrackingDatePickerFocus; var popup; var popupContents; // ----------------------------------------------------------------- // expose methods for controlling the popup ------------------------ // ----------------------------------------------------------------- datePicker.hide = function () { popup.hide(); }; datePicker.show = function () { popup.show(); }; datePicker.setDate = function (value) { if (typeof calendar !== 'undefined') { calendar.datepicker('setDate', value); } }; datePicker.getDate = function () { if (typeof calendar !== 'undefined') { return calendar.datepicker('getDate'); } }; // ----------------------------------------------------------------- // initialise the calendar ----------------------------------------- // ----------------------------------------------------------------- initCalendar = function initCalendar(i18nConfig) { popupContents.off(); if (options.hint) { var $hint = (0, _jquery2.default)('<div/>').addClass('aui-datepicker-hint'); $hint.append('<span/>').text(options.hint); popupContents.append($hint); } calendar = (0, _jquery2.default)('<div/>'); calendar.attr('data-aui-dp-popup-uuid', datePickerUUID); popupContents.append(calendar); var config = { 'dateFormat': options.dateFormat, 'defaultDate': $field.val(), 'maxDate': $field.attr('max'), 'minDate': $field.attr('min'), 'nextText': '>', 'onSelect': function onSelect(dateText) { $field.val(dateText); $field.change(); datePicker.hide(); isSuppressingShow = true; $field.focus(); options.onSelect && options.onSelect.call(this, dateText); }, onChangeMonthYear: function onChangeMonthYear() { // defer rehresh call until current stack has cleared (after month has rendered) setTimeout(popup.refresh, 0); }, 'prevText': '<' }; _jquery2.default.extend(config, i18nConfig); if (options.firstDay > -1) { config.firstDay = options.firstDay; } if (typeof $field.attr('step') !== 'undefined') { logger.log('WARNING: The date picker polyfill currently does not support the step attribute!'); } calendar.datepicker(config); // bind additional field processing events (0, _jquery2.default)('body').on('keydown', handleDatePickerFocus); $field.on('focusout keydown', handleFieldBlur); $field.on('propertychange keyup input paste', handleFieldUpdate); }; // ----------------------------------------------------------------- // event handler wrappers ------------------------------------------ // ----------------------------------------------------------------- handleDatePickerFocus = function handleDatePickerFocus(event) { var $eventTarget = (0, _jquery2.default)(event.target); var isTargetInput = $eventTarget.closest(popupContents).length || $eventTarget.is($field); var isTargetPopup = $eventTarget.closest('.ui-datepicker-header').length; // Hide if we're clicking anywhere else but the input or popup OR if esc is pressed. if (!isTargetInput && !isTargetPopup || event.keyCode === _keyCode2.default.ESCAPE) { datePicker.hide(); return; } if ($eventTarget[0] !== $field[0]) { event.preventDefault(); } }; handleFieldBlur = function handleFieldBlur() { // Trigger blur if event is keydown and esc OR is focusout. if (!isTrackingDatePickerFocus) { (0, _jquery2.default)('body').on('focus blur click mousedown', '*', handleDatePickerFocus); isTrackingDatePickerFocus = true; } }; handleFieldFocus = function handleFieldFocus() { if (!isSuppressingShow) { datePicker.show(); } else { isSuppressingShow = false; } }; handleFieldUpdate = function handleFieldUpdate() { var val = (0, _jquery2.default)(this).val(); // IE10/11 fire the 'input' event when internally showing and hiding // the placeholder of an input. This was cancelling the inital click // event and preventing the selection of the first date. The val check here // is a workaround to assure we have legitimate user input that should update // the calendar if (val) { calendar.datepicker('setDate', $field.val()); calendar.datepicker('option', { 'maxDate': $field.attr('max'), 'minDate': $field.attr('min') }); } }; // ----------------------------------------------------------------- // undo (almost) everything ---------------------------------------- // ----------------------------------------------------------------- datePicker.destroyPolyfill = function () { // goodbye, cruel world! datePicker.hide(); $field.attr('placeholder', null); $field.off('propertychange keyup input paste', handleFieldUpdate); $field.off('focus click', handleFieldFocus); $field.off('focusout keydown', handleFieldBlur); (0, _jquery2.default)('body').off('keydown', handleFieldBlur); if (DatePicker.prototype.browserSupportsDateField) { $field[0].type = 'date'; } if (typeof calendar !== 'undefined') { calendar.datepicker('destroy'); } // TODO: figure out a way to tear down the popup (if necessary) delete datePicker.destroyPolyfill; delete datePicker.show; delete datePicker.hide; }; // ----------------------------------------------------------------- // polyfill bootstrap ---------------------------------------------- // ----------------------------------------------------------------- isSuppressingShow = false; // used to stop the popover from showing when focus is restored to the field after a date has been selected isTrackingDatePickerFocus = false; // used to prevent multiple bindings of handleDatePickerFocus within handleFieldBlur if (!(options.languageCode in DatePicker.prototype.localisations)) { options.languageCode = ''; } var i18nConfig = DatePicker.prototype.localisations; var containerClass = ''; var width = 240; if (i18nConfig.size === 'large') { width = 325; containerClass = 'aui-datepicker-dialog-large'; } var dialogOptions = { 'hideCallback': function hideCallback() { (0, _jquery2.default)('body').off('focus blur click mousedown', '*', handleDatePickerFocus); isTrackingDatePickerFocus = false; if (parentPopup && parentPopup._datePickerPopup) { delete parentPopup._datePickerPopup; } }, 'hideDelay': null, 'noBind': true, 'persistent': true, 'closeOthers': false, 'width': width }; if (options.position) { dialogOptions.calculatePositions = function (popup, targetPosition) { // create a jQuery object from the internal var vanilla = (0, _jquery2.default)(popup[0]); return options.position.call(this, vanilla, targetPosition); }; } popup = (0, _inlineDialog2.default)($field, undefined, function (contents, trigger, showPopup) { if (typeof calendar === 'undefined') { popupContents = contents; initCalendar(i18nConfig); } parentPopup = (0, _jquery2.default)(trigger).closest('.aui-inline-dialog').get(0); if (parentPopup) { parentPopup._datePickerPopup = popup; // AUI-2696 - hackish coupling to control inline-dialog close behaviour. } showPopup(); }, dialogOptions); popup.addClass('aui-datepicker-dialog'); popup.addClass(containerClass); // bind what we need to start off with $field.on('focus click', handleFieldFocus); // the click is for fucking opera... Y U NO FIRE FOCUS EVENTS PROPERLY??? // give users a hint that this is a date field; note that placeholder isn't technically a valid attribute // according to the spec... $field.attr('placeholder', options.dateFormat); // override the browser's default date field implementation (if applicable) // since IE doesn't support date input fields, we should be fine... if (options.overrideBrowserDefault && DatePicker.prototype.browserSupportsDateField) { $field[0].type = 'text'; //workaround for this issue in Edge: https://connect.microsoft.com/IE/feedback/details/1603512/changing-an-input-type-to-text-does-not-set-the-value var value = $field[0].getAttribute('value'); //can't use jquery to get the attribute because it doesn't work in Edge if (value) { $field[0].value = value; } } }; datePicker.reset = function () { if (typeof datePicker.destroyPolyfill === 'function') { datePicker.destroyPolyfill(); } if (!DatePicker.prototype.browserSupportsDateField || options.overrideBrowserDefault) { initPolyfill(); } }; // --------------------------------------------------------------------- // bootstrap ----------------------------------------------------------- // --------------------------------------------------------------------- datePicker.reset(); return datePicker; }; // ------------------------------------------------------------------------- // things that should be common -------------------------------------------- // ------------------------------------------------------------------------- DatePicker.prototype.browserSupportsDateField = (0, _browser.supportsDateField)(); DatePicker.prototype.defaultOptions = { overrideBrowserDefault: false, firstDay: -1, languageCode: (0, _jquery2.default)('html').attr('lang') || 'en-AU', dateFormat: _jquery2.default.datepicker.W3C // same as $.datepicker.ISO_8601 }; // adapted from the jQuery UI Datepicker widget (v1.8.16), with the following changes: // - dayNamesShort -> dayNamesMin // - unnecessary attributes omitted /* CODE to extract codes out: var langCode, langs, out; langs = jQuery.datepicker.regional; out = {}; for (langCode in langs) { if (langs.hasOwnProperty(langCode)) { out[langCode] = { 'dayNames': langs[langCode].dayNames, 'dayNamesMin': langs[langCode].dayNamesShort, // this is deliberate 'firstDay': langs[langCode].firstDay, 'isRTL': langs[langCode].isRTL, 'monthNames': langs[langCode].monthNames, 'showMonthAfterYear': langs[langCode].showMonthAfterYear, 'yearSuffix': langs[langCode].yearSuffix }; } } */ DatePicker.prototype.localisations = { "dayNames": [_i18n2.default.getText('ajs.datepicker.localisations.day-names.sunday'), _i18n2.default.getText('ajs.datepicker.localisations.day-names.monday'), _i18n2.default.getText('ajs.datepicker.localisations.day-names.tuesday'), _i18n2.default.getText('ajs.datepicker.localisations.day-names.wednesday'), _i18n2.default.getText('ajs.datepicker.localisations.day-names.thursday'), _i18n2.default.getText('ajs.datepicker.localisations.day-names.friday'), _i18n2.default.getText('ajs.datepicker.localisations.day-names.saturday')], "dayNamesMin": [_i18n2.default.getText('ajs.datepicker.localisations.day-names-min.sunday'), _i18n2.default.getText('ajs.datepicker.localisations.day-names-min.monday'), _i18n2.default.getText('ajs.datepicker.localisations.day-names-min.tuesday'), _i18n2.default.getText('ajs.datepicker.localisations.day-names-min.wednesday'), _i18n2.default.getText('ajs.datepicker.localisations.day-names-min.thursday'), _i18n2.default.getText('ajs.datepicker.localisations.day-names-min.friday'), _i18n2.default.getText('ajs.datepicker.localisations.day-names-min.saturday')], "firstDay": _i18n2.default.getText('ajs.datepicker.localisations.first-day'), "isRTL": _i18n2.default.getText('ajs.datepicker.localisations.is-RTL') === "true" ? true : false, "monthNames": [_i18n2.default.getText('ajs.datepicker.localisations.month-names.january'), _i18n2.default.getText('ajs.datepicker.localisations.month-names.february'), _i18n2.default.getText('ajs.datepicker.localisations.month-names.march'), _i18n2.default.getText('ajs.datepicker.localisations.month-names.april'), _i18n2.default.getText('ajs.datepicker.localisations.month-names.may'), _i18n2.default.getText('ajs.datepicker.localisations.month-names.june'), _i18n2.default.getText('ajs.datepicker.localisations.month-names.july'), _i18n2.default.getText('ajs.datepicker.localisations.month-names.august'), _i18n2.default.getText('ajs.datepicker.localisations.month-names.september'), _i18n2.default.getText('ajs.datepicker.localisations.month-names.october'), _i18n2.default.getText('ajs.datepicker.localisations.month-names.november'), _i18n2.default.getText('ajs.datepicker.localisations.month-names.december')], "showMonthAfterYear": _i18n2.default.getText('ajs.datepicker.localisations.show-month-after-year') === "true" ? true : false, "yearSuffix": _i18n2.default.getText('ajs.datepicker.localisations.year-suffix') // ------------------------------------------------------------------------- // finally, integrate with jQuery for convenience -------------------------- // ------------------------------------------------------------------------- };_jquery2.default.fn.datePicker = function (options) { return new DatePicker(this, options); }; (0, _globalize2.default)('DatePicker', DatePicker); exports.default = DatePicker; module.exports = exports['default']; return module.exports; }).call(this); // src/js/aui-datepicker.js (typeof window === 'undefined' ? global : window).__021750f2eb4bbcc8daf658a0fb718d85 = (function () { var module = { exports: {} }; var exports = module.exports; 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); __3ae5ebef5a8a8e3966bd34269cda1292; exports.default = window.AJS; module.exports = exports['default']; return module.exports; }).call(this);
/** * @license Highcharts JS v9.0.1 (2021-02-16) * @module highcharts/modules/cylinder * @requires highcharts * @requires highcharts/highcharts-3d * * Highcharts cylinder module * * (c) 2010-2021 Kacper Madej * * License: www.highcharts.com/license */ 'use strict'; import '../../Series/Cylinder/CylinderSeries.js';
/** @license React vundefined * react.profiling.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ (function(){'use strict';(function(c,y){"object"===typeof exports&&"undefined"!==typeof module?y(exports):"function"===typeof define&&define.amd?define(["exports"],y):(c=c||self,y(c.React={}))})(this,function(c){function y(a){if(null===a||"object"!==typeof a)return null;a=W&&a[W]||a["@@iterator"];return"function"===typeof a?a:null}function w(a,b,g){this.props=a;this.context=b;this.refs=X;this.updater=g||Y}function Z(){}function K(a,b,g){this.props=a;this.context=b;this.refs=X;this.updater=g||Y}function aa(a, b,g){var l,e={},c=null,k=null;if(null!=b)for(l in void 0!==b.ref&&(k=b.ref),void 0!==b.key&&(c=""+b.key),b)ba.call(b,l)&&!ca.hasOwnProperty(l)&&(e[l]=b[l]);var p=arguments.length-2;if(1===p)e.children=g;else if(1<p){for(var h=Array(p),d=0;d<p;d++)h[d]=arguments[d+2];e.children=h}if(a&&a.defaultProps)for(l in p=a.defaultProps,p)void 0===e[l]&&(e[l]=p[l]);return{$$typeof:x,type:a,key:c,ref:k,props:e,_owner:L.current}}function ta(a,b){return{$$typeof:x,type:a.type,key:b,ref:a.ref,props:a.props,_owner:a._owner}} function M(a){return"object"===typeof a&&null!==a&&a.$$typeof===x}function ua(a){var b={"=":"=0",":":"=2"};return"$"+a.replace(/[=:]/g,function(a){return b[a]})}function N(a,b){return"object"===typeof a&&null!==a&&null!=a.key?ua(""+a.key):b.toString(36)}function B(a,b,g,l,e){var c=typeof a;if("undefined"===c||"boolean"===c)a=null;var k=!1;if(null===a)k=!0;else switch(c){case "string":case "number":k=!0;break;case "object":switch(a.$$typeof){case x:case da:k=!0}}if(k)return k=a,e=e(k),a=""===l?"."+ N(k,0):l,ea(e)?(g="",null!=a&&(g=a.replace(fa,"$&/")+"/"),B(e,b,g,"",function(a){return a})):null!=e&&(M(e)&&(e=ta(e,g+(!e.key||k&&k.key===e.key?"":(""+e.key).replace(fa,"$&/")+"/")+a)),b.push(e)),1;k=0;l=""===l?".":l+":";if(ea(a))for(var d=0;d<a.length;d++){c=a[d];var h=l+N(c,d);k+=B(c,b,g,h,e)}else if(h=y(a),"function"===typeof h)for(a=h.call(a),d=0;!(c=a.next()).done;)c=c.value,h=l+N(c,d++),k+=B(c,b,g,h,e);else if("object"===c)throw b=String(a),Error("Objects are not valid as a React child (found: "+ ("[object Object]"===b?"object with keys {"+Object.keys(a).join(", ")+"}":b)+"). If you meant to render a collection of children, use an array instead.");return k}function C(a,b,g){if(null==a)return a;var c=[],e=0;B(a,c,"","",function(a){return b.call(g,a,e++)});return c}function va(a){if(-1===a._status){var b=a._result;b=b();b.then(function(b){if(0===a._status||-1===a._status)a._status=1,a._result=b},function(b){if(0===a._status||-1===a._status)a._status=2,a._result=b});-1===a._status&&(a._status= 0,a._result=b)}if(1===a._status)return a._result.default;throw a._result;}function O(a,b){var g=a.length;a.push(b);a:for(;0<g;){var c=g-1>>>1,e=a[c];if(0<D(e,b))a[c]=b,a[g]=e,g=c;else break a}}function q(a){return 0===a.length?null:a[0]}function E(a){if(0===a.length)return null;var b=a[0],g=a.pop();if(g!==b){a[0]=g;a:for(var c=0,e=a.length,d=e>>>1;c<d;){var k=2*(c+1)-1,p=a[k],h=k+1,f=a[h];if(0>D(p,g))h<e&&0>D(f,p)?(a[c]=f,a[h]=g,c=h):(a[c]=p,a[k]=g,c=k);else if(h<e&&0>D(f,g))a[c]=f,a[h]=g,c=h;else break a}}return b} function D(a,b){var c=a.sortIndex-b.sortIndex;return 0!==c?c:a.id-b.id}function P(a){for(var b=q(t);null!==b;){if(null===b.callback)E(t);else if(b.startTime<=a)E(t),b.sortIndex=b.expirationTime,O(r,b);else break;b=q(t)}}function Q(a){z=!1;P(a);if(!u)if(null!==q(r))u=!0,R(S);else{var b=q(t);null!==b&&T(Q,b.startTime-a)}}function S(a,b){u=!1;z&&(z=!1,ha(A),A=-1);F=!0;var c=f;try{P(b);for(n=q(r);null!==n&&(!(n.expirationTime>b)||a&&!ia());){var l=n.callback;if("function"===typeof l){n.callback=null; f=n.priorityLevel;var e=l(n.expirationTime<=b);b=v();"function"===typeof e?n.callback=e:n===q(r)&&E(r);P(b)}else E(r);n=q(r)}if(null!==n)var d=!0;else{var k=q(t);null!==k&&T(Q,k.startTime-b);d=!1}return d}finally{n=null,f=c,F=!1}}function ia(){return v()-ja<ka?!1:!0}function R(a){G=a;H||(H=!0,I())}function T(a,b){A=la(function(){a(v())},b)}var x=60103,da=60106;c.Fragment=60107;c.StrictMode=60108;c.Profiler=60114;var ma=60109,na=60110,oa=60112;c.Suspense=60113;var pa=60115,qa=60116;if("function"=== typeof Symbol&&Symbol.for){var d=Symbol.for;x=d("react.element");da=d("react.portal");c.Fragment=d("react.fragment");c.StrictMode=d("react.strict_mode");c.Profiler=d("react.profiler");ma=d("react.provider");na=d("react.context");oa=d("react.forward_ref");c.Suspense=d("react.suspense");pa=d("react.memo");qa=d("react.lazy")}var W="function"===typeof Symbol&&Symbol.iterator,wa=Object.prototype.hasOwnProperty,U=Object.assign||function(a,b){if(null==a)throw new TypeError("Object.assign target cannot be null or undefined"); for(var c=Object(a),d=1;d<arguments.length;d++){var e=arguments[d];if(null!=e){var f=void 0;e=Object(e);for(f in e)wa.call(e,f)&&(c[f]=e[f])}}return c},Y={isMounted:function(a){return!1},enqueueForceUpdate:function(a,b,c){},enqueueReplaceState:function(a,b,c,d){},enqueueSetState:function(a,b,c,d){}},X={};w.prototype.isReactComponent={};w.prototype.setState=function(a,b){if("object"!==typeof a&&"function"!==typeof a&&null!=a)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables."); this.updater.enqueueSetState(this,a,b,"setState")};w.prototype.forceUpdate=function(a){this.updater.enqueueForceUpdate(this,a,"forceUpdate")};Z.prototype=w.prototype;d=K.prototype=new Z;d.constructor=K;U(d,w.prototype);d.isPureReactComponent=!0;var ea=Array.isArray,ba=Object.prototype.hasOwnProperty,L={current:null},ca={key:!0,ref:!0,__self:!0,__source:!0},fa=/\/+/g,m={current:null},J={transition:0};if("object"===typeof performance&&"function"===typeof performance.now){var xa=performance;var v=function(){return xa.now()}}else{var ra= Date,ya=ra.now();v=function(){return ra.now()-ya}}var r=[],t=[],za=1,n=null,f=3,F=!1,u=!1,z=!1,la="function"===typeof setTimeout?setTimeout:null,ha="function"===typeof clearTimeout?clearTimeout:null,sa="undefined"!==typeof setImmediate?setImmediate:null;"undefined"!==typeof navigator&&void 0!==navigator.scheduling&&void 0!==navigator.scheduling.isInputPending&&navigator.scheduling.isInputPending.bind(navigator.scheduling);var H=!1,G=null,A=-1,ka=5,ja=-1,V=function(){if(null!==G){var a=v();ja=a;var b= !0;try{b=G(!0,a)}finally{b?I():(H=!1,G=null)}}else H=!1};if("function"===typeof sa)var I=function(){sa(V)};else if("undefined"!==typeof MessageChannel){d=new MessageChannel;var Aa=d.port2;d.port1.onmessage=V;I=function(){Aa.postMessage(null)}}else I=function(){la(V,0)};d={ReactCurrentDispatcher:m,ReactCurrentOwner:L,ReactCurrentBatchConfig:J,assign:U,Scheduler:{__proto__:null,unstable_ImmediatePriority:1,unstable_UserBlockingPriority:2,unstable_NormalPriority:3,unstable_IdlePriority:5,unstable_LowPriority:4, unstable_runWithPriority:function(a,b){switch(a){case 1:case 2:case 3:case 4:case 5:break;default:a=3}var c=f;f=a;try{return b()}finally{f=c}},unstable_next:function(a){switch(f){case 1:case 2:case 3:var b=3;break;default:b=f}var c=f;f=b;try{return a()}finally{f=c}},unstable_scheduleCallback:function(a,b,c){var d=v();"object"===typeof c&&null!==c?(c=c.delay,c="number"===typeof c&&0<c?d+c:d):c=d;switch(a){case 1:var e=-1;break;case 2:e=250;break;case 5:e=1073741823;break;case 4:e=1E4;break;default:e= 5E3}e=c+e;a={id:za++,callback:b,priorityLevel:a,startTime:c,expirationTime:e,sortIndex:-1};c>d?(a.sortIndex=c,O(t,a),null===q(r)&&a===q(t)&&(z?(ha(A),A=-1):z=!0,T(Q,c-d))):(a.sortIndex=e,O(r,a),u||F||(u=!0,R(S)));return a},unstable_cancelCallback:function(a){a.callback=null},unstable_wrapCallback:function(a){var b=f;return function(){var c=f;f=b;try{return a.apply(this,arguments)}finally{f=c}}},unstable_getCurrentPriorityLevel:function(){return f},unstable_shouldYield:ia,unstable_requestPaint:function(){}, unstable_continueExecution:function(){u||F||(u=!0,R(S))},unstable_pauseExecution:function(){},unstable_getFirstCallbackNode:function(){return q(r)},get unstable_now(){return v},unstable_forceFrameRate:function(a){0>a||125<a?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):ka=0<a?Math.floor(1E3/a):5},unstable_Profiling:null}};c.Children={map:C,forEach:function(a,b,c){C(a,function(){b.apply(this,arguments)},c)},count:function(a){var b= 0;C(a,function(){b++});return b},toArray:function(a){return C(a,function(a){return a})||[]},only:function(a){if(!M(a))throw Error("React.Children.only expected to receive a single React element child.");return a}};c.Component=w;c.PureComponent=K;c.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=d;c.cloneElement=function(a,b,c){if(null===a||void 0===a)throw Error("React.cloneElement(...): The argument must be a React element, but you passed "+a+".");var d=U({},a.props),e=a.key,g=a.ref,k=a._owner; if(null!=b){void 0!==b.ref&&(g=b.ref,k=L.current);void 0!==b.key&&(e=""+b.key);if(a.type&&a.type.defaultProps)var f=a.type.defaultProps;for(h in b)ba.call(b,h)&&!ca.hasOwnProperty(h)&&(d[h]=void 0===b[h]&&void 0!==f?f[h]:b[h])}var h=arguments.length-2;if(1===h)d.children=c;else if(1<h){f=Array(h);for(var m=0;m<h;m++)f[m]=arguments[m+2];d.children=f}return{$$typeof:x,type:a.type,key:e,ref:g,props:d,_owner:k}};c.createContext=function(a){a={$$typeof:na,_currentValue:a,_currentValue2:a,_threadCount:0, Provider:null,Consumer:null};a.Provider={$$typeof:ma,_context:a};return a.Consumer=a};c.createElement=aa;c.createFactory=function(a){var b=aa.bind(null,a);b.type=a;return b};c.createRef=function(){return{current:null}};c.forwardRef=function(a){return{$$typeof:oa,render:a}};c.isValidElement=M;c.lazy=function(a){return{$$typeof:qa,_payload:{_status:-1,_result:a},_init:va}};c.memo=function(a,b){return{$$typeof:pa,type:a,compare:void 0===b?null:b}};c.startTransition=function(a){var b=J.transition;J.transition= 1;try{a()}finally{J.transition=b}};c.unstable_act=function(a){throw Error("act(...) is not supported in production builds of React.");};c.unstable_createMutableSource=function(a,b){return{_getVersion:b,_source:a,_workInProgressVersionPrimary:null,_workInProgressVersionSecondary:null}};c.useCallback=function(a,b){return m.current.useCallback(a,b)};c.useContext=function(a){return m.current.useContext(a)};c.useDebugValue=function(a,b){};c.useDeferredValue=function(a){return m.current.useDeferredValue(a)}; c.useEffect=function(a,b){return m.current.useEffect(a,b)};c.useId=function(){return m.current.useId()};c.useImperativeHandle=function(a,b,c){return m.current.useImperativeHandle(a,b,c)};c.useInsertionEffect=function(a,b){return m.current.useInsertionEffect(a,b)};c.useLayoutEffect=function(a,b){return m.current.useLayoutEffect(a,b)};c.useMemo=function(a,b){return m.current.useMemo(a,b)};c.useReducer=function(a,b,c){return m.current.useReducer(a,b,c)};c.useRef=function(a){return m.current.useRef(a)}; c.useState=function(a){return m.current.useState(a)};c.useSyncExternalStore=function(a,b,c){return m.current.useSyncExternalStore(a,b,c)};c.useTransition=function(){return m.current.useTransition()};c.version="18.0.0-rc.0-575791925-20211213"}); })();
'use strict'; /** ******************************* * 加载依赖 ******************************* */ const fs = require('fs'), path = require('path'), stat = require('./stat'); /** ******************************* * 定义软链接方法 ******************************* */ function symlink(src, dist, files) { // 遍历需要链接的文件 files.length && files.forEach(async function(file) { // 获取输入、输出路径 let srcFile = path.resolve(src, file), distFile = path.resolve(dist, file), stats = await stat(distFile); // 输出关联目录 console.log(`==> ${srcFile} : ${distFile}`); // 不存在目标文件时,直接创建链接 if (!stats) { return fs.symlink(srcFile, distFile, err => err && console.error(err)); } // 删除目标文件 fs.unlink(distFile, err => { // 输出错误信息 if (err) { return console.error(err); } // 生成软链接 fs.symlink(srcFile, distFile, err => err && console.error(err)); }); }); } /** ******************************* * 抛出接口 ******************************* */ module.exports = symlink;
'use strict'; var inherits = require('inherits'); var $ = require('bitcore-lib').util.preconditions; var Script = require('bitcore-lib').Script; var Transaction = require('bitcore-lib').Transaction; var _ = require('bitcore-lib').deps._; /** * A commitment transaction (also referred to as Lock transaction). * * @constructor * @param {Object} opts * @param {Array.<string>} opts.publicKeys * @param {string|bitcore.Network} opts.network - livenet by default */ function Commitment(opts) { $.checkArgument(opts.publicKeys && opts.publicKeys.length === 2, 'Must provide exactly two public keys'); Transaction.call(this, opts.transaction); this.network = opts.network || 'livenet'; this.publicKeys = opts.publicKeys; this.outscript = Script.buildMultisigOut(this.publicKeys, 2); this.address = this.outscript.toScriptHashOut().toAddress(); if (!this.outputs.length) { this.change(this.address); } Object.defineProperty(this, 'amount', { configurable: false, get: function() { return this.inputAmount; } }); } inherits(Commitment, Transaction); Commitment.prototype.toObject = function() { var transaction = Transaction.prototype.toObject.apply(this); return { transaction: transaction, publicKeys: _.map(this.publicKeys, function(publicKey) { return publicKey.toString(); }), network: this.network.toString(), }; }; /** * @return {bitcore.Address} */ Commitment.prototype.getAddress = function() { return this.address; }; module.exports = Commitment;
/* * Copyright (C) 2012 David Geary. This code is from the book * Core HTML5 Canvas, published by Prentice-Hall in 2012. * * License: * * 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 may not be used to create training material of any sort, * including courses, books, instructional videos, presentations, etc. * without the express written consent of David Geary. * * 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. */ // Functions..................................................... // .............................................................. // Check to see if a polygon collides with another polygon // .............................................................. function polygonCollidesWithPolygon (p1, p2, displacement) { // displacement for p1 var mtv1 = p1.minimumTranslationVector(p1.getAxes(), p2, displacement), mtv2 = p1.minimumTranslationVector(p2.getAxes(), p2, displacement); if (mtv1.overlap === 0 || mtv2.overlap === 0) return { axis: undefined, overlap: 0 }; else return mtv1.overlap < mtv2.overlap ? mtv1 : mtv2; }; // .............................................................. // Check to see if a circle collides with another circle // .............................................................. function circleCollidesWithCircle (c1, c2) { var distance = Math.sqrt( Math.pow(c2.x - c1.x, 2) + Math.pow(c2.y - c1.y, 2)), overlap = Math.abs(c1.radius + c2.radius) - distance; return overlap < 0 ? new MinimumTranslationVector(undefined, 0) : new MinimumTranslationVector(undefined, overlap); }; // .............................................................. // Get the polygon's point that's closest to the circle // .............................................................. function getPolygonPointClosestToCircle(polygon, circle) { var min = BIG_NUMBER, length, testPoint, closestPoint; for (var i=0; i < polygon.points.length; ++i) { testPoint = polygon.points[i]; length = Math.sqrt(Math.pow(testPoint.x - circle.x, 2), Math.pow(testPoint.y - circle.y, 2)); if (length < min) { min = length; closestPoint = testPoint; } } return closestPoint; }; // .............................................................. // Get the circle's axis (circle's don't have an axis, so this // method manufactures one) // .............................................................. function getCircleAxis(circle, polygon, closestPoint) { var v1 = new Vector(new Point(circle.x, circle.y)), v2 = new Vector(new Point(closestPoint.x, closestPoint.y)), surfaceVector = v1.subtract(v2); return surfaceVector.normalize(); }; // .............................................................. // Tests to see if a polygon collides with a circle // .............................................................. function polygonCollidesWithCircle (polygon, circle, displacement) { var axes = polygon.getAxes(), closestPoint = getPolygonPointClosestToCircle(polygon, circle); axes.push(getCircleAxis(circle, polygon, closestPoint)); return polygon.minimumTranslationVector(axes, circle, displacement); }; // .............................................................. // Given two shapes, and a set of axes, returns the minimum // translation vector. // .............................................................. function getMTV(shape1, shape2, displacement, axes) { var minimumOverlap = BIG_NUMBER, overlap, axisWithSmallestOverlap, mtv; for (var i=0; i < axes.length; ++i) { axis = axes[i]; projection1 = shape1.project(axis); projection2 = shape2.project(axis); overlap = projection1.getOverlap(projection2); if (overlap === 0) { return new MinimumTranslationVector(undefined, 0); } else { if (overlap < minimumOverlap) { minimumOverlap = overlap; axisWithSmallestOverlap = axis; } } } mtv = new MinimumTranslationVector(axisWithSmallestOverlap, minimumOverlap); return mtv; }; // Constants..................................................... var BIG_NUMBER = 1000000; // Points........................................................ var Point = function (x, y) { this.x = x; this.y = y; }; Point.prototype = { rotate: function (rotationPoint, angle) { var tx, ty, rx, ry; tx = this.x - rotationPoint.x; // tx = translated X ty = this.y - rotationPoint.y; // ty = translated Y rx = tx * Math.cos(-angle) - // rx = rotated X ty * Math.sin(-angle); ry = tx * Math.sin(-angle) + // ry = rotated Y ty * Math.cos(-angle); return new Point(rx + rotationPoint.x, ry + rotationPoint.y); } }; // Lines......................................................... var Line = function(p1, p2) { this.p1 = p1; // point 1 this.p2 = p2; // point 2 } Line.prototype.intersectionPoint = function (line) { var m1, m2, b1, b2, ip = new Point(); if (this.p1.x === this.p2.x) { m2 = (line.p2.y - line.p1.y) / (line.p2.x - line.p1.x); b2 = line.p1.y - m2 * line.p1.x; ip.x = this.p1.x; ip.y = m2 * ip.x + b2; } else if(line.p1.x === line.p2.x) { m1 = (this.p2.y - this.p1.y) / (this.p2.x - this.p1.x); b1 = this.p1.y - m1 * this.p1.x; ip.x = line.p1.x; ip.y = m1 * ip.x + b1; } else { m1 = (this.p2.y - this.p1.y) / (this.p2.x - this.p1.x); m2 = (line.p2.y - line.p1.y) / (line.p2.x - line.p1.x); b1 = this.p1.y - m1 * this.p1.x; b2 = line.p1.y - m2 * line.p1.x; ip.x = (b2 - b1) / (m1 - m2); ip.y = m1 * ip.x + b1; } return ip; }; // Bounding boxes................................................ var BoundingBox = function(left, top, width, height) { this.left = left; this.top = top; this.width = width; this.height = height; }; // Vectors....................................................... var Vector = function(point) { if (point === undefined) { this.x = 0; this.y = 0; } else { this.x = point.x; this.y = point.y; } }; Vector.prototype = { getMagnitude: function () { return Math.sqrt(Math.pow(this.x, 2) + Math.pow(this.y, 2)); }, setMagnitude: function (m) { var uv = this.normalize(); this.x = uv.x * m; this.y = uv.y * m; }, dotProduct: function (vector) { return this.x * vector.x + this.y * vector.y; }, add: function (vector) { var v = new Vector(); v.x = this.x + vector.x; v.y = this.y + vector.y; return v; }, subtract: function (vector) { var v = new Vector(); v.x = this.x - vector.x; v.y = this.y - vector.y; return v; }, normalize: function () { var v = new Vector(), m = this.getMagnitude(); v.x = this.x / m; v.y = this.y / m; return v; }, perpendicular: function () { var v = new Vector(); v.x = this.y; v.y = 0-this.x; return v; }, reflect: function (axis) { var dotProductRatio, vdotl, ldotl, v = new Vector(), vdotl = this.dotProduct(axis), ldotl = axis.dotProduct(axis), dotProductRatio = vdotl / ldotl; v.x = 2 * dotProductRatio * axis.x - this.x; v.y = 2 * dotProductRatio * axis.y - this.y; return v; } }; // Shapes........................................................ var Shape = function () { this.fillStyle = 'rgba(255, 255, 0, 0.8)'; this.strokeStyle = 'white'; }; Shape.prototype = { move: function (dx, dy) { throw 'move(dx, dy) not implemented'; }, createPath: function (context) { throw 'createPath(context) not implemented'; }, boundingBox: function () { throw 'boundingBox() not implemented'; }, fill: function (context) { context.save(); context.fillStyle = this.fillStyle; this.createPath(context); context.fill(); context.restore(); }, stroke: function (context) { context.save(); context.strokeStyle = this.strokeStyle; this.createPath(context); context.stroke(); context.restore(); }, collidesWith: function (shape, displacement) { throw 'collidesWith(shape, displacement) not implemented'; }, isPointInPath: function (context, x, y) { this.createPath(context); return context.isPointInPath(x, y); }, project: function (axis) { throw 'project(axis) not implemented'; }, minimumTranslationVector: function (axes, shape, displacement) { return getMTV(this, shape, displacement, axes); } }; // Circles....................................................... var Circle = function (x, y, radius) { this.x = x; this.y = y; this.radius = radius; this.strokeStyle = 'blue'; this.fillStyle = 'yellow'; } Circle.prototype = new Shape(); Circle.prototype.centroid = function () { return new Point(this.x,this.y); }; Circle.prototype.move = function (dx, dy) { this.x += dx; this.y += dy; }; Circle.prototype.boundingBox = function (dx, dy) { return new BoundingBox(this.x - this.radius, this.y - this.radius, 2*this.radius, 2*this.radius); }; Circle.prototype.createPath = function (context) { context.beginPath(); context.arc(this.x, this.y, this.radius, 0, Math.PI*2, false); }; Circle.prototype.project = function (axis) { var scalars = [], point = new Point(this.x, this.y); dotProduct = new Vector(point).dotProduct(axis); scalars.push(dotProduct); scalars.push(dotProduct + this.radius); scalars.push(dotProduct - this.radius); return new Projection(Math.min.apply(Math, scalars), Math.max.apply(Math, scalars)); }; Circle.prototype.collidesWith = function (shape, displacement) { if (shape.radius === undefined) { return polygonCollidesWithCircle(shape, this, displacement); } else { return circleCollidesWithCircle(this, shape, displacement); } }; // Polygons...................................................... var Polygon = function () { this.points = []; this.strokeStyle = 'blue'; this.fillStyle = 'white'; }; Polygon.prototype = new Shape(); Polygon.prototype.getAxes = function () { var v1, v2, surfaceVector, axes = [], pushAxis = true; for (var i=0; i < this.points.length-1; i++) { v1 = new Vector(this.points[i]); v2 = new Vector(this.points[i+1]); surfaceVector = v2.subtract(v1); axes.push(surfaceVector.perpendicular().normalize()); } return axes; }; Polygon.prototype.project = function (axis) { var scalars = []; this.points.forEach( function (point) { scalars.push(new Vector(point).dotProduct(axis)); }); return new Projection(Math.min.apply(Math, scalars), Math.max.apply(Math, scalars)); }; Polygon.prototype.addPoint = function (x, y) { this.points.push(new Point(x,y)); }; Polygon.prototype.createPath = function (context) { if (this.points.length === 0) return; context.beginPath(); context.moveTo(this.points[0].x, this.points[0].y); for (var i=0; i < this.points.length; ++i) { context.lineTo(this.points[i].x, this.points[i].y); } context.closePath(); }; Polygon.prototype.move = function (dx, dy) { var point, x; for(var i=0; i < this.points.length; ++i) { point = this.points[i]; x += dx; y += dy; } }; Polygon.prototype.collidesWith = function (shape, displacement) { if (shape.radius !== undefined) { return polygonCollidesWithCircle(this, shape, displacement); } else { return polygonCollidesWithPolygon(this, shape, displacement); } }; Polygon.prototype.move = function (dx, dy) { for (var i=0, point; i < this.points.length; ++i) { point = this.points[i]; point.x += dx; point.y += dy; } }; Polygon.prototype.boundingBox = function (dx, dy) { var minx = BIG_NUMBER, miny = BIG_NUMBER, maxx = -BIG_NUMBER, maxy = -BIG_NUMBER, point; for (var i=0; i < this.points.length; ++i) { point = this.points[i]; minx = Math.min(minx,point.x); miny = Math.min(miny,point.y); maxx = Math.max(maxx,point.x); maxy = Math.max(maxy,point.y); } return new BoundingBox(minx, miny, parseFloat(maxx - minx), parseFloat(maxy - miny)); }; Polygon.prototype.centroid = function () { var pointSum = new Point(0,0); for (var i=0, point; i < this.points.length; ++i) { point = this.points[i]; pointSum.x += point.x; pointSum.y += point.y; } return new Point(pointSum.x / this.points.length, pointSum.y / this.points.length); } // Projections................................................... var Projection = function (min, max) { this.min = min; this.max = max; }; Projection.prototype = { overlaps: function (projection) { return this.max > projection.min && projection.max > this.min; }, getOverlap: function (projection) { var overlap; if (!this.overlaps(projection)) return 0; if (this.max > projection.max) { overlap = projection.max - this.min; } else { overlap = this.max - projection.min; } return overlap; } }; // MinimumTranslationVector......................................... var MinimumTranslationVector = function (axis, overlap) { this.axis = axis; this.overlap = overlap; }; var ImageShape = function(imageSource, x, y, w, h) { var self = this; this.image = new Image(); this.imageLoaded = false; this.points = [ new Point(x,y) ]; this.x = x; this.y = y; this.image.src = imageSource; this.image.addEventListener('load', function (e) { self.setPolygonPoints(); self.imageLoaded = true; }, false); } ImageShape.prototype = new Polygon(); ImageShape.prototype.fill = function (context) { }; ImageShape.prototype.setPolygonPoints = function() { this.points.push(new Point(this.x + this.image.width, this.y)); this.points.push(new Point(this.x + this.image.width, this.y + this.image.height)); this.points.push(new Point(this.x, this.y + this.image.height)); this.points.push(new Point(this.x, this.y)); this.points.push(new Point(this.x + this.image.width, this.y)); }; ImageShape.prototype.drawImage = function (context) { context.drawImage(this.image, this.points[0].x, this.points[0].y); }; ImageShape.prototype.stroke = function (context) { var self = this; if (this.imageLoaded) { context.drawImage(this.image, this.points[0].x, this.points[0].y); } else { this.image.addEventListener('load', function (e) { self.drawImage(context); }, false); } }; var SpriteShape = function (sprite, x, y) { this.sprite = sprite; this.x = x; this.y = y; sprite.left = x; sprite.top = y; this.setPolygonPoints(); }; SpriteShape.prototype = new Polygon(); SpriteShape.prototype.move = function (dx, dy) { var point, x; for(var i=0; i < this.points.length; ++i) { point = this.points[i]; point.x += dx; point.y += dy; } this.sprite.left = this.points[0].x; this.sprite.top = this.points[0].y; }; SpriteShape.prototype.fill = function (context) { }; SpriteShape.prototype.setPolygonPoints = function() { this.points.push(new Point(this.x, this.y)); this.points.push(new Point(this.x, this.y + this.sprite.height)); this.points.push(new Point(this.x + this.sprite.width, this.y + this.sprite.height)); this.points.push(new Point(this.x + this.sprite.width, this.y)); this.points.push(new Point(this.x, this.y)); }; /* SpriteShape.prototype.stroke = function (context) { this.sprite.paint(context); }; */
define(['modules/core/src/TimeSignatureModel'], function(TimeSignatureModel) { /** * Bar core model * @exports core/BarModel */ function BarModel(options) { options = options || {}; this.begining = options.begining; this.clef = options.clef; // empty clef means it doesn't change from previous this.ending = options.ending; // object with repeat, type (BEGIN,END, BEGIN_END, MID) and ending (text) this.style = options.style || ''; this.setTimeSignatureChange(options.timeSignatureChange);// empty timeSignature means it doesn't change from previous this.keySignatureChange = options.keySignatureChange; this.labels = []; // Segno, fine, coda ... we set an array, although currentlu CSLJson only accepts one label per bar if (options.label){ this.labels.push(options.label); }else if (options.labels) { this.labels = options.labels; } this.sublabel = options.sublabel; // Ds, Ds al fine, ds al capo ... } BarModel.prototype.setBegining = function(begining) { if (typeof begining === "undefined") { throw 'BarModel - begining should not be undefined'; } this.begining = begining; }; BarModel.prototype.getBegining = function() { return this.begining; }; BarModel.prototype.setClef = function(clef) { var clefType = ['', 'treble', 'bass', 'alto', 'tenor', 'percussion']; if (typeof clef === "undefined" && typeof clefType[clef] === "undefined") { throw 'BarModel - clef should not be undefined'; } this.clef = clef; }; BarModel.prototype.getClef = function() { return this.clef; }; BarModel.prototype.setEnding = function(ending) { if (typeof ending === "undefined") { ending = undefined; } this.ending = ending; }; BarModel.prototype.removeEnding = function() { this.ending = undefined; }; BarModel.prototype.getEnding = function() { return this.ending; }; BarModel.prototype.setStyle = function(style) { if (typeof style === "undefined") { style = ''; } this.style = style; }; BarModel.prototype.getStyle = function() { return this.style; }; /** * if param is string, it is converted to TimeSignatureModel * @param {TimeSignatureModel | String} timeSignatureChange */ BarModel.prototype.setTimeSignatureChange = function(timeSignatureChange) { if (!timeSignatureChange) { this.timeSignatureChange = undefined; } else if (typeof timeSignatureChange === 'string'){ this.timeSignatureChange = new TimeSignatureModel(timeSignatureChange); }else{ this.timeSignatureChange = timeSignatureChange; } }; BarModel.prototype.getTimeSignatureChange = function() { return this.timeSignatureChange; }; BarModel.prototype.setKeySignatureChange = function(keySignatureChange) { if (typeof keySignatureChange === "undefined") { keySignatureChange = ''; } this.keySignatureChange = keySignatureChange; }; BarModel.prototype.getKeySignatureChange = function() { return this.keySignatureChange; }; BarModel.prototype.setLabel = function(label) { if (!!label && this.labels.indexOf(label) === -1){ this.labels.push(label); } }; BarModel.prototype.getLabel = function() { label = this.labels.length === 0 ? null : this.labels.length === 1 ? this.labels[0] : this.labels; return label || ""; }; BarModel.prototype.setSublabel = function(sublabel) { if (typeof sublabel === "undefined") { sublabel = ''; } this.sublabel = sublabel; }; /** * * @param {boolan} formatted : if true, it returns formatted example for drawing. * @return {String} e.g.: if formatted -> "DC_AL_CODA"; else -> "DC al Coda" */ BarModel.prototype.getSublabel = function(formatted) { if (formatted && typeof this.sublabel !== 'undefined') { return this.sublabel.replace(/ /g, "_").toUpperCase(); } else { return this.sublabel; } }; /** * @param {boolean} unfolding , if true it means we are unfolding so we want to remove endings, labels..etc., if false, is pure cloning * @return {BarModel} */ BarModel.prototype.clone = function(unfolding) { var newBar = new BarModel(this); if (unfolding) { newBar.removeEnding(); } return newBar; }; return BarModel; });
#!/usr/bin/env node /** * Stairway of frequencies * * @author Viacheslav Lotsmanov */ var jackConnector = require('../index.js'); var jackClientName = 'JACK connector - stairway of frequencies'; console.log('Opening JACK client...'); jackConnector.openClientSync(jackClientName); console.log('Registering JACK ports...'); jackConnector.registerOutPortSync('out'); var sampleRate = jackConnector.getSampleRateSync(); // from 20Hz to 20kHz var freqMin = 20; var freqMax = 20000; var freqCur; var freqStep = 8; var phaseInc; // phase increment var phase = 0; if (process.argv.length < 3) { console.error( 'Please, choose OSC type by first argument:\n'+ ' 1 - sine\n'+ ' 2 - saw\n'+ ' 3 - square\n'+ ' 4 - triangle' ); process.exit(1); } var oscType; switch (process.argv[2]) { case '1': case '2': case '3': case '4': oscType = parseInt(process.argv[2], 10) - 1; break; default: throw new Error('Incorrect OSC type by first argument ("'+ process.argv[2] +'")'); } var twoPI = Math.PI * 2; var upFreqCount = 0; var upFreqSpeed = 5; // ms // transform to samples upFreqSpeed *= sampleRate; upFreqSpeed /= 1000; function updateIncrement() { phaseInc = ((freqCur * 2) * Math.PI) / sampleRate; } function setFrequency(freqVal) { freqCur = freqVal; updateIncrement(); } function incFrequency() { if (freqCur + freqStep > freqMax) freqCur = freqMin; else setFrequency(freqCur + freqStep); } function osc(nframes, upFreqAt) { // {{{1 var type = oscType % 4; var buf = new Array(nframes); switch (type) { case 0: // sine for (var i=0; i<nframes; i++) { if (upFreqAt > -1 && i == upFreqAt) incFrequency(); buf[i] = Math.sin(phase); phase += phaseInc; while (phase >= twoPI) phase -= twoPI; } break; case 1: // saw for (var i=0; i<nframes; i++) { if (upFreqAt > -1 && i == upFreqAt) incFrequency(); buf[i] = 1.0 - ((2.0 * phase) / twoPI); phase += phaseInc; while (phase >= twoPI) phase -= twoPI; } break; case 2: // square for (var i=0; i<nframes; i++) { if (upFreqAt > -1 && i == upFreqAt) incFrequency(); if (phase <= Math.PI) buf[i] = 1.0; else buf[i] = -1.0; phase += phaseInc; while (phase >= twoPI) phase -= twoPI; } break; case 3: // triangle var val; for (var i=0; i<nframes; i++) { if (upFreqAt > -1 && i == upFreqAt) incFrequency(); val = -1.0 + ((2.0 * phase) / twoPI); buf[i] = 2.0 * (Math.abs(val) - 0.5); phase += phaseInc; while (phase >= twoPI) phase -= twoPI; } break; } return buf; } // osc() }}}1 setFrequency(freqMin); function audioProcess(err, nframes) { if (err) { console.error(err); process.exit(1); return; } var upFreqAt = -1; upFreqCount += nframes; if (upFreqCount >= upFreqSpeed) upFreqAt = upFreqCount -= upFreqSpeed; return { out: osc(nframes, upFreqAt) }; // port name: buffer array } console.log('Binding audio-process callback...'); jackConnector.bindProcessSync(audioProcess); console.log('Activating JACK client...'); jackConnector.activateSync(); console.log('Auto-connecting to hardware ports...'); jackConnector.connectPortSync(jackClientName + ':out', 'system:playback_1'); jackConnector.connectPortSync(jackClientName + ':out', 'system:playback_2'); (function mainLoop() { console.log('Main loop is started.'); setTimeout(mainLoop, 1000000000); })(); process.on('SIGTERM', function () { console.log('Deactivating JACK client...'); jackConnector.deactivateSync(); console.log('Closing JACK client...'); jackConnector.closeClient(function (err) { if (err) { console.error(err); process.exit(1); return; } console.log('Exiting...'); process.exit(0); }); });
'use strict'; /** * Module dependencies. */ const mongoose = require('mongoose'); const { wrap: async } = require('co'); const { respond } = require('../utils'); const Article = mongoose.model('Article'); /** * List items tagged with a tag */ exports.index = async(function* (req, res) { const criteria = { tags: req.params.tag }; const page = (req.params.page > 0 ? req.params.page : 1) - 1; const limit = 30; const options = { limit: limit, page: page, criteria: criteria }; const articles = yield Article.list(options); const count = yield Article.count(criteria); respond(res, 'articles/index', { title: 'Articles tagged ' + req.params.tag, articles: articles, page: page + 1, pages: Math.ceil(count / limit) }); });
var express = require('express'); var User = require(softblu + 'model/user'); module.exports = function (router) { /** * An example route which returns all users in the database. * * Note: This route makes no excuses of being insecure - it does no additional * authorisation checks beforehand. It's just an example. * * @method GET * @path /api/users */ router.get('/', function (req, res, next) { User.find(function (err, users) { if (err) { next(new Error('Could not fetch list of users')); } else { res.send({ result: users }); } }); }); };
'use strict'; var autoprefixer = require('gulp-autoprefixer'); var browserify = require('browserify'); var buffer = require('vinyl-buffer'); var connect = require('gulp-connect'); var del = require('del'); var eslint = require('gulp-eslint'); var gulp = require('gulp'); var insert = require('gulp-insert'); var path = require('path'); var rename = require('gulp-rename'); var sass = require('gulp-sass'); var source = require('vinyl-source-stream'); var stream = require('event-stream'); var uglify = require('gulp-uglify'); var zip = require('gulp-zip'); var version = '/* perfect-scrollbar v' + require('./package').version + ' */\n'; gulp.task('lint', function () { return gulp.src(['./src/**/*.js', './gulpfile.js']) .pipe(eslint()) .pipe(eslint.format()) .pipe(eslint.failOnError()); }); gulp.task('clean:js', function () { return del(['./dist/js/*.js']); }); gulp.task('clean:js:min', function () { return del(['./dist/js/*.min.js']); }); var jsEntries = [ './src/js/adaptor/global.js', './src/js/adaptor/jquery.js' ]; var autoPrefixerConfig = { browsers: ['> 0%'], // '> 0%' forces autoprefixer to use all the possible prefixes. See https://github.com/ai/browserslist#queries for more details. IMO 'last 3 versions' would be good enough. cascade: false }; gulp.task('js', ['clean:js'], function () { var tasks = jsEntries.map(function (src) { return browserify([src]).bundle() .pipe(source(path.basename(src))) .pipe(buffer()) .pipe(insert.prepend(version)) .pipe(rename(function (path) { if (path.basename === 'global') { path.basename = 'perfect-scrollbar'; } else { path.basename = 'perfect-scrollbar.' + path.basename; } })) .pipe(gulp.dest('./dist/js')) .pipe(connect.reload()); }); return stream.merge.apply(null, tasks); }); gulp.task('js:min', ['clean:js:min'], function () { var tasks = jsEntries.map(function (src) { return browserify([src]).bundle() .pipe(source(path.basename(src))) .pipe(buffer()) .pipe(uglify()) .pipe(insert.prepend(version)) .pipe(rename(function (path) { if (path.basename === 'global') { path.basename = 'perfect-scrollbar.min'; } else { path.basename = 'perfect-scrollbar.' + path.basename + '.min'; } })) .pipe(gulp.dest('./dist/js')) .pipe(connect.reload()); }); return stream.merge.apply(null, tasks); }); gulp.task('clean:css', function () { return del(['./dist/css/perfect-scrollbar.css']); }); gulp.task('clean:css:min', function () { return del(['./dist/css/perfect-scrollbar.min.css']); }); gulp.task('css', ['clean:css'], function () { return gulp.src('./src/css/main.scss') .pipe(sass()) .pipe(autoprefixer(autoPrefixerConfig)) .pipe(insert.prepend(version)) .pipe(rename('perfect-scrollbar.css')) .pipe(gulp.dest('./dist/css')) .pipe(connect.reload()); }); gulp.task('css:min', ['clean:css:min'], function () { return gulp.src('./src/css/main.scss') .pipe(sass({outputStyle: 'compressed'})) .pipe(autoprefixer(autoPrefixerConfig)) .pipe(insert.prepend(version)) .pipe(rename('perfect-scrollbar.min.css')) .pipe(gulp.dest('./dist/css')); }); gulp.task('build', ['js', 'js:min', 'css', 'css:min']); gulp.task('connect', ['build'], function () { connect.server({ root: __dirname, livereload: true }); }); gulp.task('watch', function () { gulp.watch(['src/js/**/*'], ['js']); gulp.watch(['src/css/**/*'], ['css']); }); gulp.task('serve', ['connect', 'watch']); gulp.task('compress', function () { return gulp.src('./dist/**') .pipe(zip('perfect-scrollbar.zip')) .pipe(gulp.dest('./dist')); }); gulp.task('default', ['lint', 'build']);
/** * mongodb.js * * A simple wrapper for mongodb driver */ var mongo = require('yieldb').connect; var db; module.exports = database; /** * Return an instance of yieldb * * @param Object opts Custom options for driver * @return MongoDB */ function *database(opts) { if (db) { return db; } if (!opts) { throw new Error('missing options'); } if (!opts.hasOwnProperty('database')) { throw new Error('database must be specified'); } if (!opts.hasOwnProperty('w')) { throw new Error('writeConcern must be specified'); } // build server string var url = 'mongodb://'; if (opts.user && opts.pass) { url += opts.user + ':' + opts.pass + '@'; } if (opts.server) { url += opts.server; } if (opts.port) { url += ':' + opts.port; } // explicit set default database and write concern url += '/' + opts.database + '?w=' + opts.w; if (opts.replSet) { url += '&replicaSet=' + opts.replSet; } if (opts.userdb) { url += '&authSource=' + opts.userdb; } // make sure we have active connection to db db = yield mongo(url); return db; };
// Generated by LiveScript 1.5.0 /** * @package Shop * @category modules * @author Nazar Mokrynskyi <nazar@mokrynskyi.com> * @license 0BSD */ (function(){ Polymer({ is: 'cs-shop-category-nested', properties: { href: String, category_title: String }, ready: function(){ var img, link; img = this.querySelector('#img'); this.$.img.src = img.src; this.$.img.title = img.title; link = this.querySelector('#link'); this.set('href', link.href); this.set('category_title', link.textContent); } }); }).call(this);
if(typeof exports === 'object') { var assert = require("assert"); var alasql = require('..'); }; describe('Test 79 - Prettify', function() { // it('localStorage', function(done){ // done(); // }); });
/* eslint-disable no-var, comma-dangle, object-shorthand */ /* global Notes */ import '~/merge_request_tabs'; import '~/commit/pipelines/pipelines_bundle'; import '~/breakpoints'; import '~/lib/utils/common_utils'; import '~/diff'; import '~/files_comment_button'; import '~/notes'; import 'vendor/jquery.scrollTo'; (function () { describe('MergeRequestTabs', function () { var stubLocation = {}; var setLocation = function (stubs) { var defaults = { pathname: '', search: '', hash: '' }; $.extend(stubLocation, defaults, stubs || {}); }; const inlineChangesTabJsonFixture = 'merge_request_diffs/inline_changes_tab_with_comments.json'; const parallelChangesTabJsonFixture = 'merge_request_diffs/parallel_changes_tab_with_comments.json'; preloadFixtures( 'merge_requests/merge_request_with_task_list.html.raw', 'merge_requests/diff_comment.html.raw', inlineChangesTabJsonFixture, parallelChangesTabJsonFixture ); beforeEach(function () { this.class = new gl.MergeRequestTabs({ stubLocation: stubLocation }); setLocation(); this.spies = { history: spyOn(window.history, 'replaceState').and.callFake(function () {}) }; }); afterEach(function () { this.class.unbindEvents(); this.class.destroyPipelinesView(); }); describe('activateTab', function () { beforeEach(function () { spyOn($, 'ajax').and.callFake(function () {}); loadFixtures('merge_requests/merge_request_with_task_list.html.raw'); this.subject = this.class.activateTab; }); it('shows the notes tab when action is show', function () { this.subject('show'); expect($('#notes')).toHaveClass('active'); }); it('shows the commits tab when action is commits', function () { this.subject('commits'); expect($('#commits')).toHaveClass('active'); }); it('shows the diffs tab when action is diffs', function () { this.subject('diffs'); expect($('#diffs')).toHaveClass('active'); }); }); describe('opensInNewTab', function () { var tabUrl; var windowTarget = '_blank'; beforeEach(function () { loadFixtures('merge_requests/merge_request_with_task_list.html.raw'); tabUrl = $('.commits-tab a').attr('href'); spyOn($.fn, 'attr').and.returnValue(tabUrl); }); describe('meta click', () => { beforeEach(function () { spyOn(gl.utils, 'isMetaClick').and.returnValue(true); }); it('opens page when commits link is clicked', function () { spyOn(window, 'open').and.callFake(function (url, name) { expect(url).toEqual(tabUrl); expect(name).toEqual(windowTarget); }); this.class.bindEvents(); document.querySelector('.merge-request-tabs .commits-tab a').click(); }); it('opens page when commits badge is clicked', function () { spyOn(window, 'open').and.callFake(function (url, name) { expect(url).toEqual(tabUrl); expect(name).toEqual(windowTarget); }); this.class.bindEvents(); document.querySelector('.merge-request-tabs .commits-tab a .badge').click(); }); }); it('opens page tab in a new browser tab with Ctrl+Click - Windows/Linux', function () { spyOn(window, 'open').and.callFake(function (url, name) { expect(url).toEqual(tabUrl); expect(name).toEqual(windowTarget); }); this.class.clickTab({ metaKey: false, ctrlKey: true, which: 1, stopImmediatePropagation: function () {} }); }); it('opens page tab in a new browser tab with Cmd+Click - Mac', function () { spyOn(window, 'open').and.callFake(function (url, name) { expect(url).toEqual(tabUrl); expect(name).toEqual(windowTarget); }); this.class.clickTab({ metaKey: true, ctrlKey: false, which: 1, stopImmediatePropagation: function () {} }); }); it('opens page tab in a new browser tab with Middle-click - Mac/PC', function () { spyOn(window, 'open').and.callFake(function (url, name) { expect(url).toEqual(tabUrl); expect(name).toEqual(windowTarget); }); this.class.clickTab({ metaKey: false, ctrlKey: false, which: 2, stopImmediatePropagation: function () {} }); }); }); describe('setCurrentAction', function () { beforeEach(function () { spyOn($, 'ajax').and.callFake(function () {}); this.subject = this.class.setCurrentAction; }); it('changes from commits', function () { setLocation({ pathname: '/foo/bar/merge_requests/1/commits' }); expect(this.subject('show')).toBe('/foo/bar/merge_requests/1'); expect(this.subject('diffs')).toBe('/foo/bar/merge_requests/1/diffs'); }); it('changes from diffs', function () { setLocation({ pathname: '/foo/bar/merge_requests/1/diffs' }); expect(this.subject('show')).toBe('/foo/bar/merge_requests/1'); expect(this.subject('commits')).toBe('/foo/bar/merge_requests/1/commits'); }); it('changes from diffs.html', function () { setLocation({ pathname: '/foo/bar/merge_requests/1/diffs.html' }); expect(this.subject('show')).toBe('/foo/bar/merge_requests/1'); expect(this.subject('commits')).toBe('/foo/bar/merge_requests/1/commits'); }); it('changes from notes', function () { setLocation({ pathname: '/foo/bar/merge_requests/1' }); expect(this.subject('diffs')).toBe('/foo/bar/merge_requests/1/diffs'); expect(this.subject('commits')).toBe('/foo/bar/merge_requests/1/commits'); }); it('includes search parameters and hash string', function () { setLocation({ pathname: '/foo/bar/merge_requests/1/diffs', search: '?view=parallel', hash: '#L15-35' }); expect(this.subject('show')).toBe('/foo/bar/merge_requests/1?view=parallel#L15-35'); }); it('replaces the current history state', function () { var newState; setLocation({ pathname: '/foo/bar/merge_requests/1' }); newState = this.subject('commits'); expect(this.spies.history).toHaveBeenCalledWith({ url: newState }, document.title, newState); }); it('treats "show" like "notes"', function () { setLocation({ pathname: '/foo/bar/merge_requests/1/commits' }); expect(this.subject('show')).toBe('/foo/bar/merge_requests/1'); }); }); describe('tabShown', () => { beforeEach(function () { spyOn($, 'ajax').and.callFake(function (options) { options.success({ html: '' }); }); loadFixtures('merge_requests/merge_request_with_task_list.html.raw'); }); describe('with "Side-by-side"/parallel diff view', () => { beforeEach(function () { this.class.diffViewType = () => 'parallel'; gl.Diff.prototype.diffViewType = () => 'parallel'; }); it('maintains `container-limited` for pipelines tab', function (done) { const asyncClick = function (selector) { return new Promise((resolve) => { setTimeout(() => { document.querySelector(selector).click(); resolve(); }); }); }; asyncClick('.merge-request-tabs .pipelines-tab a') .then(() => asyncClick('.merge-request-tabs .diffs-tab a')) .then(() => asyncClick('.merge-request-tabs .pipelines-tab a')) .then(() => { const hasContainerLimitedClass = document.querySelector('.content-wrapper .container-fluid').classList.contains('container-limited'); expect(hasContainerLimitedClass).toBe(true); }) .then(done) .catch((err) => { done.fail(`Something went wrong clicking MR tabs: ${err.message}\n${err.stack}`); }); }); it('maintains `container-limited` when switching from "Changes" tab before it loads', function (done) { const asyncClick = function (selector) { return new Promise((resolve) => { setTimeout(() => { document.querySelector(selector).click(); resolve(); }); }); }; asyncClick('.merge-request-tabs .diffs-tab a') .then(() => asyncClick('.merge-request-tabs .notes-tab a')) .then(() => { const hasContainerLimitedClass = document.querySelector('.content-wrapper .container-fluid').classList.contains('container-limited'); expect(hasContainerLimitedClass).toBe(true); }) .then(done) .catch((err) => { done.fail(`Something went wrong clicking MR tabs: ${err.message}\n${err.stack}`); }); }); }); }); describe('loadDiff', function () { beforeEach(() => { loadFixtures('merge_requests/diff_comment.html.raw'); spyOn(window.gl.utils, 'getPagePath').and.returnValue('merge_requests'); window.gl.ImageFile = () => {}; window.notes = new Notes('', []); spyOn(window.notes, 'toggleDiffNote').and.callThrough(); }); afterEach(() => { delete window.gl.ImageFile; delete window.notes; }); it('requires an absolute pathname', function () { spyOn($, 'ajax').and.callFake(function (options) { expect(options.url).toEqual('/foo/bar/merge_requests/1/diffs.json'); }); this.class.loadDiff('/foo/bar/merge_requests/1/diffs'); }); describe('with inline diff', () => { let noteId; let noteLineNumId; beforeEach(() => { const diffsResponse = getJSONFixture(inlineChangesTabJsonFixture); const $html = $(diffsResponse.html); noteId = $html.find('.note').attr('id'); noteLineNumId = $html .find('.note') .closest('.notes_holder') .prev('.line_holder') .find('a[data-linenumber]') .attr('href') .replace('#', ''); spyOn($, 'ajax').and.callFake(function (options) { options.success(diffsResponse); }); }); describe('with note fragment hash', () => { it('should expand and scroll to linked fragment hash #note_xxx', function () { spyOn(window.gl.utils, 'getLocationHash').and.returnValue(noteId); this.class.loadDiff('/foo/bar/merge_requests/1/diffs'); expect(noteId.length).toBeGreaterThan(0); expect(window.notes.toggleDiffNote).toHaveBeenCalledWith({ target: jasmine.any(Object), lineType: 'old', forceShow: true, }); }); it('should gracefully ignore non-existant fragment hash', function () { spyOn(window.gl.utils, 'getLocationHash').and.returnValue('note_something-that-does-not-exist'); this.class.loadDiff('/foo/bar/merge_requests/1/diffs'); expect(window.notes.toggleDiffNote).not.toHaveBeenCalled(); }); }); describe('with line number fragment hash', () => { it('should gracefully ignore line number fragment hash', function () { spyOn(window.gl.utils, 'getLocationHash').and.returnValue(noteLineNumId); this.class.loadDiff('/foo/bar/merge_requests/1/diffs'); expect(noteLineNumId.length).toBeGreaterThan(0); expect(window.notes.toggleDiffNote).not.toHaveBeenCalled(); }); }); }); describe('with parallel diff', () => { let noteId; let noteLineNumId; beforeEach(() => { const diffsResponse = getJSONFixture(parallelChangesTabJsonFixture); const $html = $(diffsResponse.html); noteId = $html.find('.note').attr('id'); noteLineNumId = $html .find('.note') .closest('.notes_holder') .prev('.line_holder') .find('a[data-linenumber]') .attr('href') .replace('#', ''); spyOn($, 'ajax').and.callFake(function (options) { options.success(diffsResponse); }); }); describe('with note fragment hash', () => { it('should expand and scroll to linked fragment hash #note_xxx', function () { spyOn(window.gl.utils, 'getLocationHash').and.returnValue(noteId); this.class.loadDiff('/foo/bar/merge_requests/1/diffs'); expect(noteId.length).toBeGreaterThan(0); expect(window.notes.toggleDiffNote).toHaveBeenCalledWith({ target: jasmine.any(Object), lineType: 'new', forceShow: true, }); }); it('should gracefully ignore non-existant fragment hash', function () { spyOn(window.gl.utils, 'getLocationHash').and.returnValue('note_something-that-does-not-exist'); this.class.loadDiff('/foo/bar/merge_requests/1/diffs'); expect(window.notes.toggleDiffNote).not.toHaveBeenCalled(); }); }); describe('with line number fragment hash', () => { it('should gracefully ignore line number fragment hash', function () { spyOn(window.gl.utils, 'getLocationHash').and.returnValue(noteLineNumId); this.class.loadDiff('/foo/bar/merge_requests/1/diffs'); expect(noteLineNumId.length).toBeGreaterThan(0); expect(window.notes.toggleDiffNote).not.toHaveBeenCalled(); }); }); }); }); }); }).call(window);
!function(root) { var IS_MODULE = 'object' === typeof exports function Grapnel(options) { var _this = this this.options = options || {} this.options.env = this.options.env || (IS_MODULE ? 'server' : 'client') this.options.mode = this.options.mode || (!!(this.options.env !== 'server' && this.options.pushState && root.history && root.history.pushState) ? 'pushState' : 'hashchange') if ('function' === typeof root.addEventListener) { root.addEventListener('hashchange', function() { _this.trigger('hashchange') }) root.addEventListener('popstate', function(e) { // Make sure popstate doesn't run on init -- this is a common issue with Safari and old versions of Chrome if (_this.state && _this.state.previousState === null) return false _this.trigger('navigate') }) } } Grapnel.prototype.events = {} Grapnel.prototype.state = null /** * Create a RegExp Route from a string * This is the heart of the router and I've made it as small as possible! * * @param {String} Path of route * @param {Array} Array of keys to fill * @param {Bool} Case sensitive comparison * @param {Bool} Strict mode */ Grapnel.regexRoute = function(path, keys, sensitive, strict) { if (path instanceof RegExp) return path if (path instanceof Array) path = '(' + path.join('|') + ')' // Build route RegExp path = path .concat(strict ? '' : '/?') .replace(/\/\(/g, '(?:/') .replace(/\+/g, '__plus__') .replace(/(\/)?(\.)?:(\w+)(?:(\(.*?\)))?(\?)?/g, function(_, slash, format, key, capture, optional) { keys.push({ name: key, optional: !!optional, }) slash = slash || '' return '' + (optional ? '' : slash) + '(?:' + (optional ? slash : '') + (format || '') + (capture || (format && '([^/.]+?)') || '([^/]+?)') + ')' + (optional || '') }) .replace(/([\/.])/g, '\\$1') .replace(/__plus__/g, '(.+)') .replace(/\*/g, '(.*)') return new RegExp('^' + path + '$', sensitive ? '' : 'i') } /** * ForEach workaround utility * * @param {Array} to iterate * @param {Function} callback */ Grapnel._forEach = function(a, callback) { if (typeof Array.prototype.forEach === 'function') return Array.prototype.forEach.call(a, callback) // Replicate forEach() return function(c, next) { for (var i = 0, n = this.length; i < n; ++i) { c.call(next, this[i], i, this) } }.call(a, callback) } /** * Add a route and handler * * @param {String|RegExp} route name * @return {_this} Router */ Grapnel.prototype.get = Grapnel.prototype.add = function(route) { var _this = this, middleware = Array.prototype.slice.call(arguments, 1, -1), handler = Array.prototype.slice.call(arguments, -1)[0], request = new Request(route) var invoke = function() { // Build request parameters var req = request.parse(_this.path()) // Check if matches are found if (req.match) { // Match found var extra = { route: route, params: req.params, req: req, regex: req.match, } // Create call stack -- add middleware first, then handler var stack = new CallStack(_this, extra).enqueue(middleware.concat(handler)) // Trigger main event _this.trigger('match', stack, req) // Continue? if (!stack.runCallback) return _this // Previous state becomes current state stack.previousState = _this.state // Save new state _this.state = stack // Prevent this handler from being called if parent handler in stack has instructed not to propagate any more events if (stack.parent() && stack.parent().propagateEvent === false) { stack.propagateEvent = false return _this } // Call handler stack.callback() } // Returns _this return _this } // Event name var eventName = _this.options.mode !== 'pushState' && _this.options.env !== 'server' ? 'hashchange' : 'navigate' // Invoke when route is defined, and once again when app navigates return invoke().on(eventName, invoke) } /** * Fire an event listener * * @param {String} event name * @param {Mixed} [attributes] Parameters that will be applied to event handler * @return {_this} Router */ Grapnel.prototype.trigger = function(event) { var _this = this, params = Array.prototype.slice.call(arguments, 1) // Call matching events if (this.events[event]) { Grapnel._forEach(this.events[event], function(fn) { fn.apply(_this, params) }) } return this } /** * Add an event listener * * @param {String} event name (multiple events can be called when separated by a space " ") * @param {Function} callback * @return {_this} Router */ Grapnel.prototype.on = Grapnel.prototype.bind = function(event, handler) { var _this = this, events = event.split(' ') Grapnel._forEach(events, function(event) { if (_this.events[event]) { _this.events[event].push(handler) } else { _this.events[event] = [handler] } }) return this } /** * Allow event to be called only once * * @param {String} event name(s) * @param {Function} callback * @return {_this} Router */ Grapnel.prototype.once = function(event, handler) { var ran = false return this.on(event, function() { if (ran) return false ran = true handler.apply(this, arguments) handler = null return true }) } /** * @param {String} Route context (without trailing slash) * @param {[Function]} Middleware (optional) * @return {Function} Adds route to context */ Grapnel.prototype.context = function(context) { var _this = this, middleware = Array.prototype.slice.call(arguments, 1) return function() { var value = arguments[0], submiddleware = arguments.length > 2 ? Array.prototype.slice.call(arguments, 1, -1) : [], handler = Array.prototype.slice.call(arguments, -1)[0], prefix = context.slice(-1) !== '/' && value !== '/' && value !== '' ? context + '/' : context, path = value.substr(0, 1) !== '/' ? value : value.substr(1), pattern = prefix + path return _this.add.apply( _this, [pattern] .concat(middleware) .concat(submiddleware) .concat([handler]) ) } } /** * Navigate through history API * * @param {String} Pathname * @return {_this} Router */ Grapnel.prototype.navigate = function(path) { return this.path(path).trigger('navigate') } Grapnel.prototype.path = function(pathname) { var _this = this, frag if ('string' === typeof pathname) { // Set path if (_this.options.mode === 'pushState') { frag = _this.options.root ? _this.options.root + pathname : pathname root.history.pushState({}, null, frag) } else if (root.location) { root.location.hash = (_this.options.hashBang ? '!' : '') + pathname } else { root._pathname = pathname || '' } return this } else if ('undefined' === typeof pathname) { // Get path if (_this.options.mode === 'pushState') { frag = root.location.pathname.replace(_this.options.root, '') } else if (_this.options.mode !== 'pushState' && root.location) { frag = root.location.hash ? root.location.hash.split(_this.options.hashBang ? '#!' : '#')[1] : '' } else { frag = root._pathname || '' } return frag } else if (pathname === false) { // Clear path if (_this.options.mode === 'pushState') { root.history.pushState({}, null, _this.options.root || '/') } else if (root.location) { root.location.hash = _this.options.hashBang ? '!' : '' } return _this } } /** * Create routes based on an object * * @param {Object} [Options, Routes] * @param {Object Routes} * @return {_this} Router */ Grapnel.listen = function() { var opts, routes if (arguments[0] && arguments[1]) { opts = arguments[0] routes = arguments[1] } else { routes = arguments[0] } // Return a new Grapnel instance return function() { // TODO: Accept multi-level routes for (var key in routes) { this.add.call(this, key, routes[key]) } return this }.call(new Grapnel(opts || {})) } /** * Create a call stack that can be enqueued by handlers and middleware * * @param {Object} Router * @param {Object} Extend * @return {_this} CallStack */ function CallStack(router, extendObj) { this.stack = CallStack.global.slice(0) this.router = router this.runCallback = true this.callbackRan = false this.propagateEvent = true this.value = router.path() for (var key in extendObj) { this[key] = extendObj[key] } return this } /** * Build request parameters and allow them to be checked against a string (usually the current path) * * @param {String} Route * @return {_this} Request */ function Request(route) { this.route = route this.keys = [] this.regex = Grapnel.regexRoute(route, this.keys) } // This allows global middleware CallStack.global = [] /** * Prevent a callback from being called * * @return {_this} CallStack */ CallStack.prototype.preventDefault = function() { this.runCallback = false } /** * Prevent any future callbacks from being called * * @return {_this} CallStack */ CallStack.prototype.stopPropagation = function() { this.propagateEvent = false } /** * Get parent state * * @return {Object} Previous state */ CallStack.prototype.parent = function() { var hasParentEvents = !!(this.previousState && this.previousState.value && this.previousState.value == this.value) return hasParentEvents ? this.previousState : false } /** * Run a callback (calls to next) * * @return {_this} CallStack */ CallStack.prototype.callback = function() { this.callbackRan = true this.timeStamp = Date.now() this.next() } /** * Add handler or middleware to the stack * * @param {Function|Array} Handler or a array of handlers * @param {Int} Index to start inserting * @return {_this} CallStack */ CallStack.prototype.enqueue = function(handler, atIndex) { var handlers = !Array.isArray(handler) ? [handler] : atIndex < handler.length ? handler.reverse() : handler while (handlers.length) { this.stack.splice(atIndex || this.stack.length + 1, 0, handlers.shift()) } return this } /** * Call to next item in stack -- this adds the `req`, `event`, and `next()` arguments to all middleware * * @return {_this} CallStack */ CallStack.prototype.next = function() { var _this = this return this.stack.shift().call(this.router, this.req, this, function next() { _this.next.call(_this) }) } /** * Match a path string -- returns a request object if there is a match -- returns false otherwise * * @return {Object} req */ Request.prototype.parse = function(path) { var match = path.match(this.regex), _this = this var req = { params: {}, keys: this.keys, matches: (match || []).slice(1), match: match, } // Build parameters Grapnel._forEach(req.matches, function(value, i) { var key = _this.keys[i] && _this.keys[i].name ? _this.keys[i].name : i // Parameter key will be its key or the iteration index. This is useful if a wildcard (*) is matched req.params[key] = value ? decodeURIComponent(value) : undefined }) return req } // Append utility constructors to Grapnel Grapnel.CallStack = CallStack Grapnel.Request = Request if (IS_MODULE) { exports.default = Grapnel } else { root.Grapnel = Grapnel } }('object' === typeof window ? window : this)
var lang = { 'A %type% block is not rendered when the editor is active' : 'A %type% block is not rendered when the editor is active', 'This operation is not allowed when you are editing the contents' : 'This operation is not allowed when you are editing the contents', 'This operation is not allowed when you are editing the slots' : 'This operation is not allowed when you are editing the slots', 'Are you sure to start the deploying of "%env%" environment' : 'Are you sure to start the deploying of "%env%" environment', 'Are you sure to remove the active block' : 'Are you sure to remove the active block', 'Are you sure you want to remove the selected image' : 'Are you sure you want to remove the selected image', 'Are you sure to remove the active item' : 'Are you sure to remove the active item', 'Are you sure to remove the selected language' : 'Are you sure to remove the selected language', 'New value' : 'New value', 'Edit' : 'Edit', 'Delete' : 'Delete', 'Are you sure to remove the page and its attributes' : 'Are you sure to remove the page and its attributes', 'Click me to close the panel' : 'Click me to close the panel', 'Are you sure you want to remove the user' : 'Are you sure you want to remove the user', 'Are you sure you want to remove the role' : 'Are you sure you want to remove the role', 'WARNING: this command will destroy all the saved data and start a new site base on the choosen theme from the scratch: are you sure to continue?' : 'WARNING: this command will destroy all the saved data and start a new site base on the choosen theme from the scratch: are you sure to continue?', 'You are trying to edit a placeholder for a slot which does not contain blocks: please do not edit this placeholder but simply add a new block to this slot': 'You are trying to edit a placeholder for a slot which does not contain blocks: please do not edit this placeholder but simply add a new block to this slot', 'A space character is not accepted, when adding an internal route' : 'A space character is not accepted, when adding an internal route' };
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M16.45 13.62 19 12 8 5v.17zM2.81 2.81 1.39 4.22 8 10.83V19l4.99-3.18 6.79 6.79 1.41-1.42z" }), 'PlayDisabledSharp'); exports.default = _default;
var settingsSubscriptionScreenForms = { updateCard: function () { return { number: '', cvc: '', month: '', year: '', zip: '', errors: [], updating: false, updated: false }; } }; Vue.component('spark-settings-subscription-screen', { /* * Bootstrap the component. Load the initial data. */ ready: function () { Stripe.setPublishableKey(STRIPE_KEY); this.getPlans(); this.initializeTooltips(); }, /* * Configure watched data listeners. */ watch: { 'subscribeForm.plan': function (value, oldValue) { if (value.length > 0) { setTimeout(function () { $('.spark-first-field').filter(':visible:first').focus(); }, 250); } else { this.initializeTooltips(); } } }, /* * Initial state of the component's data. */ data: function () { return { user: null, currentCoupon: null, plans: [], subscribeForm: { plan: '', terms: false, stripe_token: null, errors: [], subscribing: false }, cardForm: { number: '', cvc: '', month: '', year: '', zip: '', errors: [] }, changePlanForm: { plan: '', errors: [], changing: false }, updateCardForm: settingsSubscriptionScreenForms.updateCard(), extraBillingInfoForm: { text: '', errors: [], updating: false, updated: false }, resumeSubscriptionForm: { errors: [], resuming: false }, cancelSubscriptionForm: { errors: [], cancelling: false } }; }, computed: { /* * Determine if the user has been loaded from the database. */ userIsLoaded: function () { if (this.user) { return true; } return false; }, /* * Determine if the user is currently on the "grace period". */ userIsOnGracePeriod: function () { if (this.user.subscription_ends_at) { return moment().isBefore(this.user.subscription_ends_at); } return false; }, /* * Determine the date that the user's grace period is over. */ subscriptionEndsAt: function () { if (this.user.subscription_ends_at) { return moment(this.user.subscription_ends_at).format('MMMM Do'); } }, /* * Determine if the plans have been loaded from the database. */ plansAreLoaded: function () { return this.plans.length > 0; }, /* * This method is used to determine if we need to display both a * monthly and yearly plans column, or if we will just show a * single column of available plans for the user to choose. */ includesBothPlanIntervals: function () { return this.plansAreLoaded && this.monthlyPlans.length > 0 && this.yearlyPlans.length > 0; }, /* * Retrieve the plan that the user is currently subscribed to. */ currentPlan: function () { var self = this; if ( ! this.userIsLoaded) { return null; } var plan = _.find(this.plans, function (plan) { return plan.id == self.user.stripe_plan; }); if (plan !== 'undefined') { return plan; } }, /* * Get the plan currently selected on the subscribe form. */ selectedPlan: function () { var self = this; return _.find(this.plans, function (plan) { return plan.id == self.subscribeForm.plan; }); }, /* * Get the full selected plan price with currency symbol. */ selectedPlanPrice: function () { if (this.selectedPlan) { return this.selectedPlan.currencySymbol + this.selectedPlan.price; } }, /* * Get all of the plans that have a mnthly interval. */ monthlyPlans: function() { return _.filter(this.plans, function(plan) { return plan.interval == 'monthly' && plan.active; }); }, /* * Get all of the plans that have a yearly interval. */ yearlyPlans: function() { return _.filter(this.plans, function(plan) { return plan.interval == 'yearly' && plan.active; }); }, /* * Get all of the "default" available plans. Typically this is monthly. */ defaultPlans: function () { if (this.monthlyPlans.length > 0) { return this.monthlyPlans; } if (this.yearlyPlans.length > 0) { return this.yearlyPlans; } }, /* * Get all of the available plans except this user's current plan. * This'll typically be the monthly plans unless there are none. */ defaultPlansExceptCurrent: function () { if (this.monthlyPlansExceptCurrent.length > 0) { return this.monthlyPlansExceptCurrent; } if (this.yearlyPlansExceptCurrent.length > 0) { return this.yearlyPlansExceptCurrent; } }, /* * Get all of the monthly plans except the user's current plan. */ monthlyPlansExceptCurrent: function() { var self = this; if ( ! this.currentPlan) { return []; } return _.filter(this.monthlyPlans, function (plan) { return plan.id != self.currentPlan.id; }); }, /* * Get all of the yearly plans except the user's current plan. */ yearlyPlansExceptCurrent: function() { var self = this; if ( ! this.currentPlan) { return []; } return _.filter(this.yearlyPlans, function (plan) { return plan.id != self.currentPlan.id; }); }, /* * Get the expiratoin date for the current coupon in displayable form. */ currentCouponDisplayDiscount: function () { if (this.currentCoupon) { if (this.currentCoupon.amountOff) { return this.currentPlan.currencySymbol + this.currentCoupon.amountOff; } if (this.currentCoupon.percentOff) { return this.currentCoupon.percentOff + '%'; } } }, /* * Get the expiratoin date for the current coupon in displayable form. */ currentCouponDisplayExpiresOn: function () { return moment(this.currentCoupon.expiresOn).format('MMMM Do, YYYY'); } }, events: { /** * Handle the "userRetrieved" event. */ userRetrieved: function (user) { this.user = user; this.extraBillingInfoForm.text = this.user.extra_billing_info; if (this.user.stripe_id) { this.getCoupon(); } } }, methods: { /* * Get the coupon currently applying to the customer. */ getCoupon: function () { this.$http.get('spark/api/subscriptions/user/coupon') .success(function (coupon) { this.currentCoupon = coupon; }) .error(function () { // }); }, /* * Get all of the Spark plans from the API. */ getPlans: function () { this.$http.get('spark/api/subscriptions/plans') .success(function (plans) { this.plans = plans; }); }, /* * Subscribe the user to a new plan. */ subscribe: function () { var self = this; this.subscribeForm.errors = []; this.subscribeForm.subscribing = true; /* * Here we will build the payload to send to Stripe, which will * return a token. This token can be used to make charges on * the user's credit cards instead of storing the numbers. */ var payload = { name: this.user.name, number: this.cardForm.number, cvc: this.cardForm.cvc, exp_month: this.cardForm.month, exp_year: this.cardForm.year, address_zip: this.cardForm.zip }; Stripe.card.createToken(payload, function (status, response) { if (response.error) { self.subscribeForm.errors.push(response.error.message); self.subscribeForm.subscribing = false; } else { self.subscribeForm.stripe_token = response.id; self.sendSubscription(); } }); }, /* * Subscribe the user to a new plan. */ sendSubscription: function () { this.$http.post('settings/user/plan', this.subscribeForm) .success(function (user) { this.user = user; this.subscribeForm.subscribing = false; }) .error(function (errors) { Spark.setErrorsOnForm(this.subscribeForm, errors); this.subscribeForm.subscribing = false; }); }, /* * Reset the subscription form plan to allow another plan to be selected. */ selectAnotherPlan: function () { this.subscribeForm.plan = ''; }, /* * Show the modal screen to select another subscription plan. */ confirmPlanChange: function() { this.changePlanForm.errors = []; this.changePlanForm.changing = false; $('#modal-change-plan').modal('show'); this.initializeTooltips(); }, /* * Subscribe the user to another subscription plan. */ changePlan: function() { this.changePlanForm.errors = []; this.changePlanForm.changing = true; this.$http.put('settings/user/plan', { plan: this.changePlanForm.plan }) .success(function (user) { this.user = user; this.$dispatch('updateUser'); /* * We need to re-initialize the tooltips on the screen because * some of the plans may not have been displayed yet if the * users just "switched" plans to another available plan. */ $('#modal-change-plan').modal('hide'); this.initializeTooltips(); this.changePlanForm.changing = false; }) .error(function (errors) { this.changePlanForm.changing = false; Spark.setErrorsOnForm(this.changePlanForm, errors); }); }, /* * Update the user's subscription billing card (Stripe portion). */ updateCard: function (e) { var self = this; e.preventDefault(); this.updateCardForm.errors = []; this.updateCardForm.updated = false; this.updateCardForm.updating = true; /* * Here we will build the payload to send to Stripe, which will * return a token. This token can be used to make charges on * the user's credit cards instead of storing the numbers. */ var payload = { name: this.user.name, number: this.updateCardForm.number, cvc: this.updateCardForm.cvc, exp_month: this.updateCardForm.month, exp_year: this.updateCardForm.year, address_zip: this.updateCardForm.zip }; Stripe.card.createToken(payload, function (status, response) { if (response.error) { self.updateCardForm.errors.push(response.error.message); self.updateCardForm.updating = false; } else { self.updateCardUsingToken(response.id); } }); }, /* * Update the user's subscription billing card. */ updateCardUsingToken: function (token) { this.$http.put('settings/user/card', { stripe_token: token }) .success(function (user) { this.user = user; this.updateCardForm = settingsSubscriptionScreenForms.updateCard(); this.updateCardForm.updated = true; }) .error(function (errors) { this.updateCardForm.updating = false; Spark.setErrorsOnForm(this.updateCardForm, errors); }); }, /* * Update the user's extra billing information. */ updateExtraBillingInfo: function () { this.extraBillingInfoForm.errors = []; this.extraBillingInfoForm.updated = false; this.extraBillingInfoForm.updating = true; this.$http.put('settings/user/vat', this.extraBillingInfoForm) .success(function () { this.extraBillingInfoForm.updated = true; this.extraBillingInfoForm.updating = false; }) .error(function (errors) { Spark.setErrorsOnForm(this.extraBillingInfoForm, errors); this.extraBillingInfoForm.updating = false; }); }, /* * Display the modal window to confirm subscription deletion. */ confirmSubscriptionCancellation: function () { $('#modal-cancel-subscription').modal('show'); }, /* * Cancel the user's subscription with Stripe. */ cancelSubscription: function () { this.cancelSubscriptionForm.errors = []; this.cancelSubscriptionForm.cancelling = true; this.$http.delete('settings/user/plan') .success(function (user) { var self = this; this.user = user; $('#modal-cancel-subscription').modal('hide'); setTimeout(function () { self.cancelSubscriptionForm.cancelling = false; }, 500); }) .error(function (errors) { this.cancelSubscriptionForm.cancelling = false; Spark.setErrorsOnForm(this.cancelSubscriptionForm, errors); }); }, /* * Resume the user's subscription on Stripe. */ resumeSubscription: function () { this.resumeSubscriptionForm.errors = []; this.resumeSubscriptionForm.resuming = true; this.$http.post('settings/user/plan/resume') .success(function (user) { this.user = user; this.resumeSubscriptionForm.resuming = false; }) .error(function (errors) { this.resumeSubscriptionForm.resuming = false; Spark.setErrorsOnForm(this.resumeSubscriptionForm, errors); }); }, /* * Get the feature list from the plan formatted for a tooltip. */ getPlanFeaturesForTooltip: function (plan) { var result = '<ul>'; _.each(plan.features, function (feature) { result += '<li>' + feature + '</li>'; }); return result + '</ul>'; }, /* * Initialize the tooltips for the plan features. */ initializeTooltips: function () { setTimeout(function () { $('[data-toggle="tooltip"]').tooltip({ html: true }); }, 250); } } });
import { test } from 'qunit'; import moduleForAcceptance from '../../tests/helpers/module-for-acceptance'; import Materialize from 'materialize'; moduleForAcceptance('Materialize Shim Tests'); test('Installation verification', function(assert) { visit('/'); andThen(function() { assert.ok( find('#title') .css('font-family') .indexOf('Roboto') >= 0, 'Stylesheet is installed' ); assert.equal( find('.material-icons') .css('font-family') .replace(/['"]/g, ''), 'Material Icons', 'Icons are installed' ); assert.equal(typeof Materialize, 'object', 'JS is installed as an ES6 module'); assert.equal(currentURL(), '/'); }); });
var activeRequests = {} var requestCounter = 0; mtajax = {} mtajax.makeRequest = function () { var args = Array.prototype.slice.call(arguments); var arglist = [ "onClientAJAXRequest", requestCounter ]; arglist.push.apply(arglist, args); mta.triggerEvent.apply(null, arglist) var def = $.Deferred(); activeRequests[requestCounter] = def; requestCounter++; return def.promise(); } mtajax.triggerCallback = function (callid, good, args) { if(good) activeRequests[callid].resolve.apply(null, jQuery.parseJSON(args)); else activeRequests[callid].reject(); }
/* * Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to 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. * */ /*jslint vars: true, plusplus: true, devel: true, browser: true, nomen: true, indent: 4, maxerr: 50 */ /*global define, describe, it, expect, beforeEach, afterEach, waits, runs, $, brackets, waitsForDone, spyOn */ define(function (require, exports, module) { "use strict"; // Modules from the SpecRunner window var KeyEvent = brackets.getModule("utils/KeyEvent"), PreferencesManager = brackets.getModule("preferences/PreferencesManager"), SpecRunnerUtils = brackets.getModule("spec/SpecRunnerUtils"), testContentCSS = require("text!unittest-files/unittests.css"), testContentHTML = require("text!unittest-files/unittests.html"), provider = require("main").inlineColorEditorProvider, InlineColorEditor = require("InlineColorEditor").InlineColorEditor, ColorEditor = require("ColorEditor").ColorEditor, tinycolor = require("thirdparty/tinycolor-min"); describe("Inline Color Editor - unit", function () { var testDocument, testEditor, inline; /** * Creates an inline color editor connected to the given cursor position in the test editor. * Note that this does *not* actually open it as an inline editor in the test editor. * Tests that use this must wrap their contents in a runs() block. * @param {!{line:number, ch: number}} cursor Position for which to open the inline editor. * if the provider did not create an inline editor. */ function makeColorEditor(cursor) { runs(function () { var promise = provider(testEditor, cursor); if (promise) { promise.done(function (inlineResult) { inlineResult.onAdded(); inline = inlineResult; }); waitsForDone(promise, "open color editor"); } }); } /** * Expects an inline editor to be opened at the given cursor position and to have the * given initial color (which should match the color at that position). * @param {!{line:number, ch:number}} cursor The cursor position to try opening the inline at. * @param {string} color The expected color. */ function testOpenColor(cursor, color) { makeColorEditor(cursor); runs(function () { expect(inline).toBeTruthy(); expect(inline._color).toBe(color); }); } /** * Simulate the given event with clientX/clientY specified by the given * ratios of the item's actual width/height (offset by the left/top of the * item). * @param {string} event The name of the event to simulate. * @param {object} $item A jQuery object to trigger the event on. * @param {Array.<number>} ratios Numbers between 0 and 1 indicating the x and y positions of the * event relative to the item's width and height. */ function eventAtRatio(event, $item, ratios) { $item.trigger($.Event(event, { clientX: $item.offset().left + (ratios[0] * $item.width()), clientY: $item.offset().top + (ratios[1] * $item.height()) })); } describe("Inline editor - CSS", function () { beforeEach(function () { var mock = SpecRunnerUtils.createMockEditor(testContentCSS, "css"); testDocument = mock.doc; testEditor = mock.editor; }); afterEach(function () { SpecRunnerUtils.destroyMockEditor(testDocument); testEditor = null; testDocument = null; inline = null; }); describe("simple open cases", function () { it("should show the correct color when opened on an #rrggbb color", function () { testOpenColor({line: 1, ch: 18}, "#abcdef"); }); it("should open when at the beginning of the color", function () { testOpenColor({line: 1, ch: 16}, "#abcdef"); }); it("should open when at the end of the color", function () { testOpenColor({line: 1, ch: 23}, "#abcdef"); }); it("should show the correct color when opened on an #rgb color", function () { testOpenColor({line: 5, ch: 18}, "#abc"); }); it("should show the correct color when opened on an rgb() color", function () { testOpenColor({line: 9, ch: 18}, "rgb(100, 200, 150)"); }); it("should show the correct color when opened on an rgba() color", function () { testOpenColor({line: 13, ch: 18}, "rgba(100, 200, 150, 0.5)"); }); it("should show the correct color when opened on an hsl() color", function () { testOpenColor({line: 17, ch: 18}, "hsl(180, 50%, 50%)"); }); it("should show the correct color when opened on an hsla() color", function () { testOpenColor({line: 21, ch: 18}, "hsla(180, 50%, 50%, 0.5)"); }); it("should show the correct color when opened on an uppercase hex color", function () { testOpenColor({line: 33, ch: 18}, "#DEFCBA"); }); it("should show the correct color when opened on a color in a shorthand property", function () { testOpenColor({line: 41, ch: 27}, "#0f0f0f"); }); it("should show the correct color when opened on an rgba() color with a leading period in the alpha field", function () { testOpenColor({line: 45, ch: 18}, "rgba(100, 200, 150, .5)"); }); it("should show the correct color when opened on an hsla() color with a leading period in the alpha field", function () { testOpenColor({line: 49, ch: 18}, "hsla(180, 50%, 50%, .5)"); }); it("should not open when not on a color", function () { makeColorEditor({line: 1, ch: 6}); runs(function () { expect(inline).toEqual(null); }); }); it("should not open when on an invalid color", function () { makeColorEditor({line: 25, ch: 18}); runs(function () { expect(inline).toEqual(null); }); }); it("should not open when on an hsl color with missing percent signs", function () { makeColorEditor({line: 37, ch: 18}); runs(function (inline) { expect(inline).toEqual(null); }); }); it("should open on the second color when there are two colors in the same line", function () { testOpenColor({line: 29, ch: 48}, "#ddeeff"); }); it("should properly add/remove ref to document when opened/closed", function () { runs(function () { spyOn(testDocument, "addRef").andCallThrough(); spyOn(testDocument, "releaseRef").andCallThrough(); }); makeColorEditor({line: 1, ch: 18}); runs(function () { expect(testDocument.addRef).toHaveBeenCalled(); expect(testDocument.addRef.callCount).toBe(1); inline.onClosed(); expect(testDocument.releaseRef).toHaveBeenCalled(); expect(testDocument.releaseRef.callCount).toBe(1); }); }); }); describe("update host document on edit in color editor", function () { it("should update host document when change is committed in color editor", function () { makeColorEditor({line: 1, ch: 18}); runs(function () { inline.colorEditor.setColorFromString("#c0c0c0"); expect(testDocument.getRange({line: 1, ch: 16}, {line: 1, ch: 23})).toBe("#c0c0c0"); }); }); it("should update correct range of host document with color format of different length", function () { makeColorEditor({line: 1, ch: 18}); runs(function () { inline.colorEditor.setColorFromString("rgb(20, 20, 20)"); expect(testDocument.getRange({line: 1, ch: 16}, {line: 1, ch: 31})).toBe("rgb(20, 20, 20)"); }); }); it("should not invalidate range when change is committed", function () { makeColorEditor({line: 1, ch: 18}); runs(function () { inline.colorEditor.setColorFromString("rgb(20, 20, 20)"); expect(inline.getCurrentRange()).toBeTruthy(); }); }); }); describe("update color editor on edit in host editor", function () { it("should update when edit is made to color range in host editor", function () { makeColorEditor({line: 1, ch: 18}); runs(function () { spyOn(inline, "close"); testDocument.replaceRange("0", {line: 1, ch: 18}, {line: 1, ch: 19}); expect(inline._color).toBe("#a0cdef"); // TODO (#2201): this assumes getColor() is a tinycolor, but sometimes it's a string expect(inline.colorEditor.getColor().toHexString().toLowerCase()).toBe("#a0cdef"); expect(inline.close).not.toHaveBeenCalled(); expect(inline.getCurrentRange()).toEqual({start: {line: 1, ch: 16}, end: {line: 1, ch: 23}}); }); }); it("should close itself if edit is made that destroys end bookmark and leaves color invalid", function () { makeColorEditor({line: 1, ch: 18}); runs(function () { spyOn(inline, "close"); // Replace everything including the semicolon, so it crosses the bookmark boundary. testDocument.replaceRange("rgb(255, 25", {line: 1, ch: 16}, {line: 1, ch: 24}); expect(inline.close).toHaveBeenCalled(); }); }); it("should maintain the range if the user deletes the last character of the color and types a new one", function () { makeColorEditor({line: 1, ch: 18}); runs(function () { spyOn(inline, "close"); testDocument.replaceRange("", {line: 1, ch: 22}, {line: 1, ch: 23}); testDocument.replaceRange("0", {line: 1, ch: 22}, {line: 1, ch: 22}); expect(inline._color).toBe("#abcde0"); expect(inline.close).not.toHaveBeenCalled(); expect(inline.getCurrentRange()).toEqual({start: {line: 1, ch: 16}, end: {line: 1, ch: 23}}); }); }); it("should not update the end bookmark to a shorter valid match if the bookmark still exists and the color becomes invalid", function () { makeColorEditor({line: 1, ch: 18}); runs(function () { testDocument.replaceRange("", {line: 1, ch: 22}, {line: 1, ch: 23}); expect(inline._color).toBe("#abcde"); expect(inline.getCurrentRange()).toEqual({start: {line: 1, ch: 16}, end: {line: 1, ch: 22}}); }); }); // TODO: (issue #2166) The following test fails because if the end bookmark is deleted, we match the shorter // #xxx string at the beginning of the color and assume that's valid, and then reset the bookmark // to the end of that location. // it("should not update the end bookmark to a shorter valid match if the bookmark no longer exists and the color becomes invalid", function () { // makeColorEditor({line: 1, ch: 18}).done(function (inline) { // testDocument.replaceRange("", {line: 1, ch: 22}, {line: 1, ch: 24}); // expect(inline._color).toBe("#abcde"); // expect(inline.getCurrentRange()).toEqual({start: {line: 1, ch: 16}, end: {line: 1, ch: 22}}); // }); // }); }); describe("edit batching", function () { it("should combine multiple edits within the same inline editor into a single undo in the host editor", function () { makeColorEditor({line: 1, ch: 18}); runs(function () { inline.colorEditor.setColorFromString("#010101"); inline.colorEditor.setColorFromString("#123456"); inline.colorEditor.setColorFromString("#bdafe0"); testDocument._masterEditor._codeMirror.undo(); expect(testDocument.getRange({line: 1, ch: 16}, {line: 1, ch: 23})).toBe("#abcdef"); }); }); }); }); describe("Inline editor - HTML", function () { beforeEach(function () { var mock = SpecRunnerUtils.createMockEditor(testContentHTML, "html"); testDocument = mock.doc; testEditor = mock.editor; }); afterEach(function () { SpecRunnerUtils.destroyMockEditor(testDocument); testEditor = null; testDocument = null; }); it("should open on a color in an HTML file", function () { testOpenColor({line: 4, ch: 30}, "#dead01"); }); }); describe("Inline editor - used colors processing", function () { it("should trim the original array to the given length", function () { var inline = new InlineColorEditor(); var result = inline._collateColors(["#abcdef", "#fedcba", "#aabbcc", "#bbccdd"], 2); expect(result).toEqual([ {value: "#abcdef", count: 1}, {value: "#fedcba", count: 1} ]); }); it("should remove duplicates from the original array and sort it by usage", function () { var inline = new InlineColorEditor(); var result = inline._collateColors(["#abcdef", "#fedcba", "#123456", "#FEDCBA", "#123456", "#123456", "rgb(100, 100, 100)"], 100); expect(result).toEqual([ {value: "#123456", count: 3}, {value: "#fedcba", count: 2}, {value: "#abcdef", count: 1}, {value: "rgb(100, 100, 100)", count: 1} ]); }); }); describe("Color editor UI", function () { var colorEditor, defaultSwatches = [{value: "#abcdef", count: 3}, {value: "rgba(100, 200, 250, 0.5)", count: 2}]; /** * Creates a hidden ColorEditor and appends it to the body. Note that this is a standalone * ColorEditor, not inside an InlineColorEditor. * @param {string} initialColor The color that should be initially set in the ColorEditor. * @param {?function} callback An optional callback to be passed as the ColorEditor's callback. If * none is supplied, a dummy function is passed. * @param {?Array.<{value:string, count:number}>} swatches An optional array of swatches to display. * If none is supplied, a default set of two swatches is passed. * @param {boolean=} hide Whether to hide the color picker; default is true. */ function makeUI(initialColor, callback, swatches, hide) { colorEditor = new ColorEditor($(document.body), initialColor, callback || function () { }, swatches || defaultSwatches); if (hide !== false) { colorEditor.getRootElement().css("display", "none"); } } afterEach(function () { colorEditor.getRootElement().remove(); }); /** * Checks whether the difference between val1 and val2 is within the given tolerance. * (We can't use Jasmine's .toBeCloseTo() because that takes a precision in decimal places, * whereas we often need to check an absolute distance.) * @param {(number|string)} val1 The first value to check. * @param {(number|string)} val2 The second value to check. * @param {number} tolerance The desired tolerance. */ function checkNear(val1, val2, tolerance) { expect(Math.abs(Number(val1) - Number(val2)) < (tolerance || 1.0)).toBe(true); } /** * Checks whether the given percentage string is near the given value. * @param {string} pct The percentage to check. Assumed to be a string ending in "%". * @param {number} val The value to check against. Assumed to be a percentage number, but not ending in "%". */ function checkPercentageNear(pct, val) { expect(checkNear(pct.substr(0, pct.length - 1), val)); } /** Returns the colorEditor's current value as a string in its current format */ function getColorString() { return tinycolor(colorEditor.getColor()).getOriginalInput(); } describe("simple load/commit", function () { it("should load the initial color correctly", function () { var colorStr = "rgba(77, 122, 31, 0.5)"; var colorStrRgb = "rgb(77, 122, 31)"; runs(function () { makeUI(colorStr); expect(colorEditor.getColor().getOriginalInput()).toBe(colorStr); expect(colorEditor.$colorValue.val()).toBe(colorStr); expect(tinycolor.equals(colorEditor.$currentColor.css("background-color"), colorStr)).toBe(true); // Not sure why the tolerances need to be larger for these. checkNear(tinycolor(colorEditor.$selection.css("background-color")).toHsv().h, 90, 2.0); checkNear(tinycolor(colorEditor.$hueBase.css("background-color")).toHsv().h, 90, 2.0); expect(tinycolor.equals(colorEditor.$selectionBase.css("background-color"), colorStrRgb)).toBe(true); }); // Need to do these on a timeout since we can't seem to read back CSS positions synchronously. waits(1); runs(function () { checkPercentageNear(colorEditor.$hueSelector[0].style.bottom, 25); checkPercentageNear(colorEditor.$opacitySelector[0].style.bottom, 50); checkPercentageNear(colorEditor.$selectionBase[0].style.left, 74); checkPercentageNear(colorEditor.$selectionBase[0].style.bottom, 47); }); }); it("should load a committed color correctly", function () { var colorStr = "rgba(77, 122, 31, 0.5)"; var colorStrRgb = "rgb(77, 122, 31)"; runs(function () { makeUI("#0a0a0a"); colorEditor.setColorFromString(colorStr); expect(colorEditor.getColor().getOriginalInput()).toBe(colorStr); expect(colorEditor.$colorValue.val()).toBe(colorStr); expect(tinycolor.equals(colorEditor.$currentColor.css("background-color"), colorStr)).toBe(true); checkNear(tinycolor(colorEditor.$selection.css("background-color")).toHsv().h, tinycolor(colorStr).toHsv().h); checkNear(tinycolor(colorEditor.$hueBase.css("background-color")).toHsv().h, tinycolor(colorStr).toHsv().h); expect(tinycolor.equals(colorEditor.$selectionBase.css("background-color"), colorStrRgb)).toBe(true); }); // Need to do these on a timeout since we can't seem to read back CSS positions synchronously. waits(1); runs(function () { checkPercentageNear(colorEditor.$hueSelector[0].style.bottom, 25); checkPercentageNear(colorEditor.$opacitySelector[0].style.bottom, 50); checkPercentageNear(colorEditor.$selectionBase[0].style.left, 74); checkPercentageNear(colorEditor.$selectionBase[0].style.bottom, 47); }); }); it("should call the callback when a new color is committed", function () { var lastColor; makeUI("rgba(100, 100, 100, 0.5)", function (color) { lastColor = color; }); colorEditor.setColorFromString("#a0a0a0"); expect(lastColor).toBe("#a0a0a0"); }); }); /** * Test whether converting the given color to the given mode results in the expected color. * @param {string} initialColor The color to convert. * @param {string} mode The mode to convert to: must be "rgba", "hsla", or "hex". * @param {string} result The expected result of the conversion. */ function testConvert(initialColor, mode, result) { makeUI(initialColor); var buttonMap = { "rgba": "$rgbaButton", "hsla": "$hslButton", "hex": "$hexButton" }; colorEditor[buttonMap[mode]].trigger("click"); expect(colorEditor.getColor().getOriginalInput()).toBe(result); } describe("conversions in lower case", function () { it("should convert a hex color to rgb when mode button clicked", function () { testConvert("#112233", "rgba", "rgb(17, 34, 51)"); }); it("should convert a hex color to hsl when mode button clicked", function () { testConvert("#112233", "hsla", "hsl(210, 50%, 13%)"); }); it("should convert an rgb color to hex when mode button clicked", function () { testConvert("rgb(15, 160, 21)", "hex", "#0fa015"); }); it("should convert an rgba color to hex (dropping alpha) when mode button clicked", function () { testConvert("rgba(15, 160, 21, 0.5)", "hex", "#0fa015"); }); it("should convert an rgb color to hsl when mode button clicked", function () { testConvert("rgb(15, 160, 21)", "hsla", "hsl(122, 83%, 34%)"); }); it("should convert an rgba color to hsla when mode button clicked", function () { testConvert("rgba(15, 160, 21, 0.3)", "hsla", "hsla(122, 83%, 34%, 0.3)"); }); it("should convert an hsl color to hex when mode button clicked", function () { testConvert("hsl(152, 12%, 22%)", "hex", "#313f39"); }); it("should convert an hsla color to hex (dropping alpha) when mode button clicked", function () { testConvert("hsla(152, 12%, 22%, 0.7)", "hex", "#313f39"); }); it("should convert an hsl color to rgb when mode button clicked", function () { testConvert("hsl(152, 12%, 22%)", "rgba", "rgb(49, 63, 57)"); }); it("should convert an hsla color to rgba when mode button clicked", function () { testConvert("hsla(152, 12%, 22%, 0.7)", "rgba", "rgba(49, 63, 57, 0.7)"); }); it("should convert a mixed case hsla color to rgba when mode button clicked", function () { testConvert("HsLa(152, 12%, 22%, 0.7)", "rgba", "rgba(49, 63, 57, 0.7)"); }); it("should convert a mixed case hex color to rgb when mode button clicked", function () { testConvert("#fFfFfF", "rgba", "rgb(255, 255, 255)"); }); }); describe("conversions in UPPER CASE", function () { beforeEach(function () { // Enable uppercase colors PreferencesManager.set("uppercaseColors", true); }); afterEach(function () { // Re-disable uppercase colors PreferencesManager.set("uppercaseColors", false); }); it("should use uppercase colors", function () { expect(PreferencesManager.get("uppercaseColors")).toBe(true); }); it("should convert a hex color to rgb in uppercase when mode button clicked", function () { testConvert("#112233", "rgba", "RGB(17, 34, 51)"); }); it("should convert a hex color to hsl in uppercase when mode button clicked", function () { testConvert("#112233", "hsla", "HSL(210, 50%, 13%)"); }); it("should convert an rgb color to hex in uppercase when mode button clicked", function () { testConvert("RGB(15, 160, 21)", "hex", "#0FA015"); }); it("should convert an rgba color to hex (dropping alpha) in uppercase when mode button clicked", function () { testConvert("RGBA(15, 160, 21, 0.5)", "hex", "#0FA015"); }); it("should convert an rgb color to hsl in uppercase when mode button clicked", function () { testConvert("RGB(15, 160, 21)", "hsla", "HSL(122, 83%, 34%)"); }); it("should convert an rgba color to hsla in uppercase when mode button clicked", function () { testConvert("RGBA(15, 160, 21, 0.3)", "hsla", "HSLA(122, 83%, 34%, 0.3)"); }); it("should convert an hsl color to hex in uppercase when mode button clicked", function () { testConvert("HSL(152, 12%, 22%)", "hex", "#313F39"); }); it("should convert an hsla color to hex (dropping alpha) in uppercase when mode button clicked", function () { testConvert("HSLA(152, 12%, 22%, 0.7)", "hex", "#313F39"); }); it("should convert an hsl color to rgb in uppercase when mode button clicked", function () { testConvert("HSL(152, 12%, 22%)", "rgba", "RGB(49, 63, 57)"); }); it("should convert an hsla color to rgba in uppercase when mode button clicked", function () { testConvert("HSLA(152, 12%, 22%, 0.7)", "rgba", "RGBA(49, 63, 57, 0.7)"); }); it("should convert a mixed case hsla color to rgba in uppercase when mode button clicked", function () { testConvert("HsLa(152, 12%, 22%, 0.7)", "rgba", "RGBA(49, 63, 57, 0.7)"); }); it("should convert a mixed case hex color to rgb in uppercase when mode button clicked", function () { testConvert("#fFfFfF", "rgba", "RGB(255, 255, 255)"); }); }); describe("parameter editing with mouse", function () { /** * Test a mouse down event on the given UI element. * @param {object} opts The parameters to test: * item: The (string) name of the member of ColorEditor that references the element to test. * clickAt: An [x, y] array specifying the simulated x/y mouse position as a fraction of the * item's width/height. For example, [0.5, 0.5] would specify a click exactly in the * center of the element. * param: The (string) parameter whose value we're testing (h, s, v, or a). * expected: The expected value for the parameter. * tolerance: The tolerance in variation for the expected value. */ function testMousedown(opts) { makeUI("#0000ff"); eventAtRatio("mousedown", colorEditor[opts.item], opts.clickAt); checkNear(tinycolor(colorEditor.getColor()).toHsv()[opts.param], opts.expected, opts.tolerance); colorEditor[opts.item].trigger("mouseup"); // clean up drag state } /** * Test a drag event on the given UI element. * @param {object} opts The parameters to test: * item: The (string) name of the member of ColorEditor that references the element to test. * clickAt: An [x, y] array specifying the simulated x/y mouse position for the initial mouse down * as a fraction of the item's width/height. For example, [0.5, 0.5] would specify a click * exactly in the center of the element. * dragTo: An [x, y] array specifying the location to drag to, using the same convention as clickAt. * param: The (string) parameter whose value we're testing (h, s, v, or a). * expected: The expected value for the parameter. * tolerance: The tolerance in variation for the expected value. */ function testDrag(opts) { makeUI("#0000ff"); eventAtRatio("mousedown", colorEditor[opts.item], opts.clickAt); eventAtRatio("mousemove", colorEditor[opts.item], opts.dragTo); checkNear(tinycolor(colorEditor.getColor()).toHsv()[opts.param], opts.expected, opts.tolerance); colorEditor[opts.item].trigger("mouseup"); // clean up drag state } it("should set saturation on mousedown", function () { testMousedown({ item: "$selection", clickAt: [0.25, 0], // x: saturation, y: 1.0 - value param: "s", expected: 0.25, tolerance: 0.1 }); }); it("should set saturation on drag", function () { testDrag({ item: "$selection", clickAt: [0.25, 0], // x: saturation, y: 1.0 - value dragTo: [0.75, 0], param: "s", expected: 0.75, tolerance: 0.1 }); }); it("should clip saturation to min value", function () { testDrag({ item: "$selection", clickAt: [0.25, 0], // x: saturation, y: 1.0 - value dragTo: [-0.25, 0], param: "s", expected: 0, tolerance: 0.1 }); }); it("should clip saturation to max value", function () { testDrag({ item: "$selection", clickAt: [0.25, 0], // x: saturation, y: 1.0 - value dragTo: [1.25, 0], param: "s", expected: 1, tolerance: 0.1 }); }); it("should set value on mousedown", function () { testMousedown({ item: "$selection", clickAt: [1.0, 0.75], // x: saturation, y: 1.0 - value param: "v", expected: 0.25, tolerance: 0.1 }); }); it("should set value on drag", function () { testDrag({ item: "$selection", clickAt: [1.0, 0.75], // x: saturation, y: 1.0 - value dragTo: [1.0, 0.25], param: "v", expected: 0.75, tolerance: 0.1 }); }); it("should clip value to min value", function () { testDrag({ item: "$selection", clickAt: [1.0, 0.75], // x: saturation, y: 1.0 - value dragTo: [1.0, 1.25], param: "v", expected: 0, tolerance: 0.1 }); }); it("should clip value to max value", function () { testDrag({ item: "$selection", clickAt: [1.0, 0.75], dragTo: [1.0, -0.25], param: "v", expected: 1, tolerance: 0.1 }); }); it("should set hue on mousedown", function () { testMousedown({ item: "$hueSlider", clickAt: [0, 0.75], // x: unused, y: 1.0 - (hue / 360) param: "h", expected: 90, tolerance: 1 }); }); it("should set hue on drag", function () { testDrag({ item: "$hueSlider", clickAt: [0, 0.75], // x: unused, y: 1.0 - (hue / 360) dragTo: [0, 0.25], param: "h", expected: 270, tolerance: 1 }); }); it("should clip hue to min value", function () { testDrag({ item: "$hueSlider", clickAt: [0, 0.75], // x: unused, y: 1.0 - (hue / 360) dragTo: [0, 1.25], param: "h", expected: 0, tolerance: 1 }); }); it("should clip hue to max value", function () { testDrag({ item: "$hueSlider", clickAt: [0, 0.75], // x: unused, y: 1.0 - (hue / 360) dragTo: [0, -0.25], param: "h", expected: 0, tolerance: 1 }); }); it("should set opacity on mousedown", function () { testMousedown({ item: "$opacitySlider", clickAt: [0, 0.75], // x: unused, y: 1.0 - opacity param: "a", expected: 0.25, tolerance: 0.1 }); }); it("should set opacity on drag", function () { testDrag({ item: "$opacitySlider", clickAt: [0, 0.75], // x: unused, y: 1.0 - opacity dragTo: [0, 0.25], param: "a", expected: 0.75, tolerance: 0.1 }); }); it("should clip opacity to min value", function () { testDrag({ item: "$opacitySlider", clickAt: [0, 0.75], // x: unused, y: 1.0 - opacity dragTo: [0, 1.25], param: "a", expected: 0, tolerance: 0.1 }); }); it("should clip opacity to max value", function () { // A increases going up, so a clientY at -0.25 of the item's height corresponds to >100%. testDrag({ item: "$opacitySlider", clickAt: [0, 0.75], // x: unused, y: 1.0 - opacity dragTo: [0, -0.25], param: "a", expected: 1, tolerance: 0.1 }); }); }); describe("parameter editing with keyboard", function () { function makeKeyEvent(opts) { return $.Event("keydown", { keyCode: opts.key, shiftKey: !!opts.shift }); } /** * Test a key event on the given UI element. * @param {object} opts The parameters to test: * color: An optional initial value to set in the ColorEditor. Defaults to "hsla(50, 25%, 50%, 0.5)". * item: The (string) name of the member of ColorEditor that references the element to test. * key: The KeyEvent key code to simulate. * shift: Optional boolean specifying whether to simulate the shift key being down (default false). * param: The (string) parameter whose value we're testing (h, s, v, or a). * delta: The expected change in value for the parameter. * tolerance: The tolerance in variation for the expected value. * exact: True to compare the actual values stored in the _hsv object, false (default) to * compare tinycolor's normalization of the color value. */ function testKey(opts) { function getParam() { if (opts.exact) { var result = colorEditor._hsv[opts.param]; // Because of #2201, this is sometimes a string with a percentage value. if (typeof result === "string" && result.charAt(result.length - 1) === "%") { result = Number(result.substr(0, result.length - 1)); } return result; } else { return tinycolor(colorEditor.getColor()).toHsv()[opts.param]; } } makeUI(opts.color || "hsla(50, 25%, 50%, 0.5)"); var before = getParam(); colorEditor[opts.item].trigger(makeKeyEvent(opts)); var after = getParam(); checkNear(after, before + opts.delta, opts.tolerance); } /** * Test whether the given event's default is or isn't prevented on a given key. * @param {object} opts The parameters to test: * color: An optional initial value to set in the ColorEditor. Defaults to "hsla(50, 25%, 50%, 0.5)". * item: The (string) name of the member of ColorEditor that references the element to test. * selection: An optional array ([start, end]) specifying the selection to set in the given element. * key: The KeyEvent key code to simulate. * shift: Optional boolean specifying whether to simulate the shift key being down (default false). * expected: Whether the default is expected to be prevented. */ function testPreventDefault(opts) { var event, $item; // The color picker needs to be displayed for this test; otherwise the // selection won't be properly set, because you can only set the selection // when the text field has focus. makeUI(opts.color || "hsla(50, 25%, 50%, 0.5)", function () { }, defaultSwatches, false); $item = colorEditor[opts.item]; $item.focus(); if (opts.selection) { $item[0].setSelectionRange(opts.selection[0], opts.selection[1]); } event = makeKeyEvent(opts); $item.trigger(event); expect(event.isDefaultPrevented()).toBe(opts.expected); } it("should increase saturation by 1.5% on right arrow", function () { testKey({ item: "$selectionBase", key: KeyEvent.DOM_VK_RIGHT, param: "s", delta: 0.015, tolerance: 0.01 }); }); it("should clip max saturation on right arrow", function () { testKey({ color: "hsla(50, 100%, 50%, 0.5)", item: "$selectionBase", key: KeyEvent.DOM_VK_RIGHT, param: "s", delta: 0, tolerance: 0.01 }); }); it("should increase saturation by 7.5% on shift right arrow", function () { testKey({ item: "$selectionBase", key: KeyEvent.DOM_VK_RIGHT, shift: true, param: "s", delta: 0.075, tolerance: 0.01 }); }); it("should clip max saturation on shift right arrow", function () { testKey({ color: "hsla(50, 100%, 50%, 0.5)", item: "$selectionBase", key: KeyEvent.DOM_VK_RIGHT, shift: true, param: "s", delta: 0, tolerance: 0.01 }); }); it("should decrease saturation by 1.5% on left arrow", function () { testKey({ item: "$selectionBase", key: KeyEvent.DOM_VK_LEFT, param: "s", delta: -0.015, tolerance: 0.01 }); }); it("should clip min saturation on left arrow", function () { testKey({ color: "hsla(50, 0%, 50%, 0.5)", item: "$selectionBase", key: KeyEvent.DOM_VK_LEFT, param: "s", delta: 0, tolerance: 0.01 }); }); it("should decrease saturation by 7.5% on shift left arrow", function () { testKey({ item: "$selectionBase", key: KeyEvent.DOM_VK_LEFT, shift: true, param: "s", delta: -0.075, tolerance: 0.01 }); }); it("should clip min saturation on shift left arrow", function () { testKey({ color: "hsla(50, 0%, 50%, 0.5)", item: "$selectionBase", key: KeyEvent.DOM_VK_LEFT, shift: true, param: "s", delta: 0, tolerance: 0.01 }); }); it("should increase value by 1.5% on up arrow", function () { testKey({ item: "$selectionBase", key: KeyEvent.DOM_VK_UP, param: "v", delta: 0.015, tolerance: 0.01 }); }); it("should clip max value on up arrow", function () { testKey({ color: "hsla(50, 25%, 100%, 0.5)", item: "$selectionBase", key: KeyEvent.DOM_VK_UP, param: "v", delta: 0, tolerance: 0.01 }); }); it("should increase value by 7.5% on shift up arrow", function () { testKey({ item: "$selectionBase", key: KeyEvent.DOM_VK_UP, shift: true, param: "v", delta: 0.075, tolerance: 0.01 }); }); it("should clip max value on shift up arrow", function () { testKey({ color: "hsla(50, 25%, 100%, 0.5)", item: "$selectionBase", key: KeyEvent.DOM_VK_UP, shift: true, param: "v", delta: 0, tolerance: 0.01 }); }); it("should decrease value by 1.5% on down arrow", function () { testKey({ item: "$selectionBase", key: KeyEvent.DOM_VK_DOWN, param: "v", delta: -0.015, tolerance: 0.01 }); }); it("should clip min value on down arrow", function () { testKey({ color: "hsla(50, 25%, 0%, 0.5)", item: "$selectionBase", key: KeyEvent.DOM_VK_DOWN, param: "v", delta: 0, tolerance: 0.01 }); }); it("should decrease value by 7.5% on shift down arrow", function () { testKey({ item: "$selectionBase", key: KeyEvent.DOM_VK_DOWN, shift: true, param: "v", delta: -0.075, tolerance: 0.01 }); }); it("should clip min value on shift down arrow", function () { testKey({ color: "hsla(50, 25%, 0%, 0.5)", item: "$selectionBase", key: KeyEvent.DOM_VK_DOWN, shift: true, param: "v", delta: 0, tolerance: 0.01 }); }); it("should increase hue by 3.6 on up arrow", function () { testKey({ item: "$hueBase", key: KeyEvent.DOM_VK_UP, param: "h", delta: 3.6, tolerance: 1 }); }); it("should wrap around max hue on up arrow", function () { testKey({ color: "hsla(359, 25%, 50%, 0.5)", item: "$hueBase", key: KeyEvent.DOM_VK_UP, param: "h", delta: -359 + 3.6, tolerance: 1 }); }); it("should increase hue by 18 on shift up arrow", function () { testKey({ item: "$hueBase", key: KeyEvent.DOM_VK_UP, shift: true, param: "h", delta: 18, tolerance: 1 }); }); it("should wrap around max hue on shift up arrow", function () { testKey({ color: "hsla(359, 25%, 50%, 0.5)", item: "$hueBase", key: KeyEvent.DOM_VK_UP, shift: true, param: "h", delta: -359 + 18, tolerance: 1 }); }); it("should decrease hue by 3.6 on down arrow", function () { testKey({ item: "$hueBase", key: KeyEvent.DOM_VK_DOWN, param: "h", delta: -3.6, tolerance: 1 }); }); it("should wrap around min hue on down arrow", function () { testKey({ color: "hsla(0, 25%, 50%, 0.5)", item: "$hueBase", key: KeyEvent.DOM_VK_DOWN, param: "h", delta: 360 - 3.6, tolerance: 1 }); }); it("should decrease hue by 18 on shift down arrow", function () { testKey({ item: "$hueBase", key: KeyEvent.DOM_VK_DOWN, shift: true, param: "h", delta: -18, tolerance: 1 }); }); it("should wrap around min hue on shift down arrow", function () { testKey({ color: "hsla(0, 25%, 50%, 0.5)", item: "$hueBase", key: KeyEvent.DOM_VK_DOWN, shift: true, param: "h", delta: 360 - 18, tolerance: 1 }); }); it("should increase opacity by 0.01 on up arrow", function () { testKey({ item: "$opacitySelector", key: KeyEvent.DOM_VK_UP, param: "a", delta: 0.01, tolerance: 0.005 }); }); it("should clip max opacity on up arrow", function () { testKey({ color: "hsla(90, 25%, 50%, 1.0)", item: "$opacitySelector", key: KeyEvent.DOM_VK_UP, param: "a", delta: 0, tolerance: 0.005 }); }); it("should increase opacity by 0.05 on shift up arrow", function () { testKey({ item: "$opacitySelector", key: KeyEvent.DOM_VK_UP, shift: true, param: "a", delta: 0.05, tolerance: 0.005 }); }); it("should clip max opacity on shift up arrow", function () { testKey({ color: "hsla(90, 25%, 50%, 1.0)", item: "$opacitySelector", key: KeyEvent.DOM_VK_UP, shift: true, param: "a", delta: 0, tolerance: 0.005 }); }); it("should decrease opacity by 0.01 on down arrow", function () { testKey({ item: "$opacitySelector", key: KeyEvent.DOM_VK_DOWN, param: "a", delta: -0.01, tolerance: 0.005 }); }); it("should clip min opacity on down arrow", function () { testKey({ color: "hsla(90, 25%, 50%, 0)", item: "$opacitySelector", key: KeyEvent.DOM_VK_DOWN, param: "a", delta: 0, tolerance: 0.005 }); }); it("should decrease opacity by 0.05 on shift down arrow", function () { testKey({ item: "$opacitySelector", key: KeyEvent.DOM_VK_DOWN, shift: true, param: "a", delta: -0.05, tolerance: 0.005 }); }); it("should clip min opacity on shift down arrow", function () { testKey({ color: "hsla(90, 25%, 50%, 0)", item: "$opacitySelector", key: KeyEvent.DOM_VK_DOWN, shift: true, param: "a", delta: 0, tolerance: 0.005 }); }); // For #2138 it("should increase hue by 18 on shift up arrow even if saturation is 0", function () { testKey({ color: "hsl(180, 0, 0)", item: "$hueBase", key: KeyEvent.DOM_VK_UP, shift: true, param: "h", delta: 18, tolerance: 1, exact: true }); }); it("should increase hue by 18 on shift up arrow for a near-gray hex color", function () { testKey({ color: "#5c5b56", item: "$hueBase", key: KeyEvent.DOM_VK_UP, shift: true, param: "h", delta: 18, tolerance: 1, exact: true }); }); it("should not change value when hue changes", function () { testKey({ color: "#8e8247", item: "$hueBase", key: KeyEvent.DOM_VK_UP, shift: true, param: "v", delta: 0, tolerance: 0.01, exact: true }); }); // For #2193 and #2229 it("should prevent default on the key event for an unhandled arrow key on non-text-field", function () { testPreventDefault({ color: "#8e8247", item: "$hueBase", key: KeyEvent.DOM_VK_RIGHT, expected: true }); }); it("should prevent default on left arrow at the start of the text field", function () { testPreventDefault({ color: "#8e8247", item: "$colorValue", selection: [0, 0], key: KeyEvent.DOM_VK_LEFT, expected: true }); }); it("should not prevent default on left arrow in the middle of the text field", function () { testPreventDefault({ color: "#8e8247", item: "$colorValue", selection: [3, 3], key: KeyEvent.DOM_VK_LEFT, expected: false }); }); it("should not prevent default on left arrow at the end of the text field", function () { testPreventDefault({ color: "#8e8247", item: "$colorValue", selection: [7, 7], key: KeyEvent.DOM_VK_LEFT, expected: false }); }); it("should not prevent default on left arrow with a range selection", function () { testPreventDefault({ color: "#8e8247", item: "$colorValue", selection: [0, 7], key: KeyEvent.DOM_VK_LEFT, expected: false }); }); it("should not prevent default on right arrow at the start of the text field", function () { testPreventDefault({ color: "#8e8247", item: "$colorValue", selection: [0, 0], key: KeyEvent.DOM_VK_RIGHT, expected: false }); }); it("should not prevent default on right arrow in the middle of the text field", function () { testPreventDefault({ color: "#8e8247", item: "$colorValue", selection: [3, 3], key: KeyEvent.DOM_VK_RIGHT, expected: false }); }); it("should prevent default on right arrow at the end of the text field", function () { testPreventDefault({ color: "#8e8247", item: "$colorValue", selection: [7, 7], key: KeyEvent.DOM_VK_RIGHT, expected: true }); }); it("should not prevent default on right arrow with a range selection", function () { testPreventDefault({ color: "#8e8247", item: "$colorValue", selection: [0, 7], key: KeyEvent.DOM_VK_RIGHT, expected: false }); }); }); describe("color swatches and original color", function () { it("should restore to original color when clicked on", function () { makeUI("#abcdef"); colorEditor.setColorFromString("#0000ff"); colorEditor.$originalColor.trigger("click"); expect(tinycolor(colorEditor.getColor()).toHexString()).toBe("#abcdef"); }); it("should create swatches", function () { makeUI("#abcdef"); expect($(".swatch").length).toBe(2); }); it("should set color to a swatch when clicked on", function () { makeUI("#fedcba"); $($(".swatch")[0]).trigger("click"); expect(tinycolor(colorEditor.getColor()).toHexString()).toBe("#abcdef"); }); }); describe("input text field syncing", function () { it("should commit valid changes made in the input field on the input event", function () { makeUI("#abcdef"); colorEditor.$colorValue.val("#fedcba"); colorEditor.$colorValue.trigger("input"); expect(tinycolor(colorEditor.getColor()).toHexString()).toBe("#fedcba"); }); it("should commit valid changes made in the input field on the change event", function () { makeUI("#abcdef"); colorEditor.$colorValue.val("#fedcba"); colorEditor.$colorValue.trigger("change"); expect(tinycolor(colorEditor.getColor()).toHexString()).toBe("#fedcba"); }); it("should not commit changes on the input event while the value is invalid, but should keep them in the text field", function () { makeUI("#abcdef"); colorEditor.$colorValue.val("rgb(0, 0, 0"); colorEditor.$colorValue.trigger("input"); expect(tinycolor(colorEditor.getColor()).toHexString()).toBe("#abcdef"); expect(colorEditor.$colorValue.val()).toBe("rgb(0, 0, 0"); }); it("should revert to the previous value on the change event while the value is invalid", function () { makeUI("#abcdef"); colorEditor.$colorValue.val("rgb(0, 0, 0"); colorEditor.$colorValue.trigger("change"); expect(tinycolor(colorEditor.getColor()).toHexString()).toBe("#abcdef"); expect(colorEditor.$colorValue.val()).toBe("#abcdef"); }); it("should convert percentage RGB values to normal values", function () { makeUI("#abcdef"); expect(colorEditor._convertToNormalRGB("rgb(25%, 50%, 75%)")).toBe("rgb(64, 128, 191)"); }); it("should normalize a string to match tinycolor's format", function () { makeUI("#abcdef"); //Percentage based colors are now supported: the following test is obsolete //expect(colorEditor._normalizeColorString("rgb(25%,50%,75%)")).toBe("rgb(64, 128, 191)"); expect(colorEditor._normalizeColorString("rgb(10,20, 30)")).toBe("rgb(10, 20, 30)"); }); }); describe("undo/redo", function () { function triggerCtrlKey($element, key, shift) { var ctrlKeyProperty = (brackets.platform === "win" ? "ctrlKey" : "metaKey"), eventProps = {keyCode: key, shiftKey: shift}; eventProps[ctrlKeyProperty] = true; $element.trigger($.Event("keydown", eventProps)); } it("should undo when Ctrl-Z is pressed on a focused element in the color editor", function () { makeUI("#abcdef"); runs(function () { colorEditor.setColorFromString("#a0a0a0"); colorEditor.$hueBase.focus(); triggerCtrlKey(colorEditor.$hueBase, KeyEvent.DOM_VK_Z); expect(getColorString()).toBe("#abcdef"); }); }); it("should redo when Ctrl-Shift-Z is pressed on a focused element in the color editor", function () { makeUI("#abcdef"); runs(function () { colorEditor._commitColor("#a0a0a0", true); colorEditor.$hueBase.focus(); triggerCtrlKey(colorEditor.$hueBase, KeyEvent.DOM_VK_Z); triggerCtrlKey(colorEditor.$hueBase, KeyEvent.DOM_VK_Z, true); expect(getColorString()).toBe("#a0a0a0"); }); }); it("should redo when Ctrl-Y is pressed on a focused element in the color editor", function () { makeUI("#abcdef"); runs(function () { colorEditor._commitColor("#a0a0a0", true); colorEditor.$hueBase.focus(); triggerCtrlKey(colorEditor.$hueBase, KeyEvent.DOM_VK_Z); triggerCtrlKey(colorEditor.$hueBase, KeyEvent.DOM_VK_Y); expect(getColorString()).toBe("#a0a0a0"); }); }); it("should redo when Ctrl-Y is pressed after two Ctrl-Zs (only one Ctrl-Z should take effect)", function () { makeUI("#abcdef"); runs(function () { colorEditor._commitColor("#a0a0a0", true); colorEditor.$hueBase.focus(); triggerCtrlKey(colorEditor.$hueBase, KeyEvent.DOM_VK_Z); triggerCtrlKey(colorEditor.$hueBase, KeyEvent.DOM_VK_Z); triggerCtrlKey(colorEditor.$hueBase, KeyEvent.DOM_VK_Y); expect(getColorString()).toBe("#a0a0a0"); }); }); it("should undo when Ctrl-Z is pressed after two Ctrl-Ys (only one Ctrl-Y should take effect)", function () { makeUI("#abcdef"); runs(function () { colorEditor._commitColor("#a0a0a0", true); colorEditor.$hueBase.focus(); triggerCtrlKey(colorEditor.$hueBase, KeyEvent.DOM_VK_Z); triggerCtrlKey(colorEditor.$hueBase, KeyEvent.DOM_VK_Y); triggerCtrlKey(colorEditor.$hueBase, KeyEvent.DOM_VK_Y); triggerCtrlKey(colorEditor.$hueBase, KeyEvent.DOM_VK_Z); expect(getColorString()).toBe("#abcdef"); }); }); it("should undo an rgba conversion", function () { makeUI("#abcdef"); runs(function () { colorEditor.$rgbaButton.click(); triggerCtrlKey(colorEditor.$rgbaButton, KeyEvent.DOM_VK_Z); expect(getColorString()).toBe("#abcdef"); }); }); it("should undo an hsla conversion", function () { makeUI("#abcdef"); runs(function () { colorEditor.$hslButton.click(); triggerCtrlKey(colorEditor.$hslButton, KeyEvent.DOM_VK_Z); expect(getColorString()).toBe("#abcdef"); }); }); it("should undo a hex conversion", function () { makeUI("rgba(12, 32, 65, 0.2)"); runs(function () { colorEditor.$hexButton.trigger("click"); triggerCtrlKey(colorEditor.$hexButton, KeyEvent.DOM_VK_Z); expect(getColorString()).toBe("rgba(12, 32, 65, 0.2)"); }); }); it("should undo a saturation/value change", function () { makeUI("rgba(100, 150, 200, 0.3)"); runs(function () { eventAtRatio("mousedown", colorEditor.$selectionBase, [0.5, 0.5]); triggerCtrlKey(colorEditor.$selectionBase, KeyEvent.DOM_VK_Z); expect(getColorString()).toBe("rgba(100, 150, 200, 0.3)"); colorEditor.$selectionBase.trigger("mouseup"); // clean up drag state }); }); it("should undo a hue change", function () { makeUI("rgba(100, 150, 200, 0.3)"); runs(function () { eventAtRatio("mousedown", colorEditor.$hueBase, [0, 0.5]); triggerCtrlKey(colorEditor.$hueBase, KeyEvent.DOM_VK_Z); expect(getColorString()).toBe("rgba(100, 150, 200, 0.3)"); colorEditor.$hueBase.trigger("mouseup"); // clean up drag state }); }); it("should undo an opacity change", function () { makeUI("rgba(100, 150, 200, 0.3)"); runs(function () { eventAtRatio("mousedown", colorEditor.$opacitySelector, [0, 0.5]); triggerCtrlKey(colorEditor.$opacitySelector, KeyEvent.DOM_VK_Z); expect(getColorString()).toBe("rgba(100, 150, 200, 0.3)"); colorEditor.$opacitySelector.trigger("mouseup"); // clean up drag state }); }); it("should undo a text field change", function () { makeUI("rgba(100, 150, 200, 0.3)"); runs(function () { colorEditor.$colorValue.val("rgba(50, 50, 50, 0.9)"); triggerCtrlKey(colorEditor.$colorValue, KeyEvent.DOM_VK_Z); expect(getColorString()).toBe("rgba(100, 150, 200, 0.3)"); }); }); it("should undo a swatch click", function () { makeUI("rgba(100, 150, 200, 0.3)"); runs(function () { var $swatch = $(colorEditor.$swatches.find("li")[0]); $swatch.trigger("click"); triggerCtrlKey($swatch, KeyEvent.DOM_VK_Z); expect(getColorString()).toBe("rgba(100, 150, 200, 0.3)"); }); }); }); }); }); });
'use strict'; var assert = require('assert'); describe('Array', function(){ describe('#indexOf()', function(){ it('should return -1 when the value is not present', function(){ assert.equal(-1, [1,2,3].indexOf(5)); assert.equal(-1, [1,2,3].indexOf(0)); }); }); });
import {inject, bindable} from 'aurelia-framework'; import {I18N} from 'aurelia-i18n'; import {EventAggregator} from 'aurelia-event-aggregator'; import {parseJSON} from './resources/jsonparser'; import {Field} from './resources/form/abstract/field'; import {schema, fieldsToShow} from './schemas/index'; import {Validation} from './validation'; import * as space from './space'; import YAML from 'yamljs'; import $ from 'jquery'; window.$ = $; window.jQuery = $; import SwaggerUIBundle from 'swagger-ui'; import SwaggerUIStandalonePreset from 'swagger-ui/swagger-ui-standalone-preset'; // I have no idea why this works. // PNotify has a very interesting module system that I couldn't get to work work // when importing in any other way than by using the monstrosity below. // Aurelia is probably not completely guilt-free either. // // To add a new pnotify module, you must add it to both of the arrays below in // the same format as the existing extra modules. require( [ 'pnotify', 'pnotify/pnotify.animate', 'pnotify/pnotify.confirm' ], () => require( [ 'pnotify', 'pnotify.animate', 'pnotify.confirm' ], pnfTemp => window.PNotify = pnfTemp)); window.stack_bottomright = { dir1: 'up', dir2: 'left', push: 'up' }; const DEFAULT_SPLIT = 'editor'; @inject(I18N, EventAggregator) export class App { @bindable language = window.localStorage.language || 'en'; enableBranding = true; spaceLoginApinf = false; ieWarningDismissed = window.localStorage.ieWarningDismissed === 'true'; cookieWarningDismissed = window.localStorage.cookieWarningDismissed === 'true'; toggleSpaceLoginType() { this.spaceLoginApinf = !this.spaceLoginApinf; } dismissIEWarning() { this.ieWarningDismissed = true; window.localStorage.ieWarningDismissed = true; } dismissCookieWarning() { this.cookieWarningDismissed = true; window.localStorage.cookieWarningDismissed = true; } constructor(i18n, ea) { this.i18n = i18n; Field.internationalizer = i18n; Field.eventAggregator = ea; Field.validationFunctions = new Validation(i18n); // Allow access from browser console window.$oai = this; try { const pointerlessSchema = $.extend(true, {}, schema); this.forms = parseJSON('form', pointerlessSchema); if (window.localStorage['openapi-v2-design']) { const savedData = JSON.parse(window.localStorage['openapi-v2-design']); this.forms.setValue(savedData); } } catch (exception) { console.error(exception); this.exception = exception; return; } this.activeForm = 'about'; window.onhashchange = () => { const formID = window.location.hash.substr(2) || 'about'; if (typeof this.activeForm === 'object') { this.activeForm.show = false; } if (formID === 'about') { this.activeForm = 'about'; } else if (this.forms.hasChild(formID)) { this.activeForm = this.forms.getChild(formID); this.activeForm.show = true; } else { return; } $('.nav > .editor-nav > .nav-link.open').removeClass('open'); $(`#nav-${formID}`).addClass('open'); }; this.forms.addChangeListener(() => this.saveFormLocal()); window.addEventListener('message', ({data}) => { if (data.swagger) { if (!data.noDelete) { delete(true); } this.forms.setValue(data); } }, false); } bind() { this.split(window.localStorage.split || DEFAULT_SPLIT, true); } languageChanged() { window.localStorage.language = this.language; location.reload(); } spaceLogin() { space.login(this, this.spaceUsername.value, this.spacePassword.value, this.spaceLoginApinf ? 'apinf' : 'space'); } spaceRegister() { space.register(this, this.spaceEmail.value, this.spaceRegisterUsername.value, this.spaceRegisterPassword.value); } logout() { space.logout(this); } showRichPreview() { if (!this.richPreviewObj) { // The DOM isn't ready yet, but swagger-ui requires it to be ready. // Let's try again a bit later. setTimeout(() => this.showRichPreview(), 500); return; } setTimeout(() => { this.richPreview = new SwaggerUIBundle({ spec: this.getFormData(), dom_id: '#rich-preview', // Disable Swagger.io online validation (AKA spyware) validatorUrl: null, presets: [ SwaggerUIBundle.presets.apis, SwaggerUIStandalonePreset ], plugins: [ SwaggerUIBundle.plugins.DownloadUrl ], layout: 'StandaloneLayout' }); }, 0); } hideRichPreview() { this.richPreview = undefined; $(this.richPreviewObj).empty(); } split(type, force = false) { if (type === 'preview') { if (!force) { let errors = {}; this.forms.revalidate(errors); this.richPreviewErrors = Object.entries(errors); if (this.richPreviewErrors.length > 0) { this.richPreviewErrorModal.open(); return; } } else if (this.richPreviewErrorModal) { this.richPreviewErrorModal.close(); } } this.previousSplit = window.localStorage.split || DEFAULT_SPLIT; this.showEditor = type === 'editor' || type === 'split'; this.showOutput = type === 'output'; this.splitView = type === 'split'; this.showPreview = type === 'preview'; if (this.showPreview) { this.showRichPreview(); } else if (this.richPreview) { this.hideRichPreview(); } window.localStorage.split = type; } notify(title, text = '', type = 'info', url = '', onclick = undefined) { /*eslint no-new: 0*/ const notif = new PNotify({ title, text, type, stack: stack_bottomright, addclass: 'stack-bottomright', animate: { animate: true, in_class: 'slideInUp', out_class: 'slideOutDown' } }); notif.get().click(() => { notif.remove(); if (onclick) { onclick(); } if (url) { window.open(url, '_blank'); } }); } confirm(title, text, type = 'info') { return new Promise((resolve, reject) => { const notif = new PNotify({ title, text, type, stack: stack_bottomright, addclass: 'stack-bottomright', animate: { animate: true, in_class: 'bounceInUp', out_class: 'bounceOutDown' }, confirm: { confirm: true } }); notif.get() .on('pnotify.confirm', resolve) .on('pnotify.cancel', reject) .click(() => notif.remove()); }); } attached() { if (window.onhashchange) { window.onhashchange(); } } setLanguage(lang) { window.localStorage.language = lang; location.reload(); } importOutputEditor() { const rawData = $(this.outputEditor).val(); let data; try { data = YAML.parse(rawData); } catch (_) { try { data = JSON.parse(rawData); } catch (ex) { this.notify( this.i18n.tr('notify.import-failed.title'), this.i18n.tr('notify.import-failed.body', {error: ex}), 'error'); return; } } delete(true); this.forms.setValue(data); this.notify( this.i18n.tr('notify.editor-import-complete.title'), this.i18n.tr('notify.editor-import-complete.body', { title: this.forms.resolveRef('#/header/info/title').getValue(), version: this.forms.resolveRef('#/header/info/version').getValue() }), 'success' ); } importFile() { delete(true); const fileInput = $('<input/>', { type: 'file' }); fileInput.css({display: 'none'}); fileInput.appendTo('body'); fileInput.trigger('click'); // IE/Edge don't want to trigger change events, so I have to do it for them... // // Check that the browser is IE/Edge if (!!window.StyleMedia) { // Check if there is a file every 0.5 seconds const interval = setInterval(() => { if (fileInput[0].files[0]) { // The file was found, so trigger a change event and stop the interval. fileInput.trigger('change'); clearInterval(interval); } }, 500); } fileInput.change(() => { const file = fileInput[0].files[0]; const reader = new FileReader(); reader.addEventListener('load', () => { let data; try { if (file.name.endsWith('.yaml') || file.name.endsWith('.yml')) { data = YAML.parse(reader.result); } else { data = JSON.parse(reader.result); } } catch (ex) { this.notify( this.i18n.tr('notify.import-failed.title'), this.i18n.tr('notify.import-failed.body', {error: ex}), 'error'); return; } this.forms.setValue(data); this.notify( this.i18n.tr('notify.import-complete.title'), this.i18n.tr('notify.import-complete.body', { title: this.forms.resolveRef('#/header/info/title').getValue(), version: this.forms.resolveRef('#/header/info/version').getValue() }), 'success' ); }, false); reader.readAsText(file); }); } download(type, force) { if (!force) { let errors = {}; this.forms.revalidate(errors); this.downloadErrors = Object.entries(errors); if (this.downloadErrors.length > 0) { $(this.downloadErrorBox).attr('data-dl-type', type); this.downloadErrorModal.open(); return; } } else { this.downloadErrorModal.close(); } this.downloadErrors = []; if (!type) { type = $(this.downloadErrorBox).attr('data-dl-type'); } let data; if (type === 'json') { data = this.json; } else if (type === 'yaml') { data = this.yaml; } else { return; } // Add an anchor element that has the data as the href attribute, then click // the element to download the data. const blob = new Blob([data], {type: 'text/json'}); if (window.navigator.msSaveOrOpenBlob) { window.navigator.msSaveBlob(blob, `swagger.${type}`); } else { const downloadLink = document.createElement('a'); downloadLink.href = window.URL.createObjectURL(blob); downloadLink.download = `swagger.${type}`; document.body.appendChild(downloadLink); downloadLink.click(); document.body.removeChild(downloadLink); } } uploadSpace() { space.upload.call(space, this.getFormData(), this); } publish() { space.publish.call(space, this.getFormData(), this); } delete(force = false, notify = false) { if (!force) { this.confirm( this.i18n.tr('confirm.delete.title'), this.i18n.tr('confirm.delete.body') ).then(() => this.delete(true, notify)) .catch(() => void (0)); return; } let oldData; if (notify) { oldData = this.forms.getValue(); } const pointerlessSchema = $.extend(true, {}, schema); this.forms = parseJSON('form', pointerlessSchema); delete localStorage['openapi-v2-design']; window.onhashchange(); if (notify) { this.notify( this.i18n.tr('notify.delete.title'), this.i18n.tr('notify.delete.body'), 'info', '', () => { this.delete(true, false); this.forms.setValue(oldData); }); } } getFormData() { const data = this.forms.getValue(); data.swagger = '2.0'; return data; } get yaml() { return YAML.stringify(this.getFormData(), 10, 2); } get json() { const data = JSON.stringify(this.getFormData(), '', ' '); return data; } saveFormLocal() { window.localStorage['openapi-v2-design'] = JSON.stringify(this.getFormData()); } get currentFormJSON() { if (fieldsToShow.hasOwnProperty(this.activeForm.id)) { const rawData = this.getFormData(); let output = ''; for (const field of fieldsToShow[this.activeForm.id]) { if (rawData[field]) { output += `"${field}": ${JSON.stringify(rawData[field], '', ' ')}\n`; } } return output; } const data = this.activeForm.getValue(); if (!data || (typeof data === 'object' && Object.entries(data).length === 0)) { return ''; } const stringData = JSON.stringify(data, '', ' '); return `"${this.activeForm.id}": ${stringData}`; } }
// Friendly login & sign up form // // based on http://blog.leahculver.com/2009/11/log-in-or-sign-up.html // // @author Rolando Espinoza La fuente // @web http://rolandoespinoza.info // @license MIT // in case there isn't firebug if (typeof console == 'undefined') { console = {log: function(){}}; } jQuery(function($) { // form starts hidden $('#login_signup').show(); // caching form node var $form = $('#login_signup form'); // // login & sign up flow // $('input[name="action"]', $form).click(function() { // log action attribute console.log('after ' + $form.attr('action')); // which action user wants var action = $(this).val(); // steps: // - change form action // - change password label // - change button label // - show/hide password confirmation // - show/hide forgot & terms if (action == 'signup') { $form.get(0).setAttribute('action', 'signup'); $('p.password2', $form).show(); $('label[for="password"]', $form).html('Choose a password'); $('input[type="submit"]', $form).attr('value', 'Sign up!'); $('p.forgot_password', $form).hide(); $('p.terms', $form).show(); } else if (action == 'login') { $form.get(0).setAttribute('action', 'login'); $('p.password2', $form).hide(); $('label[for="password"]', $form).html('Password'); $('input[type="submit"]', $form).attr('value', 'Log in'); $('p.forgot_password', $form).show(); $('p.terms', $form).hide(); } else { console.log('unknown action: ' + action); } // log action attribute console.log('before ' + $form.attr('action')); }); // // forgot password flow // $('p.forgot_password', $form).click(function() { // change form action $form.get(0).setAttribute('action', 'forgot_password'); // hide all elements $('p', $form).hide(); // only show email field $('p.email', $form).show(); // display submit button $('p.submit', $form).show(); // display forgot hint $('p.forgot_hint', $form).show(); // update submit button label $('input[type="submit"]', $form).attr('value', 'Recover password'); return false; }); // back to login. Only available on forgot password $('a.back_link', $form).click(function() { // hide container to prevent elements flickering $form.hide(); // show all form $('p', $form).show(); // hide hint $('p.forgot_hint', $form).hide(); // restore login form state $('input[name="action"][value="login"]', $form).click(); // show form $form.show(); return false; }); // catch form submit just for demo $form.submit(function(e) { var action = $form.attr('action'); alert("Submit action: " + action); e.preventDefault(); return false; }); });
(function (app, $, undefined) { $(document).ready(function () { console.log('document.ready'); require([ 'dojo/dom', 'dojo/dom-construct' ], function (dom, domConstruct) { var greetingNode = dom.byId('greeting'); domConstruct.place('<i> Dojo!</i>', greetingNode); }); }); })(window.app = window.app || {}, jQuery)