code
stringlengths
2
1.05M
var app = require('app'); // Module to control application life. var BrowserWindow = require('browser-window'); // Module to create native browser window. require('./server/server'); // Report crashes to our server. require('crash-reporter').start(); // Keep a global reference of the window object, if you don't, the window will // be closed automatically when the JavaScript object is garbage collected. var mainWindow = null; // Quit when all windows are closed. app.on('window-all-closed', function() { // On OS X it is common for applications and their menu bar // to stay active until the user quits explicitly with Cmd + Q if (process.platform != 'darwin') { app.quit(); } }); // This method will be called when Electron has finished // initialization and is ready to create browser windows. app.on('ready', function() { // Create the browser window. mainWindow = new BrowserWindow({ width: 800, height: 675, resizable: false }); // and load the index.html of the app. mainWindow.loadUrl('http://localhost:8000'); // Open the DevTools. // mainWindow.openDevTools(); // Emitted when the window is closed. mainWindow.on('closed', function() { // Dereference the window object, usually you would store windows // in an array if your app supports multi windows, this is the time // when you should delete the corresponding element. mainWindow = null; }); });
/*jslint node:true plusplus:true white:true */ 'use strict'; /* * this solution is solid, but not nearly as simple and beautiful as the * expected solution, which is: * module.exports = function map(arr, fn) { return arr.reduce(function(acc, item, index, arr) { return acc.concat(fn(item, index, arr)) }, []) } */ module.exports = function (arr, fn) { function reducer (currentResult, currentValue, currentIndex, arr) { currentResult[currentIndex] = fn(currentValue); return currentResult; } return arr.reduce(reducer, []); };
(function() { var ApiBase, debug, querystring, slumber, bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; debug = require('debug')('vatapi:ApiBaseHTTP'); ApiBase = require('./ApiBase').ApiBase; querystring = require('querystring'); slumber = require('slumber'); module.exports.ApiBaseHTTP = (function(superClass) { extend(ApiBaseHTTP, superClass); function ApiBaseHTTP() { this.patch = bind(this.patch, this); this.put = bind(this.put, this); this.post = bind(this.post, this); this["delete"] = bind(this["delete"], this); this.get = bind(this.get, this); this.fn_wrapper = bind(this.fn_wrapper, this); this.prepare_opts = bind(this.prepare_opts, this); this.init = bind(this.init, this); this.handleOptions = bind(this.handleOptions, this); return ApiBaseHTTP.__super__.constructor.apply(this, arguments); } ApiBaseHTTP.prototype.handleOptions = function() { var base, base1, base2; ApiBaseHTTP.__super__.handleOptions.apply(this, arguments); if ((base = this.options).base_url == null) { base.base_url = ''; } if (!this.options.key) { throw "`key` is mandatory"; } if ((base1 = this.options).slumber == null) { base1.slumber = {}; } if ((base2 = this.options.slumber).append_slash == null) { base2.append_slash = false; } if (this.options.auth != null) { this.options.slumber.auth = this.options.auth; } return debug("handleOptions()"); }; ApiBaseHTTP.prototype.init = function() { var api; ApiBaseHTTP.__super__.init.apply(this, arguments); api = slumber.API('https://vatapi.com', this.options.slumber); return this.slumber = api(this.options.base_url); }; ApiBaseHTTP.prototype.prepare_opts = function(opts) { if (opts.__query == null) { opts.__query = {}; } opts.headers = { 'Apikey': this.options.key }; return opts; }; ApiBaseHTTP.prototype.fn_wrapper = function(fn) { return (function(_this) { return function(err, response, ret) { var arity; arity = fn.length; debug('fn_wrapper arity', arity); switch (arity) { case 1: return fn(ret); case 2: return fn(err, ret || JSON.parse(response.body).message); case 3: return fn(err, response, ret); } }; })(this); }; ApiBaseHTTP.prototype.get = function(path, query, fn) { var opts; if (query == null) { query = {}; } if (fn == null) { fn = null; } if ('function' === typeof query) { fn = query; query = {}; } opts = this.prepare_opts(query); return this.slumber(path).get(opts, this.fn_wrapper(fn)); }; ApiBaseHTTP.prototype["delete"] = function(path, fn) { var opts; if (fn == null) { fn = null; } opts = this.prepare_opts({}); return this.slumber(path)["delete"](opts, this.fn_wrapper(fn)); }; ApiBaseHTTP.prototype.post = function(path, data, fn) { var opts; if (data == null) { data = {}; } if (fn == null) { fn = null; } opts = this.prepare_opts(data); return this.slumber(path).post(opts, this.fn_wrapper(fn)); }; ApiBaseHTTP.prototype.put = function(path, data, fn) { var opts; if (data == null) { data = {}; } if (fn == null) { fn = null; } opts = this.prepare_opts(data); return this.slumber(path).put(opts, this.fn_wrapper(fn)); }; ApiBaseHTTP.prototype.patch = function(path, data, fn) { var opts; if (data == null) { data = {}; } if (fn == null) { fn = null; } opts = this.prepare_opts(data); return this.slumber(path).patch(opts, this.fn_wrapper(fn)); }; return ApiBaseHTTP; })(ApiBase); }).call(this);
'use strict'; var _ = require('../../undash'); const buildChoicesMap = (replaceChoices) => { var choices = {}; replaceChoices.forEach(function (choice) { var key = choice.value; choices[key] = choice.label; }); return choices; }; const getTagPositions = (text) => { var lines = text.split('\n'); var re = /\{\{.+?\}\}/g; var positions = []; var m; for(var i = 0; i < lines.length; i++) { while ((m = re.exec(lines[i])) !== null) { var tag = m[0].substring(2, m[0].length - 2); positions.push({ line: i, start: m.index, stop: m.index + m[0].length, tag: tag }); } } return positions; }; const tokenize = (text) => { text = String(text); if (text === '') { return []; } var regexp = /(\{\{|\}\})/; var parts = text.split(regexp); var tokens = []; var inTag = false; parts.forEach(function (part) { if (part === '{{') { inTag = true; } else if (part === '}}') { inTag = false; } else if (inTag) { tokens.push({type: 'tag', value: part}); } else { tokens.push({type: 'string', value: part}); } }); return tokens; }; /* Given a CodeMirror document position like {line: 0, ch: 10}, return the tag position object for that position, for example {line: 0, start: 8, stop: 12} When clicking on a pretty tag, CodeMirror .getCursor() may return either the position of the start or the end of the tag, so we use this function to normalize it. Clicking on a pretty tag is jumpy - the cursor goes from one end to the other each time you click it. We should probably fix that, and the need for this function might go away. */ const getTrueTagPosition = (text, cmPos) => { const positions = getTagPositions(text); return _.find(positions, p => cmPos.line === p.line && cmPos.ch >= p.start && cmPos.ch <= p.stop); }; /* Creates helper to translate between tags like {{firstName}} and an encoded representation suitable for use in CodeMirror. */ const TagTranslator = (replaceChoices, humanize) => { // Map of tag to label 'firstName' --> 'First Name' var choices = buildChoicesMap(replaceChoices); return { /* Get label for tag. For example 'firstName' becomes 'First Name'. Returns a humanized version of the tag if we don't have a label for the tag. */ getLabel: (tag) => { var label = choices[tag]; if (!label) { // If tag not found and we have a humanize function, humanize the tag. // Otherwise just return the tag. label = humanize && humanize(tag) || tag; } return label; }, getTagPositions, tokenize, getTrueTagPosition }; }; module.exports = TagTranslator;
$( document ).ready(function() { $("#kereses").live('click', function () { $( "#main" ).load( "./table.php", function() { $("#adattar").live('click', function () { $("#main").load("./about.html", function() { }); }); $("#sugo").live('click', function () { $("#main").load("./help.html", function() { }); }); $("#kotetek").live('click', function () { $("#main").load("./downloads.html", function() { }); }); $("#publikaciok").live('click', function () { $("#main").load("./publish.html", function() { }); }); console.log("hej"); var table = $('#example').DataTable({ "bProcessing": true, "bServerSide": true, bAutoWidth: false , "oLanguage": { "sSearch": "Keresés: ", "sProcessing": "Adatok lekérdezése...", "oPaginate": { "sFirst": "Első oldal", // This is the link to the first page "sPrevious": "Előző oldal", // This is the link to the previous page "sNext": "Következő oldal", // This is the link to the next page "sLast": "Utolsó oldal" // This is the link to the last page } }, "columnDefs": [ { "sWidth": "6%", "targets": [0] }, { "sWidth": "8%", "targets": [1] }, { "sWidth": "8%", "targets": [2] }, { "sWidth": "10%", "targets": [3] }, { "sWidth": "12%", "targets": [4] }, { "sWidth": "23%", "targets": [5] }, { "sWidth": "8%", "targets": [6] }, { "sWidth": "8%", "targets": [7] }, { "sWidth": "8%", "targets": [8] }, { "sWidth": "8%", "targets": [9] }, { "targets": [10], "visible": false, }, { "targets": [11], "visible": false }, { "targets": [12], "visible": false }, { "targets": [13], "visible": false }, { "targets": [14], "visible": false }, { "targets": [15], "visible": false } ], "bAutoWidth": false, "bLengthChange": false, "bSort": false, "sAjaxSource": "./Nice.php", }); $('#cucc th').each(function () { var title = $(this).text(); console.log(title); if (title=="Adat"){ $(this).html('<div style="width: 100px; margin-left:-20px"><input style="border: 1px solid white;background-color : #7195BC; " size=100px id="' + title + '" type="text" placeholder=" Keresés..." /></div>'); } else { $(this).html('<div><input style="border: 1px solid white;background-color : #7195BC; " id="' + title + '" type="text" placeholder=" Keresés..." /></div>'); } }); table.columns().every(function () { var that = this; //nsole.log( $('input', this.header())); $('input', this.header()).on('keyup change', function () { //console.log(this.header()); if (this.value!=""){ this.style.backgroundColor = "white"; this.style.color="black"; this.style.border="1px solid grey"; } else { this.style.backgroundColor = "#7195BC"; this.style.border="2px solid white"; } if (that.search() !== this.value) { that .search(this.value) .draw(); } }); }); $("#removeInputValues").live('click', function () { var i = 0; $("#example :input").each(function () { $(this).val(""); i++; if (i == 10) { return false; } }); table.columns().search("").draw(); }); $('#export').live('click', function () { var i = 0; var k = 0; var urlParams = "?"; $("#example :input").each(function () { i++; k = i - 1; if (i == 11) { return false; } urlParams = urlParams + "sSearch_" + k + "=" + $(this).val() + "&"; }); urlParams = urlParams + "sSearch_10=&sSearch_11&sSearch_12=&sSearch_13=&sSearch_14=&sSearch_15"; console.log(urlParams); window.open("Export.php" + urlParams + "", "_self"); }); $('#startMap').live('click', function () { destroy(); var i = 0; var k = 0; var urlParams = "?"; $("#example :input").each(function () { i++; k = i - 1; if (i == 11) { return false; } urlParams = urlParams + "sSearch_" + k + "=" + $(this).val() + "&"; }); urlParams = urlParams + "sSearch_10=&sSearch_11&sSearch_12=&sSearch_13=&sSearch_14=&sSearch_15"; $.ajax({ dataType: "json", type: "GET", url: "Map.php" + urlParams, success: function (data) { for (var i = 0; i < data.length; i++) { if (data[i].szelesseg != "") { addMarker(data[i].szelesseg, data[i].hosszusag, data[i].telepulesSZTA, data[i].adat); } } } }); }); });}); $("#fejlec").live('click', function () { $( "#main" ).load( "./table.php", function() { $("#adattar").live('click', function () { $("#main").load("./about.html", function() { }); }); $("#sugo").live('click', function () { $("#main").load("./help.html", function() { }); }); $("#kotetek").live('click', function () { $("#main").load("./downloads.html", function() { }); }); $("#publikaciok").live('click', function () { $("#main").load("./publish.html", function() { }); }); console.log("hej"); var table = $('#example').DataTable({ "bProcessing": true, "bServerSide": true, bAutoWidth: false , "oLanguage": { "sSearch": "Keresés: ", "sProcessing": "Adatok lekérdezése...", "oPaginate": { "sFirst": "Első oldal", // This is the link to the first page "sPrevious": "Előző oldal", // This is the link to the previous page "sNext": "Következő oldal", // This is the link to the next page "sLast": "Utolsó oldal" // This is the link to the last page } }, "columnDefs": [ { "sWidth": "6%", "targets": [0] }, { "sWidth": "8%", "targets": [1] }, { "sWidth": "8%", "targets": [2] }, { "sWidth": "10%", "targets": [3] }, { "sWidth": "12%", "targets": [4] }, { "sWidth": "23%", "targets": [5] }, { "sWidth": "8%", "targets": [6] }, { "sWidth": "8%", "targets": [7] }, { "sWidth": "8%", "targets": [8] }, { "sWidth": "8%", "targets": [9] }, { "targets": [10], "visible": false, }, { "targets": [11], "visible": false }, { "targets": [12], "visible": false }, { "targets": [13], "visible": false }, { "targets": [14], "visible": false }, { "targets": [15], "visible": false } ], "bAutoWidth": false, "bLengthChange": false, "bSort": false, "sAjaxSource": "./Nice.php", }); $('#cucc th').each(function () { var title = $(this).text(); console.log(title); if (title=="Adat"){ $(this).html('<div style="width: 100px; margin-left:-20px"><input style="border: 1px solid white;background-color : #7195BC; " size=100px id="' + title + '" type="text" placeholder=" Keresés..." /></div>'); } else { $(this).html('<div><input style="border: 1px solid white;background-color : #7195BC; " id="' + title + '" type="text" placeholder=" Keresés..." /></div>'); } }); table.columns().every(function () { var that = this; //nsole.log( $('input', this.header())); $('input', this.header()).on('keyup change', function () { //console.log(this.header()); if (this.value!=""){ this.style.backgroundColor = "white"; this.style.color="black"; this.style.border="1px solid grey"; } else { this.style.backgroundColor = "#7195BC"; this.style.border="2px solid white"; } if (that.search() !== this.value) { that .search(this.value) .draw(); } }); }); $("#removeInputValues").live('click', function () { var i = 0; $("#example :input").each(function () { $(this).val(""); i++; if (i == 10) { return false; } }); table.columns().search("").draw(); }); $('#export').live('click', function () { var i = 0; var k = 0; var urlParams = "?"; $("#example :input").each(function () { i++; k = i - 1; if (i == 11) { return false; } urlParams = urlParams + "sSearch_" + k + "=" + $(this).val() + "&"; }); urlParams = urlParams + "sSearch_10=&sSearch_11&sSearch_12=&sSearch_13=&sSearch_14=&sSearch_15"; console.log(urlParams); window.open("Export.php" + urlParams + "", "_self"); }); $('#startMap').live('click', function () { destroy(); var i = 0; var k = 0; var urlParams = "?"; $("#example :input").each(function () { i++; k = i - 1; if (i == 11) { return false; } urlParams = urlParams + "sSearch_" + k + "=" + $(this).val() + "&"; }); urlParams = urlParams + "sSearch_10=&sSearch_11&sSearch_12=&sSearch_13=&sSearch_14=&sSearch_15"; $.ajax({ dataType: "json", type: "GET", url: "Map.php" + urlParams, success: function (data) { for (var i = 0; i < data.length; i++) { if (data[i].szelesseg != "") { addMarker(data[i].szelesseg, data[i].hosszusag, data[i].telepulesSZTA, data[i].adat); } } } }); }); });}); $( "#main" ).load( "./table.php", function() { $("#adattar").live('click', function () { $("#main").load("./about.html", function() { }); }); console.log("hej"); var table = $('#example').DataTable({ "bProcessing": true, "bServerSide": true, bAutoWidth: false , "oLanguage": { "sSearch": "Keresés: ", "sProcessing": "Adatok lekérdezése...", "oPaginate": { "sFirst": "Első oldal", // This is the link to the first page "sPrevious": "Előző oldal", // This is the link to the previous page "sNext": "Következő oldal", // This is the link to the next page "sLast": "Utolsó oldal" // This is the link to the last page } }, "columnDefs": [ { "sWidth": "6%", "targets": [0] }, { "sWidth": "8%", "targets": [1] }, { "sWidth": "8%", "targets": [2] }, { "sWidth": "10%", "targets": [3] }, { "sWidth": "12%", "targets": [4] }, { "sWidth": "23%", "targets": [5] }, { "sWidth": "8%", "targets": [6] }, { "sWidth": "8%", "targets": [7] }, { "sWidth": "8%", "targets": [8] }, { "sWidth": "8%", "targets": [9] }, { "targets": [10], "visible": false, }, { "targets": [11], "visible": false }, { "targets": [12], "visible": false }, { "targets": [13], "visible": false }, { "targets": [14], "visible": false }, { "targets": [15], "visible": false } ], "bAutoWidth": false, "bLengthChange": false, "bSort": false, "sAjaxSource": "./Nice.php", }); $('#cucc th').each(function () { var title = $(this).text(); console.log(title); if (title=="Adat"){ $(this).html('<div style="width: 100px; margin-left:-20px"><input style="border: 1px solid white;background-color : #7195BC; " size=100px id="' + title + '" type="text" placeholder=" Keresés..." /></div>'); } else { $(this).html('<div><input style="border: 1px solid white;background-color : #7195BC; " id="' + title + '" type="text" placeholder=" Keresés..." /></div>'); } }); table.columns().every(function () { var that = this; //nsole.log( $('input', this.header())); $('input', this.header()).on('keyup change', function () { //console.log(this.header()); if (this.value!=""){ this.style.backgroundColor = "white"; this.style.color="black"; this.style.border="1px solid grey"; } else { this.style.backgroundColor = "#7195BC"; this.style.border="2px solid white"; } if (that.search() !== this.value) { that .search(this.value) .draw(); } }); }); $("#removeInputValues").live('click', function () { var i = 0; $("#example :input").each(function () { $(this).val(""); i++; if (i == 10) { return false; } }); table.columns().search("").draw(); }); $('#export').live('click', function () { var i = 0; var k = 0; var urlParams = "?"; $("#example :input").each(function () { i++; k = i - 1; if (i == 11) { return false; } urlParams = urlParams + "sSearch_" + k + "=" + $(this).val() + "&"; }); urlParams = urlParams + "sSearch_10=&sSearch_11&sSearch_12=&sSearch_13=&sSearch_14=&sSearch_15"; console.log(urlParams); window.open("Export.php" + urlParams + "", "_self"); }); $('#startMap').live('click', function () { destroy(); var i = 0; var k = 0; var urlParams = "?"; $("#example :input").each(function () { i++; k = i - 1; if (i == 11) { return false; } urlParams = urlParams + "sSearch_" + k + "=" + $(this).val() + "&"; }); urlParams = urlParams + "sSearch_10=&sSearch_11&sSearch_12=&sSearch_13=&sSearch_14=&sSearch_15"; $.ajax({ dataType: "json", type: "GET", url: "Map.php" + urlParams, success: function (data) { for (var i = 0; i < data.length; i++) { if (data[i].szelesseg != "") { addMarker(data[i].szelesseg, data[i].hosszusag, data[i].telepulesSZTA, data[i].adat); } } } }); }); }); $("#menu").load("./menu.html", function() { }); });
import React, { Component, PropTypes} from 'react' import { Link } from 'react-router-dom'; import { connect} from 'react-redux'; import styles from './styles.scss'; import { Tab, Tabs, TabList, TabPanel } from 'react-tabs'; import SettingsAddAHVCluster from '../../components/SettingsAddAHVCluster/SettingsAddAHVCluster'; import SettingsAddVeeamServerWiz from '../../components/SettingsAddVeeamServerWiz/SettingsAddVeeamServerWiz'; import { GetBackupServers} from './SettingsAction' import { GetDetailServer} from './SettingsAction' import { GetDetailCluster} from './SettingsAction' import { UpdatePassLogin} from './SettingsAction' import { GetClusters} from './SettingsAction' class Settings extends Component { constructor(props) { super(props) this.state = { filteredItems: false, filterval: '', tabIndex: 0, tabts:3, } } componentDidMount() { this.props.GetBackupServers(); this.props.GetClusters(); } componentDidUpdate () { this.ddd = 'sss' $( ".table-content tbody" ).on( "click", "tr", function() { $('.table-content tbody tr').removeClass("selected-green"); $(this).addClass( "selected-green" ); }); } componentWillReceiveProps(nextProps) { if(nextProps.listbackups) { this.setState({listTab1:nextProps.listbackups}) } if(nextProps.cluster_list) { this.setState({listTab2:nextProps.cluster_list}) } } filter(e) { var value = e.target.value; this.setState({filterval: value}) this.setState({ filteredItems: !value ? false : this.state.table.filter(function (item) { return item.name.toLowerCase().indexOf(value.toLowerCase()) !== -1; }) }) } openWizEdit() { this.setState({openWiz:true,edit1:true}) this.props.GetDetailServer(this.state.choosen); } deleteJob() { } firstTab() { var list = this.state.filteredItems || this.state.listTab1 || [] return ( <div> <div className="clear-wrapper gt-clear mar2020 he36"> <div className="gt-left"> {(list.length > 0) ? ( <a className="bk-btn gt-left add-btn fixpad disabled">Add</a>) : ( <a onClick={this.openWiz.bind(this)} className="bk-btn gt-left add-btn fixpad">Add</a>)} {this.state.choosen ? ( <a onClick={this.openWizEdit.bind(this)} className="bk-btn gt-left edit-btn fixpad">Edit</a>) : ( <a className="bk-btn gt-left edit-btn fixpad disabled">Edit</a>)} {this.state.choosen ? ( <a onClick={this.deleteJob.bind(this)} className="bk-btn gt-left red_delete-btn fixpad disabled">Delete</a>) : ( <a className="bk-btn gt-left red_delete-btn fixpad disabled">Delete</a>)} </div> <div className="search-panel gt-right"> <input value={this.state.filterval} onChange={this.filter.bind(this)} className="srch-comp" placeholder="search"/> </div> </div> <div className="border-bottom-100"></div> <div className="table-wrapper"> <div className="table-content"> <table className="bk-table"> <thead> <tr> <th>IP Address</th> <th className="width20th">Backup Repositories</th> <th>Status</th> <th>Version</th> <th className="width20th">Server Description</th> </tr> </thead> <tbody> {list.map((item,index) => ( <tr onClick={()=>{this.setState({choosen:item.Id})}} className="" key={index}> <td>{item.ip}:{item.port}</td> <td>{item.repositoriesCount}</td> <td className="width11">{item.status}</td> <td>{item.version}</td> <td>{item.description}</td> </tr> ))} </tbody> </table> </div> </div> <SettingsAddVeeamServerWiz editable={this.state.edit1} open={this.state.openWiz} close={this.closeWiz.bind(this)}/> </div> ) } closeWiz() { this.setState({openWiz:false}) } openWiz() { this.setState({openWiz:true,edit1:false}) } closeWiz2() { this.setState({openWiz2:false}) } openWiz2() { this.setState({openWiz2:true,edit2:false}) } openWizEdit2() { this.setState({openWiz2:true,edit2:true}) this.props.GetDetailCluster(this.state.choosen2); } deleteJob2() { } secondTab() { var list = this.state.filteredItems || this.state.listTab2 || [] return ( <div> <div className="clear-wrapper gt-clear mar2020 he36"> <div className="gt-left"> {(list.length > 0) ? ( <a className="bk-btn gt-left add-btn fixpad disabled">Add</a>) : ( <a onClick={this.openWiz2.bind(this)} className="bk-btn gt-left add-btn fixpad">Add</a>)} {this.state.choosen2 ? ( <a onClick={this.openWizEdit2.bind(this)} className="bk-btn gt-left edit-btn fixpad">Edit</a>) : ( <a className="bk-btn gt-left edit-btn fixpad disabled">Edit</a>)} {this.state.choosen2 ? ( <a onClick={this.deleteJob2.bind(this)} className="bk-btn gt-left red_delete-btn fixpad disabled">Delete</a>) : ( <a className="bk-btn gt-left red_delete-btn fixpad disabled">Delete</a>)} </div> <div className="search-panel gt-right"> <input value={this.state.filterval} onChange={this.filter.bind(this)} className="srch-comp" placeholder="search"/> </div> </div> <div className="border-bottom-100"></div> <div className="table-wrapper"> <div className="table-content"> <table className="bk-table"> <thead> <tr > <th className="width20th">Cluster Address</th> <th>Status</th> <th>Version</th> <th>description</th> </tr> </thead> <tbody> {list.map((item,index) => ( <tr onClick={()=>{this.setState({choosen2:item.Id})}} key={index}> <td> {item.ip}:{item.port} </td> <td>{item.status}</td> <td>{item.version}</td> <td>{item.description}</td> </tr> ))} </tbody> </table> </div> </div> <SettingsAddAHVCluster editable={this.state.edit2} open={this.state.openWiz2} close={this.closeWiz2.bind(this)}/> </div> ) } forthTab() { return ( <div className="tab4-con"> <div className="gt-clear"> <Tabs > <div className="wrapper-settings"> <TabList className="tablist-inner"> <div className=""> <Tab className="inner-tabs" selectedClassName="inner-tabs__active" >Summary</Tab> <Tab className="inner-tabs" selectedClassName="inner-tabs__active">Network</Tab> <Tab className="inner-tabs" selectedClassName="inner-tabs__active">Security</Tab> <Tab className="inner-tabs" selectedClassName="inner-tabs__active">Notifications</Tab> </div> </TabList> </div> <div className="border-bottom-100"></div> <TabPanel> {this.innerTab1()} </TabPanel> <TabPanel> {this.innerTab2()} </TabPanel> <TabPanel> {this.innerTab3()} </TabPanel> <TabPanel> 4 </TabPanel> </Tabs> </div> </div> ) } checkBoxInnerTab2 () { if( this.state.checkInnerTab2) { this.setState({checkInnerTab2:false}) } if( !this.state.checkInnerTab2) { this.setState({checkInnerTab2:true}) } } changeToggleSwitcher () { if( this.state.toggleCheck) { // this.setState({toggleCheck:false}) } if( !this.state.toggleCheck) { // this.setState({toggleCheck:true}) } } innerTab3() { return ( <div className="wrapper-settings"> <div className="gt-clear h55 toggle-group"> <div className="gt-left enableSSH__label">Enable SSH Access</div> <div className="gt-left"> <div className="toggle-switch"> <label className="switch"> <input type="checkbox" onChange={this.changeToggleSwitcher.bind(this)} value={this.state.toggleCheck} readOnly checked={false}/> <span className="slider round"></span> </label> </div> </div> <div className="gt-left off__label">{this.state.toggleCheck ? ("ON"):("OFF")}</div> </div> <div className="account-status">Administrator account</div> <div className="gt-clear row-label-input"> <div className="gt-left width165px"> Login </div> <div className="gt-left"> <input value="admin" readOnly/> </div> </div> <div className="gt-clear row-label-input"> <div className="gt-left width165px"> Password </div> <div className="gt-left"> <input value={this.state.password} onChange={(e)=> {this.setState({password:e.target.value})}} type="password"/> </div> </div> <div className="gt-clear row-label-input marbtm20"> <div className="gt-left width165px"> Confirm Password </div> <div className="gt-left"> <input value={this.state.NewPassword} onChange={(e)=> {this.setState({NewPassword:e.target.value})}} type="password" /> </div> </div> <a onClick={this.SavePassword.bind(this)} className="apply-btn btn-left-mar">Apply</a> </div> ) } SavePassword() { const Obj = { // login:'admin', "@odata.type": "ChangePasswordData", OldPassword:this.state.password, NewPassword:this.state.NewPassword, } this.props.UpdatePassLogin(Obj); } innerTab2(){ return ( <div className="wrapper-settings innerTab2wrapper"> <div className="innerTab2-checkbox"> <label><input type="checkbox" onChange={this.checkBoxInnerTab2.bind(this)} checked={this.state.checkInnerTab2} name="dva"/> Obtain an IP address automatically</label> </div> <div className="gt-clear row-label-input"> <div className="gt-left width165px"> IP Address </div> <div className="gt-left"> <input/> </div> </div> <div className="gt-clear row-label-input"> <div className="gt-left width165px"> Subnet mask </div> <div className="gt-left"> <input/> </div> </div> <div className="gt-clear row-label-input"> <div className="gt-left width165px"> Default gateway </div> <div className="gt-left"> <input/> </div> </div> <div className="gt-clear row-label-input marbtm20"> <div className="gt-left width165px"> Preffered DNS server </div> <div className="gt-left"> <input/> </div> </div> <a className="apply-btn btn-left-mar">Apply</a> </div> ) } innerTab1() { return ( <div className="wrapper-settings "> <div className="gt-clear he38"> <div className="btns-group gt-right"> <a className="bk-btn gt-left config_backup-btn fixpad removewidth">Config Backup</a> <a className="bk-btn gt-left reboot-btn fixpad removewidth">Reboot</a> <a className="bk-btn gt-left shutdown-btn fixpad removewidth">Shutdown</a> <a className="bk-btn gt-left bundle-btn fixpad removewidth mrrcl">Support bundle</a> </div> </div> <dl className="floated"> <dt >Appliance Hostname</dt> <dd className="border0">vba.contoso.com</dd> <dt>Product</dt> <dd>Veeam Backup</dd> <dt>Appliance version</dt> <dd>35</dd> </dl> </div> ) } tabChanged(index) { console.log(index) this.setState({tabSelected:index,choosen:false,choosen2:false}) } render(){ console.log(this.props.tabt) return ( <div className="setttings"> <div className="filters"> <div className="filter-wrapper gt-clear"> <div className="gt-left"> <div className="breadcrumbs"> <Link to='/'>Home</Link> / Infrastructure Settings </div> <div className="vm-counter gt-left">Infrastructure Settings</div> </div> </div> <div className=""> <Tabs defaultIndex={this.props.tabt} onSelect={this.tabChanged.bind(this)}> {/* <Tabs defaultIndex={this.state.tabts}> */} <div className="tab-s-wrap"> <TabList> <div className="tabs-settings"> <Tab>Manage Veeam B&R Servers </Tab><div className="separator"></div> <Tab>Manage Nutanix Clusters</Tab> <div className="separator"></div> {/* <Tab>Credentials</Tab> <div className="separator"></div> */} <Tab>Appliance Settings</Tab> </div> </TabList> </div> <TabPanel> {this.firstTab()} </TabPanel> <TabPanel> {this.secondTab()} </TabPanel> {/* <TabPanel></TabPanel> */} <TabPanel> {this.forthTab()} </TabPanel> </Tabs> </div> </div> </div> ) } } const mapDispatchToProps = function(dispatch) { return { GetBackupServers: () => dispatch(GetBackupServers()), GetDetailServer: (id) => dispatch(GetDetailServer(id)), GetClusters: () => dispatch(GetClusters()), GetDetailCluster: (id) => dispatch(GetDetailCluster(id)), UpdatePassLogin: (obj) => dispatch(UpdatePassLogin(obj)), // cleartask_info: () => dispatch(cleartask_info()), } } function mapStateToProps(state) { console.log(state.toJS().BackupReducer.backups); return { tabt:state.toJS().NavBarReducer.InTab, listbackups:state.toJS().SettingsReducer.listbackups, cluster_list:state.toJS().SettingsReducer.cluster_list, } } export default connect(mapStateToProps, mapDispatchToProps)(Settings);
(function ($) { var _accountService = abp.services.app.account; var _$form = $('form[name=TenantChangeForm]'); function switchToSelectedTenant () { var tenancyName = _$form.find('input[name=TenancyName]').val(); if (!tenancyName) { abp.multiTenancy.setTenantIdCookie(null); location.reload(); return; } _accountService.isTenantAvailable({ tenancyName: tenancyName }).done(function (result) { switch (result.state) { case 1: //Available abp.multiTenancy.setTenantIdCookie(result.tenantId); //_modalManager.close(); location.reload(); return; case 2: //InActive abp.message.warn(abp.utils.formatString(abp.localization .localize("TenantIsNotActive", "Repairis"), this.tenancyName)); break; case 3: //NotFound abp.message.warn(abp.utils.formatString(abp.localization .localize("ThereIsNoTenantDefinedWithName{0}", "Repairis"), this.tenancyName)); break; } }); } //Handle save button click _$form.closest('div.modal-content').find(".save-button").click(function(e) { e.preventDefault(); switchToSelectedTenant(); }); //Handle enter key _$form.find('input').on('keypress', function (e) { if (e.which === 13) { e.preventDefault(); switchToSelectedTenant(); } }); })(jQuery);
/** * ###### * ###### * ############ ####( ###### #####. ###### ############ ############ * ############# #####( ###### #####. ###### ############# ############# * ###### #####( ###### #####. ###### ##### ###### ##### ###### * ###### ###### #####( ###### #####. ###### ##### ##### ##### ###### * ###### ###### #####( ###### #####. ###### ##### ##### ###### * ############# ############# ############# ############# ##### ###### * ############ ############ ############# ############ ##### ###### * ###### * ############# * ############ * * Adyen Payment module (https://www.adyen.com/) * * Copyright (c) 2015 Adyen BV (https://www.adyen.com/) * See LICENSE.txt for license details. * * Author: Adyen <magento@adyen.com> */ define( [ 'underscore', 'jquery', 'Magento_Checkout/js/model/quote', 'Magento_Payment/js/view/payment/cc-form' ], function (_, $, quote, Component) { 'use strict'; var billingAddress = quote.billingAddress(); var firstname = ''; var lastname = ''; if (!!billingAddress) { firstname = billingAddress.firstname; lastname = billingAddress.lastname; } return Component.extend({ self: this, defaults: { template: 'Adyen_Payment/payment/boleto-form', firstname: self.firstname, lastname: self.lastname }, initObservable: function () { this._super() .observe([ 'socialSecurityNumber', 'boletoType', 'firstname', 'lastname' ]); return this; }, setPlaceOrderHandler: function (handler) { this.placeOrderHandler = handler; }, setValidateHandler: function (handler) { this.validateHandler = handler; }, getCode: function () { return 'adyen_boleto'; }, getData: function () { return { 'method': this.item.method, 'additional_data': { 'social_security_number': this.socialSecurityNumber(), 'boleto_type': this.boletoType(), 'firstname': this.firstname(), 'lastname': this.lastname() } }; }, isActive: function () { return true; }, getControllerName: function () { return window.checkoutConfig.payment.iframe.controllerName[this.getCode()]; }, getPlaceOrderUrl: function () { return window.checkoutConfig.payment.iframe.placeOrderUrl[this.getCode()]; }, context: function () { return this; }, validate: function () { var form = 'form[data-role=adyen-boleto-form]'; var validate = $(form).validation() && $(form).validation('isValid'); if (!validate) { return false; } return true; }, showLogo: function () { return window.checkoutConfig.payment.adyen.showLogo; }, getBoletoTypes: function () { return _.map(window.checkoutConfig.payment.adyenBoleto.boletoTypes, function (value, key) { return { 'key': value.value, 'value': value.label } }); } }); } );
// Mongoose User Schema var mongoose = require('mongoose'), Schema = mongoose.Schema, moment = require('moment'); moment().format(); var ListingSchema = new mongoose.Schema({ owner: { type: String, required: true } , ownerName: { type: String, required: true } , type: { type: String, required: true } , typeInfo: Array , title: { type: String, required: true } , description: { type: String, required: true } , location: { type: String, required: true } , preciseMarker: Boolean , city: { type: String} , state: { type: String} , zip: { type: String} , latLng: { lat: { type: Number, required: true, select: false } , lng: { type: Number, required: true, select: false } } , displayLatLng: { lat: { type: Number } , lng: { type: Number } } , publicListing: Boolean , imgData: Array , created: { type: Date } , updated: { type: Date } , expires: { type: Date } , active: { type: Boolean, required: true } }); ListingSchema.pre('save', function(next) { this.displayLatLng = {} console.log(this.preciseMarker); if (this.preciseMarker != true) { this.preciseMarker = false // Calculate Display LatLng var r = 274/111300 , y0 = this.latLng.lat , x0 = this.latLng.lng , u = Math.random() , v = Math.random() , w = r * Math.sqrt(u) , t = 2 * Math.PI * v , x = w * Math.cos(t) , y1 = w * Math.sin(t) , x1 = x / Math.cos(y0) this.displayLatLng.lat = y0 + y1 this.displayLatLng.lng = x0 + x1 } else { console.log(this.latLng) this.displayLatLng = this.latLng } now = new Date() expire = moment().add(1, 'years') console.log('now: '+now) console.log('expires: '+expire) this.updated = now this.expires = expire if ( !this.created ) { this.created = now } this.title = this.title.replace(/(<([^>]+)>)/ig,"") this.description = this.description.replace(/(<([^>]+)>)/ig,"") next() }); module.exports = mongoose.model('Listing', ListingSchema);
// All code points in the `Gujarati` script as per Unicode v8.0.0: [ 0xA81, 0xA82, 0xA83, 0xA85, 0xA86, 0xA87, 0xA88, 0xA89, 0xA8A, 0xA8B, 0xA8C, 0xA8D, 0xA8F, 0xA90, 0xA91, 0xA93, 0xA94, 0xA95, 0xA96, 0xA97, 0xA98, 0xA99, 0xA9A, 0xA9B, 0xA9C, 0xA9D, 0xA9E, 0xA9F, 0xAA0, 0xAA1, 0xAA2, 0xAA3, 0xAA4, 0xAA5, 0xAA6, 0xAA7, 0xAA8, 0xAAA, 0xAAB, 0xAAC, 0xAAD, 0xAAE, 0xAAF, 0xAB0, 0xAB2, 0xAB3, 0xAB5, 0xAB6, 0xAB7, 0xAB8, 0xAB9, 0xABC, 0xABD, 0xABE, 0xABF, 0xAC0, 0xAC1, 0xAC2, 0xAC3, 0xAC4, 0xAC5, 0xAC7, 0xAC8, 0xAC9, 0xACB, 0xACC, 0xACD, 0xAD0, 0xAE0, 0xAE1, 0xAE2, 0xAE3, 0xAE6, 0xAE7, 0xAE8, 0xAE9, 0xAEA, 0xAEB, 0xAEC, 0xAED, 0xAEE, 0xAEF, 0xAF0, 0xAF1, 0xAF9 ];
var config = module.exports; config["My tests"] = { environment: "node", // or "browser" rootPath: "../", sources: [ ], tests: [ "test/*Test.js" ] };
define([ 'src/Type' ], function(Type) { const $type = Symbol.for('cell-type'); const $attrs = Symbol.for('cell-type.attrs'); const $statics = Symbol.for('cell-type.statics'); const $inner = Symbol.for('cell-type.inner'); // reference to the wrapped inner function describe("Type", function() { describe("Basic usage", function() { it("should demonstrate the basic functions of cell-multiset", function() { const Beginner = Type({properties: { init(skill) { this._x = 0; this.skills = ['html']; if(skill) {this.skills.push(skill)} return this }, stringify() { return 'beginner' }, get x() { return this._x - 1 }, set x(val) { return this._x = val + 2 }, staticMethod() { "<$attrs static>"; // attributes can be used to supply additional functionality { return 'iamstatic' }} }}); const Specialist = Type({links: Beginner, properties: { init(skill) { this._upper(skill); this.skills.push('css'); return this } }}); // using the new keyword is also possible const Expert = new Type({name: 'Expert', links: Specialist, properties: { // an additional name can be supplied for debugging purposes init(skill) { this._x = 7; this._upper(skill); this.skills.push('js'); return this }, stringify() { return 'expert' }, get x() { return this._upper() - 3 }, set x(val) { this._x = this._upper(val) + 4 }, staticMethod() { "<$attrs static enumerable !configurable>"; // attributes can be used to supply additional functionality { return this._upper() }}, staticProp: {[$attrs]: 'static', value: 10} }}); const e1 = Object.create(Expert).init('xhtml'); // default inheritance features expect(e1.skills).to.eql(["html", "xhtml", "css", "js"]); expect(Beginner.isPrototypeOf(e1)).to.be.true; expect(Specialist.isPrototypeOf(e1)).to.be.true; expect(Expert.isPrototypeOf(e1)).to.be.true; // inheritance for getters/setters e1.x = 4; expect(e1._x).to.deep.equal(10); expect(e1.x).to.deep.equal(6); // inheritance of static methods expect(Expert.staticMethod()).to.eql('iamstatic'); // wrapping of static properties e2 = Object.create(Expert); e1.staticProp = 20; expect(e1.staticProp).to.eql(20); expect(e2.staticProp).to.eql(20); // using attributes to supply additional functionality expect(Object.getOwnPropertyDescriptor(Expert, 'init').enumerable).to.be.false; // by default enumerable is set to false expect(Object.getOwnPropertyDescriptor(Expert, 'init').configurable).to.be.true; // by default configurable is set to true expect(Object.getOwnPropertyDescriptor(Expert, 'staticMethod').enumerable).to.be.true; // using attributes this can be changed expect(Object.getOwnPropertyDescriptor(Expert, 'staticMethod').configurable).to.be.false; // using attributes this can be changed // validations expect(console.warn.calledWith("[Expert]: No overriding attribute and not calling upper in overriding (value) property 'stringify'.")).to.be.true; }); }); describe("inheritance principles", function() { it("should be able to use simple inheritance i.e. super/upper and proper context", function() { const B = Type({name: 'Beginner', properties: { init(skill) { this.skills = ['html']; if(skill) {this.skills.push(skill)} return this } }}); const S = Type({name: 'Specialist', links: B, properties: { init(skill) { this._upper(skill); this.skills.push('css'); return this } }}); // using the new keyword is also possible const E = new Type({name: 'Expert', links: S, properties: { init(skill) { this._x = 7; this._upper(skill); this.skills.push('js'); return this } }}); const e = Object.create(E).init('xhtml'); expect(e.skills).to.eql(["html", "xhtml", "css", "js"]); expect(B.isPrototypeOf(e)).to.be.true; expect(S.isPrototypeOf(e)).to.be.true; expect(E.isPrototypeOf(e)).to.be.true; }); it("should be able be able to inherit from getter and setter functions", function() { const B = Type({name: 'Beginner', properties: { init() { this._x = 0; return this }, get x() { return this._x - 1 }, set x(val) { return this._x = val + 2 } }}); // make sure it is able to find properties higher up the prototype chain const S = Type({name: 'Specialist', links: B, properties: { }}); const E = Type({name: 'Expert', links: S, properties: { init() { return this._upper(); }, get x() { return this._upper() - 3 }, set x(val) { this._x = this._upper(val) + 4 } }}); const e = Object.create(E).init(); e.x = 4; expect(e._x).to.deep.equal(10); expect(e.x).to.deep.equal(6); }); it("should be able be able to inherit from static methods", function() { const B = Type({name: 'Beginner', properties: { staticMethod() { "<$attrs static>"; return 'iamstatic' } }}); // make sure it is able to find properties higher up the prototype chain const S = Type({name: 'Specialist', links: B, properties: { }}); const E = Type({name: 'Expert', links: S, properties: { staticMethod() { "<$attrs static>"; return this._upper() } }}); expect(E.staticMethod()).to.eql('iamstatic'); expect(E[$statics].staticMethod).to.eql(E.staticMethod[$inner]); }); }); describe("Attributes", function() { it("should log a warning in case of an unknown attribute.", function() { const B = Type({name: 'Beginner', properties: { init() { "<$attrs unknown1 !unknown2 unknown3=huh>"; { return this }}, prop: {[$attrs]: 'unknown4', value: 100} }}); expect(console.warn.calledWith("'unknown1' is an unknown attribute and will not be processed.")).to.be.true; expect(console.warn.calledWith("'unknown2' is an unknown attribute and will not be processed.")).to.be.true; expect(console.warn.calledWith("'unknown3' is an unknown attribute and will not be processed.")).to.be.true; expect(console.warn.calledWith("'unknown4' is an unknown attribute and will not be processed.")).to.be.true; }); describe("default descriptor properties", function() { it("should set the default descriptor settings: enumerable=false configurable=true writable=true", function() { const B = Type({name: 'Beginner', properties: { prop: 100 }}); const dsc = Object.getOwnPropertyDescriptor(B, 'prop'); expect(dsc.enumerable).to.be.false; expect(dsc.configurable).to.be.true; expect(dsc.writable).to.be.true; }); it("should set the correct values if set as attributes", function() { const B = Type({name: 'Beginner', properties: { prop: {[$attrs]: "enumerable !configurable !writable", value: 100} }}); const dsc = Object.getOwnPropertyDescriptor(B, 'prop'); expect(dsc.enumerable).to.be.true; expect(dsc.configurable).to.be.false; expect(dsc.writable).to.be.false; }); it("should set correct values for attached & solid", function() { const B = Type({name: 'Beginner', properties: { solidProp: {[$attrs]: "solid", value: 100}, attachedProp: {[$attrs]: "attached", value: 200} }}); const dsc1 = Object.getOwnPropertyDescriptor(B, 'solidProp'); const dsc2 = Object.getOwnPropertyDescriptor(B, 'attachedProp'); expect(dsc1.configurable).to.be.false; expect(dsc1.writable).to.be.false; expect(dsc2.configurable).to.be.false; expect(dsc2.writable).to.be.true; }); }); describe("static", function() { it("should add static properties to the prototype", function() { const B = Type({name: 'Beginner', properties: { method() {"<$attrs static>"; return 10 }, prop: {[$attrs]: 'static', value: 10} }}); expect(B.method()).to.eql(10); expect(B.prop).to.eql(10); }); it("should wrap static properties using getter/setters so we can change the value on the prototype from this", function() { const B = Type({name: 'Beginner', properties: { method() {"<$attrs static>"; return 10 }, prop: {[$attrs]: 'static', value: 10} }}); e1 = Object.create(B); b2 = Object.create(B); e1.prop = 20; expect(e1.prop).to.eql(20); expect(b2.prop).to.eql(20); }); it("should wrap static set method to a warning message in case it contains !writable, readonly or const", function() { const B = Type({name: 'Beginner', properties: { prop1: {[$attrs]: 'static !writable', value: 10}, prop2: {[$attrs]: 'static readonly', value: 10}, prop3: {[$attrs]: 'static const', value: 10} }}); let b = Object.create(B); b.prop1 = 1; b.prop2 = 2; b.prop3 = 3; expect(console.warn.calledWith("Trying to set value '1' on readonly (static) property 'prop1'.")).to.be.true; expect(console.warn.calledWith("Trying to set value '2' on readonly (static) property 'prop2'.")).to.be.true; expect(console.warn.calledWith("Trying to set value '3' on readonly (static) property 'prop3'.")).to.be.true; }); }); it("should define aliases if the alias attribute is provided", function() { const B = Type({name: 'Beginner', properties: { init() {"<$attrs alias=ctor|construct>"; return 'alias' }, }}); let b = Object.create(B); expect(b.init()).to.eql('alias'); expect(b.ctor()).to.eql('alias'); expect(b.construct()).to.eql('alias'); }); it("should set frozen, sealed, extensible from attributes on the designated obj", function() { const B = Type({name: 'Beginner', properties: { frozen: {[$attrs]: "frozen", value: {}}, sealed: {[$attrs]: "sealed", value: {}}, ['!extensible']: {[$attrs]: "!extensible", value: {}}, }}); expect(Object.isFrozen(B.frozen)).to.be.true; expect(Object.isSealed(B.sealed)).to.be.true; expect(Object.isExtensible(B['!extensible'])).to.be.false; }); }); describe("Prototype/function swapping", function() { it("should be possible to swap prototypes with breaking super/upper functionality", function() { const BA = Type({name: 'BeginnerA', properties: { init(skill) { this.skills = ['html']; if(skill) {this.skills.push(skill)} return this } }}); const BB = Type({name: 'BeginnerB', properties: { init(skill) { this.skills = ['sneering']; if(skill) {this.skills.push(skill)} return this } }}); const S = Type({name: 'Specialist', links: BA, properties: { init(skill) { this._upper(skill); this.skills.push('css'); return this } }}); const E = Type({name: 'Expert', links: S, properties: { init(skill) { this._x = 7; this._upper(skill); this.skills.push('js'); return this } }}); // swap B for BB Object.setPrototypeOf(S, BB); const e = Object.create(E).init('xhtml'); expect(e.skills).to.eql(["sneering", "xhtml", "css", "js"]); // TODO testcase for traits that should break methods using upper unless some kind of adopt method is implemented }); it("should be possible to swap functions with breaking super/upper functionality", function() { const B = Type({name: 'BeginnerA', properties: { init(skill) { this.skills = ['html']; if(skill) {this.skills.push(skill)} return this } }}); const S = Type({name: 'Specialist', links: B, properties: { init(skill) { this._upper(skill); this.skills.push('css'); return this } }}); const E = Type({name: 'Expert', links: S, properties: { init(skill) { this._x = 7; this._upper(skill); this.skills.push('js'); return this } }}); // swap B init B.init = function(skill) { this.skills = ['sneering']; if(skill) {this.skills.push(skill)} return this }; const e = Object.create(E).init('xhtml'); expect(e.skills).to.eql(["sneering", "xhtml", "css", "js"]); // TODO testcase for traits that should break methods using upper unless some kind of adopt method is implemented }); }); describe("links/inherits", function() { it("should be able to use the alias inherits instead of links", function() { const B = Type({name: 'Beginner', properties: { staticMethod() { "<$attrs static>"; return 'iamstatic' } }}); // make sure it is able to find properties higher up the prototype chain const S = Type({name: 'Specialist', inherits: B, properties: { }}); expect(S.staticMethod()).to.eql('iamstatic'); }); it("should be possible to swap prototypes using the links method", function() { const BA = Type({name: 'BeginnerA', properties: { init(skill) { this.skills = ['html']; if(skill) {this.skills.push(skill)} return this } }}); const BB = Type({name: 'BeginnerB', properties: { init(skill) { this.skills = ['sneering']; if(skill) {this.skills.push(skill)} return this } }}); const S = Type({name: 'Specialist', links: BA, properties: { init(skill) { this._upper(skill); this.skills.push('css'); return this } }}); const E = Type({name: 'Expert', links: S, properties: { init(skill) { this._x = 7; this._upper(skill); this.skills.push('js'); return this } }}); S[$type].links(BB); const e = Object.create(E).init('xhtml'); expect(e.skills).to.eql(["sneering", "xhtml", "css", "js"]); }); it("should return the linked prototype in case no arguments are given to links/inherits", function() { const B = Type({name: 'Beginner', properties: { staticMethod() { "<$attrs static>"; return 'iamstatic' } }}); // make sure it is able to find properties higher up the prototype chain const S = Type({name: 'Specialist', inherits: B, properties: { }}); expect(S[$type].links()).to.eql(B); expect(S[$type].inherits()).to.eql(B); }); }); describe("Validations", function() { it("should throw an error in case of illegal private usage", function() { function BType() { const B = Type({name: 'Beginner', properties: { init () { return illegal._private } }}); } expect(BType).to.throw("[Beginner]: Illegal use of private property 'illegal._private' in (value) method 'init'."); }); it("should give a warning in case of overrides without an override attribute or without using upper", function() { const B = Type({name: 'Beginner', properties: { validOverwriteMethod() { return 'something' }, validOverwriteMethod2() { return 'something' }, validOverwriteProp: 42, warnOnThisOverrideMethod() { }, warnOnThisOverrideProperty: 42 }}); const S = Type({name: 'Specialist', links: B, properties: { validOverwriteMethod() { return this._upper() }, validOverwriteMethod2() { "<$attrs override>"; return 'random stuff' }, validOverwriteProp: {[$attrs]: "override", value: 43}, warnOnThisOverrideMethod() {}, warnOnThisOverrideProperty: 43 }}); expect(console.warn.calledWith("[Specialist]: No overriding attribute and not calling upper in overriding (value) property 'warnOnThisOverrideMethod'.")).to.be.true; expect(console.warn.calledWith("[Specialist]: No overriding attribute in overriding (value) property 'warnOnThisOverrideProperty'.")).to.be.true; }); it("should throw an error in case of illegal use of non-static methods", function() { function BType() { const B = Type({name: 'Beginner', properties: { nonStatic1 () { return this }, nonStatic2 () { return this }, illegalNonStaticMethodCall() { "<$attrs static>"; this.staticMethod(); // is fine return this.nonStatic1() + this.nonStatic2(); // should throw an error }, staticMethod() { "<$attrs static>"; return 'stuff' } }}); } expect(BType).to.throw("[Beginner]: Illegal usage of non-static methods 'this.nonStatic1,this.nonStatic2' in static method 'illegalNonStaticMethodCall'."); }); it("should output Type instead of the name in case none is given", function() { function BType() { const B = Type({properties: { nonStatic1 () { return this }, nonStatic2 () { return this }, illegalNonStaticMethodCall() { "<$attrs static>"; this.staticMethod(); // is fine return this.nonStatic1() + this.nonStatic2(); // should throw an error }, staticMethod() { "<$attrs static>"; return 'stuff' } }}); } expect(BType).to.throw("[Type]: Illegal usage of non-static methods 'this.nonStatic1,this.nonStatic2' in static method 'illegalNonStaticMethodCall'."); }); }); describe("Statics", function() { it("should implement static properties is using the statics property without using a static attribute", function() { const B = Type({name: 'Beginner', statics: { staticMethod() { return 'staticMethod' }, staticProperty: 42 }}); expect(B[$statics].staticProperty).to.eql(42); expect(B[$statics].staticMethod).to.eql(B.staticMethod); }); it("should be able to add static methods later on using the statics method", function() { const B = Type({name: 'Beginner'}); B[$type].statics({ staticMethod() { return 'staticMethod' }, staticProperty: 42 }); expect(B[$statics].staticProperty).to.eql(42); expect(B[$statics].staticMethod).to.eql(B.staticMethod); }); it("should pass the statics properties in case the statics method is given no arguments", function() { const B = Type({name: 'Beginner'}); let statics = B[$type].statics(); expect(B[$statics]).to.eql(statics); }); }); describe("simple symbol test", function() { var $init = Symbol('init'); var $prop = Symbol('prop'); var $$prop = Symbol('$prop'); it("should be able use symbols as keys and use attributes such as static", function() { const B = Type({name: 'Beginner', properties: { [$init](skill) { this.skills = ['html']; if(skill) {this.skills.push(skill)} return this }, [$prop]: 42, [$$prop]: {[$attrs]: 'static', value: 43} }}); const b = Object.create(B)[$init]('xhtml'); expect(b.skills).to.eql(["html", "xhtml"]); expect(b[$prop]).to.eql(42); expect(b[$$prop]).to.eql(43); b[$$prop] = 44; expect(b[$$prop]).to.eql(44); expect(b[$statics][$$prop]).to.eql(44); }); }); describe("inheritance principles with symbols", function() { var $init = Symbol('init'); it("should be able to use simple inheritance i.e. super/upper and proper context", function() { const B = Type({name: 'Beginner', properties: { [$init](skill) { this.skills = ['html']; if(skill) {this.skills.push(skill)} return this } }}); const S = Type({name: 'Specialist', links: B, properties: { [$init](skill) { this._upper(skill); this.skills.push('css'); return this } }}); const E = Type({name: 'Expert', links: S, properties: { [$init](skill) { this._x = 7; this._upper(skill); this.skills.push('js'); return this } }}); const e = Object.create(E)[$init]('xhtml'); expect(e.skills).to.eql(["html", "xhtml", "css", "js"]); expect(B.isPrototypeOf(e)).to.be.true; expect(S.isPrototypeOf(e)).to.be.true; expect(E.isPrototypeOf(e)).to.be.true; }); }); }); });
$('.form').find('input, textarea').on('keyup blur focus', function (e) { var $this = $(this), label = $this.prev('label'); if (e.type === 'keyup') { if($this.is('#question')) { if ($this.val() === '') { label.removeClass('bigActive highlight'); } else { label.addClass('bigActive highlight'); } } else { if ($this.val() === '') { label.removeClass('active highlight'); } else { label.addClass('active highlight'); } } } else if (e.type === 'blur') { if( $this.val() === '' ) { label.removeClass('active highlight'); } else { label.removeClass('highlight'); } } else if (e.type === 'focus') { if( $this.val() === '' ) { label.removeClass('highlight'); } else if( $this.val() !== '' ) { label.addClass('highlight'); } } }); $('select.login-dropdown').change(function(){ $(this).addClass('highlight'); }); $('.tab a').on('click', function (e) { e.preventDefault(); $(this).parent().addClass('active'); $(this).parent().siblings().removeClass('active'); target = $(this).attr('href'); $('.tab-content > div').not(target).hide(); $(target).fadeIn(600); });
(function(Radiometal, $) { Radiometal.controller('EmissionsController', ['$scope', function($scope){ $scope.selected = 1; $scope.select = function(id) { $scope.selected = id; }; } ]); })(Radiometal,jQuery); var Radiometal = angular.module('Radiometal', []);
/** * A mechanism for displaying data using custom layout templates and formatting. * * The View uses an {@link Ext.XTemplate} as its internal templating mechanism, and is bound to an * {@link Ext.data.Store} so that as the data in the store changes the view is automatically updated * to reflect the changes. The view also provides built-in behavior for many common events that can * occur for its contained items including click, doubleclick, mouseover, mouseout, etc. as well as a * built-in selection model. **In order to use these features, an {@link #itemSelector} config must * be provided for the View to determine what nodes it will be working with.** * * The example below binds a View to a {@link Ext.data.Store} and renders it into an {@link Ext.panel.Panel}. * * @example * Ext.define('Image', { * extend: 'Ext.data.Model', * fields: [ * { name:'src', type:'string' }, * { name:'caption', type:'string' } * ] * }); * * Ext.create('Ext.data.Store', { * id:'imagesStore', * model: 'Image', * data: [ * { src:'http://www.sencha.com/img/20110215-feat-drawing.png', caption:'Drawing & Charts' }, * { src:'http://www.sencha.com/img/20110215-feat-data.png', caption:'Advanced Data' }, * { src:'http://www.sencha.com/img/20110215-feat-html5.png', caption:'Overhauled Theme' }, * { src:'http://www.sencha.com/img/20110215-feat-perf.png', caption:'Performance Tuned' } * ] * }); * * var imageTpl = new Ext.XTemplate( * '<tpl for=".">', * '<div style="margin-bottom: 10px;" class="thumb-wrap">', * '<img src="{src}" />', * '<br/><span>{caption}</span>', * '</div>', * '</tpl>' * ); * * Ext.create('Ext.view.View', { * store: Ext.data.StoreManager.lookup('imagesStore'), * tpl: imageTpl, * itemSelector: 'div.thumb-wrap', * emptyText: 'No images available', * renderTo: Ext.getBody() * }); */ Ext.define('Ext.view.View', { extend: 'Ext.view.AbstractView', alternateClassName: 'Ext.DataView', alias: 'widget.dataview', inputTagRe: /^textarea$|^input$/i, keyEventRe: /^key/, manageLayoutScroll: false, inheritableStatics: { /** * @private * @static * @inheritable */ EventMap: { longpress: 'LongPress', mousedown: 'MouseDown', mouseup: 'MouseUp', click: 'Click', dblclick: 'DblClick', contextmenu: 'ContextMenu', mouseover: 'MouseOver', mouseout: 'MouseOut', mouseenter: 'MouseEnter', mouseleave: 'MouseLeave', keydown: 'KeyDown', keyup: 'KeyUp', keypress: 'KeyPress', focus: 'Focus' }, /** * @private * @static * @inheritable */ TouchEventMap: { touchstart: 'mousedown', touchend: 'mouseup', tap: 'click', doubletap: 'dblclick' } }, /** * @event beforeitemmousedown * @preventable * Fires before the mousedown event on an item is processed. Return false to cancel * the default action. * @param {Ext.view.View} this * @param {Ext.data.Model} record The record that belongs to the item * @param {HTMLElement} item The item's element * @param {Number} index The item's index * @param {Ext.event.Event} e The raw event object */ /** * @event beforeitemmouseup * @preventable * Fires before the mouseup event on an item is processed. Return false to cancel * the default action. * @inheritdoc #beforeitemmousedown */ /** * @event beforeitemmouseenter * @preventable * Fires before the mouseenter event on an item is processed. Return false to cancel * the default action. * @inheritdoc #beforeitemmousedown */ /** * @event beforeitemmouseleave * @preventable * Fires before the mouseleave event on an item is processed. Return false to cancel * the default action. * @inheritdoc #beforeitemmousedown */ /** * @event beforeitemclick * @preventable * Fires before the click event on an item is processed. Return false to cancel the * default action. * @inheritdoc #beforeitemmousedown */ /** * @event beforeitemdblclick * @preventable * Fires before the dblclick event on an item is processed. Return false to cancel * the default action. * @inheritdoc #beforeitemmousedown */ /** * @event beforeitemcontextmenu * @preventable * Fires before the contextmenu event on an item is processed. Return false to * cancel the default action. * @inheritdoc #beforeitemmousedown */ /** * @event beforeitemlongpress * @preventable * Fires before the longpress event on an item is processed. Return false to * cancel the default action. * @inheritdoc #beforeitemmousedown */ /** * @event beforeitemkeydown * @preventable * Fires before the keydown event on an item is processed. Return false to cancel * the default action. * @inheritdoc #beforeitemmousedown */ /** * @event beforeitemkeyup * @preventable * Fires before the keyup event on an item is processed. Return false to cancel the * default action. * @inheritdoc #beforeitemmousedown */ /** * @event beforeitemkeypress * @preventable * Fires before the keypress event on an item is processed. Return false to cancel * the default action. * @inheritdoc #beforeitemmousedown */ /** * @event itemmousedown * Fires when there is a mouse down on an item * @inheritdoc #beforeitemmousedown */ /** * @event itemmouseup * Fires when there is a mouse up on an item * @inheritdoc #beforeitemmousedown */ /** * @event itemmouseenter * Fires when the mouse enters an item. * @inheritdoc #beforeitemmousedown */ /** * @event itemmouseleave * Fires when the mouse leaves an item. * @inheritdoc #beforeitemmousedown */ /** * @event itemclick * Fires when an item is clicked. * @inheritdoc #beforeitemmousedown */ /** * @event itemdblclick * Fires when an item is double clicked. * @inheritdoc #beforeitemmousedown */ /** * @event itemcontextmenu * Fires when an item is right clicked. * @inheritdoc #beforeitemmousedown */ /** * @event itemlongpress * Fires on a longpress event on an item. * @inheritdoc #beforeitemmousedown */ /** * @event itemkeydown * Fires when a key is pressed down while an item is currently selected. * @inheritdoc #beforeitemmousedown */ /** * @event itemkeyup * Fires when a key is released while an item is currently selected. * @inheritdoc #beforeitemmousedown */ /** * @event itemkeypress * Fires when a key is pressed while an item is currently selected. * @inheritdoc #beforeitemmousedown */ /** * @event beforecontainermousedown * Fires before the mousedown event on the container is processed. Returns false to cancel the default action. * @param {Ext.view.View} this * @param {Ext.event.Event} e The raw event object */ /** * @event beforecontainermouseup * Fires before the mouseup event on the container is processed. Returns false to cancel the default action. * @param {Ext.view.View} this * @param {Ext.event.Event} e The raw event object */ /** * @event beforecontainermouseover * Fires before the mouseover event on the container is processed. Returns false to cancel the default action. * @param {Ext.view.View} this * @param {Ext.event.Event} e The raw event object */ /** * @event beforecontainermouseout * Fires before the mouseout event on the container is processed. Returns false to cancel the default action. * @param {Ext.view.View} this * @param {Ext.event.Event} e The raw event object */ /** * @event beforecontainerclick * Fires before the click event on the container is processed. Returns false to cancel the default action. * @param {Ext.view.View} this * @param {Ext.event.Event} e The raw event object */ /** * @event beforecontainerdblclick * Fires before the dblclick event on the container is processed. Returns false to cancel the default action. * @param {Ext.view.View} this * @param {Ext.event.Event} e The raw event object */ /** * @event beforecontainercontextmenu * Fires before the contextmenu event on the container is processed. Returns false to cancel the default action. * @param {Ext.view.View} this * @param {Ext.event.Event} e The raw event object */ /** * @event beforecontainerkeydown * Fires before the keydown event on the container is processed. Returns false to cancel the default action. * @param {Ext.view.View} this * @param {Ext.event.Event} e The raw event object. Use {@link Ext.event.Event#getKey getKey()} to retrieve the key that was pressed. */ /** * @event beforecontainerkeyup * Fires before the keyup event on the container is processed. Returns false to cancel the default action. * @param {Ext.view.View} this * @param {Ext.event.Event} e The raw event object. Use {@link Ext.event.Event#getKey getKey()} to retrieve the key that was pressed. */ /** * @event beforecontainerkeypress * Fires before the keypress event on the container is processed. Returns false to cancel the default action. * @param {Ext.view.View} this * @param {Ext.event.Event} e The raw event object. Use {@link Ext.event.Event#getKey getKey()} to retrieve the key that was pressed. */ /** * @event containermousedown * Fires when there is a mousedown on the container * @param {Ext.view.View} this * @param {Ext.event.Event} e The raw event object */ /** * @event containermouseup * Fires when there is a mouseup on the container * @param {Ext.view.View} this * @param {Ext.event.Event} e The raw event object */ /** * @event containermouseover * Fires when you move the mouse over the container. * @param {Ext.view.View} this * @param {Ext.event.Event} e The raw event object */ /** * @event containermouseout * Fires when you move the mouse out of the container. * @param {Ext.view.View} this * @param {Ext.event.Event} e The raw event object */ /** * @event containerclick * Fires when the container is clicked. * @param {Ext.view.View} this * @param {Ext.event.Event} e The raw event object */ /** * @event containerdblclick * Fires when the container is double clicked. * @param {Ext.view.View} this * @param {Ext.event.Event} e The raw event object */ /** * @event containercontextmenu * Fires when the container is right clicked. * @param {Ext.view.View} this * @param {Ext.event.Event} e The raw event object */ /** * @event containerkeydown * Fires when a key is pressed down while the container is focused, and no item is currently selected. * @param {Ext.view.View} this * @param {Ext.event.Event} e The raw event object. Use {@link Ext.event.Event#getKey getKey()} to retrieve the key that was pressed. */ /** * @event containerkeyup * Fires when a key is released while the container is focused, and no item is currently selected. * @param {Ext.view.View} this * @param {Ext.event.Event} e The raw event object. Use {@link Ext.event.Event#getKey getKey()} to retrieve the key that was pressed. */ /** * @event containerkeypress * Fires when a key is pressed while the container is focused, and no item is currently selected. * @param {Ext.view.View} this * @param {Ext.event.Event} e The raw event object. Use {@link Ext.event.Event#getKey getKey()} to retrieve the key that was pressed. */ /** * @event selectionchange * @inheritdoc Ext.selection.DataViewModel#selectionchange */ /** * @event beforeselect * @inheritdoc Ext.selection.DataViewModel#beforeselect */ /** * @event beforedeselect * @inheritdoc Ext.selection.DataViewModel#beforedeselect */ /** * @event select * @inheritdoc Ext.selection.DataViewModel#select */ /** * @event deselect * @inheritdoc Ext.selection.DataViewModel#deselect */ /** * @event focuschange * @inheritdoc Ext.selection.DataViewModel#focuschange */ /** * @event highlightitem * Fires when a node is highlighted using keyboard navigation, or mouseover. * @param {Ext.view.View} view This View Component. * @param {Ext.dom.Element} node The highlighted node. */ /** * @event unhighlightitem * Fires when a node is unhighlighted using keyboard navigation, or mouseout. * @param {Ext.view.View} view This View Component. * @param {Ext.dom.Element} node The previously highlighted node. */ afterRender: function() { var me = this; me.callParent(); me.mon(me.el, { scope: me, click: me.handleEvent, longpress: me.handleEvent, mousedown: me.handleEvent, mouseup: me.handleEvent, dblclick: me.handleEvent, contextmenu: me.handleEvent, keydown: me.handleEvent, keyup: me.handleEvent, keypress: me.handleEvent, mouseover: me.handleMouseOver, mouseout: me.handleMouseOut }); }, // Can be overridden by features or anything that needs to use a specific selector as a target. getTargetSelector: function () { return this.dataRowSelector || this.itemSelector; }, handleMouseOver: function(e) { var me = this, // this.getTargetSelector() can be used as a template method, e.g., in features. itemSelector = me.getTargetSelector(), item = e.getTarget(itemSelector); // If mouseover/out handling is buffered, view might have been destyroyed during buffer time. if (!me.destroyed) { if (item) { if (me.mouseOverItem !== item && me.el.contains(item)) { me.mouseOverItem = e.item = item; e.newType = 'mouseenter'; me.handleEvent(e); } } else { // We're not over an item, so handle a container event. me.handleEvent(e); } } }, handleMouseOut: function (e) { var me = this, itemSelector = me.getTargetSelector(), item = e.getTarget(itemSelector), computedRelatedTarget = e.getRelatedTarget(itemSelector), sourceView; // We can only exit early when mousing within the same row, but we can't simply do an equality check // since it's valid for both item and computedRelatedTarget to be null! if ((item === computedRelatedTarget) && !(item === null && computedRelatedTarget === null)) { return; } // Note that a mouseout event can trigger either an item event or a container event. // If mouseover/out handling is buffered, view might have been destroyed during buffer time. if (!me.destroyed) { // Yes, this is an assignment. if (item && (sourceView = me.self.getBoundView(item))) { e.item = item; e.newType = 'mouseleave'; sourceView.handleEvent(e); sourceView.mouseOverItem = null; } else { // We're not over an item, so handle a container event. me.handleEvent(e); } } }, handleEvent: function(e) { var me = this, isKeyEvent = me.keyEventRe.test(e.type); // We need to know if the event target is an input field to block // drag n' drop plugin(s) from stopping pointer events as this makes // input fields unfocusable and unselectable. We also need to know // this for key events to prevent scrolling, see below. e.isInputFieldEvent = Ext.fly(e.target).isInputField(); e.view = me; // Find the item from the event target. e.item = e.getTarget(me.itemSelector); if (e.item) { e.record = me.getRecord(e.item); } if (me.processUIEvent(e) !== false) { me.processSpecialEvent(e); } // We need to prevent default action on navigation keys // that can cause View element scroll unless the event is from an input field. // We MUST prevent browser's default action on SPACE which is to focus the event's target element. // Focusing causes the browser to attempt to scroll the element into view. if (isKeyEvent && !e.isInputFieldEvent) { if (e.getKey() === e.SPACE || e.isNavKeyPress(true)) { e.preventDefault(); } } e.view = null; }, /** * @private */ processItemEvent: Ext.emptyFn, processContainerEvent: Ext.emptyFn, processSpecialEvent: Ext.emptyFn, processUIEvent: function(e) { // If the target event has been removed from the body (data update causing view DOM to be updated), // do not process. isAncestor uses native methods to check. if (!Ext.getBody().isAncestor(e.target)) { return; } var me = this, item = e.item, self = me.self, map = self.EventMap, touchMap = self.TouchEventMap, index, record = e.record, type = e.type, newType = type; // If the event is a mouseover/mouseout event converted to a mouseenter/mouseleave, // use that event type. if (e.newType) { newType = e.newType; } if (item) { newType = touchMap[newType] || newType; index = e.recordIndex = me.indexInStore ? me.indexInStore(record) : me.indexOf(item); // It is possible for an event to arrive for which there is no record... this // can happen with dblclick where the clicks are on removal actions (think a // grid w/"delete row" action column) or if the record was in a page that was // pruned by a buffered store. if (!record || me.processItemEvent(record, item, index, e) === false) { return false; } if ( (me['onBeforeItem' + map[newType]](record, item, index, e) === false) || (me.fireEvent('beforeitem' + newType, me, record, item, index, e) === false) || (me['onItem' + map[newType]](record, item, index, e) === false) ) { return false; } me.fireEvent('item' + newType, me, record, item, index, e); } else { type = touchMap[type] || type; if ( (me.processContainerEvent(e) === false) || (me['onBeforeContainer' + map[type]](e) === false) || (me.fireEvent('beforecontainer' + type, me, e) === false) || (me['onContainer' + map[type]](e) === false) ) { return false; } me.fireEvent('container' + type, me, e); } return true; }, /** * @private */ onItemMouseEnter: function(record, item, index, e) { if (this.trackOver) { this.highlightItem(item); } }, /** * @private */ onItemMouseLeave : function(record, item, index, e) { if (this.trackOver) { this.clearHighlight(); } }, /** * @private */ onItemMouseDown: Ext.emptyFn, onItemLongPress: Ext.emptyFn, onItemMouseUp: Ext.emptyFn, onItemFocus: Ext.emptyFn, onItemClick: Ext.emptyFn, onItemDblClick: Ext.emptyFn, onItemContextMenu: Ext.emptyFn, onItemKeyDown: Ext.emptyFn, onItemKeyUp: Ext.emptyFn, onItemKeyPress: Ext.emptyFn, onBeforeItemLongPress: Ext.emptyFn, onBeforeItemMouseDown: Ext.emptyFn, onBeforeItemMouseUp: Ext.emptyFn, onBeforeItemFocus: Ext.emptyFn, onBeforeItemMouseEnter: Ext.emptyFn, onBeforeItemMouseLeave: Ext.emptyFn, onBeforeItemClick: Ext.emptyFn, onBeforeItemDblClick: Ext.emptyFn, onBeforeItemContextMenu: Ext.emptyFn, onBeforeItemKeyDown: Ext.emptyFn, onBeforeItemKeyUp: Ext.emptyFn, onBeforeItemKeyPress: Ext.emptyFn, /** * @private */ onContainerMouseDown: Ext.emptyFn, onContainerLongPress: Ext.emptyFn, onContainerMouseUp: Ext.emptyFn, onContainerMouseOver: Ext.emptyFn, onContainerMouseOut: Ext.emptyFn, onContainerClick: Ext.emptyFn, onContainerDblClick: Ext.emptyFn, onContainerContextMenu: Ext.emptyFn, onContainerKeyDown: Ext.emptyFn, onContainerKeyUp: Ext.emptyFn, onContainerKeyPress: Ext.emptyFn, onBeforeContainerMouseDown: Ext.emptyFn, onBeforeContainerLongPress: Ext.emptyFn, onBeforeContainerMouseUp: Ext.emptyFn, onBeforeContainerMouseOver: Ext.emptyFn, onBeforeContainerMouseOut: Ext.emptyFn, onBeforeContainerClick: Ext.emptyFn, onBeforeContainerDblClick: Ext.emptyFn, onBeforeContainerContextMenu: Ext.emptyFn, onBeforeContainerKeyDown: Ext.emptyFn, onBeforeContainerKeyUp: Ext.emptyFn, onBeforeContainerKeyPress: Ext.emptyFn, /** * @private */ setHighlightedItem: function(item){ var me = this, highlighted = me.highlightedItem, overItemCls = me.overItemCls; if (highlighted !== item){ if (highlighted) { Ext.fly(highlighted).removeCls(overItemCls); //<feature legacyBrowser> // Work around for an issue in IE8 where the focus/over/selected borders do not // get updated where applied using adjacent sibling selectors. if (Ext.isIE8) { me.repaintBorder(highlighted); me.repaintBorder(highlighted.nextSibling); } //</feature> if (me.hasListeners.unhighlightitem) { me.fireEvent('unhighlightitem', me, highlighted); } } me.highlightedItem = item; if (item) { Ext.fly(item).addCls(me.overItemCls); //<feature legacyBrowser> // Work around for an issue in IE8 where the focus/over/selected borders do not // get updated where applied using adjacent sibling selectors. if (Ext.isIE8) { me.repaintBorder(item.nextSibling); } //</feature> if (me.hasListeners.highlightitem) { me.fireEvent('highlightitem', me, item); } } } }, /** * Highlights a given item in the View. This is called by the mouseover handler if {@link #overItemCls} * and {@link #trackOver} are configured, but can also be called manually by other code, for instance to * handle stepping through the list via keyboard navigation. * @param {HTMLElement} item The item to highlight */ highlightItem: function(item) { this.setHighlightedItem(item); }, /** * Un-highlights the currently highlighted item, if any. */ clearHighlight: function() { this.setHighlightedItem(undefined); }, handleUpdate: function(store, record){ var me = this, node, newNode, highlighted; if (me.viewReady) { node = me.getNode(record); newNode = me.callParent(arguments); highlighted = me.highlightedItem; if (highlighted && highlighted === node) { delete me.highlightedItem; if (newNode) { me.highlightItem(newNode); } } } }, refresh: function() { this.clearHighlight(); this.callParent(arguments); }, /** * Focuses a node in the view. * @param {Ext.data.Model} rec The record associated to the node that is to be focused. */ focusNode: function(rec){ var me = this, node = Ext.fly(me.getNode(rec)), el = me.el, adjustmentY = 0, adjustmentX = 0, elRegion = el.getRegion(), nodeRegion; // Viewable region must not include scrollbars, so use // DOM client dimensions elRegion.bottom = elRegion.top + el.dom.clientHeight; elRegion.right = elRegion.left + el.dom.clientWidth; if (node) { nodeRegion = node.getRegion(); // node is above if (nodeRegion.top < elRegion.top) { adjustmentY = nodeRegion.top - elRegion.top; } // node is below else if (nodeRegion.bottom > elRegion.bottom) { adjustmentY = nodeRegion.bottom - elRegion.bottom; } // node is left if (nodeRegion.left < elRegion.left) { adjustmentX = nodeRegion.left - elRegion.left; } // node is right else if (nodeRegion.right > elRegion.right) { adjustmentX = nodeRegion.right - elRegion.right; } if (adjustmentX || adjustmentY) { me.scrollBy(adjustmentX, adjustmentY, false); } // Poke on a tabIndex to make the node focusable. node.set({ tabIndex: -1 }); node.focus(); } }, privates: { //<feature legacyBrowser> // Work around for an issue in IE8 where the focus/over/selected borders do not // get updated where applied using adjacent sibling selectors. repaintBorder: function(rowIdx) { var node = this.getNode(rowIdx); if (node) { node.className = node.className; } } //</feature> } });
/** * Angular loading bar configuration. */ define([ ], function () { "use strict"; var LoadingBarConfig = function ($stateProvider, $urlRouterProvider, cfpLoadingBarProvider) { // set loading bar preferences cfpLoadingBarProvider.includeSpinner = true; // only show the loading bar if the resolve takes more than 1 second. this prevents the user // from seeing the loading bar flash on the screen when the resolve completes quickly. cfpLoadingBarProvider.latencyThreshold = 1000; }; return function(app) { app.config(['$stateProvider', '$urlRouterProvider', 'cfpLoadingBarProvider', LoadingBarConfig]); }; });
let Action = require('./Action'), calc = require('../inc/calc'), utils = require('../inc/utils'), simulations = require('./simulate/simulations'); const DEFAULT_PROP = 'velocity'; class Simulate extends Action { constructor(...args) { super(...args); this.calculatesVelocity = true; this.inactiveFrames = 0; } getDefaultProps() { return { maxInactiveFrames: 3 }; } getDefaultValue() { return { // [string]: Simulation to .run simulate: DEFAULT_PROP, // [number]: Deceleration to apply to value, in units per second deceleration: 0, // [number]: Acceleration to apply to value, in units per second acceleration: 0, // [number]: Factor to multiply velocity by on bounce bounce: 0, // [number]: Spring strength during 'string' spring: 80, // [number]: Timeconstant of glide timeConstant: 395, // [number]: Stop simulation under this speed stopSpeed: 5, // [boolean]: Capture with spring physics on limit breach capture: false, // [number]: Friction to apply per frame friction: 0, to: 0, round: false }; } getDefaultValueProp() { return DEFAULT_PROP; } /* Simulate the Value's per-frame movement @param [Actor] @param [Value]: Current value @param [string]: Key of current value @param [number]: Duration of frame in ms @return [number]: Calculated value */ process(actor, value, key, timeSinceLastFrame) { var simulate = value.simulate, simulation = utils.isString(simulate) ? simulations[simulate] : simulate, newVelocity = simulation ? simulation(value, timeSinceLastFrame, actor.started) : 0; value.velocity = (Math.abs(newVelocity) >= value.stopSpeed) ? newVelocity : 0; return value.current + calc.speedPerFrame(value.velocity, timeSinceLastFrame); } /* Has this action ended? Use a framecounter to see if Action has changed in the last x frames and declare ended if not @param [Actor] @param [boolean]: Has Action changed? @return [boolean]: Has Action ended? */ hasEnded(actor, hasChanged) { this.inactiveFrames = hasChanged ? 0 : this.inactiveFrames + 1; return (this.inactiveFrames > actor.maxInactiveFrames); } /* Limit output to value range, if any If velocity is at or more than range, and value has a bounce property, run the bounce simulation @param [number]: Calculated output @param [Value]: Current Value @return [number]: Limit-adjusted output */ limit(output, value) { var isOutsideMax = (output >= value.max), isOutsideMin = (output <= value.min), isOutsideRange = isOutsideMax || isOutsideMin; if (isOutsideRange) { output = calc.restricted(output, value.min, value.max); if (value.bounce) { value.velocity = simulations.bounce(value); } else if (value.capture) { simulations.capture(value, isOutsideMax ? value.max : value.min); } } return output; } } module.exports = Simulate;
/** * Created by Vicky on 5/26/2017. */ function fruitOrVeggie(item){ "use strict"; switch (item){ case 'banana': case 'apple': case 'kiwi': case 'cherry': case 'lemon': case 'grapes': case 'peach': console.log('fruit'); break; case 'tomato': case 'cucumber': case 'pepper': case 'onion': case 'garlic': case 'parsley': console.log('vegetable'); break; default: console.log('unknown'); } }
define([], function() { "use strict"; var $__default = { "abstract": true, "controller": true, "template": true, "url": "" }; return { get default() { return $__default; }, __esModule: true }; });
"use strict"; exports.__esModule = true; var core_1 = require("@angular/core"); var ImagePreviewDirective = (function () { function ImagePreviewDirective(el, renderer) { this.el = el; this.renderer = renderer; } ImagePreviewDirective.prototype.ngOnChanges = function (changes) { var reader = new FileReader(); var el = this.el; reader.onloadend = function (e) { el.nativeElement.style.backgroundImage = "url(" + reader.result + ")"; }; if (this.image) { return reader.readAsDataURL(this.image); } }; return ImagePreviewDirective; }()); ImagePreviewDirective.decorators = [ { type: core_1.Directive, args: [{ selector: 'div[imgPreview]' },] }, ]; /** @nocollapse */ ImagePreviewDirective.ctorParameters = function () { return [ { type: core_1.ElementRef }, { type: core_1.Renderer }, ]; }; ImagePreviewDirective.propDecorators = { 'image': [{ type: core_1.Input },] }; exports.ImagePreviewDirective = ImagePreviewDirective;
const next = require('next'); const express = require('express'); const port = parseInt(process.env.PORT, 10) || 3000; const dev = process.env.NODE_ENV !== 'production'; const app = next({ dev }); const handle = app.getRequestHandler(); app.prepare().then(() => { const server = express(); // use pages/index.js as / server.get('/', (req, res) => app.render(req, res, '/', req.query)); // use pages/post.js as /blogger/:id server.get('/blogger/:route', (req, res) => app.render(req, res, '/blogger', Object.assign({ route: req.params.route }, req.query))); server.get('/blogger/:route/:id', (req, res) => app.render(req, res, '/blogger', Object.assign({ route: req.params.route, id: req.params.id }, req.query))); // redirect from /post to /blogger or /post?id to /blogger/:id // server.get('/post', (req, res) => { // if (req.query.id) { // return res.redirect('/blogger'); // } // res.redirect(301, `/blogger/${req.query.id}`); // }); // redirect / to /blogger // server.get('/', (req, res) => { // res.redirect(301, '/blogger'); // }); // handle each other url server.get('*', (req, res) => handle(req, res)); server.listen(port, err => { if (err) throw err; console.log(`> Ready on http://localhost:${port}`); }); });
/* eslint-disable react/prefer-stateless-function, no-use-before-define, react/jsx-no-bind, react/prop-types */ import React, { Component } from 'react-native'; import FriendEntry from '../components/friend_entry'; import { connect } from 'react-redux'; import Immutable from 'immutable'; // just for testing import { fetchFriends } from '../actions/index'; import Button from '../components/button'; import { inviteFriends } from '../actions/index'; const { ListView, PropTypes, StyleSheet, Text, View, ActivityIndicatorIOS, } = React; // todo: consider factoring out view rendering into own component class SelectFriendsContainer extends Component { constructor(props) { super(props); this.getDataSource = this.getDataSource.bind(this); this.onCheck = this.onCheck.bind(this); this.onRenderRow = this.onRenderRow.bind(this); this.onInvitePress = this.onInvitePress.bind(this); this.state = { checkedFriends: {}, }; } componentWillMount() { this.props.fetchFriends({ id: this.props.userId, token: this.props.token, }); } onCheck(id) { const newChecked = this.state.checkedFriends; if (newChecked[id]) { delete newChecked[id]; } else { newChecked[id] = true; } this.setState({checkedFriends: newChecked}); } onSubmitClick(quiltId, navigator) { // route to video camera not yet implemented navigator.push('video'); } onInvitePress() { const checkedIds = Object.keys(this.state.checkedFriends).map(id => parseInt(id)); this.props.inviteFriends(checkedIds); this.props.navigator.push({ name: 'camera' }); } onRenderRow(rowData) { return ( <FriendEntry user={rowData} onCheck={this.onCheck} checked={ this.props.currentQuilt.get('users').toArray() ? this.props.currentQuilt.get('users').toArray().indexOf(rowData.id) !== -1 : false } key={rowData.id} /> ); } getDataSource() { const ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => !Immutable.is(r1, r2) }); return ds.cloneWithRows(this.props.friends.get('friendsList').toArray()); } render() { if (this.props.friends.get('isFetching')) { return <ActivityIndicatorIOS animating={true} style={{height: 80}} size="large" />; } return ( <View style={styles.container}> <ListView dataSource={this.getDataSource()} renderRow={this.onRenderRow} /> <Button text={'Invite!'} onPress={this.onInvitePress} /> </View> ); } } SelectFriendsContainer.propTypes = { onPress: PropTypes.func, // quilts: PropTypes.object, friends: PropTypes.object, }; const styles = StyleSheet.create({ container: { flex: 1, }, }); const mapStateToProps = (state) => { const friends = state.get('friends'); const currentQuilt = state.get('currentQuilt'); const user = state.get('user'); return { friends, currentQuilt, username: user.get('username'), token: user.get('token'), userId: user.get('id'), }; }; function mapDispatchToProps(dispatch) { return { fetchFriends: (data) => { dispatch(fetchFriends(data)); }, inviteFriends: (data) => { dispatch(inviteFriends(data)); }, }; } export default connect(mapStateToProps, mapDispatchToProps)(SelectFriendsContainer);
var jef = require('jef'); function TextControl(model, element, contentBinding){ var control = this; this._render = function(){ if(typeof window === 'undefined'){ this.element = element; }else{ this.element = document.createTextNode(element.textContent); element.parentNode.insertBefore(this.element, element); element.parentNode.removeChild(element); } }; this._contentBinding = contentBinding; jef.Control.apply(this, arguments); jef.addProperty(control, 'content'); this._bind(); } TextControl.prototype = Object.create(jef.Control.prototype); TextControl.prototype.constructor = TextControl; TextControl.prototype._bind = function(){ var control = this; this.content.onChange(function(value){ control.element.textContent = value == null ? '' : value; }); this.content.bindTo(control.model, this._contentBinding); }; module.exports = TextControl;
/** * Created by SASi on 14-May-16. */ module.exports = (function () { const mongoose = global.mongoose; const jwt = global.jwt; const bcrypt = global.bcrypt; const request = require("request"); const UserModel = require('../models/user'); const ProjectModel = require('../models/project'); const ReportsModel = require('../models/reports'); const uuid = global.uuid; /** replace with your mail gun api key & domain*/ const mail_gun_api_key = 'key-c30200eed9880cbcf5f07aa0725146a0'; const domain = 'sandboxb54041ce3a43476a8e0a99c7836e96f1.mailgun.org'; var mailgun = require('mailgun-js')({apiKey: mail_gun_api_key, domain: domain}); /** Register new user*/ const register = function (req, res) { var data = req.body; if (data.password !== data.confirmPassword) { res.status(401).json({err: "Password and Confirm Password must be the same"}); } else { var user = new UserModel({ email: data.email, name: data.name, password: bcrypt.hashSync(data.password), mobile: data.mobile, 'meta.verification_token': uuid.v4() }); user.save(function (err, userDoc, numAffected) { if (err) { if (err.code === 11000) { res.status(400).json({err: "Account already exists"}); } else { res.status(400).json(err); } } else { var myToken = jwt.sign({email: data.email, id: userDoc._id}, global.secret, {expiresIn: '1d'}); res.status(200).json({ message: "success", name: user.name, email: user.email, mobile: user.mobile, auth_token: myToken }); } }); } }; /** Login existing user*/ const login = function (req, res) { var data = req.body; UserModel.findOne({email: data.email}, function (err, user) { if (err) res.status(400).json(err); else if (user) { bcrypt.compare(data.password, user.password, function (err, status) { if (status) { var myToken = jwt.sign({ username: data.email, id: user._id }, global.secret, {expiresIn: '1d'}); res.status(200).json({ name: user.name, email: user.email, mobile: user.mobile, auth_token: myToken }); } else { res.status(401).json({err: "Invalid Password"}); } }); } else { res.status(401).json({err: "Account doesn't exists."}); } }); }; /** Create a new project */ const addProject = function (req, res) { var data = req.body; var cookies = req.cookies; var token = cookies.auth_token; jwt.verify(token, global.secret, function (err, decoded) { if (err) { res.status(401).json(err); } else { var user = decoded; var project = new ProjectModel({ title: data.title, description: data.description }); project.save(function (err, projectDoc, numAffected) { if (err) { res.status(400).json(err); } else { UserModel.findByIdAndUpdate(user.id, {$push: {projects: projectDoc._id}}, function (err, doc) { if (err) console.log(err); else { res.status(200).json({ _id: projectDoc._id, title: projectDoc.title, description: projectDoc.description }); } }); } }); } }); }; /** List projects related to an User */ const getProjects = function (req, res) { var cookies = req.cookies; var token = cookies.auth_token; jwt.verify(token, global.secret, function (err, decoded) { if (err) { res.status(401).json(err); } else { var user = decoded; UserModel.findById(user.id) .select('projects') .populate('projects', '-reports -configuration') .exec(function (err, projectDocs) { if (err) { res.status(400).json(err); } else { res.status(200).json(projectDocs.projects.reverse()); } }); } }); }; /** Get a Project details */ const getProject = function (req, res) { var id = req.params.id; var cookies = req.cookies; var token = cookies.auth_token; jwt.verify(token, global.secret, function (err, decoded) { if (err) { res.status(401).json(err); } else { var user = decoded; ProjectModel.findById(id, function (err, project) { if (err) { res.status(400).json(err); } else { res.status(200).json(project); } }); } }); }; /** Update project details */ const updateProject = function (req, res) { var data = req.body; var id = req.params.id; var emailsConfigured = data.emailsConfigured.split(","); var cookies = req.cookies; var token = cookies.auth_token; jwt.verify(token, global.secret, function (err, decoded) { if (err) { res.status(401).json(err); } else { var user = decoded; ProjectModel.findByIdAndUpdate(id, { title: data.title, description: data.description, 'configuration.emailsConfigured': emailsConfigured, 'configuration.slackConfiguration.api_key': data.slackAPIKey, 'configuration.slackConfiguration.channel_name': data.slackChannelName }, function (err, project) { if (err) res.status(400).json(err); else res.status(200).json(project); }); } }); }; /** Delete a project */ const deleteProject = function (req, res) { var id = req.params.id; var cookies = req.cookies; var token = cookies.auth_token; jwt.verify(token, global.secret, function (err, decoded) { if (err) { res.status(401).json(err); } else { var user = decoded; ProjectModel.findByIdAndRemove(id, function (err) { if (err) { res.status(400).json(err); } else { res.status(200).json({message: "success"}); } }); } }); }; const reportError = function (req, res) { var data = JSON.parse(req.body.report); ProjectModel.findById(data.key, function (err, project) { if (err) res.status(400).json(err); else if (project != null) { var report = new ReportsModel({ error_type: data.error_type, error_message: data.error_message, url: data.url, line_number: data.line_number, column_number: data.column_number, stack_trace: data.stack_trace, browser_details: data.browser_details, operating_system: data.operating_system, time_stamp: data.time_stamp }); report.save(function (err, reportDoc, numAffected) { if (err) res.status(400).json(err); else { project.reports.push(reportDoc._id); project.save(function (err) { if (err) res.status(400).json(err); else { res.status(200).json({message: "success"}); var recipients = project.configuration.emailsConfigured; /** mail */ if (!recipients.length) return; else { var mail_data = { from: 'Bug Tracker <no-reply@bugtracker.mailgun.org>', to: recipients, subject: 'Bug Report', html: '<pre>' + "Project Name: " + project.title + "\nError Type: " + data.error_type + "\nError Message: " + data.error_message + "\nurl: " + data.url + "\nLine Number: " + data.line_number + "\nColumn Number: " + data.column_number + "\nStack Trace: " + data.stack_trace + "\nBrowser Details: " + data.browser_details + "\nOperating System: " + data.operating_system + "\nTime Stamp: " + data.time_stamp + '</pre>' }; mailgun.messages().send(mail_data, function (error, body) { console.log(error); }); } /**slack*/ var slackAPIKey = project.configuration.slackConfiguration.api_key; var channelName = project.configuration.slackConfiguration.channel_name; if (slackAPIKey) { var options = { method: 'POST', uri: 'https://slack.com/api/chat.postMessage', form: { token: slackAPIKey, channel: channelName, text: 'Bug Report : ' + JSON.stringify(data) } }; request(options, function (error, response, body) { if (error) console.log(error); else console.log(response); }); } } }); } }) } else { res.status(502).json({err: "Not found"}); } }); }; /** Get reports related to a project */ const getReports = function (req, res) { var id = req.params.id; var cookies = req.cookies; var token = cookies.auth_token; jwt.verify(token, global.secret, function (err, decoded) { if (err) { res.status(401).json(err); } else { var user = decoded; ProjectModel.findById(id) .select('reports') .populate('reports') .exec(function (err, reportDocs) { if (err) res.status(400).json(err); else { res.status(200).json(reportDocs.reports.reverse()); } }) } }); }; const updateReport = function (req, res) { var id = req.params.id; var data = req.body; var cookies = req.cookies; var token = cookies.auth_token; jwt.verify(token, global.secret, function (err, decoded) { if (err) { res.status(401).json(err); } else { var user = decoded; ReportsModel.findByIdAndUpdate(id, { is_resolved: data.is_resolved }, function (err, reportDoc) { if (err) res.status(400).json(err); else { res.status(200).json(reportDoc); } }); } }); }; const deleteReport = function (req, res) { var id = req.params.id; var cookies = req.cookies; var token = cookies.auth_token; jwt.verify(token, global.secret, function (err, decoded) { if (err) { res.status(401).json(err); } else { var user = decoded; ReportsModel.findByIdAndRemove(id, function (err) { if (err) res.status(400).json(err); else { res.status(200).json({message: "success"}); } }); } }); }; return { register: register, login: login, addProject: addProject, getProjects: getProjects, getProject: getProject, updateProject: updateProject, deleteProject: deleteProject, reportError: reportError, getReports: getReports, updateReport: updateReport, deleteReport: deleteReport } })();
angular.module('app.posts-index', []). config(function($stateProvider) { $stateProvider.state( 'posts-index', { resolve:{ posts: function(getPosts){ // $http returns a promise for the url data //return $http({method: 'GET', url: '/posts'}); return getPosts.init(); } }, url: '/posts', views: { "main": { controller: 'PostsIndexCtrl', templateUrl: 'posts/index/posts-index.tpl.html' } }, data:{ pageTitle: 'Start'} }); }) .controller('PostsIndexCtrl',function($scope, $http, posts){ $scope.posts=posts.data; });
'use strict'; angular.module('myApp.loginDirective', ['ngRoute']).directive('login', function () { return { restrict: 'E', scope: {}, templateUrl: 'components/directives/templates/login-template.html', controller: function ($scope, loginService, $cookies) { $scope.loggedIn = false; $scope.errorTextAlert = false; var token; $cookies.get('praktika_token') ? token = JSON.parse($cookies.get('praktika_token')).token : token = false; if($cookies.get('praktika_token')) { $scope.guestName = JSON.parse($cookies.get('praktika_token')).username; $scope.loggedIn = true; } $scope.login = function () { loginService.loginUser($scope.guest).then( function (success) { $scope.errorTextAlert = loginService.errorText(); //$scope.errorTextAlert = success.message; //console.log(success); if(success.success) { loginService.setToken(success.token, success.username,success.userID); //console.log($scope.guest); //console.log(success.username,success.userID); //loginService.guestName = $scope.guest.username; //$scope.guestName = loginService.guestName; $scope.guestName = $scope.guest.username; $scope.loggedIn = true; } }, function (error) { console.log('error'); $scope.errorTextAlert = error; }); }; } }; });
angular.module('arBlog') .controller('TagsCtrl',[ '$scope', 'postsFactory', 'metaService', 'marked', function($scope,postsFactory,metaService,marked){ $scope.posts = postsFactory.posts; $scope.resume = function(body){ //console.log(body); return body.split(/\s+/).slice(0,10).join(" ") + "..."; }; $scope.renderText = function(text){ return marked(text); }; //meta title metaService.setTitle('Blog de mierda'); //meta description metaService.setDescription('Descripción del Blog de mierda'); } ]); //incluir codigo de paginación???
// default message object function messages(type) { switch(type) { case 'home': var message = { title: 'Escribe en el buscador lo que quieres encontrar', advices: [ 'Escribe tu búsqueda en el campo que figura en la parte superior de la pantalla.' ] } break case 'page_not_found': var message = { title: 'Parece que esta página no existe', advices: [ 'Escribe tu búsqueda en el campo que figura en la parte superior de la pantalla.' ] } break case 'product_not_found': var message = { title: 'No hay publicaciones que coincidan con tu búsqueda.', advices: [ 'Revisa la ortografía de la palabra.', 'Utiliza palabras más genéricas o menos palabras.', 'Navega por categorías de productos para encontrar un producto similar.' ] } break case 'error': var message = { title: 'Ha ocurrido un error!', advices: [ 'Intentá refrescar la pantalla' ] } break } // return return message } // exports module.exports = messages
var searchData= [ ['disablecompare_124',['disableCompare',['../class_a_d_c___module.html#ac635f675a9690a4db016c73c31818262',1,'ADC_Module']]], ['disabledma_125',['disableDMA',['../class_a_d_c___module.html#ac1610dcab46476f287c2dd4d96465c47',1,'ADC_Module']]], ['disableinterrupts_126',['disableInterrupts',['../class_a_d_c___module.html#aa4509062644982526fee3c02e0b528fc',1,'ADC_Module']]] ];
/* Product Name: dhtmlxSuite Version: 4.3 Edition: Standard License: content of this file is covered by GPL. Usage outside GPL terms is prohibited. To obtain Commercial or Enterprise license contact sales@dhtmlx.com Copyright UAB Dinamenta http://www.dhtmlx.com */ //please beware that function started from _in_header_ must not be obfuscated /** * @desc: filter grid by mask * @type: public * @param: column - {number} zero based index of column * @param: value - {string} filtering mask * @param: preserve - {bool} filter current or initial state ( false by default ) * @edition: Professional * @topic: 0 */ dhtmlXGridObject.prototype.filterBy=function(column, value, preserve){ if (this.isTreeGrid()) return this.filterTreeBy(column, value, preserve); if (this._f_rowsBuffer){ if (!preserve){ this.rowsBuffer=dhtmlxArray([].concat(this._f_rowsBuffer)); if (this._fake) this._fake.rowsBuffer=this.rowsBuffer; } } else this._f_rowsBuffer=[].concat(this.rowsBuffer); //backup copy if (!this.rowsBuffer.length) return; var d=true; this.dma(true) if (typeof(column)=="object") for (var j=0; j<value.length; j++) this._filterA(column[j],value[j]); else this._filterA(column,value); this.dma(false) if (this.pagingOn && this.rowsBuffer.length/this.rowsBufferOutSize < (this.currentPage-1)) this.changePage(0); this._reset_view(); this.callEvent("onGridReconstructed",[]) } dhtmlXGridObject.prototype._filterA=function(column,value){ if (value=="") return; var d=true; if (typeof(value)=="function") d=false; else value=(value||"").toString().toLowerCase(); if (!this.rowsBuffer.length) return; for (var i=this.rowsBuffer.length-1; i>=0; i--) if (d?(this._get_cell_value(this.rowsBuffer[i],column).toString().toLowerCase().indexOf(value)==-1):(!value.call(this, this._get_cell_value(this.rowsBuffer[i],column),this.rowsBuffer[i].idd))) this.rowsBuffer.splice(i,1);//filter row } dhtmlXGridObject.prototype.getFilterElement=function(index){ if (!this.filters) return; for (var i=0; i < this.filters.length; i++) { if (this.filters[i][1]==index) return (this.filters[i][0].combo||this.filters[i][0]); }; return null; } /** * @desc: get all possible values in column * @type: public * @param: column - {number} zero based index of column * @returns: {array} array of all possible values in column * @edition: Professional * @topic: 0 */ dhtmlXGridObject.prototype.collectValues=function(column){ var evs = this.dhxevs.data.oncollectvalues; if (evs){ var value = true; for (var key in evs){ var nextvalue = evs[key].call(this, column); if (nextvalue !== true) value = nextvalue || value; } if (value !== true) return value; } if (this.isTreeGrid()) return this.collectTreeValues(column); this.dma(true) this._build_m_order(); column=this._m_order?this._m_order[column]:column; var c={}; var f=[]; var col=this._f_rowsBuffer||this.rowsBuffer; for (var i=0; i<col.length; i++){ var val=this._get_cell_value(col[i],column); if (val && (!col[i]._childIndexes || col[i]._childIndexes[column]!=col[i]._childIndexes[column-1])) c[val]=true; } this.dma(false); var vals= (this.combos[column]||(this._col_combos?this._col_combos[column]:false)); for (var d in c) if (c[d]===true){ if(vals){ if(vals.get&&vals.get(d)){ d = vals.get(d); } else if(vals.getOption&&vals.getOption(d)){ d = vals.getOption(d).text; } } f.push(d); } return f.sort(); } dhtmlXGridObject.prototype._build_m_order=function(){ if (this._c_order){ this._m_order=[] for (var i=0; i < this._c_order.length; i++) { this._m_order[this._c_order[i]]=i; }; } } /** * @desc: force grid filtering by registered inputs ( created by # starting shortcuts, or by makeFilter function ) * @type: public * @edition: Professional * @topic: 0 */ dhtmlXGridObject.prototype.filterByAll=function(){ var a=[]; var b=[]; this._build_m_order(); for (var i=0; i<this.filters.length; i++){ var ind=this._m_order?this._m_order[this.filters[i][1]]:this.filters[i][1]; if (ind >= this._cCount) continue; b.push(ind); var val=this.filters[i][0].old_value=this.filters[i][0].value; if (this.filters[i][0]._filter) val = this.filters[i][0]._filter(); var vals; if (typeof val != "function" && (vals=(this.combos[ind]||(this._col_combos?this._col_combos[ind]:false)))){ if(vals.values){ ind=vals.values._dhx_find(val); val=(ind==-1)?val:vals.keys[ind]; } else if(vals.getOptionByLabel){ val=(vals.getOptionByLabel(val)?vals.getOptionByLabel(val).value:val); } } a.push(val); } if (!this.callEvent("onFilterStart",[b,a])) return; this.filterBy(b,a); if (this._cssEven) this._fixAlterCss(); this.callEvent("onFilterEnd",[this.filters]); if (this._f_rowsBuffer && this.rowsBuffer.length == this._f_rowsBuffer.length) this._f_rowsBuffer = null; } /** * @desc: create a filter from any input element (text filter), select (dropdown) or DIV (combobox based on dhtmlxCombo) * @type: public * @param: id - {string|object} input id or input html object * @param: column - {number} index of column * @param: preserve - {bool} filter current state or initial one ( false by default ) * @edition: Professional * @topic: 0 */ dhtmlXGridObject.prototype.makeFilter=function(id,column,preserve){ if (!this.filters) this.filters=[]; if (typeof(id)!="object") id=document.getElementById(id); if(!id) return; var self=this; if (!id.style.width) id.style.width = "90%"; if (id.tagName=='SELECT'){ this.filters.push([id,column]); this._loadSelectOptins(id,column); id.onchange=function(){ self.filterByAll(); } if(_isIE) id.style.marginTop="1px"; this.attachEvent("onEditCell",function(stage,a,ind){ this._build_m_order(); if (stage==2 && this.filters && ( this._m_order?(ind==this._m_order[column]):(ind==column) )) this._loadSelectOptins(id,column); return true; }); } else if (id.tagName=='INPUT'){ this.filters.push([id,column]); id.old_value = id.value=''; id.onkeydown=function(){ if (this._timer) window.clearTimeout(this._timer); this._timer=window.setTimeout(function(){ if (id.value != id.old_value){ self.filterByAll(); id.old_value=id.value; } },500); }; } else if (id.tagName=='DIV' && id.className=="combo"){ this.filters.push([id,column]); id.style.padding="0px";id.style.margin="0px"; if (!window.dhx_globalImgPath) window.dhx_globalImgPath=this.imgURL; var z=new dhtmlXCombo(id,"_filter","90%"); z.filterSelfA=z.filterSelf; z.filterSelf=function(){ if (this.getSelectedIndex()==0) this.setComboText(""); this.filterSelfA.apply(this,arguments); this.optionsArr[0].hide(false); } z.enableFilteringMode(true); id.combo=z; id.value=""; this._loadComboOptins(id,column); z.attachEvent("onChange",function(){ id.value=z.getSelectedValue(); if (id.value === null) id.value = ""; self.filterByAll(); }); } if (id.parentNode) id.parentNode.className+=" filter"; this._filters_ready(); //set event handlers } /** * @desc: find cell in grid by value * @param: value - search string * @param: c_ind - index of column to search in (optional. if not specified, then search everywhere) * @param: count - count of results to return * @edition: Professional * @returns: array each member of which contains array with row ID and cell index * @type: public */ dhtmlXGridObject.prototype.findCell=function(value, c_ind, count, compare){ var compare = compare || (function(master, check){ return check.toString().toLowerCase().indexOf(master) != -1; }); if (compare === true) compare = function(master, check){ return check.toString().toLowerCase() == master; }; var res = new Array(); value=value.toString().toLowerCase(); if (typeof count != "number") count = count?1:0; if (!this.rowsBuffer.length) return res; for (var i = (c_ind||0); i < this._cCount; i++){ if (this._h2) this._h2.forEachChild(0,function(el){ if (count && res.length==count) return res; if (compare(value, this._get_cell_value(el.buff,i))){ res.push([el.id,i]); } },this) else for (var j=0; j < this.rowsBuffer.length; j++) if (compare(value, this._get_cell_value(this.rowsBuffer[j],i))){ res.push([this.rowsBuffer[j].idd,i]); if (count && res.length==count) return res; } if (typeof (c_ind) != "undefined") return res; } return res; } /** * @desc: create a search box (set selection to the row with found value) from any input * @type: public * @param: id - {string|object} input id or input html object * @param: column - {number} index of column * @edition: Professional * @topic: 0 */ dhtmlXGridObject.prototype.makeSearch=function(id,column,strict){ if (typeof(id)!="object") id=document.getElementById(id); if(!id) return; var self=this; if (id.tagName=='INPUT'){ id.onkeypress=function(){ if (this._timer) window.clearTimeout(this._timer); this._timer=window.setTimeout(function(){ if (id.value=="") return; var z=self.findCell(id.value,column,true,strict); if (z.length){ if (self._h2) self.openItem(z[0][0]); self.selectCell(self.getRowIndex(z[0][0]),(column||0)) } },500); }; } if (id.parentNode) id.parentNode.className+=" filter"; } dhtmlXGridObject.prototype._loadSelectOptins=function(t,c){ var l=this.collectValues(c); var v=t.value; t.innerHTML=""; t.options[0]=new Option("",""); var f=this._filter_tr?this._filter_tr[c]:null; for (var i=0; i<l.length; i++) t.options[t.options.length]=new Option(f?f(l[i]):l[i],l[i]); t.value=v; } dhtmlXGridObject.prototype.setSelectFilterLabel=function(ind,fun){ if (!this._filter_tr) this._filter_tr=[]; this._filter_tr[ind]=fun; } dhtmlXGridObject.prototype._loadComboOptins=function(t,c){ if (!t.combo) return; // prevent calls from refreshFilters var l=this.collectValues(c); t.combo.clearAll(); var opts = [["",""]]; for (var i=0; i<l.length; i++) opts.push([l[i],l[i]]); t.combo.addOption(opts); } /** * @desc: refresh filtering ( can be used if data in grid changed and filters need to be updated ) * @type: public * @edition: Professional * @topic: 0 */ dhtmlXGridObject.prototype.refreshFilters=function(){ if(!this.filters) return; for (var i=0; i<this.filters.length; i++){ switch(this.filters[i][0].tagName.toLowerCase()){ case "input": break; case "select": this._loadSelectOptins.apply(this,this.filters[i]); break; case "div": this._loadComboOptins.apply(this,this.filters[i]); break; } } } dhtmlXGridObject.prototype._filters_ready=function(fl,code){ this.attachEvent("onXLE",this.refreshFilters); this.attachEvent("onRowCreated",function(id,r){ if (this._f_rowsBuffer) for (var i=0; i<this._f_rowsBuffer.length; i++) if (this._f_rowsBuffer[i].idd == id) return this._f_rowsBuffer[i]=r; }) this.attachEvent("onClearAll",function(){ this._f_rowsBuffer=null; if (!this.hdr.rows.length) this.filters=[]; }); /* if (window.dhtmlXCombo) this.attachEvent("onScroll",dhtmlXCombo.prototype.closeAll); */ this.attachEvent("onSetSizes", this._filters_resize_combo); this.attachEvent("onResize", this._filters_resize_combo); this._filters_ready=function(){}; } dhtmlXGridObject.prototype._filters_resize_combo=function(){ if (!this.filters) return; for (var q=0; q<this.filters.length; q++) { if (this.filters[q][0].combo != null) { this.filters[q][0].combo.setSize(Math.round(this.filters[q][0].offsetWidth*90/100)); } } return true; } dhtmlXGridObject.prototype._in_header_text_filter=function(t,i){ t.innerHTML="<input type='text'>"; t.onclick=t.onmousedown = function(e){ (e||event).cancelBubble=true; return true; } t.onselectstart=function(){ return (event.cancelBubble=true); } this.makeFilter(t.firstChild,i); } dhtmlXGridObject.prototype._in_header_text_filter_inc=function(t,i){ t.innerHTML="<input type='text'>"; t.onclick=t.onmousedown = function(e){ (e||event).cancelBubble=true; return true; } t.onselectstart=function(){ return (event.cancelBubble=true); } this.makeFilter(t.firstChild,i); t.firstChild._filter=function(){ if (t.firstChild.value=="") return ""; return function(val){ return (val.toString().toLowerCase().indexOf(t.firstChild.value.toLowerCase())==0); } } this._filters_ready(); } dhtmlXGridObject.prototype._in_header_select_filter=function(t,i){ t.innerHTML="<select></select>"; t.onclick=function(e){ (e||event).cancelBubble=true; return false; } this.makeFilter(t.firstChild,i); } dhtmlXGridObject.prototype._in_header_select_filter_strict=function(t,i){ t.innerHTML="<select style='width:90%; font-size:8pt; font-family:Tahoma;'></select>"; t.onclick=function(e){ (e||event).cancelBubble=true; return false; } this.makeFilter(t.firstChild,i); var combos = this.combos; t.firstChild._filter=function(){ var value = t.firstChild.value; if (!value) return ""; if (combos[i]) value = combos[i].keys[combos[i].values._dhx_find(value)]; value = value.toLowerCase(); return function(val){ return (val.toString().toLowerCase()==value); }; }; this._filters_ready(); } dhtmlXGridObject.prototype._in_header_combo_filter=function(t,i){ t.innerHTML="<div style='width:100%; padding-left:2px; overflow:hidden; ' class='combo'></div>"; t.onselectstart=function(){ return (event.cancelBubble=true); } t.onclick=t.onmousedown=function(e){ (e||event).cancelBubble=true; return true; } this.makeFilter(t.firstChild,i); } dhtmlXGridObject.prototype._search_common=function(t, i){ t.innerHTML="<input type='text' style='width:90%; '>"; t.onclick= t.onmousedown = function(e){ (e||event).cancelBubble=true; return true; } t.onselectstart=function(){ return (event.cancelBubble=true); } } dhtmlXGridObject.prototype._in_header_text_search=function(t,i, strict){ this._search_common(t, i); this.makeSearch(t.firstChild,i); } dhtmlXGridObject.prototype._in_header_text_search_strict=function(t,i){ this._search_common(t, i); this.makeSearch(t.firstChild,i, true); } dhtmlXGridObject.prototype._in_header_numeric_filter=function(t,i){ this._in_header_text_filter.call(this,t,i); t.firstChild._filter=function(){ var v=this.value; var r; var op="=="; var num=parseFloat(v.replace("=","")); var num2=null; if (v){ if (v.indexOf("..")!=-1){ v=v.split(".."); num=parseFloat(v[0]); num2=parseFloat(v[1]); return function(v){ if (v>=num && v<=num2) return true; return false; } } r=v.match(/>=|<=|>|</) if (r) { op=r[0]; num=parseFloat(v.replace(op,"")); } return Function("v"," if (v "+op+" "+num+" ) return true; return false;"); } return ""; }; } dhtmlXGridObject.prototype._in_header_master_checkbox=function(t,i,c){ t.innerHTML=c[0]+"<input type='checkbox' />"+c[1]; var self=this; t.getElementsByTagName("input")[0].onclick=function(e){ self._build_m_order(); var j=self._m_order?self._m_order[i]:i; var val=this.checked?1:0; self.forEachRowA(function(id){ var c=this.cells(id,j); if (c.isCheckbox()) { c.setValue(val); c.cell.wasChanged = true; } this.callEvent("onEditCell",[1,id,j,val]); this.callEvent("onCheckbox", [id, j, val]); }); (e||event).cancelBubble=true; } } dhtmlXGridObject.prototype._in_header_stat_total=function(t,i,c){ var calck=function(){ var summ=0; this._build_m_order(); var ii = this._m_order?this._m_order[i]:i; for (var j=0; j<this.rowsBuffer.length; j++){ var v=parseFloat(this._get_cell_value(this.rowsBuffer[j],ii)); summ+=isNaN(v)?0:v; } return this._maskArr[ii]?this._aplNF(summ,ii):(Math.round(summ*100)/100); } this._stat_in_header(t,calck,i,c,c); } dhtmlXGridObject.prototype._in_header_stat_multi_total=function(t,i,c){ var cols=c[1].split(":"); c[1]=""; for(var k = 0; k < cols.length;k++){ cols[k]=parseInt(cols[k]); } var calck=function(){ var summ=0; for (var j=0; j<this.rowsBuffer.length; j++){ var v = 1; for(var k = 0; k < cols.length;k++){ v *= parseFloat(this._get_cell_value(this.rowsBuffer[j],cols[k])) } summ+=isNaN(v)?0:v; } return this._maskArr[i]?this._aplNF(summ,i):(Math.round(summ*100)/100); } var track=[]; for(var ind = 0; ind < cols.length;ind++){ track[cols[ind]]=true; } this._stat_in_header(t,calck,track,c,c); } dhtmlXGridObject.prototype._in_header_stat_max=function(t,i,c){ var calck=function(){ this._build_m_order(); var ii = this._m_order?this._m_order[i]:i; var summ=-999999999; if (this.getRowsNum()==0) return "&nbsp;"; for (var j=0; j<this.rowsBuffer.length; j++) summ=Math.max(summ,parseFloat(this._get_cell_value(this.rowsBuffer[j],ii))); return this._maskArr[i]?this._aplNF(summ,i):summ; } this._stat_in_header(t,calck,i,c); } dhtmlXGridObject.prototype._in_header_stat_min=function(t,i,c){ var calck=function(){ this._build_m_order(); var ii = this._m_order?this._m_order[i]:i; var summ=999999999; if (this.getRowsNum()==0) return "&nbsp;"; for (var j=0; j<this.rowsBuffer.length; j++) summ=Math.min(summ,parseFloat(this._get_cell_value(this.rowsBuffer[j],ii))); return this._maskArr[i]?this._aplNF(summ,i):summ; } this._stat_in_header(t,calck,i,c); } dhtmlXGridObject.prototype._in_header_stat_average=function(t,i,c){ var calck=function(){ this._build_m_order(); var ii = this._m_order?this._m_order[i]:i; var summ=0; var count=0; if (this.getRowsNum()==0) return "&nbsp;"; for (var j=0; j<this.rowsBuffer.length; j++){ var v=parseFloat(this._get_cell_value(this.rowsBuffer[j],ii)); if (!isNaN(v)){ summ+=v; count++; } } return this._maskArr[i]?this._aplNF(summ/count,i):(Math.round(summ/count*100)/100); } this._stat_in_header(t,calck,i,c); } dhtmlXGridObject.prototype._in_header_stat_count=function(t,i,c){ var calck=function(){ return this.getRowsNum(); } this._stat_in_header(t,calck,i,c); } dhtmlXGridObject.prototype._stat_in_header=function(t,calck,i,c){ var that=this; var f=function(){ this.dma(true) t.innerHTML=(c[0]?c[0]:"")+calck.call(this)+(c[1]?c[1]:""); this.dma(false) this.callEvent("onStatReady",[]) } if (!this._stat_events) { this._stat_events=[]; this.attachEvent("onClearAll",function(){ if (!this.hdr.rows[1]){ for (var i=0; i<this._stat_events.length; i++) for (var j=0; j < 4; j++) this.detachEvent(this._stat_events[i][j]); this._stat_events=[]; } }) } this._stat_events.push([ this.attachEvent("onGridReconstructed",f), this.attachEvent("onXLE",f), this.attachEvent("onFilterEnd",f), this.attachEvent("onEditCell",function(stage,id,ind){ if (stage==2 && ( ind==i || ( i && i[ind]) ) ) f.call(this); return true; })]); t.innerHTML=""; } //(c)dhtmlx ltd. www.dhtmlx.com
React.createElement(Component, React.__spread({}, x, { y: 2, z: true }));
// when the extension is first installed chrome.runtime.onInstalled.addListener(function(details) { chrome.storage.sync.get("muted_list", function (data) { if (!data["muted_list"]) { chrome.storage.sync.set({"muted_list": null}); } }); chrome.storage.sync.get("transparency", function (data) { if (!data["muted_list"]) { chrome.storage.sync.set({ "transparency": "medium"}); } }); }); // listen for any changes to the URL of any tab. chrome.tabs.onUpdated.addListener(function(id, info, tab){ if (tab.url.toLowerCase().indexOf("facebook.com") > -1){ chrome.pageAction.show(tab.id); } });
const { UIPlugin } = require('@uppy/core') const { h } = require('preact') const { SearchProvider, Provider } = require('@uppy/companion-client') const { SearchProviderViews } = require('@uppy/provider-views') /** * Unsplash * */ module.exports = class Unsplash extends UIPlugin { static VERSION = require('../package.json').version constructor (uppy, opts) { super(uppy, opts) this.id = this.opts.id || 'Unsplash' this.title = this.opts.title || 'Unsplash' Provider.initPlugin(this, opts, {}) this.icon = () => ( <svg viewBox="0 0 32 32" height="32" width="32" aria-hidden="true"> <path d="M46.575 10.883v-9h12v9zm12 5h10v18h-32v-18h10v9h12z" fill="#fff" /> <rect className="uppy-ProviderIconBg" width="32" height="32" rx="16" /> <path d="M13 12.5V8h6v4.5zm6 2.5h5v9H8v-9h5v4.5h6z" fill="#fff" /> </svg> ) if (!this.opts.companionUrl) { throw new Error('Companion hostname is required, please consult https://uppy.io/docs/companion') } this.hostname = this.opts.companionUrl this.provider = new SearchProvider(uppy, { companionUrl: this.opts.companionUrl, companionHeaders: this.opts.companionHeaders, companionCookiesRule: this.opts.companionCookiesRule, provider: 'unsplash', pluginId: this.id, }) } install () { this.view = new SearchProviderViews(this, { provider: this.provider, viewType: 'unsplash', }) const { target } = this.opts if (target) { this.mount(target, this) } } onFirstRender () { // do nothing } render (state) { return this.view.render(state) } uninstall () { this.unmount() } }
const SUPPORTED_BROWSERS = [ // based on free plan with BrowserStack 'chrome', 'firefox', 'ie' ] exports.config = { framework: 'mocha', seleniumAddress: 'http://hub-cloud.browserstack.com/wd/hub', specs: [ 'test-all.js' ], commonCapabilities: { 'browserstack.user': process.env.BROWSERSTACK_USERNAME, 'browserstack.key': process.env.BROWSERSTACK_ACCESS_KEY, build: 'protractor-browserstack', 'browserstack.debug': true, 'browserstack.local': true, 'browserstack.localIdentifier': process.env.BROWSERSTACK_LOCAL_IDENTIFIER }, multiCapabilities: SUPPORTED_BROWSERS.map(browserName => ({ browserName })) } exports.config.multiCapabilities.forEach(caps => { Object.keys(exports.config.commonCapabilities).forEach(key => { caps[key] = caps[key] || exports.config.commonCapabilities[key] }) })
import Rollbar from 'rollbar'; import omit from 'lodash/omit'; import isFunction from 'lodash/isFunction'; import { bunyanLevelToRollbarLevelName } from '../common/rollbar'; /** * @description Custom bunyan stream that transports to Rollbar from a node process. * See https://rollbar.com/docs/notifier/node_rollbar/ for integration details * * @param {Object} token, codeVersion, and environment */ export default function ServerRollbarLogger({ token, codeVersion, environment }) { // https://rollbar.com/docs/notifier/rollbar.js/#quick-start-server this._rollbar = new Rollbar({ accessToken: token, captureUncaught: true, captureUnhandledRejections: true, code_version: codeVersion, environment, }); } /** * Transport to Rollbar * @description handles `err` and `req` properties, attaches any custom data, * and calls the appropriate Rollbar method. * * @param {Object} data * @returns {undefined} */ ServerRollbarLogger.prototype.write = function (data = {}) { const rollbarLevelName = bunyanLevelToRollbarLevelName(data.level); const scopeData = omit(data, ['req', 'err', 'level']); const payload = Object.assign({ level: rollbarLevelName }, scopeData); // https://rollbar.com/docs/notifier/rollbar.js/#rollbarlog-1 const logFn = this._rollbar[rollbarLevelName]; if (isFunction(logFn)) { logFn.call(this._rollbar, data.msg, data.err, data.req, payload); } else { this._rollbar.error(data.msg, data.err, data.req, payload); } };
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); else if(typeof exports === 'object') exports["kompo"] = factory(); else root["kompo"] = factory(); })(this, function() { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // identity function for calling harmony imports with the correct context /******/ __webpack_require__.i = function(value) { return value; }; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 60); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; exports.default = construct; exports.constructClass = constructClass; exports.render = render; exports.update = update; exports.kompo = kompo; exports.setState = setState; exports.getState = getState; exports.mount = mount; exports.unmount = unmount; exports.unmountAll = unmountAll; exports.mountIndex = mountIndex; exports.react = react; exports.slot = slot; exports.hasSlot = hasSlot; exports.getRouter = getRouter; exports.compose = compose; exports.getProps = getProps; exports.getMethods = getMethods; exports.getMounts = getMounts; exports.mountable = mountable; exports.debug = debug; exports.debugLifeCycle = debugLifeCycle; exports.getSelector = getSelector; var _store = __webpack_require__(2); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /** * When KOMPO_DEBUG is defined it returns it, otherwise is returns false * @returns boolean */ function isKompoDebug() { if (typeof KOMPO_DEBUG != 'undefined') { return KOMPO_DEBUG; } return false; } /** * Adds construct function to Element prototype */ if ((typeof Element === 'undefined' ? 'undefined' : _typeof(Element)) === 'object') { Object.defineProperty(Element.prototype, 'construct', { writable: true, value: function value() { throw new Error('Must override the construct method'); } }); } /** * Creates a compnent from an Element * * @param tag * @param constructFn * @param defaultProps * @returns {function()} */ function construct(tag, constructFn) { var defaultProps = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2]; return function () { var props = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var c = kompo(document.createElement(tag)); c.kompo.props = _extends({}, defaultProps, props); c.construct = constructFn; return c; }; } function constructClass(tag, constructClass) { var defaultProps = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2]; var methods = getMethods(constructClass.prototype); return function () { var props = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var c = kompo(document.createElement(tag)); c.kompo.props = _extends({}, defaultProps, props); _extends(c, methods); return c; }; } /** * Renders given component * * @param Element */ function render(Element) { var kompo = Element.kompo; if (!kompo.initial) return; if (isKompoDebug() && kompo.debug) { console.groupCollapsed('RENDER: '); console.log(Element); console.log(kompo); console.groupCollapsed('CONSTRUCT: '); } // Construct then ... Element.construct(kompo.props); kompo.initial = false; if (isKompoDebug() && kompo.debug) { console.groupEnd(); } // ... react var statefulls = kompo.statefulls, selector = kompo.selector, state = selector ? selector(Element.__kompo__.state) : Element.__kompo__.state; if (statefulls.length > 0 && state) { if (isKompoDebug() && kompo.debug) { console.log('HAS STATE: ', state); console.groupCollapsed('REACTS: '); } for (var i = 0, l = statefulls.length; i < l; ++i) { statefulls[i](state, Element); } if (isKompoDebug() && kompo.debug) { console.groupEnd(); } } if (isKompoDebug() && kompo.debug) { console.groupEnd(); } } function update(Element, state) { var kompo = Element.kompo; if (isKompoDebug() && kompo.debug) { console.groupCollapsed('UPDATE: '); console.log(Element); console.log(kompo); } updateStatefulls(Element, kompo, state); var mounts = kompo.mounts; if (mounts.length > 0) { if (isKompoDebug() && kompo.debug) { console.groupCollapsed('MOUNTS: '); } for (var i = 0, l = mounts.length; i < l; ++i) { update(mounts[i], state); } if (isKompoDebug() && kompo.debug) { console.groupEnd(); } } if (isKompoDebug() && kompo.debug) { console.groupEnd(); } } function updateStatefulls(Element, kompo, state) { var statefulls = kompo.statefulls; // Only run if a component has statefulls if (statefulls.length == 0) return; var selector = kompo.selector, selectedState = selector ? selector(Element.__kompo__.state) : Element.__kompo__.state; if (selectedState && (state === selectedState || inProperties(selectedState, state))) { if (isKompoDebug() && kompo.debug) { console.log('HAS DIRTY STATE: ', selectedState); console.groupCollapsed('REACTS: '); } for (var i = 0, l = statefulls.length; i < l; ++i) { var st = statefulls[i]; if ((0, _store.shouldIgnore)(state, st)) { (0, _store.resetIgnore)(state); continue; } st(selectedState, Element); } if (isKompoDebug() && kompo.debug) { console.groupEnd(); } } } function inProperties(selectedState, state) { if (selectedState && !(0, _store.isProxy)(selectedState)) { var keys = Object.keys(selectedState); for (var i = 0, l = keys.length; i < l; ++i) { if (state === selectedState[keys[i]]) { return true; } } } return false; } function kompo(Element) { Element.kompo = { initial: true, props: {}, defaultProps: {}, mounts: [], statefulls: [], slots: {}, routed: undefined, selector: undefined, // state: undefined, // TODO Unavailable now but could perhaps be used as caching mechanism (also see setState()) unmount: undefined, debug: false }; return Element; } function setState(Element, selector) { var kompo = Element.kompo; // TODO Unavailable now but could perhaps be used as caching mechanism // if(apply) kompo.state = selector(Element.__kompo__.state); kompo.selector = selector; return Element; } function getState(Element) { var selector = Element.kompo.selector; return selector ? selector(Element.__kompo__.state) : Element.__kompo__.state; } function mount(parent, child, selector) { if (Array.isArray(child)) { _mountAll(parent, child, selector); } else { _mount(parent, child, selector); } } function _mount(parent, child, selector) { if (selector) { setState(child, selector); } else if (child instanceof Mountable) { setState(child.Element, child.selector); child = child.Element; } render(child); // Protection if same element is appended multiple times var mounts = parent.kompo.mounts; if (mounts.indexOf(child) === -1) { child.kompo.unmount = function () { mounts.splice(mounts.indexOf(child), 1); }; mounts.push(child); } } function _mountAll(parent, children, selector) { // Mount all children ... for (var i = 0, l = children.length; i < l; ++i) { _mount(parent, children[i], selector ? selector : undefined); } } function unmount(Element) { Element.kompo.unmount(); } function unmountAll(Element) { Element.kompo.mounts = []; } function mountIndex(parent, child) { return parent.kompo.mounts.indexOf(child); } function react(Element, statefull) { Element.kompo.statefulls.push(statefull); } /** * Mimics the slot functionality of * Web Components * * Slots are named, their name & location is * predefined in the component. * * @param Element * @param name * @param cb */ function slot(Element, name, cb) { if (arguments.length === 2) { Element.kompo.slots[name](Element); } else { Element.kompo.slots[name] = cb; } } /** * Checks whether a slot with the given name exists * * @param Element * @param name * @returns {boolean} */ function hasSlot(Element, name) { return Element.kompo.slots[name] ? true : false; } /** * Gets the router from an Element. The router is * add globally to the Element prototype * * @param Element * @returns {router} */ function getRouter(Element) { return Element.__kompo__.router; } /** * Adds properties to an existing component, * making it possible to compose a component with * different behavior. * * @param constructComponent * @param composeProps * @returns {function()} */ function compose(constructComponent, composeProps) { return function () { var props = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; return constructComponent(_extends(composeProps, props)); }; } function getProps(Element) { return Element.kompo.props; } function getMethods(clss) { var props = [], methods = {}; var obj = clss; do { var ps = Object.getOwnPropertyNames(obj); var fps = []; for (var i = 0, l = ps.length; i < l; ++i) { var p = ps[i]; if (typeof obj[p] === 'function' //only the methods && p != 'constructor' //not the constructor && (i == 0 || p !== ps[i - 1]) //not overriding in this prototype && props.indexOf(p) === -1 //not overridden in a child ) { fps.push(p); methods[p] = clss[p]; } } props.push.apply(props, fps); } while ((obj = Object.getPrototypeOf(obj)) && //walk-up the prototype chain Object.getPrototypeOf(obj) //not the the Object prototype methods (hasOwnProperty, etc...) ); return methods; } function getMounts(Element) { return Element.kompo.mounts; } var Mountable = function Mountable(Element, selector) { _classCallCheck(this, Mountable); this.Element = Element; this.selector = selector; }; function mountable(Element, selector) { return new Mountable(Element, selector); } function debug(Element, level) { if (!Element instanceof HTMLElement) { throw new Error('Not an instance of Element'); } if (!Element.hasOwnProperty('kompo')) { throw new Error('Is not a KompoElement'); } var kompo = Element.kompo, mounts = kompo.mounts; console.log(Element, kompo); if (Number.isInteger(level) && level > 0 && mounts.length > 0) { console.groupCollapsed('MOUNTS: '); var nl = --level; for (var i = 0, l = mounts.length; i < l; ++i) { debug(mounts[i], nl); console.log('__END_OF_MOUNT__'); } console.groupEnd(); } return Element; } function debugLifeCycle(Element) { if (!Element instanceof HTMLElement) { throw new Error('Not an instance of Element'); } if (!Element.hasOwnProperty('kompo')) { throw new Error('Is not a KompoElement'); } // Set to true so render & update functions log the components life cycle Element.kompo.debug = true; return Element; } function getSelector(Element) { return Element.kompo.selector; } /***/ }), /* 1 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.util = exports.state = exports.router = undefined; var _component = __webpack_require__(0); var _component2 = _interopRequireDefault(_component); var _link = __webpack_require__(19); var _link2 = _interopRequireDefault(_link); var _router = __webpack_require__(20); var _router2 = _interopRequireDefault(_router); var _app = __webpack_require__(21); var _app2 = _interopRequireDefault(_app); var _store = __webpack_require__(2); var _store2 = _interopRequireDefault(_store); var _hasProxy = __webpack_require__(23); var _hasProxy2 = _interopRequireDefault(_hasProxy); var _deproxy = __webpack_require__(22); var _deproxy2 = _interopRequireDefault(_deproxy); var _isObject = __webpack_require__(3); var _isObject2 = _interopRequireDefault(_isObject); var _merge = __webpack_require__(24); var _merge2 = _interopRequireDefault(_merge); var _isFunction = __webpack_require__(8); var _isFunction2 = _interopRequireDefault(_isFunction); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var router = { construct: _router2.default, route: _router.route, indexRoute: _router.indexRoute, swap: _router.swap, link: _link2.default }; var state = { app: _app2.default, observe: _store2.default, isProxy: _store.isProxy, ignore: _store.ignore, shouldIgnore: _store.shouldIgnore, resetIgnore: _store.resetIgnore, dispatch: _store.dispatch, ignoreUpdate: _store.ignoreUpdate, resetIgnoreUpdate: _store.resetIgnoreUpdate, triggerUpdate: _store.triggerUpdate }; var util = { hasProxy: _hasProxy2.default, deproxy: _deproxy2.default, isObject: _isObject2.default, merge: _merge2.default, isFunction: _isFunction2.default }; exports.default = { construct: _component2.default, render: _component.render, update: _component.update, kompo: _component.kompo, setState: _component.setState, mount: _component.mount, getMounts: _component.getMounts, mountable: _component.mountable, react: _component.react, slot: _component.slot, getRouter: _component.getRouter, unmount: _component.unmount, unmountAll: _component.unmountAll, mountIndex: _component.mountIndex, getState: _component.getState, compose: _component.compose, getProps: _component.getProps, constructClass: _component.constructClass, debug: _component.debug, debugLifeCycle: _component.debugLifeCycle, getSelector: _component.getSelector }; exports.router = router; exports.state = state; exports.util = util; /***/ }), /* 2 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = observe; exports.isProxy = isProxy; exports.ignore = ignore; exports.shouldIgnore = shouldIgnore; exports.resetIgnore = resetIgnore; exports.dispatch = dispatch; exports.ignoreUpdate = ignoreUpdate; exports.resetIgnoreUpdate = resetIgnoreUpdate; exports.triggerUpdate = triggerUpdate; var _component = __webpack_require__(0); var _isObject = __webpack_require__(3); var _isObject2 = _interopRequireDefault(_isObject); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var OBSERVED_KEY = '__kompo_observed__', IGNORE_STATEFULL_KEY = '__kompo_ignore_statefulls__', IGNORE_KEY = '__kompo_ignore__', TRIGGER_UPDATE_KEY = '__kompo_trigger_update__', // IMPORTANT Should not be in reserved keys reservedKeys = ['length', IGNORE_STATEFULL_KEY, IGNORE_KEY]; function observe(obj, root) { var isObj = (0, _isObject2.default)(obj), isArray = Array.isArray(obj); if (!isObj && !isArray || obj.hasOwnProperty(OBSERVED_KEY)) return obj; Object.defineProperty(obj, OBSERVED_KEY, { value: true }); Object.defineProperty(obj, IGNORE_STATEFULL_KEY, { value: [], writable: true }); Object.defineProperty(obj, IGNORE_KEY, { value: false, writable: true }); Object.defineProperty(obj, TRIGGER_UPDATE_KEY, { value: true, writable: true }); var keys = Object.keys(obj); for (var i = 0, l = keys.length; i < l; ++i) { var key = keys[i]; if (reservedKeys.indexOf(key) === -1) { obj[key] = observe(obj[key], root); } } obj = new Proxy(obj, { deleteProperty: function deleteProperty(target, key) { delete target[key]; if (!obj[IGNORE_KEY]) requestAnimationFrame(function () { return (0, _component.update)(root, obj); }); return true; }, set: function set(target, key, val) { if (reservedKeys.indexOf(key) > -1 || obj[IGNORE_KEY]) { target[key] = val; } else { target[key] = observe(val, root); requestAnimationFrame(function () { return (0, _component.update)(root, obj); }); } return true; } }); return obj; } function isProxy(obj) { return obj.hasOwnProperty(OBSERVED_KEY); } function ignore(obj) { for (var _len = arguments.length, statefulls = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { statefulls[_key - 1] = arguments[_key]; } obj[IGNORE_STATEFULL_KEY] = statefulls; } function shouldIgnore(obj, statefull) { return obj[IGNORE_STATEFULL_KEY].indexOf(statefull) !== -1; } function resetIgnore(obj) { obj[IGNORE_STATEFULL_KEY] = []; } function dispatch(Element, cb, silent) { if (!cb) return; var state = (0, _component.getState)(Element); ignoreUpdate(state); cb(state); resetIgnoreUpdate(state); if (!silent) triggerUpdate(state); } function ignoreUpdate(obj) { obj[IGNORE_KEY] = true; } function resetIgnoreUpdate(obj) { obj[IGNORE_KEY] = false; } function triggerUpdate(obj) { obj[TRIGGER_UPDATE_KEY] = true; } /***/ }), /* 3 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; exports.default = isObject; /** * Checks if `value` is the language type of `Object`. * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * **Note:** See the [ES5 spec](https://es5.github.io/#x8) for more details. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(1); * // => false */ function isObject(value) { // Avoid a V8 JIT bug in Chrome 19-20. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details. var type = typeof value === 'undefined' ? 'undefined' : _typeof(value); return type == 'function' || value && type == 'object' || false; } /***/ }), /* 4 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.addClasses = exports.throttle = exports.replace = exports.remove = exports.merge = exports.matches = exports.isObject = exports.isFunction = exports.empty = exports.delegate = exports.debounce = exports.addAttributes = exports.createText = exports.createFragment = exports.create = exports.capitalize = undefined; var _capitalize = __webpack_require__(10); var _capitalize2 = _interopRequireDefault(_capitalize); var _create = __webpack_require__(5); var _create2 = _interopRequireDefault(_create); var _debounce = __webpack_require__(11); var _debounce2 = _interopRequireDefault(_debounce); var _delegate = __webpack_require__(12); var _delegate2 = _interopRequireDefault(_delegate); var _empty = __webpack_require__(13); var _empty2 = _interopRequireDefault(_empty); var _isFunction = __webpack_require__(14); var _isFunction2 = _interopRequireDefault(_isFunction); var _isObject = __webpack_require__(6); var _isObject2 = _interopRequireDefault(_isObject); var _matches = __webpack_require__(7); var _matches2 = _interopRequireDefault(_matches); var _merge = __webpack_require__(15); var _merge2 = _interopRequireDefault(_merge); var _remove = __webpack_require__(16); var _remove2 = _interopRequireDefault(_remove); var _replace = __webpack_require__(17); var _replace2 = _interopRequireDefault(_replace); var _throttle = __webpack_require__(18); var _throttle2 = _interopRequireDefault(_throttle); var _addClasses = __webpack_require__(9); var _addClasses2 = _interopRequireDefault(_addClasses); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.capitalize = _capitalize2.default; exports.create = _create2.default; exports.createFragment = _create.createFragment; exports.createText = _create.createText; exports.addAttributes = _create.addAttributes; exports.debounce = _debounce2.default; exports.delegate = _delegate2.default; exports.empty = _empty2.default; exports.isFunction = _isFunction2.default; exports.isObject = _isObject2.default; exports.matches = _matches2.default; exports.merge = _merge2.default; exports.remove = _remove2.default; exports.replace = _replace2.default; exports.throttle = _throttle2.default; exports.addClasses = _addClasses2.default; /***/ }), /* 5 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = create; exports.addAttributes = addAttributes; exports.createFragment = createFragment; exports.createText = createText; var doc = document; /** * Creates an Element, when no tagName * is given it create an empty div to serve * as root. * * @param {string|undefined} tagName * @returns {Element} */ function create(tagName, attributes) { var Element = void 0; if (!tagName) { Element = doc.createElement('div'); } else { Element = doc.createElement(tagName); } if (attributes) { addAttributes(Element, attributes); } return Element; } /** * Adds attributes to an Element * through iterating through an object * * @param {Element} Element * @param {Object} obj * @returns {Element} */ function addAttributes(Element, obj) { var keys = Object.keys(obj); for (var i = 0, l = keys.length; i < l; i++) { var key = keys[i], value = obj[key]; Element.setAttribute(key, value); } return Element; } /** * Syntactic sugar for creating a DocumentFragment * * @returns {DocumentFragment} */ function createFragment() { return doc.createDocumentFragment(); } /** * Syntactic sugar for creating a TextNode * * @param {string} str * @returns {Text} */ function createText(str) { return doc.createTextNode(str); } /***/ }), /* 6 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; }; exports.default = isObject; /** * Checks if `value` is the language type of `Object`. * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * **Note:** See the [ES5 spec](https://es5.github.io/#x8) for more details. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(1); * // => false */ function isObject(value) { // Avoid a V8 JIT bug in Chrome 19-20. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details. var type = typeof value === 'undefined' ? 'undefined' : _typeof(value); return type == 'function' || value && type == 'object' || false; } /***/ }), /* 7 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * Polyfills the matches function on Elements * * Used with event delegation in Components class */ exports.default = function () { if (!Element.prototype.matches) { var ep = Element.prototype; if (ep.webkitMatchesSelector) // Chrome <34, SF<7.1, iOS<8 ep.matches = ep.webkitMatchesSelector; if (ep.msMatchesSelector) // IE9/10/11 & Edge ep.matches = ep.msMatchesSelector; if (ep.mozMatchesSelector) // FF<34 ep.matches = ep.mozMatchesSelector; } }(); /***/ }), /* 8 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = isFunction; /** * Checks if given variable is a function * * @param {*} functionToCheck * @returns {boolean} */ function isFunction(functionToCheck) { var getType = {}; return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]'; } /***/ }), /* 9 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = addClasses; function addClasses(Element, classes) { for (var i = 0, l = classes.length; i < l; ++i) { Element.classList.add(classes[i]); } } /***/ }), /* 10 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = capitalize; /** * Capitalizes string * * @param {string} str * @returns {string} */ function capitalize(str) { if (typeof str === "string") { return str.charAt(0).toUpperCase() + str.slice(1); } } /***/ }), /* 11 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = debounce; /** * Debounces a function call * * @param {Function} fn - function to debounce * @param {Number} delay - timeout for debouncing * @param {Object} scope * @returns {Function} */ function debounce(fn, delay, scope) { var timer = null; return function () { var context = scope || this, args = arguments; clearTimeout(timer); timer = setTimeout(function () { fn.apply(context, args); }, delay); }; } /***/ }), /* 12 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = delegate; __webpack_require__(7); // Self-executing function delegate(Element, selector, type, listener) { Element.addEventListener(type, function (e) { for (var target = e.target; target && target != this; target = target.parentNode) { // loop parent nodes from the target to the delegation node if (target.matches(selector)) { listener.bind(target)(e); break; } } }, false); } /***/ }), /* 13 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = empty; function empty(Element) { while (Element.lastChild) { Element.removeChild(Element.lastChild); } return Element; } /***/ }), /* 14 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = isFunction; /** * Checks if given variable is a function * * @param {*} functionToCheck * @returns {boolean} */ function isFunction(functionToCheck) { var getType = {}; return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]'; } /***/ }), /* 15 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = merge; /** * Merges given objects * * @param {...Object} objs - Any given amount of objects * @returns {Object} */ function merge() { var object = Array.prototype.shift.call(arguments); for (var i = 0; i < arguments.length; i++) { var obj = arguments[i]; for (var j in obj) { object[j] = obj[j]; } } return object; } /***/ }), /* 16 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = function (Element) { var parent = Element.parentNode; if (parent) { parent.removeChild(Element); } }; /***/ }), /* 17 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = replace; var _create = __webpack_require__(5); var _create2 = _interopRequireDefault(_create); var _isObject = __webpack_require__(6); var _isObject2 = _interopRequireDefault(_isObject); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Replaces an Node for another one * * @param {Node} parent - parent element to replace child on * @param {*} child - new child to replace for old child * @param {(boolean|Object)} replaceLastChild - replace first or last child | represents an attribute object * @param {boolean} rLC * @returns {Element} child - child element */ function replace(parent, child) { var replaceLastChild = arguments.length <= 2 || arguments[2] === undefined ? false : arguments[2]; var rLC = arguments.length <= 3 || arguments[3] === undefined ? false : arguments[3]; var arg2isObject = (0, _isObject2.default)(arguments[2]); var replacedChild = void 0; if (arg2isObject) { replacedChild = rLC ? parent.lastChild : parent.firstChild; } else { replacedChild = replaceLastChild ? parent.lastChild : parent.firstChild; } if (typeof child === 'string') { child = (0, _create2.default)(child); } if (arg2isObject) { (0, _create.addAttributes)(child, replaceLastChild); } if (replacedChild) { parent.replaceChild(child, replacedChild); } else { parent.appendChild(child); } return child; } /***/ }), /* 18 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = throttle; /** * Throttle function * * @param {Function} fn - function to throttle * @param {Number} threshold - timeout for throttling * @param {Object} scope * @returns {Function} */ function throttle(fn, threshold, scope) { threshold || (threshold = 250); var last = void 0, deferTimer = void 0; return function () { var context = scope || this, now = +new Date(), args = arguments; if (last && now < last + threshold) { // hold on to it clearTimeout(deferTimer); deferTimer = setTimeout(function () { last = now; fn.apply(context, args); }, threshold); } else { last = now; return fn.apply(context, args); } }; } /***/ }), /* 19 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _component = __webpack_require__(0); var _component2 = _interopRequireDefault(_component); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = (0, _component2.default)('a', function (_ref) { var _this = this; var url = _ref.url; var child = _ref.child; var classNames = _ref.classNames; var data = _ref.data; var title = _ref.title; var defaultEvent = _ref.defaultEvent; var activeClass = _ref.activeClass; var onClick = _ref.onClick; // First add classes for (var i = 0, l = classNames.length; i < l; ++i) { this.classList.add(classNames[i]); } var router = (0, _component.getRouter)(this); (0, _component.react)(this, function () { if (router.isUrl(url)) { _this.classList.add(activeClass); } else { _this.classList.remove(activeClass); } }); this.setAttribute('href', url); if (typeof child === 'string') { this.textContent = child; } else if (child.hasOwnProperty('kompo')) { (0, _component.mount)(this, child); this.appendChild(child); } else if (child instanceof Node) { this.appendChild(child); } else if ((0, _component.hasSlot)(this, 'child')) { (0, _component.slot)(this, 'child'); } else { throw new Error('Child should be a string, KompoElement, Node or a slot callback named "child"'); } this.addEventListener(defaultEvent, function (e) { e.preventDefault(); if (onClick) { onClick(e); } router.goTo(url, title, data); var state = (0, _component.getState)(_this); state.url = url; }); }, { url: '', child: '', classNames: [], data: undefined, // Data to push with pushState() title: '', defaultEvent: 'click', activeClass: 'active', onClick: undefined }); /***/ }), /* 20 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; exports.default = construct; exports.route = route; exports.indexRoute = indexRoute; exports.swap = swap; var _component = __webpack_require__(0); var _isFunction = __webpack_require__(8); var _isFunction2 = _interopRequireDefault(_isFunction); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function construct(props) { props = _extends({ base: '/', url: '/', notFoundCallback: function notFoundCallback(url) { throw new Error('No matching route found for url: ' + url + '. Provide a notFoundCallback callback option or correct the url or route.'); } }, props); var base = void 0, url = void 0, index = 0, params = []; var rawRoutes = {}, routes = {}; setBase(props.base); setUrl(props.url); parseRoute(props.routes); function setBase(b) { if (b[0] !== '/') { b = '/' + b; } if (b.slice(-1) === '/') { b = b.slice(0, -1); } base = b; } function setUrl(u) { url = u[0] === '/' ? u : '/' + u; } function isUrl(u) { u = u[0] === '/' ? u : '/' + u; return url === u; } function parseRoute(Route) { buildPath(Route); var rawKeys = Object.keys(rawRoutes); for (var i = 0, l = rawKeys.length; i < l; i++) { var k = rawKeys[i], // TODO: Could this be improved? nk = k.replace(/(:([\w-]+))/g, '([\\w-]+)').replace(/\//g, '\\/'); routes[nk] = rawRoutes[k]; } } function buildPath(route) { var ancestors = arguments.length <= 1 || arguments[1] === undefined ? [] : arguments[1]; var hierarchy = arguments.length <= 2 || arguments[2] === undefined ? [] : arguments[2]; var level = arguments.length <= 3 || arguments[3] === undefined ? 0 : arguments[3]; var children = route.children; var routeComponent = route.component; if (routeComponent instanceof Element) { routeComponent.kompo.level = level; } else if (routeComponent instanceof Promise || (0, _isFunction2.default)(routeComponent)) { // Set a level to the promise routeComponent.kompo = { level: level }; } if (!children) return; var basePath = route.path, isRoot = ancestors.length === 0; for (var i = 0, l = children.length; i < l; i++) { var childRoute = children[i], componentPath = !isRoot ? ancestors.concat(childRoute.component) : ancestors.concat(routeComponent, childRoute.component), childHierarchy = hierarchy.concat(i); var _path = void 0; if (childRoute.path[0] === '/') { _path = childRoute.path; } else if (isRoot) { _path = basePath + childRoute.path; } else if (childRoute.path === '') { _path = basePath; } else { _path = basePath + '/' + childRoute.path; } childRoute.path = _path; rawRoutes[_path] = { components: componentPath, hierarchy: childHierarchy }; buildPath(childRoute, componentPath, childHierarchy, level + 1); } } function match(url, against) { var keys = Object.keys(against); for (var i = 0, l = keys.length; i < l; i++) { var regexstr = keys[i], _match = url.match(new RegExp('^' + regexstr + '$')); if (_match !== null) { _match.shift(); params = _match; return against[regexstr]; } } if (props.notFoundCallback) { props.notFoundCallback(url); } return []; // Return empty array to keep it all running } function getSiblingRoutes(hierarchy, index) { return scanSiblingsRoutes(hierarchy, props.routes, index - 1, 0); } function scanSiblingsRoutes(hierarchy, parentRoute, toIndex, currentIndex) { hierarchy = hierarchy.slice(); // Slice in order to prevent editing original array if (currentIndex === toIndex) { return parentRoute.children; } return scanSiblingsRoutes(hierarchy, parentRoute.children[hierarchy.shift()], toIndex, currentIndex + 1); } return { getParams: function getParams() { return params; }, isUrl: isUrl, getUrl: function getUrl() { return url; }, setTo: function setTo(u) { u = u.replace(base, ''); if (isUrl(u)) return false; setUrl(u); return true; }, goTo: function goTo(u) { var title = arguments.length <= 1 || arguments[1] === undefined ? '' : arguments[1]; var data = arguments.length <= 2 || arguments[2] === undefined ? null : arguments[2]; if (isUrl(u)) return false; setUrl(u); history.pushState(data, title, base + url); return true; }, get: function get(parent, depth, includeSiblings) { if (parent instanceof Element) { index = parent.kompo.level + 1; } var md = match(url, routes), mc = md.components; if (depth) { if (includeSiblings) { mc[index] = { component: mc[index], siblings: getSiblingRoutes(md.hierarchy, index) }; } // For negative values, do + because index-(-depth) will be positive instead of negative if (depth < 0) return mc.slice(index + depth, index + 1); return mc.slice(index, index + depth); } else { return includeSiblings ? { component: mc[index], siblings: getSiblingRoutes(md.hierarchy, index) } : mc[index]; } } }; } function route(path, component, children) { return { path: path, component: component, children: children }; } function indexRoute(component, children) { return route('', component, children); } function swap(component, router, element) { var c = router.get(component), fn = void 0; if (c) { if ((0, _isFunction2.default)(c)) { fn = c; c = _toPromise(c); } if (c instanceof Element) { _swap(component, c, element); } else if (c instanceof Promise) { if (c.kompo.resolved) { _swap(component, c.kompo.resolved, element); } else { c.then(function (rc) { rc.kompo.level = c.kompo.level; _swap(component, rc, element); c.kompo.resolved = rc; if (fn) fn.kompo.resolved = rc; }).catch(function () { console.error("Cannot dynamically load module for route"); }); } } } } function _toPromise(fn) { var pr = fn(); // Transfer kompo object including level to the promise pr.kompo = fn.kompo; return pr; } function _swap(parent, routedComponent, element) { var routed = parent.kompo.routed, el = element ? element : parent; if (routed === routedComponent) return; if (routed) { el.replaceChild(routedComponent, routed); (0, _component.unmount)(routed); } else { el.appendChild(routedComponent); } (0, _component.mount)(parent, routedComponent); parent.kompo.routed = routedComponent; } /***/ }), /* 21 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = app; var _store = __webpack_require__(2); var _store2 = _interopRequireDefault(_store); var _component = __webpack_require__(0); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function app(root, state, router) { state = (0, _store2.default)(state, root); // Make available for all Elements Object.defineProperty(Element.prototype, '__kompo__', { value: { root: root, state: state, router: router } }); return { start: function start(selector) { if (selector) { (0, _component.setState)(root, selector); } requestAnimationFrame(function () { return (0, _component.render)(root); }); return root; } }; } /***/ }), /* 22 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; exports.default = deproxy; var _isObject = __webpack_require__(3); var _isObject2 = _interopRequireDefault(_isObject); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function deproxy(obj) { var isObj = (0, _isObject2.default)(obj), isArray = Array.isArray(obj); if (!isObj && !isArray) return obj; if (isArray) { obj = obj.slice(); for (var i = 0, l = obj.length; i < l; ++i) { obj[i] = deproxy(obj[i]); } } else { obj = _extends({}, obj); var keys = Object.keys(obj); for (var i = 0, l = keys.length; i < l; ++i) { obj[keys[i]] = deproxy(obj[keys[i]]); } } return obj; } /***/ }), /* 23 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = function () { if (typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope) { return 'Proxy' in self; } else { return 'Proxy' in window; } }(); /***/ }), /* 24 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = merge; /** * Merges given objects * * @param {...Object} objs - Any given amount of objects * @returns {Object} */ function merge() { var object = Array.prototype.shift.call(arguments); for (var i = 0; i < arguments.length; i++) { var obj = arguments[i]; for (var j in obj) { object[j] = obj[j]; } } return object; } /***/ }), /* 25 */ /***/ (function(module, exports) { /* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ // css base code, injected by the css-loader module.exports = function(useSourceMap) { var list = []; // return the list of modules as css string list.toString = function toString() { return this.map(function (item) { var content = cssWithMappingToString(item, useSourceMap); if(item[2]) { return "@media " + item[2] + "{" + content + "}"; } else { return content; } }).join(""); }; // import a list of modules into the list list.i = function(modules, mediaQuery) { if(typeof modules === "string") modules = [[null, modules, ""]]; var alreadyImportedModules = {}; for(var i = 0; i < this.length; i++) { var id = this[i][0]; if(typeof id === "number") alreadyImportedModules[id] = true; } for(i = 0; i < modules.length; i++) { var item = modules[i]; // skip already imported module // this implementation is not 100% perfect for weird media query combinations // when a module is imported multiple times with different media queries. // I hope this will never occur (Hey this way we have smaller bundles) if(typeof item[0] !== "number" || !alreadyImportedModules[item[0]]) { if(mediaQuery && !item[2]) { item[2] = mediaQuery; } else if(mediaQuery) { item[2] = "(" + item[2] + ") and (" + mediaQuery + ")"; } list.push(item); } } }; return list; }; function cssWithMappingToString(item, useSourceMap) { var content = item[1] || ''; var cssMapping = item[3]; if (!cssMapping) { return content; } if (useSourceMap && typeof btoa === 'function') { var sourceMapping = toComment(cssMapping); var sourceURLs = cssMapping.sources.map(function (source) { return '/*# sourceURL=' + cssMapping.sourceRoot + source + ' */' }); return [content].concat(sourceURLs).concat([sourceMapping]).join('\n'); } return [content].join('\n'); } // Adapted from convert-source-map (MIT) function toComment(sourceMap) { // eslint-disable-next-line no-undef var base64 = btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap)))); var data = 'sourceMappingURL=data:application/json;charset=utf-8;base64,' + base64; return '/*# ' + data + ' */'; } /***/ }), /* 26 */ /***/ (function(module, exports, __webpack_require__) { /* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ var stylesInDom = {}; var memoize = function (fn) { var memo; return function () { if (typeof memo === "undefined") memo = fn.apply(this, arguments); return memo; }; }; var isOldIE = memoize(function () { // Test for IE <= 9 as proposed by Browserhacks // @see http://browserhacks.com/#hack-e71d8692f65334173fee715c222cb805 // Tests for existence of standard globals is to allow style-loader // to operate correctly into non-standard environments // @see https://github.com/webpack-contrib/style-loader/issues/177 return window && document && document.all && !window.atob; }); var getElement = (function (fn) { var memo = {}; return function(selector) { if (typeof memo[selector] === "undefined") { memo[selector] = fn.call(this, selector); } return memo[selector] }; })(function (target) { return document.querySelector(target) }); var singleton = null; var singletonCounter = 0; var stylesInsertedAtTop = []; var fixUrls = __webpack_require__(27); module.exports = function(list, options) { if (typeof DEBUG !== "undefined" && DEBUG) { if (typeof document !== "object") throw new Error("The style-loader cannot be used in a non-browser environment"); } options = options || {}; options.attrs = typeof options.attrs === "object" ? options.attrs : {}; // Force single-tag solution on IE6-9, which has a hard limit on the # of <style> // tags it will allow on a page if (!options.singleton) options.singleton = isOldIE(); // By default, add <style> tags to the <head> element if (!options.insertInto) options.insertInto = "head"; // By default, add <style> tags to the bottom of the target if (!options.insertAt) options.insertAt = "bottom"; var styles = listToStyles(list, options); addStylesToDom(styles, options); return function update (newList) { var mayRemove = []; for (var i = 0; i < styles.length; i++) { var item = styles[i]; var domStyle = stylesInDom[item.id]; domStyle.refs--; mayRemove.push(domStyle); } if(newList) { var newStyles = listToStyles(newList, options); addStylesToDom(newStyles, options); } for (var i = 0; i < mayRemove.length; i++) { var domStyle = mayRemove[i]; if(domStyle.refs === 0) { for (var j = 0; j < domStyle.parts.length; j++) domStyle.parts[j](); delete stylesInDom[domStyle.id]; } } }; }; function addStylesToDom (styles, options) { for (var i = 0; i < styles.length; i++) { var item = styles[i]; var domStyle = stylesInDom[item.id]; if(domStyle) { domStyle.refs++; for(var j = 0; j < domStyle.parts.length; j++) { domStyle.parts[j](item.parts[j]); } for(; j < item.parts.length; j++) { domStyle.parts.push(addStyle(item.parts[j], options)); } } else { var parts = []; for(var j = 0; j < item.parts.length; j++) { parts.push(addStyle(item.parts[j], options)); } stylesInDom[item.id] = {id: item.id, refs: 1, parts: parts}; } } } function listToStyles (list, options) { var styles = []; var newStyles = {}; for (var i = 0; i < list.length; i++) { var item = list[i]; var id = options.base ? item[0] + options.base : item[0]; var css = item[1]; var media = item[2]; var sourceMap = item[3]; var part = {css: css, media: media, sourceMap: sourceMap}; if(!newStyles[id]) styles.push(newStyles[id] = {id: id, parts: [part]}); else newStyles[id].parts.push(part); } return styles; } function insertStyleElement (options, style) { var target = getElement(options.insertInto) if (!target) { throw new Error("Couldn't find a style target. This probably means that the value for the 'insertInto' parameter is invalid."); } var lastStyleElementInsertedAtTop = stylesInsertedAtTop[stylesInsertedAtTop.length - 1]; if (options.insertAt === "top") { if (!lastStyleElementInsertedAtTop) { target.insertBefore(style, target.firstChild); } else if (lastStyleElementInsertedAtTop.nextSibling) { target.insertBefore(style, lastStyleElementInsertedAtTop.nextSibling); } else { target.appendChild(style); } stylesInsertedAtTop.push(style); } else if (options.insertAt === "bottom") { target.appendChild(style); } else { throw new Error("Invalid value for parameter 'insertAt'. Must be 'top' or 'bottom'."); } } function removeStyleElement (style) { style.parentNode.removeChild(style); var idx = stylesInsertedAtTop.indexOf(style); if(idx >= 0) { stylesInsertedAtTop.splice(idx, 1); } } function createStyleElement (options) { var style = document.createElement("style"); options.attrs.type = "text/css"; addAttrs(style, options.attrs); insertStyleElement(options, style); return style; } function createLinkElement (options) { var link = document.createElement("link"); options.attrs.type = "text/css"; options.attrs.rel = "stylesheet"; addAttrs(link, options.attrs); insertStyleElement(options, link); return link; } function addAttrs (el, attrs) { Object.keys(attrs).forEach(function (key) { el.setAttribute(key, attrs[key]); }); } function addStyle (obj, options) { var style, update, remove, result; // If a transform function was defined, run it on the css if (options.transform && obj.css) { result = options.transform(obj.css); if (result) { // If transform returns a value, use that instead of the original css. // This allows running runtime transformations on the css. obj.css = result; } else { // If the transform function returns a falsy value, don't add this css. // This allows conditional loading of css return function() { // noop }; } } if (options.singleton) { var styleIndex = singletonCounter++; style = singleton || (singleton = createStyleElement(options)); update = applyToSingletonTag.bind(null, style, styleIndex, false); remove = applyToSingletonTag.bind(null, style, styleIndex, true); } else if ( obj.sourceMap && typeof URL === "function" && typeof URL.createObjectURL === "function" && typeof URL.revokeObjectURL === "function" && typeof Blob === "function" && typeof btoa === "function" ) { style = createLinkElement(options); update = updateLink.bind(null, style, options); remove = function () { removeStyleElement(style); if(style.href) URL.revokeObjectURL(style.href); }; } else { style = createStyleElement(options); update = applyToTag.bind(null, style); remove = function () { removeStyleElement(style); }; } update(obj); return function updateStyle (newObj) { if (newObj) { if ( newObj.css === obj.css && newObj.media === obj.media && newObj.sourceMap === obj.sourceMap ) { return; } update(obj = newObj); } else { remove(); } }; } var replaceText = (function () { var textStore = []; return function (index, replacement) { textStore[index] = replacement; return textStore.filter(Boolean).join('\n'); }; })(); function applyToSingletonTag (style, index, remove, obj) { var css = remove ? "" : obj.css; if (style.styleSheet) { style.styleSheet.cssText = replaceText(index, css); } else { var cssNode = document.createTextNode(css); var childNodes = style.childNodes; if (childNodes[index]) style.removeChild(childNodes[index]); if (childNodes.length) { style.insertBefore(cssNode, childNodes[index]); } else { style.appendChild(cssNode); } } } function applyToTag (style, obj) { var css = obj.css; var media = obj.media; if(media) { style.setAttribute("media", media) } if(style.styleSheet) { style.styleSheet.cssText = css; } else { while(style.firstChild) { style.removeChild(style.firstChild); } style.appendChild(document.createTextNode(css)); } } function updateLink (link, options, obj) { var css = obj.css; var sourceMap = obj.sourceMap; /* If convertToAbsoluteUrls isn't defined, but sourcemaps are enabled and there is no publicPath defined then lets turn convertToAbsoluteUrls on by default. Otherwise default to the convertToAbsoluteUrls option directly */ var autoFixUrls = options.convertToAbsoluteUrls === undefined && sourceMap; if (options.convertToAbsoluteUrls || autoFixUrls) { css = fixUrls(css); } if (sourceMap) { // http://stackoverflow.com/a/26603875 css += "\n/*# sourceMappingURL=data:application/json;base64," + btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap)))) + " */"; } var blob = new Blob([css], { type: "text/css" }); var oldSrc = link.href; link.href = URL.createObjectURL(blob); if(oldSrc) URL.revokeObjectURL(oldSrc); } /***/ }), /* 27 */ /***/ (function(module, exports) { /** * When source maps are enabled, `style-loader` uses a link element with a data-uri to * embed the css on the page. This breaks all relative urls because now they are relative to a * bundle instead of the current page. * * One solution is to only use full urls, but that may be impossible. * * Instead, this function "fixes" the relative urls to be absolute according to the current page location. * * A rudimentary test suite is located at `test/fixUrls.js` and can be run via the `npm test` command. * */ module.exports = function (css) { // get current location var location = typeof window !== "undefined" && window.location; if (!location) { throw new Error("fixUrls requires window.location"); } // blank or null? if (!css || typeof css !== "string") { return css; } var baseUrl = location.protocol + "//" + location.host; var currentDir = baseUrl + location.pathname.replace(/\/[^\/]*$/, "/"); // convert each url(...) /* This regular expression is just a way to recursively match brackets within a string. /url\s*\( = Match on the word "url" with any whitespace after it and then a parens ( = Start a capturing group (?: = Start a non-capturing group [^)(] = Match anything that isn't a parentheses | = OR \( = Match a start parentheses (?: = Start another non-capturing groups [^)(]+ = Match anything that isn't a parentheses | = OR \( = Match a start parentheses [^)(]* = Match anything that isn't a parentheses \) = Match a end parentheses ) = End Group *\) = Match anything and then a close parens ) = Close non-capturing group * = Match anything ) = Close capturing group \) = Match a close parens /gi = Get all matches, not the first. Be case insensitive. */ var fixedCss = css.replace(/url\s*\(((?:[^)(]|\((?:[^)(]+|\([^)(]*\))*\))*)\)/gi, function(fullMatch, origUrl) { // strip quotes (if they exist) var unquotedOrigUrl = origUrl .trim() .replace(/^"(.*)"$/, function(o, $1){ return $1; }) .replace(/^'(.*)'$/, function(o, $1){ return $1; }); // already a full url? no change if (/^(#|data:|http:\/\/|https:\/\/|file:\/\/\/)/i.test(unquotedOrigUrl)) { return fullMatch; } // convert the url to a full url var newUrl; if (unquotedOrigUrl.indexOf("//") === 0) { //TODO: should we add protocol? newUrl = unquotedOrigUrl; } else if (unquotedOrigUrl.indexOf("/") === 0) { // path should be relative to the base url newUrl = baseUrl + unquotedOrigUrl; // already starts with '/' } else { // path should be relative to current directory newUrl = currentDir + unquotedOrigUrl.replace(/^\.\//, ""); // Strip leading './' } // send back the fixed url(...) return "url(" + JSON.stringify(newUrl) + ")"; }); // send back the fixed css return fixedCss; }; /***/ }), /* 28 */, /* 29 */, /* 30 */, /* 31 */, /* 32 */, /* 33 */, /* 34 */, /* 35 */, /* 36 */, /* 37 */, /* 38 */, /* 39 */, /* 40 */, /* 41 */, /* 42 */, /* 43 */, /* 44 */, /* 45 */, /* 46 */, /* 47 */, /* 48 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_kompo__ = __webpack_require__(1); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_kompo___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_kompo__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_kompo_util__ = __webpack_require__(4); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_kompo_util___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_1_kompo_util__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__css_orderGrid_css__ = __webpack_require__(75); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__css_orderGrid_css___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_2__css_orderGrid_css__); var construct = __WEBPACK_IMPORTED_MODULE_0_kompo___default.a.construct; var react = __WEBPACK_IMPORTED_MODULE_0_kompo___default.a.react; var mount = __WEBPACK_IMPORTED_MODULE_0_kompo___default.a.mount; var unmountAll = __WEBPACK_IMPORTED_MODULE_0_kompo___default.a.unmountAll; var getState = __WEBPACK_IMPORTED_MODULE_0_kompo___default.a.getState; var dispatch = __WEBPACK_IMPORTED_MODULE_0_kompo__["state"].dispatch; var markDirty = __WEBPACK_IMPORTED_MODULE_0_kompo__["state"].markDirty; /* harmony default export */ __webpack_exports__["a"] = (construct('div', function (_ref) { var _classList, _this = this; var defaultClass = _ref.defaultClass; var classes = _ref.classes; classes.push(defaultClass); (_classList = this.classList).add.apply(_classList, classes); react(this, function (state) { console.log(state); if (!state || !Array.isArray(state)) return; __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1_kompo_util__["empty"])(_this); // Always reset var frag = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1_kompo_util__["createFragment"])(); for (var i = 0, l = state.length; i < l; ++i) { var row = state[i], rowElement = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1_kompo_util__["create"])('div', { 'class': 'o-OrderGrid-row' }); for (var ri = 0, rl = row.length; ri < rl; ++ri) { var columnElement = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1_kompo_util__["create"])('div', { 'class': 'o-OrderGrid-column' }); columnElement.textContent = i + '.' + ri; rowElement.appendChild(columnElement); } frag.appendChild(rowElement); } _this.appendChild(frag); }); }, { defaultClass: 'o-OrderGrid', classes: [] })); /***/ }), /* 49 */, /* 50 */, /* 51 */, /* 52 */, /* 53 */, /* 54 */, /* 55 */, /* 56 */, /* 57 */, /* 58 */, /* 59 */, /* 60 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_kompo__ = __webpack_require__(1); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_kompo___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_kompo__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__src_js_orderGrid_orderGrid__ = __webpack_require__(48); function _objectDestructuringEmpty(obj) { if (obj == null) throw new TypeError("Cannot destructure undefined"); } // Component and content creation classes and functions var construct = __WEBPACK_IMPORTED_MODULE_0_kompo___default.a.construct; var mount = __WEBPACK_IMPORTED_MODULE_0_kompo___default.a.mount; // Create root component var root = construct('div', function (_ref) { _objectDestructuringEmpty(_ref); var og = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__src_js_orderGrid_orderGrid__["a" /* default */])({}); mount(this, og, function (state) { return state.grid; }); this.appendChild(og); }); // Create instance of root and // append table to body document.body.appendChild(__WEBPACK_IMPORTED_MODULE_0_kompo__["state"].app(root(), { grid: [[{}], // Row 1 [{}, {}], // Row 2 [{}, {}, {}] // Row 3 ] }).start()); /***/ }), /* 61 */, /* 62 */, /* 63 */, /* 64 */, /* 65 */, /* 66 */, /* 67 */, /* 68 */, /* 69 */, /* 70 */, /* 71 */, /* 72 */ /***/ (function(module, exports, __webpack_require__) { exports = module.exports = __webpack_require__(25)(undefined); // imports // module exports.push([module.i, "", ""]); // exports /***/ }), /* 73 */, /* 74 */, /* 75 */ /***/ (function(module, exports, __webpack_require__) { // style-loader: Adds some css to the DOM by adding a <style> tag // load the styles var content = __webpack_require__(72); if(typeof content === 'string') content = [[module.i, content, '']]; // Prepare cssTransformation var transform; var options = {} options.transform = transform // add the styles to the DOM var update = __webpack_require__(26)(content, options); if(content.locals) module.exports = content.locals; // Hot Module Replacement if(false) { // When the styles change, update the <style> tags if(!content.locals) { module.hot.accept("!!../../node_modules/css-loader/index.js!./orderGrid.css", function() { var newContent = require("!!../../node_modules/css-loader/index.js!./orderGrid.css"); if(typeof newContent === 'string') newContent = [[module.id, newContent, '']]; update(newContent); }); } // When the module is disposed, remove the <style> tags module.hot.dispose(function() { update(); }); } /***/ }) /******/ ]); }); //# sourceMappingURL=bundle.js.map
define([ 'channel', 'backbone' ], function(){ var Channel = Backbone.Model.extend({ initialize: function(){ this._channel = null; this._clientId = this.createId(); }, createId: function() { var rand = Math.floor(Math.random() * 1000); var date = new Date(); var time = date.getTime(); return rand + '_' + time.toString(); }, open: function() { $.ajax({ type: 'GET', url: '/api/channel/' + this._clientId, timeout: 10000 }) .done(function(data){ this._channel = new goog.appengine.Channel(data.token); this._channel.open({ onopen: this.onOpen, onmessage: this.onMessage.bind(this), onerror: this.onError, onclose: this.onClose }) }.bind(this)) }, onOpen: function(){ console.log('channel opened!'); }, onMessage: function(message) { var m = JSON.parse(message.data); this.trigger(m.path, m.data); }, onError: function(error) { console.log(error.code + ':' + error.description); }, onClose: function() { console.log('closed'); this.open(); }, sendMessage: function(path, data){ var d = { path: path, data: data }; $.ajax({ type: 'POST', url: '/api/channel/' + this._clientId, dataType: 'json', data: JSON.stringify(d) }) } }) ch = new Channel(); return ch; } )
(function () { 'use strict'; angular .module('com.module.files') .service('FileService', function ($http, CoreService, Setting, gettextCatalog) { this.find = function () { return $http.get(CoreService.env.apiUrl + 'containers/files/files').success(function (res) { console.log(res.data); return res.data; }); }; this.delete = function (id, successCb, cancelCb) { CoreService.confirm( gettextCatalog.getString('Are you sure?'), gettextCatalog.getString('Deleting this cannot be undone'), function () { $http.delete(CoreService.env.apiUrl + '/containers/files/files/' + encodeURIComponent(id)).success( function () { CoreService.toastSuccess( gettextCatalog.getString('File deleted'), gettextCatalog.getString('Your file is deleted!') ); successCb(); }); }, function (err) { CoreService.toastError( gettextCatalog.getString('Error deleting file'), gettextCatalog.getString('Your file is not deleted! ') + err); cancelCb(); }); }; }); })();
function CLASS_PHOTO_UPLOAD(){ this.init(); } CLASS_PHOTO_UPLOAD.prototype = { init:function(){ this.$upLoadBar = $('#up_file'); this.$unUploadTip = $('.unUploadTip'); this.$operationBtn = $('.operationBtn'); this.$startUpload = $('#startUpload'); this.$removeList = $('#removeList'); this.$albumSelect = $('#albumSelect'); this.ajaxUrl = 'upload.php'; this.$miskChild = $('.miskChild'); this.fileNameArr = []; this.fileSizeArr = []; this.albumId = ''; this.plug('uploadify'); this.view('clearDiv'); //样式兼容ie6、7 this.event('removeList'); this.event('saveFile'); this.event('notAlbumTip'); }, view:function(method,arg){ var self = this; var _class = { clearDiv:function(){ var $uploadifyQueue = $('#up_fileQueue'); $uploadifyQueue.removeClass('uploadifyQueue'); }, checkAlbumExist:function(){ var url = window.location.href; var pattern = /\S+?albumId=(\d+)$/; if(pattern.test(url)){ var arr = pattern.exec(url); if(arr[1] !== ''){ self.albumId = arr[1]; } } else{ if(self.$albumSelect.size() <= 0){ alert('您还没有相册,请创建相册后再上传图片。'); return false; } else{ self.albumId = self.$albumSelect.val(); } } } }; return _class[method](arg); }, event:function(method,arg){ var self = this; var _class = { removeList:function(){ self.$removeList.bind('click',function(){ var $uploadifyQueue = $('#up_fileQueue'); var $fileSizeInputs = $uploadifyQueue.find('input.fileSize'); $fileSizeInputs.each(function(i,o){ self.fileSizeArr.push($(o).val()); }); var dataObj = { fileNameArr:self.fileNameArr, act:'remove' }; self.model('ajax',[self.ajaxUrl,dataObj,function(data){ if(data.state === 1){ self.fileNameArr = []; self.fileSizeArr = []; $uploadifyQueue.empty(); self.$unUploadTip.show(); self.$removeList.hide(); self.$startUpload.hide(); } },function(XMLHttpRequest,textStatus,errorThrown){ alert(textStatus); }]); }) }, saveFile:function(){ self.$startUpload.bind('click',function(){ var $fileSizeInputs = $('#up_fileQueue').find('input.fileSize'); self.fileSizeArr = []; $fileSizeInputs.each(function(i,o){ self.fileSizeArr.push($(o).val()); }); self.view('checkAlbumExist'); var dataObj = { fileNameArr:self.fileNameArr, fileSizeArr:self.fileSizeArr, album_id:self.albumId, act:'save' }; self.model('ajax',[self.ajaxUrl,dataObj,function(data){ if(data.state === 1){ window.location.href = 'photoList.php?albumId='+self.albumId; } else{ alert(data.msg); } },function(XMLHttpRequest,textStatus,errorThrown){ alert(textStatus); }]); }); }, notAlbumTip:function(){ if(self.$miskChild.size() === 1){ self.$miskChild.bind('click',function(){ alert('您尚未创建相册,请创建相册后再上传图片。'); }); } } }; return _class[method](arg); }, plug:function(method,arg){ var self = this; var _class = { uploadify:function(){ self.$upLoadBar.uploadify({ 'uploader': '/mysmarty/swf/uploadify.swf', 'script': '/mysmarty/upload.php', // 'cancelImg': '/mysmarty/images/cancel.png', 'buttonImg': '/mysmarty/images/upload.png', 'width':84, 'height':32, 'folder': '/mysmarty/tmp', 'auto':true, 'multi':true, 'removeCompleted':false, 'fileExt':'*.jpg;*.jpeg;*.gif;*.png;', 'fileDesc':'文件类型(.JPG, .GIF, .PNG)', 'onSelectOnce':function(e,data){ self.$unUploadTip.hide(); self.view('checkAlbumExist'); }, 'onComplete':function(event,queueId,fileObj,response,data){ var responseJson = eval('('+response+')'); if(responseJson.state === 1){ self.fileNameArr.push(responseJson.msg); } else if(responseJson.state === 0){ alert(responseJson.msg); } }, 'onAllComplete':function(event,data){ self.$operationBtn.show(); if(self.$removeList.is(':hidden')){ self.$removeList.show(); } if(self.$startUpload.is(':hidden')){ self.$startUpload.show(); } } }); } }; return _class[method](arg); }, model:function(method,arg){ var self = this; var _class = { ajax:function(arg){ $.ajax({ type:'post', url:arg[0], data:arg[1], dataType:'json', success:arg[2], error:arg[3] }); } }; return _class[method](arg); } } $(function(){ new CLASS_PHOTO_UPLOAD(); })
import React from 'react'; import { storiesOf, action } from '@kadira/storybook'; import loremipsum from './loremipsum'; import loremipsumAsReact from './loremipsumAsReact'; import IframeResizer from '../index'; // need to pass in checkOrigin=false for our tests const iframeResizerOptions = { // log: true, // autoResize: true, checkOrigin: false, // resizeFrom: 'parent', // heightCalculationMethod: 'max', // initCallback: () => { console.log('ready!'); }, // resizedCallback: () => { console.log('resized!'); }, }; storiesOf('IframeResizer', module) .add('defaults with lorem ipsum REACT as content, set as children', () => ( <div> <p>Content Before Iframe (style unaffected by iframe)</p> <IframeResizer iframeResizerOptions={iframeResizerOptions}> {loremipsumAsReact} </IframeResizer> <p>Content After Iframe (style unaffected by iframe)</p> </div> )) .add('defaults with lorem ipsum REACT as content, set via prop', () => ( <div> <p>Content Before Iframe (styleeunaffected by iframe)</p> <IframeResizer iframeResizerOptions={iframeResizerOptions} content={loremipsumAsReact} /> <p>Content After Iframe (style unaffected by iframe)</p> </div> )) .add('defaults with lorem ipsum HTML as content, set as children (RAW HTML)', () => ( <div> <p>Content Before Iframe (style unaffected by iframe)</p> <IframeResizer iframeResizerOptions={iframeResizerOptions}> {loremipsum} </IframeResizer> <p>Content After Iframe (style unaffected by iframe)</p> </div> )) .add('defaults with lorem ipsum HTML as content, set via prop', () => ( <div> <p>Content Before Iframe (style unaffected by iframe)</p> <IframeResizer iframeResizerOptions={iframeResizerOptions} content={loremipsum} /> <p>Content After Iframe (style unaffected by iframe)</p> </div> )) .add('defaults with example URL as src (mis-matched domains with content JS work)', () => ( <div> <p>Content Before Iframe (style unaffected by iframe)</p> <IframeResizer iframeResizerOptions={iframeResizerOptions} iframeResizerUrl={false} src="http://davidjbradshaw.com/iframe-resizer/example/frame.content.html" /> <p>Content After Iframe (style unaffected by iframe)</p> <p> This <strong>works</strong> <em>because</em> the content <a href="http://davidjbradshaw.com/iframe-resizer/example/frame.content.html" target="_blank" >URL</a> already has the <a href="https://cdnjs.cloudflare.com/ajax/libs/iframe-resizer/3.5.8/iframeResizer.contentWindow.min.js" target="_blank" >iframeResizer.contentWindow.js</a> loaded </p> <p>We are setting <code>iframeResizerUrl=false</code> so it doesn't try to inject again</p> </div> )) .add('does NOT work with example.com src (mis-matched domains without content JS fail)', () => ( <div> <p>Content Before Iframe (style unaffected by iframe)</p> <IframeResizer iframeResizerOptions={iframeResizerOptions} frameBorder={1} src="http://example.com" /> <p>Content After Iframe (style unaffected by iframe)</p> <p><em> Resize <strong>did not work</strong>, because the iframe content did not have the <a href="https://cdnjs.cloudflare.com/ajax/libs/iframe-resizer/3.5.8/iframeResizer.contentWindow.min.js" target="_blank" >iframeResizer.contentWindow.js</a> loaded, and it is in a different domain so we could not inject it. </em></p> <p>Your console should show an error like the following:</p> <pre style={{ color: 'darkred' }}> Uncaught DOMException: Failed to read the 'contentDocument' property from 'HTMLIFrameElement':<br/> Blocked a frame with origin "http://&lt;hostname&gt;" from accessing a cross-origin frame. </pre> <p><em>Solutions:</em></p> <p><em>Option 1: Write an iframe and inject via <code>content</code> prop</em></p> <p><em>Option 2: Edit the iframe src page, and add the iframe helper script <a href="https://cdnjs.cloudflare.com/ajax/libs/iframe-resizer/3.5.8/iframeResizer.contentWindow.min.js" target="_blank" >iframeResizer.contentWindow.js</a> in a script tag.</em></p> <p><em>Option 3: Proxy the src to a URL on the same domain as the page hosting the iframe; then we should be able to inject the helper script.</em></p> </div> )) .add('custom iframe styles', () => { const style = { width: 150, backgroundColor: '#f2f2f2', textTransform: 'uppercase', color: '#FF8833', marginLeft: 30, }; return ( <div> <p>Content Before Iframe (style unaffected by iframe)</p> <IframeResizer iframeResizerOptions={iframeResizerOptions} content={loremipsum} frameBorder={1} style={style} >No Support For Iframes</IframeResizer> <p>Content After Iframe (style unaffected by iframe)</p> </div> ); }); // <IframeResizer // style={style} // />
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _classnames = require('classnames'); var _classnames2 = _interopRequireDefault(_classnames); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var CollectionItem = function (_Component) { _inherits(CollectionItem, _Component); function CollectionItem() { _classCallCheck(this, CollectionItem); return _possibleConstructorReturn(this, (CollectionItem.__proto__ || Object.getPrototypeOf(CollectionItem)).apply(this, arguments)); } _createClass(CollectionItem, [{ key: 'render', value: function render() { var _props = this.props, active = _props.active, children = _props.children, className = _props.className, other = _objectWithoutProperties(_props, ['active', 'children', 'className']); var classes = { 'collection-item': true, active: active }; var C = this.props.href ? 'a' : 'li'; return _react2.default.createElement( C, _extends({}, other, { className: (0, _classnames2.default)(className, classes) }), children ); } }]); return CollectionItem; }(_react.Component); CollectionItem.propTypes = { active: _react.PropTypes.bool, children: _react.PropTypes.node, className: _react.PropTypes.string, href: _react.PropTypes.string }; exports.default = CollectionItem;
const { EventEmitter } = require( "events" ); QUnit.module( "ConsoleReporter", hooks => { let emitter; let callCount; hooks.beforeEach( function() { emitter = new EventEmitter(); callCount = 0; const con = { log: () => { callCount++; } }; QUnit.reporters.console.init( emitter, con ); } ); QUnit.test( "Event \"runStart\"", assert => { emitter.emit( "runStart", {} ); assert.equal( callCount, 1 ); } ); QUnit.test( "Event \"runEnd\"", assert => { emitter.emit( "runEnd", {} ); assert.equal( callCount, 1 ); } ); QUnit.test( "Event \"testStart\"", assert => { emitter.emit( "testStart", {} ); assert.equal( callCount, 1 ); } ); QUnit.test( "Event \"testEnd\"", assert => { emitter.emit( "testEnd", {} ); assert.equal( callCount, 1 ); } ); QUnit.test( "Event \"error\"", assert => { emitter.emit( "error", {} ); assert.equal( callCount, 1 ); } ); } );
// Copyright (c) 2008-2013 Kris Maglione <maglione.k at Gmail> // Copyright (c) 2006-2009 by Martin Stubenschrott <stubenschrott@vimperator.org> // // This work is licensed for reuse under an MIT license. Details are // given in the LICENSE.txt file included with this file. "use strict"; /** @scope modules */ // command names taken from: // http://developer.mozilla.org/en/docs/Editor_Embedding_Guide /** @instance editor */ var Editor = Module("editor", XPCOM(Ci.nsIEditActionListener, ModuleBase), { init: function init(elem) { if (elem) this.element = elem; else this.__defineGetter__("element", function () { let elem = dactyl.focusedElement; if (elem) return elem.inputField || elem; let win = document.commandDispatcher.focusedWindow; return DOM(win).isEditable && win || null; }); }, get registers() storage.newMap("registers", { privateData: true, store: true }), get registerRing() storage.newArray("register-ring", { privateData: true, store: true }), skipSave: false, // Fixme: Move off this object. currentRegister: null, /** * Temporarily set the default register for the span of the next * mapping. */ pushRegister: function pushRegister(arg) { let restore = this.currentRegister; this.currentRegister = arg; mappings.afterCommands(2, function () { this.currentRegister = restore; }, this); }, defaultRegister: "*", selectionRegisters: { "*": "selection", "+": "global" }, /** * Get the value of the register *name*. * * @param {string|number} name The name of the register to get. * @returns {string|null} * @see #setRegister */ getRegister: function getRegister(name) { if (name == null) name = editor.currentRegister || editor.defaultRegister; if (name == '"') name = 0; if (name == "_") var res = null; else if (Set.has(this.selectionRegisters, name)) res = { text: dactyl.clipboardRead(this.selectionRegisters[name]) || "" }; else if (!/^[0-9]$/.test(name)) res = this.registers.get(name); else res = this.registerRing.get(name); return res != null ? res.text : res; }, /** * Sets the value of register *name* to value. The following * registers have special semantics: * * * - Tied to the PRIMARY selection value on X11 systems. * + - Tied to the primary global clipboard. * _ - The null register. Never has any value. * " - Equivalent to 0. * 0-9 - These act as a kill ring. Setting any of them pushes the * values of higher numbered registers up one slot. * * @param {string|number} name The name of the register to set. * @param {string|Range|Selection|Node} value The value to save to * the register. */ setRegister: function setRegister(name, value, verbose) { if (name == null) name = editor.currentRegister || editor.defaultRegister; if (isinstance(value, [Ci.nsIDOMRange, Ci.nsIDOMNode, Ci.nsISelection])) value = DOM.stringify(value); value = { text: value, isLine: modes.extended & modes.LINE, timestamp: Date.now() * 1000 }; if (name == '"') name = 0; if (name == "_") ; else if (Set.has(this.selectionRegisters, name)) dactyl.clipboardWrite(value.text, verbose, this.selectionRegisters[name]); else if (!/^[0-9]$/.test(name)) this.registers.set(name, value); else { this.registerRing.insert(value, name); this.registerRing.truncate(10); } }, get isCaret() modes.getStack(1).main == modes.CARET, get isTextEdit() modes.getStack(1).main == modes.TEXT_EDIT, get editor() DOM(this.element).editor, getController: function getController(cmd) { let controllers = this.element && this.element.controllers; dactyl.assert(controllers); return controllers.getControllerForCommand(cmd || "cmd_beginLine"); }, get selection() this.editor && this.editor.selection || null, get selectionController() this.editor && this.editor.selectionController || null, deselect: function () { if (this.selection && this.selection.focusNode) this.selection.collapse(this.selection.focusNode, this.selection.focusOffset); }, get selectedRange() { if (!this.selection) return null; if (!this.selection.rangeCount) { let range = RangeFind.nodeContents(this.editor.rootElement.ownerDocument); range.collapse(true); this.selectedRange = range; } return this.selection.getRangeAt(0); }, set selectedRange(range) { this.selection.removeAllRanges(); if (range != null) this.selection.addRange(range); }, get selectedText() String(this.selection), get preserveSelection() this.editor && !this.editor.shouldTxnSetSelection, set preserveSelection(val) { if (this.editor) this.editor.setShouldTxnSetSelection(!val); }, copy: function copy(range, name) { range = range || this.selection; if (!range.collapsed) this.setRegister(name, range); }, cut: function cut(range, name, noStrip) { if (range) this.selectedRange = range; if (!this.selection.isCollapsed) this.setRegister(name, this.selection); this.editor.deleteSelection(0, this.editor[noStrip ? "eNoStrip" : "eStrip"]); }, paste: function paste(name) { let text = this.getRegister(name); dactyl.assert(text && this.editor instanceof Ci.nsIPlaintextEditor); this.editor.insertText(text); }, // count is optional, defaults to 1 executeCommand: function executeCommand(cmd, count) { if (!callable(cmd)) { var controller = this.getController(cmd); util.assert(controller && controller.supportsCommand(cmd) && controller.isCommandEnabled(cmd)); cmd = bind("doCommand", controller, cmd); } // XXX: better as a precondition if (count == null) count = 1; let didCommand = false; while (count--) { // some commands need this try/catch workaround, because a cmd_charPrevious triggered // at the beginning of the textarea, would hang the doCommand() // good thing is, we need this code anyway for proper beeping // What huh? --Kris try { cmd(this.editor, controller); didCommand = true; } catch (e) { util.reportError(e); dactyl.assert(didCommand); break; } } }, moveToPosition: function (pos, select) { if (isObject(pos)) var { startContainer, startOffset } = pos; else [startOffset, startOffset] = [this.selection.focusNode, pos]; this.selection[select ? "extend" : "collapse"](startContainer, startOffset); }, mungeRange: function mungeRange(range, munger, selectEnd) { let { editor } = this; editor.beginPlaceHolderTransaction(null); let [container, offset] = ["startContainer", "startOffset"]; if (selectEnd) [container, offset] = ["endContainer", "endOffset"]; try { // :( let idx = range[offset]; let parent = range[container].parentNode; let parentIdx = Array.indexOf(parent.childNodes, range[container]); let delta = 0; for (let node in Editor.TextsIterator(range)) { let text = node.textContent; let start = 0, end = text.length; if (node == range.startContainer) start = range.startOffset; if (node == range.endContainer) end = range.endOffset; if (start == 0 && end == text.length) text = munger(text); else text = text.slice(0, start) + munger(text.slice(start, end)) + text.slice(end); if (text == node.textContent) continue; if (selectEnd) delta = text.length - node.textContent.length; if (editor instanceof Ci.nsIPlaintextEditor) { this.selectedRange = RangeFind.nodeContents(node); editor.insertText(text); } else node.textContent = text; } let node = parent.childNodes[parentIdx]; if (node instanceof Text) idx = Math.constrain(idx + delta, 0, node.textContent.length); this.selection.collapse(node, idx); } finally { editor.endPlaceHolderTransaction(); } }, findChar: function findChar(key, count, backward, offset) { count = count || 1; // XXX ? offset = (offset || 0) - !!backward; // Grab the charcode of the key spec. Using the key name // directly will break keys like < let code = DOM.Event.parse(key)[0].charCode; let char = String.fromCharCode(code); util.assert(code); let range = this.selectedRange.cloneRange(); let collapse = DOM(this.element).whiteSpace == "normal"; // Find the *count*th occurance of *char* before a non-collapsed // \n, ignoring the character at the caret. let i = 0; function test(c) (collapse || c != "\n") && !!(!i++ || c != char || --count) Editor.extendRange(range, !backward, { test: test }, true); dactyl.assert(count == 0); range.collapse(backward); // Skip to any requested offset. count = Math.abs(offset); Editor.extendRange(range, offset > 0, { test: c => !!count-- }, true); range.collapse(offset < 0); return range; }, findNumber: function findNumber(range) { if (!range) range = this.selectedRange.cloneRange(); // Find digit (or \n). Editor.extendRange(range, true, /[^\n\d]/, true); range.collapse(false); // Select entire number. Editor.extendRange(range, true, /\d/, true); Editor.extendRange(range, false, /\d/, true); // Sanity check. dactyl.assert(/^\d+$/.test(range)); if (false) // Skip for now. if (range.startContainer instanceof Text && range.startOffset > 2) { if (range.startContainer.textContent.substr(range.startOffset - 2, 2) == "0x") range.setStart(range.startContainer, range.startOffset - 2); } // Grab the sign, if it's there. Editor.extendRange(range, false, /[+-]/, true); return range; }, modifyNumber: function modifyNumber(delta, range) { range = this.findNumber(range); let number = parseInt(range) + delta; if (/^[+-]?0x/.test(range)) number = number.toString(16).replace(/^[+-]?/, "$&0x"); else if (/^[+-]?0\d/.test(range)) number = number.toString(8).replace(/^[+-]?/, "$&0"); this.selectedRange = range; this.editor.insertText(String(number)); this.selection.modify("move", "backward", "character"); }, /** * Edits the given file in the external editor as specified by the * 'editor' option. * * @param {object|File|string} args An object specifying the file, line, * and column to edit. If a non-object is specified, it is treated as * the file parameter of the object. * @param {boolean} blocking If true, this function does not return * until the editor exits. */ editFileExternally: function (args, blocking) { if (!isObject(args) || args instanceof File) args = { file: args }; args.file = args.file.path || args.file; let args = options.get("editor").format(args); dactyl.assert(args.length >= 1, _("option.notSet", "editor")); io.run(args.shift(), args, blocking); }, // TODO: clean up with 2 functions for textboxes and currentEditor? editFieldExternally: function editFieldExternally(forceEditing) { if (!options["editor"]) return; let textBox = config.isComposeWindow ? null : dactyl.focusedElement; if (!DOM(textBox).isInput) textBox = null; let line, column; let keepFocus = modes.stack.some(m => isinstance(m.main, modes.COMMAND_LINE)); if (!forceEditing && textBox && textBox.type == "password") { commandline.input(_("editor.prompt.editPassword") + " ", function (resp) { if (resp && resp.match(/^y(es)?$/i)) editor.editFieldExternally(true); }); return; } if (textBox) { var text = textBox.value; var pre = text.substr(0, textBox.selectionStart); } else { var editor_ = window.GetCurrentEditor ? GetCurrentEditor() : Editor.getEditor(document.commandDispatcher.focusedWindow); dactyl.assert(editor_); text = Array.map(editor_.rootElement.childNodes, e => DOM.stringify(e, true)) .join(""); if (!editor_.selection.rangeCount) var sel = ""; else { let range = RangeFind.nodeContents(editor_.rootElement); let end = editor_.selection.getRangeAt(0); range.setEnd(end.startContainer, end.startOffset); pre = DOM.stringify(range, true); if (range.startContainer instanceof Text) pre = pre.replace(/^(?:<[^>"]+>)+/, ""); if (range.endContainer instanceof Text) pre = pre.replace(/(?:<\/[^>"]+>)+$/, ""); } } line = 1 + pre.replace(/[^\n]/g, "").length; column = 1 + pre.replace(/[^]*\n/, "").length; let origGroup = DOM(textBox).highlight.toString(); let cleanup = util.yieldable(function cleanup(error) { if (timer) timer.cancel(); let blink = ["EditorBlink1", "EditorBlink2"]; if (error) { dactyl.reportError(error, true); blink[1] = "EditorError"; } else dactyl.trapErrors(update, null, true); if (tmpfile && tmpfile.exists()) tmpfile.remove(false); if (textBox) { DOM(textBox).highlight.remove("EditorEditing"); if (!keepFocus) dactyl.focus(textBox); for (let group in values(blink.concat(blink, ""))) { highlight.highlightNode(textBox, origGroup + " " + group); yield 100; } } }); function update(force) { if (force !== true && tmpfile.lastModifiedTime <= lastUpdate) return; lastUpdate = Date.now(); let val = tmpfile.read(); if (textBox) { textBox.value = val; if (true) { let elem = DOM(textBox); elem.attrNS(NS, "modifiable", true) .style.MozUserInput; elem.input().attrNS(NS, "modifiable", null); } } else { while (editor_.rootElement.firstChild) editor_.rootElement.removeChild(editor_.rootElement.firstChild); editor_.rootElement.innerHTML = val; } } try { var tmpfile = io.createTempFile("txt", "." + buffer.uri.host); if (!tmpfile) throw Error(_("io.cantCreateTempFile")); if (textBox) { if (!keepFocus) textBox.blur(); DOM(textBox).highlight.add("EditorEditing"); } if (!tmpfile.write(text)) throw Error(_("io.cantEncode")); var lastUpdate = Date.now(); var timer = services.Timer(update, 100, services.Timer.TYPE_REPEATING_SLACK); this.editFileExternally({ file: tmpfile.path, line: line, column: column }, cleanup); } catch (e) { cleanup(e); } }, /** * Expands an abbreviation in the currently active textbox. * * @param {string} mode The mode filter. * @see Abbreviation#expand */ expandAbbreviation: function (mode) { if (!this.selection) return; let range = this.selectedRange.cloneRange(); if (!range.collapsed) return; Editor.extendRange(range, false, /\S/, true); let abbrev = abbreviations.match(mode, String(range)); if (abbrev) { range.setStart(range.startContainer, range.endOffset - abbrev.lhs.length); this.selectedRange = range; this.editor.insertText(abbrev.expand(this.element)); } }, // nsIEditActionListener: WillDeleteNode: util.wrapCallback(function WillDeleteNode(node) { if (!editor.skipSave && node.textContent) this.setRegister(0, node); }), WillDeleteSelection: util.wrapCallback(function WillDeleteSelection(selection) { if (!editor.skipSave && !selection.isCollapsed) this.setRegister(0, selection); }), WillDeleteText: util.wrapCallback(function WillDeleteText(node, start, length) { if (!editor.skipSave && length) this.setRegister(0, node.textContent.substr(start, length)); }) }, { TextsIterator: Class("TextsIterator", { init: function init(range, context, after) { this.after = after; this.start = context || range[after ? "endContainer" : "startContainer"]; if (after) this.context = this.start; this.range = range; }, __iterator__: function __iterator__() { while (this.nextNode()) yield this.context; }, prevNode: function prevNode() { if (!this.context) return this.context = this.start; var node = this.context; if (!this.after) node = node.previousSibling; if (!node) node = this.context.parentNode; else while (node.lastChild) node = node.lastChild; if (!node || !RangeFind.containsNode(this.range, node, true)) return null; this.after = false; return this.context = node; }, nextNode: function nextNode() { if (!this.context) return this.context = this.start; if (!this.after) var node = this.context.firstChild; if (!node) { node = this.context; while (node.parentNode && node != this.range.endContainer && !node.nextSibling) node = node.parentNode; node = node.nextSibling; } if (!node || !RangeFind.containsNode(this.range, node, true)) return null; this.after = false; return this.context = node; }, getPrev: function getPrev() { return this.filter("prevNode"); }, getNext: function getNext() { return this.filter("nextNode"); }, filter: function filter(meth) { let node; while (node = this[meth]()) if (node instanceof Ci.nsIDOMText && DOM(node).isVisible && DOM(node).style.MozUserSelect != "none") return node; } }), extendRange: function extendRange(range, forward, re, sameWord, root, end) { function advance(positive) { while (true) { while (idx == text.length && (node = iterator.getNext())) { if (node == iterator.start) idx = range[offset]; start = text.length; text += node.textContent; range[set](node, idx - start); } if (idx >= text.length || re.test(text[idx]) != positive) break; range[set](range[container], ++idx - start); } } function retreat(positive) { while (true) { while (idx == 0 && (node = iterator.getPrev())) { let str = node.textContent; if (node == iterator.start) idx = range[offset]; else idx = str.length; text = str + text; range[set](node, idx); } if (idx == 0 || re.test(text[idx - 1]) != positive) break; range[set](range[container], --idx); } } if (end == null) end = forward ? "end" : "start"; let [container, offset, set] = [end + "Container", end + "Offset", "set" + util.capitalize(end)]; if (!root) for (root = range[container]; root.parentNode instanceof Element && !DOM(root).isEditable; root = root.parentNode) ; if (root instanceof Ci.nsIDOMNSEditableElement) root = root.editor; if (root instanceof Ci.nsIEditor) root = root.rootElement; let node = range[container]; let iterator = Editor.TextsIterator(RangeFind.nodeContents(root), node, !forward); let text = ""; let idx = 0; let start = 0; if (forward) { advance(true); if (!sameWord) advance(false); } else { if (!sameWord) retreat(false); retreat(true); } return range; }, getEditor: function (elem) { if (arguments.length === 0) { dactyl.assert(dactyl.focusedElement); return dactyl.focusedElement; } if (!elem) elem = dactyl.focusedElement || document.commandDispatcher.focusedWindow; dactyl.assert(elem); return DOM(elem).editor; } }, { modes: function initModes() { modes.addMode("OPERATOR", { char: "o", description: "Mappings which move the cursor", bases: [] }); modes.addMode("VISUAL", { char: "v", description: "Active when text is selected", display: function () "VISUAL" + (this._extended & modes.LINE ? " LINE" : ""), bases: [modes.COMMAND], ownsFocus: true }, { enter: function (stack) { if (editor.selectionController) editor.selectionController.setCaretVisibilityDuringSelection(true); }, leave: function (stack, newMode) { if (newMode.main == modes.CARET) { let selection = content.getSelection(); if (selection && !selection.isCollapsed) selection.collapseToStart(); } else if (stack.pop) editor.deselect(); } }); modes.addMode("TEXT_EDIT", { char: "t", description: "Vim-like editing of input elements", bases: [modes.COMMAND], ownsFocus: true }, { onKeyPress: function (eventList) { const KILL = false, PASS = true; // Hack, really. if (eventList[0].charCode || /^<(?:.-)*(?:BS|Del|C-h|C-w|C-u|C-k)>$/.test(DOM.Event.stringify(eventList[0]))) { dactyl.beep(); return KILL; } return PASS; } }); modes.addMode("INSERT", { char: "i", description: "Active when an input element is focused", insert: true, ownsFocus: true }); modes.addMode("AUTOCOMPLETE", { description: "Active when an input autocomplete pop-up is active", display: function () "AUTOCOMPLETE (insert)", bases: [modes.INSERT] }); }, commands: function initCommands() { commands.add(["reg[isters]"], "List the contents of known registers", function (args) { completion.listCompleter("register", args[0]); }, { argCount: "*" }); }, completion: function initCompletion() { completion.register = function complete_register(context) { context = context.fork("registers"); context.keys = { text: util.identity, description: editor.closure.getRegister }; context.match = function (r) !this.filter || ~this.filter.indexOf(r); context.fork("clipboard", 0, this, function (ctxt) { ctxt.match = context.match; ctxt.title = ["Clipboard Registers"]; ctxt.completions = Object.keys(editor.selectionRegisters); }); context.fork("kill-ring", 0, this, function (ctxt) { ctxt.match = context.match; ctxt.title = ["Kill Ring Registers"]; ctxt.completions = Array.slice("0123456789"); }); context.fork("user", 0, this, function (ctxt) { ctxt.match = context.match; ctxt.title = ["User Defined Registers"]; ctxt.completions = editor.registers.keys(); }); }; }, mappings: function initMappings() { Map.types["editor"] = { preExecute: function preExecute(args) { if (editor.editor && !this.editor) { this.editor = editor.editor; if (!this.noTransaction) this.editor.beginTransaction(); } editor.inEditMap = true; }, postExecute: function preExecute(args) { editor.inEditMap = false; if (this.editor) { if (!this.noTransaction) this.editor.endTransaction(); this.editor = null; } }, }; Map.types["operator"] = { preExecute: function preExecute(args) { editor.inEditMap = true; }, postExecute: function preExecute(args) { editor.inEditMap = true; if (modes.main == modes.OPERATOR) modes.pop(); } }; // add mappings for commands like h,j,k,l,etc. in CARET, VISUAL and TEXT_EDIT mode function addMovementMap(keys, description, hasCount, caretModeMethod, caretModeArg, textEditCommand, visualTextEditCommand) { let extraInfo = { count: !!hasCount, type: "operator" }; function caretExecute(arg) { let win = document.commandDispatcher.focusedWindow; let controller = util.selectionController(win); let sel = controller.getSelection(controller.SELECTION_NORMAL); let buffer = Buffer(win); if (!sel.rangeCount) // Hack. buffer.resetCaret(); if (caretModeMethod == "pageMove") { // Grr. buffer.scrollVertical("pages", caretModeArg ? 1 : -1); buffer.resetCaret(); } else controller[caretModeMethod](caretModeArg, arg); } mappings.add([modes.VISUAL], keys, description, function ({ count }) { count = count || 1; let caret = !dactyl.focusedElement; let controller = buffer.selectionController; while (count-- && modes.main == modes.VISUAL) { if (caret) caretExecute(true, true); else { if (callable(visualTextEditCommand)) visualTextEditCommand(editor.editor); else editor.executeCommand(visualTextEditCommand); } } }, extraInfo); mappings.add([modes.CARET, modes.TEXT_EDIT, modes.OPERATOR], keys, description, function ({ count }) { count = count || 1; if (editor.editor) editor.executeCommand(textEditCommand, count); else { while (count--) caretExecute(false); } }, extraInfo); } // add mappings for commands like i,a,s,c,etc. in TEXT_EDIT mode function addBeginInsertModeMap(keys, commands, description) { mappings.add([modes.TEXT_EDIT], keys, description || "", function () { commands.forEach(function (cmd) { editor.executeCommand(cmd, 1); }); modes.push(modes.INSERT); }, { type: "editor" }); } function selectPreviousLine() { editor.executeCommand("cmd_selectLinePrevious"); if ((modes.extended & modes.LINE) && !editor.selectedText) editor.executeCommand("cmd_selectLinePrevious"); } function selectNextLine() { editor.executeCommand("cmd_selectLineNext"); if ((modes.extended & modes.LINE) && !editor.selectedText) editor.executeCommand("cmd_selectLineNext"); } function updateRange(editor, forward, re, modify, sameWord) { let sel = editor.selection; let range = sel.getRangeAt(0); let end = range.endContainer == sel.focusNode && range.endOffset == sel.focusOffset; if (range.collapsed) end = forward; Editor.extendRange(range, forward, re, sameWord, editor.rootElement, end ? "end" : "start"); modify(range); editor.selectionController.repaintSelection(editor.selectionController.SELECTION_NORMAL); } function clear(forward, re) function _clear(editor) { updateRange(editor, forward, re, function (range) {}); dactyl.assert(!editor.selection.isCollapsed); editor.selection.deleteFromDocument(); let parent = DOM(editor.rootElement.parentNode); if (parent.isInput) parent.input(); } function move(forward, re, sameWord) function _move(editor) { updateRange(editor, forward, re, function (range) { range.collapse(!forward); }, sameWord); } function select(forward, re) function _select(editor) { updateRange(editor, forward, re, function (range) {}); } function beginLine(editor_) { editor.executeCommand("cmd_beginLine"); move(true, /\s/, true)(editor_); } // COUNT CARET TEXT_EDIT VISUAL_TEXT_EDIT addMovementMap(["k", "<Up>"], "Move up one line", true, "lineMove", false, "cmd_linePrevious", selectPreviousLine); addMovementMap(["j", "<Down>", "<Return>"], "Move down one line", true, "lineMove", true, "cmd_lineNext", selectNextLine); addMovementMap(["h", "<Left>", "<BS>"], "Move left one character", true, "characterMove", false, "cmd_charPrevious", "cmd_selectCharPrevious"); addMovementMap(["l", "<Right>", "<Space>"], "Move right one character", true, "characterMove", true, "cmd_charNext", "cmd_selectCharNext"); addMovementMap(["b", "<C-Left>"], "Move left one word", true, "wordMove", false, move(false, /\w/), select(false, /\w/)); addMovementMap(["w", "<C-Right>"], "Move right one word", true, "wordMove", true, move(true, /\w/), select(true, /\w/)); addMovementMap(["B"], "Move left to the previous white space", true, "wordMove", false, move(false, /\S/), select(false, /\S/)); addMovementMap(["W"], "Move right to just beyond the next white space", true, "wordMove", true, move(true, /\S/), select(true, /\S/)); addMovementMap(["e"], "Move to the end of the current word", true, "wordMove", true, move(true, /\W/), select(true, /\W/)); addMovementMap(["E"], "Move right to the next white space", true, "wordMove", true, move(true, /\s/), select(true, /\s/)); addMovementMap(["<C-f>", "<PageDown>"], "Move down one page", true, "pageMove", true, "cmd_movePageDown", "cmd_selectNextPage"); addMovementMap(["<C-b>", "<PageUp>"], "Move up one page", true, "pageMove", false, "cmd_movePageUp", "cmd_selectPreviousPage"); addMovementMap(["gg", "<C-Home>"], "Move to the start of text", false, "completeMove", false, "cmd_moveTop", "cmd_selectTop"); addMovementMap(["G", "<C-End>"], "Move to the end of text", false, "completeMove", true, "cmd_moveBottom", "cmd_selectBottom"); addMovementMap(["0", "<Home>"], "Move to the beginning of the line", false, "intraLineMove", false, "cmd_beginLine", "cmd_selectBeginLine"); addMovementMap(["^"], "Move to the first non-whitespace character of the line", false, "intraLineMove", false, beginLine, "cmd_selectBeginLine"); addMovementMap(["$", "<End>"], "Move to the end of the current line", false, "intraLineMove", true, "cmd_endLine" , "cmd_selectEndLine"); addBeginInsertModeMap(["i", "<Insert>"], [], "Insert text before the cursor"); addBeginInsertModeMap(["a"], ["cmd_charNext"], "Append text after the cursor"); addBeginInsertModeMap(["I"], ["cmd_beginLine"], "Insert text at the beginning of the line"); addBeginInsertModeMap(["A"], ["cmd_endLine"], "Append text at the end of the line"); addBeginInsertModeMap(["s"], ["cmd_deleteCharForward"], "Delete the character in front of the cursor and start insert"); addBeginInsertModeMap(["S"], ["cmd_deleteToEndOfLine", "cmd_deleteToBeginningOfLine"], "Delete the current line and start insert"); addBeginInsertModeMap(["C"], ["cmd_deleteToEndOfLine"], "Delete from the cursor to the end of the line and start insert"); function addMotionMap(key, desc, select, cmd, mode, caretOk) { function doTxn(range, editor) { try { editor.editor.beginTransaction(); cmd(editor, range, editor.editor); } finally { editor.editor.endTransaction(); } } mappings.add([modes.TEXT_EDIT], key, desc, function ({ command, count, motion }) { let start = editor.selectedRange.cloneRange(); mappings.pushCommand(); modes.push(modes.OPERATOR, null, { forCommand: command, count: count, leave: function leave(stack) { try { if (stack.push || stack.fromEscape) return; editor.withSavedValues(["inEditMap"], function () { this.inEditMap = true; let range = RangeFind.union(start, editor.selectedRange); editor.selectedRange = select ? range : start; doTxn(range, editor); }); editor.currentRegister = null; modes.delay(function () { if (mode) modes.push(mode); }); } finally { if (!stack.push) mappings.popCommand(); } } }); }, { count: true, type: "motion" }); mappings.add([modes.VISUAL], key, desc, function ({ count, motion }) { dactyl.assert(caretOk || editor.isTextEdit); if (editor.isTextEdit) doTxn(editor.selectedRange, editor); else cmd(editor, buffer.selection.getRangeAt(0)); }, { count: true, type: "motion" }); } addMotionMap(["d", "x"], "Delete text", true, function (editor) { editor.cut(); }); addMotionMap(["c"], "Change text", true, function (editor) { editor.cut(null, null, true); }, modes.INSERT); addMotionMap(["y"], "Yank text", false, function (editor, range) { editor.copy(range); }, null, true); addMotionMap(["gu"], "Lowercase text", false, function (editor, range) { editor.mungeRange(range, String.toLocaleLowerCase); }); addMotionMap(["gU"], "Uppercase text", false, function (editor, range) { editor.mungeRange(range, String.toLocaleUpperCase); }); mappings.add([modes.OPERATOR], ["c", "d", "y"], "Select the entire line", function ({ command, count }) { dactyl.assert(command == modes.getStack(0).params.forCommand); let sel = editor.selection; sel.modify("move", "backward", "lineboundary"); sel.modify("extend", "forward", "lineboundary"); if (command != "c") sel.modify("extend", "forward", "character"); }, { count: true, type: "operator" }); let bind = function bind(names, description, action, params) mappings.add([modes.INPUT], names, description, action, update({ type: "editor" }, params)); bind(["<C-w>"], "Delete previous word", function () { if (editor.editor) clear(false, /\w/)(editor.editor); else editor.executeCommand("cmd_deleteWordBackward", 1); }); bind(["<C-u>"], "Delete until beginning of current line", function () { // Deletes the whole line. What the hell. // editor.executeCommand("cmd_deleteToBeginningOfLine", 1); editor.executeCommand("cmd_selectBeginLine", 1); if (editor.selection && editor.selection.isCollapsed) { editor.executeCommand("cmd_deleteCharBackward", 1); editor.executeCommand("cmd_selectBeginLine", 1); } if (editor.getController("cmd_delete").isCommandEnabled("cmd_delete")) editor.executeCommand("cmd_delete", 1); }); bind(["<C-k>"], "Delete until end of current line", function () { editor.executeCommand("cmd_deleteToEndOfLine", 1); }); bind(["<C-a>"], "Move cursor to beginning of current line", function () { editor.executeCommand("cmd_beginLine", 1); }); bind(["<C-e>"], "Move cursor to end of current line", function () { editor.executeCommand("cmd_endLine", 1); }); bind(["<C-h>"], "Delete character to the left", function () { events.feedkeys("<BS>", true); }); bind(["<C-d>"], "Delete character to the right", function () { editor.executeCommand("cmd_deleteCharForward", 1); }); bind(["<S-Insert>"], "Insert clipboard/selection", function () { editor.paste(); }); bind(["<C-i>"], "Edit text field with an external editor", function () { editor.editFieldExternally(); }); bind(["<C-t>"], "Edit text field in Text Edit mode", function () { dactyl.assert(!editor.isTextEdit && editor.editor); dactyl.assert(dactyl.focusedElement || // Sites like Google like to use a // hidden, editable window for keyboard // focus and use their own WYSIWYG editor // implementations for the visible area, // which we can't handle. let (f = document.commandDispatcher.focusedWindow.frameElement) f && Hints.isVisible(f, true)); modes.push(modes.TEXT_EDIT); }); // Ugh. mappings.add([modes.INPUT, modes.CARET], ["<*-CR>", "<*-BS>", "<*-Del>", "<*-Left>", "<*-Right>", "<*-Up>", "<*-Down>", "<*-Home>", "<*-End>", "<*-PageUp>", "<*-PageDown>", "<M-c>", "<M-v>", "<*-Tab>"], "Handled by " + config.host, () => Events.PASS_THROUGH); mappings.add([modes.INSERT], ["<Space>", "<Return>"], "Expand Insert mode abbreviation", function () { editor.expandAbbreviation(modes.INSERT); return Events.PASS_THROUGH; }); mappings.add([modes.INSERT], ["<C-]>", "<C-5>"], "Expand Insert mode abbreviation", function () { editor.expandAbbreviation(modes.INSERT); }); let bind = function bind(names, description, action, params) mappings.add([modes.TEXT_EDIT], names, description, action, update({ type: "editor" }, params)); bind(["<C-a>"], "Increment the next number", function ({ count }) { editor.modifyNumber(count || 1); }, { count: true }); bind(["<C-x>"], "Decrement the next number", function ({ count }) { editor.modifyNumber(-(count || 1)); }, { count: true }); // text edit mode bind(["u"], "Undo changes", function ({ count }) { editor.editor.undo(Math.max(count, 1)); editor.deselect(); }, { count: true, noTransaction: true }); bind(["<C-r>"], "Redo undone changes", function ({ count }) { editor.editor.redo(Math.max(count, 1)); editor.deselect(); }, { count: true, noTransaction: true }); bind(["D"], "Delete characters from the cursor to the end of the line", function () { editor.executeCommand("cmd_deleteToEndOfLine"); }); bind(["o"], "Open line below current", function () { editor.executeCommand("cmd_endLine", 1); modes.push(modes.INSERT); events.feedkeys("<Return>"); }); bind(["O"], "Open line above current", function () { editor.executeCommand("cmd_beginLine", 1); modes.push(modes.INSERT); events.feedkeys("<Return>"); editor.executeCommand("cmd_linePrevious", 1); }); bind(["X"], "Delete character to the left", function (args) { editor.executeCommand("cmd_deleteCharBackward", Math.max(args.count, 1)); }, { count: true }); bind(["x"], "Delete character to the right", function (args) { editor.executeCommand("cmd_deleteCharForward", Math.max(args.count, 1)); }, { count: true }); // visual mode mappings.add([modes.CARET, modes.TEXT_EDIT], ["v"], "Start Visual mode", function () { modes.push(modes.VISUAL); }); mappings.add([modes.VISUAL], ["v", "V"], "End Visual mode", function () { modes.pop(); }); bind(["V"], "Start Visual Line mode", function () { modes.push(modes.VISUAL, modes.LINE); editor.executeCommand("cmd_beginLine", 1); editor.executeCommand("cmd_selectLineNext", 1); }); mappings.add([modes.VISUAL], ["s"], "Change selected text", function () { dactyl.assert(editor.isTextEdit); editor.executeCommand("cmd_cut"); modes.push(modes.INSERT); }); mappings.add([modes.VISUAL], ["o"], "Move cursor to the other end of the selection", function () { if (editor.isTextEdit) var selection = editor.selection; else selection = buffer.focusedFrame.getSelection(); util.assert(selection.focusNode); let { focusOffset, anchorOffset, focusNode, anchorNode } = selection; selection.collapse(focusNode, focusOffset); selection.extend(anchorNode, anchorOffset); }); bind(["p"], "Paste clipboard contents", function ({ count }) { dactyl.assert(!editor.isCaret); editor.executeCommand(modules.bind("paste", editor, null), count || 1); }, { count: true }); mappings.add([modes.COMMAND], ['"'], "Bind a register to the next command", function ({ arg }) { editor.pushRegister(arg); }, { arg: true }); mappings.add([modes.INPUT], ["<C-'>", '<C-">'], "Bind a register to the next command", function ({ arg }) { editor.pushRegister(arg); }, { arg: true }); let bind = function bind(names, description, action, params) mappings.add([modes.TEXT_EDIT, modes.OPERATOR, modes.VISUAL], names, description, action, update({ type: "editor" }, params)); // finding characters function offset(backward, before, pos) { if (!backward && modes.main != modes.TEXT_EDIT) return before ? 0 : 1; if (before) return backward ? +1 : -1; return 0; } bind(["f"], "Find a character on the current line, forwards", function ({ arg, count }) { editor.moveToPosition(editor.findChar(arg, Math.max(count, 1), false, offset(false, false)), modes.main == modes.VISUAL); }, { arg: true, count: true, type: "operator" }); bind(["F"], "Find a character on the current line, backwards", function ({ arg, count }) { editor.moveToPosition(editor.findChar(arg, Math.max(count, 1), true, offset(true, false)), modes.main == modes.VISUAL); }, { arg: true, count: true, type: "operator" }); bind(["t"], "Find a character on the current line, forwards, and move to the character before it", function ({ arg, count }) { editor.moveToPosition(editor.findChar(arg, Math.max(count, 1), false, offset(false, true)), modes.main == modes.VISUAL); }, { arg: true, count: true, type: "operator" }); bind(["T"], "Find a character on the current line, backwards, and move to the character after it", function ({ arg, count }) { editor.moveToPosition(editor.findChar(arg, Math.max(count, 1), true, offset(true, true)), modes.main == modes.VISUAL); }, { arg: true, count: true, type: "operator" }); // text edit and visual mode mappings.add([modes.TEXT_EDIT, modes.VISUAL], ["~"], "Switch case of the character under the cursor and move the cursor to the right", function ({ count }) { function munger(range) String(range).replace(/./g, function (c) { let lc = c.toLocaleLowerCase(); return c == lc ? c.toLocaleUpperCase() : lc; }); var range = editor.selectedRange; if (range.collapsed) { count = count || 1; Editor.extendRange(range, true, { test: c => !!count-- }, true); } editor.mungeRange(range, munger, count != null); modes.pop(modes.TEXT_EDIT); }, { count: true }); let bind = function bind(...args) mappings.add.apply(mappings, [[modes.AUTOCOMPLETE]].concat(args)); bind(["<Esc>"], "Return to Insert mode", () => Events.PASS_THROUGH); bind(["<C-[>"], "Return to Insert mode", function () { events.feedkeys("<Esc>", { skipmap: true }); }); bind(["<Up>"], "Select the previous autocomplete result", () => Events.PASS_THROUGH); bind(["<C-p>"], "Select the previous autocomplete result", function () { events.feedkeys("<Up>", { skipmap: true }); }); bind(["<Down>"], "Select the next autocomplete result", () => Events.PASS_THROUGH); bind(["<C-n>"], "Select the next autocomplete result", function () { events.feedkeys("<Down>", { skipmap: true }); }); }, options: function initOptions() { options.add(["editor"], "The external text editor", "string", 'gvim -f +<line> +"sil! call cursor(0, <column>)" <file>', { format: function (obj, value) { let args = commands.parseArgs(value || this.value, { argCount: "*", allowUnknownOptions: true }) .map(util.compileMacro) .filter(fmt => fmt.valid(obj)) .map(fmt => fmt(obj)); if (obj["file"] && !this.has("file")) args.push(obj["file"]); return args; }, has: function (key) Set.has(util.compileMacro(this.value).seen, key), validator: function (value) { this.format({}, value); return Object.keys(util.compileMacro(value).seen) .every(k => ["column", "file", "line"].indexOf(k) >= 0); } }); options.add(["insertmode", "im"], "Enter Insert mode rather than Text Edit mode when focusing text areas", "boolean", true); options.add(["spelllang", "spl"], "The language used by the spell checker", "string", config.locale, { initValue: function () {}, getter: function getter() { try { return services.spell.dictionary || ""; } catch (e) { return ""; } }, setter: function setter(val) { services.spell.dictionary = val; }, completer: function completer(context) { let res = {}; services.spell.getDictionaryList(res, {}); context.completions = res.value; context.keys = { text: util.identity, description: util.identity }; } }); }, sanitizer: function initSanitizer() { sanitizer.addItem("registers", { description: "Register values", persistent: true, action: function (timespan, host) { if (!host) { for (let [k, v] in editor.registers) if (timespan.contains(v.timestamp)) editor.registers.remove(k); editor.registerRing.truncate(0); } } }); } }); // vim: set fdm=marker sw=4 sts=4 ts=8 et:
angular.module("mainPage").controller("MainPageController", [ "$scope", "Authentication", function($scope, Authentication) { $scope.authentication = Authentication; } ]);
var mongoose = require('mongoose'); var Schema = mongoose.Schema; ObjectId = Schema.ObjectId; // create FPU schema var FPUSchema = new Schema({ location: { lat : Number, long : Number }, destination : ObjectId, boardingPoint : ObjectId, boardingTime : Number, travelTime : Number, bus : ObjectId, created_at: Date, updated_at: Date }); var FPU = mongoose.model('FPU', FPUSchema); // Export FPU model module.exports = FPU;
'use strict'; /** * Generates a guest name from the provided session id. * @param {string} session_id - A session id. * @returns {string} - A guest name generated from the socket session object. * @readonly */ exports.generate = function(session_id) { var value = parseInt(session_id.slice(-5), 16) % 100000; return 'Guest' + value; }; /** * Determines whether a given string is a guest name. * @param {string} string - A sring to check. * @returns {boolean} - Whether or not a string is a guest name. * @readonly */ exports.check = function(string) { var regex = new RegExp(/(Guest)([1-9]{1,})/i); return (regex.test(string)); };
'use strict'; // Use application configuration module to register a new module ApplicationConfiguration.registerModule('items');
// All code points in the `Elbasan` script as per Unicode v8.0.0: [ 0x10500, 0x10501, 0x10502, 0x10503, 0x10504, 0x10505, 0x10506, 0x10507, 0x10508, 0x10509, 0x1050A, 0x1050B, 0x1050C, 0x1050D, 0x1050E, 0x1050F, 0x10510, 0x10511, 0x10512, 0x10513, 0x10514, 0x10515, 0x10516, 0x10517, 0x10518, 0x10519, 0x1051A, 0x1051B, 0x1051C, 0x1051D, 0x1051E, 0x1051F, 0x10520, 0x10521, 0x10522, 0x10523, 0x10524, 0x10525, 0x10526, 0x10527 ];
import {expect} from 'chai' import {d3Line} from 'ember-frost-chart/helpers/d3-line' import {describe, it} from 'mocha' describe.skip('Unit | Helper | d3 line', function () { // Replace this with your real tests. it('should work', function () { let result = d3Line(42) expect(result).not.to.equal(null) }) })
import React from 'react'; import Range from '../../components/range'; class RangeTest extends React.Component { state = { range2: { first: 0, second: 5 }, range3: { first: 0, second: 1 }, }; handleChange = (range, value) => { this.setState({ ...this.state, [range]: value }); }; render() { return ( <section id="Range"> <h5>Ranges</h5> <p>Normal range</p> <Range value={this.state.range1} onChange={this.handleChange.bind(this, 'range1')} /> <p>With steps, initial value and editable</p> <Range min={0} max={10} editable value={this.state.range2} onChange={this.handleChange.bind(this, 'range2')} /> <p>Pinned and with snaps</p> <Range pinned snaps min={0} max={10} step={2} editable value={this.state.range3} onChange={this.handleChange.bind(this, 'range3')} /> <p>Disabled status</p> <Range disabled pinned snaps min={0} max={10} step={2} editable value={this.state.range3} onChange={this.handleChange.bind(this, 'range3')} /> <p>Map pinned text</p> <Range pinned step={1} max={200} mapValueOnPin={x => { const inch = x / 2.54; return `${Math.floor(inch / 12)}'${Math.round(inch % 12)}"`; }} value={this.state.range4} showValues onChange={this.handleChange.bind(this, 'range4')} /> </section> ); } } export default RangeTest;
'use strict'; var Vaulted = {}, Promise = require('bluebird'), _ = require('lodash'); /** * @module auth/token * @extends Vaulted * @desc Provides implementation for the Vault Auth Token backend APIs * */ module.exports = function extend(Proto) { Vaulted.getCreateTokenEndpoint = _.partialRight( _.partial(Proto.validateEndpoint, 'auth/%s/create'), 'token'); Vaulted.getTokenRenewEndpoint = _.partialRight( _.partial(Proto.validateEndpoint, 'auth/%s/renew/:id'), 'token'); Vaulted.getTokenRenewSelfEndpoint = _.partialRight( _.partial(Proto.validateEndpoint, 'auth/%s/renew-self'), 'token'); Vaulted.getTokenLookupSelfEndpoint = _.partialRight( _.partial(Proto.validateEndpoint, 'auth/%s/lookup-self'), 'token'); Vaulted.getTokenLookupEndpoint = _.partialRight( _.partial(Proto.validateEndpoint, 'auth/%s/lookup/:id'), 'token'); Vaulted.getTokenRevokeSelfEndpoint = _.partialRight( _.partial(Proto.validateEndpoint, 'auth/%s/revoke-self'), 'token'); Vaulted.getTokenRevokeEndpoint = _.partialRight( _.partial(Proto.validateEndpoint, 'auth/%s/revoke/:id'), 'token'); Vaulted.getTokenRevokeOrphanEndpoint = _.partialRight( _.partial(Proto.validateEndpoint, 'auth/%s/revoke-orphan/:id'), 'token'); Vaulted.getTokenRevokePrefixEndpoint = _.partialRight( _.partial(Proto.validateEndpoint, 'auth/%s/revoke-prefix/:id'), 'token'); _.extend(Proto, Vaulted); }; /** * @method createToken * @desc Creates a token to use for authenticating with the Vault. * * @param {string} [options.body.id] - ID of the client token * @param {Array} [options.body.policies] - list of policies for the token * @param {Object} [options.body.meta] - map of string to string valued metadata * @param {boolean} [options.body.no_parent] - creates a token with no parent * @param {boolean} [options.body.no_default_profile] - default profile will not be a part of this token's policy set * @param {string} [options.body.ttl] - TTL period of the token * @param {string} [options.body.display_name] - display name of the token * @param {number} [options.body.num_uses] - maximum uses for the given token * @param {string} [options.token] - the authentication token * @param {string} [mountName=token] - path name the token auth backend is mounted on * @resolve {Auth} Resolves with token details. * @reject {Error} An error indicating what went wrong * @return {Promise} */ Vaulted.createToken = Promise.method(function createToken(options, mountName) { options = options || {}; return this.getCreateTokenEndpoint(mountName) .post({ headers: this.headers, body: options.body, _token: options.token }); }); /** * @method renewToken * @desc Renew an existing token to use for authenticating with the Vault. * * @param {string} options.id - unique identifier for the token * @param {number} [options.body.increment] - lease increment * @param {string} [options.token] - the authentication token * @param {string} [mountName=token] - path name the token auth backend is mounted on * @resolve {Auth} Resolves with token details. * @reject {Error} An error indicating what went wrong * @return {Promise} */ Vaulted.renewToken = Promise.method(function renewToken(options, mountName) { options = options || {}; return this.getTokenRenewEndpoint(mountName) .post({ headers: this.headers, id: options.id, body: options.body, _token: options.token }); }); /** * @method renewTokenSelf * @desc Renews the token used by this client. * * @param {number} [options.body.increment] - lease increment * @param {string} [options.token] - the authentication token * @param {string} [mountName=token] - path name the token auth backend is mounted on * @resolve {Auth} Resolves with token details. * @reject {Error} An error indicating what went wrong * @return {Promise} */ Vaulted.renewTokenSelf = Promise.method(function renewSelf(options, mountName) { options = options || {}; return this.getTokenRenewSelfEndpoint(mountName) .post({ headers: this.headers, body: options.body, _token: options.token }); }); /** * @method lookupToken * @desc Retrieve information about the specified existing token. * * @param {string} options.id - unique identifier for the token * @param {string} [options.token] - the authentication token * @param {string} [mountName=token] - path name the token auth backend is mounted on * @resolve {Auth} Resolves with token details. * @reject {Error} An error indicating what went wrong * @return {Promise} */ Vaulted.lookupToken = Promise.method(function lookupToken(options, mountName) { options = options || {}; return this.getTokenLookupEndpoint(mountName) .get({ headers: this.headers, id: options.id, _token: options.token }); }); /** * @method revokeToken * @desc Revokes the specified existing token and all child tokens. * * @param {string} options.id - unique identifier for the token * @param {string} [options.token] - the authentication token * @param {string} [mountName=token] - path name the token auth backend is mounted on * @resolve success * @reject {Error} An error indicating what went wrong * @return {Promise} */ Vaulted.revokeToken = Promise.method(function revokeToken(options, mountName) { options = options || {}; return this.getTokenRevokeEndpoint(mountName) .post({ headers: this.headers, id: options.id, _token: options.token }); }); /** * @method revokeTokenOrphan * @desc Revokes the specified existing token but not the child tokens. * * @param {string} options.id - unique identifier for the token * @param {string} [options.token] - the authentication token * @param {string} [mountName=token] - path name the token auth backend is mounted on * @resolve success * @reject {Error} An error indicating what went wrong * @return {Promise} */ Vaulted.revokeTokenOrphan = Promise.method(function revokeTokenOrphan(options, mountName) { options = options || {}; return this.getTokenRevokeOrphanEndpoint(mountName) .post({ headers: this.headers, id: options.id, _token: options.token }); }); /** * @method revokeTokenPrefix * @desc Revokes all tokens generated at a given prefix including children and secrets. * * @param {string} options.id - token prefix * @param {string} [options.token] - the authentication token * @param {string} [mountName=token] - path name the token auth backend is mounted on * @resolve success * @reject {Error} An error indicating what went wrong * @return {Promise} */ Vaulted.revokeTokenPrefix = Promise.method(function revokeTokenPrefix(options, mountName) { options = options || {}; return this.getTokenRevokePrefixEndpoint(mountName) .post({ headers: this.headers, id: options.id, _token: options.token }); }); /** * @method lookupTokenSelf * @desc Retrieve information about the current client token. * * @param {string} [options.token] - the authentication token * @param {string} [mountName=token] - path name the token auth backend is mounted on * @resolve {Auth} Resolves with token details. * @reject {Error} An error indicating what went wrong * @return {Promise} */ Vaulted.lookupTokenSelf = Promise.method(function lookupTokenSelf(options, mountName) { options = options || {}; return this.getTokenLookupSelfEndpoint(mountName) .get({ headers: this.headers, _token: options.token }); }); /** * @method revokeTokenSelf * @desc Revokes the current client token and all child tokens. * * @param {string} [options.token] - the authentication token * @param {string} [mountName=token] - path name the token auth backend is mounted on * @resolve success * @reject {Error} An error indicating what went wrong * @return {Promise} */ Vaulted.revokeTokenSelf = Promise.method(function revokeTokenSelf(options, mountName) { options = options || {}; return this.getTokenRevokeSelfEndpoint(mountName) .post({ headers: this.headers, _token: options.token }); });
"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var core_1 = require('@angular/core'); var platform_browser_1 = require('@angular/platform-browser'); var forms_1 = require('@angular/forms'); var http_1 = require('@angular/http'); // Imports for loading & configuring the in-memory web api var angular_in_memory_web_api_1 = require('angular-in-memory-web-api'); var in_memory_data_service_1 = require('./in-memory-data.service'); var app_component_1 = require('./app.component'); var hero_detail_component_1 = require('./hero-detail.component'); var heroes_component_1 = require('./heroes.component'); var hero_service_1 = require('./hero.service'); var dashboard_component_1 = require('./dashboard.component'); var hero_search_component_1 = require('./hero-search.component'); var app_routing_module_1 = require('./app-routing.module'); var AppModule = (function () { function AppModule() { } AppModule = __decorate([ core_1.NgModule({ imports: [ platform_browser_1.BrowserModule, forms_1.FormsModule, http_1.HttpModule, angular_in_memory_web_api_1.InMemoryWebApiModule.forRoot(in_memory_data_service_1.InMemoryDataService), app_routing_module_1.AppRoutingModule ], declarations: [ app_component_1.AppComponent, dashboard_component_1.DashboardComponent, hero_detail_component_1.HeroDetailComponent, heroes_component_1.HeroesComponent, hero_search_component_1.HeroSearchComponent ], providers: [hero_service_1.HeroService], bootstrap: [app_component_1.AppComponent] }), __metadata('design:paramtypes', []) ], AppModule); return AppModule; }()); exports.AppModule = AppModule; //# sourceMappingURL=app.module.js.map
define(['snake/snake-objects','snake/snake-renderer'],function(Objects,Renderer) { 'use strict' var Engine; Engine = (function() { var TILE_SIZE = 10, TOTAL_HORIZONTAL_TILES=100, TOTAL_VERTICAL_TILES = 50, SNAKE_START_SIZE= 5, DELLEY = 4; function generateRandomFood(snake){ var x, y, i, snakePart, inSnake; do { inSnake = false; x = Math.floor(Math.random() * TOTAL_HORIZONTAL_TILES); y = Math.floor(Math.random() * TOTAL_VERTICAL_TILES); snakePart=snake.head; for(i=0; i< snake.size;i++){ if(x===snakePart.x && y === snakePart.y){ inSnake = true; break; } snakePart = snakePart.next; } } while(inSnake) return new Objects.Food(x,y); } function Engine(canvasID) { this._canvas = document.getElementById(canvasID); this._canvas.width = TILE_SIZE*TOTAL_HORIZONTAL_TILES; this._canvas.height = TILE_SIZE*TOTAL_VERTICAL_TILES+100; this._renderer = new Renderer(canvasID,{tileSize:TILE_SIZE, horizontal_tiles:TOTAL_HORIZONTAL_TILES, verticalTiles: TOTAL_HORIZONTAL_TILES}); this._snake = new Objects.Snake(TOTAL_HORIZONTAL_TILES/2,TOTAL_VERTICAL_TILES/2,SNAKE_START_SIZE,0); this._lives =3; this._points =0; this._food=generateRandomFood(this._snake); } Engine.prototype.start = function(){ var animation, renderer=this._renderer, snake=this._snake, pause=false, food =this._food, lives = this._lives, points = this._points, renderCycle=0; document.addEventListener('keydown',function(ev){ var key = ev.keyCode || window.event.keyCode; switch (key) { case 37: if(snake.direction !== 0) { snake.direction = 2; } break; case 38: if(snake.direction !== 1) { snake.direction = 3; } break; case 39: if(snake.direction !== 2) { snake.direction = 0; } break; case 40: if(snake.direction !== 3) { snake.direction = 1; } break; case 27: pause = !pause; if(!pause){ animation = window.requestAnimationFrame(gameLoop); } break; } }) renderer.drawStats(this._snake.size,this._lives,this._points); animation = window.requestAnimationFrame(gameLoop); function gameLoop(){ if(pause) { return; } renderCycle = (renderCycle +1)%DELLEY; if(!renderCycle) { renderer.enqueForDelete(snake); renderer.executeDelete(); snake.move(); if(snake.head.x<0 || snake.head.x>=TOTAL_HORIZONTAL_TILES || snake.head.y<0 || snake.head.y>=TOTAL_VERTICAL_TILES){ snake = new Objects.Snake(TOTAL_HORIZONTAL_TILES/2,TOTAL_VERTICAL_TILES/2,SNAKE_START_SIZE,0); lives=lives-1; renderer.drawStats(snake.size,lives,points); if(lives === 0){ renderer.drawGameOver(); return; } } if(snake.head.x === food.x && snake.head.y=== food.y){ snake.size++; food=generateRandomFood(snake); points+=10; renderer.drawStats(snake.size,lives,points); } else { //no food found var tail = snake.tail; snake.tail = snake.tail.prev; snake.tail.next = null; tail.prev = null; } renderer.enqueForRender(snake); renderer.enqueForRender(food); renderer.executeRender(); } window.requestAnimationFrame(gameLoop); } } return Engine; }()) return Engine; })
var expect = require('chai').expect; describe('When adding renderer to tokens', function () { var ebookr; beforeEach(function () { ebookr = require('../lib/ebookr').new(); }); it('should be able to add renderer individually', function () { var fn = function () {}; ebookr.addRenderer('foo', fn); expect(ebookr.tokens.foo.renderer).to.equal(fn); }); it('should be able to add renderers en masse', function () { var fn1 = function (foo) {}, fn2 = function (foo, bar) {}; ebookr.addRenderers({ 'test1': fn1, 'test2': fn2 }); expect(ebookr.tokens.test1.renderer).to.equal(fn1); expect(ebookr.tokens.test2.renderer).to.equal(fn2); }); });
var CookiesHandler = function(){ this.startObserverMessage(); } CookiesHandler.prototype.startObserverMessage = function(){ var handler = this; $('#cookies-alert').show(); $('#cookies-alertButton').click(function(){ handler.createCookie(); $('#cookies-alert').fadeOut(); }); $('#accept-cookies-btn').click(function(){ handler.createCookie(); $('#cookies-alert').hide(); }); } CookiesHandler.prototype.createCookie = function(){ var date = new Date(new Date().setYear(new Date().getFullYear() + 1)); document.cookie = 'viewed_cookie_policy=true; expires='+date; }
import React, { Component } from 'react'; import { StyleSheet, View, Dimensions, } from 'react-native'; import MapView from 'react-native-maps'; const { width, height } = Dimensions.get('window'); const ASPECT_RATIO = width / height; const LATITUDE = 35.679976; const LONGITUDE = 139.768458; const LATITUDE_DELTA = 0.01; const LONGITUDE_DELTA = LATITUDE_DELTA * ASPECT_RATIO; // 116423, 51613, 17 const OVERLAY_TOP_LEFT_COORDINATE1 = [35.68184060244454, 139.76531982421875]; const OVERLAY_BOTTOM_RIGHT_COORDINATE1 = [35.679609609368576, 139.76806640625]; const IMAGE_URL1 = 'https://maps.gsi.go.jp/xyz/std/17/116423/51613.png'; // 116423, 51615, 17 const OVERLAY_TOP_LEFT_COORDINATE2 = [35.67737855391474, 139.76531982421875]; const OVERLAY_BOTTOM_RIGHT_COORDINATE2 = [35.67514743608467, 139.76806640625]; const IMAGE_URL2 = 'https://maps.gsi.go.jp/xyz/std/17/116423/51615.png'; export default class ImageOverlayWithURL extends Component { static propTypes = { provider: MapView.ProviderPropType, }; constructor(props) { super(props); this.state = { region: { latitude: LATITUDE, longitude: LONGITUDE, latitudeDelta: LATITUDE_DELTA, longitudeDelta: LONGITUDE_DELTA, }, overlay1: { bounds: [OVERLAY_TOP_LEFT_COORDINATE1, OVERLAY_BOTTOM_RIGHT_COORDINATE1], image: IMAGE_URL1, }, overlay2: { bounds: [OVERLAY_TOP_LEFT_COORDINATE2, OVERLAY_BOTTOM_RIGHT_COORDINATE2], image: IMAGE_URL2, }, }; } render() { return ( <View style={styles.container}> <MapView provider={this.props.provider} style={styles.map} initialRegion={this.state.region} > <MapView.Overlay bounds={this.state.overlay1.bounds} image={this.state.overlay1.image} zindex={2} /> <MapView.Overlay bounds={this.state.overlay2.bounds} image={this.state.overlay2.image} /> </MapView> </View> ); } } const styles = StyleSheet.create({ container: { ...StyleSheet.absoluteFillObject, justifyContent: 'flex-end', alignItems: 'center', }, map: { ...StyleSheet.absoluteFillObject, }, bubble: { backgroundColor: 'rgba(255,255,255,0.7)', paddingHorizontal: 18, paddingVertical: 12, borderRadius: 20, }, latlng: { width: 200, alignItems: 'stretch', }, button: { width: 80, paddingHorizontal: 12, alignItems: 'center', marginHorizontal: 10, }, buttonContainer: { flexDirection: 'row', marginVertical: 20, backgroundColor: 'transparent', }, });
/*global startLiveviewWS, getTimeText, log*/ //the current structure let structure; //keep a copy of the current amendment let amendment; //the current amendment and clause elements let amendmentElements; //list of last amendments let lastAmdList; //maps between string path segments and sub element selectors const pathSegmentMapping = { sub: e => e.children(".subs").children(), phrase: e => e.children("div.clause-content").children("span.phrase"), content: e => e.children("div.clause-content").children("span.main-content"), contentExt: e => e.children("div.ext-content").children("span.ext-text-content") }; //cache paths and the elements they result in let changeCache = {}; //preset strings for action message in amendments const amdActionTexts = { change: "change", replace: "replace", add: "append", remove: "strike out", noselection: "?" }; //applies a change to the resolution document in html given a path and a new content //basically does a translation between the resolution document and the dom version of it const applyDocumentChange = (resolution, path, content) => { //element to apply the change to (set new value) let currentElem; //convert the path into a string as a key for caching const pathAsString = path.join(","); //if there is an already found element for the path, use that results instead of calculating it if (pathAsString in changeCache) { //simply use already computed result const cacheResult = changeCache[pathAsString]; currentElem = cacheResult.elem; //change in already found place in structure cacheResult.clause[path[0]] = content; } else { //pop off the first element from the path stack as the type sign let pathProp = path.pop(); //structure to modify with the update let structureObj; //for amendment content update if (pathProp === "amendment") { //element is amendment clause currentElem = (amendmentElements.replacementClause.length ? amendmentElements.replacementClause : amendmentElements.clause ).children("li"); //use new clause as object to modify structureObj = amendment.newClause; } else { //the current element we are searching in, start off with preamb/op seperation currentElem = $( pathProp === "operative" ? "#op-clauses > .op-wrapper > li" : "#preamb-clauses > div.preamb-clause" ); //get object for first step from resolution structureObj = resolution.clauses[pathProp]; } //until we get to the element specified by the whole path while (path.length && currentElem.length) { //pop off the next property to follow pathProp = path.pop(); //is a string: return a sub element of the current element if (typeof pathProp === "string") { //apply a mapping from path segment to selector const elementFinder = pathSegmentMapping[pathProp]; //if there even is a mapping for this path segment if (typeof elementFinder === "undefined") { //bad, unknown path segment throw Error(`unknown path segment: ${pathProp}`); } else { //get element with selector currentElem = elementFinder(currentElem); } } else if ( typeof pathProp === "number" && pathProp < currentElem.length ) { //is a number and needs to be within length of elements //select nth element using given index currentElem = currentElem.eq(pathProp); } else { //invalid path throw Error(`invalid path segment: ${pathProp}`); } //for the structure object: continue down if it results in an object const pathStepResult = structureObj[pathProp]; if (typeof pathStepResult === "object") { //use as next structureObj structureObj = pathStepResult; } } //stop if there are no elements left and the path was selecting a non-existant element if (currentElem.length !== 1) { throw Error("path didn't resolve to a single element"); } //apply the change in the structure object structureObj[pathProp] = content; //put element result into cache changeCache[pathAsString] = { elem: currentElem, clause: structureObj }; } //apply the change to the found end of the path currentElem.text(content); //scroll the containing clause into view, //this may have to be disabled if it prooves to be annoying currentElem.closest("div.preamb-clause, div.op-wrapper").scrollIntoView(); }; //makes the given element go into full screen mode const makeFullScreen = elem => { if (elem.requestFullscreen) { elem.requestFullscreen(); } else if (elem.msRequestFullscreen) { elem.msRequestFullscreen(); } else if (elem.mozRequestFullScreen) { elem.mozRequestFullScreen(); } else if (elem.webkitRequestFullscreen) { elem.webkitRequestFullscreen(); } }; //returns the correct punctuation for a given (op) clause context const getPunctuation = (subPresent, lastInClause, lastInDoc) => //essentially a precendence waterfall subPresent ? ":" : lastInDoc ? "." : lastInClause ? ";" : ","; //iterates over an object like forEach, but deals with the diff property const diffForEach = (obj, callback) => { //needs to have length property and above 0 if (!obj.length) { return; } //for all numeric of obj for (let i = 0; i < obj.length; i++) { //call callback with value at property, property itself, the whole object, diff for this prop callback(obj[i], i, obj, obj.diff && obj.diff[i]); } }; //diff type color class map converts between diff types and color marking classes const diffTypeColorMap = { updated: "mark-yellow", added: "mark-green", deleted: "mark-red", none: "mark-grey" }; //marks an element with diff colors according to the passed diff type $.fn.colorDiff = function(type) { //can't do anything if falsy if (!type) { return; } //add marking class corresponding to diff type, or grey if no match found this.addClass(diffTypeColorMap[type] || "mark-grey"); }; //updates the last amd list (given there are any in the list) const updateLastAmdList = () => { //if there are last amendments if (lastAmdList) { //unhide collection and get child elements const lastAmdElems = $("#last-amd") .removeClass("hide-this") .children(); //for the first three elements of the last amendments (we only expect/handle three) //TODO: make constiable through setting on server for (let i = 0; i < 3; i++) { //get element from list const amdItem = lastAmdList[i]; //get current element from display item collection const amdElem = lastAmdElems.eq(i); //if there is data for this index if (amdItem) { //unhide element amdElem.removeClass("hide-this"); //set time text in display element amdElem .find(".item-age") .text(getTimeText((Date.now() - amdItem.timestamp) / 1000, "ago")); //get the apply status const applyStatus = amdItem.saveType === "apply"; //apply attributes of item to display element amdElem.find(".item-sponsor").text(amdItem.sponsor); amdElem.find(".item-clause").text(amdItem.clauseIndex + 1); //convert to 1-start counting amdElem.find(".item-action").text(amdActionTexts[amdItem.type]); const itemStatus = amdElem .find(".item-status") .text(applyStatus ? "Accepted" : "Rejected"); //apply color class to accepted/rejected text itemStatus .classState(applyStatus, "green-text") .classState(!applyStatus, "red-text"); } else { //nothing there, hide element amdElem.setHide(true); } } } }; //renders the given structure to the liveview display, //re-generates elements completely: do not use for content update const render = () => { //update the last amendments list updateLastAmdList(); //the structure to render let renderStructure = structure; //apply amendment if present let amdContainer; if (amendment) { //get a clone of the template amendment container amdContainer = $("#amd-container").clone(); //if the structure object will be modified, copy if ( amendment.type === "add" || amendment.type === "replace" || amendment.type === "change" ) { //make a copy for rendering with amendment, these change types modify the structure renderStructure = $.extend(true, {}, structure); } //get the array of op clauses in the resolution const opClauses = renderStructure.resolution.clauses.operative; //if it's adding a clause if (amendment.type === "add") { //set the index to point to the newly added clause amendment.clauseIndex = opClauses.length; //add it the end of the resolution opClauses.push(amendment.newClause); } else if (amendment.type === "replace") { //add new clause after index of targeted clause as replacement //make the new clause a replacement clause so it's rendered as one amendment.newClause.isReplacement = true; //splice into clauses (for replace and change) opClauses.splice(amendment.clauseIndex + 1, 0, amendment.newClause); } else if ( amendment.type === "change" || amendment.type === "noselection" ) { //replace clause that is to be changed opClauses.splice(amendment.clauseIndex, 1, amendment.newClause); } } //clear change cache because we are generating new elements //that aren't referenced in the cache changeCache = {}; //update header $(".forum-info").text(renderStructure.resolution.address.forum); $("#question-of-info").text(renderStructure.resolution.address.questionOf); $("#sponsor-info").text(renderStructure.resolution.address.sponsor.main); //if there are co-sponsors fill in that field as well const coSponsors = renderStructure.resolution.address.sponsor.co; if (coSponsors && coSponsors.length) { //insert content $("#co-sponsor-info").text(coSponsors.join(", ")); //show enclosing row $("#co-sponsor-row").setHide(false); } else { $("#co-sponsor-row").setHide(true); } //get clause content template and prepare for use const clauseContentTemplate = $("#clause-content-template") .clone() .removeAttr("id"); //process clauses [ { //the name in the resolution structure object //and the selectors/tag names for the elements to create name: "operative", listSelector: "#op-clauses", elementType: "li", subListType: "ol" }, { name: "preambulatory", listSelector: "#preamb-clauses", elementType: "div", subListType: "ul" } ].forEach(clauseType => { //for both types of clauses in the resolution //get the dom list element and empty for new filling const container = $(clauseType.listSelector).empty(); //flag for this being in the ops const isOps = clauseType.name === "operative"; //for all clauses of this type, get clauses from structure renderStructure.resolution.clauses[clauseType.name].forEach( (clauseData, index, arr) => { //create a clause object by cloning the template const content = clauseContentTemplate.clone(); const clause = $(`<${clauseType.elementType}/>`).append(content); //the element to be put into the container let clauseWrapper = clause; //only clause itself for preambs //stick op clauses into an additional container for amendment display if (isOps) { //create a wrapper and add op-wrapper for layout and styling clauseWrapper = $("<div/>").addClass("op-wrapper"); //color green as replacement clause in amendment if (clauseData.isReplacement) { clauseWrapper.addClass("mark-green"); } //set replacement clause (for scroll) //this is always called after displayAmendment has run, //so replacementClause won't be erased by it if (clauseData.isReplacement) { amendmentElements.replacementClause = clauseWrapper; } //encapsulate the inner clause element clauseWrapper.append(clause); } else { //add clause to preamb div for identification clauseWrapper.addClass("preamb-clause"); } //add the space between the phrase and the content content.prepend(" "); //add the phrase span content.prepend( $("<span/>", { class: "phrase", text: clauseData.phrase.trim() }) ); //check if subclauses exist const subsPresent = "sub" in clauseData; //check if this is the last clause (can't be last if it's a preamb) const lastClause = isOps && index === arr.length - 1; //check if there is ext content for this subclause const contentExtPresent = "contentExt" in clauseData; //compute if the main content of this clause is the lat piece of it let lastPieceOfClause = !subsPresent && !contentExtPresent; //fill in the content data content.children(".main-content").text(clauseData.content.trim()); //add punctuation content.append( getPunctuation(subsPresent, isOps && !subsPresent, lastClause) ); //apply diff colors if given if (clauseData.diff) { //add coloring on content body content.colorDiff(clauseData.diff.content); //add coloring on phrase if there is any, otherwise mark as grey clause background content .children(".phrase") .colorDiff(clauseData.diff.phrase || "none"); } //process subclauses if any specified in data if (subsPresent) { //add list for subclauses, choose type according to type of clause const subList = $(`<${clauseType.subListType}/>`) .addClass("subs") .appendTo(clause); //add clause list to clause //color whole sublist if specified if (clauseData.diff) { subList.colorDiff(clauseData.diff.sub); } //add subclauses diffForEach( clauseData.sub, (subClauseData, subIndex, subArr, subDiffType) => { //make the subclause const subContent = clauseContentTemplate.clone(); const subClause = $("<li/>") .append(subContent) .appendTo(subList); //add subclause to its sub list //color whole subclause with diff subClause.colorDiff(subDiffType); //if there are diff specs for the things in this subclause if (subClauseData.diff) { //color content subContent.colorDiff(subClauseData.diff.content); } //check if a sub list is specified const subsubsPresent = "sub" in subClauseData; //check if there is ext content for this subclause const subContentExtPresent = "contentExt" in subClauseData; //check if this is the last subclause of this clause //(not in preambs, those are always ",") const lastSubClause = isOps && subIndex === subArr.length - 1; //compute if the main content of this subclause is the last piece of the clause lastPieceOfClause = !subsubsPresent && !contentExtPresent && !subContentExtPresent && lastSubClause; //add data to content subContent .children("span.main-content") .text(subClauseData.content); //add punctuation subContent.append( getPunctuation( subsubsPresent, lastPieceOfClause, lastPieceOfClause && lastClause ) ); //update lastPieceOfClause for subsubs lastPieceOfClause = !contentExtPresent && !subContentExtPresent && lastSubClause; //if there are subsubs if (subsubsPresent) { //add subclause list const subsubList = $(`<${clauseType.subListType}/>`) .addClass("subs subsubs") .appendTo(subClause); //add sub list to clause //color whole subsublist if specified if (subClauseData.diff) { subsubList.colorDiff(subClauseData.diff.sub); } //add all subsub clauses diffForEach( subClauseData.sub, ( subsubClauseData, subsubIndex, subsubArr, subsubDiffType ) => { //make the subclause const subsubContent = clauseContentTemplate.clone(); $("<li/>") .append(subsubContent) .appendTo(subsubList); //add subsubclause to its sub list //color subsubclause subsubContent.colorDiff(subsubDiffType); //add data to content subsubContent .children("span.main-content") .text(subsubClauseData.content); //add punctuation const lastSubsubClause = subsubIndex === subsubArr.length - 1; subsubContent.append( getPunctuation( false, lastSubsubClause && lastPieceOfClause, lastSubsubClause && lastPieceOfClause && lastClause ) ); } ); } //append ext content if specified if (subContentExtPresent) { //create another span with the text const subContentExt = $("<div/>", { class: "ext-content" }).appendTo(subClause); //add text inside subContentExt.append( $("<span/>", { class: "ext-text-content", text: subClauseData.contentExt }) ); //color ext content if (subClauseData.diff) { subContentExt.colorDiff(subClauseData.diff.contentExt); } //update whether or not this is the last piece of the clause lastPieceOfClause = !contentExtPresent && lastSubClause; //add extra punctuation for ext content subContentExt.append( getPunctuation( false, lastPieceOfClause, lastPieceOfClause && lastClause ) ); } } ); } //append ext content if specified if (contentExtPresent) { //create another span with the text const contentExt = $("<div/>", { class: "ext-content" }).appendTo(clause); //add text inside contentExt.append( $("<span/>", { class: "ext-text-content", text: clauseData.contentExt }) ); //color ext content if (clauseData.diff) { contentExt.colorDiff(clauseData.diff.contentExt); } //add extra punctuation for ext content contentExt.append(getPunctuation(false, isOps, lastClause)); } //add the newly created clause to the document and make it visible clauseWrapper.appendTo(container).setHide(false); //check if the clause is subject of the amendment if (isOps && amendment && amendment.clauseIndex === index) { //sets an amendment to be displayed inline in the resolution //clauseWrapper must have a parent element that we can put the amendment element in //error and stop if no such type exists let actionText; if (amendment.type in amdActionTexts) { //get action string for this type of amendment actionText = amdActionTexts[amendment.type]; } else { //throw on unknown amd type throw Error(`no amendment action type '${amendment.type}' exists.`); } //fill clone with info amdContainer .find("span.amd-sponsor") .html( amendment.sponsor || "<em class='grey-text text-darken-1'>Submitter</em>" ); amdContainer.find("span.amd-action-text").text(actionText); //convert to 1 indexed counting amdContainer .find("span.amd-target") .text(`OC${amendment.clauseIndex + 1}`); //set the dom elements amendmentElements = { amd: amdContainer, clause: clauseWrapper, replacementClause: $() //empty set }; //prepend before the given clause element and make visible amdContainer.insertBefore(clauseWrapper).setHide(false); } } ); }); //if there is an amendment to display if (amendment) { //reset color classes amendmentElements.amd.removeClass( "mark-amd-green mark-amd-red mark-amd-grey" ); //set the color of the amendment according to type if (amendment.type === "add") { amendmentElements.amd.addClass("mark-amd-green"); } else if (amendment.type === "remove" || amendment.type === "replace") { amendmentElements.amd.addClass("mark-amd-red"); } else if ( amendment.type === "change" || amendment.type === "noselection" ) { amendmentElements.amd.addClass("mark-amd-grey"); } } }; //sets the last amd list and limits its elements const setLastAmdList = newList => { //set to new list lastAmdList = newList; //if there are items if (lastAmdList && lastAmdList.length) { //limit to the last n items lastAmdList.splice(0, lastAmdList.length - 3); } }; //start liveview as viewer on document load $(document).ready(() => { //true because we are a viewer, add function to deal with the updates it receives startLiveviewWS(true, null, null, (type, data) => { //given type and update data //switch to update type switch (type) { case "editorJoined": //remove amendment and re-render amendment = null; render(); break; case "updateStructure": //whole resolution content is resent because structure has changed case "initStructure": //handle init the same way for now //prepare if not prepared yet (first) if (!structure) { //show content container and hide the spinner and no-content warning $("#resolution").setHide(false); $("#spinner-wrapper").setHide(true); $("#no-content-msg").setHide(true); } //copy given resolution to current structure structure = data.resolutionData || data.update; //set last amendment list setLastAmdList(data.lastAmd); //render everything render(); break; case "updateContent": //the content of one clause changed and only that is sent //if we've got some structure at all if (structure) { //apply the change to the document applyDocumentChange( structure.resolution, data.update.contentPath, data.update.content ); } else { //bad, no content update should arrive before the init or updateStructure messages log({ msg: "no content update should arrive before structure is received" }); } break; case "amendment": //save the amendment amendment = data.update; //require new clause to be specified with types add and replace if ( (amendment.type === "add" || amendment.type === "replace") && !amendment.newClause ) { //error if not present throw Error( "a new clause has to be specified with the amendment " + "types add and replace, but was not." ); } //render everything render(); //scroll the amendment elements and the clause into view amendmentElements.amd .add(amendmentElements.clause) //will do nothing if it is a empty set because the amendment isn't type replace .add(amendmentElements.replacementClause) .scrollIntoView(); break; case "saveAmd": //reset the amendment to nothing amendment = null; //if in apply mode if (data.update.saveType === "apply") { //save given new structure structure = data.update.newStructure; } //save list of last amendments setLastAmdList(data.update.lastAmd); //if not given if (!lastAmdList) { //hide whole display list $("#last-amd").setHide(true); } //re-render without amendment render(); break; } }); //display no content message after two seconds (if the content isn't there then) setTimeout(() => { //check if the content is there, if not, display no content message if ($("#resolution").is(":hidden")) { $("#no-content-msg").show(250); } }, 2000); //register fullscreen handlers $("#enter-fullscreen").on("click", () => //get the viewcontent and try to make it fullscreen makeFullScreen($("#viewcontent")[0]) ); }); //regularly update the last amd list (every 10 seconds) //we need this to update the time dispaly on the last amd items setInterval(updateLastAmdList, 10000);
export default { en: { save: 'Save', shippingMethodLabel: 'Select Shipping Method' }, es: { save: 'Guardar', shippingMethodLabel: 'Selecione Método de Envio' } };
import I from 'immutable'; import { createReducer, createAction } from 'redux/creator'; import { FETCH_LIST_DATA, FETCH_LIST_DATA_SUCCESS, FETCH_LIST_DATA_FAIL } from 'redux/action-types'; let defaultState = I.fromJS([ { id: 1, name: '复仇之魂 Shendelzare Silkwood' }, { id: 2, name: '变体精灵 Morphling 墨斐琳' }, { id: 3, name: '剑圣 Yurnero 尤尼路·扎伽呐塔' }, { id: 4, name: '之骑士 Luna Moonfang 露娜·月牙' }, { id: 5, name: '刚背兽 Rigwarl 里格瓦尔' } ]); export default createReducer(I.fromJS(defaultState), { [FETCH_LIST_DATA_SUCCESS](state, action) { return I.fromJS(action.result); } }); export function requestFetchList() { return { types: [FETCH_LIST_DATA, FETCH_LIST_DATA_SUCCESS, FETCH_LIST_DATA_FAIL], promise: () => { return new Promise(resolve => resolve([])); } }; }
'use strict'; angular.module('refugeesApp') .controller('user-managementDeleteController', function($scope, $uibModalInstance, entity, User) { $scope.user = entity; $scope.clear = function() { $uibModalInstance.dismiss('cancel'); }; $scope.confirmDelete = function (login) { User.delete({login: login}, function () { $uibModalInstance.close(true); }); }; });
/* * jQuery simple-color plugin * @requires jQuery v1.4.2 or later * * See https://github.com/recurser/jquery-simple-color * * Licensed under the MIT license: * http://www.opensource.org/licenses/mit-license.php * * Version: 1.2.3 (Sat, 29 Aug 2020 11:55:25 GMT) */ (function($) { /** * simpleColor() provides a mechanism for displaying simple color-choosers. * * If an options Object is provided, the following attributes are supported: * * defaultColor: Default (initially selected) color. * Default value: '#FFF' * * cellWidth: Width of each individual color cell. * Default value: 10 * * cellHeight: Height of each individual color cell. * Default value: 10 * * cellMargin: Margin of each individual color cell. * Default value: 1 * * boxWidth: Width of the color display box. * Default value: 115px * * boxHeight: Height of the color display box. * Default value: 20px * * columns: Number of columns to display. Color order may look strange if this is altered. * Default value: 16 * * insert: The position to insert the color chooser. 'before' or 'after'. * Default value: 'after' * * colors: An array of colors to display, if you want to customize the default color set. * Default value: default color set - see 'defaultColors' below. * * displayColorCode: Display the color code (eg #333333) as text inside the button. true or false. * Default value: false * * colorCodeAlign: Text alignment used to display the color code inside the button. Only used if * 'displayColorCode' is true. 'left', 'center' or 'right' * Default value: 'center' * * colorCodeColor: Text color of the color code inside the button. Only used if 'displayColorCode' * is true. * Default value: '#FFF' or '#000', decided based on the color selected in the chooser. * * onSelect: Callback function to call after a color has been chosen. The callback * function will be passed two arguments - the hex code of the selected color, * and the input element that triggered the chooser. * Default value: null * Returns: hex value * * onCellEnter: Callback function that excecutes when the mouse enters a cell. The callback * function will be passed two arguments - the hex code of the current color, * and the input element that triggered the chooser. * Default value: null * Returns: hex value * * onClose: Callback function that executes when the chooser is closed. The callback * function will be passed one argument - the input element that triggered * the chooser. * Default value: null * * hideInput If true, hides the original input when displaying the color picker. * Default: true * * livePreview: The color display will change to show the color of the hovered color cell. * The display will revert if no color is selected. * Default value: false * * chooserCSS: An associative array of CSS properties that will be applied to the pop-up * color chooser. * Default value: see options.chooserCSS in the source * * displayCSS: An associative array of CSS properties that will be applied to the color * display box. * Default value: see options.displayCSS in the source * * inputCSS An associative array of CSS properties that will be applied to the form input * ex. { 'float':'left' } * */ /** * Decides if the text should be white or black, based on the chooser's selected color. * * @param {string} hexColor - The color selected in the chooser. * * @return {string} - Either #FFF or #000. */ function getAdaptiveTextColor(hexColor) { var matches = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hexColor); if (!matches) return '#FFF'; var r = parseInt(matches[1], 16); var g = parseInt(matches[2], 16); var b = parseInt(matches[3], 16); var isWhite = (0.213 * r / 255) + (0.715 * g / 255) + (0.072 * b / 255) < 0.5; return isWhite ? '#FFF' : '#000'; } /** * Sets the color of the given chooser, applying the given options. * * @param {Object} displayBox - jQuery-enhanced color display box element. * @param {string} color - The hex color that has been selected. * @param {Object} options - The options specified by the user. */ var setColor = function(displayBox, color, options) { var textColor = options.colorCodeColor || getAdaptiveTextColor(color); displayBox.data('color', color).css({ color: textColor, textAlign: options.colorCodeAlign, backgroundColor: color }); if (options.displayColorCode === true) { displayBox.text(color); } } $.fn.simpleColor = function(options) { var element = this; var defaultColors = [ '990033', 'ff3366', 'cc0033', 'ff0033', 'ff9999', 'cc3366', 'ffccff', 'cc6699', '993366', '660033', 'cc3399', 'ff99cc', 'ff66cc', 'ff99ff', 'ff6699', 'cc0066', 'ff0066', 'ff3399', 'ff0099', 'ff33cc', 'ff00cc', 'ff66ff', 'ff33ff', 'ff00ff', 'cc0099', '990066', 'cc66cc', 'cc33cc', 'cc99ff', 'cc66ff', 'cc33ff', '993399', 'cc00cc', 'cc00ff', '9900cc', '990099', 'cc99cc', '996699', '663366', '660099', '9933cc', '660066', '9900ff', '9933ff', '9966cc', '330033', '663399', '6633cc', '6600cc', '9966ff', '330066', '6600ff', '6633ff', 'ccccff', '9999ff', '9999cc', '6666cc', '6666ff', '666699', '333366', '333399', '330099', '3300cc', '3300ff', '3333ff', '3333cc', '0066ff', '0033ff', '3366ff', '3366cc', '000066', '000033', '0000ff', '000099', '0033cc', '0000cc', '336699', '0066cc', '99ccff', '6699ff', '003366', '6699cc', '006699', '3399cc', '0099cc', '66ccff', '3399ff', '003399', '0099ff', '33ccff', '00ccff', '99ffff', '66ffff', '33ffff', '00ffff', '00cccc', '009999', '669999', '99cccc', 'ccffff', '33cccc', '66cccc', '339999', '336666', '006666', '003333', '00ffcc', '33ffcc', '33cc99', '00cc99', '66ffcc', '99ffcc', '00ff99', '339966', '006633', '336633', '669966', '66cc66', '99ff99', '66ff66', '339933', '99cc99', '66ff99', '33ff99', '33cc66', '00cc66', '66cc99', '009966', '009933', '33ff66', '00ff66', 'ccffcc', 'ccff99', '99ff66', '99ff33', '00ff33', '33ff33', '00cc33', '33cc33', '66ff33', '00ff00', '66cc33', '006600', '003300', '009900', '33ff00', '66ff00', '99ff00', '66cc00', '00cc00', '33cc00', '339900', '99cc66', '669933', '99cc33', '336600', '669900', '99cc00', 'ccff66', 'ccff33', 'ccff00', '999900', 'cccc00', 'cccc33', '333300', '666600', '999933', 'cccc66', '666633', '999966', 'cccc99', 'ffffcc', 'ffff99', 'ffff66', 'ffff33', 'ffff00', 'ffcc00', 'ffcc66', 'ffcc33', 'cc9933', '996600', 'cc9900', 'ff9900', 'cc6600', '993300', 'cc6633', '663300', 'ff9966', 'ff6633', 'ff9933', 'ff6600', 'cc3300', '996633', '330000', '663333', '996666', 'cc9999', '993333', 'cc6666', 'ffcccc', 'ff3333', 'cc3333', 'ff6666', '660000', '990000', 'cc0000', 'ff0000', 'ff3300', 'cc9966', 'ffcc99', 'ffffff', 'cccccc', '999999', '666666', '333333', '000000', '000000', '000000', '000000', '000000', '000000', '000000', '000000', '000000' ]; // Option defaults options = $.extend({ defaultColor: this.attr('defaultColor') || '#FFF', cellWidth: this.attr('cellWidth') || 10, cellHeight: this.attr('cellHeight') || 10, cellMargin: this.attr('cellMargin') || 1, boxWidth: this.attr('boxWidth') || '115px', boxHeight: this.attr('boxHeight') || '20px', columns: this.attr('columns') || 16, insert: this.attr('insert') || 'after', colors: this.attr('colors') || defaultColors, displayColorCode: this.attr('displayColorCode') || false, colorCodeAlign: this.attr('colorCodeAlign') || 'center', colorCodeColor: this.attr('colorCodeColor') || false, hideInput: this.attr('hideInput') || true, onSelect: null, onCellEnter: null, onClose: null, livePreview: false }, options || {}); // Figure out the cell dimensions options.totalWidth = options.columns * (options.cellWidth + (2 * options.cellMargin)); // Custom CSS for the chooser, which relies on previously defined options. options.chooserCSS = $.extend({ 'border': '1px solid #000', 'margin': '0 0 0 5px', 'width': options.totalWidth, 'height': options.totalHeight, 'top': 0, 'left': options.boxWidth, 'position': 'absolute', 'background-color': '#fff' }, options.chooserCSS || {}); // Custom CSS for the display box, which relies on previously defined options. options.displayCSS = $.extend({ 'background-color': options.defaultColor, 'border': '1px solid #000', 'width': options.boxWidth, 'height': options.boxHeight, 'line-height': options.boxHeight + 'px', 'cursor': 'pointer' }, options.displayCSS || {}); // Custom CSS for the input field. options.inputCSS = $.extend({}, options.inputCSS || {}); if (options.hideInput) { // Hide the input unless configured otherwise. this.hide(); } else { // Apply custom CSS to the input field if it is visible. this.css(options.inputCSS); } // This should probably do feature detection - I don't know why we need +2 for IE // but this works for jQuery 1.9.1 if (navigator.userAgent.indexOf("MSIE")!=-1){ options.totalWidth += 2; } options.totalHeight = Math.ceil(options.colors.length / options.columns) * (options.cellHeight + (2 * options.cellMargin)); // Store these options so they'll be available to the other functions // TODO - must be a better way to do this, not sure what the 'official' // jQuery method is. Ideally i want to pass these as a parameter to the // each() function but i'm not sure how $.simpleColorOptions = options; function buildChooser(index) { options = $.simpleColorOptions; // Create a container to hold everything var container = $("<div class='simpleColorContainer' />"); // Absolutely positioned child elements now 'work'. container.css('position', 'relative'); // Create the color display box var defaultColor = (this.value && this.value != '') ? this.value : options.defaultColor; var displayBox = $("<div class='simpleColorDisplay' />"); displayBox.css(options.displayCSS); setColor(displayBox, defaultColor, options); container.append(displayBox); var selectCallback = function (event) { // Bind and namespace the click listener only when the chooser is // displayed. Unbind when the chooser is closed. $('html').bind("click.simpleColorDisplay", function(e) { $('html').unbind("click.simpleColorDisplay"); $('.simpleColorChooser').hide(); // If the user has not selected a new color, then revert the display. // Makes sure the selected cell is within the current color chooser. var target = $(e.target); if (target.is('.simpleColorCell') === false || $.contains( $(event.target).closest('.simpleColorContainer')[0], target[0]) === false) { setColor(displayBox, displayBox.data('color'), options); } // Execute onClose callback whenever the color chooser is closed. if (options.onClose) { options.onClose(element); } }); // Use an existing chooser if there is one if (event.data.container.chooser) { event.data.container.chooser.toggle(); // Build the chooser. } else { // Make a chooser div to hold the cells var chooser = $("<div class='simpleColorChooser'/>"); chooser.css(options.chooserCSS); event.data.container.chooser = chooser; event.data.container.append(chooser); // Create the cells for (var i=0; i<options.colors.length; i++) { var cell = $("<div class='simpleColorCell' id='" + options.colors[i] + "'/>"); cell.css({ 'width': options.cellWidth + 'px', 'height': options.cellHeight + 'px', 'margin': options.cellMargin + 'px', 'cursor': 'pointer', 'lineHeight': options.cellHeight + 'px', 'fontSize': '1px', 'float': 'left', 'background-color': '#'+options.colors[i] }); chooser.append(cell); if (options.onCellEnter || options.livePreview) { cell.bind('mouseenter', function(event) { if (options.onCellEnter) { options.onCellEnter(this.id, element); } if (options.livePreview) { setColor(displayBox, '#' + this.id, options); } }); } cell.bind('click', { input: event.data.input, chooser: chooser, displayBox: displayBox }, function(event) { var color = '#' + this.id event.data.input.value = color; $(event.data.input).change(); setColor(displayBox, color, options); event.data.chooser.hide(); // If 'displayColorCode' is turned on, display the currently selected color code as text inside the button. if (options.displayColorCode) { event.data.displayBox.text(color); } // If an onSelect callback function is defined then excecute it. if (options.onSelect) { options.onSelect(this.id, element); } }); } } }; // Also bind the display box button to display the chooser. var callbackParams = { input: this, container: container, displayBox: displayBox }; displayBox.bind('click', callbackParams, selectCallback); $(this).after(container); $(this).data('container', container); }; this.each(buildChooser); $('.simpleColorDisplay').each(function() { $(this).click(function(e){ e.stopPropagation(); }); }); return this; }; /* * Close the given color choosers. */ $.fn.closeChooser = function() { this.each( function(index) { $(this).data('container').find('.simpleColorChooser').hide(); }); return this; }; /* * Set the color of the given color choosers. * * @param {string} color - The hex color to select in the chooser. */ $.fn.setColor = function(color) { this.each( function(index) { var displayBox = $(this).data('container').find('.simpleColorDisplay'); setColor(displayBox, color, { displayColorCode: displayBox.data('displayColorCode') }); }); return this; }; })(jQuery);
version https://git-lfs.github.com/spec/v1 oid sha256:b221b09f129c267d9c118ab0e7e193fd1990b0b27316d34f171dc2f38201237b size 38076
import * as server from './server'; import * as logs from './logs'; export const api = { server, logs };
//= require socket var myApp = angular.module('myApp', [ 'ui.bootstrap', 'ui.ace', 'socket' ]); myApp.controller('appCtrl', ['$scope', '$http', 'socket', function($scope, $http, socket) { $scope.editorW = 'col-md-6'; $scope.html = ''; $scope.css = ''; $scope.js = ''; $scope.jsType = 'origin'; $scope.oneAtATime = true; var baseUrl = 'preview'; $scope.preview = baseUrl; $scope.isShown = false; $scope.showPreview = function() { if ($scope.isShown) { $scope.preview = '/404'; $scope.isShown = false; $scope.editorW = 'col-md-12'; } else { $scope.preview = baseUrl; $scope.isShown = true; $scope.editorW = 'col-md-6'; } } $scope.openPreview = function() { window.open(baseUrl); } $scope.htmlLoaded = function() { $scope.html_isopen = true; } $scope.cssLoaded = function(_editor) { $scope.changeCssMode = function(mode) { _editor.getSession().setMode('ace/mode/' + mode); } } $scope.jsLoaded = function(_editor) { $scope.changeJsMode = function(mode) { _editor.getSession().setMode('ace/mode/' + mode); } } $scope.htmlChange = function(e) { $scope.html = e[1].getValue(); socket.emit('html', $scope.html); } $scope.cssChange = function(e) { $scope.css = e[1].getValue(); socket.emit('css', $scope.css); } $scope.jsChange = function(e) { $scope.js = e[1].getValue(); var js = { type: $scope.jsType, content: $scope.js } socket.emit('js', js); } $scope.jsTypeChange = function(e) { $scope.jsType = e; $scope.changeJsMode(e); } } ]);
import { SELECT_ITEM, LOAD_DATA, DATA_LOADING_SUCCESS, DATA_LOADING_ERROR, DRAG_MOVE_ITEM, DRAG_RESET_ITEMS, LOAD_RELATIONSHIP_DATA, } from './constants'; import { loadItems, } from '../List/actions'; /** * Select an item * * @param {String} itemId The item ID */ export function selectItem (itemId) { return { type: SELECT_ITEM, id: itemId, }; } /** * Load the item data of the current item */ export function loadItemData () { return (dispatch, getState) => { // Hold on to the id of the item we currently want to load. // Dispatch this reference to our redux store to hold on to as a 'loadingRef'. const currentItemID = getState().item.id; dispatch({ type: LOAD_DATA, }); const state = getState(); const list = state.lists.currentList; // const itemID = state.item.id; // Load a specific item with the utils/List.js helper list.loadItem(state.item.id, { drilldown: true }, (err, itemData) => { // Once this async request has fired this callback, check that // the item id referenced by thisLoadRef is the same id // referenced by loadingRef in the redux store. // If it is, then this is the latest request, and it is safe to resolve it normally. // If it is not the same id however, // this means that this request is NOT the latest fired request, // and so we'll bail out of it early. if (getState().item.id !== currentItemID) return; if (err || !itemData) { dispatch(dataLoadingError(err)); } else { dispatch(dataLoaded(itemData)); } }); }; } export function loadRelationshipItemData ({ columns, refList, relationship, relatedItemId }) { return (dispatch, getState) => { refList.loadItems({ columns: columns, filters: [{ field: refList.fields[relationship.refPath], value: { value: relatedItemId }, }], }, (err, items) => { // // TODO: indicate pagination & link to main list view // this.setState({ items }); dispatch(relationshipDataLoaded(relationship.path, items)); }); }; } /** * Called when data of the current item is loaded * * @param {Object} data The item data */ export function dataLoaded (data) { return { type: DATA_LOADING_SUCCESS, loadingRef: null, data, }; } export function relationshipDataLoaded (path, data) { return { type: LOAD_RELATIONSHIP_DATA, relationshipPath: path, data, }; }; /** * Called when there was an error during the loading of the current item data, * will retry loading the data ever NETWORK_ERROR_RETRY_DELAY milliseconds * * @param {Object} error The error */ export function dataLoadingError (err) { return { type: DATA_LOADING_ERROR, loadingRef: null, error: err, }; } /** * Deletes an item and optionally redirects to the current list URL * * @param {String} id The ID of the item we want to delete * @param {Object} router A react-router router object. If this is passed, we * redirect to Keystone.adminPath/currentList.path! */ export function deleteItem (id, router) { return (dispatch, getState) => { const state = getState(); const list = state.lists.currentList; list.deleteItem(id, (err) => { // TODO Proper error handling if (err) { if(err.error !== undefined) { alert(err.error); } else{ alert(err); } } else { // If a router is passed, redirect to the current list path, // otherwise stay where we are if (router) { let redirectUrl = `${Keystone.adminPath}/${list.path}`; if (state.lists.page.index && state.lists.page.index > 1) { redirectUrl = `${redirectUrl}?page=${state.lists.page.index}`; } console.log(state, redirectUrl); router.push(redirectUrl); } dispatch(loadItems()); } }); }; } export function reorderItems ({ columns, refList, relationship, relatedItemId, item, prevSortOrder, newSortOrder }) { return (dispatch, getState) => { // Send the item, previous sortOrder and the new sortOrder // we should get the proper list and new page results in return refList.reorderItems( item, prevSortOrder, newSortOrder, { columns: columns, filters: [{ field: refList.fields[relationship.refPath], value: { value: relatedItemId }, }], }, (err, items) => { dispatch(relationshipDataLoaded(relationship.path, items)); // If err, flash the row alert // if (err) { // dispatch(resetItems(item.id)); // // return this.resetItems(this.findItemById[item.id]); // } else { // dispatch(itemsLoaded(items)); // dispatch(setRowAlert({ // success: item.id, // fail: false, // })); // } } ); }; } export function moveItem ({ prevIndex, newIndex, relationshipPath, newSortOrder }) { return { type: DRAG_MOVE_ITEM, prevIndex, newIndex, relationshipPath, newSortOrder, }; } export function resetItems () { return { type: DRAG_RESET_ITEMS, }; }
myApp.factory('galleryModel', ['$http', function($http) { return { saveGallery: function(galleryData) { return $http({ headers: { 'Content-Type': 'application/json' }, url: baseUrl + 'galeri', method: "POST", data: { name: galleryData.name } }); }, getAllGalleries: function() { return $http.get(baseUrl + 'galeri'); }, getGalleryById: function(id) { return $http.get(baseUrl + 'galeri/' + id); } }; }])
// @flow import React, { Component } from 'react'; import Peaks from '../../../../node_modules/peaks.js/peaks.js'; //import Peaks from 'peaks.js'; import styles from './WaveformPeaks.css'; import LoadingDots from '../../LoadingDots'; class WaveformPeaks extends Component { props: { filePath: string, pos: number, handlePosChange: Function, playing: boolean }; state: { width: string, loading: boolean }; constructor(props) { super(props); this.state = { width: '100%', loading: true }; this.ctx = new AudioContext(); this.resolveContainerPromise = null; this.container = new Promise((resolve, reject) => { this.resolveContainerPromise = resolve; }); this.container.then((container) => { window.addEventListener('resize', this.adjustContainer.bind(this, container, '100%', () => {})); window.addEventListener('error', this.handlePeaksErrors.bind(this, container)); }); this.onAudio = this.onAudio.bind(this); this.updateCurrentTime = this.updateCurrentTime.bind(this); this.handlePeaksErrors = this.handlePeaksErrors.bind(this); this.onContainer = this.onContainer.bind(this); } componentDidUpdate(prevProps, prevState) { if(prevProps.filePath !== this.props.filePath) { window.clearTimeout(this.timeoutId); this.audio.src = this.props.filePath; this.setState({ width: '100%', loading: true }); } if(prevProps.segments !== this.props.segments) { this.updateSegments(); } if(this.props.playing && !prevProps.playing) { this.audio.play(); this.updateCurrentTime(); } else if(!this.props.playing && prevProps.playing) { this.audio.pause(); } } componentWillMount() { this.ctx.close(); } updateCurrentTime() { this.props.handlePosChange(this.audio.currentTime); if(!this.props.playing) return; window.requestAnimationFrame(this.updateCurrentTime); } updateSegments() { const peaks = this.peaks; if(!peaks || !peaks.segments) return; const { segments, fileName } = this.props; if(!segments.length) return peaks.segments.removeAll(); const peaksSegments = peaks.segments.getSegments(); segments.forEach(({ id, startTimeSeconds: startTime, endTimeSeconds: endTime, color }, index) => { const peaksSegment = peaksSegments.find(s => s.id === id); if(!peaksSegment || peaksSegment.startTime !== startTime || peaksSegment.endTime !== endTime) { peaks.segments.removeById(id); peaks.segments.add({ startTime, endTime, color, labelText: `${fileName}_${index + 1}`, id }) } }); } adjustContainer(container, targetWidth, callback) { const maxWidth = this.audio.duration * 92; let width = '100%'; if(!targetWidth) { if(container.offsetWidth > maxWidth) { width = `${maxWidth}px`; } } else { width = targetWidth; } this.setState({ width }, callback); } onAudio(audio) { this.audio = audio; this.audio.addEventListener('loadedmetadata', () => { this.container.then((container) => { this.adjustContainer(container, null, () => { this.initPeaks(container, audio); }); }); }); this.audio.addEventListener('timeupdate', (e) => { this.updateCurrentTime(); }); } onContainer(container) { this.containerSet = true; this.resolveContainerPromise(container); } handlePeaksErrors(container, error) { if(error.message.match(/zoom level \d+ too low/ig)) { this.adjustContainer(container, null, () => { this.initPeaks(container, this.audio); }); } } initPeaks(container, audio) { if(this.peaks) { console.log('destroy peaks') this.peaks.destroy(); this.peaks = null; } const { segments, fileName } = this.props; const ctx = this.ctx; this.peaks = Peaks.init({ container: container, mediaElement: audio, audioContext: ctx, height: 100, zoomWaveformColor: 'rgba(0, 225, 128, 1)', playheadColor: '#D62B70', segments: segments.map(({ startTimeSeconds, endTimeSeconds, id, color }, index) => { return { startTime: startTimeSeconds, endTime: endTimeSeconds, color, labelText: `${fileName}_${index + 1}`, id }; }) }); this.peaks.on('error', (error) => { console.log('peaks had an error'); this.handlePeaksErrors(container, error); }); this.peaks.on('segments.ready', () => { this.timeoutId = window.setTimeout(() => { this.setState({ loading: false }); }, 400); }); } render() { const { filePath, pos, handlePosChange, playing } = this.props; const { loading, width } = this.state; return ( <div className={styles.container}> {loading && <div className={styles.loader}><LoadingDots/></div>} <div id="peaks-container" ref={(container) => { !this.containerSet && this.onContainer(container); }} className={styles.waveform} style={{ width: width }}> </div> <audio ref={(audio) => { !this.audio && this.onAudio(audio); }} src={filePath}/> </div> ); } } export default WaveformPeaks;
Package.describe({ name: "nova:voting", summary: "Telescope scoring package.", version: "0.26.0-nova", git: "https://github.com/TelescopeJS/Telescope.git" }); Package.onUse(function (api) { api.versionsFrom("METEOR@1.0"); api.use(['nova:core@0.26.0-nova']); api.use([ 'nova:posts@0.26.0-nova', 'nova:comments@0.26.0-nova' ], ['client', 'server']); api.addFiles([ 'lib/scoring.js', 'lib/vote.js', 'lib/custom_fields.js' ], ['client','server']); api.addFiles([ 'lib/server/cron.js', ], ['server']); });
/* * /MathJax-v2/localization/gl/FontWarnings.js * * Copyright (c) 2009-2018 The MathJax Consortium * * 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. */ MathJax.Localization.addTranslation("gl","FontWarnings",{version:"2.7.8",isLoaded:true,strings:{}});MathJax.Ajax.loadComplete("[MathJax]/localization/gl/FontWarnings.js");
module.exports = { prefix: 'far', iconName: 'arrow-alt-left', icon: [448, 512, [], "f355", "M272 431.952v-73.798h128c26.51 0 48-21.49 48-48V201.846c0-26.51-21.49-48-48-48H272V80.057c0-42.638-51.731-64.15-81.941-33.941l-176 175.943c-18.745 18.745-18.746 49.137 0 67.882l176 175.952C220.208 496.042 272 474.675 272 431.952zM48 256L224 80v121.846h176v108.308H224V432L48 256z"] };
import React from 'react'; import ReactDOM from 'react-dom'; import Nav from './Nav'; import Board from './Board'; import '../scss/App.scss'; ReactDOM.render( <Nav />, document.getElementById('navbar-container') ); ReactDOM.render( <Board count={20} />, document.getElementById('react-container') );
define(['content/extend', 'content/plugin'], function (extend, Plugin) { function Admonition() { } Admonition.prototype = extend(Plugin.prototype, { }); return Admonition; });
// // var tobi = require('tobi'); // var app = require('../app.js'); // var browser = tobi.createBrowser(app); // // browser.get('/', function(res, $) { // // browser.click('get_test', function(res, $){ // $('content').should.be('') // }); // // }); // // app.close();
<script type="text/javascript"> (function () { "use strict"; // once cached, the css file is stored on the client forever unless // the URL below is changed. Any change will invalidate the cache var css_href = './index_files/web-fonts.css'; // a simple event handler wrapper function on(el, ev, callback) { if (el.addEventListener) { el.addEventListener(ev, callback, false); } else if (el.attachEvent) { el.attachEvent("on" + ev, callback); } } // if we have the fonts in localStorage or if we've cached them using the native batrowser cache if ((window.localStorage && localStorage.font_css_cache) || document.cookie.indexOf('font_css_cache') > -1){ // just use the cached version injectFontsStylesheet(); } else { // otherwise, don't block the loading of the page; wait until it's done. on(window, "load", injectFontsStylesheet); } // quick way to determine whether a css file has been cached locally function fileIsCached(href) { return window.localStorage && localStorage.font_css_cache && (localStorage.font_css_cache_file === href); } // time to get the actual css file function injectFontsStylesheet() { // if this is an older browser if (!window.localStorage || !window.XMLHttpRequest) { var stylesheet = document.createElement('link'); stylesheet.href = css_href; stylesheet.rel = 'stylesheet'; stylesheet.type = 'text/css'; document.getElementsByTagName('head')[0].appendChild(stylesheet); // just use the native browser cache // this requires a good expires header on the server document.cookie = "font_css_cache"; // if this isn't an old browser } else { // use the cached version if we already have it if (fileIsCached(css_href)) { injectRawStyle(localStorage.font_css_cache); // otherwise, load it with ajax } else { var xhr = new XMLHttpRequest(); xhr.open("GET", css_href, true); // cater for IE8 which does not support addEventListener or attachEvent on XMLHttpRequest xhr.onreadystatechange = function () { if (xhr.readyState === 4) { // once we have the content, quickly inject the css rules injectRawStyle(xhr.responseText); // and cache the text content for further use // notice that this overwrites anything that might have already been previously cached localStorage.font_css_cache = xhr.responseText; localStorage.font_css_cache_file = css_href; } }; xhr.send(); } } } // this is the simple utitily that injects the cached or loaded css text function injectRawStyle(text) { var style = document.createElement('style'); // cater for IE8 which doesn't support style.innerHTML style.setAttribute("type", "text/css"); if (style.styleSheet) { style.styleSheet.cssText = text; } else { style.innerHTML = text; } document.getElementsByTagName('head')[0].appendChild(style); } }()); </script>
var mongoose = require('mongoose'); var Schema = mongoose.Schema; var attendeeSchema = new Schema({ name: String, profileId: String, meetingId: String }); var Attendee = mongoose.model('Attendee', attendeeSchema); module.exports = Attendee;
import alt from '../alt'; import request from 'superagent'; class SignupActions { createUser(user) { request .post('/api/users') .send(user) .set('Accept', 'application/json') .end((err, result) => { if(err) { this.signupErrorDispatcher(err.response.body.message); } else if(result && result.body.error) { this.signupErrorDispatcher(result.body); } else { this.signupSuccessDispatcher(result.body); } }); } signupSuccessDispatcher (user) { return user; } signupErrorDispatcher (err) { return err; } } export default alt.createActions(SignupActions);
export { default as Forms } from './forms'; export { default as Form } from './form'; export { default as SignInForm } from './signInForm'; export { default as SignUpForm } from './signUpForm'; export { default as Input } from './input'; export { default as Overlay } from './overlay';
function staticLandingPageEditor(collectionId, data) { var newSections = [], newLinks = []; var setActiveTab, getActiveTab; var renameUri = false; $(".edit-accordion").on('accordionactivate', function (event, ui) { setActiveTab = $(".edit-accordion").accordion("option", "active"); if (setActiveTab !== false) { Florence.globalVars.activeTab = setActiveTab; } }); getActiveTab = Florence.globalVars.activeTab; accordion(getActiveTab); // Metadata edition and saving $("#title").on('input', function () { renameUri = true; $(this).textareaAutoSize(); data.description.title = $(this).val(); }); $("#summary").on('input', function () { $(this).textareaAutoSize(); data.description.summary = $(this).val(); }); $("#keywordsTag").tagit({ availableTags: data.description.keywords, singleField: true, allowSpaces: true, singleFieldNode: $('#keywords') }); $('#keywords').on('change', function () { data.description.keywords = $('#keywords').val().split(','); }); $("#metaDescription").on('input', function () { $(this).textareaAutoSize(); data.description.metaDescription = $(this).val(); }); // Edit content // Load and edition $(data.sections).each(function (index) { $('#section-uri_' + index).on('paste', function () { setTimeout(function () { var pastedUrl = $('#section-uri_' + index).val(); var safeUrl = checkPathParsed(pastedUrl); $('#section-uri_' + index).val(safeUrl); }, 50); }); if (!$('#section-uri_' + index).val()) { $('<button class="btn-edit-save-and-submit-for-review" id="section-get_' + index + '">Go to</button>').insertAfter('#section-uri_' + index); $('#section-get_' + index).click(function () { var iframeEvent = document.getElementById('iframe').contentWindow; iframeEvent.removeEventListener('click', Florence.Handler, true); createWorkspace(data.uri, collectionId, '', null, true); $('#section-get_' + index).html('Copy link').off().one('click', function () { var uriCheck = getPathNameTrimLast(); var uriChecked = checkPathSlashes(uriCheck); data.sections[index].uri = uriChecked; putContent(collectionId, data.uri, JSON.stringify(data), success = function (response) { console.log("Updating completed " + response); Florence.Editor.isDirty = false; viewWorkspace(data.uri, collectionId, 'edit'); refreshPreview(data.uri); var iframeEvent = document.getElementById('iframe').contentWindow; iframeEvent.addEventListener('click', Florence.Handler, true); }, error = function (response) { if (response.status === 400) { sweetAlert("Cannot edit this page", "It is already part of another collection."); } else { handleApiError(response); } } ); }); }); } $("#section-edit_" + index).click(function () { var editedSectionValue = { "title": $('#section-title_' + index).val(), "markdown": $("#section-markdown_" + index).val() }; var saveContent = function (updatedContent) { data.sections[index].summary = updatedContent; data.sections[index].title = $('#section-title_' + index).val(); data.sections[index].uri = $('#section-uri_' + index).val(); updateContent(collectionId, data.uri, JSON.stringify(data)); }; loadMarkdownEditor(editedSectionValue, saveContent, data); }); // Delete $("#section-delete_" + index).click(function () { swal ({ title: "Warning", text: "Are you sure you want to delete?", type: "warning", showCancelButton: true, confirmButtonText: "Delete", cancelButtonText: "Cancel", closeOnConfirm: false }, function(result) { if (result === true) { $("#" + index).remove(); data.sections.splice(index, 1); updateContent(collectionId, data.uri, JSON.stringify(data)); swal({ title: "Deleted", text: "This section has been deleted", type: "success", timer: 2000 }); } }); }); // Tooltips $(function () { $('#section-uri_' + index).tooltip({ items: '#section-uri_' + index, content: 'Copy link or click Go to, navigate to page and click Copy link. Then add a title and click Edit', show: "slideDown", // show immediately open: function (event, ui) { ui.tooltip.hover( function () { $(this).fadeTo("slow", 0.5); }); } }); }); $(function () { $('#section-title_' + index).tooltip({ items: '#section-title_' + index, content: 'Type a title and click Edit', show: "slideDown", // show immediately open: function (event, ui) { ui.tooltip.hover( function () { $(this).fadeTo("slow", 0.5); }); } }); }); }); //Add new content $("#add-section").one('click', function () { swal ({ title: "Warning", text: "If you do not come back to this page, you will lose any unsaved changes", type: "warning", showCancelButton: true, confirmButtonText: "Continue", cancelButtonText: "Cancel" }, function(result) { if (result === true) { data.sections.push({uri: "", title: "", summary: ""}); updateContent(collectionId, data.uri, JSON.stringify(data)); } else { loadPageDataIntoEditor(data.uri, collectionId); } }); }); function sortableContent() { $("#sortable-section").sortable(); } sortableContent(); renderExternalLinkAccordionSection(collectionId, data, 'links', 'link'); // Save var editNav = $('.edit-nav'); editNav.off(); // remove any existing event handlers. editNav.on('click', '.btn-edit-save', function () { save(updateContent); }); // completed to review editNav.on('click', '.btn-edit-save-and-submit-for-review', function () { save(saveAndCompleteContent); }); // reviewed to approve editNav.on('click', '.btn-edit-save-and-submit-for-approval', function () { save(saveAndReviewContent); }); function save(onSave) { Florence.globalVars.pagePos = $(".workspace-edit").scrollTop(); // Sections var orderSection = $("#sortable-section").sortable('toArray'); $(orderSection).each(function (indexS, nameS) { var summary = data.sections[parseInt(nameS)].summary; // Fixes title or uri not saving unless markdown edited var title = $('#section-title_' + nameS).val(); var uri = $('#section-uri_' + nameS).val(); //var title = data.sections[parseInt(nameS)].title; //var uri = data.sections[parseInt(nameS)].uri; var uriChecked = checkPathSlashes(uri); newSections[indexS] = {uri: uriChecked, title: title, summary: summary}; }); data.sections = newSections; // External links var orderLink = $("#sortable-link").sortable('toArray'); $(orderLink).each(function (indexL, nameL) { var displayText = data.links[parseInt(nameL)].title; var link = $('#link-uri_' + nameL).val(); newLinks[indexL] = {uri: link, title: displayText}; }); data.links = newLinks; checkRenameUri(collectionId, data, renameUri, onSave); } }
/** * If you change this file, make sure to run `npm run require-script` and * copy-paste the output to README.md and index.html */ ;(function ( window, document, galiteName, scriptString, src, scriptTag, firstScriptTag ) { window[galiteName] = window[galiteName] || function () { ;(window[galiteName].q = window[galiteName].q || []).push(arguments) } scriptTag = document.createElement(scriptString) firstScriptTag = document.getElementsByTagName(scriptString)[0] scriptTag.async = true scriptTag.src = src firstScriptTag.parentNode.insertBefore(scriptTag, firstScriptTag) })( window, document, 'galite', 'script', 'https://cdn.jsdelivr.net/npm/ga-lite@2/dist/ga-lite.min.js' )
var player_a = { name : 'player a', color : 'rgb(0, 255, 0)', points : 0, starting_cells : [ {x:0,y:10}, {x:0,y:11}, {x:1,y:10}, {x:1,y:11}, {x:6,y:5}, {x:5,y:6} ] }; var player_b = { name : 'player b', color : 'rgb(255, 0, 0)', points : 0, starting_cells : [ {x:11,y:0}, {x:11,y:1}, {x:10,y:0}, {x:10,y:1}, {x:5,y:5}, {x:6,y:6} ] }; var game_state = { selected_div : 0, active_player : player_a, selected_piece : 0, first_move_in_turn : true, movement_queue : [], map : 0 };
{ return [let_index, let_value]; }
var main = (function() { /* Initialise state */ var resourceTiming, loadTimings, allTimings, perfData, allResourceTimings, memoryInital, memoryMax, sizeArray, filteredArrays = { scriptArray: [], imgArray: [], styleArray: [] }, wrapperEl = $('.chart-wrapper'), topTenEl = $('#chart-topTen').html(), pageStatsEl = $('#chart-pageStats').html(), noDownloadText = 'Wow! No new resource was downloaded!', noResourceText = 'Holy! No resource exists on page', noRequestsText = 'Great! No blocking resources, or assets were previously cached'; var renderHeader = function() { var template = $('#data-header').html(); var html = Mustache.to_html(template, loadTimings); $('.head-info').html(html); }; var renderBrokenPage = function() { var brokenHtml = $('#broken').html(); $('.wrapper').html(brokenHtml); }; var renderTopTen = function() { wrapperEl.html(topTenEl); var topTenRequests = resourceTiming.map(function(value) { var shortenedResource = value.resource.split('/').slice(-1)[0]; if (shortenedResource.length > 10) { shortenedResource = shortenedResource.substring(0, 10) + '..' + (shortenedResource.split('.').slice(-1)[0] || ''); } return { meta: shortenedResource, value: value.fetchTime.toFixed(2) } }); /* Render Bar Chart to show to request times */ if(topTenRequests.length) { new Chartist.Bar('.ct-chart', { labels: resourceTiming.map(function(value) { return value.resource }), series: topTenRequests }, { distributeSeries: true, height: '400px', plugins: [ Chartist.plugins.tooltip() ] }, [ ['screen and (min-width: 441px) and (max-width: 1440px)', { showPoint: false, axisX: { labelInterpolationFnc: function(value) { var name = value.split('/').slice(-1)[0]; if (name.length > 3) { var extn = name.split('.')[1] || ""; if (extn && extn.length > 3) extn = extn.substring(0, 3); name = name.substring(0, 3) + ".." + extn; } return name; } } }] ]); } else { $('.top-ten').addClass('no-requests-text').html(noRequestsText); } }; var filterArrayByType = function(type) { return allTimings.filter(function(resource) { return resource.initiatorType === type; }); }; var allResourceTimes = function() { return allTimings.reduce(function(prev, cur) { return prev + (cur.transferSize / 1024); }, 0).toFixed(2); }; var getResourceTimes = function(type) { return filteredArrays[type].reduce(function(prev, cur) { return prev + (cur.transferSize / 1024); }, 0); }; var getResouceCount = function(type) { return filteredArrays[type].length; }; var totalTimeTaken = function() { return sizeArray.reduce(function(prev, sizeObj) { return prev + sizeObj.size; }, 0); }; var totalResources = function() { return sizeArray.reduce(function(prev, cur) { return prev + cur.count; }, 0); }; var renderPageStats = function() { allResourceTimings = allResourceTimings || allResourceTimes(); var otherStats = { data: { totalSize: allResourceTimings, totalResources: allTimings.length, totalMemory: (memoryInitial / memoryMax * 100).toFixed(2) + ' %', totalTimeOpen: ((new Date().getTime() - perfData.loadEventEnd) / 1000).toFixed(1) + ' secs' } } var html = Mustache.to_html(pageStatsEl, otherStats); wrapperEl.html(html); /* Array to hold all pie chart info */ sizeArray = [{ name: 'Images', size: getResourceTimes('imgArray'), count: getResouceCount('imgArray') }, { name: 'Scripts', size: getResourceTimes('scriptArray'), count: getResouceCount('scriptArray') }, { name: 'Stylesheets', size: getResourceTimes('styleArray'), count: getResouceCount('styleArray') }]; var dataSize = { series: [] }; var dataCount = { series: sizeArray.map(function(resource) { return { value: resource.count, meta: resource.name } }) }; sizeArray.forEach(function(sizeObj) { if (sizeObj.size) { dataSize.series.push({ meta: sizeObj.name, value: sizeObj.size.toFixed(2) }); } }); if (dataSize.series.length) { new Chartist.Pie('.ct-size-pie', dataSize, { labelInterpolationFnc: function(value, series) { return value + ' (' + ((data.series[series] / totalTimeTaken()) * 100).toFixed(1) + '%) ' }, showLabel: false, height: '200px', labelDirection: 'explode', plugins: [ Chartist.plugins.tooltip() ] }); } else { $('.ct-size-pie').addClass('no-download-text').html(noDownloadText); } if (dataCount.series.length) { new Chartist.Pie('.ct-number-pie', dataCount, { labelInterpolationFnc: function(value, series) { return value + ' (' + ((data.series[series] / totalResources()) * 100).toFixed(1) + '%) ' }, showLabel: false, height: '200px', labelDirection: 'explode', plugins: [ Chartist.plugins.tooltip() ] }); } else { $('.ct-number-pie').addClass('no-resource-text').html(noResourceText); } }; var render = { header: renderHeader, topTen: renderTopTen, stats: renderPageStats }; var tabChange = function(e) { $('.nav-item').removeClass('selected'); $(e.target).addClass('selected'); var getViewToRender = $(e.target).attr('render'); _gaq.push(['_trackEvent', getViewToRender, 'clicked']); render[getViewToRender](); }; var addPageEventListeners = function() { document.getElementById('main-navigation').addEventListener('click', tabChange, false); }; var init = function() { chrome.tabs.getSelected(null, function(tab) { chrome.storage.local.get('loadTimes', function(data) { try { addPageEventListeners(); var tabPerformance = data.loadTimes['tab' + tab.id], paints = tabPerformance.chromeData, resources = tabPerformance.resources; perfData = tabPerformance.pageLoad, memoryInitial = tabPerformance.memoryInitial, memoryMax = tabPerformance.memoryMax; allTimings = resources; filteredArrays.scriptArray = filterArrayByType('script'), filteredArrays.imgArray = filterArrayByType('img'), filteredArrays.styleArray = filterArrayByType('link'); resourceTiming = resources.filter(function(value) { return value.initiatorType !== 'img' && value.initiatorType !== 'xmlhttprequest'; }).map(function(value, key) { return { fetchTime: value.duration, resource: value.name, type: value.initiatorType, size: value.transferSize } }).sort(function(a, b) { if (a.fetchTime > b.fetchTime) { return -1; } else { return 1 } }) .splice(0, 10); /* All the math required */ var contentLoaded = perfData.domContentLoadedEventEnd - perfData.fetchStart, onLoad = perfData.loadEventStart - perfData.navigationStart, firstPaint = (paints.firstPaintTime * 1000) - perfData.navigationStart; loadTimings = { data: { "contentLoaded": contentLoaded, "onLoad": onLoad, "firstPaint": firstPaint } }; /* render header */ renderHeader(loadTimings) /* call top ten */ renderTopTen(resourceTiming); } catch (e) { console.log(e); renderBrokenPage(); } }); }); }; return { init: init } })(); /* Load the awesome! */ main.init();
import UPopover from './UPopover' export { UPopover }
/** * @author Mat Groves http://matgroves.com/ @Doormat23 */ /** * The Graphics class contains methods used to draw primitive shapes such as lines, circles and rectangles to the display, and color and fill them. * * @class Graphics * @extends DisplayObjectContainer * @constructor */ PIXI.Graphics = function() { PIXI.DisplayObjectContainer.call(this); this.renderable = true; /** * The alpha value used when filling the Graphics object. * * @property fillAlpha * @type Number */ this.fillAlpha = 1; /** * The width (thickness) of any lines drawn. * * @property lineWidth * @type Number */ this.lineWidth = 0; /** * The color of any lines drawn. * * @property lineColor * @type String * @default 0 */ this.lineColor = 0; /** * Graphics data * * @property graphicsData * @type Array * @private */ this.graphicsData = []; /** * The tint applied to the graphic shape. This is a hex value. Apply a value of 0xFFFFFF to reset the tint. * * @property tint * @type Number * @default 0xFFFFFF */ this.tint = 0xFFFFFF; /** * The blend mode to be applied to the graphic shape. Apply a value of PIXI.blendModes.NORMAL to reset the blend mode. * * @property blendMode * @type Number * @default PIXI.blendModes.NORMAL; */ this.blendMode = PIXI.blendModes.NORMAL; /** * Current path * * @property currentPath * @type Object * @private */ this.currentPath = null; /** * Array containing some WebGL-related properties used by the WebGL renderer. * * @property _webGL * @type Array * @private */ this._webGL = []; /** * Whether this shape is being used as a mask. * * @property isMask * @type Boolean */ this.isMask = false; /** * The bounds' padding used for bounds calculation. * * @property boundsPadding * @type Number */ this.boundsPadding = 0; this._localBounds = new PIXI.Rectangle(0,0,1,1); /** * Used to detect if the graphics object has changed. If this is set to true then the graphics object will be recalculated. * * @property dirty * @type Boolean * @private */ this.dirty = true; /** * Used to detect if the webgl graphics object has changed. If this is set to true then the graphics object will be recalculated. * * @property webGLDirty * @type Boolean * @private */ this.webGLDirty = false; /** * Used to detect if the cached sprite object needs to be updated. * * @property cachedSpriteDirty * @type Boolean * @private */ this.cachedSpriteDirty = false; }; // constructor PIXI.Graphics.prototype = Object.create( PIXI.DisplayObjectContainer.prototype ); PIXI.Graphics.prototype.constructor = PIXI.Graphics; /** * Specifies the line style used for subsequent calls to Graphics methods such as the lineTo() method or the drawCircle() method. * * @method lineStyle * @param lineWidth {Number} width of the line to draw, will update the objects stored style * @param color {Number} color of the line to draw, will update the objects stored style * @param alpha {Number} alpha of the line to draw, will update the objects stored style * @return {Graphics} */ PIXI.Graphics.prototype.lineStyle = function(lineWidth, color, alpha) { this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (alpha === undefined) ? 1 : alpha; if (this.currentPath) { if (this.currentPath.shape.points.length) { // halfway through a line? start a new one! this.drawShape(new PIXI.Polygon(this.currentPath.shape.points.slice(-2))); } else { // otherwise its empty so lets just set the line properties this.currentPath.lineWidth = this.lineWidth; this.currentPath.lineColor = this.lineColor; this.currentPath.lineAlpha = this.lineAlpha; } } return this; }; /** * Moves the current drawing position to x, y. * * @method moveTo * @param x {Number} the X coordinate to move to * @param y {Number} the Y coordinate to move to * @return {Graphics} */ PIXI.Graphics.prototype.moveTo = function(x, y) { this.drawShape(new PIXI.Polygon([x, y])); return this; }; /** * Draws a line using the current line style from the current drawing position to (x, y); * The current drawing position is then set to (x, y). * * @method lineTo * @param x {Number} the X coordinate to draw to * @param y {Number} the Y coordinate to draw to * @return {Graphics} */ PIXI.Graphics.prototype.lineTo = function(x, y) { if (!this.currentPath) { this.moveTo(0, 0); } this.currentPath.shape.points.push(x, y); this.dirty = true; return this; }; /** * Calculate the points for a quadratic bezier curve and then draws it. * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c * * @method quadraticCurveTo * @param cpX {Number} Control point x * @param cpY {Number} Control point y * @param toX {Number} Destination point x * @param toY {Number} Destination point y * @return {Graphics} */ PIXI.Graphics.prototype.quadraticCurveTo = function(cpX, cpY, toX, toY) { if (this.currentPath) { if (this.currentPath.shape.points.length === 0) { this.currentPath.shape.points = [0, 0]; } } else { this.moveTo(0,0); } var xa, ya, n = 20, points = this.currentPath.shape.points; if (points.length === 0) { this.moveTo(0, 0); } var fromX = points[points.length - 2]; var fromY = points[points.length - 1]; var j = 0; for (var i = 1; i <= n; ++i) { j = i / n; xa = fromX + ( (cpX - fromX) * j ); ya = fromY + ( (cpY - fromY) * j ); points.push( xa + ( ((cpX + ( (toX - cpX) * j )) - xa) * j ), ya + ( ((cpY + ( (toY - cpY) * j )) - ya) * j ) ); } this.dirty = true; return this; }; /** * Calculate the points for a bezier curve and then draws it. * * @method bezierCurveTo * @param cpX {Number} Control point x * @param cpY {Number} Control point y * @param cpX2 {Number} Second Control point x * @param cpY2 {Number} Second Control point y * @param toX {Number} Destination point x * @param toY {Number} Destination point y * @return {Graphics} */ PIXI.Graphics.prototype.bezierCurveTo = function(cpX, cpY, cpX2, cpY2, toX, toY) { if (this.currentPath) { if (this.currentPath.shape.points.length === 0) { this.currentPath.shape.points = [0, 0]; } } else { this.moveTo(0,0); } var n = 20, dt, dt2, dt3, t2, t3, points = this.currentPath.shape.points; var fromX = points[points.length-2]; var fromY = points[points.length-1]; var j = 0; for (var i = 1; i <= n; ++i) { j = i / n; dt = (1 - j); dt2 = dt * dt; dt3 = dt2 * dt; t2 = j * j; t3 = t2 * j; points.push( dt3 * fromX + 3 * dt2 * j * cpX + 3 * dt * t2 * cpX2 + t3 * toX, dt3 * fromY + 3 * dt2 * j * cpY + 3 * dt * t2 * cpY2 + t3 * toY); } this.dirty = true; return this; }; /* * The arcTo() method creates an arc/curve between two tangents on the canvas. * * "borrowed" from https://code.google.com/p/fxcanvas/ - thanks google! * * @method arcTo * @param x1 {Number} The x-coordinate of the beginning of the arc * @param y1 {Number} The y-coordinate of the beginning of the arc * @param x2 {Number} The x-coordinate of the end of the arc * @param y2 {Number} The y-coordinate of the end of the arc * @param radius {Number} The radius of the arc * @return {Graphics} */ PIXI.Graphics.prototype.arcTo = function(x1, y1, x2, y2, radius) { if (this.currentPath) { if (this.currentPath.shape.points.length === 0) { this.currentPath.shape.points.push(x1, y1); } } else { this.moveTo(x1, y1); } var points = this.currentPath.shape.points, fromX = points[points.length-2], fromY = points[points.length-1], a1 = fromY - y1, b1 = fromX - x1, a2 = y2 - y1, b2 = x2 - x1, mm = Math.abs(a1 * b2 - b1 * a2); if (mm < 1.0e-8 || radius === 0) { if (points[points.length-2] !== x1 || points[points.length-1] !== y1) { points.push(x1, y1); } } else { var dd = a1 * a1 + b1 * b1, cc = a2 * a2 + b2 * b2, tt = a1 * a2 + b1 * b2, k1 = radius * Math.sqrt(dd) / mm, k2 = radius * Math.sqrt(cc) / mm, j1 = k1 * tt / dd, j2 = k2 * tt / cc, cx = k1 * b2 + k2 * b1, cy = k1 * a2 + k2 * a1, px = b1 * (k2 + j1), py = a1 * (k2 + j1), qx = b2 * (k1 + j2), qy = a2 * (k1 + j2), startAngle = Math.atan2(py - cy, px - cx), endAngle = Math.atan2(qy - cy, qx - cx); this.arc(cx + x1, cy + y1, radius, startAngle, endAngle, b1 * a2 > b2 * a1); } this.dirty = true; return this; }; /** * The arc method creates an arc/curve (used to create circles, or parts of circles). * * @method arc * @param cx {Number} The x-coordinate of the center of the circle * @param cy {Number} The y-coordinate of the center of the circle * @param radius {Number} The radius of the circle * @param startAngle {Number} The starting angle, in radians (0 is at the 3 o'clock position of the arc's circle) * @param endAngle {Number} The ending angle, in radians * @param anticlockwise {Boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. * @param segments {Number} Optional. The number of segments to use when calculating the arc. The default is 40. If you need more fidelity use a higher number. * @return {Graphics} */ PIXI.Graphics.prototype.arc = function(cx, cy, radius, startAngle, endAngle, anticlockwise, segments) { // If we do this we can never draw a full circle if (startAngle === endAngle) { return this; } if (anticlockwise === undefined) { anticlockwise = false; } if (segments === undefined) { segments = 40; } if (!anticlockwise && endAngle <= startAngle) { endAngle += Math.PI * 2; } else if (anticlockwise && startAngle <= endAngle) { startAngle += Math.PI * 2; } var sweep = anticlockwise ? (startAngle - endAngle) * -1 : (endAngle - startAngle); var segs = Math.ceil(Math.abs(sweep) / (Math.PI * 2)) * segments; // Sweep check - moved here because we don't want to do the moveTo below if the arc fails if (sweep === 0) { return this; } var startX = cx + Math.cos(startAngle) * radius; var startY = cy + Math.sin(startAngle) * radius; if (anticlockwise && this.filling) { this.moveTo(cx, cy); } else { this.moveTo(startX, startY); } // currentPath will always exist after calling a moveTo var points = this.currentPath.shape.points; var theta = sweep / (segs * 2); var theta2 = theta * 2; var cTheta = Math.cos(theta); var sTheta = Math.sin(theta); var segMinus = segs - 1; var remainder = (segMinus % 1) / segMinus; for (var i = 0; i <= segMinus; i++) { var real = i + remainder * i; var angle = ((theta) + startAngle + (theta2 * real)); var c = Math.cos(angle); var s = -Math.sin(angle); points.push(( (cTheta * c) + (sTheta * s) ) * radius + cx, ( (cTheta * -s) + (sTheta * c) ) * radius + cy); } this.dirty = true; return this; }; /** * Specifies a simple one-color fill that subsequent calls to other Graphics methods * (such as lineTo() or drawCircle()) use when drawing. * * @method beginFill * @param color {Number} the color of the fill * @param alpha {Number} the alpha of the fill * @return {Graphics} */ PIXI.Graphics.prototype.beginFill = function(color, alpha) { this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; if (this.currentPath) { if (this.currentPath.shape.points.length <= 2) { this.currentPath.fill = this.filling; this.currentPath.fillColor = this.fillColor; this.currentPath.fillAlpha = this.fillAlpha; } } return this; }; /** * Applies a fill to the lines and shapes that were added since the last call to the beginFill() method. * * @method endFill * @return {Graphics} */ PIXI.Graphics.prototype.endFill = function() { this.filling = false; this.fillColor = null; this.fillAlpha = 1; return this; }; /** * @method drawRect * * @param x {Number} The X coord of the top-left of the rectangle * @param y {Number} The Y coord of the top-left of the rectangle * @param width {Number} The width of the rectangle * @param height {Number} The height of the rectangle * @return {Graphics} */ PIXI.Graphics.prototype.drawRect = function(x, y, width, height) { this.drawShape(new PIXI.Rectangle(x, y, width, height)); return this; }; /** * @method drawRoundedRect * @param x {Number} The X coord of the top-left of the rectangle * @param y {Number} The Y coord of the top-left of the rectangle * @param width {Number} The width of the rectangle * @param height {Number} The height of the rectangle * @param radius {Number} Radius of the rectangle corners. In WebGL this must be a value between 0 and 9. */ PIXI.Graphics.prototype.drawRoundedRect = function(x, y, width, height, radius) { this.drawShape(new PIXI.RoundedRectangle(x, y, width, height, radius)); return this; }; /** * Draws a circle. * * @method drawCircle * @param x {Number} The X coordinate of the center of the circle * @param y {Number} The Y coordinate of the center of the circle * @param diameter {Number} The diameter of the circle * @return {Graphics} */ PIXI.Graphics.prototype.drawCircle = function(x, y, diameter) { this.drawShape(new PIXI.Circle(x, y, diameter)); return this; }; /** * Draws an ellipse. * * @method drawEllipse * @param x {Number} The X coordinate of the center of the ellipse * @param y {Number} The Y coordinate of the center of the ellipse * @param width {Number} The half width of the ellipse * @param height {Number} The half height of the ellipse * @return {Graphics} */ PIXI.Graphics.prototype.drawEllipse = function(x, y, width, height) { this.drawShape(new PIXI.Ellipse(x, y, width, height)); return this; }; /** * Draws a polygon using the given path. * * @method drawPolygon * @param path {Array|Phaser.Polygon} The path data used to construct the polygon. Can either be an array of points or a Phaser.Polygon object. * @return {Graphics} */ PIXI.Graphics.prototype.drawPolygon = function(path) { if (path instanceof Phaser.Polygon || path instanceof PIXI.Polygon) { path = path.points; } // prevents an argument assignment deopt // see section 3.1: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments var points = path; if (!Array.isArray(points)) { // prevents an argument leak deopt // see section 3.2: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments points = new Array(arguments.length); for (var i = 0; i < points.length; ++i) { points[i] = arguments[i]; } } this.drawShape(new Phaser.Polygon(points)); return this; }; /** * Clears the graphics that were drawn to this Graphics object, and resets fill and line style settings. * * @method clear * @return {Graphics} */ PIXI.Graphics.prototype.clear = function() { this.lineWidth = 0; this.filling = false; this.dirty = true; this.clearDirty = true; this.graphicsData = []; return this; }; /** * Useful function that returns a texture of the graphics object that can then be used to create sprites * This can be quite useful if your geometry is complicated and needs to be reused multiple times. * * @method generateTexture * @param [resolution=1] {Number} The resolution of the texture being generated * @param [scaleMode=0] {Number} Should be one of the PIXI.scaleMode consts * @param [padding=0] {Number} Add optional extra padding to the generated texture (default 0) * @return {Texture} a texture of the graphics object */ PIXI.Graphics.prototype.generateTexture = function(resolution, scaleMode, padding) { if (resolution === undefined) { resolution = 1; } if (scaleMode === undefined) { scaleMode = PIXI.scaleModes.DEFAULT; } if (padding === undefined) { padding = 0; } var bounds = this.getBounds(); bounds.width += padding; bounds.height += padding; var canvasBuffer = new PIXI.CanvasBuffer(bounds.width * resolution, bounds.height * resolution); var texture = PIXI.Texture.fromCanvas(canvasBuffer.canvas, scaleMode); texture.baseTexture.resolution = resolution; canvasBuffer.context.scale(resolution, resolution); canvasBuffer.context.translate(-bounds.x, -bounds.y); // Call here PIXI.CanvasGraphics.renderGraphics(this, canvasBuffer.context); return texture; }; /** * Renders the object using the WebGL renderer * * @method _renderWebGL * @param renderSession {RenderSession} * @private */ PIXI.Graphics.prototype._renderWebGL = function(renderSession) { // if the sprite is not visible or the alpha is 0 then no need to render this element if (this.visible === false || this.alpha === 0 || this.isMask === true) return; if (this._cacheAsBitmap) { if (this.dirty || this.cachedSpriteDirty) { this._generateCachedSprite(); // we will also need to update the texture on the gpu too! this.updateCachedSpriteTexture(); this.cachedSpriteDirty = false; this.dirty = false; } this._cachedSprite.worldAlpha = this.worldAlpha; PIXI.Sprite.prototype._renderWebGL.call(this._cachedSprite, renderSession); return; } else { renderSession.spriteBatch.stop(); renderSession.blendModeManager.setBlendMode(this.blendMode); if (this._mask) renderSession.maskManager.pushMask(this._mask, renderSession); if (this._filters) renderSession.filterManager.pushFilter(this._filterBlock); // check blend mode if (this.blendMode !== renderSession.spriteBatch.currentBlendMode) { renderSession.spriteBatch.currentBlendMode = this.blendMode; var blendModeWebGL = PIXI.blendModesWebGL[renderSession.spriteBatch.currentBlendMode]; renderSession.spriteBatch.gl.blendFunc(blendModeWebGL[0], blendModeWebGL[1]); } // check if the webgl graphic needs to be updated if (this.webGLDirty) { this.dirty = true; this.webGLDirty = false; } PIXI.WebGLGraphics.renderGraphics(this, renderSession); // only render if it has children! if (this.children.length) { renderSession.spriteBatch.start(); // simple render children! for (var i = 0; i < this.children.length; i++) { this.children[i]._renderWebGL(renderSession); } renderSession.spriteBatch.stop(); } if (this._filters) renderSession.filterManager.popFilter(); if (this._mask) renderSession.maskManager.popMask(this.mask, renderSession); renderSession.drawCount++; renderSession.spriteBatch.start(); } }; /** * Renders the object using the Canvas renderer * * @method _renderCanvas * @param renderSession {RenderSession} * @private */ PIXI.Graphics.prototype._renderCanvas = function(renderSession) { // if the sprite is not visible or the alpha is 0 then no need to render this element if (this.visible === false || this.alpha === 0 || this.isMask === true) return; // if the tint has changed, set the graphics object to dirty. if (this._prevTint !== this.tint) { this.dirty = true; this._prevTint = this.tint; } if (this._cacheAsBitmap) { if (this.dirty || this.cachedSpriteDirty) { this._generateCachedSprite(); // we will also need to update the texture this.updateCachedSpriteTexture(); this.cachedSpriteDirty = false; this.dirty = false; } this._cachedSprite.alpha = this.alpha; PIXI.Sprite.prototype._renderCanvas.call(this._cachedSprite, renderSession); return; } else { var context = renderSession.context; var transform = this.worldTransform; if (this.blendMode !== renderSession.currentBlendMode) { renderSession.currentBlendMode = this.blendMode; context.globalCompositeOperation = PIXI.blendModesCanvas[renderSession.currentBlendMode]; } if (this._mask) { renderSession.maskManager.pushMask(this._mask, renderSession); } var resolution = renderSession.resolution; context.setTransform(transform.a * resolution, transform.b * resolution, transform.c * resolution, transform.d * resolution, transform.tx * resolution, transform.ty * resolution); PIXI.CanvasGraphics.renderGraphics(this, context); // simple render children! for (var i = 0; i < this.children.length; i++) { this.children[i]._renderCanvas(renderSession); } if (this._mask) { renderSession.maskManager.popMask(renderSession); } } }; /** * Retrieves the bounds of the graphic shape as a rectangle object * * @method getBounds * @return {Rectangle} the rectangular bounding area */ PIXI.Graphics.prototype.getBounds = function(matrix) { if (!this._currentBounds) { // Return an empty object if the item is a mask! if (!this.renderable) { return PIXI.EmptyRectangle; } if (this.dirty) { this.updateLocalBounds(); this.webGLDirty = true; this.cachedSpriteDirty = true; this.dirty = false; } var bounds = this._localBounds; var w0 = bounds.x; var w1 = bounds.width + bounds.x; var h0 = bounds.y; var h1 = bounds.height + bounds.y; var worldTransform = matrix || this.worldTransform; var a = worldTransform.a; var b = worldTransform.b; var c = worldTransform.c; var d = worldTransform.d; var tx = worldTransform.tx; var ty = worldTransform.ty; var x1 = a * w1 + c * h1 + tx; var y1 = d * h1 + b * w1 + ty; var x2 = a * w0 + c * h1 + tx; var y2 = d * h1 + b * w0 + ty; var x3 = a * w0 + c * h0 + tx; var y3 = d * h0 + b * w0 + ty; var x4 = a * w1 + c * h0 + tx; var y4 = d * h0 + b * w1 + ty; var maxX = x1; var maxY = y1; var minX = x1; var minY = y1; minX = x2 < minX ? x2 : minX; minX = x3 < minX ? x3 : minX; minX = x4 < minX ? x4 : minX; minY = y2 < minY ? y2 : minY; minY = y3 < minY ? y3 : minY; minY = y4 < minY ? y4 : minY; maxX = x2 > maxX ? x2 : maxX; maxX = x3 > maxX ? x3 : maxX; maxX = x4 > maxX ? x4 : maxX; maxY = y2 > maxY ? y2 : maxY; maxY = y3 > maxY ? y3 : maxY; maxY = y4 > maxY ? y4 : maxY; this._bounds.x = minX; this._bounds.width = maxX - minX; this._bounds.y = minY; this._bounds.height = maxY - minY; this._currentBounds = this._bounds; } return this._currentBounds; }; /** * Tests if a point is inside this graphics object * * @param point {Point} the point to test * @return {boolean} the result of the test */ PIXI.Graphics.prototype.containsPoint = function( point ) { this.worldTransform.applyInverse(point, tempPoint); var graphicsData = this.graphicsData; for (var i = 0; i < graphicsData.length; i++) { var data = graphicsData[i]; if (!data.fill) { continue; } // only deal with fills.. if (data.shape) { if (data.shape.contains(tempPoint.x, tempPoint.y)) { return true; } } } return false; }; /** * Update the bounds of the object * * @method updateLocalBounds */ PIXI.Graphics.prototype.updateLocalBounds = function() { var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; if (this.graphicsData.length) { var shape, points, x, y, w, h; for (var i = 0; i < this.graphicsData.length; i++) { var data = this.graphicsData[i]; var type = data.type; var lineWidth = data.lineWidth; shape = data.shape; if (type === PIXI.Graphics.RECT || type === PIXI.Graphics.RREC) { x = shape.x - lineWidth / 2; y = shape.y - lineWidth / 2; w = shape.width + lineWidth; h = shape.height + lineWidth; minX = x < minX ? x : minX; maxX = x + w > maxX ? x + w : maxX; minY = y < minY ? y : minY; maxY = y + h > maxY ? y + h : maxY; } else if (type === PIXI.Graphics.CIRC) { x = shape.x; y = shape.y; w = shape.radius + lineWidth / 2; h = shape.radius + lineWidth / 2; minX = x - w < minX ? x - w : minX; maxX = x + w > maxX ? x + w : maxX; minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } else if (type === PIXI.Graphics.ELIP) { x = shape.x; y = shape.y; w = shape.width + lineWidth / 2; h = shape.height + lineWidth / 2; minX = x - w < minX ? x - w : minX; maxX = x + w > maxX ? x + w : maxX; minY = y - h < minY ? y - h : minY; maxY = y + h > maxY ? y + h : maxY; } else { // POLY - assumes points are sequential, not Point objects points = shape.points; for (var j = 0; j < points.length; j++) { if (points[j] instanceof Phaser.Point) { x = points[j].x; y = points[j].y; } else { x = points[j]; y = points[j + 1]; if (j < points.length - 1) { j++; } } minX = x - lineWidth < minX ? x - lineWidth : minX; maxX = x + lineWidth > maxX ? x + lineWidth : maxX; minY = y - lineWidth < minY ? y - lineWidth : minY; maxY = y + lineWidth > maxY ? y + lineWidth : maxY; } } } } else { minX = 0; maxX = 0; minY = 0; maxY = 0; } var padding = this.boundsPadding; this._localBounds.x = minX - padding; this._localBounds.width = (maxX - minX) + padding * 2; this._localBounds.y = minY - padding; this._localBounds.height = (maxY - minY) + padding * 2; }; /** * Generates the cached sprite when the sprite has cacheAsBitmap = true * * @method _generateCachedSprite * @private */ PIXI.Graphics.prototype._generateCachedSprite = function() { var bounds = this.getLocalBounds(); if (!this._cachedSprite) { var canvasBuffer = new PIXI.CanvasBuffer(bounds.width, bounds.height); var texture = PIXI.Texture.fromCanvas(canvasBuffer.canvas); this._cachedSprite = new PIXI.Sprite(texture); this._cachedSprite.buffer = canvasBuffer; this._cachedSprite.worldTransform = this.worldTransform; } else { this._cachedSprite.buffer.resize(bounds.width, bounds.height); } // leverage the anchor to account for the offset of the element this._cachedSprite.anchor.x = -(bounds.x / bounds.width); this._cachedSprite.anchor.y = -(bounds.y / bounds.height); // this._cachedSprite.buffer.context.save(); this._cachedSprite.buffer.context.translate(-bounds.x, -bounds.y); // make sure we set the alpha of the graphics to 1 for the render.. this.worldAlpha = 1; // now render the graphic.. PIXI.CanvasGraphics.renderGraphics(this, this._cachedSprite.buffer.context); this._cachedSprite.alpha = this.alpha; }; /** * Updates texture size based on canvas size * * @method updateCachedSpriteTexture * @private */ PIXI.Graphics.prototype.updateCachedSpriteTexture = function() { var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; texture.baseTexture.width = canvas.width; texture.baseTexture.height = canvas.height; texture.crop.width = texture.frame.width = canvas.width; texture.crop.height = texture.frame.height = canvas.height; cachedSprite._width = canvas.width; cachedSprite._height = canvas.height; // update the dirty base textures texture.baseTexture.dirty(); }; /** * Destroys a previous cached sprite. * * @method destroyCachedSprite */ PIXI.Graphics.prototype.destroyCachedSprite = function() { this._cachedSprite.texture.destroy(true); this._cachedSprite = null; }; /** * Draws the given shape to this Graphics object. Can be any of Circle, Rectangle, Ellipse, Line or Polygon. * * @method drawShape * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw. * @return {GraphicsData} The generated GraphicsData object. */ PIXI.Graphics.prototype.drawShape = function(shape) { if (this.currentPath) { // check current path! if (this.currentPath.shape.points.length <= 2) { this.graphicsData.pop(); } } this.currentPath = null; // Handle mixed-type polygons if (shape instanceof Phaser.Polygon) { shape = shape.clone(); shape.flatten(); } var data = new PIXI.GraphicsData(this.lineWidth, this.lineColor, this.lineAlpha, this.fillColor, this.fillAlpha, this.filling, shape); this.graphicsData.push(data); if (data.type === PIXI.Graphics.POLY) { data.shape.closed = this.filling; this.currentPath = data; } this.dirty = true; return data; }; /** * When cacheAsBitmap is set to true the graphics object will be rendered as if it was a sprite. * This is useful if your graphics element does not change often, as it will speed up the rendering of the object in exchange for taking up texture memory. * It is also useful if you need the graphics object to be anti-aliased, because it will be rendered using canvas. * This is not recommended if you are constantly redrawing the graphics element. * * @property cacheAsBitmap * @type Boolean * @default false * @private */ Object.defineProperty(PIXI.Graphics.prototype, "cacheAsBitmap", { get: function() { return this._cacheAsBitmap; }, set: function(value) { this._cacheAsBitmap = value; if (this._cacheAsBitmap) { this._generateCachedSprite(); } else { this.destroyCachedSprite(); } this.dirty = true; this.webGLDirty = true; } });
/** * 删除对象里面value值为null的键值对 * @param {*} data 接口返回的blob数据 * @param {*} name excel名称 * @param {*} callBack 导出成功/失败回调 回调返回{type:fail/success} fail情况下 返回{ type: "fail", code, msg } */ function exportXls(data, name = 'excel', callBack) { if (!data || data.size === 0) { callBack && callBack({type: 'fail', msg: '数据为空'}); return false; } let reader = new FileReader(); reader.readAsText(data, 'utf-8'); reader.onload = (e) => { try { let {code, msg} = JSON.parse(reader.result); if (code && code !== 200) { callBack && callBack({type: 'fail', code, msg}); return false; } else { _downFile(data, name); } callBack && callBack({type: 'success'}); } catch (error) { _downFile(data, name); callBack && callBack({type: 'success'}); } }; } function _downFile(data, fileName) { let blob = new Blob([data], {type: 'application/vnd.ms-excel,charset=UTF-8'}); if (window.navigator.msSaveOrOpenBlob) { navigator.msSaveBlob(blob, fileName + '.xlsx'); } else { var link = document.createElement('a'); link.href = window.URL.createObjectURL(blob); link.download = fileName + '.xlsx'; link.click(); window.URL.revokeObjectURL(link.href); } } export default exportXls;
$(document).ready(function(){ $("#title").hide().fadeIn(2000); $("#subtext").hide().fadeIn(2900); $("#login_button").hide().fadeIn(2000); $("#tour_button").hide().fadeIn(3300); $("#login_button").click(function(){ $("div#slide_div").animate({ "height": "toggle", "opacity": "toggle"}, 600); $("#login_button").hide(); }); $("#register_form_button").click(function(){ $("div#slide_div").animate({ "height": "toggle", "opacity": "toggle"}, 600,function(){ $("div#register_content").animate({ "height": "toggle", "opacity": "toggle"}, 600); }); $("#login_button").hide(); }); /** Function for login validation **/ $("#login_form_button").click(function(){ var username_field = $("#input_field_name").val(); var password_field = $("#input_field_pw").val(); if(username_field.length !=0 && password_field != 0) { //alert("User name can't be blank"); $("body").fadeOut(1800); } }); });
/** * Created by souzaalves on 11/05/16. */ function Model (path,server){ "use strict"; console.log('Models ready!'); var path = require('path'); var Schema = require(path.resolve('back_end/schemas/Schema')),Mongoclient = require('mongodb').MongoClient, assert = require('assert'), url = 'mongodb://localhost:27017/tangible3d', ObjectId = require('mongodb').ObjectID; this.id = ObjectId; this.schema = new Schema(path,server); this.crud = { create : (db,collection,filters,callback) => { db.collection(collection).insert( filters, function(err, result) { assert.equal(null,err); console.log(`Insert a document into the Tangible3D collection:${collection}`); callback(); }); }, update :(db,collection,filters,schema,callback) => { db.collection(collection).updateOne( filters, { $set: schema, $currentDate: {lastModified: true} }, function (err,results) { console.log(`Updated a document into the Tangible3D collection:${collection}`); callback(); } ) }, read:(db,collection,filters,callback) => { var cursor = db.collection(collection).find(filters); /* toArray(function(err,doc){ console.dir(doc); });*/ console.dir(filters); var items = []; cursor.each(function(err,doc){ assert.equal(err,null); if (doc != null){ //console.dir(doc); items.push(doc); console.log(`Read a document into the Tangible3D collection:${collection} filter: ${filters}`); } else { callback(err,items); } }); return items }, replace : (db,collection,filters,replacer,callback) => { db.collection(collection).replaceOne( filters, replacer, function(err, results) { console.log(results); console.log(`Replace a document into the Tangible3D collection:${collection}`); callback(); }); }, delete : (db,collection,filters,callback) => { db.collection(collection).deleteOne( filters, function(err,results){ console.log(results.results); console.log(`Deleted a document into the Tangible3D collection:${collection}`); callback(); } ) }, makeIndex: (db,collection,filters,options,callback) => { db.collection(collection).createIndex(filters, {unique:false}, function (err, results) { console.log(`makeIndex a document into the Tangible3D collection:${collection}`); console.log(results); callback(); } ) }, Mongo_client : Mongoclient.connect }; this.models = { home : new require('./home_mdl')(this.crud,this.schema.schemas.home,url,assert,this.operation), contact : new require('./contact_mdl')(this.crud,this.schema.schemas.contact,url,assert,this.operation), print : new require('./print_mdl')(this.crud,this.schema.schemas.print,url,assert,this.operation), data : new require('./data_mdl')(this.crud,this.schema.schemas.data,url,assert,this.operation), pay : new require('./pay_mdl')(this.crud,this.schema.schemas.pay,url,assert,this.operation), confirm : new require('./confirm_mdl')(this.crud,this.schema.schemas.confirm,url,assert,this.operation) }; } //console.log(Tangible3D.Router.routes.confirm); module.exports = Model;
/* * GET home page. */ exports.view = function(req, res){ res.render('index' , { 'projects': [ { 'name': 'Waiting in Line', 'image': 'lorempixel.people.1.jpeg', 'id': 'project1' }, { 'name': 'Needfinding', 'image': 'lorempixel.city.1.jpeg', 'id': 'project2' }, { 'name': 'Prototyping', 'image': 'lorempixel.technics.1.jpeg', 'id': 'project3' }, { 'name': 'Heuristic Evaluation', 'image': 'lorempixel.abstract.1.jpeg', 'id': 'project4' }, { 'name': 'Skeleton and a Plan', 'image': 'lorempixel.abstract.8.jpeg', 'id': 'project5' }, { 'name': 'Meat on the Bones', 'image': 'lorempixel.people.2.jpeg', 'id': 'project6' }, { 'name': 'Ready for Testing', 'image': 'lorempixel.technics.2.jpeg', 'id': 'project7' }, { 'name': 'User Test Results and Online Test Proposal', 'image': 'lorempixel.city.2.jpeg', 'id': 'project8' } ] }); };
var Buffer = require('buffer').Buffer var fs = require('fs') var test = require('tape') var http = require('../..') test('requestTimeout', function (t) { var req = http.get({ path: '/browserify.png?copies=5', requestTimeout: 10 // ms }, function (res) { res.on('data', function (data) { }) res.on('end', function () { t.fail('request completed (should have timed out)') }) }) req.on('requestTimeout', function () { t.pass('got requestTimeout') t.end() }) }) // TODO: reenable this if there's a way to make it simultaneously // fast and reliable test.skip('no requestTimeout after success', function (t) { var req = http.get({ path: '/basic.txt', requestTimeout: 50000 // ms }, function (res) { res.on('data', function (data) { }) res.on('end', function () { t.pass('success') global.setTimeout(function () { t.end() }, 50000) }) }) req.on('requestTimeout', function () { t.fail('unexpected requestTimeout') }) }) test('setTimeout', function (t) { t.plan(2) var req = http.get({ path: '/browserify.png?copies=5' }, function (res) { res.on('data', function (data) { }) res.on('end', function () { t.fail('request completed (should have timed out)') }) }) req.setTimeout(10, function () { t.pass('got setTimeout callback') }) req.on('timeout', function () { t.pass('got timeout') }) })
$("#addTripForm").unbind().bind('submit',function(){ var form = $(this); var url = form.attr('action'); var type = form.attr('method'); $.ajax({ url:url, type:type, data:form.serialize(), dataType:'text', success:function(data){ $("#tripResponse").html(data); } }); return false; });
module.exports = function (sub, base) { for (var i = 0, keys = Object.keys(base.prototype) ; i < keys.length; i++) { sub.prototype[keys[i]] = base.prototype[keys[i]]; } };
define(['exports', 'aurelia-logging', 'aurelia-route-recognizer', 'aurelia-dependency-injection', 'aurelia-history', 'aurelia-event-aggregator'], function (exports, _aureliaLogging, _aureliaRouteRecognizer, _aureliaDependencyInjection, _aureliaHistory, _aureliaEventAggregator) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.AppRouter = exports.PipelineProvider = exports.LoadRouteStep = exports.RouteLoader = exports.ActivateNextStep = exports.DeactivatePreviousStep = exports.CanActivateNextStep = exports.CanDeactivatePreviousStep = exports.Router = exports.BuildNavigationPlanStep = exports.activationStrategy = exports.RouterConfiguration = exports.Pipeline = exports.pipelineStatus = exports.RedirectToRoute = exports.Redirect = exports.NavModel = exports.NavigationInstruction = exports.CommitChangesStep = undefined; exports._normalizeAbsolutePath = _normalizeAbsolutePath; exports._createRootedPath = _createRootedPath; exports._resolveUrl = _resolveUrl; exports._ensureArrayWithSingleRoutePerConfig = _ensureArrayWithSingleRoutePerConfig; exports.isNavigationCommand = isNavigationCommand; exports._buildNavigationPlan = _buildNavigationPlan; var LogManager = _interopRequireWildcard(_aureliaLogging); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _normalizeAbsolutePath(path, hasPushState) { var absolute = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; if (!hasPushState && path[0] !== '#') { path = '#' + path; } if (hasPushState && absolute) { path = path.substring(1, path.length); } return path; } function _createRootedPath(fragment, baseUrl, hasPushState, absolute) { if (isAbsoluteUrl.test(fragment)) { return fragment; } var path = ''; if (baseUrl.length && baseUrl[0] !== '/') { path += '/'; } path += baseUrl; if ((!path.length || path[path.length - 1] !== '/') && fragment[0] !== '/') { path += '/'; } if (path.length && path[path.length - 1] === '/' && fragment[0] === '/') { path = path.substring(0, path.length - 1); } return _normalizeAbsolutePath(path + fragment, hasPushState, absolute); } function _resolveUrl(fragment, baseUrl, hasPushState) { if (isRootedPath.test(fragment)) { return _normalizeAbsolutePath(fragment, hasPushState); } return _createRootedPath(fragment, baseUrl, hasPushState); } function _ensureArrayWithSingleRoutePerConfig(config) { var routeConfigs = []; if (Array.isArray(config.route)) { for (var i = 0, ii = config.route.length; i < ii; ++i) { var current = Object.assign({}, config); current.route = config.route[i]; routeConfigs.push(current); } } else { routeConfigs.push(Object.assign({}, config)); } return routeConfigs; } var isRootedPath = /^#?\//; var isAbsoluteUrl = /^([a-z][a-z0-9+\-.]*:)?\/\//i; var CommitChangesStep = exports.CommitChangesStep = function () { function CommitChangesStep() { } CommitChangesStep.prototype.run = function run(navigationInstruction, next) { return navigationInstruction._commitChanges(true).then(function () { navigationInstruction._updateTitle(); return next(); }); }; return CommitChangesStep; }(); var NavigationInstruction = exports.NavigationInstruction = function () { function NavigationInstruction(init) { this.plan = null; this.options = {}; Object.assign(this, init); this.params = this.params || {}; this.viewPortInstructions = {}; var ancestorParams = []; var current = this; do { var currentParams = Object.assign({}, current.params); if (current.config && current.config.hasChildRouter) { delete currentParams[current.getWildCardName()]; } ancestorParams.unshift(currentParams); current = current.parentInstruction; } while (current); var allParams = Object.assign.apply(Object, [{}, this.queryParams].concat(ancestorParams)); this.lifecycleArgs = [allParams, this.config, this]; } NavigationInstruction.prototype.getAllInstructions = function getAllInstructions() { var instructions = [this]; for (var _key in this.viewPortInstructions) { var childInstruction = this.viewPortInstructions[_key].childNavigationInstruction; if (childInstruction) { instructions.push.apply(instructions, childInstruction.getAllInstructions()); } } return instructions; }; NavigationInstruction.prototype.getAllPreviousInstructions = function getAllPreviousInstructions() { return this.getAllInstructions().map(function (c) { return c.previousInstruction; }).filter(function (c) { return c; }); }; NavigationInstruction.prototype.addViewPortInstruction = function addViewPortInstruction(viewPortName, strategy, moduleId, component) { var config = Object.assign({}, this.lifecycleArgs[1], { currentViewPort: viewPortName }); var viewportInstruction = this.viewPortInstructions[viewPortName] = { name: viewPortName, strategy: strategy, moduleId: moduleId, component: component, childRouter: component.childRouter, lifecycleArgs: [].concat(this.lifecycleArgs[0], config, this.lifecycleArgs[2]) }; return viewportInstruction; }; NavigationInstruction.prototype.getWildCardName = function getWildCardName() { var wildcardIndex = this.config.route.lastIndexOf('*'); return this.config.route.substr(wildcardIndex + 1); }; NavigationInstruction.prototype.getWildcardPath = function getWildcardPath() { var wildcardName = this.getWildCardName(); var path = this.params[wildcardName] || ''; if (this.queryString) { path += '?' + this.queryString; } return path; }; NavigationInstruction.prototype.getBaseUrl = function getBaseUrl() { var _this = this; var fragment = decodeURI(this.fragment); if (fragment === '') { var nonEmptyRoute = this.router.routes.find(function (route) { return route.name === _this.config.name && route.route !== ''; }); if (nonEmptyRoute) { fragment = nonEmptyRoute.route; } } if (!this.params) { return encodeURI(fragment); } var wildcardName = this.getWildCardName(); var path = this.params[wildcardName] || ''; if (!path) { return encodeURI(fragment); } return encodeURI(fragment.substr(0, fragment.lastIndexOf(path))); }; NavigationInstruction.prototype._commitChanges = function _commitChanges(waitToSwap) { var _this2 = this; var router = this.router; router.currentInstruction = this; if (this.previousInstruction) { this.previousInstruction.config.navModel.isActive = false; } this.config.navModel.isActive = true; router._refreshBaseUrl(); router.refreshNavigation(); var loads = []; var delaySwaps = []; var _loop = function _loop(viewPortName) { var viewPortInstruction = _this2.viewPortInstructions[viewPortName]; var viewPort = router.viewPorts[viewPortName]; if (!viewPort) { throw new Error('There was no router-view found in the view for ' + viewPortInstruction.moduleId + '.'); } if (viewPortInstruction.strategy === activationStrategy.replace) { if (viewPortInstruction.childNavigationInstruction && viewPortInstruction.childNavigationInstruction.parentCatchHandler) { loads.push(viewPortInstruction.childNavigationInstruction._commitChanges(waitToSwap)); } else { if (waitToSwap) { delaySwaps.push({ viewPort: viewPort, viewPortInstruction: viewPortInstruction }); } loads.push(viewPort.process(viewPortInstruction, waitToSwap).then(function (x) { if (viewPortInstruction.childNavigationInstruction) { return viewPortInstruction.childNavigationInstruction._commitChanges(waitToSwap); } })); } } else { if (viewPortInstruction.childNavigationInstruction) { loads.push(viewPortInstruction.childNavigationInstruction._commitChanges(waitToSwap)); } } }; for (var viewPortName in this.viewPortInstructions) { _loop(viewPortName); } return Promise.all(loads).then(function () { delaySwaps.forEach(function (x) { return x.viewPort.swap(x.viewPortInstruction); }); return null; }).then(function () { return prune(_this2); }); }; NavigationInstruction.prototype._updateTitle = function _updateTitle() { var title = this._buildTitle(this.router.titleSeparator); if (title) { this.router.history.setTitle(title); } }; NavigationInstruction.prototype._buildTitle = function _buildTitle() { var separator = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ' | '; var title = ''; var childTitles = []; if (this.config.navModel.title) { title = this.router.transformTitle(this.config.navModel.title); } for (var viewPortName in this.viewPortInstructions) { var _viewPortInstruction = this.viewPortInstructions[viewPortName]; if (_viewPortInstruction.childNavigationInstruction) { var childTitle = _viewPortInstruction.childNavigationInstruction._buildTitle(separator); if (childTitle) { childTitles.push(childTitle); } } } if (childTitles.length) { title = childTitles.join(separator) + (title ? separator : '') + title; } if (this.router.title) { title += (title ? separator : '') + this.router.transformTitle(this.router.title); } return title; }; return NavigationInstruction; }(); function prune(instruction) { instruction.previousInstruction = null; instruction.plan = null; } var NavModel = exports.NavModel = function () { function NavModel(router, relativeHref) { this.isActive = false; this.title = null; this.href = null; this.relativeHref = null; this.settings = {}; this.config = null; this.router = router; this.relativeHref = relativeHref; } NavModel.prototype.setTitle = function setTitle(title) { this.title = title; if (this.isActive) { this.router.updateTitle(); } }; return NavModel; }(); function isNavigationCommand(obj) { return obj && typeof obj.navigate === 'function'; } var Redirect = exports.Redirect = function () { function Redirect(url) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; this.url = url; this.options = Object.assign({ trigger: true, replace: true }, options); this.shouldContinueProcessing = false; } Redirect.prototype.setRouter = function setRouter(router) { this.router = router; }; Redirect.prototype.navigate = function navigate(appRouter) { var navigatingRouter = this.options.useAppRouter ? appRouter : this.router || appRouter; navigatingRouter.navigate(this.url, this.options); }; return Redirect; }(); var RedirectToRoute = exports.RedirectToRoute = function () { function RedirectToRoute(route) { var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; this.route = route; this.params = params; this.options = Object.assign({ trigger: true, replace: true }, options); this.shouldContinueProcessing = false; } RedirectToRoute.prototype.setRouter = function setRouter(router) { this.router = router; }; RedirectToRoute.prototype.navigate = function navigate(appRouter) { var navigatingRouter = this.options.useAppRouter ? appRouter : this.router || appRouter; navigatingRouter.navigateToRoute(this.route, this.params, this.options); }; return RedirectToRoute; }(); var pipelineStatus = exports.pipelineStatus = { completed: 'completed', canceled: 'canceled', rejected: 'rejected', running: 'running' }; var Pipeline = exports.Pipeline = function () { function Pipeline() { this.steps = []; } Pipeline.prototype.addStep = function addStep(step) { var run = void 0; if (typeof step === 'function') { run = step; } else if (typeof step.getSteps === 'function') { var steps = step.getSteps(); for (var i = 0, l = steps.length; i < l; i++) { this.addStep(steps[i]); } return this; } else { run = step.run.bind(step); } this.steps.push(run); return this; }; Pipeline.prototype.run = function run(instruction) { var index = -1; var steps = this.steps; function next() { index++; if (index < steps.length) { var currentStep = steps[index]; try { return currentStep(instruction, next); } catch (e) { return next.reject(e); } } else { return next.complete(); } } next.complete = createCompletionHandler(next, pipelineStatus.completed); next.cancel = createCompletionHandler(next, pipelineStatus.canceled); next.reject = createCompletionHandler(next, pipelineStatus.rejected); return next(); }; return Pipeline; }(); function createCompletionHandler(next, status) { return function (output) { return Promise.resolve({ status: status, output: output, completed: status === pipelineStatus.completed }); }; } var RouterConfiguration = exports.RouterConfiguration = function () { function RouterConfiguration() { this.instructions = []; this.options = {}; this.pipelineSteps = []; } RouterConfiguration.prototype.addPipelineStep = function addPipelineStep(name, step) { if (step === null || step === undefined) { throw new Error('Pipeline step cannot be null or undefined.'); } this.pipelineSteps.push({ name: name, step: step }); return this; }; RouterConfiguration.prototype.addAuthorizeStep = function addAuthorizeStep(step) { return this.addPipelineStep('authorize', step); }; RouterConfiguration.prototype.addPreActivateStep = function addPreActivateStep(step) { return this.addPipelineStep('preActivate', step); }; RouterConfiguration.prototype.addPreRenderStep = function addPreRenderStep(step) { return this.addPipelineStep('preRender', step); }; RouterConfiguration.prototype.addPostRenderStep = function addPostRenderStep(step) { return this.addPipelineStep('postRender', step); }; RouterConfiguration.prototype.fallbackRoute = function fallbackRoute(fragment) { this._fallbackRoute = fragment; return this; }; RouterConfiguration.prototype.map = function map(route) { if (Array.isArray(route)) { route.forEach(this.map.bind(this)); return this; } return this.mapRoute(route); }; RouterConfiguration.prototype.useViewPortDefaults = function useViewPortDefaults(viewPortConfig) { this.viewPortDefaults = viewPortConfig; return this; }; RouterConfiguration.prototype.mapRoute = function mapRoute(config) { this.instructions.push(function (router) { var routeConfigs = _ensureArrayWithSingleRoutePerConfig(config); var navModel = void 0; for (var i = 0, ii = routeConfigs.length; i < ii; ++i) { var _routeConfig = routeConfigs[i]; _routeConfig.settings = _routeConfig.settings || {}; if (!navModel) { navModel = router.createNavModel(_routeConfig); } router.addRoute(_routeConfig, navModel); } }); return this; }; RouterConfiguration.prototype.mapUnknownRoutes = function mapUnknownRoutes(config) { this.unknownRouteConfig = config; return this; }; RouterConfiguration.prototype.exportToRouter = function exportToRouter(router) { var instructions = this.instructions; for (var i = 0, ii = instructions.length; i < ii; ++i) { instructions[i](router); } if (this.title) { router.title = this.title; } if (this.titleSeparator) { router.titleSeparator = this.titleSeparator; } if (this.unknownRouteConfig) { router.handleUnknownRoutes(this.unknownRouteConfig); } if (this._fallbackRoute) { router.fallbackRoute = this._fallbackRoute; } if (this.viewPortDefaults) { router.useViewPortDefaults(this.viewPortDefaults); } Object.assign(router.options, this.options); var pipelineSteps = this.pipelineSteps; if (pipelineSteps.length) { if (!router.isRoot) { throw new Error('Pipeline steps can only be added to the root router'); } var pipelineProvider = router.pipelineProvider; for (var _i = 0, _ii = pipelineSteps.length; _i < _ii; ++_i) { var _pipelineSteps$_i = pipelineSteps[_i], _name = _pipelineSteps$_i.name, _step = _pipelineSteps$_i.step; pipelineProvider.addStep(_name, _step); } } }; return RouterConfiguration; }(); var activationStrategy = exports.activationStrategy = { noChange: 'no-change', invokeLifecycle: 'invoke-lifecycle', replace: 'replace' }; var BuildNavigationPlanStep = exports.BuildNavigationPlanStep = function () { function BuildNavigationPlanStep() { } BuildNavigationPlanStep.prototype.run = function run(navigationInstruction, next) { return _buildNavigationPlan(navigationInstruction).then(function (plan) { if (plan instanceof Redirect) { return next.cancel(plan); } navigationInstruction.plan = plan; return next(); }).catch(next.cancel); }; return BuildNavigationPlanStep; }(); function _buildNavigationPlan(instruction, forceLifecycleMinimum) { var config = instruction.config; if ('redirect' in config) { var _router = instruction.router; return _router._createNavigationInstruction(config.redirect).then(function (newInstruction) { var params = Object.keys(newInstruction.params).length ? instruction.params : {}; var redirectLocation = _router.generate(newInstruction.config.name, params, instruction.options); if (instruction.queryString) { redirectLocation += '?' + instruction.queryString; } return Promise.resolve(new Redirect(redirectLocation)); }); } var prev = instruction.previousInstruction; var plan = {}; var defaults = instruction.router.viewPortDefaults; if (prev) { var newParams = hasDifferentParameterValues(prev, instruction); var pending = []; var _loop2 = function _loop2(viewPortName) { var prevViewPortInstruction = prev.viewPortInstructions[viewPortName]; var nextViewPortConfig = viewPortName in config.viewPorts ? config.viewPorts[viewPortName] : prevViewPortInstruction; if (nextViewPortConfig.moduleId === null && viewPortName in instruction.router.viewPortDefaults) { nextViewPortConfig = defaults[viewPortName]; } var viewPortPlan = plan[viewPortName] = { name: viewPortName, config: nextViewPortConfig, prevComponent: prevViewPortInstruction.component, prevModuleId: prevViewPortInstruction.moduleId }; if (prevViewPortInstruction.moduleId !== nextViewPortConfig.moduleId) { viewPortPlan.strategy = activationStrategy.replace; } else if ('determineActivationStrategy' in prevViewPortInstruction.component.viewModel) { var _prevViewPortInstruct; viewPortPlan.strategy = (_prevViewPortInstruct = prevViewPortInstruction.component.viewModel).determineActivationStrategy.apply(_prevViewPortInstruct, instruction.lifecycleArgs); } else if (config.activationStrategy) { viewPortPlan.strategy = config.activationStrategy; } else if (newParams || forceLifecycleMinimum) { viewPortPlan.strategy = activationStrategy.invokeLifecycle; } else { viewPortPlan.strategy = activationStrategy.noChange; } if (viewPortPlan.strategy !== activationStrategy.replace && prevViewPortInstruction.childRouter) { var path = instruction.getWildcardPath(); var task = prevViewPortInstruction.childRouter._createNavigationInstruction(path, instruction).then(function (childInstruction) { viewPortPlan.childNavigationInstruction = childInstruction; return _buildNavigationPlan(childInstruction, viewPortPlan.strategy === activationStrategy.invokeLifecycle).then(function (childPlan) { if (childPlan instanceof Redirect) { return Promise.reject(childPlan); } childInstruction.plan = childPlan; }); }); pending.push(task); } }; for (var viewPortName in prev.viewPortInstructions) { _loop2(viewPortName); } return Promise.all(pending).then(function () { return plan; }); } for (var viewPortName in config.viewPorts) { var viewPortConfig = config.viewPorts[viewPortName]; if (viewPortConfig.moduleId === null && viewPortName in instruction.router.viewPortDefaults) { viewPortConfig = defaults[viewPortName]; } plan[viewPortName] = { name: viewPortName, strategy: activationStrategy.replace, config: viewPortConfig }; } return Promise.resolve(plan); } function hasDifferentParameterValues(prev, next) { var prevParams = prev.params; var nextParams = next.params; var nextWildCardName = next.config.hasChildRouter ? next.getWildCardName() : null; for (var _key2 in nextParams) { if (_key2 === nextWildCardName) { continue; } if (prevParams[_key2] !== nextParams[_key2]) { return true; } } for (var _key3 in prevParams) { if (_key3 === nextWildCardName) { continue; } if (prevParams[_key3] !== nextParams[_key3]) { return true; } } if (!next.options.compareQueryParams) { return false; } var prevQueryParams = prev.queryParams; var nextQueryParams = next.queryParams; for (var _key4 in nextQueryParams) { if (prevQueryParams[_key4] !== nextQueryParams[_key4]) { return true; } } for (var _key5 in prevQueryParams) { if (prevQueryParams[_key5] !== nextQueryParams[_key5]) { return true; } } return false; } var Router = exports.Router = function () { function Router(container, history) { var _this3 = this; this.parent = null; this.options = {}; this.viewPortDefaults = {}; this.transformTitle = function (title) { if (_this3.parent) { return _this3.parent.transformTitle(title); } return title; }; this.container = container; this.history = history; this.reset(); } Router.prototype.reset = function reset() { var _this4 = this; this.viewPorts = {}; this.routes = []; this.baseUrl = ''; this.isConfigured = false; this.isNavigating = false; this.isExplicitNavigation = false; this.isExplicitNavigationBack = false; this.isNavigatingFirst = false; this.isNavigatingNew = false; this.isNavigatingRefresh = false; this.isNavigatingForward = false; this.isNavigatingBack = false; this.navigation = []; this.currentInstruction = null; this.viewPortDefaults = {}; this._fallbackOrder = 100; this._recognizer = new _aureliaRouteRecognizer.RouteRecognizer(); this._childRecognizer = new _aureliaRouteRecognizer.RouteRecognizer(); this._configuredPromise = new Promise(function (resolve) { _this4._resolveConfiguredPromise = resolve; }); }; Router.prototype.registerViewPort = function registerViewPort(viewPort, name) { name = name || 'default'; this.viewPorts[name] = viewPort; }; Router.prototype.ensureConfigured = function ensureConfigured() { return this._configuredPromise; }; Router.prototype.configure = function configure(callbackOrConfig) { var _this5 = this; this.isConfigured = true; var result = callbackOrConfig; var config = void 0; if (typeof callbackOrConfig === 'function') { config = new RouterConfiguration(); result = callbackOrConfig(config); } return Promise.resolve(result).then(function (c) { if (c && c.exportToRouter) { config = c; } config.exportToRouter(_this5); _this5.isConfigured = true; _this5._resolveConfiguredPromise(); }); }; Router.prototype.navigate = function navigate(fragment, options) { if (!this.isConfigured && this.parent) { return this.parent.navigate(fragment, options); } this.isExplicitNavigation = true; return this.history.navigate(_resolveUrl(fragment, this.baseUrl, this.history._hasPushState), options); }; Router.prototype.navigateToRoute = function navigateToRoute(route, params, options) { var path = this.generate(route, params); return this.navigate(path, options); }; Router.prototype.navigateBack = function navigateBack() { this.isExplicitNavigationBack = true; this.history.navigateBack(); }; Router.prototype.createChild = function createChild(container) { var childRouter = new Router(container || this.container.createChild(), this.history); childRouter.parent = this; return childRouter; }; Router.prototype.generate = function generate(name, params) { var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var hasRoute = this._recognizer.hasRoute(name); if ((!this.isConfigured || !hasRoute) && this.parent) { return this.parent.generate(name, params); } if (!hasRoute) { throw new Error('A route with name \'' + name + '\' could not be found. Check that `name: \'' + name + '\'` was specified in the route\'s config.'); } var path = this._recognizer.generate(name, params); var rootedPath = _createRootedPath(path, this.baseUrl, this.history._hasPushState, options.absolute); return options.absolute ? '' + this.history.getAbsoluteRoot() + rootedPath : rootedPath; }; Router.prototype.createNavModel = function createNavModel(config) { var navModel = new NavModel(this, 'href' in config ? config.href : config.route); navModel.title = config.title; navModel.order = config.nav; navModel.href = config.href; navModel.settings = config.settings; navModel.config = config; return navModel; }; Router.prototype.addRoute = function addRoute(config, navModel) { if (Array.isArray(config.route)) { var routeConfigs = _ensureArrayWithSingleRoutePerConfig(config); routeConfigs.forEach(this.addRoute.bind(this)); return; } validateRouteConfig(config, this.routes); if (!('viewPorts' in config) && !config.navigationStrategy) { config.viewPorts = { 'default': { moduleId: config.moduleId, view: config.view } }; } if (!navModel) { navModel = this.createNavModel(config); } this.routes.push(config); var path = config.route; if (path.charAt(0) === '/') { path = path.substr(1); } var caseSensitive = config.caseSensitive === true; var state = this._recognizer.add({ path: path, handler: config, caseSensitive: caseSensitive }); if (path) { var _settings = config.settings; delete config.settings; var withChild = JSON.parse(JSON.stringify(config)); config.settings = _settings; withChild.route = path + '/*childRoute'; withChild.hasChildRouter = true; this._childRecognizer.add({ path: withChild.route, handler: withChild, caseSensitive: caseSensitive }); withChild.navModel = navModel; withChild.settings = config.settings; withChild.navigationStrategy = config.navigationStrategy; } config.navModel = navModel; if ((navModel.order || navModel.order === 0) && this.navigation.indexOf(navModel) === -1) { if (!navModel.href && navModel.href !== '' && (state.types.dynamics || state.types.stars)) { throw new Error('Invalid route config for "' + config.route + '" : dynamic routes must specify an "href:" to be included in the navigation model.'); } if (typeof navModel.order !== 'number') { navModel.order = ++this._fallbackOrder; } this.navigation.push(navModel); this.navigation = this.navigation.sort(function (a, b) { return a.order - b.order; }); } }; Router.prototype.hasRoute = function hasRoute(name) { return !!(this._recognizer.hasRoute(name) || this.parent && this.parent.hasRoute(name)); }; Router.prototype.hasOwnRoute = function hasOwnRoute(name) { return this._recognizer.hasRoute(name); }; Router.prototype.handleUnknownRoutes = function handleUnknownRoutes(config) { var _this6 = this; if (!config) { throw new Error('Invalid unknown route handler'); } this.catchAllHandler = function (instruction) { return _this6._createRouteConfig(config, instruction).then(function (c) { instruction.config = c; return instruction; }); }; }; Router.prototype.updateTitle = function updateTitle() { if (this.parent) { return this.parent.updateTitle(); } if (this.currentInstruction) { this.currentInstruction._updateTitle(); } return undefined; }; Router.prototype.refreshNavigation = function refreshNavigation() { var nav = this.navigation; for (var i = 0, length = nav.length; i < length; i++) { var _current = nav[i]; if (!_current.config.href) { _current.href = _createRootedPath(_current.relativeHref, this.baseUrl, this.history._hasPushState); } else { _current.href = _normalizeAbsolutePath(_current.config.href, this.history._hasPushState); } } }; Router.prototype.useViewPortDefaults = function useViewPortDefaults(viewPortDefaults) { for (var viewPortName in viewPortDefaults) { var viewPortConfig = viewPortDefaults[viewPortName]; this.viewPortDefaults[viewPortName] = { moduleId: viewPortConfig.moduleId }; } }; Router.prototype._refreshBaseUrl = function _refreshBaseUrl() { if (this.parent) { var baseUrl = this.parent.currentInstruction.getBaseUrl(); this.baseUrl = this.parent.baseUrl + baseUrl; } }; Router.prototype._createNavigationInstruction = function _createNavigationInstruction() { var url = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ''; var parentInstruction = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; var fragment = url; var queryString = ''; var queryIndex = url.indexOf('?'); if (queryIndex !== -1) { fragment = url.substr(0, queryIndex); queryString = url.substr(queryIndex + 1); } var results = this._recognizer.recognize(url); if (!results || !results.length) { results = this._childRecognizer.recognize(url); } var instructionInit = { fragment: fragment, queryString: queryString, config: null, parentInstruction: parentInstruction, previousInstruction: this.currentInstruction, router: this, options: { compareQueryParams: this.options.compareQueryParams } }; if (results && results.length) { var first = results[0]; var _instruction = new NavigationInstruction(Object.assign({}, instructionInit, { params: first.params, queryParams: first.queryParams || results.queryParams, config: first.config || first.handler })); if (typeof first.handler === 'function') { return evaluateNavigationStrategy(_instruction, first.handler, first); } else if (first.handler && typeof first.handler.navigationStrategy === 'function') { return evaluateNavigationStrategy(_instruction, first.handler.navigationStrategy, first.handler); } return Promise.resolve(_instruction); } else if (this.catchAllHandler) { var _instruction2 = new NavigationInstruction(Object.assign({}, instructionInit, { params: { path: fragment }, queryParams: results ? results.queryParams : {}, config: null })); return evaluateNavigationStrategy(_instruction2, this.catchAllHandler); } else if (this.parent) { var _router2 = this._parentCatchAllHandler(this.parent); if (_router2) { var newParentInstruction = this._findParentInstructionFromRouter(_router2, parentInstruction); var _instruction3 = new NavigationInstruction(Object.assign({}, instructionInit, { params: { path: fragment }, queryParams: results ? results.queryParams : {}, router: _router2, parentInstruction: newParentInstruction, parentCatchHandler: true, config: null })); return evaluateNavigationStrategy(_instruction3, _router2.catchAllHandler); } } return Promise.reject(new Error('Route not found: ' + url)); }; Router.prototype._findParentInstructionFromRouter = function _findParentInstructionFromRouter(router, instruction) { if (instruction.router === router) { instruction.fragment = router.baseUrl; return instruction; } else if (instruction.parentInstruction) { return this._findParentInstructionFromRouter(router, instruction.parentInstruction); } return undefined; }; Router.prototype._parentCatchAllHandler = function _parentCatchAllHandler(router) { if (router.catchAllHandler) { return router; } else if (router.parent) { return this._parentCatchAllHandler(router.parent); } return false; }; Router.prototype._createRouteConfig = function _createRouteConfig(config, instruction) { var _this7 = this; return Promise.resolve(config).then(function (c) { if (typeof c === 'string') { return { moduleId: c }; } else if (typeof c === 'function') { return c(instruction); } return c; }).then(function (c) { return typeof c === 'string' ? { moduleId: c } : c; }).then(function (c) { c.route = instruction.params.path; validateRouteConfig(c, _this7.routes); if (!c.navModel) { c.navModel = _this7.createNavModel(c); } return c; }); }; _createClass(Router, [{ key: 'isRoot', get: function get() { return !this.parent; } }]); return Router; }(); function validateRouteConfig(config, routes) { if ((typeof config === 'undefined' ? 'undefined' : _typeof(config)) !== 'object') { throw new Error('Invalid Route Config'); } if (typeof config.route !== 'string') { var _name2 = config.name || '(no name)'; throw new Error('Invalid Route Config for "' + _name2 + '": You must specify a "route:" pattern.'); } if (!('redirect' in config || config.moduleId || config.navigationStrategy || config.viewPorts)) { throw new Error('Invalid Route Config for "' + config.route + '": You must specify a "moduleId:", "redirect:", "navigationStrategy:", or "viewPorts:".'); } } function evaluateNavigationStrategy(instruction, evaluator, context) { return Promise.resolve(evaluator.call(context, instruction)).then(function () { if (!('viewPorts' in instruction.config)) { instruction.config.viewPorts = { 'default': { moduleId: instruction.config.moduleId } }; } return instruction; }); } var CanDeactivatePreviousStep = exports.CanDeactivatePreviousStep = function () { function CanDeactivatePreviousStep() { } CanDeactivatePreviousStep.prototype.run = function run(navigationInstruction, next) { return processDeactivatable(navigationInstruction, 'canDeactivate', next); }; return CanDeactivatePreviousStep; }(); var CanActivateNextStep = exports.CanActivateNextStep = function () { function CanActivateNextStep() { } CanActivateNextStep.prototype.run = function run(navigationInstruction, next) { return processActivatable(navigationInstruction, 'canActivate', next); }; return CanActivateNextStep; }(); var DeactivatePreviousStep = exports.DeactivatePreviousStep = function () { function DeactivatePreviousStep() { } DeactivatePreviousStep.prototype.run = function run(navigationInstruction, next) { return processDeactivatable(navigationInstruction, 'deactivate', next, true); }; return DeactivatePreviousStep; }(); var ActivateNextStep = exports.ActivateNextStep = function () { function ActivateNextStep() { } ActivateNextStep.prototype.run = function run(navigationInstruction, next) { return processActivatable(navigationInstruction, 'activate', next, true); }; return ActivateNextStep; }(); function processDeactivatable(navigationInstruction, callbackName, next, ignoreResult) { var plan = navigationInstruction.plan; var infos = findDeactivatable(plan, callbackName); var i = infos.length; function inspect(val) { if (ignoreResult || shouldContinue(val)) { return iterate(); } return next.cancel(val); } function iterate() { if (i--) { try { var viewModel = infos[i]; var _result = viewModel[callbackName](navigationInstruction); return processPotential(_result, inspect, next.cancel); } catch (error) { return next.cancel(error); } } return next(); } return iterate(); } function findDeactivatable(plan, callbackName) { var list = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : []; for (var viewPortName in plan) { var _viewPortPlan = plan[viewPortName]; var prevComponent = _viewPortPlan.prevComponent; if ((_viewPortPlan.strategy === activationStrategy.invokeLifecycle || _viewPortPlan.strategy === activationStrategy.replace) && prevComponent) { var viewModel = prevComponent.viewModel; if (callbackName in viewModel) { list.push(viewModel); } } if (_viewPortPlan.strategy === activationStrategy.replace && prevComponent) { addPreviousDeactivatable(prevComponent, callbackName, list); } else if (_viewPortPlan.childNavigationInstruction) { findDeactivatable(_viewPortPlan.childNavigationInstruction.plan, callbackName, list); } } return list; } function addPreviousDeactivatable(component, callbackName, list) { var childRouter = component.childRouter; if (childRouter && childRouter.currentInstruction) { var viewPortInstructions = childRouter.currentInstruction.viewPortInstructions; for (var viewPortName in viewPortInstructions) { var _viewPortInstruction2 = viewPortInstructions[viewPortName]; var prevComponent = _viewPortInstruction2.component; var prevViewModel = prevComponent.viewModel; if (callbackName in prevViewModel) { list.push(prevViewModel); } addPreviousDeactivatable(prevComponent, callbackName, list); } } } function processActivatable(navigationInstruction, callbackName, next, ignoreResult) { var infos = findActivatable(navigationInstruction, callbackName); var length = infos.length; var i = -1; function inspect(val, router) { if (ignoreResult || shouldContinue(val, router)) { return iterate(); } return next.cancel(val); } function iterate() { i++; if (i < length) { try { var _current2$viewModel; var _current2 = infos[i]; var _result2 = (_current2$viewModel = _current2.viewModel)[callbackName].apply(_current2$viewModel, _current2.lifecycleArgs); return processPotential(_result2, function (val) { return inspect(val, _current2.router); }, next.cancel); } catch (error) { return next.cancel(error); } } return next(); } return iterate(); } function findActivatable(navigationInstruction, callbackName) { var list = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : []; var router = arguments[3]; var plan = navigationInstruction.plan; Object.keys(plan).filter(function (viewPortName) { var viewPortPlan = plan[viewPortName]; var viewPortInstruction = navigationInstruction.viewPortInstructions[viewPortName]; var viewModel = viewPortInstruction.component.viewModel; if ((viewPortPlan.strategy === activationStrategy.invokeLifecycle || viewPortPlan.strategy === activationStrategy.replace) && callbackName in viewModel) { list.push({ viewModel: viewModel, lifecycleArgs: viewPortInstruction.lifecycleArgs, router: router }); } if (viewPortPlan.childNavigationInstruction) { findActivatable(viewPortPlan.childNavigationInstruction, callbackName, list, viewPortInstruction.component.childRouter || router); } }); return list; } function shouldContinue(output, router) { if (output instanceof Error) { return false; } if (isNavigationCommand(output)) { if (typeof output.setRouter === 'function') { output.setRouter(router); } return !!output.shouldContinueProcessing; } if (output === undefined) { return true; } return output; } var SafeSubscription = function () { function SafeSubscription(subscriptionFunc) { this._subscribed = true; this._subscription = subscriptionFunc(this); if (!this._subscribed) this.unsubscribe(); } SafeSubscription.prototype.unsubscribe = function unsubscribe() { if (this._subscribed && this._subscription) this._subscription.unsubscribe(); this._subscribed = false; }; _createClass(SafeSubscription, [{ key: 'subscribed', get: function get() { return this._subscribed; } }]); return SafeSubscription; }(); function processPotential(obj, resolve, reject) { if (obj && typeof obj.then === 'function') { return Promise.resolve(obj).then(resolve).catch(reject); } if (obj && typeof obj.subscribe === 'function') { var obs = obj; return new SafeSubscription(function (sub) { return obs.subscribe({ next: function next() { if (sub.subscribed) { sub.unsubscribe(); resolve(obj); } }, error: function error(_error) { if (sub.subscribed) { sub.unsubscribe(); reject(_error); } }, complete: function complete() { if (sub.subscribed) { sub.unsubscribe(); resolve(obj); } } }); }); } try { return resolve(obj); } catch (error) { return reject(error); } } var RouteLoader = exports.RouteLoader = function () { function RouteLoader() { } RouteLoader.prototype.loadRoute = function loadRoute(router, config, navigationInstruction) { throw Error('Route loaders must implement "loadRoute(router, config, navigationInstruction)".'); }; return RouteLoader; }(); var LoadRouteStep = exports.LoadRouteStep = function () { LoadRouteStep.inject = function inject() { return [RouteLoader]; }; function LoadRouteStep(routeLoader) { this.routeLoader = routeLoader; } LoadRouteStep.prototype.run = function run(navigationInstruction, next) { return loadNewRoute(this.routeLoader, navigationInstruction).then(next).catch(next.cancel); }; return LoadRouteStep; }(); function loadNewRoute(routeLoader, navigationInstruction) { var toLoad = determineWhatToLoad(navigationInstruction); var loadPromises = toLoad.map(function (current) { return loadRoute(routeLoader, current.navigationInstruction, current.viewPortPlan); }); return Promise.all(loadPromises); } function determineWhatToLoad(navigationInstruction) { var toLoad = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; var plan = navigationInstruction.plan; for (var viewPortName in plan) { var _viewPortPlan2 = plan[viewPortName]; if (_viewPortPlan2.strategy === activationStrategy.replace) { toLoad.push({ viewPortPlan: _viewPortPlan2, navigationInstruction: navigationInstruction }); if (_viewPortPlan2.childNavigationInstruction) { determineWhatToLoad(_viewPortPlan2.childNavigationInstruction, toLoad); } } else { var _viewPortInstruction3 = navigationInstruction.addViewPortInstruction(viewPortName, _viewPortPlan2.strategy, _viewPortPlan2.prevModuleId, _viewPortPlan2.prevComponent); if (_viewPortPlan2.childNavigationInstruction) { _viewPortInstruction3.childNavigationInstruction = _viewPortPlan2.childNavigationInstruction; determineWhatToLoad(_viewPortPlan2.childNavigationInstruction, toLoad); } } } return toLoad; } function loadRoute(routeLoader, navigationInstruction, viewPortPlan) { var moduleId = viewPortPlan.config ? viewPortPlan.config.moduleId : null; return loadComponent(routeLoader, navigationInstruction, viewPortPlan.config).then(function (component) { var viewPortInstruction = navigationInstruction.addViewPortInstruction(viewPortPlan.name, viewPortPlan.strategy, moduleId, component); var childRouter = component.childRouter; if (childRouter) { var path = navigationInstruction.getWildcardPath(); return childRouter._createNavigationInstruction(path, navigationInstruction).then(function (childInstruction) { viewPortPlan.childNavigationInstruction = childInstruction; return _buildNavigationPlan(childInstruction).then(function (childPlan) { if (childPlan instanceof Redirect) { return Promise.reject(childPlan); } childInstruction.plan = childPlan; viewPortInstruction.childNavigationInstruction = childInstruction; return loadNewRoute(routeLoader, childInstruction); }); }); } return undefined; }); } function loadComponent(routeLoader, navigationInstruction, config) { var router = navigationInstruction.router; var lifecycleArgs = navigationInstruction.lifecycleArgs; return routeLoader.loadRoute(router, config, navigationInstruction).then(function (component) { var viewModel = component.viewModel, childContainer = component.childContainer; component.router = router; component.config = config; if ('configureRouter' in viewModel) { var childRouter = childContainer.getChildRouter(); component.childRouter = childRouter; return childRouter.configure(function (c) { return viewModel.configureRouter.apply(viewModel, [c, childRouter].concat(lifecycleArgs)); }).then(function () { return component; }); } return component; }); } var PipelineSlot = function () { function PipelineSlot(container, name, alias) { this.steps = []; this.container = container; this.slotName = name; this.slotAlias = alias; } PipelineSlot.prototype.getSteps = function getSteps() { var _this8 = this; return this.steps.map(function (x) { return _this8.container.get(x); }); }; return PipelineSlot; }(); var PipelineProvider = exports.PipelineProvider = function () { PipelineProvider.inject = function inject() { return [_aureliaDependencyInjection.Container]; }; function PipelineProvider(container) { this.container = container; this.steps = [BuildNavigationPlanStep, CanDeactivatePreviousStep, LoadRouteStep, this._createPipelineSlot('authorize'), CanActivateNextStep, this._createPipelineSlot('preActivate', 'modelbind'), DeactivatePreviousStep, ActivateNextStep, this._createPipelineSlot('preRender', 'precommit'), CommitChangesStep, this._createPipelineSlot('postRender', 'postcomplete')]; } PipelineProvider.prototype.createPipeline = function createPipeline() { var _this9 = this; var pipeline = new Pipeline(); this.steps.forEach(function (step) { return pipeline.addStep(_this9.container.get(step)); }); return pipeline; }; PipelineProvider.prototype._findStep = function _findStep(name) { return this.steps.find(function (x) { return x.slotName === name || x.slotAlias === name; }); }; PipelineProvider.prototype.addStep = function addStep(name, step) { var found = this._findStep(name); if (found) { if (!found.steps.includes(step)) { found.steps.push(step); } } else { throw new Error('Invalid pipeline slot name: ' + name + '.'); } }; PipelineProvider.prototype.removeStep = function removeStep(name, step) { var slot = this._findStep(name); if (slot) { slot.steps.splice(slot.steps.indexOf(step), 1); } }; PipelineProvider.prototype._clearSteps = function _clearSteps() { var name = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ''; var slot = this._findStep(name); if (slot) { slot.steps = []; } }; PipelineProvider.prototype.reset = function reset() { this._clearSteps('authorize'); this._clearSteps('preActivate'); this._clearSteps('preRender'); this._clearSteps('postRender'); }; PipelineProvider.prototype._createPipelineSlot = function _createPipelineSlot(name, alias) { return new PipelineSlot(this.container, name, alias); }; return PipelineProvider; }(); var logger = LogManager.getLogger('app-router'); var AppRouter = exports.AppRouter = function (_Router) { _inherits(AppRouter, _Router); AppRouter.inject = function inject() { return [_aureliaDependencyInjection.Container, _aureliaHistory.History, PipelineProvider, _aureliaEventAggregator.EventAggregator]; }; function AppRouter(container, history, pipelineProvider, events) { var _this10 = _possibleConstructorReturn(this, _Router.call(this, container, history)); _this10.pipelineProvider = pipelineProvider; _this10.events = events; return _this10; } AppRouter.prototype.reset = function reset() { _Router.prototype.reset.call(this); this.maxInstructionCount = 10; if (!this._queue) { this._queue = []; } else { this._queue.length = 0; } }; AppRouter.prototype.loadUrl = function loadUrl(url) { var _this11 = this; return this._createNavigationInstruction(url).then(function (instruction) { return _this11._queueInstruction(instruction); }).catch(function (error) { logger.error(error); restorePreviousLocation(_this11); }); }; AppRouter.prototype.registerViewPort = function registerViewPort(viewPort, name) { var _this12 = this; _Router.prototype.registerViewPort.call(this, viewPort, name); if (!this.isActive) { var viewModel = this._findViewModel(viewPort); if ('configureRouter' in viewModel) { if (!this.isConfigured) { var resolveConfiguredPromise = this._resolveConfiguredPromise; this._resolveConfiguredPromise = function () {}; return this.configure(function (config) { return viewModel.configureRouter(config, _this12); }).then(function () { _this12.activate(); resolveConfiguredPromise(); }); } } else { this.activate(); } } else { this._dequeueInstruction(); } return Promise.resolve(); }; AppRouter.prototype.activate = function activate(options) { if (this.isActive) { return; } this.isActive = true; this.options = Object.assign({ routeHandler: this.loadUrl.bind(this) }, this.options, options); this.history.activate(this.options); this._dequeueInstruction(); }; AppRouter.prototype.deactivate = function deactivate() { this.isActive = false; this.history.deactivate(); }; AppRouter.prototype._queueInstruction = function _queueInstruction(instruction) { var _this13 = this; return new Promise(function (resolve) { instruction.resolve = resolve; _this13._queue.unshift(instruction); _this13._dequeueInstruction(); }); }; AppRouter.prototype._dequeueInstruction = function _dequeueInstruction() { var _this14 = this; var instructionCount = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; return Promise.resolve().then(function () { if (_this14.isNavigating && !instructionCount) { return undefined; } var instruction = _this14._queue.shift(); _this14._queue.length = 0; if (!instruction) { return undefined; } _this14.isNavigating = true; var navtracker = _this14.history.getState('NavigationTracker'); if (!navtracker && !_this14.currentNavigationTracker) { _this14.isNavigatingFirst = true; _this14.isNavigatingNew = true; } else if (!navtracker) { _this14.isNavigatingNew = true; } else if (!_this14.currentNavigationTracker) { _this14.isNavigatingRefresh = true; } else if (_this14.currentNavigationTracker < navtracker) { _this14.isNavigatingForward = true; } else if (_this14.currentNavigationTracker > navtracker) { _this14.isNavigatingBack = true; }if (!navtracker) { navtracker = Date.now(); _this14.history.setState('NavigationTracker', navtracker); } _this14.currentNavigationTracker = navtracker; instruction.previousInstruction = _this14.currentInstruction; if (!instructionCount) { _this14.events.publish('router:navigation:processing', { instruction: instruction }); } else if (instructionCount === _this14.maxInstructionCount - 1) { logger.error(instructionCount + 1 + ' navigation instructions have been attempted without success. Restoring last known good location.'); restorePreviousLocation(_this14); return _this14._dequeueInstruction(instructionCount + 1); } else if (instructionCount > _this14.maxInstructionCount) { throw new Error('Maximum navigation attempts exceeded. Giving up.'); } var pipeline = _this14.pipelineProvider.createPipeline(); return pipeline.run(instruction).then(function (result) { return processResult(instruction, result, instructionCount, _this14); }).catch(function (error) { return { output: error instanceof Error ? error : new Error(error) }; }).then(function (result) { return resolveInstruction(instruction, result, !!instructionCount, _this14); }); }); }; AppRouter.prototype._findViewModel = function _findViewModel(viewPort) { if (this.container.viewModel) { return this.container.viewModel; } if (viewPort.container) { var container = viewPort.container; while (container) { if (container.viewModel) { this.container.viewModel = container.viewModel; return container.viewModel; } container = container.parent; } } return undefined; }; return AppRouter; }(Router); function processResult(instruction, result, instructionCount, router) { if (!(result && 'completed' in result && 'output' in result)) { result = result || {}; result.output = new Error('Expected router pipeline to return a navigation result, but got [' + JSON.stringify(result) + '] instead.'); } var finalResult = null; var navigationCommandResult = null; if (isNavigationCommand(result.output)) { navigationCommandResult = result.output.navigate(router); } else { finalResult = result; if (!result.completed) { if (result.output instanceof Error) { logger.error(result.output); } restorePreviousLocation(router); } } return Promise.resolve(navigationCommandResult).then(function (_) { return router._dequeueInstruction(instructionCount + 1); }).then(function (innerResult) { return finalResult || innerResult || result; }); } function resolveInstruction(instruction, result, isInnerInstruction, router) { instruction.resolve(result); var eventArgs = { instruction: instruction, result: result }; if (!isInnerInstruction) { router.isNavigating = false; router.isExplicitNavigation = false; router.isExplicitNavigationBack = false; router.isNavigatingFirst = false; router.isNavigatingNew = false; router.isNavigatingRefresh = false; router.isNavigatingForward = false; router.isNavigatingBack = false; var eventName = void 0; if (result.output instanceof Error) { eventName = 'error'; } else if (!result.completed) { eventName = 'canceled'; } else { var _queryString = instruction.queryString ? '?' + instruction.queryString : ''; router.history.previousLocation = instruction.fragment + _queryString; eventName = 'success'; } router.events.publish('router:navigation:' + eventName, eventArgs); router.events.publish('router:navigation:complete', eventArgs); } else { router.events.publish('router:navigation:child:complete', eventArgs); } return result; } function restorePreviousLocation(router) { var previousLocation = router.history.previousLocation; if (previousLocation) { router.navigate(router.history.previousLocation, { trigger: false, replace: true }); } else if (router.fallbackRoute) { router.navigate(router.fallbackRoute, { trigger: true, replace: true }); } else { logger.error('Router navigation failed, and no previous location or fallbackRoute could be restored.'); } } });
(function (factory) { 'use strict'; if (typeof define === 'function' && define.amd) { // Register as an anonymous AMD module: define([ 'jquery', 'bootstrap' ], factory); } else { // Browser globals: factory( window.jQuery ); } }(function ($) { 'use strict'; $.extend($.fn.modal.Constructor.prototype, { fit: function () { if (this.$element.hasClass('modal-fullscreen')) { var modalHeight = this.$element.find('.modal-body:first').height() , viewportHeight = $(window).height() ; var top = viewportHeight < modalHeight ? 0 : ((viewportHeight - modalHeight) / 2); if (modalHeight == 0) { top = 0; } this.$element.find('.modal-body')[this.$element.is('.fade') && this.$element.hasClass('in') ? 'animate' : 'css']({ 'margin-top': top + 'px' }); } else { this.unfit(); } } , unfit: function () { this.$element.find('.modal-body')[this.$element.is('.fade') && this.$element.hasClass('in') ? 'animate' : 'css']({ 'margin-top': '0' }); } }); var _backdrop = $.fn.modal.Constructor.prototype.backdrop; $.fn.modal.Constructor.prototype.backdrop = function () { var that = this , oldCallback = arguments[0] , newCallback = function () { oldCallback(); that.fit(); } ; arguments[0] = newCallback; return _backdrop.apply(this, arguments); }; $(window).on('resize', function () { $('.modal-fullscreen').modal('fit'); }); }));
/** * @fileOverview OpenStack integration * @author Mike Grabowski (@grabbou) * @version 0.2 */ 'use strict'; var util = require('util'), _ = require('underscore'), AmazonClient = require('./amazon'); /** * Creates new OpenStack instance * @class * @classdesc OpenStack integration. * Explanation: * - `container` - name of the cloud container * - `path` - path to the file relative to the `container` * - `url` - full url to the file * @augments AmazonClient * @param {Object} config */ var OpenstackClient = function OpenstackClient(config) { config = _.extend({ provider: 'hp' }, config); this._ensureValid(['username', 'password', 'authUrl'], config); OpenstackClient.super_.call(this, config); }; util.inherits(OpenstackClient, AmazonClient); module.exports = OpenstackClient;
var cheerio = require("cheerio"); var http = require('http'); var https = require('https'); var Iconv = require('iconv').Iconv; var querystring = require('querystring'); var cookies = {}; var doNotParseTwice = false ; var doNotDisplayLog = false ; var urlsParsed = {}; /* Generic page reading, supports redirection and cookie creation */ function readPage(options,cb,looptour){ var data = options.data; if(! looptour) looptour = 0 ; if(looptour > 10) throw "Infinite loop for "+ path ; // Avoid multiple redirections if(! options.host) throw "No host for "+JSON.stringify(options); if(! options.path) throw "No path for "+JSON.stringify(options); var httpProt = http ; var port = 80; if(options.protocol == 'https'){ port = 443; httpProt = https; process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"; } var onRedirect = false; if(options.onRedirect) onRedirect = options.onRedirect ; if(options.port) port = options.port; if(doNotParseTwice){ var hash = options.port + options.host + options.path + options.method ; if(urlsParsed[hash]){ if(! doNotDisplayLog) console.log("Do not parse twice activated:",options.path,"skipped."); return ; } urlsParsed[hash] = true ; } var method = 'GET'; var headers = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:24.0) Gecko/20100101 Firefox/24.0', 'Content-Type' : 'application/x-www-form-urlencoded; charset=utf-8' }; if(options.method) { method = options.method; } var postData; if(data){ postData = querystring.stringify(data); headers['Content-Length'] = postData.length; } // Filters var filterUTF8 = function(t){ return t.toString('utf-8') ; } if(options.charset){ (function(charset){ var iconv = new Iconv(charset,'UTF-8//TRANSLIT//IGNORE'); filterUTF8 = function(t){ return (iconv.convert(t).toString('utf-8')); } })(options.charset); } var filterBody = options.filterBody ; if(! filterBody) filterBody = function(c){return c}; var finalFilter = function(data){ var t = ""; for(var i in data) t += filterUTF8(data[i]); return filterBody(t); } // Cookies var cookiesData = {}; for(var cookieName in cookies) cookiesData[cookieName] = cookies[cookieName]; if(options.cookies) for(var cookieName in options.cookies) cookiesData[cookieName] = options.cookies[cookieName]; headers['Cookie'] = []; for(var cookieName in cookiesData){ headers['Cookie'].push(cookieName+"="+cookiesData[cookieName]) } headers['Cookie'].join(';'); // Referer if(options.referer) headers.referer = options.referer; if(! doNotDisplayLog) console.log("Calling",options.path,"on",options.host,'on port',port); var options = { host: options.host, port: port, path: options.path, method: method, rejectUnhauthorized:false, headers: headers }; var dataRes = []; var req = httpProt.request(options, function(res) { res.on('data', function(d){ dataRes.push(d); }); res.on('error',function(e){ console.error("Error",e); }); saveCookies(res.headers,function(){ res.on('end',function(){ switch (res.statusCode){ case 301: case 302: if(onRedirect) onRedirect(res.headers.location); else{ options.path = res.headers.location ; readPage(options,cb,looptour+1); } break; case 200: cb(finalFilter(dataRes)); break; default: console.error("Status for page",options.path,'=',res.statusCode); console.error("DEBUG:",res.headers,dataRes.join('')); } }); }) }); if(postData){ req.write(postData); } req.end(); } /* Save the cookies that are send from the header (append)*/ function saveCookies(headers,cb){ if(headers['set-cookie']){ for(var i in headers['set-cookie']){ var c = headers['set-cookie'][i].split(';')[0].split('='); cookies[c[0]] = c[1]; } } cb(); } exports = { doNotDisplayLog: function(dndl){ doNotDisplayLog = dndl ; }, doNotParseTwice: function(dnpt){ doNotParseTwice = dnpt ; }, /* * Callback the page content as an object * */ urlAsObject: function(options){ readPage(options,function(txt){ if(options.callback) options.callback(cheerio.load(txt)); }) }, /* * Callback for all the content in a page that match the regex * */ urlMatches: function(options){ if(! options.regex || ! options.callback) return; readPage(options,function(txt){ var res ; while(res = options.regex.exec(txt)){ options.callback(res) } }) }, /* * Return all the pages that match the regex as * */ urlMatchesAsObject: function(options){ if(options.regexUrlIndex == undefined) return; exports.urlMatches({ host:options.host, path:options.path, protocol:options.protocol, regex: options.regex, filterBody: options.filterBody, charset: options.charset, callback:function(res){ if(res[options.regexUrlIndex] == undefined) return; exports.urlAsObject({ host: options.host, path: res[options.regexUrlIndex], protocol:options.protocol, filterBody: options.filterBody, charset:options.charset, callback:options.callback }); } }); }, /* * Create a loop from today, for the n next days (include today) * */ forEachDay: function(limitDays,cb){ var date = new Date(); for(var i = 0 ; i < limitDays ; i++){ cb(date); date.setDate(date.getDate()+1); // Increase of one day } } } module.exports = exports ;
let expect = require("chai").expect; let rgbToHexColor = require('../06. RGB to Hex') describe("rgbToHexColor(red, green, blue)", function() { describe("Nominal cases (valid input)", function() { it("should return #FF9EAA for 255, 158, 170", function() { let hex = rgbToHexColor(255, 158, 170) expect(hex).to.equal('#FF9EAA'); }); it("should return #0C0D0E for 12, 13, 14", function() { let hex = rgbToHexColor(12, 13, 14) expect(hex).to.equal('#0C0D0E'); }); it("should return #000000 for 0, 0, 0", function() { let hex = rgbToHexColor(0, 0, 0) expect(hex).to.equal('#000000'); }); it("should return #FFFFFF for 255, 255, 255", function() { let hex = rgbToHexColor(255, 255, 255) expect(hex).to.equal('#FFFFFF'); }); }); describe("Special cases (invalid input)", function() { it("should return undefined for -1, 0, 0", function() { expect(rgbToHexColor(-1, 0, 0)).to.be.undefined; }); it("should return undefined for 0, -1, 0", function() { expect(rgbToHexColor(0, -1, 0)).to.be.undefined; }); it("should return undefined for 0, 0, -1", function() { expect(rgbToHexColor(0, 0, -1)).to.be.undefined; }); it("should return undefined for 256, 0, 0", function() { expect(rgbToHexColor(256, 0, 0)).to.be.undefined; }); it("should return undefined for 0, 256, 0", function() { expect(rgbToHexColor(0, 256, 0)).to.be.undefined; }); it("should return undefined for 0, 0, 256", function() { expect(rgbToHexColor(0, 0, 256)).to.be.undefined; }); it("should return undefined for 3.14, 0, 0", function() { expect(rgbToHexColor(3.14, 0, 0)).to.be.undefined; }); it("should return undefined for 0, 3.14, 0", function() { expect(rgbToHexColor(0, 3.14, 0)).to.be.undefined; }); it("should return undefined for 0, 0, 3.14", function() { expect(rgbToHexColor(0, 0, 3.14)).to.be.undefined; }); it("should return undefined for '5', [3], {8: 9}", function() { expect(rgbToHexColor('5', [3], {8: 9})).to.be.undefined; }); it("should return undefined for (empty input)", function() { expect(rgbToHexColor()).to.be.undefined; }); }); });
'use strict' const _ = require('lodash') const Analyzer = require('./analyzer') const Beautifier = require('nested-beautifier') const Cache = require('../cache/cache') const Error = require('../common/error') const MySqlWorker = require('../mysql/worker') class Djin { constructor(config) { const host = config.host const user = config.user const password = config.password const database = config.database if (!host || !user || !password || !database) { throw Error.MISSING_DATA } this.mySqlWorker = new MySqlWorker(host, user, password, database) } async initialize() { await Cache.initialize() await this.mySqlWorker.initialize() } async execRaw(rawQuery) { try { return this.mySqlWorker.execRaw(rawQuery) } catch (error) { throw error } } async select(jsonTree) { const selectTrees = computeTrees(jsonTree) let results = [] for (const selectTree of selectTrees) { const analyzer = new Analyzer(selectTree) const selectors = analyzer.getSelectors() const localResult = await this.mySqlWorker.select(selectors) var beautifiedRes = Beautifier.beautify(localResult, Object.keys(analyzer.blueprint)[0]) var resultValues = _.map(beautifiedRes, Object.keys(analyzer.blueprint)[0]) results.push({ [Object.keys(analyzer.blueprint)[0]]: resultValues }) } if (selectTrees.length === 1) { return results[0] } return results } async insert(jsonObjects) { const objectsToInsert = computeTrees(jsonObjects) try { const result = await this.mySqlWorker.insert(objectsToInsert) return _.flatten(result) } catch (error) { throw error } } } function computeTrees(jsonTree) { const baseSelectors = Object.keys(jsonTree) return _.map(baseSelectors, (selector) => { let result = {} result[selector] = jsonTree[selector] return result }) } module.exports = Djin
'use strict'; module.exports = function (grunt) { require('jit-grunt')(grunt); grunt.loadNpmTasks('grunt-jest'); grunt.loadNpmTasks('grunt-jsxhint'); grunt.loadNpmTasks('grunt-jasmine-node'); grunt.loadNpmTasks('grunt-flow'); grunt.initConfig({ less: { development: { options: { compress: false, yuicompress: true, optimization: 2, sourceMap: true, sourceMapFileInline: true }, plugins: [ new (require('less-plugin-autoprefix'))({browsers: ["last 2 versions"]}) ], files: { "build/style.css": "styles/main.less" } } }, flow: { options: { style: 'color' } }, browserify: { dev: { options: { browserifyOptions: { debug: true }, transform: [ ['reactify', {stripTypes: true}] ] }, src: './index.js', dest: 'build/bundle.js' }, production: { options: { transform: [ ['reactify', {stripTypes: true}], ['uglifyify', {global: true}] ], browserifyOptions: { debug: false } }, src: '<%= browserify.dev.src %>', dest: '<%= browserify.dev.dest %>' } }, watch: { styles: { files: ['styles/*.less'], tasks: ['less'], options: { nospawn: true } }, browserify: { files: 'scripts/**/*', tasks: ['browserify:dev'] } }, jest: { options: { coverage: false, config: './jest.config.json' } }, jasmine_node: { options: { forceExit: true, match: '.', matchall: false, extensions: 'js', specNameMatcher: 'spec' }, all: ['spec/'] }, jshint: { all: ['Gruntfile.js', 'scripts/**/*'], options: { jshintrc: true, reporter: require('jshint-stylish') } } }); grunt.registerTask('test', ['jasmine_node']); grunt.registerTask('default', ['less', 'browserify:dev', 'watch']); grunt.registerTask('package', ['less', 'browserify:production', 'test']); };
"use strict"; exports.__esModule = true; exports.hexToRgba = void 0; // https://stackoverflow.com/a/51564734 var hexToRgba = function hexToRgba(hex, alpha) { if (alpha === void 0) { alpha = 1; } if (!hex) { hex = '#OOO'; } if (hex.startsWith('var')) { return hex; } var hexColorRegexp = hex.length <= 4 ? /\w/g : /\w\w/g; var _hex$match$map = hex.match(hexColorRegexp).map(function (hexColor) { return parseInt(hexColor.length < 2 ? "" + hexColor + hexColor : hexColor, 16); }), r = _hex$match$map[0], g = _hex$match$map[1], b = _hex$match$map[2]; if ([r, g, b].includes(NaN)) return "rgba(0,0,0," + alpha + ")"; return "rgba(" + r + "," + g + "," + b + "," + alpha + ")"; }; exports.hexToRgba = hexToRgba;
import gotDownload from '../src'; import { startServer, stopServer } from './file-server'; import path from 'path'; import fs from 'fs'; import promisify from 'es6-promisify'; import mkdirpModule from 'mkdirp'; import rmrfModule from 'rimraf'; const readFile = promisify(fs.readFile); const readdir = promisify(fs.readdir); const mkdirp = promisify(mkdirpModule); const rmrf = promisify(rmrfModule); const downloadsPath = path.join(process.cwd(), '/.downloads/'); const tempPath = path.join(process.cwd(), '/.temp/'); describe('got-download', () => { beforeEach(startServer); afterEach(async () => await rmrf(downloadsPath)); afterEach(async () => await rmrf(tempPath)); beforeEach(async () => await mkdirp(downloadsPath)); beforeEach(async () => await mkdirp(tempPath)); afterEach(stopServer); afterAll(async () => { await rmrf(downloadsPath); await rmrf(tempPath); }); it('downloads file', async () => { expect.assertions(1); await gotDownload('0.0.0.0:7845/text-file.txt', { filename: path.join(downloadsPath, '/text-file.txt') }); const fileContent = await readFile(path.join(downloadsPath, '/text-file.txt'), { encoding: 'utf8' }); expect(fileContent).toEqual('some very cool test here\n'); }); it('doesn\'t save file on error', async () => { expect.assertions(1); try { await gotDownload('0.0.0.0:7845/error-download', { filename: path.join(downloadsPath, '/file'), retries: 0 }); } catch (e) { const files = await readdir(downloadsPath); expect(files.length).toBe(0); } }); it('rejects when the path is invalid', async () => { expect.assertions(1); try { await gotDownload('0.0.0.0:7845/error-download', { filename: 'invalid/path', retries: 0 }); } catch (e) { const files = await readdir(downloadsPath); expect(files.length).toBe(0); } }); it('has promise api', async () => { expect.assertions(1); const promise = gotDownload('0.0.0.0:7845/text-file.txt', { filename: path.join(downloadsPath, '/text-file.txt') }); expect(typeof promise.then).toEqual('function'); await promise; }); it('has stream api', (done) => { expect.assertions(2); const stream = gotDownload.stream('0.0.0.0:7845/text-file.txt', { filename: path.join(downloadsPath, '/text-file.txt') }); expect(typeof stream.pipe).toEqual('function'); expect(typeof stream.on).toEqual('function'); stream.on('end', done); }); it('saves download progress on temp dir', (done) => { expect.assertions(1); const stream = gotDownload.stream('0.0.0.0:7845/text-file.txt', { filename: path.join(downloadsPath, '/text-file.txt'), tempPath }); stream.on('data', async () => { const files = await readdir(tempPath); expect(files.length).toBe(1); }); stream.on('end', () => { done(); }); }); it('appends timestamp to temp file', (done) => { expect.assertions(1); const originalDate = Date; global.Date = () => new originalDate(1505509193801); global.Date.now = originalDate.now; const stream = gotDownload.stream('0.0.0.0:7845/text-file.txt', { filename: path.join(downloadsPath, '/text-file.txt'), tempPath }); stream.on('data', async () => { const [file] = await readdir(tempPath); expect(file).toBe('text-file.txt1505509193801'); }); stream.on('end', () => { global.Date = originalDate; done(); }); }); it('moves from temp path to filename when finish', async () => { expect.assertions(2); await gotDownload('0.0.0.0:7845/text-file.txt', { filename: path.join(downloadsPath, '/text-file.txt'), tempPath }); const fileContent = await readFile(path.join(downloadsPath, '/text-file.txt'), { encoding: 'utf8' }); const tempFiles = await readdir(tempPath); expect(tempFiles.length).toBe(0); expect(fileContent).toEqual('some very cool test here\n'); }); it('has progress callback', (done) => { expect.hasAssertions(); const stream = gotDownload.stream('0.0.0.0:7845/one-mb', { filename: path.join(downloadsPath, '/one-mb'), downloadProgress: (progress) => { expect(progress).toEqual({ downloaded: expect.any(Number), total: expect.any(Number) }); } }); stream.on('end', () => { done(); }); }); describe('checksum', () => { it('fails on wrong checksum', async () => { expect.assertions(1); try { await gotDownload('0.0.0.0:7845/text-file.txt', { filename: path.join(downloadsPath, '/text-file.txt'), checksum: 'wrongchecksum', algorithm: 'sha512' }); } catch (e) { expect(e).toBeDefined(); } }); it('succeeds on right checksum', async () => { expect.assertions(1); await gotDownload('0.0.0.0:7845/one-mb', { filename: path.join(downloadsPath, '/one-mb'), checksum: 'qGLDYERgb5mi0RoiB72x5Djm7SNbqcHgQdB2BCkipfGWNno44Xt4nOBiOCenY9M7ZBAqpuUgumyF0pA3plkPQw==', algorithm: 'sha512' }); const file = await readFile(path.join(downloadsPath, '/one-mb'), { encoding: 'utf8' }); expect(file).toBeDefined(); }); }); });