code
stringlengths
2
1.05M
'use strict'; var main = { expand:true, cwd: './build/styles/', src:['*.css'], dest: './build/styles/' }; module.exports = { main:main };
/** * QUnit v1.3.0pre - A JavaScript Unit Testing Framework * * http://docs.jquery.com/QUnit * * Copyright (c) 2011 John Resig, Jörn Zaefferer * Dual licensed under the MIT (MIT-LICENSE.txt) * or GPL (GPL-LICENSE.txt) licenses. * Pulled Live from Git Sat Jan 14 01:10:01 UTC 2012 * Last Commit: 0712230bb203c262211649b32bd712ec7df5f857 */ (function(window) { var defined = { setTimeout: typeof window.setTimeout !== "undefined", sessionStorage: (function() { try { return !!sessionStorage.getItem; } catch(e) { return false; } })() }; var testId = 0, toString = Object.prototype.toString, hasOwn = Object.prototype.hasOwnProperty; var Test = function(name, testName, expected, testEnvironmentArg, async, callback) { this.name = name; this.testName = testName; this.expected = expected; this.testEnvironmentArg = testEnvironmentArg; this.async = async; this.callback = callback; this.assertions = []; }; Test.prototype = { init: function() { var tests = id("qunit-tests"); if (tests) { var b = document.createElement("strong"); b.innerHTML = "Running " + this.name; var li = document.createElement("li"); li.appendChild( b ); li.className = "running"; li.id = this.id = "test-output" + testId++; tests.appendChild( li ); } }, setup: function() { if (this.module != config.previousModule) { if ( config.previousModule ) { runLoggingCallbacks('moduleDone', QUnit, { name: config.previousModule, failed: config.moduleStats.bad, passed: config.moduleStats.all - config.moduleStats.bad, total: config.moduleStats.all } ); } config.previousModule = this.module; config.moduleStats = { all: 0, bad: 0 }; runLoggingCallbacks( 'moduleStart', QUnit, { name: this.module } ); } config.current = this; this.testEnvironment = extend({ setup: function() {}, teardown: function() {} }, this.moduleTestEnvironment); if (this.testEnvironmentArg) { extend(this.testEnvironment, this.testEnvironmentArg); } runLoggingCallbacks( 'testStart', QUnit, { name: this.testName, module: this.module }); // allow utility functions to access the current test environment // TODO why?? QUnit.current_testEnvironment = this.testEnvironment; try { if ( !config.pollution ) { saveGlobal(); } this.testEnvironment.setup.call(this.testEnvironment); } catch(e) { QUnit.ok( false, "Setup failed on " + this.testName + ": " + e.message ); } }, run: function() { config.current = this; if ( this.async ) { QUnit.stop(); } if ( config.notrycatch ) { this.callback.call(this.testEnvironment); return; } try { this.callback.call(this.testEnvironment); } catch(e) { fail("Test " + this.testName + " died, exception and test follows", e, this.callback); QUnit.ok( false, "Died on test #" + (this.assertions.length + 1) + ": " + e.message + " - " + QUnit.jsDump.parse(e) ); // else next test will carry the responsibility saveGlobal(); // Restart the tests if they're blocking if ( config.blocking ) { QUnit.start(); } } }, teardown: function() { config.current = this; try { this.testEnvironment.teardown.call(this.testEnvironment); checkPollution(); } catch(e) { QUnit.ok( false, "Teardown failed on " + this.testName + ": " + e.message ); } }, finish: function() { config.current = this; if ( this.expected != null && this.expected != this.assertions.length ) { QUnit.ok( false, "Expected " + this.expected + " assertions, but " + this.assertions.length + " were run" ); } var good = 0, bad = 0, tests = id("qunit-tests"); config.stats.all += this.assertions.length; config.moduleStats.all += this.assertions.length; if ( tests ) { var ol = document.createElement("ol"); for ( var i = 0; i < this.assertions.length; i++ ) { var assertion = this.assertions[i]; var li = document.createElement("li"); li.className = assertion.result ? "pass" : "fail"; li.innerHTML = assertion.message || (assertion.result ? "okay" : "failed"); ol.appendChild( li ); if ( assertion.result ) { good++; } else { bad++; config.stats.bad++; config.moduleStats.bad++; } } // store result when possible if ( QUnit.config.reorder && defined.sessionStorage ) { if (bad) { sessionStorage.setItem("qunit-" + this.module + "-" + this.testName, bad); } else { sessionStorage.removeItem("qunit-" + this.module + "-" + this.testName); } } if (bad == 0) { ol.style.display = "none"; } var b = document.createElement("strong"); b.innerHTML = this.name + " <b class='counts'>(<b class='failed'>" + bad + "</b>, <b class='passed'>" + good + "</b>, " + this.assertions.length + ")</b>"; var a = document.createElement("a"); a.innerHTML = "Rerun"; a.href = QUnit.url({ filter: getText([b]).replace(/\([^)]+\)$/, "").replace(/(^\s*|\s*$)/g, "") }); addEvent(b, "click", function() { var next = b.nextSibling.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() == "span" || target.nodeName.toLowerCase() == "b" ) { target = target.parentNode; } if ( window.location && target.nodeName.toLowerCase() === "strong" ) { window.location = QUnit.url({ filter: getText([target]).replace(/\([^)]+\)$/, "").replace(/(^\s*|\s*$)/g, "") }); } }); var li = id(this.id); li.className = bad ? "fail" : "pass"; li.removeChild( li.firstChild ); li.appendChild( b ); li.appendChild( a ); li.appendChild( ol ); } else { for ( var i = 0; i < this.assertions.length; i++ ) { if ( !this.assertions[i].result ) { bad++; config.stats.bad++; config.moduleStats.bad++; } } } try { QUnit.reset(); } catch(e) { fail("reset() failed, following Test " + this.testName + ", exception and reset fn follows", e, QUnit.reset); } runLoggingCallbacks( 'testDone', QUnit, { name: this.testName, module: this.module, failed: bad, passed: this.assertions.length - bad, total: this.assertions.length } ); }, queue: function() { var test = this; synchronize(function() { test.init(); }); function run() { // each of these can by async synchronize(function() { test.setup(); }); synchronize(function() { test.run(); }); synchronize(function() { test.teardown(); }); synchronize(function() { test.finish(); }); } // defer when previous test run passed, if storage is available var bad = QUnit.config.reorder && defined.sessionStorage && +sessionStorage.getItem("qunit-" + this.module + "-" + this.testName); if (bad) { run(); } else { synchronize(run, true); }; } }; var QUnit = { // call on start of module test to prepend name to all tests module: function(name, testEnvironment) { config.currentModule = name; config.currentModuleTestEnviroment = testEnvironment; }, asyncTest: function(testName, expected, callback) { if ( arguments.length === 2 ) { callback = expected; expected = null; } QUnit.test(testName, expected, callback, true); }, test: function(testName, expected, callback, async) { var name = '<span class="test-name">' + escapeInnerText(testName) + '</span>', 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 = '<span class="module-name">' + config.currentModule + "</span>: " + name; } if ( !validTest(config.currentModule + ": " + testName) ) { return; } var test = new Test(name, testName, expected, testEnvironmentArg, async, callback); test.module = config.currentModule; test.moduleTestEnvironment = config.currentModuleTestEnviroment; test.queue(); }, /** * 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.current.expected = asserts; }, /** * Asserts true. * @example ok( "asdfasdf".length > 5, "There must be at least 5 chars" ); */ ok: function(a, msg) { a = !!a; var details = { result: a, message: msg }; msg = escapeInnerText(msg); runLoggingCallbacks( 'log', QUnit, details ); config.current.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) { QUnit.push(expected == actual, actual, expected, message); }, notEqual: function(actual, expected, message) { QUnit.push(expected != actual, actual, expected, message); }, deepEqual: function(actual, expected, message) { QUnit.push(QUnit.equiv(actual, expected), actual, expected, message); }, notDeepEqual: function(actual, expected, message) { QUnit.push(!QUnit.equiv(actual, expected), actual, expected, message); }, strictEqual: function(actual, expected, message) { QUnit.push(expected === actual, actual, expected, message); }, notStrictEqual: function(actual, expected, message) { QUnit.push(expected !== actual, actual, expected, message); }, raises: function(block, expected, message) { var actual, ok = false; if (typeof expected === 'string') { message = expected; expected = null; } try { block(); } catch (e) { actual = e; } if (actual) { // we don't want to validate thrown error if (!expected) { ok = true; // expected is a regexp } else if (QUnit.objectType(expected) === "regexp") { ok = expected.test(actual); // expected is a constructor } else if (actual instanceof expected) { ok = true; // expected is a validation function which returns true is validation passed } else if (expected.call({}, actual) === true) { ok = true; } } QUnit.ok(ok, message); }, start: function(count) { config.semaphore -= count || 1; if (config.semaphore > 0) { // don't start until equal number of stop-calls return; } if (config.semaphore < 0) { // ignore if start is called more often then stop config.semaphore = 0; } // A slight delay, to avoid any current callbacks if ( defined.setTimeout ) { window.setTimeout(function() { if (config.semaphore > 0) { return; } if ( config.timeout ) { clearTimeout(config.timeout); } config.blocking = false; process(true); }, 13); } else { config.blocking = false; process(true); } }, stop: function(count) { config.semaphore += count || 1; config.blocking = true; if ( config.testTimeout && defined.setTimeout ) { clearTimeout(config.timeout); config.timeout = window.setTimeout(function() { QUnit.ok( false, "Test timed out" ); config.semaphore = 1; QUnit.start(); }, config.testTimeout); } } }; //We want access to the constructor's prototype (function() { function F(){}; F.prototype = QUnit; QUnit = new F(); //Make F QUnit's constructor so that we can add to the prototype later QUnit.constructor = F; })(); // 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, // when enabled, show only failing tests // gets persisted through sessionStorage and can be changed in UI via checkbox hidepassed: false, // by default, run previously failed tests first // very useful in combination with "Hide passed tests" checked reorder: true, // by default, modify document.title when suite is done altertitle: true, urlConfig: ['noglobals', 'notrycatch'], //logging callback queues begin: [], done: [], log: [], testStart: [], testDone: [], moduleStart: [], moduleDone: [] }; // Load paramaters (function() { var location = window.location || { search: "", protocol: "file:" }, params = location.search.slice( 1 ).split( "&" ), length = params.length, urlParams = {}, current; if ( params[ 0 ] ) { for ( var i = 0; i < length; i++ ) { current = params[ i ].split( "=" ); current[ 0 ] = decodeURIComponent( current[ 0 ] ); // allow just a key to turn on a flag, e.g., test.html?noglobals current[ 1 ] = current[ 1 ] ? decodeURIComponent( current[ 1 ] ) : true; urlParams[ current[ 0 ] ] = current[ 1 ]; } } QUnit.urlParams = urlParams; config.filter = urlParams.filter; // 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; } // define these after exposing globals to keep them in these QUnit namespace only extend(QUnit, { config: config, // Initialize the configuration options init: function() { extend(config, { stats: { all: 0, bad: 0 }, moduleStats: { all: 0, bad: 0 }, started: +new Date, updateRate: 1000, blocking: false, autostart: true, autorun: false, filter: "", queue: [], semaphore: 0 }); 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 ); } if ( tests ) { result = document.createElement( "p" ); result.id = "qunit-testresult"; result.className = "result"; tests.parentNode.insertBefore( result, tests ); result.innerHTML = 'Running...<br/>&nbsp;'; } }, /** * Resets the test setup. Useful for tests that modify the DOM. * * If jQuery is available, uses jQuery's html(), otherwise just innerHTML. */ reset: function() { if ( window.jQuery ) { jQuery( "#qunit-fixture" ).html( config.fixture ); } else { var main = id( 'qunit-fixture' ); if ( main ) { main.innerHTML = config.fixture; } } }, /** * 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 QUnit.objectType( obj ) == type; }, objectType: function( obj ) { if (typeof obj === "undefined") { return "undefined"; // consider: typeof null === object } if (obj === null) { return "null"; } var type = toString.call( obj ).match(/^\[object\s(.*)\]$/)[1] || ''; switch (type) { case 'Number': if (isNaN(obj)) { return "nan"; } else { return "number"; } case 'String': case 'Boolean': case 'Array': case 'Date': case 'RegExp': case 'Function': return type.toLowerCase(); } if (typeof obj === "object") { return "object"; } return undefined; }, push: function(result, actual, expected, message) { var details = { result: result, message: message, actual: actual, expected: expected }; message = escapeInnerText(message) || (result ? "okay" : "failed"); message = '<span class="test-message">' + message + "</span>"; expected = escapeInnerText(QUnit.jsDump.parse(expected)); actual = escapeInnerText(QUnit.jsDump.parse(actual)); var output = message + '<table><tr class="test-expected"><th>Expected: </th><td><pre>' + expected + '</pre></td></tr>'; if (actual != expected) { output += '<tr class="test-actual"><th>Result: </th><td><pre>' + actual + '</pre></td></tr>'; output += '<tr class="test-diff"><th>Diff: </th><td><pre>' + QUnit.diff(expected, actual) +'</pre></td></tr>'; } if (!result) { var source = sourceFromStacktrace(); if (source) { details.source = source; output += '<tr class="test-source"><th>Source: </th><td><pre>' + escapeInnerText(source) + '</pre></td></tr>'; } } output += "</table>"; runLoggingCallbacks( 'log', QUnit, details ); config.current.assertions.push({ result: !!result, message: output }); }, url: function( params ) { params = extend( extend( {}, QUnit.urlParams ), params ); var querystring = "?", key; for ( key in params ) { if ( !hasOwn.call( params, key ) ) { continue; } querystring += encodeURIComponent( key ) + "=" + encodeURIComponent( params[ key ] ) + "&"; } return window.location.pathname + querystring.slice( 0, -1 ); }, extend: extend, id: id, addEvent: addEvent }); //QUnit.constructor is set to the empty F() above so that we can add to it's prototype later //Doing this allows us to tell if the following methods have been overwritten on the actual //QUnit object, which is a deprecated way of using the callbacks. extend(QUnit.constructor.prototype, { // Logging callbacks; all receive a single argument with the listed properties // run test/logs.html for any related changes begin: registerLoggingCallback('begin'), // done: { failed, passed, total, runtime } done: registerLoggingCallback('done'), // log: { result, actual, expected, message } log: registerLoggingCallback('log'), // testStart: { name } testStart: registerLoggingCallback('testStart'), // testDone: { name, failed, passed, total } testDone: registerLoggingCallback('testDone'), // moduleStart: { name } moduleStart: registerLoggingCallback('moduleStart'), // moduleDone: { name, failed, passed, total } moduleDone: registerLoggingCallback('moduleDone') }); if ( typeof document === "undefined" || document.readyState === "complete" ) { config.autorun = true; } QUnit.load = function() { runLoggingCallbacks( 'begin', QUnit, {} ); // Initialize the config, saving the execution queue var oldconfig = extend({}, config); QUnit.init(); extend(config, oldconfig); config.blocking = false; var urlConfigHtml = '', len = config.urlConfig.length; for ( var i = 0, val; i < len, val = config.urlConfig[i]; i++ ) { config[val] = QUnit.urlParams[val]; urlConfigHtml += '<label><input name="' + val + '" type="checkbox"' + ( config[val] ? ' checked="checked"' : '' ) + '>' + val + '</label>'; } var userAgent = id("qunit-userAgent"); if ( userAgent ) { userAgent.innerHTML = navigator.userAgent; } var banner = id("qunit-header"); if ( banner ) { banner.innerHTML = '<a href="' + QUnit.url({ filter: undefined }) + '"> ' + banner.innerHTML + '</a> ' + urlConfigHtml; addEvent( banner, "change", function( event ) { var params = {}; params[ event.target.name ] = event.target.checked ? true : undefined; window.location = QUnit.url( params ); }); } var toolbar = id("qunit-testrunner-toolbar"); if ( toolbar ) { var filter = document.createElement("input"); filter.type = "checkbox"; filter.id = "qunit-filter-pass"; addEvent( filter, "click", function() { var ol = document.getElementById("qunit-tests"); if ( filter.checked ) { ol.className = ol.className + " hidepass"; } else { var tmp = " " + ol.className.replace( /[\n\t\r]/g, " " ) + " "; ol.className = tmp.replace(/ hidepass /, " "); } if ( defined.sessionStorage ) { if (filter.checked) { sessionStorage.setItem("qunit-filter-passed-tests", "true"); } else { sessionStorage.removeItem("qunit-filter-passed-tests"); } } }); if ( config.hidepassed || defined.sessionStorage && sessionStorage.getItem("qunit-filter-passed-tests") ) { filter.checked = true; var ol = document.getElementById("qunit-tests"); ol.className = ol.className + " hidepass"; } toolbar.appendChild( filter ); var label = document.createElement("label"); label.setAttribute("for", "qunit-filter-pass"); label.innerHTML = "Hide passed tests"; toolbar.appendChild( label ); } var main = id('qunit-fixture'); if ( main ) { config.fixture = main.innerHTML; } if (config.autostart) { QUnit.start(); } }; addEvent(window, "load", QUnit.load); // addEvent(window, "error") gives us a useless event object window.onerror = function( message, file, line ) { if ( QUnit.config.current ) { ok( false, message + ", " + file + ":" + line ); } else { test( "global failure", function() { ok( false, message + ", " + file + ":" + line ); }); } }; function done() { config.autorun = true; // Log the last module results if ( config.currentModule ) { runLoggingCallbacks( 'moduleDone', QUnit, { name: config.currentModule, failed: config.moduleStats.bad, passed: config.moduleStats.all - config.moduleStats.bad, total: config.moduleStats.all } ); } var banner = id("qunit-banner"), tests = id("qunit-tests"), runtime = +new Date - config.started, passed = config.stats.all - config.stats.bad, html = [ 'Tests completed in ', runtime, ' milliseconds.<br/>', '<span class="passed">', passed, '</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 ) { id( "qunit-testresult" ).innerHTML = html; } if ( config.altertitle && typeof document !== "undefined" && document.title ) { // show ✖ for good, ✔ for bad suite result in title // use escape sequences in case file gets loaded with non-utf-8-charset document.title = [ (config.stats.bad ? "\u2716" : "\u2714"), document.title.replace(/^[\u2714\u2716] /i, "") ].join(" "); } runLoggingCallbacks( 'done', QUnit, { failed: config.stats.bad, passed: passed, total: config.stats.all, runtime: runtime } ); } function validTest( name ) { var filter = config.filter, run = false; if ( !filter ) { return true; } var not = filter.charAt( 0 ) === "!"; if ( not ) { filter = filter.slice( 1 ); } if ( name.indexOf( filter ) !== -1 ) { return !not; } if ( not ) { run = true; } return run; } // so far supports only Firefox, Chrome and Opera (buggy) // could be extended in the future to use something like https://github.com/csnover/TraceKit function sourceFromStacktrace() { try { throw new Error(); } catch ( e ) { if (e.stacktrace) { // Opera return e.stacktrace.split("\n")[6]; } else if (e.stack) { // Firefox, Chrome return e.stack.split("\n")[4]; } else if (e.sourceURL) { // Safari, PhantomJS // TODO sourceURL points at the 'throw new Error' line above, useless //return e.sourceURL + ":" + e.line; } } } function escapeInnerText(s) { if (!s) { return ""; } s = s + ""; return s.replace(/[\&<>]/g, function(s) { switch(s) { case "&": return "&amp;"; case "<": return "&lt;"; case ">": return "&gt;"; default: return s; } }); } function synchronize( callback, last ) { config.queue.push( callback ); if ( config.autorun && !config.blocking ) { process(last); } } function process( last ) { var start = new Date().getTime(); config.depth = config.depth ? config.depth + 1 : 1; while ( config.queue.length && !config.blocking ) { if ( !defined.setTimeout || config.updateRate <= 0 || ( ( new Date().getTime() - start ) < config.updateRate ) ) { config.queue.shift()(); } else { window.setTimeout( function(){ process( last ); }, 13 ); break; } } config.depth--; if ( last && !config.blocking && !config.queue.length && config.depth === 0 ) { done(); } } function saveGlobal() { config.pollution = []; if ( config.noglobals ) { for ( var key in window ) { if ( !hasOwn.call( window, key ) ) { continue; } config.pollution.push( key ); } } } function checkPollution( name ) { var old = config.pollution; saveGlobal(); var newGlobals = diff( config.pollution, old ); if ( newGlobals.length > 0 ) { ok( false, "Introduced global variable(s): " + newGlobals.join(", ") ); } var deletedGlobals = diff( old, config.pollution ); if ( deletedGlobals.length > 0 ) { ok( false, "Deleted global variable(s): " + deletedGlobals.join(", ") ); } } // 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.error(exception.stack); 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 ) { if ( b[prop] === undefined ) { delete a[prop]; // Avoid "Member not found" error in IE8 caused by setting window.constructor } else if ( prop !== "constructor" || a !== window ) { 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 ); } function registerLoggingCallback(key){ return function(callback){ config[key].push( callback ); }; } // Supports deprecated method of completely overwriting logging callbacks function runLoggingCallbacks(key, scope, args) { //debugger; var callbacks; if ( QUnit.hasOwnProperty(key) ) { QUnit[key].call(scope, args); } else { callbacks = config[key]; for( var i = 0; i < callbacks.length; i++ ) { callbacks[i].call( scope, args ); } } } // Test for equality any JavaScript type. // Author: Philippe Rathé <[email protected]> QUnit.equiv = function () { var innerEquiv; // the real equiv function var callers = []; // stack to decide between skip/abort functions var parents = []; // stack to avoiding loops from circular referencing // Call the o related callback with the given arguments. function bindCallbacks(o, callbacks, args) { var prop = QUnit.objectType(o); if (prop) { if (QUnit.objectType(callbacks[prop]) === "function") { return callbacks[prop].apply(callbacks, args); } else { return callbacks[prop]; // or undefined } } } var getProto = Object.getPrototypeOf || function (obj) { return obj.__proto__; }; 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 QUnit.objectType(b) === "date" && a.valueOf() === b.valueOf(); }, "regexp" : function(b, a) { return QUnit.objectType(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, j, loop; var len; // b could be an object literal here if (!(QUnit.objectType(b) === "array")) { return false; } len = a.length; if (len !== b.length) { // safe and faster return false; } // track reference to avoid circular references parents.push(a); for (i = 0; i < len; i++) { loop = false; for (j = 0; j < parents.length; j++) { if (parents[j] === a[i]) { loop = true;// dont rewalk array } } if (!loop && !innerEquiv(a[i], b[i])) { parents.pop(); return false; } } parents.pop(); return true; }, "object" : function(b, a) { var i, j, loop; 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) { // Allow objects with no prototype to be equivalent to // objects with Object as their constructor. if (!((getProto(a) === null && getProto(b) === Object.prototype) || (getProto(b) === null && getProto(a) === Object.prototype))) { return false; } } // stack constructor before traversing properties callers.push(a.constructor); // track reference to avoid circular references parents.push(a); for (i in a) { // be strict: don't ensures hasOwnProperty // and go deep loop = false; for (j = 0; j < parents.length; j++) { if (parents[j] === a[i]) loop = true; // don't go down the same path // twice } aProperties.push(i); // collect a's properties if (!loop && !innerEquiv(a[i], b[i])) { eq = false; break; } } callers.pop(); // unstack, we are done parents.pop(); 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" || QUnit.objectType(a) !== QUnit.objectType(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, stack ) { var i = arr.length, ret = Array(i); this.up(); while ( i-- ) ret[i] = this.parse( arr[i] , undefined , stack); this.down(); return join( '[', ret, ']' ); }; var reName = /^function (\w+)/; var jsDump = { parse:function( obj, type, stack ) { //type is used mostly internally, you can fix a (custom)type in advance stack = stack || [ ]; var parser = this.parsers[ type || this.typeOf(obj) ]; type = typeof parser; var inStack = inArray(obj, stack); if (inStack != -1) { return 'recursion('+(inStack - stack.length)+')'; } //else if (type == 'function') { stack.push(obj); var res = parser.call( this, obj, stack ); stack.pop(); return res; } // else return (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 (typeof obj.setInterval !== undefined && typeof obj.document !== "undefined" && typeof obj.nodeType === "undefined") { type = "window"; } else if (obj.nodeType === 9) { type = "document"; } else if (obj.nodeType) { type = "node"; } else if ( // native arrays toString.call( obj ) === "[object Array]" || // NodeList objects ( typeof obj.length === "number" && typeof obj.item !== "undefined" && ( obj.length ? obj.item(0) === obj[0] : ( obj.item( 0 ) === null && typeof obj[0] === "undefined" ) ) ) ) { type = "array"; } 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, QUnit.jsDump.parse( fn, 'functionArgs' ), '){'].join(''); return join( ret, QUnit.jsDump.parse(fn,'functionCode'), '}' ); }, array: array, nodelist: array, arguments: array, object:function( map, stack ) { var ret = [ ]; QUnit.jsDump.up(); for ( var key in map ) { var val = map[key]; ret.push( QUnit.jsDump.parse(key,'key') + ': ' + QUnit.jsDump.parse(val, undefined, stack)); } QUnit.jsDump.down(); return join( '{', ret, '}' ); }, node:function( node ) { var open = QUnit.jsDump.HTML ? '&lt;' : '<', close = QUnit.jsDump.HTML ? '&gt;' : '>'; var tag = node.nodeName.toLowerCase(), ret = open + tag; for ( var a in QUnit.jsDump.DOMAttrs ) { var val = node[QUnit.jsDump.DOMAttrs[a]]; if ( val ) ret += ' ' + a + '=' + QUnit.jsDump.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:false,//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; })(); // from Sizzle.js function getText( elems ) { var ret = "", elem; for ( var i = 0; elems[i]; i++ ) { elem = elems[i]; // Get the text from text nodes and CDATA nodes if ( elem.nodeType === 3 || elem.nodeType === 4 ) { ret += elem.nodeValue; // Traverse everything else, except comment nodes } else if ( elem.nodeType !== 8 ) { ret += getText( elem.childNodes ); } } return ret; }; //from jquery.js function inArray( elem, array ) { if ( array.indexOf ) { return array.indexOf( elem ); } for ( var i = 0, length = array.length; i < length; i++ ) { if ( array[ i ] === elem ) { return i; } } return -1; } /* * Javascript Diff Algorithm * By John Resig (http://ejohn.org/) * Modified by Chu Alan "sprite" * * Released under the MIT license. * * More Info: * http://ejohn.org/projects/javascript-diff-algorithm/ * * Usage: QUnit.diff(expected, actual) * * QUnit.diff("the quick brown fox jumped over", "the quick fox jumps over") == "the quick <del>brown </del> fox <del>jumped </del><ins>jumps </ins> over" */ QUnit.diff = (function() { function diff(o, n) { var ns = {}; var os = {}; for (var i = 0; i < n.length; i++) { if (ns[n[i]] == null) ns[n[i]] = { rows: [], o: null }; ns[n[i]].rows.push(i); } for (var i = 0; i < o.length; i++) { if (os[o[i]] == null) os[o[i]] = { rows: [], n: null }; os[o[i]].rows.push(i); } for (var i in ns) { if ( !hasOwn.call( ns, i ) ) { continue; } if (ns[i].rows.length == 1 && typeof(os[i]) != "undefined" && os[i].rows.length == 1) { n[ns[i].rows[0]] = { text: n[ns[i].rows[0]], row: os[i].rows[0] }; o[os[i].rows[0]] = { text: o[os[i].rows[0]], row: ns[i].rows[0] }; } } for (var i = 0; i < n.length - 1; i++) { if (n[i].text != null && n[i + 1].text == null && n[i].row + 1 < o.length && o[n[i].row + 1].text == null && n[i + 1] == o[n[i].row + 1]) { n[i + 1] = { text: n[i + 1], row: n[i].row + 1 }; o[n[i].row + 1] = { text: o[n[i].row + 1], row: i + 1 }; } } for (var i = n.length - 1; i > 0; i--) { if (n[i].text != null && n[i - 1].text == null && n[i].row > 0 && o[n[i].row - 1].text == null && n[i - 1] == o[n[i].row - 1]) { n[i - 1] = { text: n[i - 1], row: n[i].row - 1 }; o[n[i].row - 1] = { text: o[n[i].row - 1], row: i - 1 }; } } return { o: o, n: n }; } return function(o, n) { o = o.replace(/\s+$/, ''); n = n.replace(/\s+$/, ''); var out = diff(o == "" ? [] : o.split(/\s+/), n == "" ? [] : n.split(/\s+/)); var str = ""; var oSpace = o.match(/\s+/g); if (oSpace == null) { oSpace = [" "]; } else { oSpace.push(" "); } var nSpace = n.match(/\s+/g); if (nSpace == null) { nSpace = [" "]; } else { nSpace.push(" "); } if (out.n.length == 0) { for (var i = 0; i < out.o.length; i++) { str += '<del>' + out.o[i] + oSpace[i] + "</del>"; } } else { if (out.n[0].text == null) { for (n = 0; n < out.o.length && out.o[n].text == null; n++) { str += '<del>' + out.o[n] + oSpace[n] + "</del>"; } } for (var i = 0; i < out.n.length; i++) { if (out.n[i].text == null) { str += '<ins>' + out.n[i] + nSpace[i] + "</ins>"; } else { var pre = ""; for (n = out.n[i].row + 1; n < out.o.length && out.o[n].text == null; n++) { pre += '<del>' + out.o[n] + oSpace[n] + "</del>"; } str += " " + out.n[i].text + nSpace[i] + pre; } } } return str; }; })(); })(this);
import AddLearningToStoryDescription from '../../../../src/content_scripts/pivotal_tracker/use_cases/add_learning_to_story_description' import WWLTWRepository from '../../../../src/content_scripts/repositories/wwltw_repository'; import StoryTitleProvider from '../../../../src/content_scripts/utilities/story_title_provider'; import ProjectIdProvider from '../../../../src/content_scripts/utilities/project_id_provider'; describe('AddLearningToStoryDescription', function () { let wwltwRepositorySpy; let foundStory; let execute; const projectId = 'some project id'; const storyTitle = 'some story title'; beforeEach(function () { wwltwRepositorySpy = new WWLTWRepository(); foundStory = {id: '1234'}; spyOn(chrome.runtime, 'sendMessage'); spyOn(wwltwRepositorySpy, 'findByTitle').and.returnValue(Promise.resolve([foundStory])); spyOn(wwltwRepositorySpy, 'update').and.returnValue(Promise.resolve()); spyOn(StoryTitleProvider, 'currentStoryTitle').and.returnValue(storyTitle); spyOn(ProjectIdProvider, 'getProjectId').and.returnValue(projectId); const useCase = new AddLearningToStoryDescription(wwltwRepositorySpy); execute = useCase.execute; }); describe('execute', function () { describe('when called outside of AddLearningToStoryDescription instance', function () { it('finds the story', function () { execute('some tag, some other tag', 'some body'); expect(wwltwRepositorySpy.findByTitle).toHaveBeenCalledWith( projectId, storyTitle ); }); it('sends analytics data', function () { execute(); expect(chrome.runtime.sendMessage).toHaveBeenCalledWith({ eventType: 'submit' }); }); it('updates the found story', function (done) { const body = 'some body'; const tags = 'some tag, some other tag'; execute(tags, body).then(function () { expect(wwltwRepositorySpy.update).toHaveBeenCalledWith( projectId, foundStory, tags, body ); done(); }); }); }); }); });
"use strict"; var Template = function (options) { this._pageTitle = ''; this._titleSeparator = options.title_separator; this._siteTitle = options.site_title; this._req = null; this._res = null; }; Template.prototype.bindMiddleware = function(req, res) { this._req = req; this._res = res; }; Template.prototype.setPageTitle = function(pageTitle) { this._pageTitle = pageTitle; }; Template.prototype.setSiteTitle = function(siteTitle) { this._siteTitle = siteTitle; }; Template.prototype.setTitleSeparator = function(separator) { this._titleSeparator = separator; }; Template.prototype.getTitle = function() { if (this._pageTitle !== '') { return this._pageTitle + ' ' + this._titleSeparator + ' ' + this._siteTitle; } else { return this._siteTitle; } }; Template.prototype.getPageTitle = function() { return this._pageTitle; }; Template.prototype.getSiteTitle = function() { return this._siteTitle; }; Template.prototype.render = function(path, params) { this._res.render('partials/' + path, params); }; module.exports = Template;
/* eslint-env mocha */ const mockBot = require('../mockBot') const assert = require('assert') const mockery = require('mockery') const sinon = require('sinon') const json = JSON.stringify({ state: 'normal', nowTitle: 'Midnight News', nowInfo: '20/03/2019', nextStart: '2019-03-20T00:30:00Z', nextTitle: 'Book of the Week' }) describe('radio module', function () { let sandbox before(function () { // mockery mocks the entire require() mockery.enable() mockery.registerMock('request-promise', { get: () => Promise.resolve(json) }) // sinon stubs individual functions sandbox = sinon.sandbox.create() mockBot.loadModule('radio') }) it('should parse the API correctly', async function () { sandbox.useFakeTimers({ now: 1553040900000 }) // 2019-03-20T00:15:00Z const promise = await mockBot.runCommand('!r4') assert.strictEqual(promise, 'Now: \u000300Midnight News\u000f \u000315(20/03/2019)\u000f followed by Book of the Week in 15 minutes (12:30 am)') }) after(function (done) { mockery.disable() mockery.deregisterAll() done() }) })
describe("Membrane Panel Operations with flat files:", function() { "use strict"; var window; beforeEach(async function() { await getDocumentLoadPromise("base/gui/index.html"); window = testFrame.contentWindow; window.LoadPanel.testMode = {fakeFiles: true}; let p1 = MessageEventPromise(window, "MembranePanel initialized"); let p2 = MessageEventPromise( window, "MembranePanel cached configuration reset" ); window.OuterGridManager.membranePanelRadio.click(); await Promise.all([p1, p2]); }); function getErrorMessage() { let output = window.OuterGridManager.currentErrorOutput; if (!output.firstChild) return null; return output.firstChild.nodeValue; } it("starts with no graph names and two rows", function() { // two delete buttons and one add button { let buttons = window.HandlerNames.grid.getElementsByTagName("button"); expect(buttons.length).toBe(3); for (let i = 0; i < buttons.length; i++) { expect(buttons[i].disabled).toBe(i < buttons.length - 1); } } const [graphNames, graphSymbolLists] = window.HandlerNames.serializableNames(); expect(Array.isArray(graphNames)).toBe(true); expect(Array.isArray(graphSymbolLists)).toBe(true); expect(graphNames.length).toBe(0); expect(graphSymbolLists.length).toBe(0); expect(getErrorMessage()).toBe(null); }); it("supports the pass-through function for the membrane", function() { const editor = window.MembranePanel.passThroughEditor; { expect(window.MembranePanel.passThroughCheckbox.checked).toBe(false); expect(window.MembranePanel.primordialsCheckbox.checked).toBe(false); expect(window.MembranePanel.primordialsCheckbox.disabled).toBe(true); expect(window.CodeMirrorManager.getEditorEnabled(editor)).toBe(false); } { window.MembranePanel.passThroughCheckbox.click(); expect(window.MembranePanel.passThroughCheckbox.checked).toBe(true); expect(window.MembranePanel.primordialsCheckbox.disabled).toBe(false); expect(window.CodeMirrorManager.getEditorEnabled(editor)).toBe(true); } { window.MembranePanel.primordialsCheckbox.click(); expect(window.MembranePanel.passThroughCheckbox.checked).toBe(true); expect(window.MembranePanel.primordialsCheckbox.checked).toBe(true); expect(window.MembranePanel.primordialsCheckbox.disabled).toBe(false); expect(window.CodeMirrorManager.getEditorEnabled(editor)).toBe(true); const prelim = "(function() {\n const items = Membrane.Primordials.slice(0);\n\n"; const value = window.MembranePanel.getPassThrough(true); expect(value.startsWith(prelim)).toBe(true); } { window.MembranePanel.primordialsCheckbox.click(); expect(window.MembranePanel.passThroughCheckbox.checked).toBe(true); expect(window.MembranePanel.primordialsCheckbox.checked).toBe(false); expect(window.MembranePanel.primordialsCheckbox.disabled).toBe(false); expect(window.CodeMirrorManager.getEditorEnabled(editor)).toBe(true); } { window.MembranePanel.passThroughCheckbox.click(); expect(window.MembranePanel.passThroughCheckbox.checked).toBe(false); expect(window.MembranePanel.primordialsCheckbox.checked).toBe(false); expect(window.MembranePanel.primordialsCheckbox.disabled).toBe(true); expect(window.CodeMirrorManager.getEditorEnabled(editor)).toBe(false); } }); describe( "The graph handler names API requires at least two distinct names (either symbols or strings)", function() { function validateControls() { window.HandlerNames.update(); const inputs = window.MembranePanel.form.getElementsByClassName("objectgraph-name"); const rv = []; const length = inputs.length; for (let i = 0; i < length; i++) { rv.push(inputs[i].checkValidity()); expect(inputs[i].nextElementSibling.disabled).toBe(length == 2); } return rv; } it("initial state is disallowed for two inputs", function() { const states = validateControls(); expect(states.length).toBe(2); expect(states[0]).toBe(false); expect(states[1]).toBe(false); }); it("allows a name to be an unique string", function() { const inputs = window.MembranePanel.form.getElementsByClassName("objectgraph-name"); inputs[0].value = "foo"; inputs[1].value = "bar"; const states = validateControls(); expect(states.length).toBe(2); expect(states[0]).toBe(true); expect(states[1]).toBe(true); }); it("clicking on the addRow button really does add a new row", function() { window.HandlerNames.addRow(); const inputs = window.MembranePanel.form.getElementsByClassName("objectgraph-name"); inputs[0].value = "foo"; inputs[1].value = "bar"; const states = validateControls(); expect(states.length).toBe(3); expect(states[0]).toBe(true); expect(states[1]).toBe(true); expect(states[2]).toBe(false); }); it("disallows non-unique strings", function() { window.HandlerNames.addRow(); const inputs = window.MembranePanel.form.getElementsByClassName("objectgraph-name"); inputs[0].value = "foo"; inputs[1].value = "bar"; inputs[2].value = "foo"; const states = validateControls(); expect(states.length).toBe(3); expect(states[0]).toBe(true); expect(states[1]).toBe(true); expect(states[2]).toBe(false); }); it("allows removing a row", function() { window.HandlerNames.addRow(); const inputs = window.MembranePanel.form.getElementsByClassName("objectgraph-name"); inputs[0].value = "foo"; inputs[1].value = "bar"; inputs[2].value = "baz"; inputs[0].nextElementSibling.click(); expect(inputs.length).toBe(2); expect(inputs[0].value).toBe("bar"); expect(inputs[1].value).toBe("baz"); const states = validateControls(); expect(states.length).toBe(2); expect(states[0]).toBe(true); expect(states[1]).toBe(true); }); it("allows a symbol to share a name with a string", function() { window.HandlerNames.addRow(); const inputs = window.MembranePanel.form.getElementsByClassName("objectgraph-name"); inputs[0].value = "foo"; inputs[1].value = "bar"; inputs[2].value = "foo"; inputs[2].previousElementSibling.firstElementChild.checked = true; // symbol const states = validateControls(); expect(states.length).toBe(3); expect(states[0]).toBe(true); expect(states[1]).toBe(true); expect(states[2]).toBe(true); }); it("allows two symbols to share a name", function() { window.HandlerNames.addRow(); const inputs = window.MembranePanel.form.getElementsByClassName("objectgraph-name"); inputs[0].value = "foo"; inputs[1].value = "bar"; inputs[2].value = "foo"; inputs[0].previousElementSibling.firstElementChild.checked = true; // symbol inputs[2].previousElementSibling.firstElementChild.checked = true; // symbol const states = validateControls(); expect(states.length).toBe(3); expect(states[0]).toBe(true); expect(states[1]).toBe(true); expect(states[2]).toBe(true); }); } ); }); it("Membrane Panel supports pass-through function", async function() { await getDocumentLoadPromise("base/gui/index.html"); const window = testFrame.contentWindow; window.LoadPanel.testMode = { fakeFiles: true, configSource: `{ "configurationSetup": { "useZip": false, "commonFiles": [], "formatVersion": 1, "lastUpdated": "Mon, 19 Feb 2018 20:56:56 GMT" }, "membrane": { "passThroughSource": " // hello world", "passThroughEnabled": true, "primordialsPass": true }, "graphs": [ { "name": "wet", "isSymbol": false, "passThroughSource": "", "passThroughEnabled": false, "primordialsPass": false, "distortions": [] }, { "name": "dry", "isSymbol": false, "passThroughSource": "", "passThroughEnabled": false, "primordialsPass": false, "distortions": [] } ] }` }; let p1 = MessageEventPromise(window, "MembranePanel initialized"); let p2 = MessageEventPromise( window, "MembranePanel cached configuration reset", "MembranePanel exception thrown in reset" ); window.OuterGridManager.membranePanelRadio.click(); await Promise.all([p1, p2]); expect(window.MembranePanel.passThroughCheckbox.checked).toBe(true); expect(window.MembranePanel.primordialsCheckbox.checked).toBe(true); expect(window.MembranePanel.getPassThrough()).toContain("// hello world"); });
tressa.title('HyperHTML'); tressa.assert(typeof hyperHTML === 'function', 'hyperHTML is a function'); try { tressa.log(''); } catch(e) { tressa.log = console.log.bind(console); } tressa.async(function (done) { tressa.log('## injecting text and attributes'); var i = 0; var div = document.body.appendChild(document.createElement('div')); var render = hyperHTML.bind(div); function update(i) { return render` <p data-counter="${i}"> Time: ${ // IE Edge mobile did something funny here // as template string returned xxx.xxxx // but as innerHTML returned xxx.xx (Math.random() * new Date).toFixed(2) } </p> `; } function compare(html) { return /^\s*<p data-counter="\d">\s*Time: \d+\.\d+<[^>]+?>\s*<\/p>\s*$/i.test(html); } var html = update(i++).innerHTML; var p = div.querySelector('p'); var attr = p.attributes[0]; tressa.assert(compare(html), 'correct HTML'); tressa.assert(html === div.innerHTML, 'correctly returned'); setTimeout(function () { tressa.log('## updating same nodes'); var html = update(i++).innerHTML; tressa.assert(compare(html), 'correct HTML update'); tressa.assert(html === div.innerHTML, 'update applied'); tressa.assert(p === div.querySelector('p'), 'no node was changed'); tressa.assert(attr === p.attributes[0], 'no attribute was changed'); done(); }); }) .then(function () { return tressa.async(function (done) { tressa.log('## perf: same virtual text twice'); var div = document.body.appendChild(document.createElement('div')); var render = hyperHTML.bind(div); var html = (update('hello').innerHTML, update('hello').innerHTML); function update(text) { return render`<p>${text} world</p>`; } tressa.assert( update('hello').innerHTML === update('hello').innerHTML, 'same text' ); done(div); }); }) .then(function () { return tressa.async(function (done) { tressa.log('## injecting HTML'); var div = document.body.appendChild(document.createElement('div')); var render = hyperHTML.bind(div); var html = update('hello').innerHTML; function update(text) { return render`<p>${['<strong>' + text + '</strong>']}</p>`; } function compare(html) { return /^<p><strong>\w+<\/strong><!--.+?--><\/p>$/i.test(html); } tressa.assert(compare(html), 'HTML injected'); tressa.assert(html === div.innerHTML, 'HTML returned'); done(div); }); }) .then(function (div) { return tressa.async(function (done) { tressa.log('## function attributes'); var render = hyperHTML.bind(div); var times = 0; update(function (e) { console.log(e.type); if (++times > 1) { return tressa.assert(false, 'events are broken'); } if (e) { e.preventDefault(); e.stopPropagation(); } tressa.assert(true, 'onclick invoked'); tressa.assert(!a.hasAttribute('onclick'), 'no attribute'); update(null); e = document.createEvent('Event'); e.initEvent('click', false, false); a.dispatchEvent(e); done(div); }); function update(click) { // also test case-insensitive builtin events return render`<a href="#" onClick="${click}">click</a>`; } var a = div.querySelector('a'); var e = document.createEvent('Event'); e.initEvent('click', false, false); a.dispatchEvent(e); }); }) .then(function (div) { return tressa.async(function (done) { tressa.log('## changing template'); var render = hyperHTML.bind(div); var html = update('hello').innerHTML; function update(text) { return render`<p>${{any: ['<em>' + text + '</em>']}}</p>`; } function compare(html) { return /^<p><em>\w+<\/em><!--.+?--><\/p>$/i.test(html); } tressa.assert(compare(html), 'new HTML injected'); tressa.assert(html === div.innerHTML, 'new HTML returned'); done(div); }); }) .then(function () { return tressa.async(function (done) { tressa.log('## custom events'); var render = hyperHTML.bind(document.createElement('p')); var e = document.createEvent('Event'); e.initEvent('Custom-EVENT', true, true); (render`<span onCustom-EVENT="${function (e) { tressa.assert(e.type === 'Custom-EVENT', 'event triggered'); done(); }}">how cool</span>` ).firstElementChild.dispatchEvent(e); }); }) .then(function () { tressa.log('## multi wire removal'); var render = hyperHTML.wire(); var update = function () { return render` <p>1</p> <p>2</p> `; }; update().remove(); update = function () { return render` <p>1</p> <p>2</p> <p>3</p> `; }; update().remove(); tressa.assert(true, 'OK'); }) .then(function () { tressa.log('## the attribute id'); var div = document.createElement('div'); hyperHTML.bind(div)`<p id=${'id'} class='class'>OK</p>`; tressa.assert(div.firstChild.id === 'id', 'the id is preserved'); tressa.assert(div.firstChild.className === 'class', 'the class is preserved'); }) .then(function () { return tressa.async(function (done) { tressa.log('## hyperHTML.wire()'); var render = hyperHTML.wire(); var update = function () { return render` <p>1</p> `; }; var node = update(); tressa.assert(node.nodeName.toLowerCase() === 'p', 'correct node'); var same = update(); tressa.assert(node === same, 'same node returned'); render = hyperHTML.wire(null); update = function () { return render` 0 <p>1</p> `; }; node = update().childNodes; tressa.assert(Array.isArray(node), 'list of nodes'); same = update().childNodes; tressa.assert( node.length === same.length && node[0] && node.every(function (n, i) { return same[i] === n; }), 'same list returned' ); var div = document.createElement('div'); render = hyperHTML.bind(div); render`${node}`; same = div.childNodes; tressa.assert( node[0] && node.every(function (n, i) { return same[i] === n; }), 'same list applied' ); function returnSame() { return render`a`; } render = hyperHTML.wire(); tressa.assert( returnSame() === returnSame(), 'template sensible wire' ); done(); }); }) .then(function () { return tressa.async(function (done) { tressa.log('## hyperHTML.wire(object)'); var point = {x: 1, y: 2}; function update() { return hyperHTML.wire(point)` <span style="${` position: absolute; left: ${point.x}px; top: ${point.y}px; `}">O</span>`; } try { update(); } catch(e) { console.error(e) } tressa.assert(update() === update(), 'same output'); tressa.assert(hyperHTML.wire(point) === hyperHTML.wire(point), 'same wire'); done(); }); }) .then(function () { if (typeof MutationObserver === 'undefined') return; return tressa.async(function (done) { tressa.log('## preserve first child where first child is the same as incoming'); var div = document.body.appendChild(document.createElement('div')); var render = hyperHTML.bind(div); var observer = new MutationObserver(function (mutations) { for (var i = 0, len = mutations.length; i < len; i++) { trackMutations(mutations[i].addedNodes, 'added'); trackMutations(mutations[i].removedNodes, 'removed'); } }); observer.observe(div, { childList: true, subtree: true, }); var counters = []; function trackMutations (nodes, countKey) { for (var i = 0, len = nodes.length, counter, key; i < len; i++) { if (nodes[i] && nodes[i].getAttribute && nodes[i].getAttribute('data-test')) { key = nodes[i].getAttribute('data-test'); counter = counters[key] || (counters[key] = { added: 0, removed: 0 }); counter[countKey]++; } if (nodes[i].childNodes.length > 0) { trackMutations(nodes[i].childNodes, countKey); } } } var listItems = []; function update(items) { render` <section> <ul>${ items.map(function (item, i) { return hyperHTML.wire((listItems[i] || (listItems[i] = {})))` <li data-test="${i}">${() => item.text}</li> `; }) }</ul> </section>`; } update([]); setTimeout(function () { update([{ text: 'test1' }]); }, 10); setTimeout(function () { update([{ text: 'test1' }, { text: 'test2' }]); }, 20); setTimeout(function () { update([{ text: 'test1' }]); }, 30); setTimeout(function () { if (counters.length) { tressa.assert(counters[0].added === 1, 'first item added only once'); tressa.assert(counters[0].removed === 0, 'first item never removed'); } done(); }, 100); }); }) .then(function () { tressa.log('## rendering one node'); var div = document.createElement('div'); var br = document.createElement('br'); var hr = document.createElement('hr'); hyperHTML.bind(div)`<div>${br}</div>`; tressa.assert(div.firstChild.firstChild === br, 'one child is added'); hyperHTML.bind(div)`<div>${hr}</div>`; tressa.assert(div.firstChild.firstChild === hr, 'one child is changed'); hyperHTML.bind(div)`<div>${[hr, br]}</div>`; tressa.assert( div.firstChild.childNodes[0] === hr && div.firstChild.childNodes[1] === br, 'more children are added' ); hyperHTML.bind(div)`<div>${[br, hr]}</div>`; tressa.assert( div.firstChild.childNodes[0] === br && div.firstChild.childNodes[1] === hr, 'children can be swapped' ); hyperHTML.bind(div)`<div>${br}</div>`; tressa.assert(div.firstChild.firstChild === br, 'one child is kept'); hyperHTML.bind(div)`<div>${[]}</div>`; tressa.assert(/<div><!--.+?--><\/div>/.test(div.innerHTML), 'dropped all children'); }) .then(function () { tressa.log('## wire by id'); let ref = {}; let wires = { a: function () { return hyperHTML.wire(ref, ':a')`<a></a>`; }, p: function () { return hyperHTML.wire(ref, ':p')`<p></p>`; } }; tressa.assert(wires.a().nodeName.toLowerCase() === 'a', '<a> is correct'); tressa.assert(wires.p().nodeName.toLowerCase() === 'p', '<p> is correct'); tressa.assert(wires.a() === wires.a(), 'same wire for <a>'); tressa.assert(wires.p() === wires.p(), 'same wire for <p>'); }) .then(function () { return tressa.async(function (done) { tressa.log('## Promises instead of nodes'); let wrap = document.createElement('div'); let render = hyperHTML.bind(wrap); render`<p>${ new Promise(function (r) { setTimeout(r, 50, 'any'); }) }</p>${ new Promise(function (r) { setTimeout(r, 10, 'virtual'); }) }<hr><div>${[ new Promise(function (r) { setTimeout(r, 20, 1); }), new Promise(function (r) { setTimeout(r, 10, 2); }), ]}</div>${[ new Promise(function (r) { setTimeout(r, 20, 3); }), new Promise(function (r) { setTimeout(r, 10, 4); }), ]}`; let result = wrap.innerHTML; setTimeout(function () { tressa.assert(result !== wrap.innerHTML, 'promises fullfilled'); tressa.assert( /^<p>any<!--.+?--><\/p>virtual<!--.+?--><hr(?: ?\/)?><div>12<!--.+?--><\/div>34<!--.+?-->$/.test(wrap.innerHTML), 'both any and virtual content correct' ); done(); }, 100); }); }) .then(function () { hyperHTML.engine = hyperHTML.engine; tressa.log('## for code coverage sake'); let wrap = document.createElement('div'); let text = [document.createTextNode('a'), document.createTextNode('b'), document.createTextNode('c')]; let testingMajinBuu = hyperHTML.bind(wrap); testingMajinBuu`${[text]}`; tressa.assert(wrap.textContent === 'abc'); text[0] = document.createTextNode('c'); text[2] = document.createTextNode('a'); testingMajinBuu`${[text]}`; tressa.assert(wrap.textContent === 'cba'); let result = hyperHTML.wire()`<!--not hyperHTML-->`; tressa.assert(result.nodeType === 8, 'it is a comment'); tressa.assert(result.textContent === 'not hyperHTML', 'correct content'); hyperHTML.bind(wrap)`<br/>${'node before'}`; tressa.assert(/^<br(?: ?\/)?>node before<!--.+?-->$/i.test(wrap.innerHTML), 'node before'); hyperHTML.bind(wrap)`${'node after'}<br/>`; tressa.assert(/^node after<!--.+?--><br(?: ?\/)?>$/i.test(wrap.innerHTML), 'node after'); hyperHTML.bind(wrap)`<style> ${'hyper-html{}'} </style>`; tressa.assert('<style>hyper-html{}</style>' === wrap.innerHTML.toLowerCase(), 'node style'); var empty = function (value) { return hyperHTML.bind(wrap)`${value}`; }; empty(document.createTextNode('a')); empty(document.createDocumentFragment()); empty(document.createDocumentFragment()); let fragment = document.createDocumentFragment(); fragment.appendChild(document.createTextNode('b')); empty(fragment); empty(123); tressa.assert(wrap.textContent === '123', 'text as number'); empty(true); tressa.assert(wrap.textContent === 'true', 'text as boolean'); empty([1]); tressa.assert(wrap.textContent === '1', 'text as one entry array'); empty(['1', '2']); tressa.assert(wrap.textContent === '12', 'text as multi entry array of strings'); let arr = [document.createTextNode('a'), document.createTextNode('b')]; empty([arr]); tressa.assert(wrap.textContent === 'ab', 'text as multi entry array of nodes'); empty([arr]); tressa.assert(wrap.textContent === 'ab', 'same array of nodes'); empty(wrap.childNodes); tressa.assert(wrap.textContent === 'ab', 'childNodes as list'); hyperHTML.bind(wrap)`a=${{length:1, '0':'b'}}`; tressa.assert(wrap.textContent === 'a=b', 'childNodes as virtual list'); empty = function () { return hyperHTML.bind(wrap)`[${'text'}]`; }; empty(); empty(); let onclick = (e) => {}; let handler = {handleEvent: onclick}; empty = function () { return hyperHTML.bind(wrap)`<p onclick="${onclick}" onmouseover="${handler}" align="${'left'}"></p>`; }; empty(); handler = {handleEvent: onclick}; empty(); empty(); empty = function (value) { return hyperHTML.bind(wrap)`<br/>${value}<br/>`; }; empty(arr[0]); empty(arr); empty(arr); empty([]); empty(['1', '2']); empty(document.createDocumentFragment()); tressa.assert(true, 'passed various virtual content scenarios'); let svgContainer = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); if (!('ownerSVGElement' in svgContainer)) svgContainer.ownerSVGElement = null; hyperHTML.bind(svgContainer)`<rect x="1" y="2" />`; result = hyperHTML.wire(null, 'svg')`<svg></svg>`; tressa.assert(result.nodeName.toLowerCase() === 'svg', 'svg content is allowed too'); result = hyperHTML.wire()``; tressa.assert(!result.innerHTML, 'empty content'); let tr = hyperHTML.wire()`<tr><td>ok</td></tr>`; tressa.assert(true, 'even TR as template'); hyperHTML.bind(wrap)`${' 1 '}`; tressa.assert(wrap.textContent === ' 1 ', 'text in between'); hyperHTML.bind(wrap)` <br/>${1}<br/> `; tressa.assert(/^\s*<br(?: ?\/)?>1<!--.+?--><br(?: ?\/)?>\s*$/.test(wrap.innerHTML), 'virtual content in between'); let last = hyperHTML.wire(); empty = function (style) { return last`<textarea style=${style}>${() => 'same text'}</textarea>`; }; empty('border:0'); empty({border: 0}); empty({vh: 100}); empty({vh: 10, vw: 1}); empty(null); empty(''); const sameStyle = {ord: 0}; empty(sameStyle); empty(sameStyle); empty = function () { return last`<p data=${last}></p>`; }; empty(); empty(); let p = last`<p data=${last}>${0}</p>`; const UID = p.childNodes[1].data; last`<textarea new>${`<!--${UID}-->`}</textarea>`; hyperHTML.wire()`<p><!--ok--></p>`; }) .then(function () { tressa.log('## <script> shenanigans'); return tressa.async(function (done) { var div = document.createElement('div'); document.body.appendChild(div); hyperHTML.bind(div)`<script src="../index.js?_=asd" onreadystatechange="${event => { if (/loaded|complete/.test(event.readyState)) setTimeout(() => { tressa.assert(true, 'executed'); done(); }); }}" onload="${() => { tressa.assert(true, 'executed'); done(); }}" onerror="${() => { tressa.assert(true, 'executed'); done(); }}" ></script>`; // in nodejs case if (!('onload' in document.defaultView)) { var evt = document.createEvent('Event'); evt.initEvent('load', false, false); div.firstChild.dispatchEvent(evt); } }); }) .then(function () { tressa.log('## SVG and style'); var render = hyperHTML.wire(null, 'svg'); Object.prototype.ownerSVGElement = null; function rect(style) { return render`<rect style=${style} />`; } var node = rect({}); delete Object.prototype.ownerSVGElement; rect({width: 100}); console.log(node.getAttribute('style')); tressa.assert(/width:\s*100px;/.test(node.getAttribute('style')), 'correct style object'); rect('height:10px;'); tressa.assert(/height:\s*10px;/.test(node.getAttribute('style')), 'correct style string'); rect(null); tressa.assert(/^(?:|null)$/.test(node.getAttribute('style')), 'correct style reset'); }) .then(function () { var a = document.createTextNode('a'); var b = document.createTextNode('b'); var c = document.createTextNode('c'); var d = document.createTextNode('d'); var e = document.createTextNode('e'); var f = document.createTextNode('f'); var g = document.createTextNode('g'); var h = document.createTextNode('h'); var i = document.createTextNode('i'); var div = document.createElement('div'); var render = hyperHTML.bind(div); render`${[]}`; tressa.assert(div.textContent === '', 'div is empty'); render`${[c, d, e, f]}`; // all tests know that a comment node is inside the div tressa.assert(div.textContent === 'cdef' && div.childNodes.length === 5, 'div has 4 nodes'); render`${[c, d, e, f]}`; tressa.assert(div.textContent === 'cdef', 'div has same 4 nodes'); render`${[a, b, c, d, e, f]}`; tressa.assert(div.textContent === 'abcdef' && div.childNodes.length === 7, 'div has same 4 nodes + 2 prepends'); render`${[a, b, c, d, e, f, g, h, i]}`; tressa.assert(div.textContent === 'abcdefghi' && div.childNodes.length === 10, 'div has 6 nodes + 3 appends'); render`${[b, c, d, e, f, g, h, i]}`; tressa.assert(div.textContent === 'bcdefghi' && div.childNodes.length === 9, 'div has dropped first node'); render`${[b, c, d, e, f, g, h]}`; tressa.assert(div.textContent === 'bcdefgh' && div.childNodes.length === 8, 'div has dropped last node'); render`${[b, c, d, f, e, g, h]}`; tressa.assert(div.textContent === 'bcdfegh', 'div has changed 2 nodes'); render`${[b, d, c, f, g, e, h]}`; tressa.assert(div.textContent === 'bdcfgeh', 'div has changed 4 nodes'); render`${[b, d, c, g, e, h]}`; tressa.assert(div.textContent === 'bdcgeh' && div.childNodes.length === 7, 'div has removed central node'); }) .then(function () { tressa.log('## no WebKit backfire'); var div = document.createElement('div'); function update(value, attr) { return hyperHTML.bind(div)` <input value="${value}" shaka="${attr}">`; } var input = update('', '').firstElementChild; input.value = '456'; input.setAttribute('shaka', 'laka'); update('123', 'laka'); tressa.assert(input.value === '123', 'correct input'); tressa.assert(input.value === '123', 'correct attribute'); update('', ''); input.value = '123'; input.attributes.shaka.value = 'laka'; update('123', 'laka'); tressa.assert(input.value === '123', 'input.value was not reassigned'); }) .then(function () { tressa.log('## wired arrays are rendered properly'); var div = document.createElement('div'); var employees = [ {first: 'Bob', last: 'Li'}, {first: 'Ayesha', last: 'Johnson'} ]; var getEmployee = employee => hyperHTML.wire(employee)` <div>First name: ${employee.first}</div> <p></p>`; hyperHTML.bind(div)`${employees.map(getEmployee)}`; tressa.assert(div.childElementCount === 4, 'correct elements as setAny'); hyperHTML.bind(div)` <p></p>${employees.map(getEmployee)}`; tressa.assert(div.childElementCount === 5, 'correct elements as setVirtual'); hyperHTML.bind(div)` <p></p>${[]}`; tressa.assert(div.childElementCount === 1, 'only one element left'); }) .then(function () {return tressa.async(function (done) { function textarea(value) { return hyperHTML.bind(div)`<textarea>${value}</textarea>`; } tressa.log('## textarea text'); var div = document.createElement('div'); textarea(1); var ta = div.firstElementChild; tressa.assert(ta.textContent === '1', 'primitives are fine'); textarea(null); tressa.assert(ta.textContent === '', 'null/undefined is fine'); var p = Promise.resolve('OK'); textarea(p); p.then(function () { console.log(div.innerHTML); tressa.assert(ta.textContent === 'OK', 'promises are fine'); textarea({text: 'text'}); tressa.assert(ta.textContent === 'text', 'text is fine'); textarea({html: 'html'}); tressa.assert(ta.textContent === 'html', 'html is fine'); textarea({any: 'any'}); tressa.assert(ta.textContent === 'any', 'any is fine'); textarea(['ar', 'ray']); tressa.assert(ta.textContent === 'array', 'array is fine'); textarea({placeholder: 'placeholder'}); tressa.assert(ta.textContent === 'placeholder', 'placeholder is fine'); textarea({unknown: 'unknown'}); tressa.assert(ta.textContent === '', 'intents are fine'); done(); }); })}) .then(function () { tressa.log('## attributes with weird chars'); var div = document.createElement('div'); hyperHTML.bind(div)`<p _foo=${'bar'}></p>`; tressa.assert(div.firstChild.getAttribute('_foo') === 'bar', 'OK'); }) .then(function () { tressa.log('## attributes without quotes'); var div = document.createElement('div'); hyperHTML.bind(div)`<p test=${'a"b'}></p>`; tressa.assert(div.firstChild.getAttribute('test') === 'a"b', 'OK'); }) .then(function () { tressa.log('## any content extras'); var div = document.createElement('div'); var html = hyperHTML.bind(div); setContent(undefined); tressa.assert(/<p><!--.+?--><\/p>/.test(div.innerHTML), 'expected layout'); setContent({text: '<img/>'}); tressa.assert(/<p>&lt;img(?: ?\/)?&gt;<!--.+?--><\/p>/.test(div.innerHTML), 'expected text'); function setContent(which) { return html`<p>${which}</p>`; } }) .then(function () { tressa.log('## any different content extras'); var div = document.createElement('div'); hyperHTML.bind(div)`<p>${undefined}</p>`; tressa.assert(/<p><!--.+?--><\/p>/.test(div.innerHTML), 'expected layout'); hyperHTML.bind(div)`<p>${{text: '<img/>'}}</p>`; tressa.assert(/<p>&lt;img(?: ?\/)?&gt;<!--.+?--><\/p>/.test(div.innerHTML), 'expected text'); }) .then(function () { tressa.log('## virtual content extras'); var div = document.createElement('div'); hyperHTML.bind(div)`a ${null}`; tressa.assert(/a <[^>]+?>/.test(div.innerHTML), 'expected layout'); hyperHTML.bind(div)`a ${{text: '<img/>'}}`; tressa.assert(/a &lt;img(?: ?\/)?&gt;<[^>]+?>/.test(div.innerHTML), 'expected text'); hyperHTML.bind(div)`a ${{any: 123}}`; tressa.assert(/a 123<[^>]+?>/.test(div.innerHTML), 'expected any'); hyperHTML.bind(div)`a ${{html: '<b>ok</b>'}}`; tressa.assert(/a <b>ok<\/b><[^>]+?>/.test(div.innerHTML), 'expected html'); hyperHTML.bind(div)`a ${{}}`; tressa.assert(/a <[^>]+?>/.test(div.innerHTML), 'expected nothing'); }) .then(function () { tressa.log('## defined transformer'); hyperHTML.define('eUC', encodeURIComponent); var div = document.createElement('div'); hyperHTML.bind(div)`a=${{eUC: 'b c'}}`; tressa.assert(/a=b%20c<[^>]+?>/.test(div.innerHTML), 'expected virtual layout'); hyperHTML.bind(div)`<p>${{eUC: 'b c'}}</p>`; tressa.assert(/<p>b%20c<!--.+?--><\/p>/.test(div.innerHTML), 'expected layout'); // TODO: for coverage sake // defined transformer ... so what? hyperHTML.define('eUC', encodeURIComponent); // non existent one ... so what? hyperHTML.bind(div)`a=${{nOPE: 'b c'}}`; }) .then(function () { tressa.log('## attributes with null values'); var div = document.createElement('div'); var anyAttr = function (value) { hyperHTML.bind(div)`<p any-attr=${value}>any content</p>`; }; anyAttr('1'); tressa.assert( div.firstChild.hasAttribute('any-attr') && div.firstChild.getAttribute('any-attr') === '1', 'regular attribute' ); anyAttr(null); tressa.assert( !div.firstChild.hasAttribute('any-attr') && div.firstChild.getAttribute('any-attr') == null, 'can be removed' ); anyAttr(undefined); tressa.assert( !div.firstChild.hasAttribute('any-attr') && div.firstChild.getAttribute('any-attr') == null, 'multiple times' ); anyAttr('2'); tressa.assert( div.firstChild.hasAttribute('any-attr') && div.firstChild.getAttribute('any-attr') === '2', 'but can be also reassigned' ); anyAttr('3'); tressa.assert( div.firstChild.hasAttribute('any-attr') && div.firstChild.getAttribute('any-attr') === '3', 'many other times' ); var inputName = function (value) { hyperHTML.bind(div)`<input name=${value}>`; }; inputName('test'); tressa.assert( div.firstChild.hasAttribute('name') && div.firstChild.name === 'test', 'special attributes are set too' ); inputName(null); tressa.assert( !div.firstChild.hasAttribute('name') && !div.firstChild.name, 'but can also be removed' ); inputName(undefined); tressa.assert( !div.firstChild.hasAttribute('name') && !div.firstChild.name, 'with either null or undefined' ); inputName('back'); tressa.assert( div.firstChild.hasAttribute('name') && div.firstChild.name === 'back', 'and can be put back' ); }) .then(function () {return tressa.async(function (done) { tressa.log('## placeholder'); var div = document.createElement('div'); var vdiv = document.createElement('div'); hyperHTML.bind(div)`<p>${{eUC: 'b c', placeholder: 'z'}}</p>`; hyperHTML.bind(vdiv)`a=${{eUC: 'b c', placeholder: 'z'}}`; tressa.assert(/<p>z<!--.+?--><\/p>/.test(div.innerHTML), 'expected inner placeholder layout'); tressa.assert(/a=z<[^>]+?>/.test(vdiv.innerHTML), 'expected virtual placeholder layout'); setTimeout(function () { tressa.assert(/<p>b%20c<!--.+?--><\/p>/.test(div.innerHTML), 'expected inner resolved layout'); tressa.assert(/a=b%20c<[^>]+?>/.test(vdiv.innerHTML), 'expected virtual resolved layout'); hyperHTML.bind(div)`<p>${{text: 1, placeholder: '9'}}</p>`; setTimeout(function () { tressa.assert(/<p>1<!--.+?--><\/p>/.test(div.innerHTML), 'placeholder with text'); hyperHTML.bind(div)`<p>${{any: [1, 2], placeholder: '9'}}</p>`; setTimeout(function () { tressa.assert(/<p>12<!--.+?--><\/p>/.test(div.innerHTML), 'placeholder with any'); hyperHTML.bind(div)`<p>${{html: '<b>3</b>', placeholder: '9'}}</p>`; setTimeout(function () { tressa.assert(/<p><b>3<\/b><!--.+?--><\/p>/.test(div.innerHTML), 'placeholder with html'); done(); }, 10); }, 10); }, 10); }, 10); });}) .then(function () { tressa.log('## hyper(...)'); var hyper = hyperHTML.hyper; tressa.assert(typeof hyper() === 'function', 'empty hyper() is a wire tag'); tressa.assert((hyper`abc`).textContent === 'abc', 'hyper`abc`'); tressa.assert((hyper`<p>a${2}c</p>`).textContent === 'a2c', 'hyper`<p>a${2}c</p>`'); tressa.assert((hyper(document.createElement('div'))`abc`).textContent === 'abc', 'hyper(div)`abc`'); tressa.assert((hyper(document.createElement('div'))`a${'b'}c`).textContent === 'abc', 'hyper(div)`a${"b"}c`'); // WFT jsdom ?! delete Object.prototype.nodeType; tressa.assert((hyper({})`abc`).textContent === 'abc', 'hyper({})`abc`'); tressa.assert((hyper({})`<p>a${'b'}c</p>`).textContent === 'abc', 'hyper({})`<p>a${\'b\'}c</p>`'); tressa.assert((hyper({}, ':id')`abc`).textContent === 'abc', 'hyper({}, \':id\')`abc`'); tressa.assert((hyper({}, ':id')`<p>a${'b'}c</p>`).textContent === 'abc', 'hyper({}, \':id\')`<p>a${\'b\'}c</p>`'); tressa.assert((hyper('svg')`<rect />`), 'hyper("svg")`<rect />`'); }) .then(function () { tressa.log('## data=${anyContent}'); var obj = {rand: Math.random()}; var div = hyperHTML.wire()`<div data=${obj}>abc</div>`; tressa.assert(div.data === obj, 'data available without serialization'); tressa.assert(div.outerHTML === '<div>abc</div>', 'attribute not there'); }) .then(function () { tressa.log('## hyper.Component'); class Button extends hyperHTML.Component { render() { return this.html` <button>hello</button>`; } } class Rect extends hyperHTML.Component { constructor(state) { super(); this.setState(state, false); } render() { return this.svg` <rect x=${this.state.x} y=${this.state.y} />`; } } class Paragraph extends hyperHTML.Component { constructor(state) { super(); this.setState(state); } onclick() { this.clicked = true; } render() { return this.html` <p attr=${this.state.attr} onclick=${this}>hello</p>`; } } var div = document.createElement('div'); var render = hyperHTML.bind(div); render`${[ new Button, new Rect({x: 123, y: 456}) ]}`; tressa.assert(div.querySelector('button'), 'the <button> exists'); tressa.assert(div.querySelector('rect'), 'the <rect /> exists'); tressa.assert(div.querySelector('rect').getAttribute('x') == '123', 'attributes are OK'); var p = new Paragraph(() => ({attr: 'test'})); render`${p}`; tressa.assert(div.querySelector('p').getAttribute('attr') === 'test', 'the <p attr=test> is defined'); p.render().click(); tressa.assert(p.clicked, 'the event worked'); render`${[ hyperHTML.Component.for.call(Rect, {x: 789, y: 123}) ]}`; tressa.assert(div.querySelector('rect').getAttribute('x') == '789', 'the for(state) worked'); }) .then(function () { return tressa.async(function (done) { tressa.log('## Component method via data-call'); class Paragraph extends hyperHTML.Component { globally(e) { tressa.assert(e.type === 'click', 'data-call invoked globall'); done(); } test(e) { tressa.assert(e.type === 'click', 'data-call invoked locally'); } render() { return this.html` <p data-call="test" onclick=${this}>hello</p>`; } } class GlobalEvent extends hyperHTML.Component { onclick(e) { tressa.assert(e.type === 'click', 'click invoked globally'); document.removeEventListener('click', this); done(); } render() { document.addEventListener('click', this); return document; } } var p = new Paragraph(); p.render().click(); var e = document.createEvent('Event'); e.initEvent('click', true, true); (new GlobalEvent).render().dispatchEvent(e); }); }) .then(function () { return tressa.async(function (done) { tressa.log('## Custom Element attributes'); var global = document.defaultView; var registry = global.customElements; var customElements = { _: Object.create(null), define: function (name, Class) { this._[name.toLowerCase()] = Class; }, get: function (name) { return this._[name.toLowerCase()]; } }; Object.defineProperty(global, 'customElements', { configurable: true, value: customElements }); function DumbElement() {} DumbElement.prototype.dumb = null; DumbElement.prototype.asd = null; customElements.define('dumb-element', DumbElement); function update(wire) { return wire`<div> <dumb-element dumb=${true} asd=${'qwe'}></dumb-element><dumber-element dumb=${true}></dumber-element> </div>`; } var div = update(hyperHTML.wire()); if (!(div.firstElementChild instanceof DumbElement)) { tressa.assert(div.firstElementChild.dumb !== true, 'not upgraded elements does not have special attributes'); tressa.assert(div.lastElementChild.dumb !== true, 'unknown elements never have special attributes'); // simulate an upgrade div.firstElementChild.constructor.prototype.dumb = null; } div = update(hyperHTML.wire()); delete div.firstElementChild.constructor.prototype.dumb; tressa.assert(div.firstElementChild.dumb === true, 'upgraded elements have special attributes'); Object.defineProperty(global, 'customElements', { configurable: true, value: registry }); done(); }); }) .then(function () { tressa.log('## hyper.Component state'); class DefaultState extends hyperHTML.Component { get defaultState() { return {a: 'a'}; } render() {} } class State extends hyperHTML.Component {} var ds = new DefaultState; var o = ds.state; tressa.assert(!ds.propertyIsEnumerable('state'), 'states are not enumerable'); tressa.assert(!ds.propertyIsEnumerable('_state$'), 'neither their secret'); tressa.assert(o.a === 'a', 'default state retrieved'); var s = new State; s.state = o; tressa.assert(s.state === o, 'state can be set too'); ds.setState({b: 'b'}); tressa.assert(o.a === 'a' && o.b === 'b', 'state was updated'); s.state = {z: 123}; tressa.assert(s.state.z === 123 && !s.state.a, 'state can be re-set too'); }) .then(function () { tressa.log('## splice and sort'); var todo = [ {id: 0, text: 'write documentation'}, {id: 1, text: 'publish online'}, {id: 2, text: 'create Code Pen'} ]; var div = document.createElement('div'); update(); todo.sort(function(a, b) { return a.text < b.text ? -1 : 1; }); update(); tressa.assert(/^\s+create Code Pen\s*publish online\s*write documentation\s+$/.test(div.textContent), 'correct order'); function update() { hyperHTML.bind(div)`<ul> ${todo.map(function (item) { return hyperHTML.wire(item) `<li data-id=${item.id}>${item.text}</li>`; })} </ul>`; } }) .then(function () { return tressa.async(function (done) { tressa.log('## Component connected/disconnected'); var calls = 0; class Paragraph extends hyperHTML.Component { onconnected(e) { calls++; tressa.assert(e.type === 'connected', 'component connected'); e.currentTarget.parentNode.removeChild(e.currentTarget); } ondisconnected(e) { calls++; tressa.assert(e.type === 'disconnected', 'component disconnected'); } render() { return this.html` <p onconnected=${this} ondisconnected=${this}>hello</p>`; } } var p = new Paragraph().render(); document.body.appendChild(p); if (p.parentNode) { setTimeout(function () { var e = document.createEvent('Event'); e.initEvent('DOMNodeInserted', false, false); Object.defineProperty(e, 'target', {value: document.body}); document.dispatchEvent(e); setTimeout(function () { e = document.createEvent('Event'); e.initEvent('DOMNodeInserted', false, false); Object.defineProperty(e, 'target', {value: document.createTextNode('')}); document.dispatchEvent(e); setTimeout(function () { e = document.createEvent('Event'); e.initEvent('DOMNodeRemoved', false, false); Object.defineProperty(e, 'target', {value: p}); document.dispatchEvent(e); setTimeout(function () { tressa.assert(calls === 2, 'correct amount of calls'); done(); }, 100); }, 100); }, 100); }, 100); } }); }) .then(function () { tressa.log('## style=${fun}'); var render = hyperHTML.wire(); function p(style) { return render`<p style=${style}></p>`; } var node = p({fontSize:24}); tressa.assert(node.style.fontSize, node.style.fontSize); p({}); tressa.assert(!node.style.fontSize, 'object cleaned'); p('font-size: 18px'); tressa.assert(node.style.fontSize, node.style.fontSize); p({'--custom-color': 'red'}); if (node.style.cssText !== '') tressa.assert(node.style.getPropertyValue('--custom-color') === 'red', 'custom style'); else console.log('skipping CSS properties for IE'); }) .then(function () { tressa.log('## <self-closing />'); var div = hyperHTML.wire()`<div><self-closing test=${1} /><input /><self-closing test="2" /></div>`; tressa.assert(div.childNodes.length === 3, 'nodes did self close'); tressa.assert(div.childNodes[0].getAttribute('test') == "1", 'first node ok'); tressa.assert(/input/i.test(div.childNodes[1].nodeName), 'second node ok'); tressa.assert(div.childNodes[2].getAttribute('test') == "2", 'third node ok'); div = hyperHTML.wire()`<div> <self-closing test=1 /><input /><self-closing test="2" /> </div>`; tressa.assert(div.children.length === 3, 'nodes did self close'); tressa.assert(div.children[0].getAttribute('test') == "1", 'first node ok'); tressa.assert(/input/i.test(div.children[1].nodeName), 'second node ok'); tressa.assert(div.children[2].getAttribute('test') == "2", 'third node ok'); div = hyperHTML.wire()` <div style="width: 200px;"> <svg viewBox="0 0 30 30" fill="currentColor"> <path d="M 0,27 L 27,0 L 30,3 L 3,30 Z" /> <path d="M 0,3 L 3,0 L 30,27 L 27,30 Z" /> </svg> </div> `; tressa.assert(div.children.length === 1, 'one svg'); tressa.assert(div.querySelectorAll('path').length === 2, 'two paths'); }) .then(function () { tressa.log('## <with><self-closing /></with>'); function check(form) { return form.children.length === 3 && /label/i.test(form.children[0].nodeName) && /input/i.test(form.children[1].nodeName) && /button/i.test(form.children[2].nodeName) } tressa.assert( check(hyperHTML.wire()` <form onsubmit=${check}> <label/> <input type="email" placeholder="email"> <button>Button</button> </form>`), 'no quotes is OK' ); tressa.assert( check(hyperHTML.wire()` <form onsubmit=${check}> <label /> <input type="email" placeholder="email"/> <button>Button</button> </form>`), 'self closing is OK' ); tressa.assert( check(hyperHTML.wire()` <form onsubmit="${check}"> <label/> <input type="email" placeholder="email"> <button>Button</button> </form>`), 'quotes are OK' ); tressa.assert( check(hyperHTML.wire()` <form onsubmit="${check}"> <label/> <input type="email" placeholder="email" /> <button>Button</button> </form>`), 'quotes and self-closing too OK' ); }) .then(function () { return tressa.async(function (done) { tressa.log('## Nested Component connected/disconnected'); class GrandChild extends hyperHTML.Component { onconnected(e) { tressa.assert(e.type === 'connected', 'grand child component connected'); } ondisconnected(e) { tressa.assert(e.type === 'disconnected', 'grand child component disconnected'); } render() { return this.html` <p class="grandchild" onconnected=${this} ondisconnected=${this}>I'm grand child</p>`; } } class Child extends hyperHTML.Component { onconnected(e) { tressa.assert(e.type === 'connected', 'child component connected'); } ondisconnected(e) { tressa.assert(e.type === 'disconnected', 'child component disconnected'); } render() { return this.html` <div class="child" onconnected=${this} ondisconnected=${this}>I'm child ${new GrandChild()} </div> `; } } let connectedTimes = 0, disconnectedTimes = 0; class Parent extends hyperHTML.Component { onconnected(e) { connectedTimes ++; tressa.assert(e.type === 'connected', 'parent component connected'); tressa.assert(connectedTimes === 1, 'connected callback should only be triggered once'); } ondisconnected(e) { disconnectedTimes ++; tressa.assert(e.type === 'disconnected', 'parent component disconnected'); tressa.assert(disconnectedTimes === 1, 'disconnected callback should only be triggered once'); done(); } render() { return this.html` <div class="parent" onconnected=${this} ondisconnected=${this}>I'm parent ${new Child()} </div> `; } } var p = new Parent().render(); document.body.appendChild(p); setTimeout(function () { if (p.parentNode) { var e = document.createEvent('Event'); e.initEvent('DOMNodeInserted', false, false); Object.defineProperty(e, 'target', {value: document.body}); document.dispatchEvent(e); setTimeout(function () { e = document.createEvent('Event'); e.initEvent('DOMNodeRemoved', false, false); Object.defineProperty(e, 'target', {value: p}); document.dispatchEvent(e); if (p.parentNode) p.parentNode.removeChild(p); }, 100); } }, 100); }); }) .then(function () { tressa.log('## Declarative Components'); class MenuSimple extends hyperHTML.Component { render(props) { return this.setState(props, false).html` <div>A simple menu</div> <ul> ${props.items.map( (item, i) => MenuItem.for(this, i).render(item) )} </ul> `; } } class MenuWeakMap extends hyperHTML.Component { render(props) { return this.setState(props, false).html` <div>A simple menu</div> <ul> ${props.items.map( item => MenuItem.for(this, item).render(item) )} </ul> `; } } class MenuItem extends hyperHTML.Component { render(props) { return this.setState(props, false).html` <li>${props.name}</li> `; } } var a = document.createElement('div'); var b = document.createElement('div'); var method = hyperHTML.Component.for; if (!MenuSimple.for) { MenuSimple.for = method; MenuWeakMap.for = method; MenuItem.for = method; } hyperHTML.bind(a)`${MenuSimple.for(a).render({ items: [{name: 'item 1'}, {name: 'item 2'}, {name: 'item 3'}] })}`; tressa.assert(MenuSimple.for(a) === MenuSimple.for(a), 'same simple menu'); hyperHTML.bind(b)`${MenuWeakMap.for(b).render({ items: [{name: 'item 1'}, {name: 'item 2'}, {name: 'item 3'}] })}`; tressa.assert(MenuWeakMap.for(a) === MenuWeakMap.for(a), 'same weakmap menu'); tressa.assert(MenuSimple.for(a) !== MenuWeakMap.for(a), 'different from simple'); tressa.assert(MenuSimple.for(a) === MenuSimple.for(a), 'same as simple'); tressa.assert(a.outerHTML === b.outerHTML, 'same layout'); }) .then(function () { tressa.log('## Component.dispatch'); class Pomponent extends hyperHTML.Component { trigger() { this.dispatch('event', 123); } render() { return this.html`<p>a</p><p>b</p>`; } } class Solonent extends hyperHTML.Component { render() { return this.html`<p>c</p>`; } } var a = document.createElement('div'); var p = new Pomponent; p.trigger(); var s = new Solonent; var dispatched = false; hyperHTML.bind(a)`${[p, s]}`; a.addEventListener('event', event => { tressa.assert(event.detail === 123, 'expected details'); tressa.assert(event.component === p, 'expected component'); dispatched = true; }); p.trigger(); s.dispatch('test'); if (!dispatched) throw new Error('broken dispatch'); }) .then(function () { tressa.log('## slotted callback'); var div = document.createElement('div'); var result = []; function A() { result.push(arguments); return {html: '<b>a</b>'}; } function B() { result.push(arguments); return {html: '<b>b</b>'}; } function update() { hyperHTML.bind(div)`${A} - ${B}`; } update(); tressa.assert(result[0][0].parentNode === div, 'expected parent node for A'); tressa.assert(result[1][0].parentNode === div, 'expected parent node for B'); }) .then(function () { tressa.log('## define(hyper-attribute, callback)'); var a = document.createElement('div'); var random = Math.random().toPrecision(6); // IE < 11 var result = []; hyperHTML.define('hyper-attribute', function (target, value) { result.push(target, value); return random; }); hyperHTML.bind(a)`<p hyper-attribute=${random}/>`; if (!result.length) throw new Error('attributes intents failed'); else { tressa.assert(result[0] === a.firstElementChild, 'expected target'); tressa.assert(result[1] === random, 'expected value'); tressa.assert( a.firstElementChild.getAttribute('hyper-attribute') == random, 'expected attribute' ); } result.splice(0); hyperHTML.define('other-attribute', function (target, value) { result.push(target, value); return ''; }); hyperHTML.define('disappeared-attribute', function (target, value) { }); hyperHTML.define('whatever-attribute', function (target, value) { return value; }); hyperHTML.define('null-attribute', function (target, value) { return null; }); hyperHTML.bind(a)`<p other-attribute=${random} disappeared-attribute=${random} whatever-attribute=${random} null-attribute=${random} />`; if (!result.length) throw new Error('attributes intents failed'); else { tressa.assert(result[0] === a.firstElementChild, 'expected other target'); tressa.assert(result[1] === random, 'expected other value'); tressa.assert( a.firstElementChild.getAttribute('other-attribute') === '', 'expected other attribute' ); tressa.assert( !a.firstElementChild.hasAttribute('disappeared-attribute'), 'disappeared-attribute removed' ); tressa.assert( a.firstElementChild.getAttribute('whatever-attribute') == random, 'whatever-attribute set' ); tressa.assert( !a.firstElementChild.hasAttribute('null-attribute'), 'null-attribute removed' ); } }) // WARNING THESE TEST MUST BE AT THE VERY END // WARNING THESE TEST MUST BE AT THE VERY END // WARNING THESE TEST MUST BE AT THE VERY END .then(function () { // WARNING THESE TEST MUST BE AT THE VERY END tressa.log('## IE9 double viewBox 🌈 🌈'); var output = document.createElement('div'); try { hyperHTML.bind(output)`<svg viewBox=${'0 0 50 50'}></svg>`; tressa.assert(output.firstChild.getAttribute('viewBox') == '0 0 50 50', 'correct camelCase attribute'); } catch(o_O) { tressa.assert(true, 'code coverage caveat'); } }) .then(function () { tressa.log('## A-Frame compatibility'); var output = hyperHTML.wire()`<a-scene></a-scene>`; tressa.assert(output.nodeName.toLowerCase() === 'a-scene', 'correct element'); }) // */ .then(function () { if (!tressa.exitCode) { document.body.style.backgroundColor = '#0FA'; } tressa.end(); });
var DND_START_EVENT = 'dnd-start', DND_END_EVENT = 'dnd-end', DND_DRAG_EVENT = 'dnd-drag'; angular .module( 'app' ) .config( [ 'iScrollServiceProvider', function(iScrollServiceProvider){ iScrollServiceProvider.configureDefaults({ iScroll: { momentum: false, mouseWheel: true, disableMouse: false, useTransform: true, scrollbars: true, interactiveScrollbars: true, resizeScrollbars: false, probeType: 2, preventDefault: false // preventDefaultException: { // tagName: /^.*$/ // } }, directive: { asyncRefreshDelay: 0, refreshInterval: false } }); } ] ) .controller( 'main', function( $scope, draggingIndicator, iScrollService ){ 'use strict'; this.iScrollState = iScrollService.state; var DND_SCROLL_IGNORED_HEIGHT = 20, // ignoring 20px touch-scroll, // TODO: this might be stored somewhere in browser env DND_ACTIVATION_TIMEOUT = 500, // milliseconds needed to touch-activate d-n-d MOUSE_OVER_EVENT = 'mousemove'; var self = this, items = [], touchTimerId; $scope.dragging = draggingIndicator; for( var i = 0; i< 25; i++ ){ items.push( i ); } $scope.items = items; this.disable = function ( ){ $scope.iScrollInstance.disable(); }; this.log = function ( msg ){ console.log( 'got msg', msg ); }; } );
'use strict' let _ = require('lodash') let HttpClient = require('./http-client') /** * Server configuration and environment information * @extends {HttpClient} */ class Config extends HttpClient { /** * @constructs Config * @param {Object} options General configuration options * @param {Object} options.http configurations for HttpClient */ constructor (options) { super(options.http) } /** * Return the whole server information * @return {Promise} A promise that resolves to the server information */ server () { return this._httpRequest('GET') .then((response) => response.metadata) } /** * Retrieve the server configuration * @return {Promise} A promise that resolves to the server configuration */ get () { return this.server() .then((server) => server.config) } /** * Unset parameters from server configuration * @param {...String} arguments A list parameters that you want to unset * @return {Promise} A promise that resolves when the config has been unset */ unset () { return this.get() .then((config) => _.omit(config, _.flatten(Array.from(arguments)))) .then((config) => this.update(config)) } /** * Set one or more configurations in the server * @param {Object} data A plain object containing the configuration you want * to insert or update in the server * @return {Pomise} A promise that resolves when the config has been set */ set (data) { return this.get() .then((config) => _.merge(config, data)) .then((config) => this.update(config)) } /** * Replaces the whole server configuration for the one provided * @param {Object} data The new server configuration * @return {Promise} A promise that resolves when the configuration has been * replaces */ update (data) { return this._httpRequest('PUT', { config: data }) } } module.exports = Config
import $ from 'jquery'; import { router } from 'src/router'; import './header.scss'; export default class Header { static selectors = { button: '.header__enter', search: '.header__search' }; constructor($root) { this.elements = { $root, $window: $(window) }; this.attachEvents(); } attachEvents() { this.elements.$root.on('click', Header.selectors.button, this.handleClick) } handleClick = () => { const search = $(Header.selectors.search).val(); if (search) { router.navigate(`/search?query=${search}`); } } }
"use strict"; describe("This package", function(){ it("rubs the lotion on its skin, or else", function(){ 2..should.equal(2); // In this universe, it'd damn well better }); it("gets the hose again", function(){ this.should.be.extensible.and.ok; // Eventually }); it("should not fail", function(){ NaN.should.not.equal(NaN); // NaH global.foo = "Foo"; }); it("might be written later"); // Nah it("should fail", function(){ const A = { alpha: "A", beta: "B", gamma: "E", delta: "D", }; const B = { Alpha: "A", beta: "B", gamma: "E", delta: "d", }; A.should.equal(B); }); describe("Suite nesting", function(){ it("does something useful eventually", function(done){ setTimeout(() => done(), 40); }); it("cleans anonymous async functions", async function(){ if(true){ true.should.be.true; } }); it("cleans anonymous generators", function * (){ if(true){ true.should.be.true; } }); it("cleans named async functions", async function foo() { if(true){ true.should.be.true; } }); it("cleans named generators", function * foo (){ if(true){ true.should.be.true; } }); it("cleans async arrow functions", async () => { if(true){ true.should.be.true; } }); }); }); describe("Second suite at top-level", function(){ it("shows another block", function(){ Chai.expect(Date).to.be.an.instanceOf(Function); }); it("breaks something", function(){ something(); }); it("loads locally-required files", () => { expect(global.someGlobalThing).to.equal("fooXYZ"); }); unlessOnWindows.it("enjoys real symbolic links", () => { "Any Unix-like system".should.be.ok; }); }); describe("Aborted tests", () => { before(() => {throw new Error("Nah, not really")}); it("won't reach this", () => true.should.not.be.false); it.skip("won't reach this either", () => true.should.be.true); });
'use strict'; var yeoman = require('yeoman-generator'), chalk = require('chalk'), yosay = require('yosay'), bakery = require('../../lib/bakery'), feedback = require('../../lib/feedback'), debug = require('debug')('bakery:generators:cm-bash:index'), glob = require('glob'), path = require('path'), _ = require('lodash'); // placeholder for CM implementaiton delivering a BASH-based project. var BakeryCM = yeoman.Base.extend({ constructor: function () { yeoman.Base.apply(this, arguments); this._options.help.desc = 'Show this help'; this.argument('projectname', { type: String, required: this.config.get('projectname') == undefined }); }, // generators are invalid without at least one method to run during lifecycle default: function () { /* TAKE NOTE: these next two lines are fallout of having to include ALL sub-generators in .composeWith(...) at the top level. Essentially ALL SUBGENERATORS RUN ALL THE TIME. So we have to escape from generators we don't want running within EVERY lifecycle method. (ugh) */ let cmInfo = this.config.get('cm'); if (cmInfo.generatorName != 'cm-bash') { return; } } }); module.exports = BakeryCM;
/*\ |*| |*| :: cookies.js :: |*| |*| A complete cookies reader/writer framework with full unicode support. |*| |*| Revision #1 - September 4, 2014 |*| |*| https://developer.mozilla.org/en-US/docs/Web/API/document.cookie |*| https://developer.mozilla.org/User:fusionchess |*| |*| This framework is released under the GNU Public License, version 3 or later. |*| http://www.gnu.org/licenses/gpl-3.0-standalone.html |*| |*| Syntaxes: |*| |*| * docCookies.setItem(name, value[, end[, path[, domain[, secure]]]]) |*| * docCookies.getItem(name) |*| * docCookies.removeItem(name[, path[, domain]]) |*| * docCookies.hasItem(name) |*| * docCookies.keys() |*| \*/ export default { getItem: function (sKey) { if (!sKey) { return null; } return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null; }, setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) { if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false; } var sExpires = ""; if (vEnd) { switch (vEnd.constructor) { case Number: sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd; break; case String: sExpires = "; expires=" + vEnd; break; case Date: sExpires = "; expires=" + vEnd.toUTCString(); break; } } document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : ""); return true; }, removeItem: function (sKey, sPath, sDomain) { if (!this.hasItem(sKey)) { return false; } document.cookie = encodeURIComponent(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : ""); return true; }, hasItem: function (sKey) { if (!sKey) { return false; } return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie); }, keys: function () { var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/); for (var nLen = aKeys.length, nIdx = 0; nIdx < nLen; nIdx++) { aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]); } return aKeys; } };
'use strict'; // Proxy URL (optional) const proxyUrl = 'drupal.dev'; // API keys const TINYPNG_KEY = ''; // fonts const fontList = []; // vendors const jsVendorList = []; const cssVendorList = []; // paths to relevant directories const dirs = { src: './src', dest: './dist' }; // paths to file sources const sources = { js: `${dirs.src}/**/*.js`, scss: `${dirs.src}/**/*.scss`, coreScss: `${dirs.src}/scss/main.scss`, img: `./img/**/*.{png,jpg}`, font: fontList, jsVendor: jsVendorList, cssVendor: cssVendorList }; // paths to file destinations const dests = { js: `${dirs.dest}/js`, css: `${dirs.dest}/css`, img: `${dirs.dest}/img`, sigFile: `./img/.tinypng-sigs`, font: `${dirs.dest}/fonts`, vendor: `${dirs.dest}/vendors` }; // plugins import gulp from 'gulp'; import browserSync from 'browser-sync'; import gulpLoadPlugins from 'gulp-load-plugins'; // auto-load plugins const $ = gulpLoadPlugins(); /**************************************** Gulp Tasks *****************************************/ // launch browser sync as a standalone local server gulp.task('browser-sync-local', browserSyncLocal()); // browser-sync task for starting the server by proxying a local url gulp.task('browser-sync-proxy', browserSyncProxy()); // copy vendor CSS gulp.task('css-vendors', cssVendors()); // copy fonts gulp.task('fonts', fonts()); // Lint Javascript Task gulp.task('js-lint', javascriptLint()); // Concatenate and Minify Vendor JS gulp.task('js-vendors', javascriptVendors()); // lint sass task gulp.task('sass-lint', sassLint()); // Concatenate & Minify JS gulp.task('scripts', ['js-lint'], scripts()); // compile, prefix, and minify the sass gulp.task('styles', styles()); // compress and combine svg icons gulp.task('svg', svg()); // Unit testing gulp.task('test', test()); // compress png and jpg images via tinypng API gulp.task('tinypng', tinypng()); // Watch Files For Changes gulp.task('watch', watch()); // default task builds src, opens up a standalone server, and watches for changes gulp.task('default', [ 'fonts', 'styles', 'scripts', 'browser-sync-local', 'watch' ]); // local task builds src, opens up a standalone server, and watches for changes gulp.task('local', [ 'fonts', 'styles', 'scripts', 'browser-sync-local', 'watch' ]); // proxy task builds src, opens up a proxy server, and watches for changes gulp.task('proxy', [ 'fonts', 'styles', 'scripts', 'browser-sync-proxy', 'watch' ]); // builds everything gulp.task('build', [ 'fonts', 'styles', 'scripts', 'css-vendors', 'js-vendors' ]); // builds the vendor files gulp.task('vendors', [ 'css-vendors', 'js-vendors' ]); // compresses imagery gulp.task('images', [ 'svg', 'tinypng' ]); /**************************************** Task Logic *****************************************/ function browserSyncLocal () { return () => { browserSync.init({ server: '../../../../' }); }; } function browserSyncProxy () { return () => { browserSync.init({ proxy: proxyUrl }); }; } function cssVendors () { return () => { return gulp.src(sources.cssVendor) .pipe(gulp.dest(dests.vendor)); }; } function fonts () { return () => { gulp.src(sources.font) .pipe(gulp.dest(dests.font)); }; } function javascriptLint () { return () => { return gulp.src(sources.js) .pipe($.jshint({esversion: 6})) .pipe($.jshint.reporter('jshint-stylish')); }; } function javascriptVendors () { return () => { return gulp.src(sources.jsVendor) .pipe($.plumber()) .pipe($.concat('vendors.min.js')) .pipe($.uglify()) .pipe(gulp.dest(dests.vendor)); }; } function sassLint () { return () => { return gulp.src(sources.scss) .pipe($.sassLint()) .pipe($.sassLint.format()) .pipe($.sassLint.failOnError()); }; } function scripts () { return () => { return gulp.src(sources.js) .pipe($.plumber()) .pipe($.sourcemaps.init()) .pipe($.concat('main.js')) .pipe($.babel()) .pipe(gulp.dest(dests.js)) .pipe($.rename({suffix: '.min'})) .pipe($.uglify()) .pipe($.sourcemaps.write('.')) .pipe(gulp.dest(dests.js)) .pipe(browserSync.stream()); }; } function styles () { return () => { return gulp.src(sources.coreScss) .pipe($.sourcemaps.init()) .pipe($.sass().on('error', $.sass.logError)) .pipe($.autoprefixer(["> 1%", "last 2 versions"], { cascade: true })) .pipe(gulp.dest(dests.css)) .pipe($.rename({suffix: '.min'})) .pipe($.cleanCss()) .pipe($.sourcemaps.write('.')) .pipe(gulp.dest(dests.css)) .pipe(browserSync.stream()); }; } function svg () { return () => { return gulp.src('./img/icons/*.svg') .pipe($.svgmin()) .pipe($.svgstore()) .pipe(gulp.dest('./img/icons')); }; } function test (done) { return () => { let server = new karma.Server('./karma.conf.js', done); server.start(); }; } function tinypng () { return () => { return gulp.src(sources.img) .pipe($.tinypngCompress({ key: TINYPNG_KEY, sigFile: dests.sigFile })) .pipe(gulp.dest(dests.img)); }; } function watch () { return () => { gulp.watch(sources.js, ['scripts']); gulp.watch(sources.scss, ['styles']); gulp.watch('**/*.php', browserSync.reload); }; }
'use strict'; const debug = require('debug')('WechatController'); const EventEmitter = require('events').EventEmitter; const Cache = require('../../service/Cache'); const Wechat = require('../../service/Wechat'); const config = require('../../config'); const _ = require('lodash'); const async = require('async'); /* 微信公众平台连接认证 */ exports.wechatValidation = function (req, res, next) { let signature = req.query.signature; let timestamp = req.query.timestamp; let nonce = req.query.nonce; let echostr = req.query.echostr; let flag = Wechat.validateSignature(signature, timestamp, nonce); if (flag) return res.send(echostr); else return res.send({success: false}); }; /* 更新access token */ exports.updateAccessToken = function (req, res, next) { Wechat.updateAccessToken(); res.send('updateAccessToken'); }; /* 接收来自微信的消息推送 */ exports.processWechatEvent = function (req, res, next) { let content = req.body.xml; console.log('Event received. Event: %s', JSON.stringify(content)); res.send('success'); if(!content) return; try { let fromOpenId = content.FromUserName[0], toOpenId = content.ToUserName[0], createTime = content.CreateTime[0], event = content.Event ? content.Event[0] : "", eventKey = content.EventKey ? content.EventKey[0] : "", msgType = content.MsgType[0], msgId = content.MsgID ? content.MsgID[0] : "", status = content.Status ? content.Status[0] : "", ticket = content.Ticket ? content.Ticket[0] : null; if(msgType === 'event') { const WechatEvent = req.app.db.models.WechatEvent; let wechatEvent = new WechatEvent({ event: content }); wechatEvent.save((err) => { if(err) console.error(err, err.stack); handleEvent(req, res, fromOpenId, event, eventKey, msgId, status, ticket); }); } } catch(e) { console.error(e, e.stack); } }; function handleEvent(req, res, openId, name, key, msgId, status, ticket) { const Subscriber = req.app.db.models.Subscriber; const InvitationCard = req.app.db.models.InvitationCard; name = String(name).toLowerCase(); if(name === 'scan') { if(ticket) { InvitationCard.findOne({ qrTicket: ticket }).populate('invitationTask').exec((err, cardDoc) => { if(err) return console.error(err); if(cardDoc && cardDoc.invitationTask.status === 'OPEN') { if(cardDoc.openId === openId) { return Wechat.sendText(openId, "你不能扫描自己的任务卡"); } else { Subscriber.findOne({ openId, subscribe: true }).exec((err, subscriberDoc) => { if(err) return console.error(err); if(subscriberDoc) return Wechat.sendText(openId, "你已经关注,不能被邀请"); }); } } }); } } if(name === 'click') { if(key.indexOf('invitationTask') === 0) { let taskId = key.split('-')[1]; require('../../service/InvitationCard').sendCard(openId, taskId); } if(key.indexOf('message') === 0) { let replyQueueId = key.split('-')[1]; let ReplyQueue = req.app.db.models.ReplyQueue; let ReplyQueueLog = req.app.db.models.ReplyQueueLog; function sendMessages(messageGroup) { async.eachSeries(messageGroup, function(message, callback) { if(message.type === 'text') { return Wechat.sendText(openId, message.content).then((data) => { setTimeout(callback, 1000); }).catch(callback); } if(message.type === 'image') { return Wechat.sendImage(openId, message.mediaId).then((data) => { setTimeout(callback, 5000); }).catch(callback); } }, function(err) { err && console.log(err); }); } ReplyQueueLog.findOne({ openId, replyQueue: replyQueueId}).exec((err, log) => { if(log) { let nextIndex = log.clickCount; if(nextIndex > log.messageGroupsSnapshot.length-1) { nextIndex = log.messageGroupsSnapshot.length-1; } else { ReplyQueueLog.findByIdAndUpdate(log._id, { clickCount: nextIndex + 1 }, { new: true }).exec(); } sendMessages(log.messageGroupsSnapshot[nextIndex]) } else { ReplyQueue.findById(replyQueueId).exec((err, replyQueue) => { new ReplyQueueLog({ openId: openId, replyQueue: replyQueueId, messageGroupsSnapshot: replyQueue.messageGroups, clickCount: 1 }).save(); sendMessages(replyQueue.messageGroups[0]); }); } }); } } if(name === 'subscribe') { const workflow = new EventEmitter(); let introducer = null; let card = null; // 检查扫码标记 workflow.on('checkTicket', () => { debug('Event: checkTicket'); if(ticket) return workflow.emit('findNewUser'); // 在数据库中寻找该"新"用户 return workflow.emit('getSubscriberInfo'); // 获得"新"用户详情 }); // 在数据库中寻找该用户 workflow.on('findNewUser', () => { debug('Event: findNewUser'); Subscriber.findOne({ openId }).exec((err, doc) => { if(err) return workflow.emit('error', err); // 错误 if(!doc) return workflow.emit('getTaskAndCard'); // 查找邀请卡和任务配置 InvitationCard.findOne({ openId, qrTicket: ticket }).exec((err, selfScanedCardDoc) => { if(err) return workflow.emit('error', err); // 错误 if(selfScanedCardDoc) return Wechat.sendText(openId, "你不能扫描自己的任务卡"); if(doc.subscribe) return Wechat.sendText(openId, "你已经关注,不能被邀请"); Wechat.sendText(openId, "你已经被邀请过,不能被再次邀请"); }); return workflow.emit('getSubscriberInfo'); // 获得"新"用户详情 }); }); workflow.on('getTaskAndCard', () => { debug('Event: getTaskAndCard'); InvitationCard.findOne({ qrTicket: ticket }).populate('invitationTask').exec((err, cardDoc) => { if(err) return workflow.emit('error', err); // 错误 if(!cardDoc) return workflow.emit('getSubscriberInfo'); // 没有此邀请卡,获得"新"用户详情 if(!cardDoc.invitationTask) return workflow.emit('getSubscriberInfo'); // 邀请卡任务不存在,获得"新"用户详情 if(cardDoc.invitationTask.status !== 'OPEN') return workflow.emit('getSubscriberInfo'); // 邀请卡任务已关闭,获得"新"用户详情 card = cardDoc.toJSON(); Subscriber.findOne({ openId: cardDoc.openId }).exec((err, introducerDoc) => { if(err) return workflow.emit('error', err); // 错误 if(!introducerDoc) return workflow.emit('getSubscriberInfo'); // 没有此邀请人,获得"新"用户详情 introducer = introducerDoc.toJSON(); return workflow.emit('invitedCountPlus'); // 增加邀请量 }); }); }); workflow.on('invitedCountPlus', () => { debug('Event: invitedCountPlus'); InvitationCard.findOneAndUpdate({ qrTicket: ticket }, { $inc: { invitedCount: 1 }}, function(err, doc) { if(err) return workflow.emit('error', err); // 错误 console.log(`[WechatController] Add Invitation: ${ticket}`); workflow.emit('getSubscriberInfo'); }); }); workflow.on('getSubscriberInfo', () => { debug('Event: getSubscriberInfo'); Wechat.getSubscriberInfo(openId).then((info) => { let newData = { openId: info.openid, groupId: info.groupid, unionId: info.unionid, subscribe: info.subscribe ? true : false, subscribeTime: new Date(info.subscribe_time * 1000), nickname: info.nickname, remark: info.remark, gender: info.sex, headImgUrl: info.headimgurl, city: info.city, province: info.province, country: info.country, language: info.language }; if(introducer) { newData.introducer = introducer._id; if(card.invitationTask.invitedFeedback) { let invitedCount = card.invitedCount + 1; let remainCount = card.invitationTask.threshold - invitedCount; let invitedFeedback = card.invitationTask.invitedFeedback; if(remainCount > 0) { invitedFeedback = invitedFeedback.replace(/###/g, info.nickname) invitedFeedback = invitedFeedback.replace(/#invited#/g, invitedCount + ''); invitedFeedback = invitedFeedback.replace(/#remain#/g, remainCount + '') Wechat.sendText(introducer.openId, invitedFeedback); } } } Subscriber.findOneAndUpdate({ openId }, newData, { upsert: true }, function(err, doc){ if(err) return workflow.emit('error', err); // 错误 console.log(`[WechatController] New Subscriber: ${openId}`); }); }).catch((err) => { if(err) return workflow.emit('error', err); // 错误 }) }); // 错误 workflow.on('error', (err, wechatMessage) => { debug('Event: error'); if(err) { console.error(err, err.stack); } else { console.error('Undefined Error Event'); } }); workflow.emit('checkTicket'); } if(name === 'unsubscribe') { let Subscriber = req.app.db.models.Subscriber; let newData = { subscribe: false }; Subscriber.findOneAndUpdate({ openId }, newData, { upsert: true }, function(err, doc){ if (err) return console.error(err); console.log(`[WechatController] Unsubscribe: ${openId}`); }); } if(name === 'templatesendjobfinish') { let TemplateSendLog = req.app.db.models.TemplateSendLog; status = _.upperFirst(status); TemplateSendLog.findOneAndUpdate({ msgId: msgId }, { status : status }, function(err, doc){ if (err) return console.log(err); console.log(`[WechatController] TEMPLATESENDJOBFINISH: ${msgId}`); }); } }
// get the languange parameter in the URL (i for case insensitive; //exec for test for a match in a string and return thr first match) function getURLParameter(key) { var result = new RegExp(key + '=([^&]*)', 'i').exec(window.location.search); return result && result[1] || ''; } // function toggleLang(lang) { var lang = lang || 'de'; document.location = document.location.pathname + '?lang=' + lang; } // set UR var lang = getURLParameter('lang') || 'de'; $('#lang').ready(function() { $('#lang li').each(function() { var li = $(this)[0]; if (li.id == lang) $(this).addClass('selected'); }); });
'use strict'; var _get = require('babel-runtime/helpers/get')['default']; var _inherits = require('babel-runtime/helpers/inherits')['default']; var _createClass = require('babel-runtime/helpers/create-class')['default']; var _classCallCheck = require('babel-runtime/helpers/class-call-check')['default']; var _extends = require('babel-runtime/helpers/extends')['default']; var _interopRequireDefault = require('babel-runtime/helpers/interop-require-default')['default']; Object.defineProperty(exports, '__esModule', { value: true }); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _EnhancedSwitch = require('./EnhancedSwitch'); var _EnhancedSwitch2 = _interopRequireDefault(_EnhancedSwitch); var Radio = (function (_React$Component) { _inherits(Radio, _React$Component); function Radio() { _classCallCheck(this, Radio); _get(Object.getPrototypeOf(Radio.prototype), 'constructor', this).apply(this, arguments); } _createClass(Radio, [{ key: 'getValue', value: function getValue() { return this.refs.enhancedSwitch.getValue(); } }, { key: 'setChecked', value: function setChecked(newCheckedValue) { this.refs.enhancedSwitch.setSwitched(newCheckedValue); } }, { key: 'isChecked', value: function isChecked() { return this.refs.enhancedSwitch.isSwitched(); } }, { key: 'render', value: function render() { var enhancedSwitchProps = { ref: 'enhancedSwitch', inputType: 'radio' }; // labelClassName return _react2['default'].createElement(_EnhancedSwitch2['default'], _extends({}, this.props, enhancedSwitchProps)); } }]); return Radio; })(_react2['default'].Component); exports['default'] = Radio; module.exports = exports['default'];
!(function(root) { function Grapnel(opts) { "use strict"; var self = this; // Scope reference this.events = {}; // Event Listeners this.state = null; // Router state object this.options = opts || {}; // Options this.options.env = this.options.env || (!!(Object.keys(root).length === 0 && process && process.browser !== true) ? 'server' : 'client'); this.options.mode = this.options.mode || (!!(this.options.env !== 'server' && this.options.pushState && root.history && root.history.pushState) ? 'pushState' : 'hashchange'); this.version = '0.6.4'; // Version if ('function' === typeof root.addEventListener) { root.addEventListener('hashchange', function() { self.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 (self.state && self.state.previousState === null) return false; self.trigger('navigate'); }); } return this; }; /** * 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 an route and handler * * @param {String|RegExp} route name * @return {self} Router */ Grapnel.prototype.get = Grapnel.prototype.add = function(route) { var self = this, middleware = Array.prototype.slice.call(arguments, 1, -1), handler = Array.prototype.slice.call(arguments, -1)[0], request = new Request(route); var invoke = function RouteHandler() { // Build request parameters var req = request.parse(self.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(self, extra).enqueue(middleware.concat(handler)); // Trigger main event self.trigger('match', stack, req); // Continue? if (!stack.runCallback) return self; // Previous state becomes current state stack.previousState = self.state; // Save new state self.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 self; } // Call handler stack.callback(); } // Returns self return self; }; // Event name var eventName = (self.options.mode !== 'pushState' && self.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 {self} Router */ Grapnel.prototype.trigger = function(event) { var self = this, params = Array.prototype.slice.call(arguments, 1); // Call matching events if (this.events[event]) { Grapnel._forEach(this.events[event], function(fn) { fn.apply(self, 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 {self} Router */ Grapnel.prototype.on = Grapnel.prototype.bind = function(event, handler) { var self = this, events = event.split(' '); Grapnel._forEach(events, function(event) { if (self.events[event]) { self.events[event].push(handler); } else { self.events[event] = [handler]; } }); return this; }; /** * Allow event to be called only once * * @param {String} event name(s) * @param {Function} callback * @return {self} 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 self = 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 self.add.apply(self, [pattern].concat(middleware).concat(submiddleware).concat([handler])); } }; /** * Navigate through history API * * @param {String} Pathname * @return {self} Router */ Grapnel.prototype.navigate = function(path) { return this.path(path).trigger('navigate'); }; Grapnel.prototype.path = function(pathname) { var self = this, frag; if ('string' === typeof pathname) { // Set path if (self.options.mode === 'pushState') { frag = (self.options.root) ? (self.options.root + pathname) : pathname; root.history.pushState({}, null, frag); } else if (root.location) { root.location.hash = (self.options.hashBang ? '!' : '') + pathname; } else { root._pathname = pathname || ''; } return this; } else if ('undefined' === typeof pathname) { // Get path if (self.options.mode === 'pushState') { frag = root.location.pathname.replace(self.options.root, ''); } else if (self.options.mode !== 'pushState' && root.location) { frag = (root.location.hash) ? root.location.hash.split((self.options.hashBang ? '#!' : '#'))[1] : ''; } else { frag = root._pathname || ''; } return frag; } else if (pathname === false) { // Clear path if (self.options.mode === 'pushState') { root.history.pushState({}, null, self.options.root || '/'); } else if (root.location) { root.location.hash = (self.options.hashBang) ? '!' : ''; } return self; } }; /** * Create routes based on an object * * @param {Object} [Options, Routes] * @param {Object Routes} * @return {self} 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 {self} 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 {self} 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 {self} CallStack */ CallStack.prototype.preventDefault = function() { this.runCallback = false; }; /** * Prevent any future callbacks from being called * * @return {self} 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 {self} 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 {self} 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 {self} CallStack */ CallStack.prototype.next = function() { var self = this; return this.stack.shift().call(this.router, this.req, this, function next() { self.next.call(self); }); }; /** * 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), self = this; var req = { params: {}, keys: this.keys, matches: (match || []).slice(1), match: match }; // Build parameters Grapnel._forEach(req.matches, function(value, i) { var key = (self.keys[i] && self.keys[i].name) ? self.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 ('function' === typeof root.define && !root.define.amd.grapnel) { root.define(function(require, exports, module) { root.define.amd.grapnel = true; return Grapnel; }); } else if ('object' === typeof module && 'object' === typeof module.exports) { module.exports = exports = Grapnel; } else { root.Grapnel = Grapnel; } }).call({}, ('object' === typeof window) ? window : this); /* var router = new Grapnel({ pushState : true, hashBang : true }); router.get('/products/:category/:id?', function(req){ var id = req.params.id, category = req.params.category console.log(category, id); }); router.get('/tiempo', function(req){ console.log("tiempo!"); $("#matikbirdpath").load("views/rooms.html", function(res){ console.log(res); console.log("hola"); }); }); router.get('/', function(req){ console.log(req.user); console.log("hola!"); $("#matikbirdpath").load("views/rooms.html", function(res){ console.log(res); console.log("hola"); }); }); router.navigate('/'); */ NProgress.start(); var routes = { '/' : function(req, e){ $("#matikbirdpath").load("views/main.html", function(res){ console.log(res); NProgress.done(); }); }, '/dashboard' : function(req, e){ $("#matikbirdpath").load("views/dashboard.html", function(res){ console.log(res); NProgress.done(); }); }, '/calendario' : function(req, e){ $("#matikbirdpath").load("views/calendario.html", function(res){ console.log(res); console.log("hola"); }); }, '/now' : function(req, e){ $("#matikbirdpath").load("views/clase_ahora.html", function(res){ console.log(res); console.log("hola"); }); }, '/category/:id' : function(req, e){ // Handle route }, '/*' : function(req, e){ if(!e.parent()){ $("#matikbirdpath").load("views/main.html", function(res){ console.log(res); NProgress.done(); }); } } } var router = Grapnel.listen({ pushState : true, hashBang: true }, routes);
class Foo { [prop1]: string; }
(function () { "use strict"; angular.module('projectManagerSPA').controller('userLoginController', ['authenticationService', '$scope', '$state',function (authenticationService, $scope, $state) { $scope.logIn = function () { authenticationService.logIn($scope.username, $scope.password, function () { $state.go('organizationList'); }); }; $scope.logOut = function () { $state.go('userLogout'); }; }]); })();
var map; var infoWindow; // A variável markersData guarda a informação necessária a cada marcador // Para utilizar este código basta alterar a informação contida nesta variável var markersData = [ { lat: -3.741262, lng: -38.539389, nome: "Campus do Pici - Universidade Federal do Ceará", endereco:"Av. Mister Hull, s/n", telefone: "(85) 3366-9500" // não colocar virgula no último item de cada maracdor }, { lat: -3.780833, lng: -38.469656, nome: "Colosso Lake Lounge", endereco:"Rua Hermenegildo Sá Cavalcante, s/n", telefone: "(85) 98160-0088" // não colocar virgula no último item de cada maracdor } // não colocar vírgula no último marcador ]; function initialize() { var mapOptions = { center: new google.maps.LatLng(40.601203,-8.668173), zoom: 9, mapTypeId: 'roadmap', }; map = new google.maps.Map(document.getElementById('map-slackline'), mapOptions); // cria a nova Info Window com referência à variável infowindow // o conteúdo da Info Window será atribuído mais tarde infoWindow = new google.maps.InfoWindow(); // evento que fecha a infoWindow com click no mapa google.maps.event.addListener(map, 'click', function() { infoWindow.close(); }); // Chamada para a função que vai percorrer a informação // contida na variável markersData e criar os marcadores a mostrar no mapa displayMarkers(); } google.maps.event.addDomListener(window, 'load', initialize); // Esta função vai percorrer a informação contida na variável markersData // e cria os marcadores através da função createMarker function displayMarkers(){ // esta variável vai definir a área de mapa a abranger e o nível do zoom // de acordo com as posições dos marcadores var bounds = new google.maps.LatLngBounds(); // Loop que vai estruturar a informação contida em markersData // para que a função createMarker possa criar os marcadores for (var i = 0; i < markersData.length; i++){ var latlng = new google.maps.LatLng(markersData[i].lat, markersData[i].lng); var nome = markersData[i].nome; var endereco = markersData[i].endereco; var telefone = markersData[i].telefone; createMarker(latlng, nome, endereco, telefone); // Os valores de latitude e longitude do marcador são adicionados à // variável bounds bounds.extend(latlng); } // Depois de criados todos os marcadores // a API através da sua função fitBounds vai redefinir o nível do zoom // e consequentemente a área do mapa abrangida. map.fitBounds(bounds); } // Função que cria os marcadores e define o conteúdo de cada Info Window. function createMarker(latlng, nome, endereco, telefone){ var marker = new google.maps.Marker({ map: map, position: latlng, title: nome }); // Evento que dá instrução à API para estar alerta ao click no marcador. // Define o conteúdo e abre a Info Window. google.maps.event.addListener(marker, 'click', function() { // Variável que define a estrutura do HTML a inserir na Info Window. var iwContent = '<div id="iw_container">' + '<div class="iw_title">' + nome + '</div>' + '<div class="iw_content">' + endereco + '<br />' + telefone + '<br />'; // O conteúdo da variável iwContent é inserido na Info Window. infoWindow.setContent(iwContent); // A Info Window é aberta. infoWindow.open(map, marker); }); }
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = _default; function _default() { return function ({ addUtilities, variants }) { addUtilities({ '.bg-clip-border': { 'background-clip': 'border-box' }, '.bg-clip-padding': { 'background-clip': 'padding-box' }, '.bg-clip-content': { 'background-clip': 'content-box' }, '.bg-clip-text': { 'background-clip': 'text' } }, variants('backgroundClip')); }; }
var gulp = require('gulp'); var karma = require('karma').server; var concat = require('gulp-concat'); var uglify = require('gulp-uglify'); var rename = require('gulp-rename'); var path = require('path'); var plumber = require('gulp-plumber'); var runSequence = require('run-sequence'); var jshint = require('gulp-jshint'); /** * File patterns **/ // Root directory var rootDirectory = path.resolve('./'); // Source directory for build process var sourceDirectory = path.join(rootDirectory, './src'); var sourceFiles = [ // Make sure module files are handled first path.join(sourceDirectory, '/**/*.module.js'), // Then add all JavaScript files path.join(sourceDirectory, '/**/*.js') ]; var lintFiles = [ 'gulpfile.js', // Karma configuration 'karma-*.conf.js' ].concat(sourceFiles); gulp.task('build', function() { gulp.src(sourceFiles) .pipe(plumber()) .pipe(concat('df-validator.js')) .pipe(gulp.dest('./dist/')) .pipe(uglify()) .pipe(rename('df-validator.min.js')) .pipe(gulp.dest('./dist')); }); /** * Process */ gulp.task('process-all', function (done) { runSequence(/*'jshint',*/ 'test-src', 'build', done); }); /** * Watch task */ gulp.task('watch', function () { // Watch JavaScript files gulp.watch(sourceFiles, ['process-all']); }); /** * Validate source JavaScript */ gulp.task('jshint', function () { return gulp.src(lintFiles) .pipe(plumber()) .pipe(jshint()) .pipe(jshint.reporter('jshint-stylish')) .pipe(jshint.reporter('fail')); }); /** * Run test once and exit */ gulp.task('test-src', function (done) { karma.start({ configFile: __dirname + '/karma-src.conf.js', singleRun: true }, done); }); /** * Run test once and exit */ gulp.task('test-dist-concatenated', function (done) { karma.start({ configFile: __dirname + '/karma-dist-concatenated.conf.js', singleRun: true }, done); }); /** * Run test once and exit */ gulp.task('test-dist-minified', function (done) { karma.start({ configFile: __dirname + '/karma-dist-minified.conf.js', singleRun: true }, done); }); gulp.task('default', function () { runSequence('process-all', 'watch'); });
/** * Created by quanpower on 14-8-20. */ var config = require('./../config'); var redis = require('./redis'); var _ = require('lodash'); function cacheDevice(device){ if(device){ var cloned = _.clone(device); redis.set('DEVICE_' + device.uuid, JSON.stringify(cloned),function(){ //console.log('cached', uuid); }); } } function noop(){} if(config.redis){ module.exports = cacheDevice; } else{ module.exports = noop; }
/** * morningstar-base-charts * * Copyright © 2016 . All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import defaultClasses from "../config/classes.js"; import ChartBase from "./chartBase.js"; import { ChartUtils } from "../utils/utils.js"; /** * Horizontal Bar Chart Implementation * * @extends {ChartBase} */ class HorizontalBarChart extends ChartBase{ /** * Creates an instance of HorizontalBarChart. * * @param {any} options */ constructor(options) { super(options); } /** * @override */ render(options) { var axes = this.axes, yScale = axes.axis("y").scale(), xScale = axes.axis("x").scale(), data = this.data[0].values, chartArea = this.layer, barHeight = yScale.rangeBand(), barPadding = 6, hasNegative = ChartUtils.hasNegative(data), animation = (options && !options.animation) ? false : true;; var getClass = d => { if(hasNegative){ return d >= 0 ? "h-bar-positive" : "h-bar-negative"; } return "h-bar"; }; var draw = selection => { selection.attr("class", getClass) .attr("x", (d) => xScale(Math.min(0, d))) .attr("y", 6) .attr("transform", (d, i) => "translate(0," + i * barHeight + ")") .attr("width", d => animation ? 0 : Math.abs(xScale(d) - xScale(0)) ) .attr("height", barHeight - barPadding); return selection; }; var bar = chartArea.selectAll("rect").data(data); bar.call(draw) .enter().append("rect").call(draw); bar.exit().remove(); if (animation) { bar.transition().duration(300) .attr("width", d => Math.abs(xScale(d) - xScale(0))); } } /** * * * @param {any} index */ onMouseover(index) { this.canvas.svg.selectAll(`.${defaultClasses.CHART_GROUP}.${defaultClasses.FOCUS}-${index}`) .transition() .style("opacity", 0.5); } /** * * * @param {any} index */ onMouseout(index) { this.canvas.svg.selectAll(`.${defaultClasses.CHART_GROUP}.${defaultClasses.FOCUS}-${index}`) .transition() .style("opacity", 1); } /** * * * @param {any} data */ _formatData(data) { var xDomain = this.axes.axis("x").scale().domain(); this._categories = data.map(value => value.name); this.data = xDomain.map(function (series, i) { var item = { series }; item.values = data.map(value => { return { series: series, category: value.name, value: value.values[i], index: value.index }; }); return item; }); } } export default HorizontalBarChart;
/** * Copyright (c) 2014-2015, CKSource - Frederico Knabben. All rights reserved. * Licensed under the terms of the MIT License (see LICENSE.md). */ ( function( QUnit, bender ) { var total = 0, failed = 0, passed = 0, ignored = 0, errors = 0, result = { success: true, errors: [] }; // prevent QUnit from starting QUnit.config.autostart = false; bender.removeListener( window, 'load', QUnit.load ); function start() { QUnit.testStart( function() { total++; } ); QUnit.testDone( function( details ) { details.success = result.success; details.error = result.errors.length ? result.errors.join( '\n' ) : undefined; details.duration = details.runtime; details.fullName = details.module + ' ' + details.name; bender.result( details ); if ( details.success ) { if ( details.ignored ) { ignored++; } else { passed++; } } else { failed++; errors++; } result.success = true; result.errors = []; } ); QUnit.done( function( details ) { details.duration = details.runtime; bender.next( { coverage: window.__coverage__, duration: details.runtime, passed: passed, failed: failed, errors: errors, ignored: ignored, total: total } ); } ); QUnit.log( function( details ) { // add detailed error message to test result if ( !details.result ) { result.success = false; result.errors.push( [ details.message, 'Expected: ' + details.expected, 'Actual: ' + details.actual, details.source ].join( '\n' ) ); } } ); // manually start the runner QUnit.load(); QUnit.start(); } function stopRunner() { QUnit.stop(); } function isSingle( name ) { return name === decodeURIComponent( window.location.hash.substr( 1 ) ); } var oldTest = QUnit.test; QUnit.test = function( name ) { var module = this.config.currentModule, fullName = module ? module + ' ' + name : name; if ( window.location.hash && window.location.hash !== '#child' && !isSingle( fullName ) ) { return; } oldTest.apply( this, arguments ); }; window.assert = bender.assert = QUnit.assert; bender.runner = QUnit; bender.start = start; bender.stopRunner = stopRunner; } )( window.QUnit || {}, bender );
/** * This is a "mini-app" that encapsulates router definitions. See more * at: http://expressjs.com/guide/routing.html (search for "express.Router") * */ var router = require('express').Router({ mergeParams: true }); module.exports = router; // Don't just use, but also export in case another module needs to use these as well. router.callbacks = require('./controllers/hello'); router.models = require('./models'); //-- For increased module encapsulation, you could also serve templates with module-local //-- paths, but using shared layouts and partials may become tricky / impossible //var hbs = require('hbs'); //app.set('views', __dirname + '/views'); //app.set('view engine', 'handlebars'); //app.engine('handlebars', hbs.__express); // Module's Routes. Please note this is actually under /hello, because module is attached under /hello router.get('/', router.callbacks.sayHello);
import WebhookNotification, { LinkClick, LinkClickCount, MessageTrackingData, WebhookDelta, WebhookObjectAttributes, WebhookObjectData, } from '../src/models/webhook-notification'; import { WebhookTriggers } from '../src/models/webhook'; describe('Webhook Notification', () => { test('Should deserialize from JSON properly', done => { const webhookNotificationJSON = { deltas: [ { date: 1602623196, object: 'message', type: 'message.created', object_data: { namespace_id: 'aaz875kwuvxik6ku7pwkqp3ah', account_id: 'aaz875kwuvxik6ku7pwkqp3ah', object: 'message', attributes: { action: 'save_draft', job_status_id: 'abc1234', thread_id: '2u152dt4tnq9j61j8seg26ni6', received_date: 1602623166, }, id: '93mgpjynqqu5fohl2dvv6ray7', metadata: { sender_app_id: 64280, link_data: [ { url: 'https://nylas.com/', count: 1, }, ], timestamp: 1602623966, recents: [ { ip: '24.243.155.85', link_index: 0, id: 0, user_agent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36', timestamp: 1602623980, }, ], message_id: '4utnziee7bu2ohak56wfxe39p', payload: 'Tracking enabled', }, }, }, ], }; const webhookNotification = new WebhookNotification().fromJSON( webhookNotificationJSON ); expect(webhookNotification.deltas.length).toBe(1); const webhookDelta = webhookNotification.deltas[0]; expect(webhookDelta instanceof WebhookDelta).toBe(true); expect(webhookDelta.date).toEqual(new Date(1602623196 * 1000)); expect(webhookDelta.object).toEqual('message'); expect(webhookDelta.type).toEqual(WebhookTriggers.MessageCreated); const webhookDeltaObjectData = webhookDelta.objectData; expect(webhookDeltaObjectData instanceof WebhookObjectData).toBe(true); expect(webhookDeltaObjectData.id).toEqual('93mgpjynqqu5fohl2dvv6ray7'); expect(webhookDeltaObjectData.accountId).toEqual( 'aaz875kwuvxik6ku7pwkqp3ah' ); expect(webhookDeltaObjectData.namespaceId).toEqual( 'aaz875kwuvxik6ku7pwkqp3ah' ); expect(webhookDeltaObjectData.object).toEqual('message'); const webhookDeltaObjectAttributes = webhookDeltaObjectData.objectAttributes; expect( webhookDeltaObjectAttributes instanceof WebhookObjectAttributes ).toBe(true); expect(webhookDeltaObjectAttributes.action).toEqual('save_draft'); expect(webhookDeltaObjectAttributes.jobStatusId).toEqual('abc1234'); expect(webhookDeltaObjectAttributes.threadId).toEqual( '2u152dt4tnq9j61j8seg26ni6' ); expect(webhookDeltaObjectAttributes.receivedDate).toEqual( new Date(1602623166 * 1000) ); const webhookMessageTrackingData = webhookDeltaObjectData.metadata; expect(webhookMessageTrackingData instanceof MessageTrackingData).toBe( true ); expect(webhookMessageTrackingData.messageId).toEqual( '4utnziee7bu2ohak56wfxe39p' ); expect(webhookMessageTrackingData.payload).toEqual('Tracking enabled'); expect(webhookMessageTrackingData.timestamp).toEqual( new Date(1602623966 * 1000) ); expect(webhookMessageTrackingData.senderAppId).toBe(64280); expect(webhookMessageTrackingData.linkData.length).toBe(1); expect(webhookMessageTrackingData.recents.length).toBe(1); const linkData = webhookMessageTrackingData.linkData[0]; expect(linkData instanceof LinkClickCount).toBe(true); expect(linkData.url).toEqual('https://nylas.com/'); expect(linkData.count).toBe(1); const recents = webhookMessageTrackingData.recents[0]; expect(recents instanceof LinkClick).toBe(true); expect(recents.id).toBe(0); expect(recents.ip).toEqual('24.243.155.85'); expect(recents.userAgent).toEqual( 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36' ); expect(recents.timestamp).toEqual(new Date(1602623980 * 1000)); expect(recents.linkIndex).toBe(0); done(); }); });
import deepFreeze from 'deep-freeze'; import { arrayToMap, mapKeysToArray } from './mapUtils'; describe('arrayToMap', () => { it('should create map from 2D array', () => { const a = [ ['key1', 'value1'], ['key2', 'value2'] ]; deepFreeze(a); const result = arrayToMap(a); expect(result.size).toBe(2); expect(result.get('key1')).toBe('value1'); expect(result.get('key2')).toBe('value2'); }); it('should create empty map from empty array', () => { const result = arrayToMap([]); expect(result.size).toBe(0); }); }); describe('mapKeysToArray', () => { it('should create array from map keys in order', () => { const map = new Map(); map.set('a', 'value1'); map.set('c', 'value2'); map.set('1', 'value3'); map.set('b', 'value4'); map.set('2', 'value5'); const result = mapKeysToArray(map); expect(result).toEqual(['a', 'c', '1', 'b', '2']); }); it('should create empty array from new map', () => { const map = new Map(); const result = mapKeysToArray(map); expect(result).toEqual([]); }); });
require('./node') require('./console')
/* * Author: Brendan Le Foll <[email protected]> * Copyright (c) 2014 Intel Corporation. * * 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. */ var m = require("mraa") console.log("mraa version: " + m.getVersion()); var x = new m.Gpio(8) x.dir(m.DIR_OUT) x.write(1)
/*! fingoCarousel.js © heoyunjee, 2016 */ function(global, $){ 'use strict'; /** * width: carousel width * height: carousel height * margin: tabpanel margin * count: how many tabpanels will move when you click button * col: how many columns in carousel mask * row: how many rows in carousel mask * infinite: infinite carousel or not(true or false) * index: index of active tabpanel */ // Default Options var defaults = { 'width': 1240, 'height': 390, 'margin': 0, 'count': 1, 'col': 1, 'row': 1, 'infinite': false, 'index': 0 }; // Constructor Function var Carousel = function(widget, options) { // Public this.$widget = $(widget); this.settings = $.extend({}, defaults, options); this.carousel_infinite = false; this.carousel_row = 0; this.carousel_width = 0; this.carousel_height = 0; this.carousel_count = 0; this.carousel_col = 0; this.carousel_content_margin = 0; this.active_index = 0; this.carousel_one_tab = 0; this.carousel_content_width = 0; this.carousel_content_height= 0; this.$carousel = null; this.$carousel_headline = null; this.$carousel_tablist = null; this.$carousel_tabs = null; this.$carousel_button_group = null; this.$carousel_mask = null; this.$carousel_tabpanels = null; this.$carousel_tabpanel_imgs = null; this.$carousel_tabpanel_content_videos = null; this.start_tabpanel_index = 0; // 초기 설정 this.init(); // 이벤트 연결 this.events(); }; // Prototype Object Carousel.prototype = { 'init': function() { var $this = this; var $widget = this.$widget; // 캐러셀 내부 구성 요소 참조 this.$carousel = $widget; this.$carousel_headline = this.$carousel.children(':header:first'); this.$carousel_tablist = this.$carousel.children('ul').wrap('<div/>').parent(); this.$carousel_tabs = this.$carousel_tablist.find('a'); this.$carousel_tabpanels = this.$carousel.children().find('figure'); this.$carousel_content = this.$carousel_tabpanels.children().parent(); this.$carousel_tabpanel_imgs = this.$carousel.children().last().find('img').not('.icon'); this.$carousel_tabpanel_content_videos = this.$carousel.children().last().find('iframe'); this.setResponsive(); this.carousel_width = this.settings.width; this.carousel_height = this.settings.height; this.carousel_infinite = this.settings.infinite; this.carousel_row = this.settings.row; this.carousel_count = this.settings.count; this.carousel_col = this.settings.col; this.carousel_content_margin = this.settings.margin; this.start_tabpanel_index = this.settings.index; // 동적으로 캐러셀 구조 생성/추가 this.createPrevNextButtons(); this.createCarouselMask(); // 역할별 스타일링 되는 클래스 설정 this.settingClass(); this.settingSliding(); }, 'createPrevNextButtons': function() { var button_group = ['<div>', '<button type="button"></button>', '<button type="button"></button>', '</div>'].join(''); this.$carousel_button_group = $(button_group).insertAfter( this.$carousel_tablist ); }, 'createCarouselMask': function() { this.$carousel_tabpanels.parent().closest('div').wrap('<div/>'); this.$carousel_mask = this.$carousel.children().last(); }, 'settingClass': function() { this.$carousel.addClass('ui-carousel'); this.$carousel_headline.addClass('ui-carousel-headline'); this.$carousel_tablist.addClass('ui-carousel-tablist'); this.$carousel_tabs.addClass('ui-carousel-tab'); this.$carousel_button_group.addClass('ui-carousel-button-group'); this.$carousel_button_group.children().first().addClass('ui-carousel-prev-button'); this.$carousel_button_group.children().last().addClass('ui-carousel-next-button'); this.$carousel_tabpanels.addClass('ui-carousel-tabpanel'); this.$carousel_tabpanels.parent().closest('div').addClass('ui-carousel-tabpanel-wrapper'); this.$carousel_mask.addClass('ui-carousel-mask'); this.$carousel_tabpanel_imgs.addClass('ui-carousel-image'); this.$carousel_tabpanel_content_videos.addClass('ui-carousel-video'); if(this.carousel_row === 2) { var j = 1; var j2 = 1; for(var i = 0, l = this.$carousel_tabpanels.length; i < l; i++) { if(i%2===1){ this.$carousel_tabpanels.eq(i).addClass('top-2'); this.$carousel_tabpanels.eq(i).addClass('left-' + j); j++; } else { this.$carousel_tabpanels.eq(i).addClass('top-1'); this.$carousel_tabpanels.eq(i).addClass('left-' + j2); j2++; } } } }, 'settingSliding': function() { var $carousel = this.$carousel; var $tabpanel = this.$carousel_tabpanels; var $tabpanel_wrapper = $tabpanel.parent(); var $carousel_mask = this.$carousel_mask; var carousel_tabpannel_width = ($carousel_mask.width() - (this.carousel_col - 1) * this.carousel_content_margin) / this.carousel_col; this.carousel_content_width = this.$carousel_tabpanel_imgs.eq(0).width(); // carousel 높이 설정 $carousel.height(this.carousel_height); // Set carousel tabpanel(div or img) size and margin if(this.settings.col === 1) { $tabpanel.width($carousel.width()); } else { $tabpanel .width(this.carousel_content_width) .css('margin-right', this.carousel_content_margin); } // Set carousel tabpanel wrapper width $tabpanel_wrapper.width(($tabpanel.width() + this.carousel_content_margin) * ($tabpanel.length + 1)); // Set carousel one tab mask width this.carousel_one_tab = ($tabpanel.width() + this.carousel_content_margin) * this.carousel_count; if(this.start_tabpanel_index !== 0) { for(var i = 0, l = this.start_tabpanel_index + 1; i < l; i++) { this.$carousel_tabpanels.last().parent().prepend(this.$carousel_tabpanels.eq($tabpanel.length - (i + 1))); } } // Carousel 상태 초기화 if(this.carousel_infinite === true) { // tabpanel active 상태 초기화 this.$carousel_tabpanels.eq(this.active_index).radioClass('active'); // tabpanel wrapper 위치 초기화 $tabpanel_wrapper.css('left', -this.carousel_one_tab); } else if(this.carousel_col !== 1){ // Infinite Carousel이 아닐때 // prevBtn 비활성화 this.prevBtnDisable(); } // 인디케이터 active 상태 초기화 this.$carousel_tabs.eq(this.active_index).parent().radioClass('active'); }, 'prevBtnActive': function() { this.$carousel.find('.ui-carousel-prev-button') .attr('aria-disabled', 'false') .css({'opacity': 1, 'display': 'block'}); }, 'prevBtnDisable': function() { this.$carousel.find('.ui-carousel-prev-button') .attr('aria-disabled', 'true') .css({'opacity': 0, 'display': 'none'}); }, 'events': function() { var widget = this; var $carousel = widget.$carousel; var $tabs = widget.$carousel_tabs; var $buttons = widget.$carousel_button_group.children(); // buttons event $buttons.on('click', function() { if ( this.className === 'ui-carousel-prev-button' ) { widget.prevPanel(); } else { widget.nextPanel(); } }); // tabs event $.each($tabs, function(index) { var $tab = $tabs.eq(index); $tab.on('click', $.proxy(widget.viewTabpanel, widget, index, null)); }); }, 'setActiveIndex': function(index) { // 활성화된 인덱스를 사용자가 클릭한 인덱스로 변경 this.active_index = index; // tab 최대 개수 var carousel_tabs_max = (this.$carousel_tabpanels.length / (this.carousel_count * this.carousel_row)) - 1; // 한 마스크 안에 패널이 다 채워지지 않을 경우 if((this.$carousel_tabpanels.length % (this.carousel_count * this.carousel_row)) !== 0) { carousel_tabs_max = carousel_tabs_max + 1; } // 처음 또는 마지막 인덱스에 해당할 경우 마지막 또는 처음으로 변경하는 조건 처리 if ( this.active_index < 0 ) { this.active_index = carousel_tabs_max; } if ( this.active_index > carousel_tabs_max ) { this.active_index = 0; } return this.active_index; }, 'nextPanel': function() { if(!this.$carousel_tabpanels.parent().is(':animated')) { var active_index = this.setActiveIndex(this.active_index + 1); this.viewTabpanel(active_index, 'next'); } }, 'prevPanel': function() { if(!this.$carousel_tabpanels.parent().is(':animated')) { var active_index = this.setActiveIndex(this.active_index - 1); this.viewTabpanel(active_index, 'prev'); } }, 'viewTabpanel': function(index, btn, e) { // 사용자가 클릭을 하는 행위가 발생하면 이벤트 객체를 받기 때문에 // 조건 확인을 통해 브라우저의 기본 동작 차단 if (e) { e.preventDefault(); } this.active_index = index; var $carousel_wrapper = this.$carousel_tabpanels.eq(index).parent(); var one_width = this.carousel_one_tab; // Infinite Carousel if(this.carousel_infinite === true) { // index에 해당되는 탭패널 활성화 this.$carousel_tabpanels.eq(index).radioClass('active'); // next 버튼 눌렀을때 if(btn === 'next') { $carousel_wrapper.stop().animate({ 'left': -one_width * 2 }, 500, 'easeOutExpo', function() { $carousel_wrapper.append($carousel_wrapper.children().first()); $carousel_wrapper.css('left', -one_width); this.animating = false; }); // prev 버튼 눌렀을때 } else if(btn === 'prev') { $carousel_wrapper.stop().animate({ 'left': 0 }, 500, 'easeOutExpo', function() { $carousel_wrapper.prepend($carousel_wrapper.children().last()); $carousel_wrapper.css('left', -one_width); }); } } else if(this.carousel_infinite === false) { if(this.carousel_col !== 1) { if(index === 0) { this.prevBtnDisable(); } else { this.prevBtnActive(); } } $carousel_wrapper.stop().animate({ 'left': index * -this.carousel_one_tab }, 600, 'easeOutExpo'); } // 인디케이터 라디오클래스 활성화 this.$carousel_tabs.eq(index).parent().radioClass('active'); }, 'setResponsive': function() { if(global.innerWidth <= 750) { this.settings.width = this.settings.width.mobile || this.settings.width; this.settings.height = this.settings.height.mobile || this.settings.height; this.settings.margin = this.settings.margin.mobile || this.settings.margin; this.settings.count = this.settings.count.mobile || this.settings.count; this.settings.col = this.settings.col.mobile || this.settings.col; this.settings.row = this.settings.row.mobile || this.settings.row; if(this.settings.infinite.mobile !== undefined) { this.settings.infinite = this.settings.infinite.mobile; } this.settings.index = 0; } else if(global.innerWidth <= 1024) { this.settings.width = this.settings.width.tablet || this.settings.width; this.settings.height = this.settings.height.tablet || this.settings.height; this.settings.margin = this.settings.margin.tablet || this.settings.margin; this.settings.count = this.settings.count.tablet || this.settings.count; this.settings.col = this.settings.col.tablet || this.settings.col; this.settings.row = this.settings.row.tablet || this.settings.row; if(this.settings.infinite.tablet !== undefined) { this.settings.infinite = this.settings.infinite.tablet; } this.settings.index = this.settings.index.tablet || this.settings.index; } else { this.settings.width = this.settings.width.desktop || this.settings.width; this.settings.height = this.settings.height.desktop || this.settings.height; this.settings.margin = this.settings.margin.desktop || this.settings.margin; this.settings.count = this.settings.count.desktop || this.settings.count; this.settings.col = this.settings.col.desktop || this.settings.col; this.settings.row = this.settings.row.desktop || this.settings.row; if(this.settings.infinite.desktop !== undefined) { this.settings.infinite = this.settings.infinite.desktop; } this.settings.index = this.settings.index.desktop || this.settings.index; } } }; // jQuery Plugin $.fn.fingoCarousel = function(options){ var $collection = this; // jQuery {} return $.each($collection, function(idx){ var $this = $collection.eq(idx); var _instance = new Carousel( this, options ); // 컴포넌트 화 $this.data('fingoCarousel', _instance); }); }; })(this, this.jQuery);
class upnp_soaprequest { constructor() { } // System.Runtime.Remoting.ObjRef CreateObjRef(type requestedType) CreateObjRef() { } // bool Equals(System.Object obj) Equals() { } // int GetHashCode() GetHashCode() { } // System.Object GetLifetimeService() GetLifetimeService() { } // type GetType() GetType() { } // System.Object InitializeLifetimeService() InitializeLifetimeService() { } // string ToString() ToString() { } } module.exports = upnp_soaprequest;
module.exports = { schedule_inputError: "Not all required inputs are present in the request", reminder_newscheduleSuccess: "A new mail has been successfully saved and scheduled", schedule_ShdlError: "The scheduleAt should be a timestamp (like : 1411820580000) and should be in the future", gbl_oops: "Oops something went wrong", gbl_success: "success" };
/** * create edit language file link */ export default (lang) => { return `https://github.com/electerm/electerm-locales/edit/master/locales/${lang}.js` }
/** * @author Ultimo <[email protected]> * @license http://www.opensource.org/licenses/mit-license.html MIT License * @version 0.1 (25-06-2017) * * Hier schreiben wir die JavaScript Funktionen. * */ src="jquery-3.2.1.min"; $(document).ready(function(){ $("td:contains('-')").filter(":contains('€')").addClass('neg'); $(".betrag").filter(":contains('-')").addClass('neg'); }); function goBack() { window.history.back(); }
var compare = require('typewiselite') var search = require('binary-search') function compareKeys (a, b) { return compare(a.key, b.key) } module.exports = function (_compare) { var ary = [], kv _compare = _compare || compare function cmp (a, b) { return _compare(a.key, b.key) } return kv = { getIndex: function (key) { return search(ary, {key: key}, cmp, 0, ary.length - 1) }, get: function (key) { var i = this.getIndex(key) return i >= 0 ? ary[i].value : undefined }, has: function (key) { return this.getIndex(key) >= 0 }, //update a key set: function (key, value) { return kv.add({key: key, value: value}) }, add: function (o) { var i = search(ary, o, cmp) //overwrite a key, or insert a key if(i < 0) ary.splice(~i, 0, o) else ary[i] = o return i }, toJSON: function () { return ary.slice() }, store: ary } } module.exports.search = search module.exports.compareKeys = compareKeys
define( [ 'jquery', 'angular', 'json!nuke/data/dummy_model.json', 'json!nuke/data/dummy_layout.json', 'text!nuke/demo.html' ], function( $, ng, dummyModel, dummyLayout, htmlDemoTemplate ) { 'use strict'; var module = ng.module( 'NukeDemoApp', [ 'nbe' ] ) .run( [ '$templateCache', function( $templateCache ) { $templateCache.put( 'lib/demo.html', htmlDemoTemplate ); } ] ); /////////////////////////////////////////////////////////////////////////////////////////////////////////// function NukeDemoController( $scope, $timeout ) { $scope.model = dummyModel; $scope.layout = dummyLayout; } /////////////////////////////////////////////////////////////////////////////////////////////////////////// module.controller( 'NukeDemoController', [ '$scope', '$timeout', NukeDemoController ] ); /////////////////////////////////////////////////////////////////////////////////////////////////////////// return module; } );
/** * @author Richard Davey <[email protected]> * @copyright 2016 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * This is where the magic happens. The Game object is the heart of your game, * providing quick access to common functions and handling the boot process. * * "Hell, there are no rules here - we're trying to accomplish something." * Thomas A. Edison * * @class Phaser.Game * @constructor * @param {object} [gameConfig={}] - The game configuration object */ Phaser.Game = function (gameConfig) { /** * @property {number} id - Phaser Game ID (for when Pixi supports multiple instances). * @readonly */ this.id = Phaser.GAMES.push(this) - 1; /** * @property {object} config - The Phaser.Game configuration object. */ this.config = null; /** * @property {object} physicsConfig - The Phaser.Physics.World configuration object. */ this.physicsConfig = null; /** * @property {string|HTMLElement} parent - The Games DOM parent. * @default */ this.parent = ''; /** * The current Game Width in pixels. * * _Do not modify this property directly:_ use {@link Phaser.ScaleManager#setGameSize} - eg. `game.scale.setGameSize(width, height)` - instead. * * @property {integer} width * @readonly * @default */ this.width = 800; /** * The current Game Height in pixels. * * _Do not modify this property directly:_ use {@link Phaser.ScaleManager#setGameSize} - eg. `game.scale.setGameSize(width, height)` - instead. * * @property {integer} height * @readonly * @default */ this.height = 600; /** * The resolution of your game. This value is read only, but can be changed at start time it via a game configuration object. * * @property {integer} resolution * @readonly * @default */ this.resolution = 1; /** * @property {integer} _width - Private internal var. * @private */ this._width = 800; /** * @property {integer} _height - Private internal var. * @private */ this._height = 600; /** * @property {boolean} transparent - Use a transparent canvas background or not. * @default */ this.transparent = false; /** * @property {boolean} antialias - Anti-alias graphics. By default scaled images are smoothed in Canvas and WebGL, set anti-alias to false to disable this globally. * @default */ this.antialias = false; /** * @property {boolean} preserveDrawingBuffer - The value of the preserveDrawingBuffer flag affects whether or not the contents of the stencil buffer is retained after rendering. * @default */ this.preserveDrawingBuffer = false; /** * Clear the Canvas each frame before rendering the display list. * You can set this to `false` to gain some performance if your game always contains a background that completely fills the display. * @property {boolean} clearBeforeRender * @default */ this.clearBeforeRender = true; /** * @property {PIXI.CanvasRenderer|PIXI.WebGLRenderer} renderer - The Pixi Renderer. * @protected */ this.renderer = null; /** * @property {number} renderType - The Renderer this game will use. Either Phaser.AUTO, Phaser.CANVAS, Phaser.WEBGL, or Phaser.HEADLESS. * @readonly */ this.renderType = Phaser.AUTO; /** * @property {Phaser.StateManager} state - The StateManager. */ this.state = null; /** * @property {boolean} isBooted - Whether the game engine is booted, aka available. * @readonly */ this.isBooted = false; /** * @property {boolean} isRunning - Is game running or paused? * @readonly */ this.isRunning = false; /** * @property {Phaser.RequestAnimationFrame} raf - Automatically handles the core game loop via requestAnimationFrame or setTimeout * @protected */ this.raf = null; /** * @property {Phaser.GameObjectFactory} add - Reference to the Phaser.GameObjectFactory. */ this.add = null; /** * @property {Phaser.GameObjectCreator} make - Reference to the GameObject Creator. */ this.make = null; /** * @property {Phaser.Cache} cache - Reference to the assets cache. */ this.cache = null; /** * @property {Phaser.Input} input - Reference to the input manager */ this.input = null; /** * @property {Phaser.Loader} load - Reference to the assets loader. */ this.load = null; /** * @property {Phaser.Math} math - Reference to the math helper. */ this.math = null; /** * @property {Phaser.Net} net - Reference to the network class. */ this.net = null; /** * @property {Phaser.ScaleManager} scale - The game scale manager. */ this.scale = null; /** * @property {Phaser.SoundManager} sound - Reference to the sound manager. */ this.sound = null; /** * @property {Phaser.Stage} stage - Reference to the stage. */ this.stage = null; /** * @property {Phaser.Time} time - Reference to the core game clock. */ this.time = null; /** * @property {Phaser.TweenManager} tweens - Reference to the tween manager. */ this.tweens = null; /** * @property {Phaser.World} world - Reference to the world. */ this.world = null; /** * @property {Phaser.Physics} physics - Reference to the physics manager. */ this.physics = null; /** * @property {Phaser.PluginManager} plugins - Reference to the plugin manager. */ this.plugins = null; /** * @property {Phaser.RandomDataGenerator} rnd - Instance of repeatable random data generator helper. */ this.rnd = null; /** * @property {Phaser.Device} device - Contains device information and capabilities. */ this.device = Phaser.Device; /** * @property {Phaser.Camera} camera - A handy reference to world.camera. */ this.camera = null; /** * @property {HTMLCanvasElement} canvas - A handy reference to renderer.view, the canvas that the game is being rendered in to. */ this.canvas = null; /** * @property {CanvasRenderingContext2D} context - A handy reference to renderer.context (only set for CANVAS games, not WebGL) */ this.context = null; /** * @property {Phaser.Utils.Debug} debug - A set of useful debug utilities. */ this.debug = null; /** * @property {Phaser.Particles} particles - The Particle Manager. */ this.particles = null; /** * @property {Phaser.Create} create - The Asset Generator. */ this.create = null; /** * If `false` Phaser will automatically render the display list every update. If `true` the render loop will be skipped. * You can toggle this value at run-time to gain exact control over when Phaser renders. This can be useful in certain types of game or application. * Please note that if you don't render the display list then none of the game object transforms will be updated, so use this value carefully. * @property {boolean} lockRender * @default */ this.lockRender = false; /** * @property {boolean} stepping - Enable core loop stepping with Game.enableStep(). * @default * @readonly */ this.stepping = false; /** * @property {boolean} pendingStep - An internal property used by enableStep, but also useful to query from your own game objects. * @default * @readonly */ this.pendingStep = false; /** * @property {number} stepCount - When stepping is enabled this contains the current step cycle. * @default * @readonly */ this.stepCount = 0; /** * @property {Phaser.Signal} onPause - This event is fired when the game pauses. */ this.onPause = null; /** * @property {Phaser.Signal} onResume - This event is fired when the game resumes from a paused state. */ this.onResume = null; /** * @property {Phaser.Signal} onBlur - This event is fired when the game no longer has focus (typically on page hide). */ this.onBlur = null; /** * @property {Phaser.Signal} onFocus - This event is fired when the game has focus (typically on page show). */ this.onFocus = null; /** * @property {boolean} _paused - Is game paused? * @private */ this._paused = false; /** * @property {boolean} _codePaused - Was the game paused via code or a visibility change? * @private */ this._codePaused = false; /** * The ID of the current/last logic update applied this render frame, starting from 0. * The first update is `currentUpdateID === 0` and the last update is `currentUpdateID === updatesThisFrame.` * @property {integer} currentUpdateID * @protected */ this.currentUpdateID = 0; /** * Number of logic updates expected to occur this render frame; will be 1 unless there are catch-ups required (and allowed). * @property {integer} updatesThisFrame * @protected */ this.updatesThisFrame = 1; /** * @property {number} _deltaTime - Accumulate elapsed time until a logic update is due. * @private */ this._deltaTime = 0; /** * @property {number} _lastCount - Remember how many 'catch-up' iterations were used on the logicUpdate last frame. * @private */ this._lastCount = 0; /** * @property {number} _spiraling - If the 'catch-up' iterations are spiraling out of control, this counter is incremented. * @private */ this._spiraling = 0; /** * @property {boolean} _kickstart - Force a logic update + render by default (always set on Boot and State swap) * @private */ this._kickstart = true; /** * If the game is struggling to maintain the desired FPS, this signal will be dispatched. * The desired/chosen FPS should probably be closer to the {@link Phaser.Time#suggestedFps} value. * @property {Phaser.Signal} fpsProblemNotifier * @public */ this.fpsProblemNotifier = new Phaser.Signal(); /** * @property {boolean} forceSingleUpdate - Should the game loop force a logic update, regardless of the delta timer? Set to true if you know you need this. You can toggle it on the fly. */ this.forceSingleUpdate = true; /** * @property {number} _nextNotification - The soonest game.time.time value that the next fpsProblemNotifier can be dispatched. * @private */ this._nextFpsNotification = 0; // Parse the configuration object if (typeof gameConfig !== 'object') { throw new Error('Missing game configuration object: ' + gameConfig); } this.parseConfig(gameConfig); this.device.whenReady(this.boot, this); return this; }; Phaser.Game.prototype = { /** * Parses a Game configuration object. * * @method Phaser.Game#parseConfig * @protected */ parseConfig: function (config) { this.config = config; if (config['enableDebug'] === undefined) { this.config.enableDebug = true; } if (config['width']) { this._width = config['width']; } if (config['height']) { this._height = config['height']; } if (config['renderer']) { this.renderType = config['renderer']; } if (config['parent']) { this.parent = config['parent']; } if (config['transparent'] !== undefined) { this.transparent = config['transparent']; } if (config['antialias'] !== undefined) { this.antialias = config['antialias']; } if (config['resolution']) { this.resolution = config['resolution']; } if (config['preserveDrawingBuffer'] !== undefined) { this.preserveDrawingBuffer = config['preserveDrawingBuffer']; } if (config['clearBeforeRender'] !== undefined) { this.clearBeforeRender = config['clearBeforeRender']; } if (config['physicsConfig']) { this.physicsConfig = config['physicsConfig']; } var seed = [(Date.now() * Math.random()).toString()]; if (config['seed']) { seed = config['seed']; } this.rnd = new Phaser.RandomDataGenerator(seed); var state = null; if (config['state']) { state = config['state']; } this.state = new Phaser.StateManager(this, state); }, /** * Initialize engine sub modules and start the game. * * @method Phaser.Game#boot * @protected */ boot: function () { if (this.isBooted) { return; } this.onPause = new Phaser.Signal(); this.onResume = new Phaser.Signal(); this.onBlur = new Phaser.Signal(); this.onFocus = new Phaser.Signal(); this.isBooted = true; PIXI.game = this; this.math = Phaser.Math; this.scale = new Phaser.ScaleManager(this, this._width, this._height); this.stage = new Phaser.Stage(this); this.setUpRenderer(); this.world = new Phaser.World(this); this.add = new Phaser.GameObjectFactory(this); this.make = new Phaser.GameObjectCreator(this); this.cache = new Phaser.Cache(this); this.load = new Phaser.Loader(this); this.time = new Phaser.Time(this); this.tweens = new Phaser.TweenManager(this); this.input = new Phaser.Input(this); this.sound = new Phaser.SoundManager(this); this.physics = new Phaser.Physics(this, this.physicsConfig); this.particles = new Phaser.Particles(this); this.create = new Phaser.Create(this); this.plugins = new Phaser.PluginManager(this); this.net = new Phaser.Net(this); this.time.boot(); this.stage.boot(); this.world.boot(); this.scale.boot(); this.input.boot(); this.sound.boot(); this.state.boot(); if (this.config['enableDebug']) { this.debug = new Phaser.Utils.Debug(this); this.debug.boot(); } else { this.debug = { preUpdate: function () {}, update: function () {}, reset: function () {} }; } this.showDebugHeader(); this.isRunning = true; if (this.config && this.config['forceSetTimeOut']) { this.raf = new Phaser.RequestAnimationFrame(this, this.config['forceSetTimeOut']); } else { this.raf = new Phaser.RequestAnimationFrame(this, false); } this._kickstart = true; if (window['focus']) { if (!window['PhaserGlobal'] || (window['PhaserGlobal'] && !window['PhaserGlobal'].stopFocus)) { window.focus(); } } this.raf.start(); }, /** * Displays a Phaser version debug header in the console. * * @method Phaser.Game#showDebugHeader * @protected */ showDebugHeader: function () { if (window['PhaserGlobal'] && window['PhaserGlobal'].hideBanner) { return; } var v = Phaser.VERSION; var r = 'Canvas'; var a = 'HTML Audio'; var c = 1; if (this.renderType === Phaser.WEBGL) { r = 'WebGL'; c++; } else if (this.renderType === Phaser.HEADLESS) { r = 'Headless'; } if (this.device.webAudio) { a = 'WebAudio'; c++; } if (this.device.chrome) { var args = [ '%c %c %c Phaser v' + v + ' | Pixi.js | ' + r + ' | ' + a + ' %c %c ' + '%c http://phaser.io %c\u2665%c\u2665%c\u2665', 'background: #fb8cb3', 'background: #d44a52', 'color: #ffffff; background: #871905;', 'background: #d44a52', 'background: #fb8cb3', 'background: #ffffff' ]; for (var i = 0; i < 3; i++) { if (i < c) { args.push('color: #ff2424; background: #fff'); } else { args.push('color: #959595; background: #fff'); } } console.log.apply(console, args); } else if (window['console']) { console.log('Phaser v' + v + ' | Pixi.js ' + PIXI.VERSION + ' | ' + r + ' | ' + a + ' | http://phaser.io'); } }, /** * Checks if the device is capable of using the requested renderer and sets it up or an alternative if not. * * @method Phaser.Game#setUpRenderer * @protected */ setUpRenderer: function () { if (this.config['canvas']) { this.canvas = this.config['canvas']; } else { this.canvas = Phaser.Canvas.create(this, this.width, this.height, this.config['canvasID'], true); } if (this.config['canvasStyle']) { this.canvas.style = this.config['canvasStyle']; } else { this.canvas.style['-webkit-full-screen'] = 'width: 100%; height: 100%'; } if (this.renderType === Phaser.HEADLESS || this.renderType === Phaser.CANVAS || (this.renderType === Phaser.AUTO && !this.device.webGL)) { if (this.device.canvas) { // They requested Canvas and their browser supports it this.renderType = Phaser.CANVAS; this.renderer = new PIXI.CanvasRenderer(this); this.context = this.renderer.context; } else { throw new Error('Phaser.Game - Cannot create Canvas or WebGL context, aborting.'); } } else { // They requested WebGL and their browser supports it this.renderType = Phaser.WEBGL; this.renderer = new PIXI.WebGLRenderer(this); this.context = null; this.canvas.addEventListener('webglcontextlost', this.contextLost.bind(this), false); this.canvas.addEventListener('webglcontextrestored', this.contextRestored.bind(this), false); } if (this.device.cocoonJS) { this.canvas.screencanvas = (this.renderType === Phaser.CANVAS) ? true : false; } if (this.renderType !== Phaser.HEADLESS) { this.stage.smoothed = this.antialias; Phaser.Canvas.addToDOM(this.canvas, this.parent, false); Phaser.Canvas.setTouchAction(this.canvas); } }, /** * Handles WebGL context loss. * * @method Phaser.Game#contextLost * @private * @param {Event} event - The webglcontextlost event. */ contextLost: function (event) { event.preventDefault(); this.renderer.contextLost = true; }, /** * Handles WebGL context restoration. * * @method Phaser.Game#contextRestored * @private */ contextRestored: function () { this.renderer.initContext(); this.cache.clearGLTextures(); this.renderer.contextLost = false; }, /** * The core game loop. * * @method Phaser.Game#update * @protected * @param {number} time - The current time as provided by RequestAnimationFrame. */ update: function (time) { this.time.update(time); if (this._kickstart) { this.updateLogic(this.time.desiredFpsMult); // call the game render update exactly once every frame this.updateRender(this.time.slowMotion * this.time.desiredFps); this._kickstart = false; return; } // if the logic time is spiraling upwards, skip a frame entirely if (this._spiraling > 1 && !this.forceSingleUpdate) { // cause an event to warn the program that this CPU can't keep up with the current desiredFps rate if (this.time.time > this._nextFpsNotification) { // only permit one fps notification per 10 seconds this._nextFpsNotification = this.time.time + 10000; // dispatch the notification signal this.fpsProblemNotifier.dispatch(); } // reset the _deltaTime accumulator which will cause all pending dropped frames to be permanently skipped this._deltaTime = 0; this._spiraling = 0; // call the game render update exactly once every frame this.updateRender(this.time.slowMotion * this.time.desiredFps); } else { // step size taking into account the slow motion speed var slowStep = this.time.slowMotion * 1000.0 / this.time.desiredFps; // accumulate time until the slowStep threshold is met or exceeded... up to a limit of 3 catch-up frames at slowStep intervals this._deltaTime += Math.max(Math.min(slowStep * 3, this.time.elapsed), 0); // call the game update logic multiple times if necessary to "catch up" with dropped frames // unless forceSingleUpdate is true var count = 0; this.updatesThisFrame = Math.floor(this._deltaTime / slowStep); if (this.forceSingleUpdate) { this.updatesThisFrame = Math.min(1, this.updatesThisFrame); } while (this._deltaTime >= slowStep) { this._deltaTime -= slowStep; this.currentUpdateID = count; this.updateLogic(this.time.desiredFpsMult); count++; if (this.forceSingleUpdate && count === 1) { break; } else { this.time.refresh(); } } // detect spiraling (if the catch-up loop isn't fast enough, the number of iterations will increase constantly) if (count > this._lastCount) { this._spiraling++; } else if (count < this._lastCount) { // looks like it caught up successfully, reset the spiral alert counter this._spiraling = 0; } this._lastCount = count; // call the game render update exactly once every frame unless we're playing catch-up from a spiral condition this.updateRender(this._deltaTime / slowStep); } }, /** * Updates all logic subsystems in Phaser. Called automatically by Game.update. * * @method Phaser.Game#updateLogic * @protected * @param {number} timeStep - The current timeStep value as determined by Game.update. */ updateLogic: function (timeStep) { if (!this._paused && !this.pendingStep) { if (this.stepping) { this.pendingStep = true; } this.scale.preUpdate(); this.debug.preUpdate(); this.camera.preUpdate(); this.physics.preUpdate(); this.state.preUpdate(timeStep); this.plugins.preUpdate(timeStep); this.stage.preUpdate(); this.state.update(); this.stage.update(); this.tweens.update(); this.sound.update(); this.input.update(); this.physics.update(); this.particles.update(); this.plugins.update(); this.stage.postUpdate(); this.plugins.postUpdate(); } else { // Scaling and device orientation changes are still reflected when paused. this.scale.pauseUpdate(); this.state.pauseUpdate(); this.debug.preUpdate(); } this.stage.updateTransform(); }, /** * Runs the Render cycle. * It starts by calling State.preRender. In here you can do any last minute adjustments of display objects as required. * It then calls the renderer, which renders the entire display list, starting from the Stage object and working down. * It then calls plugin.render on any loaded plugins, in the order in which they were enabled. * After this State.render is called. Any rendering that happens here will take place on-top of the display list. * Finally plugin.postRender is called on any loaded plugins, in the order in which they were enabled. * This method is called automatically by Game.update, you don't need to call it directly. * Should you wish to have fine-grained control over when Phaser renders then use the `Game.lockRender` boolean. * Phaser will only render when this boolean is `false`. * * @method Phaser.Game#updateRender * @protected * @param {number} elapsedTime - The time elapsed since the last update. */ updateRender: function (elapsedTime) { if (this.lockRender) { return; } this.state.preRender(elapsedTime); if (this.renderType !== Phaser.HEADLESS) { this.renderer.render(this.stage); this.plugins.render(elapsedTime); this.state.render(elapsedTime); } this.plugins.postRender(elapsedTime); }, /** * Enable core game loop stepping. When enabled you must call game.step() directly (perhaps via a DOM button?) * Calling step will advance the game loop by one frame. This is extremely useful for hard to track down errors! * * @method Phaser.Game#enableStep */ enableStep: function () { this.stepping = true; this.pendingStep = false; this.stepCount = 0; }, /** * Disables core game loop stepping. * * @method Phaser.Game#disableStep */ disableStep: function () { this.stepping = false; this.pendingStep = false; }, /** * When stepping is enabled you must call this function directly (perhaps via a DOM button?) to advance the game loop by one frame. * This is extremely useful to hard to track down errors! Use the internal stepCount property to monitor progress. * * @method Phaser.Game#step */ step: function () { this.pendingStep = false; this.stepCount++; }, /** * Nukes the entire game from orbit. * * Calls destroy on Game.state, Game.sound, Game.scale, Game.stage, Game.input, Game.physics and Game.plugins. * * Then sets all of those local handlers to null, destroys the renderer, removes the canvas from the DOM * and resets the PIXI default renderer. * * @method Phaser.Game#destroy */ destroy: function () { this.raf.stop(); this.state.destroy(); this.sound.destroy(); this.scale.destroy(); this.stage.destroy(); this.input.destroy(); this.physics.destroy(); this.plugins.destroy(); this.state = null; this.sound = null; this.scale = null; this.stage = null; this.input = null; this.physics = null; this.plugins = null; this.cache = null; this.load = null; this.time = null; this.world = null; this.isBooted = false; this.renderer.destroy(false); Phaser.Canvas.removeFromDOM(this.canvas); PIXI.defaultRenderer = null; Phaser.GAMES[this.id] = null; }, /** * Called by the Stage visibility handler. * * @method Phaser.Game#gamePaused * @param {object} event - The DOM event that caused the game to pause, if any. * @protected */ gamePaused: function (event) { // If the game is already paused it was done via game code, so don't re-pause it if (!this._paused) { this._paused = true; this.time.gamePaused(); if (this.sound.muteOnPause) { this.sound.setMute(); } this.onPause.dispatch(event); // Avoids Cordova iOS crash event: https://github.com/photonstorm/phaser/issues/1800 if (this.device.cordova && this.device.iOS) { this.lockRender = true; } } }, /** * Called by the Stage visibility handler. * * @method Phaser.Game#gameResumed * @param {object} event - The DOM event that caused the game to pause, if any. * @protected */ gameResumed: function (event) { // Game is paused, but wasn't paused via code, so resume it if (this._paused && !this._codePaused) { this._paused = false; this.time.gameResumed(); this.input.reset(); if (this.sound.muteOnPause) { this.sound.unsetMute(); } this.onResume.dispatch(event); // Avoids Cordova iOS crash event: https://github.com/photonstorm/phaser/issues/1800 if (this.device.cordova && this.device.iOS) { this.lockRender = false; } } }, /** * Called by the Stage visibility handler. * * @method Phaser.Game#focusLoss * @param {object} event - The DOM event that caused the game to pause, if any. * @protected */ focusLoss: function (event) { this.onBlur.dispatch(event); if (!this.stage.disableVisibilityChange) { this.gamePaused(event); } }, /** * Called by the Stage visibility handler. * * @method Phaser.Game#focusGain * @param {object} event - The DOM event that caused the game to pause, if any. * @protected */ focusGain: function (event) { this.onFocus.dispatch(event); if (!this.stage.disableVisibilityChange) { this.gameResumed(event); } } }; Phaser.Game.prototype.constructor = Phaser.Game; /** * The paused state of the Game. A paused game doesn't update any of its subsystems. * When a game is paused the onPause event is dispatched. When it is resumed the onResume event is dispatched. * @name Phaser.Game#paused * @property {boolean} paused - Gets and sets the paused state of the Game. */ Object.defineProperty(Phaser.Game.prototype, "paused", { get: function () { return this._paused; }, set: function (value) { if (value === true) { if (this._paused === false) { this._paused = true; this.sound.setMute(); this.time.gamePaused(); this.onPause.dispatch(this); } this._codePaused = true; } else { if (this._paused) { this._paused = false; this.input.reset(); this.sound.unsetMute(); this.time.gameResumed(); this.onResume.dispatch(this); } this._codePaused = false; } } }); /** * * "Deleted code is debugged code." - Jeff Sickel * * ヽ(〃^▽^〃)ノ * */
/* app/ui/map/svg */ define( [ 'jquery', 'raphael', 'app/ui/map/data', 'app/ui/map/util', 'util/detector', 'pubsub' ], function ($, Raphael, MapData, MapUtil, Detector) { 'use strict'; var SVG; return { nzte: {}, markers: [], exports: {}, countryText: {}, sets: {}, continentSets: {}, text: {}, raphael: null, _$container: null, _isExportsMap: false, init: function () { SVG = this; this._$container = $('.js-map-container'); this._isExportsMap = $('#js-map-nzte').length ? false : true; //If already setup just show the map again if (this._$container.is('.is-loaded')) { this._$container.show(); return; } if (this._isExportsMap) { this._initInteractiveMap(); return; } this._initRegularMap(); }, _initInteractiveMap: function () { this._setUpMap(); this._drawMap(); this._createContinentSets(); this._initInteractiveMapEvents(); this._setLoaded(); this._hideLoader(); }, _initRegularMap: function () { this._setUpMap(); this._drawMap(); this._createSets(); this._initRegularMapEvents(); this._setLoaded(); this._hideLoader(); }, _setLoaded: function () { this._$container.addClass('is-loaded'); }, _hideLoader: function () { $.publish('/loader/hide'); }, _setUpMap: function () { var id = this._isExportsMap ? 'js-map-exports' : 'js-map-nzte'; this._$container.show(); this.raphael = Raphael(id, '100%', '100%'); this.raphael.setViewBox(0, 0, 841, 407, true); this.raphael.canvas.setAttribute('preserveAspectRatio', 'xMinYMin meet'); }, _drawMap: function () { this._addMainMap(); this._addContinentMarkers(); this._addContinentMarkerText(); if (this._isExportsMap) { this._addCountryMarkers(); } }, _addMainMap: function () { var mainAttr = { stroke: 'none', fill: '#dededd', 'fill-rule': 'evenodd', 'stroke-linejoin': 'round' }; this.nzte.main = this.raphael.path(MapData.main).attr(mainAttr); }, _addContinentMarkers: function () { var markerAttr = { stroke: 'none', fill: '#f79432', 'stroke-linejoin': 'round', cursor: 'pointer' }; var markerPaths = MapData.markers[0]; for (var continent in markerPaths) { if (!this._isExportsMap || this._isExportsMap && continent !== 'new-zealand') { this.markers[continent] = this.raphael.path(markerPaths[continent]).attr(markerAttr); } } }, _addContinentMarkerText: function () { var textAttr = { stroke: 'none', fill: '#ffffff', 'fill-rule': 'evenodd', 'stroke-linejoin': 'round', cursor: 'pointer' }; var textPaths = MapData.text[0]; for (var continent in textPaths) { if (!this._isExportsMap || this._isExportsMap && continent !== 'new-zealand') { this.text[continent] = this.raphael.path(textPaths[continent]).attr(textAttr); } } }, _addCountryMarkers: function () { var marker; for (var region in this.markers) { marker = this.markers[region]; this._createHoverBox(region, marker); } }, _createHoverBox: function (region, marker) { var set; var markerAttr = { stroke: 'none', fill: '#116697', opacity: 0, 'stroke-linejoin': 'round' }; var markerPaths = MapData.exportsText[0]; var country = markerPaths[region]; if (!country) { return; } var countryText = markerPaths[region][0]; var numberOfCountries = Object.keys(countryText).length; var markerBox = marker.getBBox(); var topX = markerBox.x; var bottomY = markerBox.y2; var width = region !== 'india-middle-east-and-africa' ? 150 : 200; //Add the rectangle this.exports[region] = this.raphael.rect(topX + 28, bottomY - 1, width, (21 * numberOfCountries) + 5).toBack().attr(markerAttr); //Create a set to combine countries, hover box and region icon/text set = this.raphael.set(); set.push( this.exports[region] ); //Add the country Text this._addCountryText(markerBox, countryText, topX + 28, bottomY - 1, 21, region, set); }, _addCountryText: function (markerBox, countryText, x, y, height, region, set) { var updatedX = x + 10; var updatedY = y + 10; var textAttr = { font: '13px Arial', textAlign: 'left', fill: "#ffffff", cursor: 'pointer', 'text-decoration': 'underline', 'text-anchor': 'start', opacity: 0 }; for (var country in countryText) { var text = countryText[country].toUpperCase(); this.countryText[country] = this.raphael.text(updatedX, updatedY, text).toBack().attr(textAttr); updatedY += height; set.push( this.countryText[country] ); } this.continentSets[region] = set.hide(); }, _createSets: function () { for (var region in this.markers) { var set = this.raphael.set(); set.push( this.markers[region], this.text[region] ); this.sets[region] = set; } }, _createContinentSets: function () { for (var region in this.markers) { var set = this.raphael.set(); set.push( this.markers[region], this.text[region], this.continentSets[region] ); this.sets[region] = set; } }, _initInteractiveMapEvents: function () { this._initCountryTextEvents(); this._initCountryHoverEvents(); }, _initRegularMapEvents: function () { var bounceEasing = 'cubic-bezier(0.680, -0.550, 0.265, 1.550)'; var mouseOverMarkerBounce = { transform: 's1.1' }; var mouseOverMarkerBounceWithTranslate = { transform: 's1.1t5,0' }; var mouseOutMarkerBounce = { transform: 's1' }; var mouseOverMarker = { fill: '#116697' }; var mouseOutMarker = { fill: '#f79432' }; for (var region in this.sets) { var set = this.sets[region]; var marker = this.markers[region]; var text = this.text[region]; (function (savedSet, savedRegion, savedMarker, savedText) { savedSet.attr({ cursor: 'pointer' }); savedSet.hover(function () { //A slight translation is needed for 'india-middle-east-and-africa' so when hovered it isn't clipped by container var transformAttr = savedRegion !== 'india-middle-east-and-africa' ? mouseOverMarkerBounce : mouseOverMarkerBounceWithTranslate; savedMarker.animate(transformAttr, 250, bounceEasing); savedMarker.animate(mouseOverMarker, 250, 'easeInOutExpo'); savedText.animate(transformAttr, 250, bounceEasing); }, function () { savedMarker.animate(mouseOutMarkerBounce, 250, bounceEasing); savedMarker.animate(mouseOutMarker, 250, 'easeInOutSine'); savedText.animate(mouseOutMarkerBounce, 250, bounceEasing); }); savedSet.click(function () { MapUtil.goToUrl(savedRegion, false); }); })(set, region, marker, text); } }, _initCountryHoverEvents: function () { var noHover = Detector.noSvgHover(); var mouseOverMarker = { fill: '#116697' }; var mouseOutMarker = { fill: '#f79432' }; for (var region in this.sets) { var set = this.sets[region]; var continentSet = this.continentSets[region]; var marker = this.markers[region]; var text = this.text[region]; var hoverBox = this.exports[region]; (function (savedSet, savedContinentSet, savedRegion, savedMarker, savedText, savedBox) { savedSet.attr({ cursor: 'pointer' }); if (noHover) { savedMarker.data('open', false); savedSet.click(function () { if (savedMarker.data('open') === false) { SVG._closeAllContinents(); savedMarker.data('open', true); savedMarker.animate(mouseOverMarker, 250, 'easeInOutExpo'); savedContinentSet.show().toFront().animate({ opacity: 1 }, 250, 'easeInOutExpo'); } else { savedMarker.data('open', false); savedMarker.animate(mouseOutMarker, 250, 'easeInOutSine'); savedContinentSet.animate({ opacity: 0 }, 250, 'easeInOutSine').hide().toBack(); } }); savedSet.hover(function () { savedMarker.animate(mouseOverMarker, 250, 'easeInOutExpo'); }, function () { savedMarker.data('open') === false && savedMarker.animate(mouseOutMarker, 250, 'easeInOutSine'); }); } else { savedSet.hover(function () { savedMarker.animate(mouseOverMarker, 250, 'easeInOutExpo'); savedContinentSet.show().toFront().animate({ opacity: 1 }, 250, 'easeInOutExpo'); }, function () { savedMarker.animate(mouseOutMarker, 250, 'easeInOutSine'); savedContinentSet.animate({ opacity: 0 }, 250, 'easeInOutSine').hide().toBack(); }); } })(set, continentSet, region, marker, text, hoverBox); } }, _closeAllContinents: function () { for (var region in this.sets) { var continentSet = this.continentSets[region]; var marker = this.markers[region]; var mouseOutMarker = { fill: '#f79432' }; marker.data('open', false); marker.animate(mouseOutMarker, 250, 'easeInOutSine'); continentSet.animate({ opacity: 0 }, 250, 'easeInOutSine').hide().toBack(); } }, _initCountryTextEvents: function () { for (var country in this.countryText) { var text = this.countryText[country]; (function (savedText, savedCountry) { savedText.click(function () { MapUtil.goToUrl(savedCountry, true); }); savedText.hover(function () { savedText.animate({ 'fill-opacity': 0.6 }, 250, 'easeInOutSine'); }, function () { savedText.animate({ 'fill-opacity': 1 }, 250, 'easeInOutSine'); }); })(text, country); } } }; } );
/*global module:false*/ module.exports = function(grunt) { // Project configuration. grunt.initConfig({ meta: { version: '2.0.0', banner: '/*! Ebla - v<%= meta.version %> - ' + '<%= grunt.template.today("yyyy-mm-dd") %>\n' + '* Copyright (c) <%= grunt.template.today("yyyy") %> ' + 'Monospaced */' }, concat: { dist: { src: ['<banner:meta.banner>', 'javascripts/libs/jquery.cookie.js', 'javascripts/ebla/ebla.js', 'javascripts/ebla/debug.js', 'javascripts/ebla/flash-message.js', 'javascripts/ebla/compatibility.js', 'javascripts/ebla/elements.js', 'javascripts/ebla/controls.js', 'javascripts/ebla/data.js', 'javascripts/ebla/images.js', 'javascripts/ebla/layout.js', 'javascripts/ebla/loader.js', 'javascripts/ebla/navigation.js', 'javascripts/ebla/navigation.event.js', 'javascripts/ebla/navigation.keyboard.js', 'javascripts/ebla/placesaver.js', 'javascripts/ebla/progress.js', 'javascripts/ebla/resize.js', 'javascripts/ebla/toc.js', 'javascripts/ebla/init.js', 'javascripts/ebla/book.js'], dest: 'javascripts/ebla.js' } }, uglify: { dist: { src: ['<banner:meta.banner>', 'javascripts/ebla.js'], dest: 'javascripts/ebla.min.js' } }, sass: { dist: { options: { style: 'compressed' }, files: { 'stylesheets/ebla.css': 'stylesheets/ebla.scss', 'stylesheets/book.css': 'stylesheets/book.scss' } } }, watch: { files: ['javascripts/ebla/*.js', 'stylesheets/*.scss'], tasks: ['sass', 'concat', 'uglify'] }, jshint: { files: ['Gruntfile.js', 'javascripts/ebla.js'], options: { curly: true, eqeqeq: true, immed: true, latedef: true, newcap: true, noarg: true, sub: true, undef: true, boss: true, eqnull: true, browser: true, jquery: true, devel: true, globals: { Modernizr: true, debug: true, bookData: true, bookJson: true } }, } }); grunt.loadNpmTasks('grunt-contrib-concat'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-sass'); // Default task. grunt.registerTask('default', ['sass', 'concat', 'jshint', 'uglify']); };
import {Chart} from 'react-google-charts'; import React, {Component, PropTypes} from 'react'; import DataFormatter from '../../utils/DataFormatter'; class EnvyBarChart extends Component { constructor(props) { super(props); this.state={ options:{ hAxis: {title: 'Event Type'}, vAxis: {title: 'Envy Events'}, legend: 'none', }, }; } generateGraph(events) { var formatter = new DataFormatter(); var result = formatter.generateEnvyGraph(events); return result; } render() { var data = this.generateGraph(this.props.events); return ( <Chart chartType="ColumnChart" data={data} options={this.state.options} graph_id="EnvyBarChart" width='40vw' height='50vh' /> ); } }; EnvyBarChart.propTypes = { events: PropTypes.array.isRequired } export default EnvyBarChart;
"use strict"; let mongoose = require('mongoose'), Schema = mongoose.Schema, EmailValidator = require('./emailValidator'); class User { constructor(explicitConnection) { this.explicitConnection = explicitConnection; this.schema = new Schema({ email: { type: 'string', trim: true, required: true }, organization: { type: 'string', trim: true, required: true }, password: {type: 'string', required: true}, isVisibleAccount: {type: 'boolean'}, userApiKey: {type: 'string'}, userApiSecret: {type: 'string'}, linkedApps: {}, avatarProto: {type: 'string'}, gmailAccount: {type: 'string'}, facebookAccount: {type: 'string'}, twitterAccount: {type: 'string'}, fullname: {type: 'string'}, loginHistories: [], changeProfileHistories: [], changeAuthorizationHistories: [], sparqlQuestions: [], blockingHistories: [], authorizations: {}, tripleUsage: {type: 'number', default: 0}, tripleUsageHistory: [], isBlocked: { type: 'boolean', required: true }, blockedCause: { type: 'string', } }).index({ email: 1, organization: 1 }, { unique: true }); } getModel() { if (this.explicitConnection === undefined) { return mongoose.model('User', this.schema); } else { return this.explicitConnection.model('User', this.schema); } } } module.exports = User;
module.export = { };
(function (ns) { // dependencies var assert = require('assert'); var esgraph = require('esgraph'); var worklist = require('analyses'); var common = require("../../base/common.js"); var Context = require("../../base/context.js"); var Base = require("../../base/index.js"); var codegen = require('escodegen'); var annotateRight = require("./infer_expression.js"); var InferenceScope = require("./registry/").InferenceScope; var System = require("./registry/system.js"); var Annotations = require("./../../type-system/annotation.js"); var walk = require('estraverse'); var Tools = require("../settools.js"); var Shade = require("../../interfaces.js"); var walkes = require('walkes'); var validator = require('../validator'); var TypeInfo = require("../../type-system/typeinfo.js").TypeInfo; // shortcuts var Syntax = common.Syntax; var Set = worklist.Set; var FunctionAnnotation = Annotations.FunctionAnnotation; var ANNO = Annotations.ANNO; function findConstantsFor(ast, names, constantVariables) { var result = new Set(), annotation, name, formerValue; constantVariables = constantVariables ? constantVariables.values() : []; walkes(ast, { AssignmentExpression: function(recurse) { if (this.left.type != Syntax.Identifier) { Shade.throwError(ast, "Can't find constant for computed left expression"); } name = this.left.name; if(names.has(name)) { annotation = ANNO(this.right); if(annotation.hasConstantValue()) { switch(this.operator) { case "=": result.add({ name: name, constant: TypeInfo.copyStaticValue(annotation)}); break; case "-=": case "+=": case "*=": case "/=": formerValue = constantVariables.filter(function(v){ return v.name == name; }); if(formerValue.length) { var c = formerValue[0].constant, v; switch(this.operator) { case "+=": v = c + TypeInfo.copyStaticValue(annotation); break; case "-=": v = c - TypeInfo.copyStaticValue(annotation); break; case "*=": v = c * TypeInfo.copyStaticValue(annotation); break; case "/=": v = c / TypeInfo.copyStaticValue(annotation); break; } result.add({ name: name, constant: v}); } break; default: assert(!this.operator); } } } recurse(this.right); }, VariableDeclarator: function(recurse) { name = this.id.name; if (this.init && names.has(name)) { annotation = ANNO(this.init); if(annotation.hasConstantValue()) { result.add({ name: name, constant: TypeInfo.copyStaticValue(annotation)}); } } recurse(this.init); }, UpdateExpression: function(recurse) { if(this.argument.type == Syntax.Identifier) { name = this.argument.name; annotation = ANNO(this); if(annotation.hasConstantValue()) { var value = TypeInfo.copyStaticValue(annotation); if (!this.prefix) { value = this.operator == "--" ? --value : ++value; } result.add({ name: name, constant: value}); } } } }); return result; } /** * * @param ast * @param {AnalysisContext} context * @param {*} opt * @constructor */ var TypeInference = function (ast, context, opt) { opt = opt || {}; this.context = context; this.propagateConstants = opt.propagateConstants || false; }; Base.extend(TypeInference.prototype, { /** * @param {*} ast * @param {*} opt * @returns {*} */ inferBody: function (ast, opt) { var cfg = esgraph(ast, { omitExceptions: true }), context = this.context, propagateConstants = this.propagateConstants; //console.log("infer body", cfg) var result = worklist(cfg, /** * @param {Set} input * @this {FlowNode} * @returns {*} */ function (input) { if (!this.astNode || this.type) // Start and end node do not influence the result return input; //console.log("Analyze", codegen.generate(this.astNode), this.astNode.type); // Local if(propagateConstants) { this.kill = this.kill || Tools.findVariableAssignments(this.astNode, true); } annotateRight(context, this.astNode, propagateConstants ? input : null ); this.decl = this.decl || context.declare(this.astNode); //context.computeConstants(this.astNode, input); if(!propagateConstants) { return input; } var filteredInput = null, generate = null; if (this.kill.size) { // Only if there's an assignment, we need to generate generate = findConstantsFor(this.astNode, this.kill, propagateConstants ? input : null); var that = this; filteredInput = new Set(input.filter(function (elem) { return !that.kill.some(function(tokill) { return elem.name == tokill }); })); } var result = Set.union(filteredInput || input, generate); // console.log("input:", input); // console.log("kill:", this.kill); // console.log("generate:", generate); // console.log("filteredInput:", filteredInput); // console.log("result:", result); return result; } , { direction: 'forward', merge: worklist.merge(function(a,b) { if (!a && !b) return null; //console.log("Merge", a && a.values(), b && b.values()) var result = Set.intersect(a, b); //console.log("Result", result && result.values()) return result; }) }); //Tools.printMap(result, cfg); return ast; } }); /** * * @param ast * @param {AnalysisContext} context * @param opt * @returns {*} */ var inferProgram = function (ast, context, opt) { opt = opt || {}; //var globalScope = createGlobalScope(ast); //registerSystemInformation(globalScope, opt); var typeInference = new TypeInference(ast, context, opt); var result = typeInference.inferBody(ast, opt); return result; }; ns.infer = inferProgram; }(exports));
import React, { Component, PropTypes } from 'react'; import { connect } from 'react-redux'; import moment from 'moment'; import { toggleSelect } from '../actions/users'; import { createLink } from '../../utils'; class User extends Component { render() { const profile_image_url_https = this.props.user.profile_image_url_https ? this.props.user.profile_image_url_https.replace('normal', 'bigger') : ''; const small_profile_image_url_https = this.props.user.profile_image_url_https ? this.props.user.profile_image_url_https.replace('normal', 'mini') : ''; var description = this.props.user.description; if(description) { description = description.replace(/@[A-Za-z_0-9]+/g, id => createLink(`https://twitter.com/${id.substring(1)}`, id)); this.props.user.entities.description.urls.forEach(url => description = description.replace(new RegExp(url.url, 'g'), createLink(url.expanded_url, url.expanded_url))); } return this.props.settings.showMode === 'card' ? ( <li className={'responsive-card ' + (this.props.user.select ? 'responsive-card--selected' : '')}> <input type="checkbox" checked={this.props.user.select} className="user__select" onChange={this.props.toggleSelect} /> <div alt="" className="card-img-top" style={{ backgroundImage: this.props.user.profile_banner_url ? `url(${this.props.user.profile_banner_url + '/600x200'})` : 'none', backgroundColor: !this.props.user.profile_banner_url ? `#${this.props.user.profile_link_color}` : 'transparent' }} onClick={this.props.toggleSelect}></div> <div className="card-block"> <div className="media"> <div className="media-left"> <img src={profile_image_url_https} width="73" height="73" className="media-left__icon" /> </div> <div className="media-body"> <div className="card-title"> <div className="card-title__name"> {this.props.user.name} </div> <div className="card-title__screen-name"> <small> <a href={`https://twitter.com/${this.props.user.screen_name}`} target="_new" title={this.props.user.id_str}>@{this.props.user.screen_name}</a> {this.props.user.protected ? ( <span> &nbsp;<i className="fa fa-lock"></i> </span> ) : null} </small> </div> </div> </div> </div> </div> <ul className="list-group list-group-flush"> { this.props.user.entities && this.props.user.entities.url ? ( <li className="list-group-item"> <a href={this.props.user.entities.url.urls[0].url} target="_new"> <i className="fa fa-link fa-fw"></i> {this.props.user.entities.url.urls[0].expanded_url ? this.props.user.entities.url.urls[0].expanded_url : this.props.user.entities.url.urls[0].url}</a> </li> ) : null } { this.props.user.location ? ( <li className="list-group-item"> <i className="fa fa-map-marker fa-fw"></i> {this.props.user.location} </li> ) : null } </ul> {this.props.user.entities && !this.props.user.entities.url && !this.props.user.location ? <hr /> : null} <div className="card-block"> <p className="card-text" dangerouslySetInnerHTML={{__html: description}}> </p> </div> </li> ) : ( <tr onClick={e => { if(['A', 'INPUT'].includes(e.target.tagName)) { e.stopPropagation(); } else { this.props.toggleSelect(); } }}> <td className="user-list-table__checkbox user-list-table__checkbox--row"> <input type="checkbox" checked={this.props.user.select} onChange={this.props.toggleSelect} /> </td> <td className="user-list-table__name user-list-table__name--row"><img src={small_profile_image_url_https} width="24" height="24" /> {this.props.user.name}</td> <td> <a href={`https://twitter.com/${this.props.user.screen_name}`} target="_new">{this.props.user.screen_name}</a> {this.props.user.protected ? ( <span> &nbsp;<i className="fa fa-lock"></i> </span> ) : null} </td> <td>{this.props.user.friends_count}</td> <td>{this.props.user.followers_count}</td> <td>{this.props.user.status ? moment(new Date(this.props.user.status.created_at)).format('YYYY/MM/DD HH:mm:ss') : null}</td> </tr> ); } } User.propTypes = { userId: PropTypes.string.isRequired, user: PropTypes.object.isRequired, settings: PropTypes.object.isRequired }; User.defaultProps = { userId: '0', user: {}, settings: {} }; function mapStateToProps(state, ownProps) { return { user: state.users.users.allUserInfo[ownProps.userId], settings: state.settings }; } function mapDispatchToProps(dispatch, ownProps) { return { toggleSelect() { dispatch(toggleSelect(ownProps.userId)); } }; } export default connect(mapStateToProps, mapDispatchToProps)(User);
/*** * Textile parser for JavaScript * * Copyright (c) 2012 Borgar Þorsteinsson (MIT License). * */ /*jshint laxcomma:true laxbreak:true eqnull:true loopfunc:true sub:true */ ;(function(){ "use strict"; /*** * Regular Expression helper methods * * This provides the `re` object, which contains several helper * methods for working with big regular expressions (soup). * */ var re = { _cache: {} , pattern: { 'punct': "[!-/:-@\\[\\\\\\]-`{-~]" , 'space': '\\s' } , escape: function ( src ) { return src.replace( /[\-\[\]\{\}\(\)\*\+\?\.\,\\\^\$\|\#\s]/g, "\\$&" ); } , collapse: function ( src ) { return src.replace( /(?:#.*?(?:\n|$))/g, '' ) .replace( /\s+/g, '' ) ; } , expand_patterns: function ( src ) { // TODO: provide escape for patterns: \[:pattern:] ? return src.replace( /\[\:\s*(\w+)\s*\:\]/g, function ( m, k ) { return ( k in re.pattern ) ? re.expand_patterns( re.pattern[ k ] ) : k ; }) ; } , isRegExp: function ( r ) { return Object.prototype.toString.call( r ) === "[object RegExp]"; } , compile: function ( src, flags ) { if ( re.isRegExp( src ) ) { if ( arguments.length === 1 ) { // no flags arg provided, use the RegExp one flags = ( src.global ? 'g' : '' ) + ( src.ignoreCase ? 'i' : '' ) + ( src.multiline ? 'm' : '' ); } src = src.source; } // don't do the same thing twice var ckey = src + ( flags || '' ); if ( ckey in re._cache ) { return re._cache[ ckey ]; } // allow classes var rx = re.expand_patterns( src ); // allow verbose expressions if ( flags && /x/.test( flags ) ) { rx = re.collapse( rx ); } // allow dotall expressions if ( flags && /s/.test( flags ) ) { rx = rx.replace( /([^\\])\./g, '$1[^\\0]' ); } // TODO: test if MSIE and add replace \s with [\s\u00a0] if it is? // clean flags and output new regexp flags = ( flags || '' ).replace( /[^gim]/g, '' ); return ( re._cache[ ckey ] = new RegExp( rx, flags ) ); } }; /*** * JSONML helper methods - http://www.jsonml.org/ * * This provides the `JSONML` object, which contains helper * methods for rendering JSONML to HTML. * * Note that the tag ! is taken to mean comment, this is however * not specified in the JSONML spec. * */ var JSONML = { escape: function ( text, esc_quotes ) { return text.replace( /&(?!(#\d{2,}|#x[\da-fA-F]{2,}|[a-zA-Z][a-zA-Z1-4]{1,6});)/g, "&amp;" ) .replace( /</g, "&lt;" ) .replace( />/g, "&gt;" ) .replace( /"/g, esc_quotes ? "&quot;" : '"' ) .replace( /'/g, esc_quotes ? "&#39;" : "'" ) ; } , toHTML: function ( jsonml ) { jsonml = jsonml.concat(); // basic case if ( typeof jsonml === "string" ) { return JSONML.escape( jsonml ); } var tag = jsonml.shift() , attributes = {} , content = [] , tag_attrs = "" , a ; if ( jsonml.length && typeof jsonml[ 0 ] === "object" && !_isArray( jsonml[ 0 ] ) ) { attributes = jsonml.shift(); } while ( jsonml.length ) { content.push( JSONML.toHTML( jsonml.shift() ) ); } for ( a in attributes ) { tag_attrs += ( attributes[ a ] == null ) ? " " + a : " " + a + '="' + JSONML.escape( String( attributes[ a ] ), true ) + '"' ; } // be careful about adding whitespace here for inline elements if ( tag == "!" ) { return "<!--" + content.join( "" ) + "-->"; } else if ( tag === "img" || tag === "br" || tag === "hr" || tag === "input" ) { return "<" + tag + tag_attrs + " />"; } else { return "<" + tag + tag_attrs + ">" + content.join( "" ) + "</" + tag + ">"; } } }; // merge object b properties into obect a function merge ( a, b ) { for ( var k in b ) { a[ k ] = b[ k ]; } return a; } var _isArray = Array.isArray || function ( a ) { return Object.prototype.toString.call(a) === '[object Array]'; }; /* expressions */ re.pattern[ 'blocks' ] = '(?:b[qc]|div|notextile|pre|h[1-6]|fn\\d+|p|###)'; re.pattern[ 'pba_class' ] = '\\([^\\)]+\\)'; re.pattern[ 'pba_style' ] = '\\{[^\\}]+\\}'; re.pattern[ 'pba_lang' ] = '\\[[^\\[\\]]+\\]'; re.pattern[ 'pba_align' ] = '(?:<>|<|>|=)'; re.pattern[ 'pba_pad' ] = '[\\(\\)]+'; re.pattern[ 'pba_attr' ] = '(?:[:pba_class:]|[:pba_style:]|[:pba_lang:]|[:pba_align:]|[:pba_pad:])*'; re.pattern[ 'url_punct' ] = '[.,«»″‹›!?]'; re.pattern[ 'html_id' ] = '[a-zA-Z][a-zA-Z\\d:]*'; re.pattern[ 'html_attr' ] = '(?:"[^"]+"|\'[^\']+\'|[^>\\s]+)'; re.pattern[ 'tx_urlch' ] = '[\\w"$\\-_.+!*\'(),";\\/?:@=&%#{}|\\\\^~\\[\\]`]'; re.pattern[ 'tx_cite' ] = ':((?:[^\\s()]|\\([^\\s()]+\\)|[()])+?)(?=[!-\\.:-@\\[\\\\\\]-`{-~]+(?:$|\\s)|$|\\s)'; re.pattern[ 'listhd' ] = '[\\t ]*[\\#\\*]*(\\*|\\#(?:_|\\d+)?)[:pba_attr:](?: \\S|\\.\\s*(?=\\S|\\n))'; re.pattern[ 'ucaps' ] = "A-Z"+ // Latin extended À-Þ "\u00c0-\u00d6\u00d8-\u00de"+ // Latin caps with embelishments and ligatures... "\u0100\u0102\u0104\u0106\u0108\u010a\u010c\u010e\u0110\u0112\u0114\u0116\u0118\u011a\u011c\u011e\u0120\u0122\u0124\u0126\u0128\u012a\u012c\u012e\u0130\u0132\u0134\u0136\u0139\u013b\u013d\u013f"+ "\u0141\u0143\u0145\u0147\u014a\u014c\u014e\u0150\u0152\u0154\u0156\u0158\u015a\u015c\u015e\u0160\u0162\u0164\u0166\u0168\u016a\u016c\u016e\u0170\u0172\u0174\u0176\u0178\u0179\u017b\u017d"+ "\u0181\u0182\u0184\u0186\u0187\u0189-\u018b\u018e-\u0191\u0193\u0194\u0196-\u0198\u019c\u019d\u019f\u01a0\u01a2\u01a4\u01a6\u01a7\u01a9\u01ac\u01ae\u01af\u01b1-\u01b3\u01b5\u01b7\u01b8\u01bc"+ "\u01c4\u01c7\u01ca\u01cd\u01cf\u01d1\u01d3\u01d5\u01d7\u01d9\u01db\u01de\u01e0\u01e2\u01e4\u01e6\u01e8\u01ea\u01ec\u01ee\u01f1\u01f4\u01f6-\u01f8\u01fa\u01fc\u01fe"+ "\u0200\u0202\u0204\u0206\u0208\u020a\u020c\u020e\u0210\u0212\u0214\u0216\u0218\u021a\u021c\u021e\u0220\u0222\u0224\u0226\u0228\u022a\u022c\u022e\u0230\u0232\u023a\u023b\u023d\u023e"+ "\u0241\u0243-\u0246\u0248\u024a\u024c\u024e"+ "\u1e00\u1e02\u1e04\u1e06\u1e08\u1e0a\u1e0c\u1e0e\u1e10\u1e12\u1e14\u1e16\u1e18\u1e1a\u1e1c\u1e1e\u1e20\u1e22\u1e24\u1e26\u1e28\u1e2a\u1e2c\u1e2e\u1e30\u1e32\u1e34\u1e36\u1e38\u1e3a\u1e3c\u1e3e\u1e40"+ "\u1e42\u1e44\u1e46\u1e48\u1e4a\u1e4c\u1e4e\u1e50\u1e52\u1e54\u1e56\u1e58\u1e5a\u1e5c\u1e5e\u1e60\u1e62\u1e64\u1e66\u1e68\u1e6a\u1e6c\u1e6e\u1e70\u1e72\u1e74\u1e76\u1e78\u1e7a\u1e7c\u1e7e"+ "\u1e80\u1e82\u1e84\u1e86\u1e88\u1e8a\u1e8c\u1e8e\u1e90\u1e92\u1e94\u1e9e\u1ea0\u1ea2\u1ea4\u1ea6\u1ea8\u1eaa\u1eac\u1eae\u1eb0\u1eb2\u1eb4\u1eb6\u1eb8\u1eba\u1ebc\u1ebe"+ "\u1ec0\u1ec2\u1ec4\u1ec6\u1ec8\u1eca\u1ecc\u1ece\u1ed0\u1ed2\u1ed4\u1ed6\u1ed8\u1eda\u1edc\u1ede\u1ee0\u1ee2\u1ee4\u1ee6\u1ee8\u1eea\u1eec\u1eee\u1ef0\u1ef2\u1ef4\u1ef6\u1ef8\u1efa\u1efc\u1efe"+ "\u2c60\u2c62-\u2c64\u2c67\u2c69\u2c6b\u2c6d-\u2c70\u2c72\u2c75\u2c7e\u2c7f"+ "\ua722\ua724\ua726\ua728\ua72a\ua72c\ua72e\ua732\ua734\ua736\ua738\ua73a\ua73c\ua73e"+ "\ua740\ua742\ua744\ua746\ua748\ua74a\ua74c\ua74e\ua750\ua752\ua754\ua756\ua758\ua75a\ua75c\ua75e\ua760\ua762\ua764\ua766\ua768\ua76a\ua76c\ua76e\ua779\ua77b\ua77d\ua77e"+ "\ua780\ua782\ua784\ua786\ua78b\ua78d\ua790\ua792\ua7a0\ua7a2\ua7a4\ua7a6\ua7a8\ua7aa"; var re_block = re.compile( /^([:blocks:])/ ) , re_block_se = re.compile( /^[:blocks:]$/ ) , re_block_normal = re.compile( /^(.*?)($|\r?\n(?=[:listhd:])|\r?\n(?:\s*\n|$)+)/, 's' ) , re_block_extended = re.compile( /^(.*?)($|\r?\n(?=[:listhd:])|\r?\n+(?=[:blocks:][:pba_attr:]\.))/, 's' ) , re_ruler = /^(\-\-\-+|\*\*\*+|___+)(\r?\n\s+|$)/ , re_list = re.compile( /^((?:[:listhd:][^\0]*?(?:\r?\n|$))+)(\s*\n|$)/,'s' ) , re_list_item = re.compile( /^([\#\*]+)([^\0]+?)(\n(?=[:listhd:])|$)/, 's' ) , re_deflist = /^((?:- (?:[^\n]\n?)+?)+:=(?: *\n[^\0]+?=:(?:\n|$)|(?:[^\0]+?(?:$|\n(?=\n|- )))))+/ , re_deflist_item = /^((?:- (?:[^\n]\n?)+?)+):=( *\n[^\0]+?=:\s*(?:\n|$)|(?:[^\0]+?(?:$|\n(?=\n|- ))))/ , re_table = re.compile( /^((?:table[:pba_attr:]\.\n)?(?:(?:[:pba_attr:]\.[^\n\S]*)?\|.*?\|[^\n\S]*(?:\n|$))+)([^\n\S]*\n)?/, 's' ) , re_table_head = /^table(_?)([^\n]+)\.\s?\n/ , re_table_row = re.compile( /^([:pba_attr:]\.[^\n\S]*)?\|(.*?)\|[^\n\S]*(\n|$)/, 's' ) , re_fenced_phrase = /^\[(__?|\*\*?|\?\?|[\-\+\^~@%])([^\n]+)\1\]/ , re_phrase = /^([\[\{]?)(__?|\*\*?|\?\?|[\-\+\^~@%])/ , re_text = re.compile( /^.+?(?=[\\<!\[_\*`]|\n|$)/, 's' ) , re_image = re.compile( /^!(?!\s)([:pba_attr:](?:\.[^\n\S]|\.(?:[^\.\/]))?)([^!\s]+?) ?(?:\(((?:[^\(\)]+|\([^\(\)]+\))+)\))?!(?::([^\s]+?(?=[!-\.:-@\[\\\]-`{-~](?:$|\s)|\s|$)))?/ ) , re_image_fenced = re.compile( /^\[!(?!\s)([:pba_attr:](?:\.[^\n\S]|\.(?:[^\.\/]))?)([^!\s]+?) ?(?:\(((?:[^\(\)]+|\([^\(\)]+\))+)\))?!(?::([^\s]+?(?=[!-\.:-@\[\\\]-`{-~](?:$|\s)|\s|$)))?\]/ ) // NB: there is an exception in here to prevent matching "TM)" , re_caps = re.compile( /^((?!TM\)|tm\))[[:ucaps:]](?:[[:ucaps:]\d]{1,}(?=\()|[[:ucaps:]\d]{2,}))(?:\((.*?)\))?(?=\W|$)/ ) , re_link = re.compile( /^"(?!\s)((?:[^\n"]|"(?![\s:])[^\n"]+"(?!:))+)"[:tx_cite:]/ ) , re_link_fenced = /^\["([^\n]+?)":((?:\[[a-z0-9]*\]|[^\]])+)\]/ , re_link_ref = re.compile( /^\[([^\]]+)\]((?:https?:\/\/|\/)\S+)(?:\s*\n|$)/ ) , re_link_title = /\s*\(((?:\([^\(\)]*\)|[^\(\)])+)\)$/ , re_footnote_def = /^fn\d+$/ , re_footnote = /^\[(\d+)(\!?)\]/ // HTML , re_html_tag_block = re.compile( /^\s*<([:html_id:](?::[a-zA-Z\d]+)*)((?:\s[^=\s\/]+(?:\s*=\s*[:html_attr:])?)+)?\s*(\/?)>(\n*)/ ) , re_html_tag = re.compile( /^<([:html_id:])((?:\s[^=\s\/]+(?:\s*=\s*[:html_attr:])?)+)?\s*(\/?)>(\n*)/ ) , re_html_comment = re.compile( /^<!--(.+?)-->/, 's' ) , re_html_end_tag = re.compile( /^<\/([:html_id:])([^>]*)>/ ) , re_html_attr = re.compile( /^\s*([^=\s]+)(?:\s*=\s*("[^"]+"|'[^']+'|[^>\s]+))?/ ) , re_entity = /&(#\d\d{2,}|#x[\da-fA-F]{2,}|[a-zA-Z][a-zA-Z1-4]{1,6});/ // glyphs , re_dimsign = /([\d\.,]+['"]? ?)x( ?)(?=[\d\.,]['"]?)/g , re_emdash = /(^|[\s\w])--([\s\w]|$)/g , re_trademark = /(\b ?|\s|^)(?:\((?:TM|tm)\)|\[(?:TM|tm)\])/g , re_registered = /(\b ?|\s|^)(?:\(R\)|\[R\])/gi , re_copyright = /(\b ?|\s|^)(?:\(C\)|\[C\])/gi , re_apostrophe = /(\w)\'(\w)/g , re_double_prime = re.compile( /(\d*[\.,]?\d+)"(?=\s|$|[:punct:])/g ) , re_single_prime = re.compile( /(\d*[\.,]?\d+)'(?=\s|$|[:punct:])/g ) , re_closing_dquote = re.compile( /([^\s\[\(])"(?=$|\s|[:punct:])/g ) , re_closing_squote = re.compile( /([^\s\[\(])'(?=$|\s|[:punct:])/g ) // pba , re_pba_classid = /^\(([^\(\)\n]+)\)/ , re_pba_padding_l = /^(\(+)/ , re_pba_padding_r = /^(\)+)/ , re_pba_align_blk = /^(<>|<|>|=)/ , re_pba_align_img = /^(<|>|=)/ , re_pba_valign = /^(~|\^|\-)/ , re_pba_colspan = /^\\(\d+)/ , re_pba_rowspan = /^\/(\d+)/ , re_pba_styles = /^\{([^\}]*)\}/ , re_pba_css = /^\s*([^:\s]+)\s*:\s*(.+)\s*$/ , re_pba_lang = /^\[([^\[\]\n]+)\]/ ; var phrase_convert = { '*': 'strong' , '**': 'b' , '??': 'cite' , '_': 'em' , '__': 'i' , '-': 'del' , '%': 'span' , '+': 'ins' , '~': 'sub' , '^': 'sup' , '@': 'code' }; // area, base, basefont, bgsound, br, col, command, embed, frame, hr, // img, input, keygen, link, meta, param, source, track or wbr var html_singletons = { 'br': 1 , 'hr': 1 , 'img': 1 , 'link': 1 , 'meta': 1 , 'wbr': 1 , 'area': 1 , 'param': 1 , 'input': 1 , 'option': 1 , 'base': 1 }; var pba_align_lookup = { '<': 'left' , '=': 'center' , '>': 'right' , '<>': 'justify' }; var pba_valign_lookup = { '~':'bottom' , '^':'top' , '-':'middle' }; // HTML tags allowed in the document (root) level that trigger HTML parsing var allowed_blocktags = { 'p': 0 , 'hr': 0 , 'ul': 1 , 'ol': 0 , 'li': 0 , 'div': 1 , 'pre': 0 , 'object': 1 , 'script': 0 , 'noscript': 0 , 'blockquote': 1 , 'notextile': 1 }; function ribbon ( feed ) { var _slot = null , org = feed + '' , pos = 0 ; return { save: function () { _slot = pos; } , load: function () { pos = _slot; feed = org.slice( pos ); } , advance: function ( n ) { pos += ( typeof n === 'string' ) ? n.length : n; return ( feed = org.slice( pos ) ); } , lookbehind: function ( nchars ) { nchars = nchars == null ? 1 : nchars; return org.slice( pos - nchars, pos ); } , startsWith: function ( s ) { return feed.substring(0, s.length) === s; } , valueOf: function(){ return feed; } , toString: function(){ return feed; } }; } function builder ( arr ) { var _arr = _isArray( arr ) ? arr : []; return { add: function ( node ) { if ( typeof node === 'string' && typeof _arr[_arr.length - 1 ] === 'string' ) { // join if possible _arr[ _arr.length - 1 ] += node; } else if ( _isArray( node ) ) { var f = node.filter(function(s){ return s !== undefined; }); _arr.push( f ); } else if ( node ) { _arr.push( node ); } return this; } , merge: function ( s ) { for (var i=0,l=s.length; i<l; i++) { this.add( s[i] ); } return this; } , linebreak: function () { if ( _arr.length ) { this.add( '\n' ); } } , get: function () { return _arr; } }; } function copy_pba ( s, blacklist ) { if ( !s ) { return undefined; } var k, d = {}; for ( k in s ) { if ( k in s && ( !blacklist || !(k in blacklist) ) ) { d[ k ] = s[ k ]; } } return d; } function parse_html_attr ( attr ) { // parse ATTR and add to element var _attr = {} , m , val ; while ( (m = re_html_attr.exec( attr )) ) { _attr[ m[1] ] = ( typeof m[2] === 'string' ) ? m[2].replace( /^(["'])(.*)\1$/, '$2' ) : null ; attr = attr.slice( m[0].length ); } return _attr; } // This "indesciminately" parses HTML text into a list of JSON-ML element // No steps are taken however to prevent things like <table><p><td> - user can still create nonsensical but "well-formed" markup function parse_html ( src, whitelist_tags ) { var org = src + '' , list = [] , root = list , _stack = [] , m , oktag = whitelist_tags ? function ( tag ) { return tag in whitelist_tags; } : function () { return true; } , tag ; src = (typeof src === 'string') ? ribbon( src ) : src; // loop do { if ( (m = re_html_comment.exec( src )) && oktag('!') ) { src.advance( m[0] ); list.push( [ '!', m[1] ] ); } // end tag else if ( (m = re_html_end_tag.exec( src )) && oktag(m[1]) ) { tag = m[1]; var junk = m[2]; if ( _stack.length ) { for (var i=_stack.length-1; i>=0; i--) { var head = _stack[i]; if ( head[0] === tag ) { _stack.splice( i ); list = _stack[ _stack.length - 1 ] || root; break; } } } src.advance( m[0] ); } // open/void tag else if ( (m = re_html_tag.exec( src )) && oktag(m[1]) ) { src.advance( m[0] ); tag = m[1]; var single = m[3] || m[1] in html_singletons , tail = m[4] , element = [ tag ] ; // attributes if ( m[2] ) { element.push( parse_html_attr( m[2] ) ); } // tag if ( single ) { // single tag // let us add the element and continue our quest... list.push( element ); if ( tail ) { list.push( tail ); } } else { // open tag if ( tail ) { element.push( tail ); } // TODO: some things auto close other things: <td>, <li>, <p>, <table> // if ( tag === 'p' && _stack.length ) { // var seek = /^(p)$/; // for (var i=_stack.length-1; i>=0; i--) { // var head = _stack[i]; // if ( seek.test( head[0] ) /* === tag */ ) { // //src.advance( m[0] ); // _stack.splice( i ); // list = _stack[i] || root; // } // } // } // TODO: some elements can move parser into "text" mode // style, xmp, iframe, noembed, noframe, textarea, title, script, noscript, plaintext //if ( /^(script)$/.test( tag ) ) { } _stack.push( element ); list.push( element ); list = element; } } else { // no match, move by all "uninteresting" chars m = /([^<]+|[^\0])/.exec( src ); if ( m ) { list.push( m[0] ); } src.advance( m ? m[0].length || 1 : 1 ); } } while ( src.valueOf() ); return root; } /* attribute parser */ function parse_attr ( input, element, end_token ) { /* The attr bit causes massive problems for span elements when parentheses are used. Parentheses are a total mess and, unsurprisingly, cause trip-ups: RC: `_{display:block}(span) span (span)_` -> `<em style="display:block;" class="span">(span) span (span)</em>` PHP: `_{display:block}(span) span (span)_` -> `<em style="display:block;">(span) span (span)</em>` PHP and RC seem to mostly solve this by not parsing a final attr parens on spans if the following character is a non-space. I've duplicated that: Class/ID is not matched on spans if it is followed by `end_token` or <space>. Lang is not matched here if it is followed by the end token. Theoretically I could limit the lang attribute to /^\[[a-z]{2+}(\-[a-zA-Z0-9]+)*\]/ because Textile is layered on top of HTML which only accepts valid BCP 47 language tags, but who knows what atrocities are being preformed out there in the real world. So this attempts to emulate the other libraries. */ input += ''; if ( !input || element === 'notextile' ) { return undefined; } var m , st = {} , o = { 'style': st } , remaining = input , is_block = element === 'table' || element === 'td' || re_block_se.test( element ) // "in" test would be better but what about fn#.? , is_img = element === 'img' , is_list = element === 'li' , is_phrase = !is_block && !is_img && element !== 'a' , re_pba_align = ( is_img ) ? re_pba_align_img : re_pba_align_blk ; do { if ( (m = re_pba_styles.exec( remaining )) ) { m[1].split(';').forEach(function(p){ var d = p.match( re_pba_css ); if ( d ) { st[ d[1] ] = d[2]; } }); remaining = remaining.slice( m[0].length ); continue; } if ( (m = re_pba_lang.exec( remaining )) ) { var rm = remaining.slice( m[0].length ); if ( ( !rm && is_phrase ) || ( end_token && end_token === rm.slice(0,end_token.length) ) ) { m = null; } else { o['lang'] = m[1]; remaining = remaining.slice( m[0].length ); } continue; } if ( (m = re_pba_classid.exec( remaining )) ) { var rm = remaining.slice( m[0].length ); if ( ( !rm && is_phrase ) || ( end_token && (rm[0] === ' ' || end_token === rm.slice(0,end_token.length)) ) ) { m = null; } else { var bits = m[1].split( '#' ); if ( bits[0] ) { o['class'] = bits[0]; } if ( bits[1] ) { o['id'] = bits[1]; } remaining = rm; } continue; } if ( is_block || is_list ) { if ( (m = re_pba_padding_l.exec( remaining )) ) { st[ "padding-left" ] = ( m[1].length ) + "em"; remaining = remaining.slice( m[0].length ); continue; } if ( (m = re_pba_padding_r.exec( remaining )) ) { st[ "padding-right" ] = ( m[1].length ) + "em"; remaining = remaining.slice( m[0].length ); continue; } } // only for blocks: if ( is_img || is_block || is_list ) { if ( (m = re_pba_align.exec( remaining )) ) { var align = pba_align_lookup[ m[1] ]; if ( is_img ) { o[ 'align' ] = align; } else { st[ 'text-align' ] = align; } remaining = remaining.slice( m[0].length ); continue; } } // only for table cells if ( element === 'td' || element === 'tr' ) { if ( (m = re_pba_valign.exec( remaining )) ) { st[ "vertical-align" ] = pba_valign_lookup[ m[1] ]; remaining = remaining.slice( m[0].length ); continue; } } if ( element === 'td' ) { if ( (m = re_pba_colspan.exec( remaining )) ) { o[ "colspan" ] = m[1]; remaining = remaining.slice( m[0].length ); continue; } if ( (m = re_pba_rowspan.exec( remaining )) ) { o[ "rowspan" ] = m[1]; remaining = remaining.slice( m[0].length ); continue; } } } while ( m ); // collapse styles var s = []; for ( var v in st ) { s.push( v + ':' + st[v] ); } if ( s.length ) { o.style = s.join(';'); } else { delete o.style; } return remaining == input ? undefined : [ input.length - remaining.length, o ] ; } /* glyph parser */ function parse_glyphs ( src ) { if ( typeof src !== 'string' ) { return src; } // NB: order is important here ... return src // arrow .replace( /([^\-]|^)->/, '$1&#8594;' ) // arrow // dimensions .replace( re_dimsign, '$1&#215;$2' ) // dimension sign // ellipsis .replace( /([^.]?)\.{3}/g, '$1&#8230;' ) // ellipsis // dashes .replace( re_emdash, '$1&#8212;$2' ) // em dash .replace( / - /g, ' &#8211; ' ) // en dash // legal marks .replace( re_trademark, '$1&#8482;' ) // trademark .replace( re_registered, '$1&#174;' ) // registered .replace( re_copyright, '$1&#169;' ) // copyright // double quotes .replace( re_double_prime, '$1&#8243;' ) // double prime .replace( re_closing_dquote, '$1&#8221;' ) // double closing quote .replace( /"/g, '&#8220;' ) // double opening quote // single quotes .replace( re_single_prime, '$1&#8242;' ) // single prime .replace( re_apostrophe, '$1&#8217;$2' ) // I'm an apostrophe .replace( re_closing_squote, '$1&#8217;' ) // single closing quote .replace( /'/g, '&#8216;' ) // fractions and degrees .replace( /[\(\[]1\/4[\]\)]/, '&#188;' ) .replace( /[\(\[]1\/2[\]\)]/, '&#189;' ) .replace( /[\(\[]3\/4[\]\)]/, '&#190;' ) .replace( /[\(\[]o[\]\)]/, '&#176;' ) .replace( /[\(\[]\+\/\-[\]\)]/, '&#177;' ) ; } /* list parser */ function list_pad ( n ) { var s = '\n'; while ( n-- ) { s += '\t'; } return s; } function parse_list ( src, options ) { src = ribbon( src.replace( /(^|\r?\n)[\t ]+/, '$1' ) ); var stack = [] , curr_idx = {} , last_idx = options._lst || {} , list_pba , item_index = 0 , m , n , s ; while ( (m = re_list_item.exec( src )) ) { var item = [ 'li' ] , start_index = 0 , dest_level = m[1].length , type = m[1].substr(-1) === '#' ? 'ol' : 'ul' , new_li = null , lst , par , pba , r ; // list starts and continuations if ( n = /^(_|\d+)/.exec( m[2] ) ) { item_index = isFinite( n[1] ) ? parseInt( n[1], 10 ) : last_idx[ dest_level ] || curr_idx[ dest_level ] || 1; m[2] = m[2].slice( n[1].length ); } if ( pba = parse_attr( m[2], 'li' ) ) { m[2] = m[2].slice( pba[0] ); pba = pba[1]; } // list control if ( /^\.\s*$/.test( m[2] ) ) { list_pba = pba || {}; src.advance( m[0] ); continue; } // create nesting until we have correct level while ( stack.length < dest_level ) { // list always has an attribute object, this simplifies first-pba resolution lst = [ type, {}, list_pad( stack.length + 1 ), (new_li = [ 'li' ]) ]; par = stack[ stack.length - 1 ]; if ( par ) { par.li.push( list_pad( stack.length ) ); par.li.push( lst ); } stack.push({ ul: lst , li: new_li , att: 0 // count pba's found per list }); curr_idx[ stack.length ] = 1; } // remove nesting until we have correct level while ( stack.length > dest_level ) { r = stack.pop(); r.ul.push( list_pad( stack.length ) ); // lists have a predictable structure - move pba from listitem to list if ( r.att === 1 && !r.ul[3][1].substr ) { merge( r.ul[1], r.ul[3].splice( 1, 1 )[ 0 ] ); } } // parent list par = stack[ stack.length - 1 ]; // have list_pba or start_index? if ( item_index ) { par.ul[1].start = curr_idx[ dest_level ] = item_index; item_index = 0; // falsy prevents this from fireing until it is set again } if ( list_pba ) { par.att = 9; // "more than 1" prevent pba transfers on list close merge( par.ul[1], list_pba ); list_pba = null; } if ( !new_li ) { par.ul.push( list_pad( stack.length ), item ); par.li = item; } if ( pba ) { par.li.push( pba ); par.att++; } Array.prototype.push.apply( par.li, parse_inline( m[2].trim(), options ) ); src.advance( m[0] ); curr_idx[ dest_level ] = (curr_idx[ dest_level ] || 0) + 1; } // remember indexes for continuations next time options._lst = curr_idx; while ( stack.length ) { s = stack.pop(); s.ul.push( list_pad( stack.length ) ); // lists have a predictable structure - move pba from listitem to list if ( s.att === 1 && !s.ul[3][1].substr ) { merge( s.ul[1], s.ul[3].splice( 1, 1 )[ 0 ] ); } } return s.ul; } /* definitions list parser */ function parse_deflist ( src, options ) { src = ribbon( src.trim() ); var deflist = [ 'dl', '\n' ] , terms , def , m ; while ( (m = re_deflist_item.exec( src )) ) { // add terms terms = m[1].split( /(?:^|\n)\- / ).slice(1); while ( terms.length ) { deflist.push( '\t' , [ 'dt' ].concat( parse_inline( terms.shift().trim(), options ) ) , '\n' ); } // add definitions def = m[2].trim(); deflist.push( '\t' , [ 'dd' ].concat( /=:$/.test( def ) ? parse_blocks( def.slice(0,-2).trim(), options ) : parse_inline( def, options ) ) , '\n' ); src.advance( m[0] ); } return deflist; } /* table parser */ function parse_table ( src, options ) { src = ribbon( src.trim() ); var table = [ 'table' ] , row , inner , pba , more , m ; if ( (m = re_table_head.exec( src )) ) { // parse and apply table attr src.advance( m[0] ); pba = parse_attr( m[2], 'table' ); if ( pba ) { table.push( pba[1] ); } } while ( (m = re_table_row.exec( src )) ) { row = [ 'tr' ]; if ( m[1] && (pba = parse_attr( m[1], 'tr' )) ) { // FIXME: requires "\.\s?" -- else what ? row.push( pba[1] ); } table.push( '\n\t', row ); inner = ribbon( m[2] ); do { inner.save(); // cell loop var th = inner.startsWith( '_' ) , cell = [ th ? 'th' : 'td' ] ; if ( th ) { inner.advance( 1 ); } pba = parse_attr( inner, 'td' ); if ( pba ) { inner.advance( pba[0] ); cell.push( pba[1] ); // FIXME: don't do this if next text fails } if ( pba || th ) { var d = /^\.\s*/.exec( inner ); if ( d ) { inner.advance( d[0] ); } else { cell = [ 'td' ]; inner.load(); } } var mx = /^(==.*?==|[^\|])*/.exec( inner ); cell = cell.concat( parse_inline( mx[0], options ) ); row.push( '\n\t\t', cell ); more = inner.valueOf().charAt( mx[0].length ) === '|'; inner.advance( mx[0].length + 1 ); } while ( more ); row.push( '\n\t' ); src.advance( m[0] ); } table.push( '\n' ); return table; } /* inline parser */ function parse_inline ( src, options ) { src = ribbon( src ); var list = builder() , m , pba ; // loop do { src.save(); // linebreak -- having this first keeps it from messing to much with other phrases if ( src.startsWith( '\r\n' ) ) { src.advance( 1 ); // skip cartridge returns } if ( src.startsWith( '\n' ) ) { src.advance( 1 ); if ( options.breaks ) { list.add( [ 'br' ] ); } list.add( '\n' ); continue; } // inline notextile if ( (m = /^==(.*?)==/.exec( src )) ) { src.advance( m[0] ); list.add( m[1] ); continue; } // lookbehind => /([\s>.,"'?!;:])$/ var behind = src.lookbehind( 1 ); var boundary = !behind || /^[\s>.,"'?!;:()]$/.test( behind ); // FIXME: need to test right boundary for phrases as well if ( (m = re_phrase.exec( src )) && ( boundary || m[1] ) ) { src.advance( m[0] ); var tok = m[2] , fence = m[1] , phrase_type = phrase_convert[ tok ] , code = phrase_type === 'code' ; if ( (pba = !code && parse_attr( src, phrase_type, tok )) ) { src.advance( pba[0] ); pba = pba[1]; } // FIXME: if we can't match the fence on the end, we should output fence-prefix as normal text // seek end var m_mid; var m_end; if ( fence === '[' ) { m_mid = '^(.*?)'; m_end = '(?:])'; } else if ( fence === '{' ) { m_mid = '^(.*?)'; m_end = '(?:})'; } else { var t1 = re.escape( tok.charAt(0) ); m_mid = ( code ) ? '^(\\S+|\\S+.*?\\S)' : '^([^\\s' + t1 + ']+|[^\\s' + t1 + '].*?\\S('+t1+'*))' ; m_end = '(?=$|[\\s.,"\'!?;:()«»„“”‚‘’])'; } var rx = re.compile( m_mid + '(' + re.escape( tok ) + ')' + m_end ); if ( (m = rx.exec( src )) && m[1] ) { src.advance( m[0] ); if ( code ) { list.add( [ phrase_type, m[1] ] ); } else { list.add( [ phrase_type, pba ].concat( parse_inline( m[1], options ) ) ); } continue; } // else src.load(); } // image if ( (m = re_image.exec( src )) || (m = re_image_fenced.exec( src )) ) { src.advance( m[0] ); pba = m[1] && parse_attr( m[1], 'img' ); var attr = pba ? pba[1] : { 'src':'' } , img = [ 'img', attr ] ; attr.src = m[2]; attr.alt = m[3] ? ( attr.title = m[3] ) : ''; if ( m[4] ) { // +cite causes image to be wraped with a link (or link_ref)? // TODO: support link_ref for image cite img = [ 'a', { 'href': m[4] }, img ]; } list.add( img ); continue; } // html comment if ( (m = re_html_comment.exec( src )) ) { src.advance( m[0] ); list.add( [ '!', m[1] ] ); continue; } // html tag // TODO: this seems to have a lot of overlap with block tags... DRY? if ( (m = re_html_tag.exec( src )) ) { src.advance( m[0] ); var tag = m[1] , single = m[3] || m[1] in html_singletons , element = [ tag ] , tail = m[4] ; if ( m[2] ) { element.push( parse_html_attr( m[2] ) ); } if ( single ) { // single tag list.add( element ).add( tail ); continue; } else { // need terminator // gulp up the rest of this block... var re_end_tag = re.compile( "^(.*?)(</" + tag + "\\s*>)", 's' ); if ( (m = re_end_tag.exec( src )) ) { src.advance( m[0] ); if ( tag === 'code' ) { element.push( tail, m[1] ); } else if ( tag === 'notextile' ) { list.merge( parse_inline( m[1], options ) ); continue; } else { element = element.concat( parse_inline( m[1], options ) ); } list.add( element ); continue; } // end tag is missing, treat tag as normal text... } src.load(); } // footnote if ( (m = re_footnote.exec( src )) && /\S/.test( behind ) ) { src.advance( m[0] ); list.add( [ 'sup', { 'class': 'footnote', 'id': 'fnr' + m[1] }, ( m[2] === '!' ? m[1] // "!" suppresses the link : [ 'a', { href: '#fn' + m[1] }, m[1] ] ) ] ); continue; } // caps / abbr if ( (m = re_caps.exec( src )) ) { src.advance( m[0] ); var caps = [ 'span', { 'class': 'caps' }, m[1] ]; if ( m[2] ) { caps = [ 'acronym', { 'title': m[2] }, caps ]; // FIXME: use <abbr>, not acronym! } list.add( caps ); continue; } // links if ( (boundary && (m = re_link.exec( src ))) || (m = re_link_fenced.exec( src )) ) { src.advance( m[0].length ); var title = m[1].match( re_link_title ) , inner = ( title ) ? m[1].slice( 0, m[1].length - title[0].length ) : m[1] ; if ( (pba = parse_attr( inner, 'a' )) ) { inner = inner.slice( pba[0] ); pba = pba[1]; } else { pba = {}; } if ( title && !inner ) { inner = title[0]; title = ""; } pba.href = m[2]; if ( title ) { pba.title = title[1]; } list.add( [ 'a', pba ].concat( parse_inline( inner.replace( /^(\.?\s*)/, '' ), options ) ) ); continue; } // no match, move by all "uninteresting" chars m = /([a-zA-Z0-9,.':]+|[ \f\r\t\v\xA0\u2028\u2029]+|[^\0])/.exec( src ); if ( m ) { list.add( m[0] ); } src.advance( m ? m[0].length || 1 : 1 ); } while ( src.valueOf() ); return list.get().map( parse_glyphs ); } /* block parser */ function parse_blocks ( src, options ) { var list = builder() , paragraph = function ( s, tag, pba, linebreak ) { tag = tag || 'p'; var out = []; s.split( /(?:\r?\n){2,}/ ).forEach(function( bit, i ) { if ( tag === 'p' && /^\s/.test( bit ) ) { // no-paragraphs // WTF?: Why does Textile not allow linebreaks in spaced lines bit = bit.replace( /\r?\n[\t ]/g, ' ' ).trim(); out = out.concat( parse_inline( bit, options ) ); } else { if ( linebreak && i ) { out.push( linebreak ); } out.push( pba ? [ tag, pba ].concat( parse_inline( bit, options ) ) : [ tag ].concat( parse_inline( bit, options ) ) ); } }); return out; } , link_refs = {} , m ; src = ribbon( src.replace( /^( *\r?\n)+/, '' ) ); // loop while ( src.valueOf() ) { src.save(); // link_ref -- this goes first because it shouldn't trigger a linebreak if ( (m = re_link_ref.exec( src )) ) { src.advance( m[0] ); link_refs[ m[1] ] = m[2]; continue; } // add linebreak list.linebreak(); // named block if ( (m = re_block.exec( src )) ) { src.advance( m[0] ); var block_type = m[0] , pba = parse_attr( src, block_type ) ; if ( pba ) { src.advance( pba[0] ); pba = pba[1]; } if ( (m = /^\.(\.?)(?:\s|(?=:))/.exec( src )) ) { // FIXME: this whole copy_pba seems rather strange? // slurp rest of block var extended = !!m[1]; m = ( extended ? re_block_extended : re_block_normal ).exec( src.advance( m[0] ) ); src.advance( m[0] ); // bq | bc | notextile | pre | h# | fn# | p | ### if ( block_type === 'bq' ) { var cite, inner = m[1]; if ( (m = /^:(\S+)\s+/.exec( inner )) ) { if ( !pba ) { pba = {}; } pba.cite = m[1]; inner = inner.slice( m[0].length ); } // RedCloth adds all attr to both: this is bad because it produces duplicate IDs list.add( [ 'blockquote', pba, '\n' ].concat( paragraph( inner, 'p', copy_pba(pba, { 'cite':1, 'id':1 }), '\n' ) ).concat(['\n']) ); } else if ( block_type === 'bc' ) { var sub_pba = ( pba ) ? copy_pba(pba, { 'id':1 }) : null; list.add( [ 'pre', pba, ( sub_pba ? [ 'code', sub_pba, m[1] ] : [ 'code', m[1] ] ) ] ); } else if ( block_type === 'notextile' ) { list.merge( parse_html( m[1] ) ); } else if ( block_type === '###' ) { // ignore the insides } else if ( block_type === 'pre' ) { // I disagree with RedCloth, but agree with PHP here: // "pre(foo#bar).. line1\n\nline2" prevents multiline preformat blocks // ...which seems like the whole point of having an extended pre block? list.add( [ 'pre', pba, m[1] ] ); } else if ( re_footnote_def.test( block_type ) ) { // footnote // Need to be careful: RedCloth fails "fn1(foo#m). footnote" -- it confuses the ID var fnid = block_type.replace( /\D+/g, '' ); if ( !pba ) { pba = {}; } pba['class'] = ( pba['class'] ? pba['class'] + ' ' : '' ) + 'footnote'; pba['id'] = 'fn' + fnid; list.add( [ "p", pba, [ 'a', { 'href': '#fnr' + fnid }, [ 'sup', fnid ] ], ' ' ].concat( parse_inline( m[1], options ) ) ); } else { // heading | paragraph list.merge( paragraph( m[1], block_type, pba, '\n' ) ); } continue; } else { src.load(); } } // HTML comment if ( (m = re_html_comment.exec( src )) ) { src.advance( m[0] + (/(?:\s*\n+)+/.exec( src ) || [])[0] ); list.add( [ '!', m[1] ] ); continue; } // block HTML if ( (m = re_html_tag_block.exec( src )) ) { var tag = m[1] , single = m[3] || tag in html_singletons , tail = m[4] ; // Unsurprisingly, all Textile implementations I have tested have trouble parsing simple HTML: // // "<div>a\n<div>b\n</div>c\n</div>d" // // I simply match them here as there is no way anyone is using nested HTML today, or if they // are, then this will at least output less broken HTML as redundant tags will get quoted. // Is block tag? ... if ( tag in allowed_blocktags ) { src.advance( m[0] ); var element = [ tag ]; if ( m[2] ) { element.push( parse_html_attr( m[2] ) ); } if ( single ) { // single tag // let us add the element and continue our quest... list.add( element ); continue; } else { // block // gulp up the rest of this block... var re_end_tag = re.compile( "^(.*?)(\\s*)(</" + tag + "\\s*>)(\\s*)", 's' ); if ( (m = re_end_tag.exec( src )) ) { src.advance( m[0] ); if ( tag === 'pre' ) { element.push( tail ); element = element.concat( parse_html( m[1].replace( /(\r?\n)+$/, '' ), { 'code': 1 } ) ); if ( m[2] ) { element.push( m[2] ); } list.add( element ); } else if ( tag === 'notextile' ) { element = parse_html( m[1].trim() ); list.merge( element ); } else if ( tag === 'script' || tag === 'noscript' ) { //element = parse_html( m[1].trim() ); element.push( tail + m[1] ); list.add( element ); } else { // These strange (and unnecessary) linebreak tests are here to get the // tests working perfectly. In reality, this doesn't matter one bit. if ( /\n/.test( tail ) ) { element.push( '\n' ); } if ( /\n/.test( m[1] ) ) { element = element.concat( parse_blocks( m[1], options ) ); } else { element = element.concat( parse_inline( m[1].replace( /^ +/, '' ), options ) ); } if ( /\n/.test( m[2] ) ) { element.push( '\n' ); } list.add( element ); } continue; } /*else { // end tag is missing, treat tag as normal text... }*/ } } src.load(); } // ruler if ( (m = re_ruler.exec( src )) ) { src.advance( m[0] ); list.add( [ 'hr' ] ); continue; } // list if ( (m = re_list.exec( src )) ) { src.advance( m[0] ); list.add( parse_list( m[0], options ) ); continue; } // definition list if ( (m = re_deflist.exec( src )) ) { src.advance( m[0] ); list.add( parse_deflist( m[0], options ) ); continue; } // table if ( (m = re_table.exec( src )) ) { src.advance( m[0] ); list.add( parse_table( m[1], options ) ); continue; } // paragraph m = re_block_normal.exec( src ); list.merge( paragraph( m[1], 'p', undefined, "\n" ) ); src.advance( m[0] ); } return list.get().map( fix_links, link_refs ); } // recurse the tree and swap out any "href" attributes function fix_links ( jsonml ) { if ( _isArray( jsonml ) ) { if ( jsonml[0] === 'a' ) { // found a link var attr = jsonml[1]; if ( typeof attr === "object" && 'href' in attr && attr.href in this ) { attr.href = this[ attr.href ]; } } for (var i=1,l=jsonml.length; i<l; i++) { if ( _isArray( jsonml[i] ) ) { fix_links.call( this, jsonml[i] ); } } } return jsonml; } /* exposed */ function textile ( txt, opt ) { // get a throw-away copy of options opt = merge( merge( {}, textile.defaults ), opt || {} ); // run the converter return parse_blocks( txt, opt ).map( JSONML.toHTML ).join( '' ); } // options textile.defaults = { 'breaks': true // single-line linebreaks are converted to <br> by default }; textile.setOptions = textile.setoptions = function ( opt ) { merge( textile.defaults, opt ); return this; }; textile.parse = textile.convert = textile; textile.html_parser = parse_html; textile.jsonml = function ( txt, opt ) { // get a throw-away copy of options opt = merge( merge( {}, textile.defaults ), opt || {} ); // parse and return tree return [ 'html' ].concat( parse_blocks( txt, opt ) ); }; textile.serialize = JSONML.toHTML; if ( typeof module !== 'undefined' && module.exports ) { module.exports = textile; } else { this.textile = textile; } }).call(function() { return this || (typeof window !== 'undefined' ? window : global); }());
/*! Copyright 2011, Ben Lin (http://dreamerslab.com/) * Licensed under the MIT License (LICENSE.txt). * * Version: 1.0.0 * * Requires: jQuery 1.2.3+ */ $.preload = function(){ var tmp = [], i = arguments.length; // reverse loop run faster for( ; i-- ; ) tmp.push( $( '<img />' ).attr( 'src', arguments[ i ] )); };
/*jshint indent: 4, browser:true*/ /*global L*/ /* * L.TimeDimension.Player */ //'use strict'; L.TimeDimension.Player = (L.Layer || L.Class).extend({ includes: (L.Evented || L.Mixin.Events), initialize: function(options, timeDimension) { L.setOptions(this, options); this._timeDimension = timeDimension; this._paused = false; this._buffer = this.options.buffer || 5; this._minBufferReady = this.options.minBufferReady || 1; this._waitingForBuffer = false; this._loop = this.options.loop || false; this._steps = 1; this._timeDimension.on('timeload', (function(data) { this.release(); // free clock this._waitingForBuffer = false; // reset buffer }).bind(this)); this.setTransitionTime(this.options.transitionTime || 1000); this._timeDimension.on('limitschanged availabletimeschanged timeload', (function(data) { this._timeDimension.prepareNextTimes(this._steps, this._minBufferReady, this._loop); }).bind(this)); }, _tick: function() { var maxIndex = this._getMaxIndex(); var maxForward = (this._timeDimension.getCurrentTimeIndex() >= maxIndex) && (this._steps > 0); var maxBackward = (this._timeDimension.getCurrentTimeIndex() == 0) && (this._steps < 0); if (maxForward || maxBackward) { // we reached the last step if (!this._loop) { this.pause(); this.stop(); this.fire('animationfinished'); return; } } if (this._paused) { return; } var numberNextTimesReady = 0, buffer = this._bufferSize; if (this._minBufferReady > 0) { numberNextTimesReady = this._timeDimension.getNumberNextTimesReady(this._steps, buffer, this._loop); // If the player was waiting, check if all times are loaded if (this._waitingForBuffer) { if (numberNextTimesReady < buffer) { console.log('Waiting until buffer is loaded. ' + numberNextTimesReady + ' of ' + buffer + ' loaded'); this.fire('waiting', { buffer: buffer, available: numberNextTimesReady }); return; } else { // all times loaded console.log('Buffer is fully loaded!'); this.fire('running'); this._waitingForBuffer = false; } } else { // check if player has to stop to wait and force to full all the buffer if (numberNextTimesReady < this._minBufferReady) { console.log('Force wait for load buffer. ' + numberNextTimesReady + ' of ' + buffer + ' loaded'); this._waitingForBuffer = true; this._timeDimension.prepareNextTimes(this._steps, buffer, this._loop); this.fire('waiting', { buffer: buffer, available: numberNextTimesReady }); return; } } } this.pause(); this._timeDimension.nextTime(this._steps, this._loop); if (buffer > 0) { this._timeDimension.prepareNextTimes(this._steps, buffer, this._loop); } }, _getMaxIndex: function(){ return Math.min(this._timeDimension.getAvailableTimes().length - 1, this._timeDimension.getUpperLimitIndex() || Infinity); }, start: function(numSteps) { if (this._intervalID) return; this._steps = numSteps || 1; this._waitingForBuffer = false; var startedOver = false; if (this.options.startOver){ if (this._timeDimension.getCurrentTimeIndex() === this._getMaxIndex()){ this._timeDimension.setCurrentTimeIndex(this._timeDimension.getLowerLimitIndex() || 0); startedOver = true; } } this.release(); this._intervalID = window.setInterval( L.bind(this._tick, this), this._transitionTime); if (!startedOver) this._tick(); this.fire('play'); this.fire('running'); }, stop: function() { if (!this._intervalID) return; clearInterval(this._intervalID); this._intervalID = null; this._waitingForBuffer = false; this.fire('stop'); }, pause: function() { this._paused = true; }, release: function () { this._paused = false; }, getTransitionTime: function() { return this._transitionTime; }, isPlaying: function() { return this._intervalID ? true : false; }, isWaiting: function() { return this._waitingForBuffer; }, isLooped: function() { return this._loop; }, setLooped: function(looped) { this._loop = looped; this.fire('loopchange', { loop: looped }); }, setTransitionTime: function(transitionTime) { this._transitionTime = transitionTime; if (typeof this._buffer === 'function') { this._bufferSize = this._buffer.call(this, this._transitionTime, this._minBufferReady, this._loop); console.log('Buffer size changed to ' + this._bufferSize); } else { this._bufferSize = this._buffer; } if (this._intervalID) { this.stop(); this.start(this._steps); } this.fire('speedchange', { transitionTime: transitionTime, buffer: this._bufferSize }); }, getSteps: function() { return this._steps; } });
'use strict'; angular.module('mean.settings').config(['$stateProvider', function($stateProvider) { var checkLoggedin = function($q, $timeout, $http, $location) { // Initialize a new promise var deferred = $q.defer(); // Make an AJAX call to check if the user is logged in $http.get('/loggedin').success(function(user) { // Authenticated if (user !== '0') $timeout(deferred.resolve); // Not Authenticated else { $timeout(deferred.reject); $location.url('/'); } }); return deferred.promise; }; $stateProvider.state('settings', { url: '/settings', templateUrl: 'settings/views/index.html', resolve: { loggedin: checkLoggedin } }); } ]);
import PropTypes from 'prop-types' import React from 'react' import block from 'bem-cn-lite' import { Field, reduxForm } from 'redux-form' import { compose } from 'underscore' import { connect } from 'react-redux' import { renderTextInput } from '../text_input' import { renderCheckboxInput } from '../checkbox_input' import { signUp, updateAuthFormStateAndClearError } from '../../client/actions' import { GDPRMessage } from 'desktop/components/react/gdpr/GDPRCheckbox' function validate(values) { const { accepted_terms_of_service, email, name, password } = values const errors = {} if (!name) errors.name = 'Required' if (!email) errors.email = 'Required' if (!password) errors.password = 'Required' if (!accepted_terms_of_service) errors.accepted_terms_of_service = 'Please agree to our terms to continue' return errors } function SignUp(props) { const { error, handleSubmit, isLoading, signUpAction, updateAuthFormStateAndClearErrorAction, } = props const b = block('consignments-submission-sign-up') return ( <div className={b()}> <div className={b('title')}>Create an Account</div> <div className={b('subtitle')}> Already have an account?{' '} <span className={b('clickable')} onClick={() => updateAuthFormStateAndClearErrorAction('logIn')} > Log in </span>. </div> <form className={b('form')} onSubmit={handleSubmit(signUpAction)}> <div className={b('row')}> <div className={b('row-item')}> <Field name="name" component={renderTextInput} item={'name'} label={'Full Name'} autofocus /> </div> </div> <div className={b('row')}> <div className={b('row-item')}> <Field name="email" component={renderTextInput} item={'email'} label={'Email'} type={'email'} /> </div> </div> <div className={b('row')}> <div className={b('row-item')}> <Field name="password" component={renderTextInput} item={'password'} label={'Password'} type={'password'} /> </div> </div> <div className={b('row')}> <div className={b('row-item')}> <Field name="accepted_terms_of_service" component={renderCheckboxInput} item={'accepted_terms_of_service'} label={<GDPRMessage />} value={false} /> </div> </div> <button className={b .builder()('sign-up-button') .mix('avant-garde-button-black')()} type="submit" > {isLoading ? <div className="loading-spinner-white" /> : 'Submit'} </button> {error && <div className={b('error')}>{error}</div>} </form> </div> ) } const mapStateToProps = state => { return { error: state.submissionFlow.error, isLoading: state.submissionFlow.isLoading, } } const mapDispatchToProps = { signUpAction: signUp, updateAuthFormStateAndClearErrorAction: updateAuthFormStateAndClearError, } SignUp.propTypes = { error: PropTypes.string, handleSubmit: PropTypes.func.isRequired, isLoading: PropTypes.bool.isRequired, signUpAction: PropTypes.func.isRequired, updateAuthFormStateAndClearErrorAction: PropTypes.func.isRequired, } export default compose( reduxForm({ form: 'signUp', // a unique identifier for this form validate, }), connect(mapStateToProps, mapDispatchToProps) )(SignUp)
TF.listen();
$(document).ready(function() { $(document).on('submit', '.status-button', function(e) { e.preventDefault(); var joinButton = e.target $.ajax(joinButton.action, { method: 'PATCH', data: $(this).serialize() }) .done(function(data) { gameDiv = $(joinButton).parent(); gameDiv.replaceWith(data); }) .fail(function() { alert("Failure!"); }); }); });
function OrganizationController() { // injetando dependência 'ngInject'; // ViewModel const vm = this; console.log('OrganizationController'); } export default { name: 'OrganizationController', fn: OrganizationController };
import React, { Component } from 'react'; import Header from './Header'; import MainSection from './MainSection'; export default class App extends Component { render() { return ( <div> <Header/> <MainSection/> </div> ); } }
version https://git-lfs.github.com/spec/v1 oid sha256:641860132ccb9772e708b19feb3d59bb6291f6c40eebbfcfa0982a4e8eeda219 size 69639
(function(global) { var vwl = {}; var receivePoster; var receiveEntry; var receiveLoadedList; // vwl.init - advertise VWL info and register for VWL messages // // Parameters: // left - (optional) url of this world's initial left entry image // right - (optional) url of this world's initial right entry image // receivePosterFunc - (optional) function to handle poster images from other // worlds // receiveEntryFunc - (optional) function to handle entry images from other // worlds // recevieLoadedListFunc - (optional) function to handle list of loaded worlds vwl.init = function(left, right, receivePosterFunc, receiveEntryFunc, receiveLoadedListFunc) { receivePoster = receivePosterFunc; receiveEntry = receiveEntryFunc; receiveLoadedList = receiveLoadedListFunc; receiveEntry && window.addEventListener('message', function(message) { if (message.source != window || message.origin != window.location.origin) return; if (message.data.tabInfo) { var left = null; var right = null; if (message.data.tabInfo.info && message.data.tabInfo.info.entry_image) { left = message.data.tabInfo.info.entry_image.left_src; right = message.data.tabInfo.info.entry_image.right_src; } receiveEntry(message.data.tabInfo.url, message.data.tabInfo.loaded, left, right); } if (message.data.loadedList !== undefined) { receiveLoadedList(message.data.loadedList); } }, false); window.postMessage({info:{entry_image:{ left_src:left, right_src:right}}}, '*'); } // vwl.getInfo - get info (entry image and poster image) on a specific world // // Parameters: // url - url of worlds to get info on // getPoster - (optional) if true get the poster image vwl.getInfo = function(url, getPoster) { if (receivePoster && getPoster) { var request = new XMLHttpRequest(); var dir = url.substr(0, url.lastIndexOf('/') + 1); request.open('GET', dir + 'vwl_info.json'); request.onreadystatechange = function() { if (request.readyState == 4 && request.status == 200) { var poster = JSON.parse(request.responseText).poster_image; receivePoster(url, poster.left_src ? dir + poster.left_src : null, poster.right_src ? dir + poster.right_src : null, poster._2d_src ? dir + poster._2d_src : null); } else { receivePoster(url); } } request.send(null); } receiveEntry && window.postMessage({getInfo:url}, '*'); } // vwl.getLoadedList - get the list of loaded worlds vwl.getLoadedList = function() { window.postMessage({getLoadedList:true}, '*'); } // vwl.open - load world // // Parameters: // url - url of world to open vwl.open = function(url) { window.postMessage({open:url}, '*'); } // vwl.navigate - navigate to a world // // Parameters: // left - (optional) new left entry image for current world // right - (optional) new right entry image for current world // url - url of world to navigate to vwl.navigate = function(left, right, url) { var message = {navigate:url}; if (left && right) { message.info = {entry_image:{left_src:left, right_src:right}}; } window.postMessage(message, '*'); } global.vwl = vwl; }) (window);
// These two object contain information about the state of Ebl var GlobalState = Base.extend({ constructor: function() { this.isAdmin = false; this.authToken = null; this.docTitle = null; this.container = null; // default config this.config = { template: 'default', language: 'en', postsPerPage: 5, pageTitleFormat: "{ebl_title} | {doc_title}", // callbacks onBlogLoaded: null, onPostOpened: null, onPageChanged: null }; } }); var LocalState = Base.extend({ constructor: function() { this.page = 0; this.post = null; this.editors = null; } }); var PostStatus = { NEW: 0, DRAFT: 1, PUBLISHED: 2, parse: function (s) { if (s.toLowerCase() == "new") return 0; if (s.toLowerCase() == "draft") return 1; if (s.toLowerCase() == "published") return 2; return null; } }; var gState = new GlobalState(); // state shared among the entire session var lState = new LocalState(); // state of the current view
import React from 'react' import { Container, Group, TabBar, Icon, Badge, amStyles, } from 'amazeui-touch' import {Link} from 'react-router' class App extends React.Component{ propsType ={ children:React.PropTypes.node } render(){ let { location, params, children, ...props } = this.props; let transition = children.props.transition || 'sfr' return ( <Container direction="column"> <Container transition={transition} > {children} </Container> <TabBar > <TabBar.Item component={Link} eventKey = 'home' active = {location.pathname === '/'} icon = 'home' title = '首页' to='/' /> <TabBar.Item component={Link} active={location.pathname === '/class'} eventKey="class" icon="list" title="课程" to='/class' /> <TabBar.Item active={location.pathname === '/search'} eventKey="search" icon="search" title="发现" /> <TabBar.Item component={Link} active={location.pathname === '/me'} eventKey="person" icon="person" title="我" to='/me' /> </TabBar> </Container> ) } } export default App
/* * unstrap v1.1.3 * https://unstrap.org * 2015-2020 * MIT license */ const version = '1.1.3', collection = {}; function extendUnstrap (v) { var list; if (!collection[v].selectors) { collection[v].selectors = ['.' + collection[v].name]; } collection[v].selectors.forEach(function (sel) { list = document.querySelectorAll(sel); for (var i = 0; i < list.length; i++) { collection[v].extend && collection[v].extend(list.item(i)); } }) } function init () { var observer = new MutationObserver(function (mut) { mut.forEach(function (m) { var n = m.addedNodes, f; for (var i=0; i<n.length; i++) { var c = n.item(i).classList; if (c) { for (var j = 0; j < c.length; j++) { if (f = collection[c.item(j)]) { f.extend && f.extend(n.item(i)); } } } } }); }); Object.keys(collection).forEach(function (v) { extendUnstrap(v); }) observer.observe(document.body, {childList: true, subtree: true}); } function register (...components) { components.forEach((component) => { if (component.name) { collection[component.name] = component; } }) } function unregister (...components) { components.forEach((component) => { delete collection[component.name]; }) } function list () { return Object.keys(collection).sort(); } window.onload = init; export default { version, register, unregister, list }
'use strict'; const toBytes = s => [...s].map(c => c.charCodeAt(0)); const xpiZipFilename = toBytes('META-INF/mozilla.rsa'); const oxmlContentTypes = toBytes('[Content_Types].xml'); const oxmlRels = toBytes('_rels/.rels'); const fileType = input => { const buf = input instanceof Uint8Array ? input : new Uint8Array(input); if (!(buf && buf.length > 1)) { return null; } const check = (header, options) => { options = Object.assign({ offset: 0 }, options); for (let i = 0; i < header.length; i++) { // If a bitmask is set if (options.mask) { // If header doesn't equal `buf` with bits masked off if (header[i] !== (options.mask[i] & buf[i + options.offset])) { return false; } } else if (header[i] !== buf[i + options.offset]) { return false; } } return true; }; const checkString = (header, options) => check(toBytes(header), options); if (check([0xFF, 0xD8, 0xFF])) { return { ext: 'jpg', mime: 'image/jpeg' }; } if (check([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A])) { return { ext: 'png', mime: 'image/png' }; } if (check([0x47, 0x49, 0x46])) { return { ext: 'gif', mime: 'image/gif' }; } if (check([0x57, 0x45, 0x42, 0x50], {offset: 8})) { return { ext: 'webp', mime: 'image/webp' }; } if (check([0x46, 0x4C, 0x49, 0x46])) { return { ext: 'flif', mime: 'image/flif' }; } // Needs to be before `tif` check if ( (check([0x49, 0x49, 0x2A, 0x0]) || check([0x4D, 0x4D, 0x0, 0x2A])) && check([0x43, 0x52], {offset: 8}) ) { return { ext: 'cr2', mime: 'image/x-canon-cr2' }; } if ( check([0x49, 0x49, 0x2A, 0x0]) || check([0x4D, 0x4D, 0x0, 0x2A]) ) { return { ext: 'tif', mime: 'image/tiff' }; } if (check([0x42, 0x4D])) { return { ext: 'bmp', mime: 'image/bmp' }; } if (check([0x49, 0x49, 0xBC])) { return { ext: 'jxr', mime: 'image/vnd.ms-photo' }; } if (check([0x38, 0x42, 0x50, 0x53])) { return { ext: 'psd', mime: 'image/vnd.adobe.photoshop' }; } // Zip-based file formats // Need to be before the `zip` check if (check([0x50, 0x4B, 0x3, 0x4])) { if ( check([0x6D, 0x69, 0x6D, 0x65, 0x74, 0x79, 0x70, 0x65, 0x61, 0x70, 0x70, 0x6C, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6F, 0x6E, 0x2F, 0x65, 0x70, 0x75, 0x62, 0x2B, 0x7A, 0x69, 0x70], {offset: 30}) ) { return { ext: 'epub', mime: 'application/epub+zip' }; } // Assumes signed `.xpi` from addons.mozilla.org if (check(xpiZipFilename, {offset: 30})) { return { ext: 'xpi', mime: 'application/x-xpinstall' }; } if (checkString('mimetypeapplication/vnd.oasis.opendocument.text', {offset: 30})) { return { ext: 'odt', mime: 'application/vnd.oasis.opendocument.text' }; } if (checkString('mimetypeapplication/vnd.oasis.opendocument.spreadsheet', {offset: 30})) { return { ext: 'ods', mime: 'application/vnd.oasis.opendocument.spreadsheet' }; } if (checkString('mimetypeapplication/vnd.oasis.opendocument.presentation', {offset: 30})) { return { ext: 'odp', mime: 'application/vnd.oasis.opendocument.presentation' }; } // https://github.com/file/file/blob/master/magic/Magdir/msooxml if (check(oxmlContentTypes, {offset: 30}) || check(oxmlRels, {offset: 30})) { const sliced = buf.subarray(4, 4 + 2000); const nextZipHeaderIndex = arr => arr.findIndex((el, i, arr) => arr[i] === 0x50 && arr[i + 1] === 0x4B && arr[i + 2] === 0x3 && arr[i + 3] === 0x4); const header2Pos = nextZipHeaderIndex(sliced); if (header2Pos !== -1) { const slicedAgain = buf.subarray(header2Pos + 8, header2Pos + 8 + 1000); const header3Pos = nextZipHeaderIndex(slicedAgain); if (header3Pos !== -1) { const offset = 8 + header2Pos + header3Pos + 30; if (checkString('word/', {offset})) { return { ext: 'docx', mime: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' }; } if (checkString('ppt/', {offset})) { return { ext: 'pptx', mime: 'application/vnd.openxmlformats-officedocument.presentationml.presentation' }; } if (checkString('xl/', {offset})) { return { ext: 'xlsx', mime: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }; } } } } } if ( check([0x50, 0x4B]) && (buf[2] === 0x3 || buf[2] === 0x5 || buf[2] === 0x7) && (buf[3] === 0x4 || buf[3] === 0x6 || buf[3] === 0x8) ) { return { ext: 'zip', mime: 'application/zip' }; } if (check([0x75, 0x73, 0x74, 0x61, 0x72], {offset: 257})) { return { ext: 'tar', mime: 'application/x-tar' }; } if ( check([0x52, 0x61, 0x72, 0x21, 0x1A, 0x7]) && (buf[6] === 0x0 || buf[6] === 0x1) ) { return { ext: 'rar', mime: 'application/x-rar-compressed' }; } if (check([0x1F, 0x8B, 0x8])) { return { ext: 'gz', mime: 'application/gzip' }; } if (check([0x42, 0x5A, 0x68])) { return { ext: 'bz2', mime: 'application/x-bzip2' }; } if (check([0x37, 0x7A, 0xBC, 0xAF, 0x27, 0x1C])) { return { ext: '7z', mime: 'application/x-7z-compressed' }; } if (check([0x78, 0x01])) { return { ext: 'dmg', mime: 'application/x-apple-diskimage' }; } if (check([0x33, 0x67, 0x70, 0x35]) || // 3gp5 ( check([0x0, 0x0, 0x0]) && check([0x66, 0x74, 0x79, 0x70], {offset: 4}) && ( check([0x6D, 0x70, 0x34, 0x31], {offset: 8}) || // MP41 check([0x6D, 0x70, 0x34, 0x32], {offset: 8}) || // MP42 check([0x69, 0x73, 0x6F, 0x6D], {offset: 8}) || // ISOM check([0x69, 0x73, 0x6F, 0x32], {offset: 8}) || // ISO2 check([0x6D, 0x6D, 0x70, 0x34], {offset: 8}) || // MMP4 check([0x4D, 0x34, 0x56], {offset: 8}) || // M4V check([0x64, 0x61, 0x73, 0x68], {offset: 8}) // DASH ) )) { return { ext: 'mp4', mime: 'video/mp4' }; } if (check([0x4D, 0x54, 0x68, 0x64])) { return { ext: 'mid', mime: 'audio/midi' }; } // https://github.com/threatstack/libmagic/blob/master/magic/Magdir/matroska if (check([0x1A, 0x45, 0xDF, 0xA3])) { const sliced = buf.subarray(4, 4 + 4096); const idPos = sliced.findIndex((el, i, arr) => arr[i] === 0x42 && arr[i + 1] === 0x82); if (idPos !== -1) { const docTypePos = idPos + 3; const findDocType = type => [...type].every((c, i) => sliced[docTypePos + i] === c.charCodeAt(0)); if (findDocType('matroska')) { return { ext: 'mkv', mime: 'video/x-matroska' }; } if (findDocType('webm')) { return { ext: 'webm', mime: 'video/webm' }; } } } if (check([0x0, 0x0, 0x0, 0x14, 0x66, 0x74, 0x79, 0x70, 0x71, 0x74, 0x20, 0x20]) || check([0x66, 0x72, 0x65, 0x65], {offset: 4}) || check([0x66, 0x74, 0x79, 0x70, 0x71, 0x74, 0x20, 0x20], {offset: 4}) || check([0x6D, 0x64, 0x61, 0x74], {offset: 4}) || // MJPEG check([0x77, 0x69, 0x64, 0x65], {offset: 4})) { return { ext: 'mov', mime: 'video/quicktime' }; } // RIFF file format which might be AVI, WAV, QCP, etc if (check([0x52, 0x49, 0x46, 0x46])) { if (check([0x41, 0x56, 0x49], {offset: 8})) { return { ext: 'avi', mime: 'video/x-msvideo' }; } if (check([0x57, 0x41, 0x56, 0x45], {offset: 8})) { return { ext: 'wav', mime: 'audio/x-wav' }; } // QLCM, QCP file if (check([0x51, 0x4C, 0x43, 0x4D], {offset: 8})) { return { ext: 'qcp', mime: 'audio/qcelp' }; } } if (check([0x30, 0x26, 0xB2, 0x75, 0x8E, 0x66, 0xCF, 0x11, 0xA6, 0xD9])) { return { ext: 'wmv', mime: 'video/x-ms-wmv' }; } if ( check([0x0, 0x0, 0x1, 0xBA]) || check([0x0, 0x0, 0x1, 0xB3]) ) { return { ext: 'mpg', mime: 'video/mpeg' }; } if (check([0x66, 0x74, 0x79, 0x70, 0x33, 0x67], {offset: 4})) { return { ext: '3gp', mime: 'video/3gpp' }; } // Check for MPEG header at different starting offsets for (let start = 0; start < 2 && start < (buf.length - 16); start++) { if ( check([0x49, 0x44, 0x33], {offset: start}) || // ID3 header check([0xFF, 0xE2], {offset: start, mask: [0xFF, 0xE2]}) // MPEG 1 or 2 Layer 3 header ) { return { ext: 'mp3', mime: 'audio/mpeg' }; } if ( check([0xFF, 0xE4], {offset: start, mask: [0xFF, 0xE4]}) // MPEG 1 or 2 Layer 2 header ) { return { ext: 'mp2', mime: 'audio/mpeg' }; } if ( check([0xFF, 0xF8], {offset: start, mask: [0xFF, 0xFC]}) // MPEG 2 layer 0 using ADTS ) { return { ext: 'mp2', mime: 'audio/mpeg' }; } if ( check([0xFF, 0xF0], {offset: start, mask: [0xFF, 0xFC]}) // MPEG 4 layer 0 using ADTS ) { return { ext: 'mp4', mime: 'audio/mpeg' }; } } if ( check([0x66, 0x74, 0x79, 0x70, 0x4D, 0x34, 0x41], {offset: 4}) || check([0x4D, 0x34, 0x41, 0x20]) ) { return { ext: 'm4a', mime: 'audio/m4a' }; } // Needs to be before `ogg` check if (check([0x4F, 0x70, 0x75, 0x73, 0x48, 0x65, 0x61, 0x64], {offset: 28})) { return { ext: 'opus', mime: 'audio/opus' }; } // If 'OggS' in first bytes, then OGG container if (check([0x4F, 0x67, 0x67, 0x53])) { // This is a OGG container // If ' theora' in header. if (check([0x80, 0x74, 0x68, 0x65, 0x6F, 0x72, 0x61], {offset: 28})) { return { ext: 'ogv', mime: 'video/ogg' }; } // If '\x01video' in header. if (check([0x01, 0x76, 0x69, 0x64, 0x65, 0x6F, 0x00], {offset: 28})) { return { ext: 'ogm', mime: 'video/ogg' }; } // If ' FLAC' in header https://xiph.org/flac/faq.html if (check([0x7F, 0x46, 0x4C, 0x41, 0x43], {offset: 28})) { return { ext: 'oga', mime: 'audio/ogg' }; } // 'Speex ' in header https://en.wikipedia.org/wiki/Speex if (check([0x53, 0x70, 0x65, 0x65, 0x78, 0x20, 0x20], {offset: 28})) { return { ext: 'spx', mime: 'audio/ogg' }; } // If '\x01vorbis' in header if (check([0x01, 0x76, 0x6F, 0x72, 0x62, 0x69, 0x73], {offset: 28})) { return { ext: 'ogg', mime: 'audio/ogg' }; } // Default OGG container https://www.iana.org/assignments/media-types/application/ogg return { ext: 'ogx', mime: 'application/ogg' }; } if (check([0x66, 0x4C, 0x61, 0x43])) { return { ext: 'flac', mime: 'audio/x-flac' }; } if (check([0x23, 0x21, 0x41, 0x4D, 0x52, 0x0A])) { return { ext: 'amr', mime: 'audio/amr' }; } if (check([0x25, 0x50, 0x44, 0x46])) { return { ext: 'pdf', mime: 'application/pdf' }; } if (check([0x4D, 0x5A])) { return { ext: 'exe', mime: 'application/x-msdownload' }; } if ( (buf[0] === 0x43 || buf[0] === 0x46) && check([0x57, 0x53], {offset: 1}) ) { return { ext: 'swf', mime: 'application/x-shockwave-flash' }; } if (check([0x7B, 0x5C, 0x72, 0x74, 0x66])) { return { ext: 'rtf', mime: 'application/rtf' }; } if (check([0x00, 0x61, 0x73, 0x6D])) { return { ext: 'wasm', mime: 'application/wasm' }; } if ( check([0x77, 0x4F, 0x46, 0x46]) && ( check([0x00, 0x01, 0x00, 0x00], {offset: 4}) || check([0x4F, 0x54, 0x54, 0x4F], {offset: 4}) ) ) { return { ext: 'woff', mime: 'font/woff' }; } if ( check([0x77, 0x4F, 0x46, 0x32]) && ( check([0x00, 0x01, 0x00, 0x00], {offset: 4}) || check([0x4F, 0x54, 0x54, 0x4F], {offset: 4}) ) ) { return { ext: 'woff2', mime: 'font/woff2' }; } if ( check([0x4C, 0x50], {offset: 34}) && ( check([0x00, 0x00, 0x01], {offset: 8}) || check([0x01, 0x00, 0x02], {offset: 8}) || check([0x02, 0x00, 0x02], {offset: 8}) ) ) { return { ext: 'eot', mime: 'application/octet-stream' }; } if (check([0x00, 0x01, 0x00, 0x00, 0x00])) { return { ext: 'ttf', mime: 'font/ttf' }; } if (check([0x4F, 0x54, 0x54, 0x4F, 0x00])) { return { ext: 'otf', mime: 'font/otf' }; } if (check([0x00, 0x00, 0x01, 0x00])) { return { ext: 'ico', mime: 'image/x-icon' }; } if (check([0x00, 0x00, 0x02, 0x00])) { return { ext: 'cur', mime: 'image/x-icon' }; } if (check([0x46, 0x4C, 0x56, 0x01])) { return { ext: 'flv', mime: 'video/x-flv' }; } if (check([0x25, 0x21])) { return { ext: 'ps', mime: 'application/postscript' }; } if (check([0xFD, 0x37, 0x7A, 0x58, 0x5A, 0x00])) { return { ext: 'xz', mime: 'application/x-xz' }; } if (check([0x53, 0x51, 0x4C, 0x69])) { return { ext: 'sqlite', mime: 'application/x-sqlite3' }; } if (check([0x4E, 0x45, 0x53, 0x1A])) { return { ext: 'nes', mime: 'application/x-nintendo-nes-rom' }; } if (check([0x43, 0x72, 0x32, 0x34])) { return { ext: 'crx', mime: 'application/x-google-chrome-extension' }; } if ( check([0x4D, 0x53, 0x43, 0x46]) || check([0x49, 0x53, 0x63, 0x28]) ) { return { ext: 'cab', mime: 'application/vnd.ms-cab-compressed' }; } // Needs to be before `ar` check if (check([0x21, 0x3C, 0x61, 0x72, 0x63, 0x68, 0x3E, 0x0A, 0x64, 0x65, 0x62, 0x69, 0x61, 0x6E, 0x2D, 0x62, 0x69, 0x6E, 0x61, 0x72, 0x79])) { return { ext: 'deb', mime: 'application/x-deb' }; } if (check([0x21, 0x3C, 0x61, 0x72, 0x63, 0x68, 0x3E])) { return { ext: 'ar', mime: 'application/x-unix-archive' }; } if (check([0xED, 0xAB, 0xEE, 0xDB])) { return { ext: 'rpm', mime: 'application/x-rpm' }; } if ( check([0x1F, 0xA0]) || check([0x1F, 0x9D]) ) { return { ext: 'Z', mime: 'application/x-compress' }; } if (check([0x4C, 0x5A, 0x49, 0x50])) { return { ext: 'lz', mime: 'application/x-lzip' }; } if (check([0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1])) { return { ext: 'msi', mime: 'application/x-msi' }; } if (check([0x06, 0x0E, 0x2B, 0x34, 0x02, 0x05, 0x01, 0x01, 0x0D, 0x01, 0x02, 0x01, 0x01, 0x02])) { return { ext: 'mxf', mime: 'application/mxf' }; } if (check([0x47], {offset: 4}) && (check([0x47], {offset: 192}) || check([0x47], {offset: 196}))) { return { ext: 'mts', mime: 'video/mp2t' }; } if (check([0x42, 0x4C, 0x45, 0x4E, 0x44, 0x45, 0x52])) { return { ext: 'blend', mime: 'application/x-blender' }; } if (check([0x42, 0x50, 0x47, 0xFB])) { return { ext: 'bpg', mime: 'image/bpg' }; } if (check([0x00, 0x00, 0x00, 0x0C, 0x6A, 0x50, 0x20, 0x20, 0x0D, 0x0A, 0x87, 0x0A])) { // JPEG-2000 family if (check([0x6A, 0x70, 0x32, 0x20], {offset: 20})) { return { ext: 'jp2', mime: 'image/jp2' }; } if (check([0x6A, 0x70, 0x78, 0x20], {offset: 20})) { return { ext: 'jpx', mime: 'image/jpx' }; } if (check([0x6A, 0x70, 0x6D, 0x20], {offset: 20})) { return { ext: 'jpm', mime: 'image/jpm' }; } if (check([0x6D, 0x6A, 0x70, 0x32], {offset: 20})) { return { ext: 'mj2', mime: 'image/mj2' }; } } if (check([0x46, 0x4F, 0x52, 0x4D, 0x00])) { return { ext: 'aif', mime: 'audio/aiff' }; } if (checkString('<?xml ')) { return { ext: 'xml', mime: 'application/xml' }; } if (check([0x42, 0x4F, 0x4F, 0x4B, 0x4D, 0x4F, 0x42, 0x49], {offset: 60})) { return { ext: 'mobi', mime: 'application/x-mobipocket-ebook' }; } // File Type Box (https://en.wikipedia.org/wiki/ISO_base_media_file_format) if (check([0x66, 0x74, 0x79, 0x70], {offset: 4})) { if (check([0x6D, 0x69, 0x66, 0x31], {offset: 8})) { return { ext: 'heic', mime: 'image/heif' }; } if (check([0x6D, 0x73, 0x66, 0x31], {offset: 8})) { return { ext: 'heic', mime: 'image/heif-sequence' }; } if (check([0x68, 0x65, 0x69, 0x63], {offset: 8}) || check([0x68, 0x65, 0x69, 0x78], {offset: 8})) { return { ext: 'heic', mime: 'image/heic' }; } if (check([0x68, 0x65, 0x76, 0x63], {offset: 8}) || check([0x68, 0x65, 0x76, 0x78], {offset: 8})) { return { ext: 'heic', mime: 'image/heic-sequence' }; } } return null; };
let fs = require("fs"); let path = require("path"); let cp = require("child_process"); function runCommand(folder, args) { cp.spawn("npm", args, { env: process.env, cwd: folder, stdio: "inherit" }); } function getPackages(category) { let folder = path.join(__dirname, category); return fs .readdirSync(folder) .map(function(dir) { let fullPath = path.join(folder, dir); // check for a package.json file if (!fs.existsSync(path.join(fullPath, "package.json"))) { return; } return fullPath; }) .filter(function(pkg) { return pkg !== undefined; }); } function runCommandInCategory(category, args) { let pkgs = getPackages(category); pkgs.forEach(function(pkg) { runCommand(pkg, args); }); } let CATEGORIES = ["react", "vue", "svelte", "misc"]; let category = process.argv[2]; let args = process.argv.slice(3); if (category === "all") { CATEGORIES.forEach(function(c) { runCommandInCategory(c, args); }); } else { runCommandInCategory(category, args); }
var models=require('../models/models.js'); // Autoload :id de comentarios exports.load=function (req,res,next,commentId) { models.Comment.find({ where:{ id:Number(commentId) } }).then(function (comment) { if(comment){ req.comment=comment; next(); }else{ next(new Error('No existe commentId=' +commentId)) } }).catch(function (error) { next(error); }); }; //GET /quizes/:quizId/comments/new exports.new=function (req,res) { res.render('comments/new.ejs',{quizid:req.params.quizId, errors:[]}); }; //POST /quizes/:quizId/comments exports.create=function (req,res) { var comment =models.Comment.build( { texto:req.body.comment.texto, QuizId:req.params.quizId, }); comment .validate() .then( function (err) { if(err){ res.render('comments/new.ejs', {comment:comment,quizid:req.params.quizId,errors:err.errors}); }else{ comment //save :guarda en DB campo texto .save() .then(function () { res.redirect('/quizes/'+req.params.quizId); }); } } ).catch(function (error) { next(error); }); }; //GET /quizes/:quizId/comments/:commentId/publish exports.publish=function (req,res) { req.comment.publicado=true; req.comment.save({fields:["publicado"]}).then( function () { res.redirect('/quizes/'+req.params.quizId); }).catch(function (error) { next(error); }); };
import React, { PropTypes } from 'react'; import TodoItem from './TodoItem'; const TodoList = ({todos}) => ( <ul className="todo-list"> {todos.map(todo => <TodoItem key={todo.id} {...todo} /> )} </ul> ); TodoList.propTypes = { todos: PropTypes.array.isRequired } export default TodoList;
/* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2017 Christian Boulanger License: MIT: https://opensource.org/licenses/MIT See the LICENSE file in the project's top-level directory for details. Authors: * Christian Boulanger ([email protected], @cboulanger) ************************************************************************ */ const process = require("process"); const path = require("upath"); const semver = require("semver"); const fs = qx.tool.utils.Promisify.fs; /** * Installs a package */ qx.Class.define("qx.tool.cli.commands.package.Migrate", { extend: qx.tool.cli.commands.Package, statics: { /** * Flag to prevent recursive call to process() */ migrationInProcess: false, /** * Return the Yargs configuration object * @return {{}} */ getYargsCommand: function() { return { command: "migrate", describe: "migrates the package system to a newer version.", builder: { "verbose": { alias: "v", describe: "Verbose logging" }, "quiet": { alias: "q", describe: "No output" } } }; } }, members: { /** * Announces or applies a migration * @param {Boolean} announceOnly If true, announce the migration without * applying it. */ process: async function(announceOnly=false) { const self = qx.tool.cli.commands.package.Migrate; if (self.migrationInProcess) { return; } self.migrationInProcess = true; let needFix = false; // do not call this.base(arguments) here! let pkg = qx.tool.cli.commands.Package; let cwd = process.cwd(); let migrateFiles = [ [ path.join(cwd, pkg.lockfile.filename), path.join(cwd, pkg.lockfile.legacy_filename) ], [ path.join(cwd, pkg.cache_dir), path.join(cwd, pkg.legacy_cache_dir) ], [ path.join(qx.tool.cli.ConfigDb.getDirectory(), pkg.package_cache_name), path.join(qx.tool.cli.ConfigDb.getDirectory(), pkg.legacy_package_cache_name) ] ]; if (this.checkFilesToRename(migrateFiles).length) { let replaceInFiles = [{ files: path.join(cwd, ".gitignore"), from: pkg.legacy_cache_dir + "/", to: pkg.cache_dir + "/" }]; await this.migrate(migrateFiles, replaceInFiles, announceOnly); if (announceOnly) { needFix = true; } else { if (!this.argv.quiet) { qx.tool.compiler.Console.info("Fixing path names in the lockfile..."); } this.argv.reinstall = true; await (new qx.tool.cli.commands.package.Upgrade(this.argv)).process(); } } // Migrate all manifest in a package const registryModel = qx.tool.config.Registry.getInstance(); let manifestModels =[]; if (await registryModel.exists()) { // we have a qooxdoo.json index file containing the paths of libraries in the repository await registryModel.load(); let libraries = registryModel.getLibraries(); for (let library of libraries) { manifestModels.push((new qx.tool.config.Abstract(qx.tool.config.Manifest.config)).set({baseDir: path.join(cwd, library.path)})); } } else if (fs.existsSync(qx.tool.config.Manifest.config.fileName)) { manifestModels.push(qx.tool.config.Manifest.getInstance()); } for (const manifestModel of manifestModels) { await manifestModel.set({warnOnly: true}).load(); manifestModel.setValidate(false); needFix = false; let s = ""; if (!qx.lang.Type.isArray(manifestModel.getValue("info.authors"))) { needFix = true; s += " missing info.authors\n"; } if (!semver.valid(manifestModel.getValue("info.version"))) { needFix = true; s += " missing or invalid info.version\n"; } let obj = { "info.qooxdoo-versions": null, "info.qooxdoo-range": null, "provides.type": null, "requires.qxcompiler": null, "requires.qooxdoo-sdk": null, "requires.qooxdoo-compiler": null }; if (manifestModel.keyExists(obj)) { needFix = true; s += " obsolete entry:\n"; for (let key in obj) { if (obj[key]) { s += " " + key + "\n"; } } } if (needFix) { if (announceOnly) { qx.tool.compiler.Console.warn("*** Manifest(s) need to be updated:\n" + s); } else { manifestModel .transform("info.authors", authors => { if (authors === "") { return []; } else if (qx.lang.Type.isString(authors)) { return [{name: authors}]; } else if (qx.lang.Type.isObject(authors)) { return [{ name: authors.name, email: authors.email }]; } else if (qx.lang.Type.isArray(authors)) { return authors.map(r => qx.lang.Type.isObject(r) ? { name: r.name, email: r.email } : { name: r } ); } return []; }) .transform("info.version", version => { let coerced = semver.coerce(version); if (coerced === null) { qx.tool.compiler.Console.warn(`*** Version string '${version}' could not be interpreted as semver, changing to 1.0.0`); return "1.0.0"; } return String(coerced); }) .unset("info.qooxdoo-versions") .unset("info.qooxdoo-range") .unset("provides.type") .unset("requires.qxcompiler") .unset("requires.qooxdoo-compiler") .unset("requires.qooxdoo-sdk"); await manifestModel.save(); if (!this.argv.quiet) { qx.tool.compiler.Console.info(`Updated settings in ${manifestModel.getRelativeDataPath()}.`); } } } // check framework and compiler dependencies // if none are given in the Manifest, use the present framework and compiler const compiler_version = qx.tool.compiler.Version.VERSION; const compiler_range = manifestModel.getValue("requires.@qooxdoo/compiler") || compiler_version; const framework_version = await this.getLibraryVersion(await this.getGlobalQxPath()); const framework_range = manifestModel.getValue("requires.@qooxdoo/framework") || framework_version; if ( !semver.satisfies(compiler_version, compiler_range) || !semver.satisfies(framework_version, framework_range)) { needFix = true; if (announceOnly) { qx.tool.compiler.Console.warn(`*** Mismatch between installed framework version (${framework_version}) and/or compiler version (${compiler_version}) and the declared dependencies in the Manifest.`); } else { manifestModel .setValue("requires.@qooxdoo/compiler", "^" + compiler_version) .setValue("requires.@qooxdoo/framework", "^" + framework_version); manifestModel.setWarnOnly(false); // now model should validate await manifestModel.save(); if (!this.argv.quiet) { qx.tool.compiler.Console.info(`Updated dependencies in ${manifestModel.getRelativeDataPath()}.`); } } } manifestModel.setValidate(true); } if (!announceOnly) { let compileJsonFilename = path.join(process.cwd(), "compile.json"); let replaceInFiles = [{ files: compileJsonFilename, from: "\"qx/browser\"", to: "\"@qooxdoo/qx/browser\"" }]; await this.migrate([compileJsonFilename], replaceInFiles); } let compileJsFilename = path.join(process.cwd(), "compile.js"); if (await fs.existsAsync(compileJsFilename)) { let data = await fs.readFileAsync(compileJsFilename, "utf8"); if (data.indexOf("module.exports") < 0) { qx.tool.compiler.Console.warn("*** Your compile.js appears to be missing a `module.exports` statement - please see https://git.io/fjBqU for more details"); } } self.migrationInProcess = false; if (needFix) { if (announceOnly) { qx.tool.compiler.Console.error(`*** Try executing 'qx package migrate' to apply the changes. Alternatively, upgrade or downgrade framework and/or compiler to match the library dependencies.`); process.exit(1); } qx.tool.compiler.Console.info("Migration completed."); } else if (!announceOnly && !this.argv.quiet) { qx.tool.compiler.Console.info("Everything is up-to-date. No migration necessary."); } } } });
// Video: https://www.youtube.com/watch?v=WH5BrkzGgQY const daggy = require('daggy') const compose = (f, g) => x => f(g(x)) const id = x => x //===============Define Coyoneda========= // create constructor with props 'x' and 'f' // 'x' is our value, 'f' is a function const Coyoneda = daggy.tagged('x', 'f') // map composes the function Coyoneda.prototype.map = function(f) { return Coyoneda(this.x, compose(f, this.f)) } Coyoneda.prototype.lower = function() { return this.x.map(this.f) } // lift starts off Coyoneda with the 'id' function Coyoneda.lift = x => Coyoneda(x, id) //===============Map over a non-Functor - Set ========= // Set does not have a 'map' method const set = new Set([1, 1, 2, 3, 3, 4]) console.log("Set([1, 1, 2, 3, 3, 4]) : ", set) // Wrap set into Coyoneda with 'id' function const coyoResult = Coyoneda.lift(set) .map(x => x + 1) .map(x => `${x}!`) console.log( "Coyoneda.lift(set).map(x => x + 1).map(x => `${x}!`): ", coyoResult ) // equivalent to buildUpFn = coyoResult.f, ourSet = coyoResult.x const {f: builtUpFn, x: ourSet} = coyoResult console.log("builtUpFn is: ", builtUpFn, "; ourSet is: ", ourSet) ourSet .forEach(n => console.log(builtUpFn(n))) // 2! // 3! // 4! // 5! //===============Lift a functor in (Array) and achieve Loop fusion========= console.log( `Coyoneda.lift([1,2,3]).map(x => x * 2).map(x => x - 1).lower() : `, Coyoneda.lift([1,2,3]) .map(x => x * 2) .map(x => x - 1) .lower() ) // [ 1, 3, 5 ] //===============Make Any Type a Functor========= // Any object becomes a functor when placed in Coyoneda const Container = daggy.tagged('x') const tunacan = Container("tuna") const res = Coyoneda.lift(tunacan) .map(x => x.toUpperCase()) .map(x => x + '!') const {f: fn, x: can} = res console.log(fn(can.x)) // TUNA!
var map, boroughSearch = [], theaterSearch = [], museumSearch = []; /* Basemap Layers */ var mapquestOSM = L.tileLayer("http://{s}.tiles.mapbox.com/v3/am3081.h0po4e8k/{z}/{x}/{y}.png"); var mbTerrainSat = L.tileLayer("https://{s}.tiles.mapbox.com/v3/matt.hd0b27jd/{z}/{x}/{y}.png"); var mbTerrainReg = L.tileLayer("https://{s}.tiles.mapbox.com/v3/aj.um7z9lus/{z}/{x}/{y}.png"); var mapquestOAM = L.tileLayer("http://{s}.tiles.mapbox.com/v3/am3081.h0pml9h7/{z}/{x}/{y}.png", { maxZoom: 19, }); var mapquestHYB = L.layerGroup([L.tileLayer("http://{s}.tiles.mapbox.com/v3/am3081.h0pml9h7/{z}/{x}/{y}.png", { maxZoom: 19, }), L.tileLayer("http://{s}.mqcdn.com/tiles/1.0.0/hyb/{z}/{x}/{y}.png", { maxZoom: 19, subdomains: ["oatile1", "oatile2", "oatile3", "oatile4"], })]); map = L.map("map", { zoom: 5, center: [39, -95], layers: [mapquestOSM] }); /* Larger screens get expanded layer control */ if (document.body.clientWidth <= 767) { var isCollapsed = true; } else { var isCollapsed = false; } var baseLayers = { "Street Map": mapquestOSM, "Aerial Imagery": mapquestOAM, "Imagery with Streets": mapquestHYB }; var overlays = {}; var layerControl = L.control.layers(baseLayers, {}, { collapsed: isCollapsed }).addTo(map); /* Add overlay layers to map after defining layer control to preserver order */ var sidebar = L.control.sidebar("sidebar", { closeButton: true, position: "left" }).addTo(map); sidebar.toggle(); /* Highlight search box text on click */ $("#searchbox").click(function () { $(this).select(); }); /* Placeholder hack for IE */ if (navigator.appName == "Microsoft Internet Explorer") { $("input").each(function () { if ($(this).val() === "" && $(this).attr("placeholder") !== "") { $(this).val($(this).attr("placeholder")); $(this).focus(function () { if ($(this).val() === $(this).attr("placeholder")) $(this).val(""); }); $(this).blur(function () { if ($(this).val() === "") $(this).val($(this).attr("placeholder")); }); } }); } $(function(){ var popup = { init : function() { // position popup windowW = $(window).width(); $("#map").on("mousemove", function(e) { var x = e.pageX + 20; var y = e.pageY; var windowH = $(window).height(); if (y > (windowH - 100)) { var y = e.pageY - 100; } else { var y = e.pageY - 20; } $("#info").css({ "left": x, "top": y }); }); } }; popup.init(); })
/////////////////////////////////////////////////////////////////////////// // Copyright © Esri. All Rights Reserved. // // Licensed under the Apache License Version 2.0 (the 'License'); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an 'AS IS' BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /////////////////////////////////////////////////////////////////////////// define({ "configText": "Ustaw tekst konfiguracyjny:", "generalSettings": { "tabTitle": "Ustawienia ogólne", "measurementUnitLabel": "Jednostka miary", "currencyLabel": "Symbol miary", "roundCostLabel": "Zaokrąglaj koszt", "projectOutputSettings": "Ustawienia wynikowe projektu", "typeOfProjectAreaLabel": "Typ obszaru projektu", "bufferDistanceLabel": "Odległość buforowania", "roundCostValues": { "twoDecimalPoint": "Dwa miejsca po przecinku", "nearestWholeNumber": "Najbliższa liczba całkowita", "nearestTen": "Najbliższa dziesiątka", "nearestHundred": "Najbliższa setka", "nearestThousand": "Najbliższe tysiące", "nearestTenThousands": "Najbliższe dziesiątki tysięcy" }, "projectAreaType": { "outline": "Obrys", "buffer": "Bufor" }, "errorMessages": { "currency": "Nieprawidłowa jednostka waluty", "bufferDistance": "Nieprawidłowa odległość buforowania", "outOfRangebufferDistance": "Wartość powinna być większa niż 0 i mniejsza niż lub równa 100" } }, "projectSettings": { "tabTitle": "Ustawienia projektu", "costingGeometrySectionTitle": "Zdefiniuj obszar geograficzny na potrzeby kalkulacji kosztów (opcjonalnie)", "costingGeometrySectionNote": "Uwaga: skonfigurowanie tej warstwy umożliwi użytkownikowi konfigurowanie równań kosztów szablonów obiektów na podstawie obszarów geograficznych.", "projectTableSectionTitle": "Możliwość zapisania/wczytania ustawień projektu (opcjonalnie)", "projectTableSectionNote": "Uwaga: skonfigurowanie wszystkich tabel i warstw umożliwi użytkownikowi zapisanie/wczytanie projektu w celu ponownego wykorzystania.", "costingGeometryLayerLabel": "Warstwa geometrii kalkulacji kosztów", "fieldLabelGeography": "Pole do oznaczenia etykietą obszaru geograficznego", "projectAssetsTableLabel": "Tabela zasobów projektu", "projectMultiplierTableLabel": "Tabela kosztów dodatkowych mnożnika projektu", "projectLayerLabel": "Warstwa projektu", "configureFieldsLabel": "Skonfiguruj pola", "fieldDescriptionHeaderTitle": "Opis pola", "layerFieldsHeaderTitle": "Pole warstwy", "selectLabel": "Zaznacz", "errorMessages": { "duplicateLayerSelection": "Warstwa ${layerName} jest już wybrana", "invalidConfiguration": "Należy wybrać wartość ${fieldsString}" }, "costingGeometryHelp": "<p>Zostaną wyświetlone warstwy poligonowe z następującymi warunkami: <br/> <li>\tWarstwa musi mieć możliwość wykonywania zapytania</li><li>\tWarstwa musi zawierać pole GlobalID</li></p>", "fieldToLabelGeographyHelp": "<p>Pola znakowe i liczbowe wybranej warstwy geometrii kalkulacji kosztów zostaną wyświetlone w menu rozwijanym Pole do oznaczenia etykietą obszaru geograficznego.</p>", "projectAssetsTableHelp": "<p>Zostaną wyświetlone tabele z następującymi warunkami: <br/> <li>Tabela musi mieć możliwości edycji, czyli tworzenia, usuwania i aktualizacji</li> <li>Tabela musi zawierać sześć pól o dokładnie takich nazwach i typach danych:</li><ul><li>\tAssetGUID (pole typu GUID)</li><li>\tCostEquation (pole typu String)</li><li>\tScenario (pole typu String)</li><li>\tTemplateName (pole typu String)</li><li> GeographyGUID (pole typu GUID)</li><li>\tProjectGUID (pole typu GUID)</li></ul> </p>", "projectMultiplierTableHelp": "<p>Zostaną wyświetlone tabele z następującymi warunkami: <br/> <li>Tabela musi mieć możliwości edycji, czyli tworzenia, usuwania i aktualizacji</li> <li>Tabela musi zawierać pięć pól o dokładnie takich nazwach i typach danych:</li><ul><li>\tDescription (pole typu String)</li><li>\tType (pole typu String)</li><li>\tValue (pole typu Float/Double)</li><li>\tCostindex (pole typu Integer)</li><li> \tProjectGUID (pole typu GUID))</li></ul> </p>", "projectLayerHelp": "<p>Zostaną wyświetlone warstwy poligonowe z następującymi warunkami: <br/> <li>Warstwa musi mieć możliwości edycji, czyli tworzenia, usuwania i aktualizacji</li> <li>Warstwa musi zawierać pięć pól o dokładnie takich nazwach i typach danych:</li><ul><li>ProjectName (pole typu String)</li><li>Description (pole typu String)</li><li>Totalassetcost (pole typu Float/Double)</li><li>Grossprojectcost (pole typu Float/Double)</li><li>GlobalID (pole typu GlobalID)</li></ul> </p>", "pointLayerCentroidLabel": "Centroid warstwy punktowej", "selectRelatedPointLayerDefaultOption": "Zaznacz", "pointLayerHintText": "<p>Zostaną wyświetlone warstwy punktowe z następującymi warunkami: <br/> <li>\tWarstwa musi mieć pole 'Projectid' (typ GUID)</li><li>\tWarstwa musi mieć możliwość edycji, a więc atrybut 'Tworzenie', 'Usuwanie' i 'Aktualizacja'</li></p>" }, "layerSettings": { "tabTitle": "Ustawienia warstwy", "layerNameHeaderTitle": "Nazwa warstwy", "layerNameHeaderTooltip": "Lista warstw na mapie", "EditableLayerHeaderTitle": "Edytowalne", "EditableLayerHeaderTooltip": "Dołącz warstwę i jej szablony w widżecie kalkulacji kosztów", "SelectableLayerHeaderTitle": "Podlegające selekcji", "SelectableLayerHeaderTooltip": "Geometria z obiektu może zostać użyta do wygenerowania nowego elementu kosztu", "fieldPickerHeaderTitle": "ID projektu (opcjonalnie)", "fieldPickerHeaderTooltip": "Pole opcjonalne (typu znakowego), w którym będzie przechowywany identyfikator projektu", "selectLabel": "Zaznacz", "noAssetLayersAvailable": "Nie znaleziono warstwy zasobów na wybranej mapie internetowej", "disableEditableCheckboxTooltip": "Ta warstwa nie ma możliwości edycji", "missingCapabilitiesMsg": "Dla tej warstwy brak następujących funkcji:", "missingGlobalIdMsg": "Ta warstwa nie ma pola GlobalId", "create": "Tworzenie", "update": "Aktualizuj", "delete": "Usuwanie", "attributeSettingHeaderTitle": "Ustawienia atrybutów", "addFieldLabelTitle": "Dodaj atrybuty", "layerAttributesHeaderTitle": "Atrybuty warstwy", "projectLayerAttributesHeaderTitle": "Atrybuty warstwy projektu", "attributeSettingsPopupTitle": "Ustawienia atrybutów warstwy" }, "costingInfo": { "tabTitle": "Informacje o kalkulacji kosztów", "proposedMainsLabel": "Proponowane elementy główne", "addCostingTemplateLabel": "Dodaj szablon kalkulacji kosztów", "manageScenariosTitle": "Zarządzaj scenariuszami", "featureTemplateTitle": "Szablon obiektu", "costEquationTitle": "Równanie kosztów", "geographyTitle": "Obszar geograficzny", "scenarioTitle": "Scenariusz", "actionTitle": "Działania", "scenarioNameLabel": "Nazwa scenariusza", "addBtnLabel": "Dodaj", "srNoLabel": "Nie.", "deleteLabel": "Usuwanie", "duplicateScenarioName": "Duplikuj nazwę scenariusza", "hintText": "<div>Wskazówka: użyj następujących słów kluczowych</div><ul><li><b>{TOTALCOUNT}</b>: używa łącznej liczby zasobów tego samego typu w obszarze geograficznym</li><li><b>{MEASURE}</b>: używa długości dla zasobu liniowego i pola powierzchni dla zasobu poligonowego</li><li><b>{TOTALMEASURE}</b>: używa łącznej długości dla zasobu liniowego i łącznego pola powierzchni dla zasobu poligonowego tego samego typu w obszarze geograficznym</li></ul> Możesz użyć funkcji, takich jak:<ul><li>Math.abs(-100)</li><li>Math.floor({TOTALMEASURE})</li></ul>Należy zmodyfikować równanie kosztów zgodnie z wymaganiami projektu.", "noneValue": "Brak", "requiredCostEquation": "Niepoprawne równanie kosztów dla warstwy ${layerName} : ${templateName}", "duplicateTemplateMessage": "Istnieje podwójny wpis szablonu dla warstwy ${layerName} : ${templateName}", "defaultEquationRequired": "Wymagane jest domyślne równanie dla warstwy ${layerName} : ${templateName}", "validCostEquationMessage": "Wprowadź prawidłowe równanie kosztów", "costEquationHelpText": "Edytuj równanie kosztów zgodnie z wymaganiami projektu", "scenarioHelpText": "Wybierz scenariusz zgodnie z wymaganiami projektu", "copyRowTitle": "Kopiuj wiersz", "noTemplateAvailable": "Dodaj co najmniej jeden szablon dla warstwy ${layerName}", "manageScenarioLabel": "Zarządzaj scenariuszem", "noLayerMessage": "Wprowadź co najmniej jedną warstwę w ${tabName}", "noEditableLayersAvailable": "Warstwy, które należy oznaczyć jako możliwe do edycji na karcie ustawień warstwy", "updateProjectCostCheckboxLabel": "Aktualizuj równania projektu", "updateProjectCostEquationHint": "Wskazówka: Umożliwia użytkownikowi aktualizowanie równań kosztów zasobów, które zostały już dodane do istniejących projektów, za pomocą nowych równań zdefiniowanych niżej na podstawie szablonu obiektu, geografii i scenariusza. Jeśli brak określonej kombinacji, zostanie przyjęty koszt domyślny, tzn. geografia i scenariusz ma wartość 'None' (brak). W przypadku usunięcia szablonu obiektu ustawiony zostanie koszt równy 0." }, "statisticsSettings": { "tabTitle": "Dodatkowe ustawienia", "addStatisticsLabel": "Dodaj statystykę", "fieldNameTitle": "Pole", "statisticsTitle": "Etykieta", "addNewStatisticsText": "Dodaj nową statystykę", "deleteStatisticsText": "Usuń statystykę", "moveStatisticsUpText": "Przesuń statystykę w górę", "moveStatisticsDownText": "Przesuń statystykę w dół", "selectDeselectAllTitle": "Zaznacz wszystkie" }, "projectCostSettings": { "addProjectCostLabel": "Dodaj koszt dodatkowy projektu", "additionalCostValueColumnHeader": "Wartość", "invalidProjectCostMessage": "Nieprawidłowa wartość kosztu projektu", "additionalCostLabelColumnHeader": "Etykieta", "additionalCostTypeColumnHeader": "Typ" }, "statisticsType": { "countLabel": "Liczba", "averageLabel": "Średnia", "maxLabel": "Maksimum", "minLabel": "Minimum", "summationLabel": "Zsumowanie", "areaLabel": "Pole powierzchni", "lengthLabel": "Długość" } });
import { moduleForModel, test } from 'ember-qunit'; moduleForModel('commentator', 'Unit | Model | commentator', { // Specify the other units that are required for this test. needs: [] }); test('it exists', function(assert) { let model = this.subject(); // let store = this.store(); assert.ok(!!model); });
const fs = require('fs') const { normalize, resolve, join, sep } = require('path') function getAppDir () { let dir = process.cwd() while (dir.length && dir[dir.length - 1] !== sep) { if (fs.existsSync(join(dir, 'quasar.conf.js'))) { return dir } dir = normalize(join(dir, '..')) } const { fatal } = require('./helpers/logger') fatal(`Error. This command must be executed inside a Quasar v1+ project folder.`) } const appDir = getAppDir() const cliDir = resolve(__dirname, '..') const srcDir = resolve(appDir, 'src') const pwaDir = resolve(appDir, 'src-pwa') const ssrDir = resolve(appDir, 'src-ssr') const cordovaDir = resolve(appDir, 'src-cordova') const capacitorDir = resolve(appDir, 'src-capacitor') const electronDir = resolve(appDir, 'src-electron') const bexDir = resolve(appDir, 'src-bex') module.exports = { cliDir, appDir, srcDir, pwaDir, ssrDir, cordovaDir, capacitorDir, electronDir, bexDir, resolve: { cli: dir => join(cliDir, dir), app: dir => join(appDir, dir), src: dir => join(srcDir, dir), pwa: dir => join(pwaDir, dir), ssr: dir => join(ssrDir, dir), cordova: dir => join(cordovaDir, dir), capacitor: dir => join(capacitorDir, dir), electron: dir => join(electronDir, dir), bex: dir => join(bexDir, dir) } }
module.exports = { testClient: 'http://localhost:8089/dist/', mochaTimeout: 10000, testLayerIds: [0], seleniumTimeouts: { script: 5000, implicit: 1000, pageLoad: 5000 } }
'use strict'; import Maths from './maths.js' import FSM from './fsm.js' import { Animation, Interpolation } from './animation.js' export { Maths, FSM, Interpolation, Animation }
// Runs the wiki on port 80 var server = require('./server'); server.run(80);
var Type = require("@kaoscript/runtime").Type; module.exports = function(expect) { class Shape { constructor() { this.__ks_init(); this.__ks_cons(arguments); } __ks_init_0() { this._color = ""; } __ks_init() { Shape.prototype.__ks_init_0.call(this); } __ks_cons_0(color) { if(arguments.length < 1) { throw new SyntaxError("Wrong number of arguments (" + arguments.length + " for 1)"); } if(color === void 0 || color === null) { throw new TypeError("'color' is not nullable"); } else if(!Type.isString(color)) { throw new TypeError("'color' is not of type 'String'"); } this._color = color; } __ks_cons(args) { if(args.length === 1) { Shape.prototype.__ks_cons_0.apply(this, args); } else { throw new SyntaxError("Wrong number of arguments"); } } __ks_func_color_0() { return this._color; } color() { if(arguments.length === 0) { return Shape.prototype.__ks_func_color_0.apply(this); } throw new SyntaxError("Wrong number of arguments"); } __ks_func_draw_0() { return "I'm drawing a " + this._color + " rectangle."; } draw() { if(arguments.length === 0) { return Shape.prototype.__ks_func_draw_0.apply(this); } throw new SyntaxError("Wrong number of arguments"); } } Shape.prototype.__ks_cons_1 = function() { this._color = "red"; }; Shape.prototype.__ks_cons = function(args) { if(args.length === 0) { Shape.prototype.__ks_cons_1.apply(this); } else if(args.length === 1) { Shape.prototype.__ks_cons_0.apply(this, args); } else { throw new SyntaxError("Wrong number of arguments"); } } let shape = new Shape(); expect(shape.draw()).to.equals("I'm drawing a red rectangle."); };
'use strict' angular .module('softvApp') .controller('ModalAddhubCtrl', function (clusterFactory, tapFactory, $rootScope, areaTecnicaFactory, $uibModalInstance, opcion, ngNotify, $state) { function init() { if (opcion.opcion === 1) { vm.blockForm2 = true; muestraColonias(); muestrarelaciones(); vm.Titulo = 'Nuevo HUB'; } else if (opcion.opcion === 2) { areaTecnicaFactory.GetConHub(opcion.id, '', '', 3).then(function (data) { console.log(); vm.blockForm2 = false; var hub = data.GetConHubResult[0]; vm.Clv_Txt = hub.Clv_txt; vm.Titulo = 'Editar HUB - '+hub.Clv_txt; vm.Descripcion = hub.Descripcion; vm.clv_hub = hub.Clv_Sector; muestraColonias(); muestrarelaciones(); }); } else if (opcion.opcion === 3) { areaTecnicaFactory.GetConHub(opcion.id, '', '', 3).then(function (data) { vm.blockForm2 = true; vm.blocksave = true; var hub = data.GetConHubResult[0]; vm.Clv_Txt = hub.Clv_txt; vm.Titulo = 'Consultar HUB - '+hub.Clv_txt; vm.Descripcion = hub.Descripcion; vm.clv_hub = hub.Clv_Sector; muestraColonias(); muestrarelaciones(); }); } } function muestraColonias() { areaTecnicaFactory.GetMuestraColoniaHub(0, 0, 0) .then(function (data) { vm.colonias = data.GetMuestraColoniaHubResult; }); } function AddSector() { if (opcion.opcion === 1) { areaTecnicaFactory.GetNueHub(0, vm.Clv_Txt, vm.Descripcion).then(function (data) { if (data.GetNueHubResult > 0) { vm.clv_hub = data.GetNueHubResult; ngNotify.set('El HUB se ha registrado correctamente ,ahora puedes agregar la relación con las colonias', 'success'); $rootScope.$broadcast('reloadlista'); vm.blockForm2 = false; vm.blocksave = true; } else { ngNotify.set('La clave del HUB ya existe', 'error'); } }); } else if (opcion.opcion === 2) { areaTecnicaFactory.GetModHub(vm.clv_hub, vm.Clv_Txt, vm.Descripcion).then(function (data) { console.log(data); ngNotify.set('El HUB se ha editado correctamente', 'success'); $rootScope.$broadcast('reloadlista'); $uibModalInstance.dismiss('cancel'); }); } } function cancel() { $uibModalInstance.dismiss('cancel'); } function validaRelacion(clv) { var count = 0; vm.RelColonias.forEach(function (item) { count += (item.IdColonia === clv) ? 1 : 0; }); return (count > 0) ? true : false; } function NuevaRelacionSecColonia() { if (validaRelacion(vm.Colonia.IdColonia) === true) { ngNotify.set('La relación HUB-COLONIA ya esta establecida', 'warn'); return; } areaTecnicaFactory.GetNueRelHubColonia(vm.clv_hub, vm.Colonia.IdColonia) .then(function (data) { muestrarelaciones(); ngNotify.set('se agrego la relación correctamente', 'success'); }); } function muestrarelaciones() { areaTecnicaFactory.GetConRelHubColonia(vm.clv_hub) .then(function (rel) { console.log(rel); vm.RelColonias = rel.GetConRelHubColoniaResult; }); } function deleterelacion(clv) { clusterFactory.GetQuitarEliminarRelClusterSector(2, vm.clv_cluster, clv).then(function (data) { ngNotify.set('Se eliminó la relación correctamente', 'success'); muestrarelaciones(); }); } var vm = this; init(); vm.cancel = cancel; vm.clv_hub = 0; vm.RelColonias = []; vm.AddSector = AddSector; vm.NuevaRelacionSecColonia = NuevaRelacionSecColonia; });
'use strict'; var path = require('path'); var fs = require('fs'); module.exports = function(gen,cb) { var sections; if (gen.config.get('framework')==='bigwheel') { var model = require(path.join(process.cwd(),'src/model/index.js')); sections = ['Preloader']; Object.keys(model).forEach(function(key) { if (key.charAt(0)==="/") sections.push(key.substr(1) || 'Landing'); }); } else { sections = ['Landing']; } nextSection(sections,gen,cb); }; function nextSection(arr,gen,cb) { if (arr.length>0) { createSection(arr.shift(),gen,function() { nextSection(arr,gen,cb); }); } else { if (cb) cb(); } } function createSection(cur,gen,cb) { var name = gen.config.get('sectionNames') ? '{{section}}.js' : 'index.js'; var style = gen.config.get('sectionNames') ? '{{section}}.{{css}}' : 'style.{{css}}'; var count = 0; var total = 0; var done = function() { count++; if (count>=total) cb(); }; fs.stat('src/sections/'+cur+'/',function(err,stat) { if (err) { gen.config.set('section',cur); if (gen.config.get('framework')==='bigwheel') { var type = cur==='Preloader' ? 'preloader' : 'normal'; gen.copy('templates/sections/{{framework}}/'+type+'/index.js','src/sections/{{section}}/'+name,done); gen.copy('templates/sections/{{framework}}/'+type+'/style.css','src/sections/{{section}}/'+style,done); gen.copy('templates/sections/{{framework}}/'+type+'/template.hbs','src/sections/{{section}}/template.hbs',done); gen.copy('templates/.gitkeep','src/ui/{{section}}/.gitkeep',done); total += 4; } else if (gen.config.get('framework')==='react') { gen.copy('templates/sections/{{framework}}/index.js','src/sections/{{section}}/'+name,done); gen.copy('templates/sections/{{framework}}/style.css','src/sections/{{section}}/'+style,done); total += 2; } } else { done(); } }); };
'use strict'; describe('Controller: MainCtrl', function () { // load the controller's module beforeEach(module('pillzApp')); var MainCtrl, scope, $httpBackend; // Initialize the controller and a mock scope beforeEach(inject(function (_$httpBackend_, $controller, $rootScope) { $httpBackend = _$httpBackend_; $httpBackend.expectGET('/api/awesomeThings') .respond(['HTML5 Boilerplate', 'AngularJS', 'Karma', 'Express']); scope = $rootScope.$new(); MainCtrl = $controller('MainCtrl', { $scope: scope }); })); it('should attach a list of awesomeThings to the scope', function () { expect(scope.awesomeThings).toBeUndefined(); $httpBackend.flush(); expect(scope.awesomeThings.length).toBe(4); }); });
'use strict'; var assert = require('power-assert'); var resetStorage = require('./'); var dbName = 'test-item'; describe('#localStorage', function () { beforeEach(function (done) { localStorage.clear(); done(); }); it('should save value', function () { var expected = { foo: 'bar', goo: 'nuu' }; localStorage.setItem('item', JSON.stringify(expected)); assert.deepEqual(expected, JSON.parse(localStorage.getItem('item'))); }); it('should clear value', function (done) { var input = { foo: 'bar', goo: 'nuu' }; localStorage.setItem('item', JSON.stringify(input)); resetStorage .localStorage() .then(function () { assert.equal(null, localStorage.getItem('item')); done(); }); }); }); describe('#indexedDB', function () { var db; beforeEach(function (done) { var req = indexedDB.deleteDatabase('test-item'); req.onsuccess = function() { done(); }; }); // http://dev.classmethod.jp/ria/html5/html5-indexed-database-api/ it('should save value', function (done) { if (!indexedDB) { throw new Error('Your browser doesn\'t support a stable version of IndexedDB.'); } var openRequest = indexedDB.open(dbName, 2); var key = 'foo'; var value = 'bar'; var expected = {}; expected[key] = value; openRequest.onerror = function(event) { throw new Error(event.toString); }; openRequest.onupgradeneeded = function(event) { db = event.target.result; var store = db.createObjectStore('mystore', { keyPath: 'mykey'}); store.createIndex('myvalueIndex', 'myvalue'); }; openRequest.onsuccess = function() { db = openRequest.result; var transaction = db.transaction(['mystore'], 'readwrite'); var store = transaction.objectStore('mystore'); var request = store.put({ mykey: key, myvalue: value }); request.onsuccess = function () { var transaction = db.transaction(['mystore'], 'readwrite'); var store = transaction.objectStore('mystore'); var request = store.get(key); request.onsuccess = function (event) { assert.equal(value, event.target.result.myvalue); db.close(); done(); }; request.onerror = function (event) { db.close(); throw new Error(event.toString); }; }; request.onerror = function(event) { db.close(); throw new Error(event.toString); }; }; }); it.skip('should clear value. Writing this test is too hard for me.', function (done) { if (true) {// eslint-disable-line no-constant-condition throw new Error(); } if (!indexedDB) { throw new Error('Your browser doesn\'t support a stable version of IndexedDB.'); } var openRequest = indexedDB.open(dbName, 2); var key = 'foo'; var value = 'bar'; var expected = {}; expected[key] = value; openRequest.onerror = function(event) { throw new Error(event.toString); }; openRequest.onupgradeneeded = function(event) { db = event.target.result; var store = db.createObjectStore('mystore', { keyPath: 'mykey'}); store.createIndex('myvalueIndex', 'myvalue'); }; openRequest.onsuccess = function() { db = openRequest.result; var transaction = db.transaction(['mystore'], 'readwrite'); var store = transaction.objectStore('mystore'); var request = store.put({ mykey: key, myvalue: value }); request.onsuccess = function () { db.close(); var openRequest = indexedDB.open(dbName, 2); openRequest.onerror = function(event) { throw new Error(event.toString); }; openRequest.onsuccess = function() { var db = openRequest.result; var transaction = db.transaction(['mystore'], 'readwrite'); var store = transaction.objectStore('mystore'); var request = store.get(key); request.onsuccess = function (event) { assert.equal(value, event.target.result.myvalue); db.close(); done(); }; request.onerror = function (event) { db.close(); throw new Error(event.toString); }; }; }; request.onerror = function(event) { db.close(); throw new Error(event.toString); }; }; }); });
import React from 'react' import DocumentTitle from 'react-document-title' import ReactHeight from 'react-height' import Header from './header/header' import Content from './content/content' import Footer from './footer/footer' import { APP_NAME } from '../constants' class Layout extends React.Component { render() { const hfStyle = { flex: 'none' } const contentStyle = { flex: 1 } const containerStyle = { display: 'flex', minHeight: window.innerHeight, flexDirection: 'column' } return ( <div style={containerStyle}> <DocumentTitle title={APP_NAME}/> <Header style={hfStyle}/> <Content style={contentStyle}/> <Footer style={hfStyle}/> </div> ) } } export default Layout
var i18n = require('i18n'); var _ = require('lodash'); exports.register = function (plugin, options, next) { i18n.configure(options); plugin.ext('onPreResponse', function (request, extNext) { // If is an error message if(request.response.isBoom) { i18n.setLocale(getLocale(request, options)); request.response.output.payload.message = i18n.__(request.response.output.payload.message); return extNext(request.response); } extNext(); }); next(); }; var getLocale = function(request, options) { i18n.init(request.raw.req); if(_.contains(_.keys(i18n.getCatalog()), request.raw.req.language)) { return request.raw.req.language; } else { return options.defaultLocale; } };
import expect from 'expect'; import createStore from './createStore'; describe('createStore()', () => { let store; beforeEach(() => { store = createStore(); }); it('should write data and return its key when write() is called', () => { const hash = store.write({ hello: 'world' }); expect(hash).toBe(store.keys()[0]); }); it('should return data when read() is called with a valid key', () => { const hash = store.write({ hello: 'world' }); expect(store.read(hash)).toEqual({ hello: 'world' }); }); it('should throw an error when read() is called with an invalid key', () => { store.write({ hello: 'world' }); expect(() => store.read('wrong')).toThrow(/Entry wrong not found/); }); it('should return all keys when keys() is called', () => { const hash1 = store.write({ hello: 'world' }); const hash2 = store.write({ hello2: 'world2' }); expect(store.keys()).toEqual([ hash1, hash2, ]); }); it('should return all store content when toJSON() is called', () => { const hash1 = store.write({ hello: 'world' }); const hash2 = store.write({ hello2: 'world2' }); expect(store.toJSON()).toEqual({ [hash1]: { hello: 'world', }, [hash2]: { hello2: 'world2', }, }); }); it('should init the store if a snapshot is given', () => { const localStore = createStore({ ae3: { hello: 'world', }, }); expect(localStore.read('ae3')).toEqual({ hello: 'world', }); }); it('should write data with the given hash if provided', () => { const hash = store.write({ hello: 'world' }, 'forcedHash'); expect(hash).toBe('forcedHash'); expect(store.keys()[0]).toBe('forcedHash'); expect(store.read('forcedHash')).toEqual({ hello: 'world' }); }); it('should notify any subscriber when something is written into the store', () => { const subscriber1 = expect.createSpy(); store.subscribe(subscriber1); const subscriber2 = expect.createSpy(); store.subscribe(subscriber2); const hash = store.write({ hello: 'world' }); expect(subscriber1).toHaveBeenCalledWith(hash); expect(subscriber2).toHaveBeenCalledWith(hash); store.unsubscribe(subscriber1); const hash2 = store.write({ hello: 'earth' }); expect(subscriber1.calls.length).toBe(1); expect(subscriber2).toHaveBeenCalledWith(hash2); expect(subscriber2.calls.length).toBe(2); }); });
var xml = require('xmlbuilder'); var fs = require('fs'); /** * Function is used to create plis file which is required for downloading ios app. * @param {string} name app name * @param {string} path path to application * @param {string} title title for alert * @param {Function} callback function which will be called when plist file is created */ function creatPlist(name, path, title, callback){ var d = xml.create('plist', {'version':'1.0'}) .ele('dict') .ele('key','items').up() .ele('array') .ele('dict') .ele('key','assets').up() .ele('array') .ele('dict') .ele('key','kind').up() .ele('string','software-package').up() .ele('key','url').up() .ele('string',path).up() .up() .up() .ele('key','metadata').up() .ele('dict') .ele('key','bundle-identifier').up() .ele('string', name).up() .ele('key', 'kind').up() .ele('string','software').up() .ele('key','title').up() .ele('string', title) .up() .up() .up() .up() .up() .end({ pretty: true}); //generate unique file path:) use this for now. var filePath = './processing/file' + new Date().getMilliseconds() + '.plist'; fs.writeFile(filePath, d, function(err){ callback(err,filePath); }); console.log(xml); } //--------------EXPORTS---------------// exports.creatPlist = creatPlist;
'use strict'; define([], function($) { var Util = class { static charToLineCh(string, char) { var stringUpToChar = string.substr(0, char); var lines = stringUpToChar.split("\n"); return { line: lines.length - 1, ch: lines[lines.length - 1].length }; } }; return Util; });
function initBtnStartAlgo(){ $('#btn_startDispatch').bind('click', function(event) { event.preventDefault(); initAlgo(); createResultPanel("div_resultPanel"); doRound(); printRound("resultRegion"); printResultPersonal("resultPersonal"); createDownloadableContent(); }); } // 初始化變數、將 html 清空 function initAlgo(){ // 有時會發生役男進來後,才臨時驗退的情形,我們會在其分數欄位填入 "NA" ,在算平均成績時不把他算進去 // 注意這裡只是預設值,當程式執行時,此預設值會被算出的值取代 // Fixed: 2014, Dec, 11 var not_here_student = 0; students = new Array(); avgScore = 0.0; for(x in regionDatas){ regionDatas[x].queue = new Array(); regionDatas[x].resultArray = new Array(); } for(var i=1;i<=TOTAL_STUDENT;i++){ var student = new Student(); student.id = i; student.score = $('#score'+i).val(); student.home = $('#wishList'+i+'_0').val(); student.wish1 = $('#wishList'+i+'_1').val(); student.result = NO_REGION_RESULT; student.homeFirst = $('#homeFirst'+i).is(':checked'); // Add to lists students[i-1] = student; // 處理臨時被驗退的 if($('#score'+i).val()==="NA"){ students[i-1].result = "NA"; // 要給予跟 NO_REGION_RESULT 不一樣的值 not_here_student++; continue; } // parserInt() used to cause lost of digits. Fixed: 2014, Oct 29 avgScore += parseFloat(student.score); } avgScore = avgScore/(TOTAL_STUDENT-not_here_student); var size = Math.pow(10, 2); avgScore = Math.round(avgScore * size) / size; } // 畫出 平均分數、Round1、Round2、Round3、分發結果(依個人)的那個 nav-tabs function createResultPanel(printToDivID){ var str = '<div class="panel panel-info">'; str += '<div class="panel-heading">'; str += '<h3 class="panel-title">第 ' + WHAT_T + ' 梯 預排結果 ( 平均分數:'+avgScore+' )</h3>'; str += '</div>'; str += '<div class="panel-body" id="div_dispatchResult">'; str += '<ul class="nav nav-tabs">'; str += '<li class="active"><a href="#resultRegion" data-toggle="tab">地區</a></li>'; str += '<li><a href="#resultPersonal" data-toggle="tab">個人</a></li>'; // color block 色塊 str += '<li><canvas width="13" height="13" class="colorBlock" style="background:' + fontColors.typeHome + ';"></canvas> 家因</li>'; str += '<li><canvas width="13" height="13" class="colorBlock" style="background:' + fontColors.type1 + ';"></canvas> 高均+戶籍</li>'; str += '<li><canvas width="13" height="13" class="colorBlock" style="background:' + fontColors.type2 + ';"></canvas> 高均+非戶籍</li>'; str += '<li><canvas width="13" height="13" class="colorBlock" style="background:' + fontColors.type3 + ';"></canvas> 低均+戶籍地</li>'; str += '<li><canvas width="13" height="13" class="colorBlock" style="background:' + fontColors.type4 + ';"></canvas> 低均+非戶籍</li>'; str += '<li><canvas width="13" height="13" class="colorBlock" style="background:' + fontColors.typeKicked + ';"></canvas> 被擠掉</li>'; str += '</ul>'; str += '<div id="resultTabContent" class="tab-content">'; str += ' <div class="tab-pane fade active in" id="resultRegion"></div>'; str += ' <div class="tab-pane fade" id="resultPersonal"></div>'; str += '</div>'; str += '</div>'; str += '<div class="panel-fotter">'; str += ' <div class="btn-group btn-group-justified">'; str += ' <a href="" class="btn btn-primary" id="btn_downloadTXT">下載程式可讀取的格式(.txt)</a>'; str += ' <a href="" class="btn btn-info" id="btn_downloadCSVRegion">給輔導組(照地區.csv)</a>'; str += ' <a href="" class="btn btn-success" id="btn_downloadCSVPersonnel">給輔導組(照個人.csv)</a>'; str += ' </div>'; str += '</div>'; str += '</div>'; $("#"+printToDivID).html(str); } // 將 分發規則 用演算法實作 function doRound(){ // 可以清空 queue,因為我們可以直接從 student.result 的內容來找出還沒被分發的學生,送進下一 round for(var i=0;i<regionDatas.length;i++){ regionDatas[i].queue = new Array(); } // Step 1: 將學生加入其第N志願的 queue (N depend on round) var regionDatasLength = regionDatas.length; for(var k=0;k<TOTAL_STUDENT;k++){ // 如果學生已經分發到某的地點,就不須再分發,可跳過直接看下個學生。 if(students[k].result != NO_REGION_RESULT){ continue; } // TODO: 這邊改用 key hash 應該會漂亮、效能也更好 for(var i=0;i<regionDatasLength;i++){ if(students[k].wish1 == regionDatas[i].name){ regionDatas[i].queue.push(students[k]); } } } // Step 2: 將每個單位的 queue 裡面的學生互相比較,取出最適合此單位的學生放入此單位的 resultArray for(var i=0;i<regionDatasLength;i++){ var region = regionDatas[i]; // 此單位名額已經滿,跳過 if(region.resultArray.length == region.available){ continue; } // 要去的人數 小於等於 開放的名額,每個人都錄取 else if(region.queue.length <= region.available){ // 其實可以不用排序,但是排序之後印出來比較好看 region.queue.sort(function(a, b){return a.score-b.score}); popItemFromQueueAndPushToResultArray(region, region.queue.length); } // 要去的人數 大於 開放的名額,依照 分發規則 找出最適合此單位的學生放入此單位的 resultArray else{ // 不管是中央還是地方,都要比較成績,所以先依照成績排序 region.queue.sort(function(a, b){return a.score-b.score}); // 依照成績排序後是"由小到大",亦即 [30分, 40分, 60分, 90分, 100分] // 考慮到之後的 Array.pop() 是 pop 出"最後一個"物件,這樣排列比較方便之後的處理 cruelFunction(i, region); } } } // This function is so cruel that I cannot even look at it. function cruelFunction(regionID, region){ if(regionID<=3){ // 中央只有比成績,不考慮戶籍地,因此可直接依成績排序找出錄取的學生 popItemFromQueueAndPushToResultArray(region, region.available); }else{ // 地方單位在依照成績排序後,再把 "過均標" 且 "符合戶籍地" 的往前排 // 剛剛已經過成績順序了,現在要分別對“過均標”跟“沒過均標”的做戶籍地優先的排序 region.queue.sort(function(a, b){ if((a.score >= avgScore && b.score >= avgScore) || (a.score < avgScore && b.score < avgScore)){ if(a.home == region.homeName && b.home != region.homeName){ return 1; }else if(b.home == region.homeName && a.home != region.homeName){ return -1; } } return 0; }); // 接下來,把家因的抓出來,要優先分發,所以丟到 queue 最後面。(等等 pop()時會變成最前面 ) region.queue.sort(function(a, b){ if(a.homeFirst==true){ return 1; } return 0; }); // 排完後再依照順序找出錄取的學生 popItemFromQueueAndPushToResultArray(region, region.available); } } // 從 region 的排序過後的 queue 裡面,抓出 numberOfItems 個學生,丟進 resultArray 裡面 function popItemFromQueueAndPushToResultArray(region, numberOfItems){ for(var k=0;k<numberOfItems;k++){ region.resultArray.push(region.queue.pop()); } assignStudentToRegion(region.homeName, region.resultArray); } // 將已經被分配到某地區的學生的 result attribute 指定為該地區。(resultArray[] 的 items 為學生,擁有 result ) function assignStudentToRegion(regionName, resultArray){ var length = resultArray.length; for(var i=0;i<length;i++){ resultArray[i].result = regionName; } }
'use strict'; angular.module('articles').controller('ChangeHeaderImageController', ['$scope', '$timeout', '$stateParams', '$window', 'Authentication', 'FileUploader', 'Articles', function ($scope, $timeout, $stateParams, $window, Authentication, FileUploader, Articles) { $scope.user = Authentication.user; $scope.article = Articles.get({ articleId: $stateParams.articleId }); $scope.imageURL = $scope.article.headerMedia || null; // Create file uploader instance $scope.uploader = new FileUploader({ url: 'api/articles/' + $stateParams.articleId + '/headerimage', alias: 'newHeaderImage' }); // Set file uploader image filter $scope.uploader.filters.push({ name: 'imageFilter', fn: function (item, options) { var type = '|' + item.type.slice(item.type.lastIndexOf('/') + 1) + '|'; return '|jpg|png|jpeg|bmp|gif|'.indexOf(type) !== -1; } }); // Called after the user selected a new picture file $scope.uploader.onAfterAddingFile = function (fileItem) { if ($window.FileReader) { var fileReader = new FileReader(); fileReader.readAsDataURL(fileItem._file); fileReader.onload = function (fileReaderEvent) { $timeout(function () { $scope.imageURL = fileReaderEvent.target.result; }, 0); }; } }; // Called after the article has been assigned a new header image $scope.uploader.onSuccessItem = function (fileItem, response, status, headers) { // Show success message $scope.success = true; // Populate user object $scope.user = Authentication.user = response; // Clear upload buttons $scope.cancelUpload(); }; // Called after the user has failed to upload a new picture $scope.uploader.onErrorItem = function (fileItem, response, status, headers) { // Clear upload buttons $scope.cancelUpload(); // Show error message $scope.error = response.message; }; // Change article header image $scope.uploadHeaderImage = function () { console.log($scope); // Clear messages $scope.success = $scope.error = null; // Start upload $scope.uploader.uploadAll(); }; // Cancel the upload process $scope.cancelUpload = function () { $scope.uploader.clearQueue(); //$scope.imageURL = $scope.article.profileImageURL; }; } ]);
/** @jsx h */ import h from '../../../helpers/h' import { Mark } from '../../../..' export default function(change) { change.addMark( Mark.create({ type: 'bold', data: { thing: 'value' }, }) ) } export const input = ( <value> <document> <paragraph> <anchor />w<focus />ord </paragraph> </document> </value> ) export const output = ( <value> <document> <paragraph> <anchor /> <b thing="value">w</b> <focus />ord </paragraph> </document> </value> )
var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; function __export(m) { for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; } var Parameter = require("../src/Parameter"); var OT = require("./FRP"); var glow = require("./glow"); __export(require("./types")); var DEBUG = false; /** * Each frame an animation is provided a CanvasTick. The tick exposes access to the local animation time, the * time delta between the previous frame (dt) and the drawing context. Animators typically use the drawing context * directly, and pass the clock onto any time varying parameters. */ var CanvasTick = (function (_super) { __extends(CanvasTick, _super); function CanvasTick(clock, dt, ctx, events, previous) { _super.call(this, clock, dt, previous); this.clock = clock; this.dt = dt; this.ctx = ctx; this.events = events; this.previous = previous; } CanvasTick.prototype.copy = function () { return new CanvasTick(this.clock, this.dt, this.ctx, this.events, this.previous); }; CanvasTick.prototype.save = function () { var cp = _super.prototype.save.call(this); cp.ctx.save(); return cp; }; CanvasTick.prototype.restore = function () { var cp = _super.prototype.restore.call(this); cp.ctx.restore(); return cp; }; return CanvasTick; })(OT.BaseTick); exports.CanvasTick = CanvasTick; var Animation = (function (_super) { __extends(Animation, _super); function Animation(attach) { _super.call(this, attach); this.attach = attach; } /** * subclasses should override this to create another animation of the same type * @param attach */ Animation.prototype.create = function (attach) { if (attach === void 0) { attach = function (nop) { return nop; }; } return new Animation(attach); }; /** * Affect this with an effect to create combined animation. * Debug messages are inserted around the effect (e.g. a mutation to the canvas). * You can expose time varying or constant parameters to the inner effect using the optional params. */ Animation.prototype.loggedAffect = function (label, effectBuilder, param1, param2, param3, param4, param5, param6, param7, param8) { if (DEBUG) console.log(label + ": build"); return this.affect(function () { if (DEBUG) console.log(label + ": attach"); var effect = effectBuilder(); return function (tick, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8) { if (DEBUG) { var elements = []; if (arg1) elements.push(arg1 + ""); if (arg2) elements.push(arg2 + ""); if (arg3) elements.push(arg3 + ""); if (arg4) elements.push(arg4 + ""); if (arg5) elements.push(arg5 + ""); if (arg6) elements.push(arg6 + ""); if (arg7) elements.push(arg7 + ""); if (arg8) elements.push(arg8 + ""); console.log(label + ": tick (" + elements.join(",") + ")"); } effect(tick, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8); }; }, (param1 ? Parameter.from(param1) : undefined), (param2 ? Parameter.from(param2) : undefined), (param3 ? Parameter.from(param3) : undefined), (param4 ? Parameter.from(param4) : undefined), (param5 ? Parameter.from(param5) : undefined), (param6 ? Parameter.from(param6) : undefined), (param7 ? Parameter.from(param7) : undefined), (param8 ? Parameter.from(param8) : undefined)); }; Animation.prototype.velocity = function (velocity) { if (DEBUG) console.log("velocity: build"); return this.affect(function () { if (DEBUG) console.log("velocity: attach"); var pos = [0.0, 0.0]; return function (tick, velocity) { if (DEBUG) console.log("velocity: tick", velocity, pos); tick.ctx.transform(1, 0, 0, 1, pos[0], pos[1]); pos[0] += velocity[0] * tick.dt; pos[1] += velocity[1] * tick.dt; }; }, Parameter.from(velocity)); }; Animation.prototype.tween_linear = function (from, to, time) { return this.affect(function () { var t = 0; if (DEBUG) console.log("tween: init"); return function (tick, from, to, time) { t = t + tick.dt; if (t > time) t = time; var x = from[0] + (to[0] - from[0]) * t / time; var y = from[1] + (to[1] - from[1]) * t / time; if (DEBUG) console.log("tween: tick", x, y, t); tick.ctx.transform(1, 0, 0, 1, x, y); }; }, Parameter.from(from), Parameter.from(to), Parameter.from(time)); }; Animation.prototype.glow = function (decay) { if (decay === void 0) { decay = 0.1; } return glow.glow(this, decay); }; // Canvas API /** * Dynamic chainable wrapper for strokeStyle in the canvas API. */ Animation.prototype.strokeStyle = function (color) { return this.loggedAffect("strokeStyle", function () { return function (tick, color) { return tick.ctx.strokeStyle = color; }; }, color); }; /** * Dynamic chainable wrapper for fillStyle in the canvas API. */ Animation.prototype.fillStyle = function (color) { return this.loggedAffect("fillStyle", function () { return function (tick, color) { return tick.ctx.fillStyle = color; }; }, color); }; /** * Dynamic chainable wrapper for shadowColor in the canvas API. */ Animation.prototype.shadowColor = function (color) { return this.loggedAffect("shadowColor", function () { return function (tick, color) { return tick.ctx.shadowColor = color; }; }, color); }; /** * Dynamic chainable wrapper for shadowBlur in the canvas API. */ Animation.prototype.shadowBlur = function (level) { return this.loggedAffect("shadowBlur", function () { return function (tick, level) { return tick.ctx.shadowBlur = level; }; }, level); }; /** * Dynamic chainable wrapper for shadowOffsetX and shadowOffsetY in the canvas API. */ Animation.prototype.shadowOffset = function (xy) { return this.loggedAffect("shadowOffset", function () { return function (tick, xy) { tick.ctx.shadowOffsetX = xy[0]; tick.ctx.shadowOffsetY = xy[1]; }; }, xy); }; /** * Dynamic chainable wrapper for lineCap in the canvas API. */ Animation.prototype.lineCap = function (style) { return this.loggedAffect("lineCap", function () { return function (tick, arg) { return tick.ctx.lineCap = arg; }; }, style); }; /** * Dynamic chainable wrapper for lineJoin in the canvas API. */ Animation.prototype.lineJoin = function (style) { return this.loggedAffect("lineJoin", function () { return function (tick, arg) { return tick.ctx.lineJoin = arg; }; }, style); }; /** * Dynamic chainable wrapper for lineWidth in the canvas API. */ Animation.prototype.lineWidth = function (width) { return this.loggedAffect("lineWidth", function () { return function (tick, arg) { return tick.ctx.lineWidth = arg; }; }, width); }; /** * Dynamic chainable wrapper for miterLimit in the canvas API. */ Animation.prototype.miterLimit = function (limit) { return this.loggedAffect("miterLimit", function () { return function (tick, arg) { return tick.ctx.miterLimit = arg; }; }, limit); }; /** * Dynamic chainable wrapper for rect in the canvas API. */ Animation.prototype.rect = function (xy, width_height) { return this.loggedAffect("rect", function () { return function (tick, xy, width_height) { return tick.ctx.rect(xy[0], xy[1], width_height[0], width_height[1]); }; }, xy, width_height); }; /** * Dynamic chainable wrapper for fillRect in the canvas API. */ Animation.prototype.fillRect = function (xy, width_height) { return this.loggedAffect("fillRect", function () { return function (tick, xy, width_height) { return tick.ctx.fillRect(xy[0], xy[1], width_height[0], width_height[1]); }; }, xy, width_height); }; /** * Dynamic chainable wrapper for strokeRect in the canvas API. */ Animation.prototype.strokeRect = function (xy, width_height) { return this.loggedAffect("strokeRect", function () { return function (tick, xy, width_height) { return tick.ctx.strokeRect(xy[0], xy[1], width_height[0], width_height[1]); }; }, xy, width_height); }; /** * Dynamic chainable wrapper for clearRect in the canvas API. */ Animation.prototype.clearRect = function (xy, width_height) { return this.loggedAffect("clearRect", function () { return function (tick, xy, width_height) { return tick.ctx.clearRect(xy[0], xy[1], width_height[0], width_height[1]); }; }, xy, width_height); }; /** * Encloses the inner animation with a beginpath() and endpath() from the canvas API. * * This returns a path object which events can be subscribed to */ Animation.prototype.withinPath = function (inner) { return this.pipe(new PathAnimation(function (upstream) { if (DEBUG) console.log("withinPath: attach"); var beginPathBeforeInner = upstream.tapOnNext(function (tick) { return tick.ctx.beginPath(); }); return inner.attach(beginPathBeforeInner).tapOnNext(function (tick) { return tick.ctx.closePath(); }); })); }; /** * Dynamic chainable wrapper for fill in the canvas API. */ Animation.prototype.closePath = function () { return this.loggedAffect("closePath", function () { return function (tick) { return tick.ctx.closePath(); }; }); }; /** * Dynamic chainable wrapper for fill in the canvas API. */ Animation.prototype.beginPath = function () { return this.loggedAffect("beginPath", function () { return function (tick) { return tick.ctx.beginPath(); }; }); }; /** * Dynamic chainable wrapper for fill in the canvas API. */ Animation.prototype.fill = function () { return this.loggedAffect("fill", function () { return function (tick) { return tick.ctx.fill(); }; }); }; /** * Dynamic chainable wrapper for stroke in the canvas API. */ Animation.prototype.stroke = function () { return this.loggedAffect("stroke", function () { return function (tick) { return tick.ctx.stroke(); }; }); }; /** * Dynamic chainable wrapper for moveTo in the canvas API. */ Animation.prototype.moveTo = function (xy) { return this.loggedAffect("moveTo", function () { return function (tick, xy) { return tick.ctx.moveTo(xy[0], xy[1]); }; }, xy); }; /** * Dynamic chainable wrapper for lineTo in the canvas API. */ Animation.prototype.lineTo = function (xy) { return this.loggedAffect("lineTo", function () { return function (tick, xy) { return tick.ctx.lineTo(xy[0], xy[1]); }; }, xy); }; /** * Dynamic chainable wrapper for clip in the canvas API. */ Animation.prototype.clip = function () { return this.loggedAffect("clip", function () { return function (tick) { return tick.ctx.clip(); }; }); }; /** * Dynamic chainable wrapper for quadraticCurveTo in the canvas API. Use with withinPath. */ Animation.prototype.quadraticCurveTo = function (control, end) { return this.loggedAffect("quadraticCurveTo", function () { return function (tick, arg1, arg2) { return tick.ctx.quadraticCurveTo(arg1[0], arg1[1], arg2[0], arg2[1]); }; }, control, end); }; /** * Dynamic chainable wrapper for bezierCurveTo in the canvas API. Use with withinPath. */ Animation.prototype.bezierCurveTo = function (control1, control2, end) { return this.loggedAffect("bezierCurveTo", function () { return function (tick, arg1, arg2, arg3) { return tick.ctx.bezierCurveTo(arg1[0], arg1[1], arg2[0], arg2[1], arg3[0], arg3[1]); }; }, control1, control2, end); }; /** * Dynamic chainable wrapper for arc in the canvas API. Use with withinPath. */ Animation.prototype.arcTo = function (tangent1, tangent2, radius) { return this.loggedAffect("arcTo", function () { return function (tick, arg1, arg2, arg3) { return tick.ctx.arcTo(arg1[0], arg1[1], arg2[0], arg2[1], arg3); }; }, tangent1, tangent2, radius); }; /** * Dynamic chainable wrapper for scale in the canvas API. */ Animation.prototype.scale = function (xy) { return this.loggedAffect("scale", function () { return function (tick, xy) { return tick.ctx.scale(xy[0], xy[1]); }; }, xy); }; /** * Dynamic chainable wrapper for rotate in the canvas API. */ Animation.prototype.rotate = function (clockwiseRadians) { return this.loggedAffect("rotate", function () { return function (tick, arg) { return tick.ctx.rotate(arg); }; }, clockwiseRadians); }; /** * Dynamic chainable wrapper for translate in the canvas API. */ Animation.prototype.translate = function (xy) { return this.loggedAffect("translate", function () { return function (tick, xy) { tick.ctx.translate(xy[0], xy[1]); }; }, xy); }; /** * Dynamic chainable wrapper for translate in the canvas API. * [ a c e * b d f * 0 0 1 ] */ Animation.prototype.transform = function (a, b, c, d, e, f) { return this.loggedAffect("transform", function () { return function (tick, arg1, arg2, arg3, arg4, arg5, arg6) { return tick.ctx.transform(arg1, arg2, arg3, arg4, arg5, arg6); }; }, a, b, c, d, e, f); }; /** * Dynamic chainable wrapper for setTransform in the canvas API. */ Animation.prototype.setTransform = function (a, b, c, d, e, f) { return this.loggedAffect("setTransform", function () { return function (tick, arg1, arg2, arg3, arg4, arg5, arg6) { return tick.ctx.setTransform(arg1, arg2, arg3, arg4, arg5, arg6); }; }, a, b, c, d, e, f); }; /** * Dynamic chainable wrapper for font in the canvas API. */ Animation.prototype.font = function (style) { return this.loggedAffect("font", function () { return function (tick, arg) { return tick.ctx.font = arg; }; }, style); }; /** * Dynamic chainable wrapper for textAlign in the canvas API. */ Animation.prototype.textAlign = function (style) { return this.loggedAffect("textAlign", function () { return function (tick, arg) { return tick.ctx.textAlign = arg; }; }, style); }; /** * Dynamic chainable wrapper for textBaseline in the canvas API. */ Animation.prototype.textBaseline = function (style) { return this.loggedAffect("textBaseline", function () { return function (tick, arg) { return tick.ctx.textBaseline = arg; }; }, style); }; /** * Dynamic chainable wrapper for textBaseline in the canvas API. */ Animation.prototype.fillText = function (text, xy, maxWidth) { if (maxWidth) { return this.loggedAffect("fillText", function () { return function (tick, text, xy, maxWidth) { return tick.ctx.fillText(text, xy[0], xy[1], maxWidth); }; }, text, xy, maxWidth); } else { return this.loggedAffect("fillText", function () { return function (tick, text, xy, maxWidth) { return tick.ctx.fillText(text, xy[0], xy[1]); }; }, text, xy); } }; /** * Dynamic chainable wrapper for drawImage in the canvas API. */ Animation.prototype.drawImage = function (img, xy) { return this.loggedAffect("drawImage", function () { return function (tick, img, xy) { return tick.ctx.drawImage(img, xy[0], xy[1]); }; }, img, xy); }; /** * * Dynamic chainable wrapper for globalCompositeOperation in the canvas API. */ Animation.prototype.globalCompositeOperation = function (operation) { return this.loggedAffect("globalCompositeOperation", function () { return function (tick, arg) { return tick.ctx.globalCompositeOperation = arg; }; }, operation); }; Animation.prototype.arc = function (center, radius, radStartAngle, radEndAngle, counterclockwise) { if (counterclockwise === void 0) { counterclockwise = false; } return this.loggedAffect("arc", function () { return function (tick, arg1, arg2, arg3, arg4, counterclockwise) { return tick.ctx.arc(arg1[0], arg1[1], arg2, arg3, arg4, counterclockwise); }; }, center, radius, radStartAngle, radEndAngle, counterclockwise); }; return Animation; })(OT.SignalPipe); exports.Animation = Animation; function create(attach) { if (attach === void 0) { attach = function (x) { return x; }; } return new Animation(attach); } exports.create = create; var PathAnimation = (function (_super) { __extends(PathAnimation, _super); function PathAnimation() { _super.apply(this, arguments); } return PathAnimation; })(Animation); exports.PathAnimation = PathAnimation; function save(width, height, path) { var GIFEncoder = require('gifencoder'); var fs = require('fs'); var encoder = new GIFEncoder(width, height); encoder.createReadStream() .pipe(encoder.createWriteStream({ repeat: 10000, delay: 100, quality: 1 })) .pipe(fs.createWriteStream(path)); encoder.start(); return new Animation(function (upstream) { return upstream.tap(function (tick) { if (DEBUG) console.log("save: wrote frame"); encoder.addFrame(tick.ctx); }, function () { console.error("save: not saved", path); }, function () { console.log("save: saved", path); encoder.finish(); }); }); } exports.save = save;
import { h } from 'preact'; import JustNotSorry from '../src/components/JustNotSorry.js'; import { configure, mount } from 'enzyme'; import Adapter from 'enzyme-adapter-preact-pure'; configure({ adapter: new Adapter() }); describe('JustNotSorry', () => { const justNotSorry = mount(<JustNotSorry />); let editableDiv1; let editableDiv2; let editableDiv3; let wrapper; let instance; const mutationObserverMock = jest.fn(function MutationObserver(callback) { this.observe = jest.fn(); this.disconnect = jest.fn(); this.trigger = (mockedMutationList) => { callback(mockedMutationList, this); }; }); document.createRange = jest.fn(() => ({ setStart: jest.fn(), setEnd: jest.fn(), commonAncestorContainer: { nodeName: 'BODY', ownerDocument: document, }, startContainer: 'test', getClientRects: jest.fn(() => [{}]), })); global.MutationObserver = mutationObserverMock; function generateEditableDiv(id, innerHtml) { return mount( <div id={id} contentEditable={'true'}> {innerHtml ? innerHtml : ''} </div> ); } beforeAll(() => { editableDiv1 = generateEditableDiv('div-1'); editableDiv2 = generateEditableDiv('div-2', 'test just test'); editableDiv3 = generateEditableDiv('div-3', 'test justify test'); }); describe('#addObserver', () => { it('adds an observer that listens for structural changes to the content editable div', () => { // remount JNS to trigger constructor functions justNotSorry.unmount(); justNotSorry.mount(); const instance = justNotSorry.instance(); const spy = jest.spyOn(instance, 'addObserver'); const node = mount( <div id={'div-focus'} contentEditable={'true'} onFocus={instance.addObserver.bind(instance)} ></div> ); node.simulate('focus'); // There should be the document observer and the observer specifically for the target div const observerInstances = mutationObserverMock.mock.instances; const observerInstance = observerInstances[observerInstances.length - 1]; expect(observerInstances.length).toBe(2); expect(spy).toHaveBeenCalledTimes(1); expect(observerInstance.observe).toHaveBeenCalledWith(node.getDOMNode(), { attributes: false, characterData: false, childList: true, subtree: true, }); node.unmount(); }); it('starts checking for warnings', () => { const instance = justNotSorry.instance(); const spy = jest.spyOn(instance, 'checkForWarnings'); const node = mount( <div id={'div-focus'} contentEditable={'true'} onFocus={instance.addObserver.bind(instance)} ></div> ); node.simulate('focus'); expect(spy).toHaveBeenCalled(); node.unmount(); }); it('adds warnings to the content editable div', () => { const instance = justNotSorry.instance(); const spy = jest.spyOn(instance, 'addWarnings'); const node = mount( <div id={'div-focus'} contentEditable={'true'} onFocus={instance.addObserver.bind(instance)} ></div> ); node.simulate('focus'); expect(spy).toHaveBeenCalledWith(node.getDOMNode().parentNode); node.unmount(); }); }); describe('#removeObserver', () => { it('removes any existing warnings', () => { const instance = justNotSorry.instance(); const spy = jest.spyOn(instance, 'removeObserver'); const node = mount( <div id={'div-focus'} contentEditable={'true'} onFocus={instance.addObserver.bind(instance)} onBlur={instance.removeObserver.bind(instance)} > just not sorry </div> ); node.simulate('focus'); expect(justNotSorry.state('warnings').length).toEqual(2); // remount the node node.mount(); node.simulate('blur'); expect(spy).toHaveBeenCalledTimes(1); expect(justNotSorry.state('warnings').length).toEqual(0); node.unmount(); }); it('no longer checks for warnings on input events', () => { justNotSorry.unmount(); justNotSorry.mount(); const instance = justNotSorry.instance(); const node = mount( <div id={'div-remove'} contentEditable={'true'} onFocus={instance.addObserver.bind(instance)} onBlur={instance.removeObserver.bind(instance)} ></div> ); node.simulate('focus'); node.simulate('blur'); const spy = jest.spyOn(instance, 'checkForWarnings'); node.simulate('input'); expect(spy).not.toHaveBeenCalled(); node.unmount(); }); it('disconnects the observer', () => { const instance = justNotSorry.instance(); const spy = jest.spyOn(instance, 'removeObserver'); const node = mount( <div id={'div-disconnect'} contentEditable={'true'} onFocus={instance.addObserver.bind(instance)} onBlur={instance.removeObserver.bind(instance)} ></div> ); node.simulate('focus'); node.simulate('blur'); // There should be the document observer and the observer specifically for the target div const observerInstances = mutationObserverMock.mock.instances; const observerInstance = observerInstances[observerInstances.length - 1]; expect(spy).toHaveBeenCalled(); expect(observerInstance.disconnect).toHaveBeenCalled(); node.unmount(); }); }); describe('#addWarning', () => { beforeEach(() => { wrapper = mount(<JustNotSorry />); instance = wrapper.instance(); }); it('adds a warning for a single keyword', () => { const node = editableDiv2.getDOMNode(); instance.addWarning(node, 'just', 'warning message'); expect(wrapper.state('warnings').length).toEqual(1); expect(wrapper.state('warnings')[0]).toEqual( expect.objectContaining({ keyword: 'just', message: 'warning message', parentNode: node, }) ); }); it('does not add warnings for partial matches', () => { const node = editableDiv3.getDOMNode(); instance.addWarning(node, 'just', 'warning message'); expect(wrapper.state('warnings').length).toEqual(0); expect(wrapper.state('warnings')).toEqual([]); }); it('matches case insensitive', () => { const node = generateEditableDiv('div-case', 'jUsT kidding').getDOMNode(); instance.addWarning(node, 'just', 'warning message'); expect(wrapper.state('warnings').length).toEqual(1); expect(wrapper.state('warnings')[0]).toEqual( expect.objectContaining({ keyword: 'just', message: 'warning message', parentNode: node, }) ); }); it('catches keywords with punctuation', () => { const node = generateEditableDiv( 'div-punctuation', 'just. test' ).getDOMNode(); instance.addWarning(node, 'just', 'warning message'); expect(wrapper.state('warnings').length).toEqual(1); expect(wrapper.state('warnings')[0]).toEqual( expect.objectContaining({ keyword: 'just', message: 'warning message', parentNode: node, }) ); }); it('matches phrases', () => { const node = generateEditableDiv( 'div-phrase', 'my cat is so sorry because of you' ).getDOMNode(); instance.addWarning(node, 'so sorry', 'warning message'); expect(wrapper.state('warnings').length).toEqual(1); expect(wrapper.state('warnings')[0]).toEqual( expect.objectContaining({ keyword: 'so sorry', message: 'warning message', parentNode: node, }) ); }); it('does not add warnings for tooltip matches', () => { document.createRange = jest.fn(() => ({ setStart: jest.fn(), setEnd: jest.fn(), commonAncestorContainer: { nodeName: 'BODY', ownerDocument: document, }, startContainer: "The word 'very' does not communicate enough information. Find a stronger, more meaningful adverb, or omit it completely. --Andrea Ayres", getClientRects: jest.fn(() => [{}]), })); const node = editableDiv3.getDOMNode(); instance.addWarning(node, 'very', 'warning message'); expect(wrapper.state('warnings').length).toEqual(0); expect(wrapper.state('warnings')).toEqual([]); }); }); describe('#addWarnings', () => { beforeEach(() => { wrapper = mount(<JustNotSorry />); instance = wrapper.instance(); }); it('does nothing when given an empty string', () => { const node = editableDiv1.getDOMNode(); instance.addWarnings(node); expect(wrapper.state('warnings').length).toEqual(0); expect(wrapper.state('warnings')).toEqual([]); }); it('adds warnings to all keywords', () => { const node = generateEditableDiv( 'div-keywords', 'I am just so sorry. Yes, just.' ).getDOMNode(); instance.addWarnings(node); expect(wrapper.state('warnings').length).toEqual(3); }); }); describe('#checkForWarnings', () => { const instance = justNotSorry.instance(); const spy = jest.spyOn(instance, 'checkForWarnings'); const node = mount( <div onInput={instance.checkForWarnings}>just not sorry</div> ); it('updates warnings each time input is triggered', () => { node.simulate('input'); node.simulate('input'); node.simulate('input'); expect(spy).toHaveBeenCalledTimes(3); node.unmount(); }); }); });
import { Category } from '../../../stories/storiesHierarchy'; export const storySettings = { category: Category.COMPONENTS, storyName: 'ColorPicker', dataHook: 'storybook-colorpicker', };
process.env.NODE_ENV = 'test'; var chai = require('chai'); var chaihttp = require('chai-http'); chai.use(chaihttp); var expect = chai.expect; require(__dirname + '/../app.js'); describe('the error handler function', function() { it('should return a status of 500', function(done) { chai.request('localhost:3000') .get('/products/fish') .end(function(err, res) { expect(res).to.have.status(500); expect(JSON.stringify(res.body)).to.eql('{"msg":"ERROR!!"}'); done(); }); }); });
// "node scripts/create-package-app-test.js && node packages/app-test/synchronize.js && node packages/react-boilerplate-app-scripts/scripts/link-react-boilerplates.js && lerna bootstrap", 'use strict'; require('./create-package-app-test.js'); require('../packages/app-test/synchronize.js'); require('../packages/react-boilerplate-app-scripts/scripts/link-react-boilerplates.js'); const fs = require('fs-extra'); const path = require('path'); const execSync = require('child_process').execSync; try { //begin----加上packages/app-test const lernaJson = require('../lerna.json'); const packagesFolderName = 'packages/app-test'; if (lernaJson.packages.indexOf(packagesFolderName) === -1) { //可能中途ctr+c,导致包名没被删除 lernaJson.packages.push(packagesFolderName); } fs.writeFileSync( path.resolve(__dirname, '../lerna.json'), JSON.stringify(lernaJson, null, 2) ); //end----加上packages/app-test execSync('npm run lerna-bootstrap', { stdio: 'inherit' }); //begin----移除packages/app-test,发布的时候不会发布这个的,只是用来测试 if (lernaJson.packages.indexOf(packagesFolderName) !== -1) { lernaJson.packages.splice( lernaJson.packages.indexOf(packagesFolderName), 1 ); } fs.writeFileSync( path.resolve(__dirname, '../lerna.json'), JSON.stringify(lernaJson, null, 2) ); //end----移除packages/app-test,发布的时候不会发布这个的,只是用来测试 } catch (e) { console.log(e); }
'use strict'; var mongoose = require('mongoose'); var bcrypt = require('bcrypt'); var eat = require('eat'); var userSchema = new mongoose.Schema({ name: { type: String, required: true }, email: { type: String, required: true, unique: true, trim: true }, username: { type: String, required: true, unique: true, trim: true }, biography: { type: String }, location: { type: String }, auth: { basic: { username: String, password: String } } }); userSchema.methods.hashPassword = function(password) { var hash = this.auth.basic.password = bcrypt.hashSync(password, 8); return hash; }; userSchema.methods.checkPassword = function(password) { return bcrypt.compareSync(password, this.auth.basic.password); }; userSchema.methods.generateToken = function(callback) { var id = this._id; eat.encode({id: id}, process.env.APP_SECRET, callback); }; module.exports = mongoose.model('User', userSchema);
version https://git-lfs.github.com/spec/v1 oid sha256:bf2580cc3dbb5c69564e5338a736b949ba7f1c7d567f37e58589d9f573c7abbb size 481
version https://git-lfs.github.com/spec/v1 oid sha256:e7cf7648766782e7940410a3abb8126a98b94e57bd61bfc7c1523679e8ce7ed6 size 26807
const UrlPathValidator = require('../../../services/validators/url-path-validator') const referenceIdHelper = require('../../helpers/reference-id-helper') const BenefitOwner = require('../../../services/domain/benefit-owner') const ValidationError = require('../../../services/errors/validation-error') const insertBenefitOwner = require('../../../services/data/insert-benefit-owner') const SessionHandler = require('../../../services/validators/session-handler') module.exports = function (router) { router.get('/apply/:claimType/new-eligibility/benefit-owner', function (req, res) { UrlPathValidator(req.params) const isValidSession = SessionHandler.validateSession(req.session, req.url) if (!isValidSession) { return res.redirect(SessionHandler.getErrorPath(req.session, req.url)) } return res.render('apply/new-eligibility/benefit-owner', { claimType: req.session.claimType, dob: req.session.dobEncoded, relationship: req.session.relationship, benefit: req.session.benefit, referenceId: req.session.referenceId }) }) router.post('/apply/:claimType/new-eligibility/benefit-owner', function (req, res, next) { UrlPathValidator(req.params) const isValidSession = SessionHandler.validateSession(req.session, req.url) if (!isValidSession) { return res.redirect(SessionHandler.getErrorPath(req.session, req.url)) } const benefitOwnerBody = req.body try { const benefitOwner = new BenefitOwner( req.body.FirstName, req.body.LastName, req.body['dob-day'], req.body['dob-month'], req.body['dob-year'], req.body.NationalInsuranceNumber) const referenceAndEligibilityId = referenceIdHelper.extractReferenceId(req.session.referenceId) return insertBenefitOwner(referenceAndEligibilityId.reference, referenceAndEligibilityId.id, benefitOwner) .then(function () { return res.redirect(`/apply/${req.params.claimType}/new-eligibility/about-you`) }) .catch(function (error) { next(error) }) } catch (error) { if (error instanceof ValidationError) { return renderValidationError(req, res, benefitOwnerBody, error.validationErrors, false) } else { throw error } } }) } function renderValidationError (req, res, benefitOwnerBody, validationErrors, isDuplicateClaim) { return res.status(400).render('apply/new-eligibility/benefit-owner', { errors: validationErrors, isDuplicateClaim: isDuplicateClaim, claimType: req.session.claimType, dob: req.session.dobEncoded, relationship: req.session.relationship, benefit: req.session.benefit, referenceId: req.session.referenceId, benefitOwner: benefitOwnerBody }) }
import { moduleForComponent, test } from 'ember-qunit'; import hbs from 'htmlbars-inline-precompile'; moduleForComponent('memo-card', 'Integration | Component | memo card', { integration: true }); test('it renders', function(assert) { assert.expect(2); // Set any properties with this.set('myProperty', 'value'); // Handle any actions with this.on('myAction', function(val) { ... }); this.render(hbs`{{memo-card}}`); assert.equal(this.$().text().trim(), ''); // Template block usage: this.render(hbs` {{#memo-card}} template block text {{/memo-card}} `); assert.equal(this.$().text().trim(), 'template block text'); });
module.exports = function (grunt) { grunt.initConfig({ less: { test: { src: 'test/test.less', dest: 'test/test.css' } } }) grunt.loadNpmTasks('grunt-contrib-less') grunt.registerTask('default', ['less']) }
(function () { 'use strict'; // Setting up route angular .module('app.users') .run(appRun); // appRun.$inject = ['$stateProvider']; /* @ngInject */ function appRun(routerHelper) { routerHelper.configureStates(getStates()); } function getStates() { return [ { state: 'profile', config: { url: '/settings/profile', controller: 'SettingsController', controllerAs: 'vm', templateUrl: 'modules/users/views/settings/edit-profile.client.view.html' } }, { state: 'password', config: { url: '/settings/password', controller: 'SettingsController', controllerAs: 'vm', templateUrl: 'modules/users/views/settings/change-password.client.view.html' } }, { state: 'accounts', config: { url: '/settings/accounts', controller: 'SettingsController', controllerAs: 'vm', templateUrl: 'modules/users/views/settings/social-accounts.client.view.html' } }, { state: 'signup', config: { url: '/signup', controller: 'AuthenticationController', controllerAs: 'vm', templateUrl: 'modules/users/views/authentication/signup.client.view.html' } }, { state: 'signin', config: { url: '/signin', controller: 'AuthenticationController', controllerAs: 'vm', templateUrl: 'modules/users/views/authentication/signin.client.view.html' } }, { state: 'forgot', config: { url: '/password/forgot', controller: 'PasswordController', controllerAs: 'vm', templateUrl: 'modules/users/views/password/forgot-password.client.view.html' } }, { state: 'reset-invalid', config: { url: '/password/reset/invalid', controller: 'PasswordController', controllerAs: 'vm', templateUrl: 'modules/users/views/password/reset-password-invalid.client.view.html' } }, { state: 'reset-success', config: { url: '/password/reset/success', controller: 'PasswordController', controllerAs: 'vm', templateUrl: 'modules/users/views/password/reset-password-success.client.view.html' } }, { state: 'reset', config: { url: '/password/reset/:token', controller: 'PasswordController', controllerAs: 'vm', templateUrl: 'modules/users/views/password/reset-password.client.view.html' } } ]; } })();
'use strict'; const {app} = require('electron'); const appName = app.getName(); module.exports = { label: appName, submenu: [{ label: 'About ' + appName, role: 'about', params: { version: '1.0.0' } }, { type: 'separator' }, { label: 'Preferences', event: 'prefer', params: 'optional params' }, { type: 'separator' }, { label: 'Hide ' + appName, accelerator: 'Command+H', role: 'hide' }, { label: 'Hide Others', accelerator: 'Command+Shift+H', role: 'hideothers' }, { label: 'Show All', role: 'unhide' }, { type: 'separator' }, { label: 'Quit', accelerator: 'Command+Q', click: () => app.quit() }] };
(function($) { "use strict"; /** * Main controller class for jaoselect input * @param {Object} settings for widget * @param {JQuery} model initial <select> element, we hide it and use like a "model" layer */ var JaoSelect = function(settings, model) { // Delete previously created element if exists model.next('.jao_select').remove(); // Create and cache DOM blocks this.model = model.hide(); this.block = $.fn.jaoselect.htmlBuilder.render(settings, model); this.header = this.block.find('.jao_header'); this.list = this.block.find('.jao_options'); this.options = this.block.find('.jao_options input.jao_option'); this.placeholder = this.block.find('.jao_value'); this.settings = settings; this.block.data('jaoselect', this); // Event handlers this.header.click($.proxy(function() {this.toggleList();}, this)); this.options.click($.proxy(function() {this.onOptionClick();}, this)); this.model.change($.proxy(function() {this.onModelChange();}, this)); this.onModelChange(); return this; }; JaoSelect.prototype = { /* ---------------- Controllers ----------------- */ /** * Callback for option click */ onOptionClick: function() { if (!this.settings.multiple && this.settings.dropdown) { this.hideList(); } this.updateModel(); }, /** * Update model input element and init UI changes */ updateModel: function() { this.model.val(this.getValueFromView()); this.model.trigger('change'); }, /** * Change view due to model value */ onModelChange: function() { this.updateList(); this.updateHeader(); }, /** * Get/set value of input * @param value if not undefined, set this value for input element */ value: function(value) { // Get values if (!arguments.length) { return this.getValue(); } else { this.setValue(value); } }, /** * Get jaoselect value * @return {Array} */ getValue: function() { return this.model.val(); }, /** * Set jaoselect value * @param value value to be set */ setValue: function(value) { this.model.val(value); this.model.trigger('change'); }, /** * get list of values of checked options */ getValueFromView: function() { var value = []; this.options.filter(':checked').each(function() { value.push(this.value); }); return value; }, /** * get list of values with attributes */ getValueWithData: function() { var values = []; this.options.filter(':checked').parent().each(function() { values.push($.extend({}, $(this).data())); }); return values; }, /* -------------------------- View ----------------- */ toggleList: function() { this.list.toggle(); }, openList: function() { this.list.show(); }, hideList: function() { this.list.hide(); }, /** * Update list view: set correct checks and classes for checked labels */ updateList: function() { var i, value = this.getValue(); value = $.isArray(value) ? value : [value]; this.options.removeAttr('checked'); for (i=0; i<value.length; i++) { this.options.filter('[value="' + value[i] + '"]').attr('checked', 'checked'); } this.list.find('>label').removeClass('selected'); this.list.find('>label:has(input:checked)').addClass('selected'); }, /** * Update combobox header: get selected items and view them in header depending on their quantity */ updateHeader: function() { var values = this.getValueWithData(), html; switch (values.length) { case 0: html = this.settings.template.placeholder.call(this); break; case 1: html = this.settings.template.singleValue.call(this, values[0]); break; default: html = this.settings.template.multipleValue.call(this, values); } this.placeholder.html(html); } }; /** * Plugin function; get defaults, merge them with real <select> settings and user settings * @param s {Object} custom settings */ $.fn.jaoselect = function (s) { // Initialize each multiselect return this.each(function () { var $this = $(this), settings = $.extend(true, {}, $.fn.jaoselect.defaults, { // Settings specific to dom element width: this.style.width || $this.width() + 'px', height: $this.height(), multiple: !!$this.attr('multiple'), name: $this.attr('name') || $.fn.jaoselect.index++ }, s); // If multiple, model must support multiple selection if (settings.multiple) { $this.attr('multiple', 'multiple'); } new JaoSelect(settings, $this); }); }; $.fn.jaoselect.index = 0; // Index for naming different selectors if DOM name doesn't provided /** * Templates for combobox header * This is set of functions which can be called from JaoSelect object within its scope. * They return some html (depending on currently selected values), which is set to header when * combobox value changes. */ $.fn.jaoselect.template = { /** * @return placeholder html */ placeholder: function() { return '<span class="jao_placeholder">' + this.settings.placeholder + '</span>'; }, /** * @param value {Object} single value * @return html for first value */ singleValue: function(value) { var html = ''; if (value.image) { html += '<img src="' + value.image + '"> '; } html += '<span>' + value.title + '</span>'; return html; }, /** * @param values {Array} * @return html for all values, comma-separated */ multipleValue: function(values) { var i, html = []; for (i=0; i<values.length; i++) { html.push(this.settings.template.singleValue.call(this, values[i])); } return html.join(', '); }, /** * @param values {Array} * @return html for quantity of selected items and overall options */ selectedCount: function(values) { return 'Selected ' + values.length + ' of ' + this.options.size(); } }; /** * Default settings */ $.fn.jaoselect.defaults = { maxDropdownHeight: 400, dropdown: true, placeholder: '&nbsp;', template: { placeholder: $.fn.jaoselect.template.placeholder, singleValue: $.fn.jaoselect.template.singleValue, multipleValue: $.fn.jaoselect.template.selectedCount } }; /** * Helper for rendering html code */ $.fn.jaoselect.htmlBuilder = { /** * Render whole jaoselect widget * @param settings {Object} settings for widget * @param model {JQuery} initial <select> element */ render: function (settings, model) { this.settings = settings; this.model = model; var classNames = [ 'jao_select', this.model.attr('class'), (this.settings.multiple) ? 'multiple':'single', (this.settings.dropdown) ? 'dropdown':'list' ]; this.block = $( '<div class="' + classNames.join(' ') + '">' + '<div class="jao_header">' + '<div class="jao_arrow"></div>' + '<div class="jao_value"></div>' + '</div>' + this.renderOptionsList() + '</div>' ); // Sometimes model selector is in hidden or invisible block, // so we cannot adjust jaoselect in that place and must attach it to body, // then reattach in its place this.block.appendTo('body'); this.adjustStyle(); $('body').detach('.jaoselect'); this.block.insertAfter(this.model); return this.block; }, /** * render html for the selector options */ renderOptionsList: function() { var self = this, html = ''; this.model.find('option').each(function() { html += self.renderOption($(this)); }); return '<div class="jao_options">' + html + '</div>'; }, /** * render html for a single option * @param option {JQuery} */ renderOption: function(option) { var attr = { type: this.settings.multiple? 'checkbox' : 'radio', value: option.val(), name: 'jaoselect_' + this.settings.name, disabled: option.attr('disabled') ? 'disabled' : '', 'class': 'jao_option' }, labelAttr = $.extend({ 'data-title': option.text(), 'data-cls': option.attr('class') || '', 'data-value': option.val(), 'class': option.attr('disabled') ? 'disabled' : '' }, this.dataToAttributes(option)); return '<label ' + this.renderAttributes(labelAttr) + '>' + '<input ' + this.renderAttributes(attr) + ' />' + this.renderLabel(option) + '</label>'; }, /** * Render label for one option * @param option {JQuery} */ renderLabel: function(option) { var className = option.attr('class') ? 'class="' + option.attr('class') + '"' : '', image = option.data('image') ? '<img src="' + option.data('image') + '" /> ' : ''; return image + '<span ' + className + '>' + option.text() + '</span>'; }, /** * Adjust width and height of header and dropdown list due to settings */ adjustStyle: function() { this.block.css({ width: this.settings.width }); if (this.settings.dropdown) { this.adjustDropdownStyle(); } else { this.adjustListStyle(); } }, /** * Adjust dropdown combobox header and options list */ adjustDropdownStyle: function() { var header = this.block.find('div.jao_header'), options = this.block.find('div.jao_options'), optionsHeight = Math.min(options.innerHeight(), this.settings.maxDropdownHeight); // optionsWidth = Math.max(header.innerWidth(), options.width()); options.css({ width: '100%', //this.settings.width, //optionsWidth + 'px', height: optionsHeight + 'px' }); }, /** * Adjust options list for non-dropdown selector */ adjustListStyle: function() { var options = this.block.find('div.jao_options'); options.css('height', this.settings.height + 'px'); }, /** * Get html for given html attributes * @param attr {Object} list of attributes and their values */ renderAttributes: function(attr) { var key, html = []; for (key in attr) { if (attr[key]) { html.push(key + '="' + attr[key] + '"'); } } return html.join(' '); }, /** * Get all data- attributes from source jQuery object * source {JQuery} source element */ dataToAttributes: function(source) { var data = source.data(), result = {}, key; for (key in data) { result['data-' + key] = data[key]; } return result; } }; /** * Document click handler, it is responsible for closing * jaoselect dropdown list when user click somewhere else in the page */ $(document).bind('click.jaoselect', function(e) { $('.jao_select.dropdown').each(function() { // For some reasons initial select element fires "click" event when // clicking on jaoselect, so we exclude it if ($(this).data('jaoselect').model[0] == e.target) return; if (!$.contains(this, e.target)) { $(this).data('jaoselect').hideList(); } }); }); })(jQuery);