code
stringlengths
2
1.05M
"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 http_1 = require('@angular/http'); var app_config_1 = require('./app.config'); var Rx_1 = require('rxjs/Rx'); require('rxjs/add/operator/map'); var LoginService = (function () { function LoginService(http) { this.http = http; } LoginService.prototype.login = function (account, password) { var url = app_config_1.Config.url + "api/account/login"; console.log(url); var headers = new http_1.Headers({ 'Content-Type': 'application/json' }); var options = new http_1.RequestOptions({ headers: headers }); return Rx_1.Observable.create(function (observer) { observer.next({ valid: true }); }); // return this.http.post(url, { Account: account, Password: password }, options).map(res => res.json() ); }; LoginService = __decorate([ core_1.Injectable(), __metadata('design:paramtypes', [http_1.Http]) ], LoginService); return LoginService; }()); exports.LoginService = LoginService; //# sourceMappingURL=login.service.js.map
/** * @fileOverview first_run.js shows the necessary navigation and * design elements to be integrated into the privly-applications * bundle. */ /** * Initialize the applications by showing and hiding the proper * elements. */ var callbacks = { /** * Submit the registration form and await the return of the registration. */ submitRegistration: function() { privlyNetworkService.sameOriginPostRequest( privlyNetworkService.contentServerDomain() + "/users/invitation", callbacks.checkRegistration, { "user[email]": $("#register_email").val() }); }, /** * Check to see if the user's registration was accepted by the server. */ checkRegistration: function(response) { if ( response.json.success === true ) { callbacks.pendingRegistration(); } else { callbacks.registrationFailure(); } }, /** * Tell the user their registration was submitted. */ pendingRegistration: function() { $(".register_feedback_failure").slideUp(); $(".register_feedback_emailed").slideDown(); }, /** * Tell the user their registration was rejected. */ registrationFailure: function() { $(".register_feedback_emailed").slideUp(); $(".register_feedback_failure").slideDown(); } } function init() { // Set the nav bar to the proper domain privlyNetworkService.initializeNavigation(); privlyNetworkService.initPrivlyService( privlyNetworkService.contentServerDomain(), privlyNetworkService.showLoggedInNav, privlyNetworkService.showLoggedOutNav ); $("#messages").hide(); $("#form").show(); $(".content_server").text(ls.getItem("options/contentServer/url").split("//")[1]); $("#registerModal") .on("shown.bs.modal", function() { $("#register_email").focus(); }) .on("hidden.bs.modal", function() { $(".register_feedback_failure").slideUp(); $(".register_feedback_emailed").slideUp(); $("#register_email").val(""); }); $("#registerForm").on("submit", function(e) { e.preventDefault(); callbacks.submitRegistration(); }); // Show a preview of the tooltip to the user $("#tooltip").append(Privly.glyph.getGlyphDOM()) .show() .append("<br/><br/><p>This is your Privly Glyph</p>"); } // Initialize the application document.addEventListener('DOMContentLoaded', function() { // Don't start the script if it is running in a Headless // browser if( document.getElementById("logout_link") ) { init(); } });
var gulp = require('gulp'); var livereload = require('gulp-livereload'); var configuration = require('../configuration.js'); gulp.task('watch', function() { var server = livereload(); var reload = function(file) { livereload.changed(file.path); }; gulp.watch(configuration.vendor.scripts + '/**', ['uglify']); gulp.watch(configuration.source.root + '/assets/**', ['copy']); gulp.watch(configuration.source.root + '/*.html', ['html']); gulp.watch(configuration.source.scripts + '/**', ['browserify']); gulp.watch(configuration.source.styles + '/**', ['sass']); gulp.watch(configuration.source.images + '/**', ['images']); gulp.watch([configuration.target.root + '/**']).on('change', reload); });
function Upload(id, options){ console.log(options) if (!(window.File && window.FileReader && window.FileList && window.Blob)) return false; var $input = document.querySelector(id); var self = this; var pid, reader, cancelled, paused, start_time, file, file_index = 0, start_file_index; var block_size = 1048576; if (options.block_size) block_size = options.block_size; var dispatchEvent = function(name, detail){console.log('Dispatch ', name,' :', detail);$input.dispatchEvent(new CustomEvent(name, {'detail': detail}));}; var hide_btns = function(){for(var i=0; i< file_btns.length;++i){file_btns[i].style.display='none';}}; var create_btn= function(title,html, clazz){ var btn = document.createElement('a');btn.setAttribute('href', '#');btn.title=title;btn.innerHTML=html; var i = document.createElement('i'); i.className=clazz; btn.appendChild(i); return btn;}; var create_el = function(tag, clazz){ var el = document.createElement(tag);el.className=clazz;return el;}; var append_children = function(parent, children){for(var i=0; i < children.length;i++){parent.appendChild(children[i]);};}; var update_preview = function(){ preview.innerHTML=''; if(file.type.match('image')){ reader = new FileReader(); reader.onload = (function(f){ return function(e){ var img = document.createElement('img');img.setAttribute('src', e.target.result);img.title=f.name; preview.appendChild(img); };})(file); reader.readAsDataURL(file); } }; var reset_upload = function(){ hide_btns(); browse_btn.style.display='block'; cancelled = false; paused = false; preview.innerHTML=''; info.innerHTML=''; progress_label.innerHTML=''; progress_bar.style.width="0"; $input.value=''; }; var begin_upload = function(){ hide_btns(); pause_btn.style.display='block'; cancel_btn.style.display='block'; progress_label.innerHTML=''; start_time = Date.now(); start_file_index = file_index; if (paused) paused = false; var type = (file.type === "") ? atom('undefined') : bin(file.type); dispatchEvent("start_upload", {'file_name': bin(file.name), 'type': type, 'index': file_index}); // var msg = enc(tuple(atom('bert'), atom('element_upload'), bin(id), tuple(bin(file.name), tuple( atom('file_info'), //#file_info file_index,//size type, //type atom('read_write'), //access atom('undefined'),//atime atom('undefined'),//mtime atom('undefined'),//ctime atom('undefined'),//mode atom('undefined'),//links atom('undefined'),//major_device atom('undefined'),//minor_device atom('undefined'),//inode atom('undefined'),//uid atom('undefined') //guid )))); console.log('send bert', msg); //ws.send(msg); }; var read_slice = function(start, end) { reader = new FileReader(); reader.onabort = onabort; reader.onerror = onerror; reader.onloadend = onloadend; var blob = file.slice(start, end); reader.readAsBinaryString(blob); }; var onloadend = function(e){ if(e.target.readyState == FileReader.DONE){ dispatchEvent('deliver', {'pid': utf8.toByteArray(self.pid), 'data': bin(e.target.result)}) //var m = enc(tuple(atom('server'), atom('element_upload'), self.pid, bin(e.target.result))); //console.log('yoy:' ,m); //ws.send(m); } }; var update_progress_bar = function(){ var progress = Math.floor(100* (file_index / file.size)); if(progress_bar && progress_bar.style.width !== progress+'%'){ dispatchEvent('progress_changed', {'progress':progress}); } }; var calculate_eta = function(){ var delta_ms = Date.now() - start_time; var rate = (file_index- start_file_index) / delta_ms; var remaining_ms = (file.size - file_index) / rate; if(remaining_ms < 0) return; var delta_hr = parseInt(Math.floor(remaining_ms/3600000)); remaining_ms -= delta_hr*3600000; var delta_min = parseInt(Math.floor(remaining_ms/60000)); remaining_ms -= delta_min*60000; var delta_sec = parseInt(Math.floor(remaining_ms/1000)); var eta = ""; if (delta_sec>=0) eta = delta_sec + 1 + " secs"; if (delta_min>0) eta = delta_min + " mins"; if (delta_hr>0) eta = delta_hr + " hours"; etainfo.innerHTML=eta; }; $input.addEventListener('change',function(e){ file = this.files[0]; if(!file) return; info.innerHTML=file.name; progress_label.innerHTML=''; hide_btns(); browse_btn.style.display='block'; upload_btn.style.display='inline-block'; cancel_btn.style.display='block'; progress_bar.style.width="0"; if(options.preview && options.preview =='true') update_preview(); dispatchEvent("query_file", {'file_name': bin(file.name)}); }); $input.addEventListener('queried', function(e){ var size = parseInt(e.detail.file_size); file_index = 0; if (size>0) { file_index = size; hide_btns(); reupload_btn.style.display='block'; cancel_btn.style.display='block'; if (file_index < file.size) { resume_btn.style.display='block'; progress_label.innerHTML='Upload incomplete'; } else { progress_label.innerHTML='File exists'; } update_progress_bar(); } }); $input.addEventListener('read_slice', function(e){ self.pid = e.detail.pid; read_slice(file_index, file_index + block_size); }); $input.addEventListener('delivered', function(e){ var size = parseInt(e.detail.file_size); file_index += block_size; if (!paused && !cancelled && file_index<file.size) { read_slice(file_index, file_index + block_size); } if (paused) progress_label.innerHTML=''; if (cancelled) { reset_upload(); progress_label.innerHTML=''; } calculate_eta(); update_progress_bar(); if (file_index >= file.size){ for(var i=0; i< file_btns.length;++i){file_btns[i].style.display='none';} browse_btn.style.display='block'; progress_label.innerHTML='Upload complete'; etainfo.innerHTML=''; dispatchEvent('complete', {'pid': bin(self.pid)}); } }); $input.addEventListener('error', function(e){ error(e.detail.msg); }); $input.addEventListener('reset', reset_upload); $input.addEventListener('progress_changed', function(e){progress_bar.style.width=e.detail.progress + "%";}); $input.addEventListener('complete_replace', function(e){ var im = document.createElement('img'); im.setAttribute('src', e.detail.file); im.style.width='100%'; var pa = this.parentNode; pa.removeChild(this.previousSibling); pa.replaceChild(im, this); }); var browse_btn = create_btn('browse', 'browse', 'fi-browse'); browse_btn.addEventListener('click', function(e){$input.click(); e.preventDefault();}, false); var upload_btn = create_btn('Upload', 'upload', 'fi-upload'); upload_btn.onclick=begin_upload; var reupload_btn= create_btn('Reupload', 'reupload', 'fi-reupload'); reupload_btn.onclick=function(){file_index = 0;begin_upload();}; var resume_btn = create_btn('Resume', 'resume', 'fi-resume'); resume_btn.onclick=begin_upload; var cancel_btn = create_btn('Cancel', 'cancel', 'fi-cancel'); cancel_btn.onclick= function(){ reset_upload(); progress_label.innerHTML=''; cancelled=true; preview.innerHTML=''; }; var pause_btn = create_btn('Pause', 'pause', 'fi-pause'); pause_btn.onclick= function () { paused=true; pause_btn.style.display='none'; resume_btn.style.display='block'; progress_label.innerHTML=''; dispatchEvent('complete', {'pid': bin(self.pid)}); }; var etainfo = create_el('span','info'); var info = create_el('span','info'); var preview = create_el('div','preview'); var progress_ctl = create_el('div', 'progress-ctl'); append_children(progress_ctl, [upload_btn, pause_btn, resume_btn, reupload_btn]); var progress_label = document.createElement('span'); var progress_bar = create_el('div', 'progress-bar progress-bar-info'); progress_bar.setAttribute('role', 'progressbar'); progress_bar.setAttribute('aria-valuemin', '0'); progress_bar.setAttribute('aria-valuemax', '100'); append_children(progress_bar, [progress_label, progress_ctl]); var progress = create_el('div', 'progress progress-striped'); progress.appendChild(progress_bar); var ctl = create_el('div', 'ctl'); append_children(ctl, [cancel_btn, info, etainfo, browse_btn]); var fu = create_el('div','file-upload'); fu.setAttribute('contenteditable', false); append_children(fu, [preview, progress, ctl]) $input.parentNode.insertBefore(fu, $input); if(options.value && options.value !== "undefined") preview.innerHTML("<img src='"+ options.value +"'/>"); console.log('valuer parsed') var file_btns = fu.querySelectorAll("a"); var error = function(message){ reset_upload(); var close = create_el('button', 'close'); close.setAttribute('type', 'button'); close.setAttribute('data-dissmiss', 'alert'); close.innerHTML("&times;"); var alrt = create_el('div', 'alert alert-error'); append_children(alrt, [close, message]); $input.parentNode.appendChild(alrt); var bar = $input.parentNode.querySelector('.progress-bar-info'); bar.classList.remove('progress-bar-info'); bar.classList.add('progress-bar-danger'); progress_bar.style.width="100%"; progress_label.innerHTML(message); }; var onabort = function(event){ error('File upload aborted'); reader.abort();}; var onerror = function(e){ switch(e.target.error.code) { case e.target.error.NOT_FOUND_ERR: error('File not found'); break; case e.target.error.NOT_READABLE_ERR: error('File is not readable'); break; case e.target.error.ABORT_ERR: error('File upload aborted'); break; default: error('An error occurred reading the file.');}; }; handle_socket = function(d){ console.log('handle socket in upload: ', d); }; reset_upload(); } if(typeof handle_web_socket == 'function'){ old = handle_web_socket window.handle_web_socket = function(data){Upload.handle_socket(data); return old(data);} } else { window.handle_web_socket = Upload.handle_socket }
// output consumer 'use strict'; var buffers = require ('stream-buffers'); /** * output consumer constructor * this consumes the strings that compose the final result * @param bufferParams stream buffer params, see stream-buffers docs * @constructor */ function Consumer (bufferParams) { this.bufferParams = bufferParams; this.buffer = null; } /** * initialize output consumer * create buffer */ Consumer.prototype.init = function () { this.buffer = new buffers.WritableStreamBuffer (this.bufferParams); }; /** * output consumer constructor wrapper * @param bufferParams passed to constructor * @returns {Consumer} initialized consumer */ function consumer (bufferParams) { var ret = new Consumer (bufferParams); ret.init (); return ret; } /** * consume string * this implementation appends data.toString() to internal buffer * @param data object with toString property */ Consumer.prototype.write = function (data) { this.buffer.write (data.toString ()); }; /** * get string in buffer * destroy buffer * @returns {string} the result string */ Consumer.prototype.getString = function () { var string = this.buffer.getContentsAsString ( this.bufferParams.encoding); this.buffer.destroy (); this.buffer = null; return string; }; module.exports = { Consumer: Consumer, consumer: consumer };
'use strict'; var XML = require('utils/xml'); var tempoTotalEstimado = function (tempoEstimado) { var limite; if (tempoEstimado.tipo() === 'entre') { limite = m('entre', { min: tempoEstimado.entreMinimo(), max: tempoEstimado.entreMaximo(), unidade: tempoEstimado.entreTipoMaximo() }); } else if (tempoEstimado.tipo() === 'ate') { limite = m('ate', { max: tempoEstimado.ateMaximo(), unidade: tempoEstimado.ateTipoMaximo() }); } return m('tempo-total-estimado', [ limite, m('descricao', tempoEstimado.descricao()) ]); }; var item = function (i) { return m('item', i); }; var casos = function (e, nome, itemDoCaso) { return m(nome, [ m('default', e.casoPadrao().campos().map(itemDoCaso)), e.outrosCasos().map(function (caso) { return m('caso', { descricao: caso.descricao() }, caso.campos().map(itemDoCaso)); }) ]); }; var documento = function (e) { return m('item', e.descricao()); }; var documentos = function (e) { return e ? casos(e, 'documentos', documento) : ''; }; var custo = function (e) { return m('custo', [ m('descricao', e.descricao()), m('moeda', e.moeda()), m('valor', e.valor()) ]); }; var custos = function (e) { return e ? casos(e, 'custos', custo) : ''; }; var canalDePrestacao = function (e) { return m('canal-de-prestacao', { tipo: e.tipo() }, [ m('descricao', e.descricao()) ]); }; var canaisDePrestacao = function (e) { return e ? casos(e, 'canais-de-prestacao', canalDePrestacao) : ''; }; var etapa = function (e) { return m('etapa', [ m('titulo', e.titulo()), m('descricao', e.descricao()), documentos(e.documentos()), custos(e.custos()), canaisDePrestacao(e.canaisDePrestacao()) ]); }; var solicitantes = function (sol) { return m('solicitantes', sol.map(function (s) { return m('solicitante', [ m('tipo', s.tipo()), m('requisitos', s.requisitos()) ]); })); }; var Gratuidade = require('servico/modelos').Gratuidade; var gratuidade = function (ehGratuito) { switch (ehGratuito) { case Gratuidade.GRATUITO: return true; case Gratuidade.PAGO: return false; } return undefined; }; module.exports = function (servico) { var doc = XML.createDocument('http://servicos.gov.br/v3/schema'); m.render(doc, m('servico', { 'xmlns': 'http://servicos.gov.br/v3/schema', 'xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance', 'xsi:schemaLocation': 'http://servicos.gov.br/v3/schema ../servico.xsd' }, [ m('nome', servico.nome()), m('sigla', servico.sigla()), m('nomes-populares', servico.nomesPopulares().map(item)), m('descricao', servico.descricao()), m('contato', servico.orgao().contato()), m('gratuito', gratuidade(servico.gratuidade())), solicitantes(servico.solicitantes()), tempoTotalEstimado(servico.tempoTotalEstimado()), m('etapas', servico.etapas().map(etapa)), m('orgao', { id: servico.orgao().nome() }), m('segmentos-da-sociedade', servico.segmentosDaSociedade().map(item)), m('areas-de-interesse', servico.areasDeInteresse().map(item)), m('palavras-chave', servico.palavrasChave().map(item)), m('legislacoes', servico.legislacoes().map(item)) ])); XML.cdata(doc, 'nome'); XML.cdata(doc, 'descricao'); XML.cdata(doc, 'requisitos'); XML.cdata(doc, 'contato'); XML.cdata(doc, 'legislacoes item'); return doc; };
import tracer from 'tracer' const logger = tracer.console({ format: '{{timestamp}} <{{title}}> {{message}}', dateformat: 'HH:MM:ss.L', }) export default logger
'use strict'; /** * Plot sequences as rows of rectangles. * @constructor */ var SequenceVisualizer = function() { /** Margins of plot are to the view boundaries * @const */ this.margins = [ [40, 0], [0, 20] ]; /** Rendering states */ this.zoom = null; this.zoomTranslate = [0, 0]; this.zoomScale = 1.0; /** Data and colors */ this.seqData = {}; this.getSeqColor = null; // function this.getSeqInfo = null; // function this.update = null; /** @const */ this.timePointStrokeWidth = 1.0; /** On/Off state of the view */ this.show = true; /** Whether to show checkin */ this.showCheckin = true; /** Size of the view */ this.size = 0; this.sizeText = ['S', 'M', 'L', 'XL']; this.sizeHeight = [100, 200, 400, 800]; }; /** @const */ SequenceVisualizer.prototype.DEFAULT_HEIGHT = 200; SequenceVisualizer.prototype.OFF_HEIGHT = 0; /** * Setup the context for the sequence visualizer. */ SequenceVisualizer.prototype.context = function(title, panelTag) { var viewTag = panelTag + ' .panel-body'; this.svg = d3.select(panelTag + ' svg > g'); this.svgSeq = this.svg.select('.seq'); this.jqHeader = $(panelTag).find('.panel-heading'); this.jqView = $(viewTag); this.jqSvg = $(panelTag).find('svg'); this.jqSeq = this.jqSvg.find('.seq'); this.jqSelectRange = this.jqView.find('.select-range'); this.jqGrabBackground = this.jqSvg.find('.grab-background'); var width = this.jqSvg.width(), height = this.jqSvg.height(); this.svgSize = [width, height]; this.xScale = d3.time.scale() .range([this.margins[0][0], width]); // Screen y is NOT reversed, as the order of rows is arbitrary. this.plotHeight = height - this.margins[1][1]; this.yScale = d3.scale.linear() .range([0, this.plotHeight]); $('<span></span>').text(title) .appendTo(this.jqHeader); this.btnShow = $('<div></div>') .addClass('label btn-label btn-right') .attr('data-toggle', 'tooltip') .appendTo(this.jqHeader); this.btnCheckin = this.btnShow.clone() .addClass('label-primary') .appendTo(this.jqHeader); this.btnSize = this.btnShow.clone() .addClass('label-primary') .appendTo(this.jqHeader); var seqvis = this; this.btnShow .addClass(this.show ? 'label-primary' : 'label-default') .text(this.show ? 'On' : 'Off') .click(function(event) { seqvis.setShow(!seqvis.show); }); this.btnCheckin .addClass(this.showCheckin ? 'label-primary' : 'label-default') .text('Check-in') .click(function(event) { seqvis.setCheckin(); }); this.btnSize .text(this.sizeText[this.size]) .click(function(event) { seqvis.setSize(); }); this.resize(true); }; /** * Update function call * @param {function} update */ SequenceVisualizer.prototype.setUpdate = function(update) { this.update = update; }; /** * Change context when window resizes. * @param {boolean} noRender If true, skip re-rendering the scene. */ SequenceVisualizer.prototype.resize = function(noRender) { if (!this.show) return; this.jqView.css('height', this.sizeHeight[this.size]); this.jqSvg.css('height', this.sizeHeight[this.size]); this.jqGrabBackground.css('height', this.sizeHeight[this.size]); var width = this.jqSvg.width(), height = this.jqSvg.height(); this.svgSize = [width, height]; this.xScale.range([this.margins[0][0], width]); this.plotHeight = height - this.margins[1][0] - this.margins[1][1]; this.yScale.range([0, this.plotHeight]); if (!noRender) this.render(); }; /** * Turn on/off sequence visualizer. * @param {boolean} state */ SequenceVisualizer.prototype.setShow = function(state) { this.show = state; if (this.show) { this.btnShow.addClass('label-primary') .removeClass('label-default') .text('On'); this.btnSize.addClass('label-primary') .removeClass('label-default'); this.resize(true); this.update(true); } else { this.btnShow.removeClass('label-primary') .addClass('label-default') .text('Off'); this.btnSize.removeClass('label-primary') .addClass('label-default'); this.clear(); this.jqView.height(this.OFF_HEIGHT); } }; /** * Turn on/off checkin vis. * @param {boolean} state */ SequenceVisualizer.prototype.setCheckin = function(state) { if (state == undefined) state = !this.showCheckin; this.showCheckin = state; if (state) { this.btnCheckin.addClass('label-primary') .removeClass('label-default') } else { this.btnCheckin.removeClass('label-primary') .addClass('label-default') } this.render(); }; /** * Change the height of the view. * @param {number} size Index of sizes * If given, set the size to the given index. * Otherwise, switch to the next size. */ SequenceVisualizer.prototype.setSize = function(size) { if (!this.show) return; if (size == undefined) { size = (this.size + 1) % this.sizeText.length; } this.size = size; this.btnSize.text(this.sizeText[size]); this.resize(); } /** * Set a function that will map a given value of bar to its color. * @param {function} getColor */ SequenceVisualizer.prototype.setColors = function(getColor) { this.getSeqColor = getColor; }; /** * Set a function that will map a given value of bar to its info. * @param {function} getInfo */ SequenceVisualizer.prototype.setInfo = function(getInfo) { this.getSeqInfo = getInfo; }; /** * Set the sequence data * @param {Array} data */ SequenceVisualizer.prototype.setSequenceData = function(data) { this.seqData = data; var minTime = Infinity, maxTime = -Infinity; var index = 0; var order = tracker.getOrderedTargets().concat( tracker.getOrderedSelects()); for (var k = 0; k < order.length; k++) { var pid = order[k]; var as = data[pid]; if (data[pid] == undefined) continue; for (var i = 0; i < as.length; i++) { var a = as[i]; minTime = Math.min(minTime, a[0]); maxTime = Math.max(maxTime, a[0]); } as.index = index++; // assign an index } var height = this.jqSvg.height(); if (minTime != Infinity) { this.xScale.domain([minTime * utils.MILLIS, maxTime * utils.MILLIS]); // not "index - 1", otherwise the last row has now height! this.yScale.domain([0, index]); } this.interaction(); }; /** * The data has not changed. But the rendering order has changed. */ SequenceVisualizer.prototype.reindex = function() { if (!this.show) return; var data = this.seqData; var order = tracker.getOrderedTargets().concat( tracker.getOrderedSelects()); var index = 0; for (var k = 0; k < order.length; k++) { var pid = order[k]; if (data[pid] == undefined) continue; data[pid].index = index++; } this.render(); }; /** * Response zoom event. */ SequenceVisualizer.prototype.zoomHandler = function() { var translate = d3.event.translate, scale = d3.event.scale; var w = this.jqSvg.width(), h = this.jqSvg.height(); translate[0] = Math.max(w * (1 - scale), translate[0]); translate[0] = Math.min(0, translate[0]); translate[1] = 0; this.zoomTranslate = translate; this.zoomScale = scale; this.zoom.translate(translate); this.svg.select('g').attr('transform', 'translate(' + translate + ') ' + 'scale(' + scale + ',1)' ); this.svg.select('.seq-axis').call(this.axis); this.renderTimePoint(); } /** * Set up the interaction for the rendered elements. */ SequenceVisualizer.prototype.interaction = function() { var seqvis = this; this.xScaleZoom = this.xScale.copy(); this.zoom = d3.behavior.zoom() .scaleExtent([1, 1000]) .on('zoom', this.zoomHandler.bind(this)); this.zoom.x(this.xScaleZoom); this.svg.call(this.zoom); this.jqSvg.mousedown(function(event) { if (!vastcha15.keys.ctrl) return; var offset = utils.getOffset(event, $(this)); seqvis.setTimePoint(offset[0]); event.stopPropagation(); return false; }); }; /** * Get the time corresponding to the clicked position. * And set the time point to it. * @param {number} x */ SequenceVisualizer.prototype.setTimePoint = function(x) { var x = this.xScale.invert( (x - this.zoomTranslate[0]) / this.zoomScale); var t = (+x) / utils.MILLIS; t = parseInt(t); vastcha15.setTimePoint(t, true); }; /** Highlight / unhighlight hovered element. */ SequenceVisualizer.prototype.updateHover = function(pid) { var as = this.seqData[pid]; if (as == undefined) return; var index = as.index; var yl = this.yScale(index), yr = this.yScale(index + 1); this.svgSeq.append('rect') .classed('seq-hover', true) .attr('x', 0) .attr('width', this.svgSize[0]) .attr('y', yl) .attr('height', yr - yl); }; SequenceVisualizer.prototype.clearHover = function(pid) { this.svgSeq.select('.seq-hover').remove(); }; /** Wrapper */ SequenceVisualizer.prototype.render = function() { if (!this.show) return; this.renderSequences(); this.renderLabels(); this.renderTimePoint(); this.renderAxis(); }; /** Clear the rendering. */ SequenceVisualizer.prototype.clear = function() { this.svgSeq.selectAll('*').remove(); this.svg.select('.seq-labels').remove(); this.svg.select('.seq-timepoint').remove(); this.svg.select('.seq-axis').remove(); }; /** Render the sequences. */ SequenceVisualizer.prototype.renderSequences = function() { var seqvis = this; var data = this.seqData, svg = this.svgSeq; // clear previous rendering svg.selectAll('*').remove(); var scale = this.zoomScale, translate = this.zoomTranslate; for (var pid in data) { var as = data[pid]; var index = as.index; var yl = this.yScale(index), yr = this.yScale(index + 1); var g = svg.append('g') .attr('id', 'a' + pid) .attr('transform', 'translate(0,' + yl + ')'); for (var i = 0; i < as.length - 1; i++) { var xl = this.xScale(as[i][0] * utils.MILLIS), xr = this.xScale(as[i + 1][0] * utils.MILLIS), color = this.getSeqColor(as[i][1]); if (as[i][2] == 0 && this.showCheckin) // Check-in color = utils.darkerColor(color); var r = g.append('rect') .attr('x', xl) .attr('val', as[i][1]) .attr('width', xr - xl) .attr('height', yr - yl) .style('fill', color); r.on('mouseover', function() { var id = d3.event.target.parentElement.id.substr(1); tracker.setHoverPid(id); var val = $(d3.event.target).attr('val'); seqvis.renderJqLabel( [d3.event.pageX + 5, d3.event.pageY], seqvis.getSeqInfo(val) ); }) .on('mouseout', function() { tracker.setHoverPid(null); seqvis.removeJqLabel(); }) } } this.renderAxis(); this.renderLabels(); this.renderTimePoint(); }; /** * Show pid for each row */ SequenceVisualizer.prototype.renderLabels = function() { var data = this.seqData; // clear previous labels this.svg.select('.seq-labels').remove(); var g = this.svg.append('g') .classed('seq-labels', true); for (var pid in data) { var as = data[pid]; var index = as.index; var y = this.yScale(index + 0.5) + 5; var lb = g.append('text') .attr('id', 'lb' + pid) .attr('x', 3) .attr('y', y) .text(pid); lb.on('mousedown', function() { var id = d3.event.target.id.substr(2); tracker.toggleTarget(id); }) .on('mouseover', function() { var id = d3.event.target.id.substr(2); tracker.setHoverPid(id); }) .on('mouseout', function() { var id = d3.event.target.id.substr(2); tracker.setHoverPid(null); }); } this.renderTargets(); }; /** * Highlight the targeted elements */ SequenceVisualizer.prototype.renderTargets = function() { if (!this.show) return; var data = this.seqData; this.svg.selectAll('.seq-label-target') .classed('seq-label-target', false); for (var pid in data) { if (tracker.targeted[pid]) { this.svg.select('#lb' + pid) .classed('seq-label-target', true); } } }; /** * Show a label with given text and position * @param {Array<number>} pos [x, y] * @param {string} text */ SequenceVisualizer.prototype.renderJqLabel = function(pos, text) { this.removeJqLabel(); // only one label at a time $('<div></div>') .text(text) .css({ left: pos[0] + 5, top: pos[1] }) .addClass('vis-label') .appendTo(this.jqView) .click(function() { $(this).remove(); }); }; SequenceVisualizer.prototype.removeJqLabel = function() { this.jqView.find('.vis-label').remove(); }; /** * Render the current time point */ SequenceVisualizer.prototype.renderTimePoint = function() { // clear previous this.svgSeq.selectAll('.seq-timepoint, .seq-timerange').remove(); if (!this.show) return; var x = this.xScale(vastcha15.timePoint * utils.MILLIS); this.svgSeq.append('line') .classed('seq-timepoint', true) .attr('y1', 0) .attr('y2', this.plotHeight) .attr('transform', 'translate(' + x + ',0)') .style('stroke-width', this.timePointStrokeWidth / this.zoomScale); var xl = this.xScale(vastcha15.timeRangeD[0] * utils.MILLIS), xr = this.xScale(vastcha15.timeRangeD[1] * utils.MILLIS); xl = Math.max(xl, this.margins[0][0]); xr = Math.min(xr, this.svgSize[0]); this.svgSeq.append('rect') .classed('seq-timerange', true) .attr('x', this.margins[0][0]) .attr('width', xl - this.margins[0][0]) .attr('y', 0) .attr('height', this.plotHeight); this.svgSeq.append('rect') .classed('seq-timerange', true) .attr('x', xr) .attr('width', this.svgSize[0] - xr) .attr('y', 0) .attr('height', this.plotHeight); }; /** * Render the time axis */ SequenceVisualizer.prototype.renderAxis = function() { // clear previous axis this.svg.select('.seq-axis').remove(); this.axis = d3.svg.axis() .scale(this.xScaleZoom); var g = this.svg.append('g') .classed('seq-axis', true) .attr('transform', 'translate(0,' + this.plotHeight + ')') .call(this.axis); };
/** * COMMON WEBPACK CONFIGURATION */ const path = require('path'); const webpack = require('webpack'); module.exports = (options) => ({ entry: options.entry, output: Object.assign({ // Compile into js/build.js path: path.resolve(process.cwd(), 'build'), publicPath: '/', }, options.output), // Merge with env dependent settings module: { loaders: [{ test: /\.(js|jsx)$/, // Transform all .js files required somewhere with Babel loader: 'babel-loader', exclude: /node_modules/, query: options.babelQuery, }, { // Do not transform vendor's CSS with CSS-modules // The point is that they remain in global scope. // Since we require these CSS files in our JS or CSS files, // they will be a part of our compilation either way. // So, no need for ExtractTextPlugin here. test: /\.css$/, include: /node_modules/, loaders: ['style-loader', 'css-loader'], }, { test: /\.(eot|svg|ttf|woff|woff2)$/, loader: 'file-loader', }, { test: /\.(jpg|png|gif)$/, loaders: [ 'file-loader', { loader: 'image-webpack-loader', query: { progressive: true, optimizationLevel: 7, interlaced: false, pngquant: { quality: '65-90', speed: 4, }, }, }, ], }, { test: /\.html$/, loader: 'html-loader', }, { test: /\.json$/, loader: 'json-loader', }, { test: /\.(mp4|webm)$/, loader: 'url-loader', query: { limit: 10000, }, }], }, plugins: options.plugins.concat([ new webpack.ProvidePlugin({ // make fetch available fetch: 'exports-loader?self.fetch!whatwg-fetch', }), // Always expose NODE_ENV to webpack, in order to use `process.env.NODE_ENV` // inside your code for any environment checks; UglifyJS will automatically // drop any unreachable code. new webpack.DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify(process.env.NODE_ENV), }, }), new webpack.NamedModulesPlugin(), new webpack.IgnorePlugin(/\.\/locale$/), ]), resolve: { modules: ['app', 'node_modules'], extensions: [ '.js', '.jsx', '.react.js', ], mainFields: [ 'browser', 'jsnext:main', 'main', ], }, devtool: options.devtool, target: 'web', // Make web variables accessible to webpack, e.g. window performance: options.performance || {}, });
import React from 'react'; import ResumeStyles from './../../styles/resume'; export default React.createClass({ render() { return ( <header className="main-header"> <ul id="navMenu" className="site-nav"> <li data-menuanchor="about-me"> <a className="nav-link" href="#about-me">About</a> </li> <li data-menuanchor="projects"> <a className="nav-link" href="#projects">Projects</a> </li> <li data-menuanchor="contact"> <a className="nav-link" href="#contact">Contact</a> </li> </ul> </header> ); } })
import React from 'react'; import { graphql } from 'gatsby'; import Layout from '../components/Layout'; import Sidebar from '../components/Sidebar'; import Feed from '../components/Feed'; import Page from '../components/Page'; import Pagination from '../components/Pagination'; const IndexTemplate = ({ data, pageContext }) => { const { title: siteTitle, subtitle: siteSubtitle } = data.site.siteMetadata; const { currentPage, hasNextPage, hasPrevPage, prevPagePath, nextPagePath } = pageContext; const { edges } = data.allMarkdownRemark; const pageTitle = currentPage > 0 ? `Posts - Page ${currentPage} - ${siteTitle}` : siteTitle; return ( <Layout title={pageTitle} description={siteSubtitle}> <Sidebar isIndex /> <Page> <Feed edges={edges} /> <Pagination prevPagePath={prevPagePath} nextPagePath={nextPagePath} hasPrevPage={hasPrevPage} hasNextPage={hasNextPage} /> </Page> </Layout> ); }; export const query = graphql` query IndexTemplate($postsLimit: Int!, $postsOffset: Int!) { site { siteMetadata { title subtitle } } allMarkdownRemark( limit: $postsLimit, skip: $postsOffset, filter: { frontmatter: { template: { eq: "post" }, draft: { ne: true } } }, sort: { order: DESC, fields: [frontmatter___date] } ){ edges { node { fields { slug categorySlug } frontmatter { title date category description } } } } } `; export default IndexTemplate;
// Agency Theme JavaScript (function($) { "use strict"; // Start of use strict // jQuery for page scrolling feature - requires jQuery Easing plugin $(document).on('click', 'a.page-scroll', function(event) { var $anchor = $(this); $('html, body').stop().animate({ scrollTop: ($($anchor.attr('href')).offset().top - 54) }, 1250, 'easeInOutExpo'); event.preventDefault(); }); // Highlight the top nav as scrolling occurs $('body').scrollspy({ target: '#mainNav', offset: 54 }); // Closes the Responsive Menu on Menu Item Click $('.navbar-collapse>ul>li>a').click(function() { $('.navbar-collapse').collapse('hide'); }); // jQuery to collapse the navbar on scroll $(window).scroll(function() { if ($("#mainNav").offset().top > 100) { $("#mainNav").addClass("navbar-shrink"); } else { $("#mainNav").removeClass("navbar-shrink"); } }); $(window).scroll(function(){ $(".frontpage .top").css("opacity", 1 - $(window).scrollTop() / 800); }); $(document).on('click', '.click-open', function(event) { $('.text-wrap').toggleClass('open'); }); })(jQuery); // End of use strict
import Vue from 'vue'; import Router from 'vue-router'; import { routes } from '../app'; Vue.use(Router); export default new Router({ mode: 'hash', routes: routes });
/** * Account Manager System (https://github.com/PsyduckMans/accountmanager) * * @link https://github.com/PsyduckMans/accountmanager for the canonical source repository * @copyright Copyright (c) 2014 PsyduckMans (https://ninth.not-bad.org) * @license https://github.com/PsyduckMans/accountmanager/blob/master/LICENSE MIT * @author Psyduck.Mans */ Ext.define('AccountManager.model.User', { extend: 'Ext.data.Model', fields: [ {name:'UserId', type:'int'}, 'Name', 'NickName', {name:'RoleId', type:'int'}, 'RoleName', 'Password', {name:'CreateTime', type:'date', dateFormat:'c'}, {name:'UpdateTime', type:'date', dateFormat:'c'} ], idProperty:'UserId' });
export const arrowUp = {"viewBox":"0 0 10 16","children":[{"name":"path","attribs":{"fill-rule":"evenodd","d":"M5 3L0 9h3v4h4V9h3L5 3z"},"children":[]}],"attribs":{}};
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M19 5v14H5V5h14m0-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-4.86 8.86l-3 3.87L9 13.14 6 17h12l-3.86-5.14z" /> , 'PhotoOutlined');
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type {ReactProviderType, ReactContext} from 'shared/ReactTypes'; import type {LazyComponent as LazyComponentType} from 'react/src/ReactLazy'; import type {Fiber, FiberRoot} from './ReactInternalTypes'; import type {TypeOfMode} from './ReactTypeOfMode'; import type {Lanes, Lane} from './ReactFiberLane.new'; import type {MutableSource} from 'shared/ReactTypes'; import type { SuspenseState, SuspenseListRenderState, SuspenseListTailMode, } from './ReactFiberSuspenseComponent.new'; import type {SuspenseContext} from './ReactFiberSuspenseContext.new'; import type { OffscreenProps, OffscreenState, } from './ReactFiberOffscreenComponent'; import type { Cache, CacheComponentState, SpawnedCachePool, } from './ReactFiberCacheComponent.new'; import type {UpdateQueue} from './ReactUpdateQueue.new'; import {enableSuspenseAvoidThisFallback} from 'shared/ReactFeatureFlags'; import checkPropTypes from 'shared/checkPropTypes'; import { markComponentRenderStarted, markComponentRenderStopped, setIsStrictModeForDevtools, } from './ReactFiberDevToolsHook.new'; import { IndeterminateComponent, FunctionComponent, ClassComponent, HostRoot, HostComponent, HostText, HostPortal, ForwardRef, Fragment, Mode, ContextProvider, ContextConsumer, Profiler, SuspenseComponent, SuspenseListComponent, MemoComponent, SimpleMemoComponent, LazyComponent, IncompleteClassComponent, ScopeComponent, OffscreenComponent, LegacyHiddenComponent, CacheComponent, } from './ReactWorkTags'; import { NoFlags, PerformedWork, Placement, Hydrating, ContentReset, DidCapture, Update, Ref, RefStatic, ChildDeletion, ForceUpdateForLegacySuspense, StaticMask, ShouldCapture, ForceClientRender, } from './ReactFiberFlags'; import ReactSharedInternals from 'shared/ReactSharedInternals'; import { debugRenderPhaseSideEffectsForStrictMode, disableLegacyContext, disableModulePatternComponents, enableProfilerCommitHooks, enableProfilerTimer, enableSuspenseServerRenderer, warnAboutDefaultPropsOnFunctionComponents, enableScopeAPI, enableCache, enableLazyContextPropagation, enableSuspenseLayoutEffectSemantics, enableSchedulingProfiler, enablePersistentOffscreenHostContainer, } from 'shared/ReactFeatureFlags'; import isArray from 'shared/isArray'; import shallowEqual from 'shared/shallowEqual'; import getComponentNameFromFiber from 'react-reconciler/src/getComponentNameFromFiber'; import getComponentNameFromType from 'shared/getComponentNameFromType'; import ReactStrictModeWarnings from './ReactStrictModeWarnings.new'; import {REACT_LAZY_TYPE, getIteratorFn} from 'shared/ReactSymbols'; import { getCurrentFiberOwnerNameInDevOrNull, setIsRendering, } from './ReactCurrentFiber'; import { resolveFunctionForHotReloading, resolveForwardRefForHotReloading, resolveClassForHotReloading, } from './ReactFiberHotReloading.new'; import { mountChildFibers, reconcileChildFibers, cloneChildFibers, } from './ReactChildFiber.new'; import { processUpdateQueue, cloneUpdateQueue, initializeUpdateQueue, enqueueCapturedUpdate, } from './ReactUpdateQueue.new'; import { NoLane, NoLanes, SyncLane, OffscreenLane, DefaultHydrationLane, SomeRetryLane, NoTimestamp, includesSomeLane, laneToLanes, removeLanes, mergeLanes, getBumpedLaneForHydration, pickArbitraryLane, } from './ReactFiberLane.new'; import { ConcurrentMode, NoMode, ProfileMode, StrictLegacyMode, } from './ReactTypeOfMode'; import { shouldSetTextContent, isSuspenseInstancePending, isSuspenseInstanceFallback, registerSuspenseInstanceRetry, supportsHydration, isPrimaryRenderer, supportsPersistence, getOffscreenContainerProps, } from './ReactFiberHostConfig'; import type {SuspenseInstance} from './ReactFiberHostConfig'; import {shouldError, shouldSuspend} from './ReactFiberReconciler'; import {pushHostContext, pushHostContainer} from './ReactFiberHostContext.new'; import { suspenseStackCursor, pushSuspenseContext, InvisibleParentSuspenseContext, ForceSuspenseFallback, hasSuspenseContext, setDefaultShallowSuspenseContext, addSubtreeSuspenseContext, setShallowSuspenseContext, } from './ReactFiberSuspenseContext.new'; import {findFirstSuspended} from './ReactFiberSuspenseComponent.new'; import { pushProvider, propagateContextChange, lazilyPropagateParentContextChanges, propagateParentContextChangesToDeferredTree, checkIfContextChanged, readContext, prepareToReadContext, scheduleContextWorkOnParentPath, } from './ReactFiberNewContext.new'; import { renderWithHooks, checkDidRenderIdHook, bailoutHooks, } from './ReactFiberHooks.new'; import {stopProfilerTimerIfRunning} from './ReactProfilerTimer.new'; import { getMaskedContext, getUnmaskedContext, hasContextChanged as hasLegacyContextChanged, pushContextProvider as pushLegacyContextProvider, isContextProvider as isLegacyContextProvider, pushTopLevelContextObject, invalidateContextProvider, } from './ReactFiberContext.new'; import { getIsHydrating, enterHydrationState, reenterHydrationStateFromDehydratedSuspenseInstance, resetHydrationState, tryToClaimNextHydratableInstance, warnIfHydrating, } from './ReactFiberHydrationContext.new'; import { adoptClassInstance, constructClassInstance, mountClassInstance, resumeMountClassInstance, updateClassInstance, } from './ReactFiberClassComponent.new'; import {resolveDefaultProps} from './ReactFiberLazyComponent.new'; import { resolveLazyComponentTag, createFiberFromTypeAndProps, createFiberFromFragment, createFiberFromOffscreen, createWorkInProgress, createOffscreenHostContainerFiber, isSimpleFunctionComponent, } from './ReactFiber.new'; import { retryDehydratedSuspenseBoundary, scheduleUpdateOnFiber, renderDidSuspendDelayIfPossible, markSkippedUpdateLanes, getWorkInProgressRoot, pushRenderLanes, getExecutionContext, RetryAfterError, NoContext, } from './ReactFiberWorkLoop.new'; import {setWorkInProgressVersion} from './ReactMutableSource.new'; import { requestCacheFromPool, pushCacheProvider, pushRootCachePool, CacheContext, getSuspendedCachePool, restoreSpawnedCachePool, getOffscreenDeferredCachePool, } from './ReactFiberCacheComponent.new'; import {createCapturedValue} from './ReactCapturedValue'; import {createClassErrorUpdate} from './ReactFiberThrow.new'; import {completeSuspendedOffscreenHostContainer} from './ReactFiberCompleteWork.new'; import is from 'shared/objectIs'; import { getForksAtLevel, isForkedChild, pushTreeId, pushMaterializedTreeId, } from './ReactFiberTreeContext.new'; const ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner; let didReceiveUpdate: boolean = false; let didWarnAboutBadClass; let didWarnAboutModulePatternComponent; let didWarnAboutContextTypeOnFunctionComponent; let didWarnAboutGetDerivedStateOnFunctionComponent; let didWarnAboutFunctionRefs; export let didWarnAboutReassigningProps; let didWarnAboutRevealOrder; let didWarnAboutTailOptions; let didWarnAboutDefaultPropsOnFunctionComponent; if (__DEV__) { didWarnAboutBadClass = {}; didWarnAboutModulePatternComponent = {}; didWarnAboutContextTypeOnFunctionComponent = {}; didWarnAboutGetDerivedStateOnFunctionComponent = {}; didWarnAboutFunctionRefs = {}; didWarnAboutReassigningProps = false; didWarnAboutRevealOrder = {}; didWarnAboutTailOptions = {}; didWarnAboutDefaultPropsOnFunctionComponent = {}; } export function reconcileChildren( current: Fiber | null, workInProgress: Fiber, nextChildren: any, renderLanes: Lanes, ) { if (current === null) { // If this is a fresh new component that hasn't been rendered yet, we // won't update its child set by applying minimal side-effects. Instead, // we will add them all to the child before it gets rendered. That means // we can optimize this reconciliation pass by not tracking side-effects. workInProgress.child = mountChildFibers( workInProgress, null, nextChildren, renderLanes, ); } else { // If the current child is the same as the work in progress, it means that // we haven't yet started any work on these children. Therefore, we use // the clone algorithm to create a copy of all the current children. // If we had any progressed work already, that is invalid at this point so // let's throw it out. workInProgress.child = reconcileChildFibers( workInProgress, current.child, nextChildren, renderLanes, ); } } function forceUnmountCurrentAndReconcile( current: Fiber, workInProgress: Fiber, nextChildren: any, renderLanes: Lanes, ) { // This function is fork of reconcileChildren. It's used in cases where we // want to reconcile without matching against the existing set. This has the // effect of all current children being unmounted; even if the type and key // are the same, the old child is unmounted and a new child is created. // // To do this, we're going to go through the reconcile algorithm twice. In // the first pass, we schedule a deletion for all the current children by // passing null. workInProgress.child = reconcileChildFibers( workInProgress, current.child, null, renderLanes, ); // In the second pass, we mount the new children. The trick here is that we // pass null in place of where we usually pass the current child set. This has // the effect of remounting all children regardless of whether their // identities match. workInProgress.child = reconcileChildFibers( workInProgress, null, nextChildren, renderLanes, ); } function updateForwardRef( current: Fiber | null, workInProgress: Fiber, Component: any, nextProps: any, renderLanes: Lanes, ) { // TODO: current can be non-null here even if the component // hasn't yet mounted. This happens after the first render suspends. // We'll need to figure out if this is fine or can cause issues. if (__DEV__) { if (workInProgress.type !== workInProgress.elementType) { // Lazy component props can't be validated in createElement // because they're only guaranteed to be resolved here. const innerPropTypes = Component.propTypes; if (innerPropTypes) { checkPropTypes( innerPropTypes, nextProps, // Resolved props 'prop', getComponentNameFromType(Component), ); } } } const render = Component.render; const ref = workInProgress.ref; // The rest is a fork of updateFunctionComponent let nextChildren; let hasId; prepareToReadContext(workInProgress, renderLanes); if (enableSchedulingProfiler) { markComponentRenderStarted(workInProgress); } if (__DEV__) { ReactCurrentOwner.current = workInProgress; setIsRendering(true); nextChildren = renderWithHooks( current, workInProgress, render, nextProps, ref, renderLanes, ); hasId = checkDidRenderIdHook(); if ( debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictLegacyMode ) { setIsStrictModeForDevtools(true); try { nextChildren = renderWithHooks( current, workInProgress, render, nextProps, ref, renderLanes, ); hasId = checkDidRenderIdHook(); } finally { setIsStrictModeForDevtools(false); } } setIsRendering(false); } else { nextChildren = renderWithHooks( current, workInProgress, render, nextProps, ref, renderLanes, ); hasId = checkDidRenderIdHook(); } if (enableSchedulingProfiler) { markComponentRenderStopped(); } if (current !== null && !didReceiveUpdate) { bailoutHooks(current, workInProgress, renderLanes); return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); } if (getIsHydrating() && hasId) { pushMaterializedTreeId(workInProgress); } // React DevTools reads this flag. workInProgress.flags |= PerformedWork; reconcileChildren(current, workInProgress, nextChildren, renderLanes); return workInProgress.child; } function updateMemoComponent( current: Fiber | null, workInProgress: Fiber, Component: any, nextProps: any, renderLanes: Lanes, ): null | Fiber { if (current === null) { const type = Component.type; if ( isSimpleFunctionComponent(type) && Component.compare === null && // SimpleMemoComponent codepath doesn't resolve outer props either. Component.defaultProps === undefined ) { let resolvedType = type; if (__DEV__) { resolvedType = resolveFunctionForHotReloading(type); } // If this is a plain function component without default props, // and with only the default shallow comparison, we upgrade it // to a SimpleMemoComponent to allow fast path updates. workInProgress.tag = SimpleMemoComponent; workInProgress.type = resolvedType; if (__DEV__) { validateFunctionComponentInDev(workInProgress, type); } return updateSimpleMemoComponent( current, workInProgress, resolvedType, nextProps, renderLanes, ); } if (__DEV__) { const innerPropTypes = type.propTypes; if (innerPropTypes) { // Inner memo component props aren't currently validated in createElement. // We could move it there, but we'd still need this for lazy code path. checkPropTypes( innerPropTypes, nextProps, // Resolved props 'prop', getComponentNameFromType(type), ); } } const child = createFiberFromTypeAndProps( Component.type, null, nextProps, workInProgress, workInProgress.mode, renderLanes, ); child.ref = workInProgress.ref; child.return = workInProgress; workInProgress.child = child; return child; } if (__DEV__) { const type = Component.type; const innerPropTypes = type.propTypes; if (innerPropTypes) { // Inner memo component props aren't currently validated in createElement. // We could move it there, but we'd still need this for lazy code path. checkPropTypes( innerPropTypes, nextProps, // Resolved props 'prop', getComponentNameFromType(type), ); } } const currentChild = ((current.child: any): Fiber); // This is always exactly one child const hasScheduledUpdateOrContext = checkScheduledUpdateOrContext( current, renderLanes, ); if (!hasScheduledUpdateOrContext) { // This will be the props with resolved defaultProps, // unlike current.memoizedProps which will be the unresolved ones. const prevProps = currentChild.memoizedProps; // Default to shallow comparison let compare = Component.compare; compare = compare !== null ? compare : shallowEqual; if (compare(prevProps, nextProps) && current.ref === workInProgress.ref) { return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); } } // React DevTools reads this flag. workInProgress.flags |= PerformedWork; const newChild = createWorkInProgress(currentChild, nextProps); newChild.ref = workInProgress.ref; newChild.return = workInProgress; workInProgress.child = newChild; return newChild; } function updateSimpleMemoComponent( current: Fiber | null, workInProgress: Fiber, Component: any, nextProps: any, renderLanes: Lanes, ): null | Fiber { // TODO: current can be non-null here even if the component // hasn't yet mounted. This happens when the inner render suspends. // We'll need to figure out if this is fine or can cause issues. if (__DEV__) { if (workInProgress.type !== workInProgress.elementType) { // Lazy component props can't be validated in createElement // because they're only guaranteed to be resolved here. let outerMemoType = workInProgress.elementType; if (outerMemoType.$$typeof === REACT_LAZY_TYPE) { // We warn when you define propTypes on lazy() // so let's just skip over it to find memo() outer wrapper. // Inner props for memo are validated later. const lazyComponent: LazyComponentType<any, any> = outerMemoType; const payload = lazyComponent._payload; const init = lazyComponent._init; try { outerMemoType = init(payload); } catch (x) { outerMemoType = null; } // Inner propTypes will be validated in the function component path. const outerPropTypes = outerMemoType && (outerMemoType: any).propTypes; if (outerPropTypes) { checkPropTypes( outerPropTypes, nextProps, // Resolved (SimpleMemoComponent has no defaultProps) 'prop', getComponentNameFromType(outerMemoType), ); } } } } if (current !== null) { const prevProps = current.memoizedProps; if ( shallowEqual(prevProps, nextProps) && current.ref === workInProgress.ref && // Prevent bailout if the implementation changed due to hot reload. (__DEV__ ? workInProgress.type === current.type : true) ) { didReceiveUpdate = false; if (!checkScheduledUpdateOrContext(current, renderLanes)) { // The pending lanes were cleared at the beginning of beginWork. We're // about to bail out, but there might be other lanes that weren't // included in the current render. Usually, the priority level of the // remaining updates is accumulated during the evaluation of the // component (i.e. when processing the update queue). But since since // we're bailing out early *without* evaluating the component, we need // to account for it here, too. Reset to the value of the current fiber. // NOTE: This only applies to SimpleMemoComponent, not MemoComponent, // because a MemoComponent fiber does not have hooks or an update queue; // rather, it wraps around an inner component, which may or may not // contains hooks. // TODO: Move the reset at in beginWork out of the common path so that // this is no longer necessary. workInProgress.lanes = current.lanes; return bailoutOnAlreadyFinishedWork( current, workInProgress, renderLanes, ); } else if ((current.flags & ForceUpdateForLegacySuspense) !== NoFlags) { // This is a special case that only exists for legacy mode. // See https://github.com/facebook/react/pull/19216. didReceiveUpdate = true; } } } return updateFunctionComponent( current, workInProgress, Component, nextProps, renderLanes, ); } function updateOffscreenComponent( current: Fiber | null, workInProgress: Fiber, renderLanes: Lanes, ) { const nextProps: OffscreenProps = workInProgress.pendingProps; const nextChildren = nextProps.children; const prevState: OffscreenState | null = current !== null ? current.memoizedState : null; // If this is not null, this is a cache pool that was carried over from the // previous render. We will push this to the cache pool context so that we can // resume in-flight requests. let spawnedCachePool: SpawnedCachePool | null = null; if ( nextProps.mode === 'hidden' || nextProps.mode === 'unstable-defer-without-hiding' ) { // Rendering a hidden tree. if ((workInProgress.mode & ConcurrentMode) === NoMode) { // In legacy sync mode, don't defer the subtree. Render it now. const nextState: OffscreenState = { baseLanes: NoLanes, cachePool: null, }; workInProgress.memoizedState = nextState; pushRenderLanes(workInProgress, renderLanes); } else if (!includesSomeLane(renderLanes, (OffscreenLane: Lane))) { // We're hidden, and we're not rendering at Offscreen. We will bail out // and resume this tree later. let nextBaseLanes; if (prevState !== null) { const prevBaseLanes = prevState.baseLanes; nextBaseLanes = mergeLanes(prevBaseLanes, renderLanes); if (enableCache) { // Save the cache pool so we can resume later. spawnedCachePool = getOffscreenDeferredCachePool(); // We don't need to push to the cache pool because we're about to // bail out. There won't be a context mismatch because we only pop // the cache pool if `updateQueue` is non-null. } } else { nextBaseLanes = renderLanes; } // Schedule this fiber to re-render at offscreen priority. Then bailout. workInProgress.lanes = workInProgress.childLanes = laneToLanes( OffscreenLane, ); const nextState: OffscreenState = { baseLanes: nextBaseLanes, cachePool: spawnedCachePool, }; workInProgress.memoizedState = nextState; workInProgress.updateQueue = null; // We're about to bail out, but we need to push this to the stack anyway // to avoid a push/pop misalignment. pushRenderLanes(workInProgress, nextBaseLanes); if (enableLazyContextPropagation && current !== null) { // Since this tree will resume rendering in a separate render, we need // to propagate parent contexts now so we don't lose track of which // ones changed. propagateParentContextChangesToDeferredTree( current, workInProgress, renderLanes, ); } return null; } else { // This is the second render. The surrounding visible content has already // committed. Now we resume rendering the hidden tree. if (enableCache && prevState !== null) { // If the render that spawned this one accessed the cache pool, resume // using the same cache. Unless the parent changed, since that means // there was a refresh. const prevCachePool = prevState.cachePool; if (prevCachePool !== null) { spawnedCachePool = restoreSpawnedCachePool( workInProgress, prevCachePool, ); } } // Rendering at offscreen, so we can clear the base lanes. const nextState: OffscreenState = { baseLanes: NoLanes, cachePool: null, }; workInProgress.memoizedState = nextState; // Push the lanes that were skipped when we bailed out. const subtreeRenderLanes = prevState !== null ? prevState.baseLanes : renderLanes; pushRenderLanes(workInProgress, subtreeRenderLanes); } } else { // Rendering a visible tree. let subtreeRenderLanes; if (prevState !== null) { // We're going from hidden -> visible. subtreeRenderLanes = mergeLanes(prevState.baseLanes, renderLanes); if (enableCache) { // If the render that spawned this one accessed the cache pool, resume // using the same cache. Unless the parent changed, since that means // there was a refresh. const prevCachePool = prevState.cachePool; if (prevCachePool !== null) { spawnedCachePool = restoreSpawnedCachePool( workInProgress, prevCachePool, ); } } // Since we're not hidden anymore, reset the state workInProgress.memoizedState = null; } else { // We weren't previously hidden, and we still aren't, so there's nothing // special to do. Need to push to the stack regardless, though, to avoid // a push/pop misalignment. subtreeRenderLanes = renderLanes; } pushRenderLanes(workInProgress, subtreeRenderLanes); } if (enableCache) { // If we have a cache pool from a previous render attempt, then this will be // non-null. We use this to infer whether to push/pop the cache context. workInProgress.updateQueue = spawnedCachePool; } if (enablePersistentOffscreenHostContainer && supportsPersistence) { // In persistent mode, the offscreen children are wrapped in a host node. // TODO: Optimize this to use the OffscreenComponent fiber instead of // an extra HostComponent fiber. Need to make sure this doesn't break Fabric // or some other infra that expects a HostComponent. const isHidden = nextProps.mode === 'hidden' && workInProgress.tag !== LegacyHiddenComponent; const offscreenContainer = reconcileOffscreenHostContainer( current, workInProgress, isHidden, nextChildren, renderLanes, ); return offscreenContainer; } else { reconcileChildren(current, workInProgress, nextChildren, renderLanes); return workInProgress.child; } } function reconcileOffscreenHostContainer( currentOffscreen: Fiber | null, offscreen: Fiber, isHidden: boolean, children: any, renderLanes: Lanes, ) { const containerProps = getOffscreenContainerProps( isHidden ? 'hidden' : 'visible', children, ); let hostContainer; if (currentOffscreen === null) { hostContainer = createOffscreenHostContainerFiber( containerProps, offscreen.mode, renderLanes, null, ); } else { const currentHostContainer = currentOffscreen.child; if (currentHostContainer === null) { hostContainer = createOffscreenHostContainerFiber( containerProps, offscreen.mode, renderLanes, null, ); hostContainer.flags |= Placement; } else { hostContainer = createWorkInProgress( currentHostContainer, containerProps, ); } } hostContainer.return = offscreen; offscreen.child = hostContainer; return hostContainer; } // Note: These happen to have identical begin phases, for now. We shouldn't hold // ourselves to this constraint, though. If the behavior diverges, we should // fork the function. const updateLegacyHiddenComponent = updateOffscreenComponent; function updateCacheComponent( current: Fiber | null, workInProgress: Fiber, renderLanes: Lanes, ) { if (!enableCache) { return null; } prepareToReadContext(workInProgress, renderLanes); const parentCache = readContext(CacheContext); if (current === null) { // Initial mount. Request a fresh cache from the pool. const freshCache = requestCacheFromPool(renderLanes); const initialState: CacheComponentState = { parent: parentCache, cache: freshCache, }; workInProgress.memoizedState = initialState; initializeUpdateQueue(workInProgress); pushCacheProvider(workInProgress, freshCache); } else { // Check for updates if (includesSomeLane(current.lanes, renderLanes)) { cloneUpdateQueue(current, workInProgress); processUpdateQueue(workInProgress, null, null, renderLanes); } const prevState: CacheComponentState = current.memoizedState; const nextState: CacheComponentState = workInProgress.memoizedState; // Compare the new parent cache to the previous to see detect there was // a refresh. if (prevState.parent !== parentCache) { // Refresh in parent. Update the parent. const derivedState: CacheComponentState = { parent: parentCache, cache: parentCache, }; // Copied from getDerivedStateFromProps implementation. Once the update // queue is empty, persist the derived state onto the base state. workInProgress.memoizedState = derivedState; if (workInProgress.lanes === NoLanes) { const updateQueue: UpdateQueue<any> = (workInProgress.updateQueue: any); workInProgress.memoizedState = updateQueue.baseState = derivedState; } pushCacheProvider(workInProgress, parentCache); // No need to propagate a context change because the refreshed parent // already did. } else { // The parent didn't refresh. Now check if this cache did. const nextCache = nextState.cache; pushCacheProvider(workInProgress, nextCache); if (nextCache !== prevState.cache) { // This cache refreshed. Propagate a context change. propagateContextChange(workInProgress, CacheContext, renderLanes); } } } const nextChildren = workInProgress.pendingProps.children; reconcileChildren(current, workInProgress, nextChildren, renderLanes); return workInProgress.child; } function updateFragment( current: Fiber | null, workInProgress: Fiber, renderLanes: Lanes, ) { const nextChildren = workInProgress.pendingProps; reconcileChildren(current, workInProgress, nextChildren, renderLanes); return workInProgress.child; } function updateMode( current: Fiber | null, workInProgress: Fiber, renderLanes: Lanes, ) { const nextChildren = workInProgress.pendingProps.children; reconcileChildren(current, workInProgress, nextChildren, renderLanes); return workInProgress.child; } function updateProfiler( current: Fiber | null, workInProgress: Fiber, renderLanes: Lanes, ) { if (enableProfilerTimer) { workInProgress.flags |= Update; if (enableProfilerCommitHooks) { // Reset effect durations for the next eventual effect phase. // These are reset during render to allow the DevTools commit hook a chance to read them, const stateNode = workInProgress.stateNode; stateNode.effectDuration = 0; stateNode.passiveEffectDuration = 0; } } const nextProps = workInProgress.pendingProps; const nextChildren = nextProps.children; reconcileChildren(current, workInProgress, nextChildren, renderLanes); return workInProgress.child; } function markRef(current: Fiber | null, workInProgress: Fiber) { const ref = workInProgress.ref; if ( (current === null && ref !== null) || (current !== null && current.ref !== ref) ) { // Schedule a Ref effect workInProgress.flags |= Ref; if (enableSuspenseLayoutEffectSemantics) { workInProgress.flags |= RefStatic; } } } function updateFunctionComponent( current, workInProgress, Component, nextProps: any, renderLanes, ) { if (__DEV__) { if (workInProgress.type !== workInProgress.elementType) { // Lazy component props can't be validated in createElement // because they're only guaranteed to be resolved here. const innerPropTypes = Component.propTypes; if (innerPropTypes) { checkPropTypes( innerPropTypes, nextProps, // Resolved props 'prop', getComponentNameFromType(Component), ); } } } let context; if (!disableLegacyContext) { const unmaskedContext = getUnmaskedContext(workInProgress, Component, true); context = getMaskedContext(workInProgress, unmaskedContext); } let nextChildren; let hasId; prepareToReadContext(workInProgress, renderLanes); if (enableSchedulingProfiler) { markComponentRenderStarted(workInProgress); } if (__DEV__) { ReactCurrentOwner.current = workInProgress; setIsRendering(true); nextChildren = renderWithHooks( current, workInProgress, Component, nextProps, context, renderLanes, ); hasId = checkDidRenderIdHook(); if ( debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictLegacyMode ) { setIsStrictModeForDevtools(true); try { nextChildren = renderWithHooks( current, workInProgress, Component, nextProps, context, renderLanes, ); hasId = checkDidRenderIdHook(); } finally { setIsStrictModeForDevtools(false); } } setIsRendering(false); } else { nextChildren = renderWithHooks( current, workInProgress, Component, nextProps, context, renderLanes, ); hasId = checkDidRenderIdHook(); } if (enableSchedulingProfiler) { markComponentRenderStopped(); } if (current !== null && !didReceiveUpdate) { bailoutHooks(current, workInProgress, renderLanes); return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); } if (getIsHydrating() && hasId) { pushMaterializedTreeId(workInProgress); } // React DevTools reads this flag. workInProgress.flags |= PerformedWork; reconcileChildren(current, workInProgress, nextChildren, renderLanes); return workInProgress.child; } function updateClassComponent( current: Fiber | null, workInProgress: Fiber, Component: any, nextProps: any, renderLanes: Lanes, ) { if (__DEV__) { // This is used by DevTools to force a boundary to error. switch (shouldError(workInProgress)) { case false: { const instance = workInProgress.stateNode; const ctor = workInProgress.type; // TODO This way of resetting the error boundary state is a hack. // Is there a better way to do this? const tempInstance = new ctor( workInProgress.memoizedProps, instance.context, ); const state = tempInstance.state; instance.updater.enqueueSetState(instance, state, null); break; } case true: { workInProgress.flags |= DidCapture; workInProgress.flags |= ShouldCapture; // eslint-disable-next-line react-internal/prod-error-codes const error = new Error('Simulated error coming from DevTools'); const lane = pickArbitraryLane(renderLanes); workInProgress.lanes = mergeLanes(workInProgress.lanes, lane); // Schedule the error boundary to re-render using updated state const update = createClassErrorUpdate( workInProgress, createCapturedValue(error, workInProgress), lane, ); enqueueCapturedUpdate(workInProgress, update); break; } } if (workInProgress.type !== workInProgress.elementType) { // Lazy component props can't be validated in createElement // because they're only guaranteed to be resolved here. const innerPropTypes = Component.propTypes; if (innerPropTypes) { checkPropTypes( innerPropTypes, nextProps, // Resolved props 'prop', getComponentNameFromType(Component), ); } } } // Push context providers early to prevent context stack mismatches. // During mounting we don't know the child context yet as the instance doesn't exist. // We will invalidate the child context in finishClassComponent() right after rendering. let hasContext; if (isLegacyContextProvider(Component)) { hasContext = true; pushLegacyContextProvider(workInProgress); } else { hasContext = false; } prepareToReadContext(workInProgress, renderLanes); const instance = workInProgress.stateNode; let shouldUpdate; if (instance === null) { if (current !== null) { // A class component without an instance only mounts if it suspended // inside a non-concurrent tree, in an inconsistent state. We want to // treat it like a new mount, even though an empty version of it already // committed. Disconnect the alternate pointers. current.alternate = null; workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect workInProgress.flags |= Placement; } // In the initial pass we might need to construct the instance. constructClassInstance(workInProgress, Component, nextProps); mountClassInstance(workInProgress, Component, nextProps, renderLanes); shouldUpdate = true; } else if (current === null) { // In a resume, we'll already have an instance we can reuse. shouldUpdate = resumeMountClassInstance( workInProgress, Component, nextProps, renderLanes, ); } else { shouldUpdate = updateClassInstance( current, workInProgress, Component, nextProps, renderLanes, ); } const nextUnitOfWork = finishClassComponent( current, workInProgress, Component, shouldUpdate, hasContext, renderLanes, ); if (__DEV__) { const inst = workInProgress.stateNode; if (shouldUpdate && inst.props !== nextProps) { if (!didWarnAboutReassigningProps) { console.error( 'It looks like %s is reassigning its own `this.props` while rendering. ' + 'This is not supported and can lead to confusing bugs.', getComponentNameFromFiber(workInProgress) || 'a component', ); } didWarnAboutReassigningProps = true; } } return nextUnitOfWork; } function finishClassComponent( current: Fiber | null, workInProgress: Fiber, Component: any, shouldUpdate: boolean, hasContext: boolean, renderLanes: Lanes, ) { // Refs should update even if shouldComponentUpdate returns false markRef(current, workInProgress); const didCaptureError = (workInProgress.flags & DidCapture) !== NoFlags; if (!shouldUpdate && !didCaptureError) { // Context providers should defer to sCU for rendering if (hasContext) { invalidateContextProvider(workInProgress, Component, false); } return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); } const instance = workInProgress.stateNode; // Rerender ReactCurrentOwner.current = workInProgress; let nextChildren; if ( didCaptureError && typeof Component.getDerivedStateFromError !== 'function' ) { // If we captured an error, but getDerivedStateFromError is not defined, // unmount all the children. componentDidCatch will schedule an update to // re-render a fallback. This is temporary until we migrate everyone to // the new API. // TODO: Warn in a future release. nextChildren = null; if (enableProfilerTimer) { stopProfilerTimerIfRunning(workInProgress); } } else { if (enableSchedulingProfiler) { markComponentRenderStarted(workInProgress); } if (__DEV__) { setIsRendering(true); nextChildren = instance.render(); if ( debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictLegacyMode ) { setIsStrictModeForDevtools(true); try { instance.render(); } finally { setIsStrictModeForDevtools(false); } } setIsRendering(false); } else { nextChildren = instance.render(); } if (enableSchedulingProfiler) { markComponentRenderStopped(); } } // React DevTools reads this flag. workInProgress.flags |= PerformedWork; if (current !== null && didCaptureError) { // If we're recovering from an error, reconcile without reusing any of // the existing children. Conceptually, the normal children and the children // that are shown on error are two different sets, so we shouldn't reuse // normal children even if their identities match. forceUnmountCurrentAndReconcile( current, workInProgress, nextChildren, renderLanes, ); } else { reconcileChildren(current, workInProgress, nextChildren, renderLanes); } // Memoize state using the values we just used to render. // TODO: Restructure so we never read values from the instance. workInProgress.memoizedState = instance.state; // The context might have changed so we need to recalculate it. if (hasContext) { invalidateContextProvider(workInProgress, Component, true); } return workInProgress.child; } function pushHostRootContext(workInProgress) { const root = (workInProgress.stateNode: FiberRoot); if (root.pendingContext) { pushTopLevelContextObject( workInProgress, root.pendingContext, root.pendingContext !== root.context, ); } else if (root.context) { // Should always be set pushTopLevelContextObject(workInProgress, root.context, false); } pushHostContainer(workInProgress, root.containerInfo); } function updateHostRoot(current, workInProgress, renderLanes) { pushHostRootContext(workInProgress); const updateQueue = workInProgress.updateQueue; if (current === null || updateQueue === null) { throw new Error( 'If the root does not have an updateQueue, we should have already ' + 'bailed out. This error is likely caused by a bug in React. Please ' + 'file an issue.', ); } const nextProps = workInProgress.pendingProps; const prevState = workInProgress.memoizedState; const prevChildren = prevState.element; cloneUpdateQueue(current, workInProgress); processUpdateQueue(workInProgress, nextProps, null, renderLanes); const nextState = workInProgress.memoizedState; const root: FiberRoot = workInProgress.stateNode; if (enableCache) { const nextCache: Cache = nextState.cache; pushRootCachePool(root); pushCacheProvider(workInProgress, nextCache); if (nextCache !== prevState.cache) { // The root cache refreshed. propagateContextChange(workInProgress, CacheContext, renderLanes); } } // Caution: React DevTools currently depends on this property // being called "element". const nextChildren = nextState.element; if (nextChildren === prevChildren) { resetHydrationState(); return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); } if (root.isDehydrated && enterHydrationState(workInProgress)) { // If we don't have any current children this might be the first pass. // We always try to hydrate. If this isn't a hydration pass there won't // be any children to hydrate which is effectively the same thing as // not hydrating. if (supportsHydration) { const mutableSourceEagerHydrationData = root.mutableSourceEagerHydrationData; if (mutableSourceEagerHydrationData != null) { for (let i = 0; i < mutableSourceEagerHydrationData.length; i += 2) { const mutableSource = ((mutableSourceEagerHydrationData[ i ]: any): MutableSource<any>); const version = mutableSourceEagerHydrationData[i + 1]; setWorkInProgressVersion(mutableSource, version); } } } const child = mountChildFibers( workInProgress, null, nextChildren, renderLanes, ); workInProgress.child = child; let node = child; while (node) { // Mark each child as hydrating. This is a fast path to know whether this // tree is part of a hydrating tree. This is used to determine if a child // node has fully mounted yet, and for scheduling event replaying. // Conceptually this is similar to Placement in that a new subtree is // inserted into the React tree here. It just happens to not need DOM // mutations because it already exists. node.flags = (node.flags & ~Placement) | Hydrating; node = node.sibling; } } else { // Otherwise reset hydration state in case we aborted and resumed another // root. reconcileChildren(current, workInProgress, nextChildren, renderLanes); resetHydrationState(); } return workInProgress.child; } function updateHostComponent( current: Fiber | null, workInProgress: Fiber, renderLanes: Lanes, ) { pushHostContext(workInProgress); if (current === null) { tryToClaimNextHydratableInstance(workInProgress); } const type = workInProgress.type; const nextProps = workInProgress.pendingProps; const prevProps = current !== null ? current.memoizedProps : null; let nextChildren = nextProps.children; const isDirectTextChild = shouldSetTextContent(type, nextProps); if (isDirectTextChild) { // We special case a direct text child of a host node. This is a common // case. We won't handle it as a reified child. We will instead handle // this in the host environment that also has access to this prop. That // avoids allocating another HostText fiber and traversing it. nextChildren = null; } else if (prevProps !== null && shouldSetTextContent(type, prevProps)) { // If we're switching from a direct text child to a normal child, or to // empty, we need to schedule the text content to be reset. workInProgress.flags |= ContentReset; } markRef(current, workInProgress); reconcileChildren(current, workInProgress, nextChildren, renderLanes); return workInProgress.child; } function updateHostText(current, workInProgress) { if (current === null) { tryToClaimNextHydratableInstance(workInProgress); } // Nothing to do here. This is terminal. We'll do the completion step // immediately after. return null; } function mountLazyComponent( _current, workInProgress, elementType, renderLanes, ) { if (_current !== null) { // A lazy component only mounts if it suspended inside a non- // concurrent tree, in an inconsistent state. We want to treat it like // a new mount, even though an empty version of it already committed. // Disconnect the alternate pointers. _current.alternate = null; workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect workInProgress.flags |= Placement; } const props = workInProgress.pendingProps; const lazyComponent: LazyComponentType<any, any> = elementType; const payload = lazyComponent._payload; const init = lazyComponent._init; let Component = init(payload); // Store the unwrapped component in the type. workInProgress.type = Component; const resolvedTag = (workInProgress.tag = resolveLazyComponentTag(Component)); const resolvedProps = resolveDefaultProps(Component, props); let child; switch (resolvedTag) { case FunctionComponent: { if (__DEV__) { validateFunctionComponentInDev(workInProgress, Component); workInProgress.type = Component = resolveFunctionForHotReloading( Component, ); } child = updateFunctionComponent( null, workInProgress, Component, resolvedProps, renderLanes, ); return child; } case ClassComponent: { if (__DEV__) { workInProgress.type = Component = resolveClassForHotReloading( Component, ); } child = updateClassComponent( null, workInProgress, Component, resolvedProps, renderLanes, ); return child; } case ForwardRef: { if (__DEV__) { workInProgress.type = Component = resolveForwardRefForHotReloading( Component, ); } child = updateForwardRef( null, workInProgress, Component, resolvedProps, renderLanes, ); return child; } case MemoComponent: { if (__DEV__) { if (workInProgress.type !== workInProgress.elementType) { const outerPropTypes = Component.propTypes; if (outerPropTypes) { checkPropTypes( outerPropTypes, resolvedProps, // Resolved for outer only 'prop', getComponentNameFromType(Component), ); } } } child = updateMemoComponent( null, workInProgress, Component, resolveDefaultProps(Component.type, resolvedProps), // The inner type can have defaults too renderLanes, ); return child; } } let hint = ''; if (__DEV__) { if ( Component !== null && typeof Component === 'object' && Component.$$typeof === REACT_LAZY_TYPE ) { hint = ' Did you wrap a component in React.lazy() more than once?'; } } // This message intentionally doesn't mention ForwardRef or MemoComponent // because the fact that it's a separate type of work is an // implementation detail. throw new Error( `Element type is invalid. Received a promise that resolves to: ${Component}. ` + `Lazy element type must resolve to a class or function.${hint}`, ); } function mountIncompleteClassComponent( _current, workInProgress, Component, nextProps, renderLanes, ) { if (_current !== null) { // An incomplete component only mounts if it suspended inside a non- // concurrent tree, in an inconsistent state. We want to treat it like // a new mount, even though an empty version of it already committed. // Disconnect the alternate pointers. _current.alternate = null; workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect workInProgress.flags |= Placement; } // Promote the fiber to a class and try rendering again. workInProgress.tag = ClassComponent; // The rest of this function is a fork of `updateClassComponent` // Push context providers early to prevent context stack mismatches. // During mounting we don't know the child context yet as the instance doesn't exist. // We will invalidate the child context in finishClassComponent() right after rendering. let hasContext; if (isLegacyContextProvider(Component)) { hasContext = true; pushLegacyContextProvider(workInProgress); } else { hasContext = false; } prepareToReadContext(workInProgress, renderLanes); constructClassInstance(workInProgress, Component, nextProps); mountClassInstance(workInProgress, Component, nextProps, renderLanes); return finishClassComponent( null, workInProgress, Component, true, hasContext, renderLanes, ); } function mountIndeterminateComponent( _current, workInProgress, Component, renderLanes, ) { if (_current !== null) { // An indeterminate component only mounts if it suspended inside a non- // concurrent tree, in an inconsistent state. We want to treat it like // a new mount, even though an empty version of it already committed. // Disconnect the alternate pointers. _current.alternate = null; workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect workInProgress.flags |= Placement; } const props = workInProgress.pendingProps; let context; if (!disableLegacyContext) { const unmaskedContext = getUnmaskedContext( workInProgress, Component, false, ); context = getMaskedContext(workInProgress, unmaskedContext); } prepareToReadContext(workInProgress, renderLanes); let value; let hasId; if (enableSchedulingProfiler) { markComponentRenderStarted(workInProgress); } if (__DEV__) { if ( Component.prototype && typeof Component.prototype.render === 'function' ) { const componentName = getComponentNameFromType(Component) || 'Unknown'; if (!didWarnAboutBadClass[componentName]) { console.error( "The <%s /> component appears to have a render method, but doesn't extend React.Component. " + 'This is likely to cause errors. Change %s to extend React.Component instead.', componentName, componentName, ); didWarnAboutBadClass[componentName] = true; } } if (workInProgress.mode & StrictLegacyMode) { ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress, null); } setIsRendering(true); ReactCurrentOwner.current = workInProgress; value = renderWithHooks( null, workInProgress, Component, props, context, renderLanes, ); hasId = checkDidRenderIdHook(); setIsRendering(false); } else { value = renderWithHooks( null, workInProgress, Component, props, context, renderLanes, ); hasId = checkDidRenderIdHook(); } if (enableSchedulingProfiler) { markComponentRenderStopped(); } // React DevTools reads this flag. workInProgress.flags |= PerformedWork; if (__DEV__) { // Support for module components is deprecated and is removed behind a flag. // Whether or not it would crash later, we want to show a good message in DEV first. if ( typeof value === 'object' && value !== null && typeof value.render === 'function' && value.$$typeof === undefined ) { const componentName = getComponentNameFromType(Component) || 'Unknown'; if (!didWarnAboutModulePatternComponent[componentName]) { console.error( 'The <%s /> component appears to be a function component that returns a class instance. ' + 'Change %s to a class that extends React.Component instead. ' + "If you can't use a class try assigning the prototype on the function as a workaround. " + "`%s.prototype = React.Component.prototype`. Don't use an arrow function since it " + 'cannot be called with `new` by React.', componentName, componentName, componentName, ); didWarnAboutModulePatternComponent[componentName] = true; } } } if ( // Run these checks in production only if the flag is off. // Eventually we'll delete this branch altogether. !disableModulePatternComponents && typeof value === 'object' && value !== null && typeof value.render === 'function' && value.$$typeof === undefined ) { if (__DEV__) { const componentName = getComponentNameFromType(Component) || 'Unknown'; if (!didWarnAboutModulePatternComponent[componentName]) { console.error( 'The <%s /> component appears to be a function component that returns a class instance. ' + 'Change %s to a class that extends React.Component instead. ' + "If you can't use a class try assigning the prototype on the function as a workaround. " + "`%s.prototype = React.Component.prototype`. Don't use an arrow function since it " + 'cannot be called with `new` by React.', componentName, componentName, componentName, ); didWarnAboutModulePatternComponent[componentName] = true; } } // Proceed under the assumption that this is a class instance workInProgress.tag = ClassComponent; // Throw out any hooks that were used. workInProgress.memoizedState = null; workInProgress.updateQueue = null; // Push context providers early to prevent context stack mismatches. // During mounting we don't know the child context yet as the instance doesn't exist. // We will invalidate the child context in finishClassComponent() right after rendering. let hasContext = false; if (isLegacyContextProvider(Component)) { hasContext = true; pushLegacyContextProvider(workInProgress); } else { hasContext = false; } workInProgress.memoizedState = value.state !== null && value.state !== undefined ? value.state : null; initializeUpdateQueue(workInProgress); adoptClassInstance(workInProgress, value); mountClassInstance(workInProgress, Component, props, renderLanes); return finishClassComponent( null, workInProgress, Component, true, hasContext, renderLanes, ); } else { // Proceed under the assumption that this is a function component workInProgress.tag = FunctionComponent; if (__DEV__) { if (disableLegacyContext && Component.contextTypes) { console.error( '%s uses the legacy contextTypes API which is no longer supported. ' + 'Use React.createContext() with React.useContext() instead.', getComponentNameFromType(Component) || 'Unknown', ); } if ( debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictLegacyMode ) { setIsStrictModeForDevtools(true); try { value = renderWithHooks( null, workInProgress, Component, props, context, renderLanes, ); hasId = checkDidRenderIdHook(); } finally { setIsStrictModeForDevtools(false); } } } if (getIsHydrating() && hasId) { pushMaterializedTreeId(workInProgress); } reconcileChildren(null, workInProgress, value, renderLanes); if (__DEV__) { validateFunctionComponentInDev(workInProgress, Component); } return workInProgress.child; } } function validateFunctionComponentInDev(workInProgress: Fiber, Component: any) { if (__DEV__) { if (Component) { if (Component.childContextTypes) { console.error( '%s(...): childContextTypes cannot be defined on a function component.', Component.displayName || Component.name || 'Component', ); } } if (workInProgress.ref !== null) { let info = ''; const ownerName = getCurrentFiberOwnerNameInDevOrNull(); if (ownerName) { info += '\n\nCheck the render method of `' + ownerName + '`.'; } let warningKey = ownerName || ''; const debugSource = workInProgress._debugSource; if (debugSource) { warningKey = debugSource.fileName + ':' + debugSource.lineNumber; } if (!didWarnAboutFunctionRefs[warningKey]) { didWarnAboutFunctionRefs[warningKey] = true; console.error( 'Function components cannot be given refs. ' + 'Attempts to access this ref will fail. ' + 'Did you mean to use React.forwardRef()?%s', info, ); } } if ( warnAboutDefaultPropsOnFunctionComponents && Component.defaultProps !== undefined ) { const componentName = getComponentNameFromType(Component) || 'Unknown'; if (!didWarnAboutDefaultPropsOnFunctionComponent[componentName]) { console.error( '%s: Support for defaultProps will be removed from function components ' + 'in a future major release. Use JavaScript default parameters instead.', componentName, ); didWarnAboutDefaultPropsOnFunctionComponent[componentName] = true; } } if (typeof Component.getDerivedStateFromProps === 'function') { const componentName = getComponentNameFromType(Component) || 'Unknown'; if (!didWarnAboutGetDerivedStateOnFunctionComponent[componentName]) { console.error( '%s: Function components do not support getDerivedStateFromProps.', componentName, ); didWarnAboutGetDerivedStateOnFunctionComponent[componentName] = true; } } if ( typeof Component.contextType === 'object' && Component.contextType !== null ) { const componentName = getComponentNameFromType(Component) || 'Unknown'; if (!didWarnAboutContextTypeOnFunctionComponent[componentName]) { console.error( '%s: Function components do not support contextType.', componentName, ); didWarnAboutContextTypeOnFunctionComponent[componentName] = true; } } } } const SUSPENDED_MARKER: SuspenseState = { dehydrated: null, treeContext: null, retryLane: NoLane, }; function mountSuspenseOffscreenState(renderLanes: Lanes): OffscreenState { return { baseLanes: renderLanes, cachePool: getSuspendedCachePool(), }; } function updateSuspenseOffscreenState( prevOffscreenState: OffscreenState, renderLanes: Lanes, ): OffscreenState { let cachePool: SpawnedCachePool | null = null; if (enableCache) { const prevCachePool: SpawnedCachePool | null = prevOffscreenState.cachePool; if (prevCachePool !== null) { const parentCache = isPrimaryRenderer ? CacheContext._currentValue : CacheContext._currentValue2; if (prevCachePool.parent !== parentCache) { // Detected a refresh in the parent. This overrides any previously // suspended cache. cachePool = { parent: parentCache, pool: parentCache, }; } else { // We can reuse the cache from last time. The only thing that would have // overridden it is a parent refresh, which we checked for above. cachePool = prevCachePool; } } else { // If there's no previous cache pool, grab the current one. cachePool = getSuspendedCachePool(); } } return { baseLanes: mergeLanes(prevOffscreenState.baseLanes, renderLanes), cachePool, }; } // TODO: Probably should inline this back function shouldRemainOnFallback( suspenseContext: SuspenseContext, current: null | Fiber, workInProgress: Fiber, renderLanes: Lanes, ) { // If we're already showing a fallback, there are cases where we need to // remain on that fallback regardless of whether the content has resolved. // For example, SuspenseList coordinates when nested content appears. if (current !== null) { const suspenseState: SuspenseState = current.memoizedState; if (suspenseState === null) { // Currently showing content. Don't hide it, even if ForceSuspenseFallback // is true. More precise name might be "ForceRemainSuspenseFallback". // Note: This is a factoring smell. Can't remain on a fallback if there's // no fallback to remain on. return false; } } // Not currently showing content. Consult the Suspense context. return hasSuspenseContext( suspenseContext, (ForceSuspenseFallback: SuspenseContext), ); } function getRemainingWorkInPrimaryTree(current: Fiber, renderLanes) { // TODO: Should not remove render lanes that were pinged during this render return removeLanes(current.childLanes, renderLanes); } function updateSuspenseComponent(current, workInProgress, renderLanes) { const nextProps = workInProgress.pendingProps; // This is used by DevTools to force a boundary to suspend. if (__DEV__) { if (shouldSuspend(workInProgress)) { workInProgress.flags |= DidCapture; } } let suspenseContext: SuspenseContext = suspenseStackCursor.current; let showFallback = false; const didSuspend = (workInProgress.flags & DidCapture) !== NoFlags; if ( didSuspend || shouldRemainOnFallback( suspenseContext, current, workInProgress, renderLanes, ) ) { // Something in this boundary's subtree already suspended. Switch to // rendering the fallback children. showFallback = true; workInProgress.flags &= ~DidCapture; } else { // Attempting the main content if ( current === null || (current.memoizedState: null | SuspenseState) !== null ) { // This is a new mount or this boundary is already showing a fallback state. // Mark this subtree context as having at least one invisible parent that could // handle the fallback state. // Avoided boundaries are not considered since they cannot handle preferred fallback states. if ( !enableSuspenseAvoidThisFallback || nextProps.unstable_avoidThisFallback !== true ) { suspenseContext = addSubtreeSuspenseContext( suspenseContext, InvisibleParentSuspenseContext, ); } } } suspenseContext = setDefaultShallowSuspenseContext(suspenseContext); pushSuspenseContext(workInProgress, suspenseContext); // OK, the next part is confusing. We're about to reconcile the Suspense // boundary's children. This involves some custom reconciliation logic. Two // main reasons this is so complicated. // // First, Legacy Mode has different semantics for backwards compatibility. The // primary tree will commit in an inconsistent state, so when we do the // second pass to render the fallback, we do some exceedingly, uh, clever // hacks to make that not totally break. Like transferring effects and // deletions from hidden tree. In Concurrent Mode, it's much simpler, // because we bailout on the primary tree completely and leave it in its old // state, no effects. Same as what we do for Offscreen (except that // Offscreen doesn't have the first render pass). // // Second is hydration. During hydration, the Suspense fiber has a slightly // different layout, where the child points to a dehydrated fragment, which // contains the DOM rendered by the server. // // Third, even if you set all that aside, Suspense is like error boundaries in // that we first we try to render one tree, and if that fails, we render again // and switch to a different tree. Like a try/catch block. So we have to track // which branch we're currently rendering. Ideally we would model this using // a stack. if (current === null) { // Initial mount // If we're currently hydrating, try to hydrate this boundary. tryToClaimNextHydratableInstance(workInProgress); // This could've been a dehydrated suspense component. if (enableSuspenseServerRenderer) { const suspenseState: null | SuspenseState = workInProgress.memoizedState; if (suspenseState !== null) { const dehydrated = suspenseState.dehydrated; if (dehydrated !== null) { return mountDehydratedSuspenseComponent( workInProgress, dehydrated, renderLanes, ); } } } const nextPrimaryChildren = nextProps.children; const nextFallbackChildren = nextProps.fallback; if (showFallback) { const fallbackFragment = mountSuspenseFallbackChildren( workInProgress, nextPrimaryChildren, nextFallbackChildren, renderLanes, ); const primaryChildFragment: Fiber = (workInProgress.child: any); primaryChildFragment.memoizedState = mountSuspenseOffscreenState( renderLanes, ); workInProgress.memoizedState = SUSPENDED_MARKER; return fallbackFragment; } else if (typeof nextProps.unstable_expectedLoadTime === 'number') { // This is a CPU-bound tree. Skip this tree and show a placeholder to // unblock the surrounding content. Then immediately retry after the // initial commit. const fallbackFragment = mountSuspenseFallbackChildren( workInProgress, nextPrimaryChildren, nextFallbackChildren, renderLanes, ); const primaryChildFragment: Fiber = (workInProgress.child: any); primaryChildFragment.memoizedState = mountSuspenseOffscreenState( renderLanes, ); workInProgress.memoizedState = SUSPENDED_MARKER; // Since nothing actually suspended, there will nothing to ping this to // get it started back up to attempt the next item. While in terms of // priority this work has the same priority as this current render, it's // not part of the same transition once the transition has committed. If // it's sync, we still want to yield so that it can be painted. // Conceptually, this is really the same as pinging. We can use any // RetryLane even if it's the one currently rendering since we're leaving // it behind on this node. workInProgress.lanes = SomeRetryLane; return fallbackFragment; } else { return mountSuspensePrimaryChildren( workInProgress, nextPrimaryChildren, renderLanes, ); } } else { // This is an update. // If the current fiber has a SuspenseState, that means it's already showing // a fallback. const prevState: null | SuspenseState = current.memoizedState; if (prevState !== null) { // The current tree is already showing a fallback // Special path for hydration if (enableSuspenseServerRenderer) { const dehydrated = prevState.dehydrated; if (dehydrated !== null) { if (!didSuspend) { return updateDehydratedSuspenseComponent( current, workInProgress, dehydrated, prevState, renderLanes, ); } else if (workInProgress.flags & ForceClientRender) { // Something errored during hydration. Try again without hydrating. workInProgress.flags &= ~ForceClientRender; return retrySuspenseComponentWithoutHydrating( current, workInProgress, renderLanes, ); } else if ( (workInProgress.memoizedState: null | SuspenseState) !== null ) { // Something suspended and we should still be in dehydrated mode. // Leave the existing child in place. workInProgress.child = current.child; // The dehydrated completion pass expects this flag to be there // but the normal suspense pass doesn't. workInProgress.flags |= DidCapture; return null; } else { // Suspended but we should no longer be in dehydrated mode. // Therefore we now have to render the fallback. const nextPrimaryChildren = nextProps.children; const nextFallbackChildren = nextProps.fallback; const fallbackChildFragment = mountSuspenseFallbackAfterRetryWithoutHydrating( current, workInProgress, nextPrimaryChildren, nextFallbackChildren, renderLanes, ); const primaryChildFragment: Fiber = (workInProgress.child: any); primaryChildFragment.memoizedState = mountSuspenseOffscreenState( renderLanes, ); workInProgress.memoizedState = SUSPENDED_MARKER; return fallbackChildFragment; } } } if (showFallback) { const nextFallbackChildren = nextProps.fallback; const nextPrimaryChildren = nextProps.children; const fallbackChildFragment = updateSuspenseFallbackChildren( current, workInProgress, nextPrimaryChildren, nextFallbackChildren, renderLanes, ); const primaryChildFragment: Fiber = (workInProgress.child: any); const prevOffscreenState: OffscreenState | null = (current.child: any) .memoizedState; primaryChildFragment.memoizedState = prevOffscreenState === null ? mountSuspenseOffscreenState(renderLanes) : updateSuspenseOffscreenState(prevOffscreenState, renderLanes); primaryChildFragment.childLanes = getRemainingWorkInPrimaryTree( current, renderLanes, ); workInProgress.memoizedState = SUSPENDED_MARKER; return fallbackChildFragment; } else { const nextPrimaryChildren = nextProps.children; const primaryChildFragment = updateSuspensePrimaryChildren( current, workInProgress, nextPrimaryChildren, renderLanes, ); workInProgress.memoizedState = null; return primaryChildFragment; } } else { // The current tree is not already showing a fallback. if (showFallback) { // Timed out. const nextFallbackChildren = nextProps.fallback; const nextPrimaryChildren = nextProps.children; const fallbackChildFragment = updateSuspenseFallbackChildren( current, workInProgress, nextPrimaryChildren, nextFallbackChildren, renderLanes, ); const primaryChildFragment: Fiber = (workInProgress.child: any); const prevOffscreenState: OffscreenState | null = (current.child: any) .memoizedState; primaryChildFragment.memoizedState = prevOffscreenState === null ? mountSuspenseOffscreenState(renderLanes) : updateSuspenseOffscreenState(prevOffscreenState, renderLanes); primaryChildFragment.childLanes = getRemainingWorkInPrimaryTree( current, renderLanes, ); // Skip the primary children, and continue working on the // fallback children. workInProgress.memoizedState = SUSPENDED_MARKER; return fallbackChildFragment; } else { // Still haven't timed out. Continue rendering the children, like we // normally do. const nextPrimaryChildren = nextProps.children; const primaryChildFragment = updateSuspensePrimaryChildren( current, workInProgress, nextPrimaryChildren, renderLanes, ); workInProgress.memoizedState = null; return primaryChildFragment; } } } } function mountSuspensePrimaryChildren( workInProgress, primaryChildren, renderLanes, ) { const mode = workInProgress.mode; const primaryChildProps: OffscreenProps = { mode: 'visible', children: primaryChildren, }; const primaryChildFragment = mountWorkInProgressOffscreenFiber( primaryChildProps, mode, renderLanes, ); primaryChildFragment.return = workInProgress; workInProgress.child = primaryChildFragment; return primaryChildFragment; } function mountSuspenseFallbackChildren( workInProgress, primaryChildren, fallbackChildren, renderLanes, ) { const mode = workInProgress.mode; const progressedPrimaryFragment: Fiber | null = workInProgress.child; const primaryChildProps: OffscreenProps = { mode: 'hidden', children: primaryChildren, }; let primaryChildFragment; let fallbackChildFragment; if ( (mode & ConcurrentMode) === NoMode && progressedPrimaryFragment !== null ) { // In legacy mode, we commit the primary tree as if it successfully // completed, even though it's in an inconsistent state. primaryChildFragment = progressedPrimaryFragment; primaryChildFragment.childLanes = NoLanes; primaryChildFragment.pendingProps = primaryChildProps; if (enableProfilerTimer && workInProgress.mode & ProfileMode) { // Reset the durations from the first pass so they aren't included in the // final amounts. This seems counterintuitive, since we're intentionally // not measuring part of the render phase, but this makes it match what we // do in Concurrent Mode. primaryChildFragment.actualDuration = 0; primaryChildFragment.actualStartTime = -1; primaryChildFragment.selfBaseDuration = 0; primaryChildFragment.treeBaseDuration = 0; } fallbackChildFragment = createFiberFromFragment( fallbackChildren, mode, renderLanes, null, ); } else { primaryChildFragment = mountWorkInProgressOffscreenFiber( primaryChildProps, mode, NoLanes, ); fallbackChildFragment = createFiberFromFragment( fallbackChildren, mode, renderLanes, null, ); } primaryChildFragment.return = workInProgress; fallbackChildFragment.return = workInProgress; primaryChildFragment.sibling = fallbackChildFragment; workInProgress.child = primaryChildFragment; return fallbackChildFragment; } function mountWorkInProgressOffscreenFiber( offscreenProps: OffscreenProps, mode: TypeOfMode, renderLanes: Lanes, ) { // The props argument to `createFiberFromOffscreen` is `any` typed, so we use // this wrapper function to constrain it. return createFiberFromOffscreen(offscreenProps, mode, NoLanes, null); } function updateWorkInProgressOffscreenFiber( current: Fiber, offscreenProps: OffscreenProps, ) { // The props argument to `createWorkInProgress` is `any` typed, so we use this // wrapper function to constrain it. return createWorkInProgress(current, offscreenProps); } function updateSuspensePrimaryChildren( current, workInProgress, primaryChildren, renderLanes, ) { const currentPrimaryChildFragment: Fiber = (current.child: any); const currentFallbackChildFragment: Fiber | null = currentPrimaryChildFragment.sibling; const primaryChildFragment = updateWorkInProgressOffscreenFiber( currentPrimaryChildFragment, { mode: 'visible', children: primaryChildren, }, ); if ((workInProgress.mode & ConcurrentMode) === NoMode) { primaryChildFragment.lanes = renderLanes; } primaryChildFragment.return = workInProgress; primaryChildFragment.sibling = null; if (currentFallbackChildFragment !== null) { // Delete the fallback child fragment const deletions = workInProgress.deletions; if (deletions === null) { workInProgress.deletions = [currentFallbackChildFragment]; workInProgress.flags |= ChildDeletion; } else { deletions.push(currentFallbackChildFragment); } } workInProgress.child = primaryChildFragment; return primaryChildFragment; } function updateSuspenseFallbackChildren( current, workInProgress, primaryChildren, fallbackChildren, renderLanes, ) { const mode = workInProgress.mode; const currentPrimaryChildFragment: Fiber = (current.child: any); const currentFallbackChildFragment: Fiber | null = currentPrimaryChildFragment.sibling; const primaryChildProps: OffscreenProps = { mode: 'hidden', children: primaryChildren, }; let primaryChildFragment; if ( // In legacy mode, we commit the primary tree as if it successfully // completed, even though it's in an inconsistent state. (mode & ConcurrentMode) === NoMode && // Make sure we're on the second pass, i.e. the primary child fragment was // already cloned. In legacy mode, the only case where this isn't true is // when DevTools forces us to display a fallback; we skip the first render // pass entirely and go straight to rendering the fallback. (In Concurrent // Mode, SuspenseList can also trigger this scenario, but this is a legacy- // only codepath.) workInProgress.child !== currentPrimaryChildFragment ) { const progressedPrimaryFragment: Fiber = (workInProgress.child: any); primaryChildFragment = progressedPrimaryFragment; primaryChildFragment.childLanes = NoLanes; primaryChildFragment.pendingProps = primaryChildProps; if (enableProfilerTimer && workInProgress.mode & ProfileMode) { // Reset the durations from the first pass so they aren't included in the // final amounts. This seems counterintuitive, since we're intentionally // not measuring part of the render phase, but this makes it match what we // do in Concurrent Mode. primaryChildFragment.actualDuration = 0; primaryChildFragment.actualStartTime = -1; primaryChildFragment.selfBaseDuration = currentPrimaryChildFragment.selfBaseDuration; primaryChildFragment.treeBaseDuration = currentPrimaryChildFragment.treeBaseDuration; } if (enablePersistentOffscreenHostContainer && supportsPersistence) { // In persistent mode, the offscreen children are wrapped in a host node. // We need to complete it now, because we're going to skip over its normal // complete phase and go straight to rendering the fallback. const currentOffscreenContainer = currentPrimaryChildFragment.child; const offscreenContainer: Fiber = (primaryChildFragment.child: any); const containerProps = getOffscreenContainerProps( 'hidden', primaryChildren, ); offscreenContainer.pendingProps = containerProps; offscreenContainer.memoizedProps = containerProps; completeSuspendedOffscreenHostContainer( currentOffscreenContainer, offscreenContainer, ); } // The fallback fiber was added as a deletion during the first pass. // However, since we're going to remain on the fallback, we no longer want // to delete it. workInProgress.deletions = null; } else { primaryChildFragment = updateWorkInProgressOffscreenFiber( currentPrimaryChildFragment, primaryChildProps, ); if (enablePersistentOffscreenHostContainer && supportsPersistence) { // In persistent mode, the offscreen children are wrapped in a host node. // We need to complete it now, because we're going to skip over its normal // complete phase and go straight to rendering the fallback. const currentOffscreenContainer = currentPrimaryChildFragment.child; if (currentOffscreenContainer !== null) { const isHidden = true; const offscreenContainer = reconcileOffscreenHostContainer( currentPrimaryChildFragment, primaryChildFragment, isHidden, primaryChildren, renderLanes, ); offscreenContainer.memoizedProps = offscreenContainer.pendingProps; completeSuspendedOffscreenHostContainer( currentOffscreenContainer, offscreenContainer, ); } } // Since we're reusing a current tree, we need to reuse the flags, too. // (We don't do this in legacy mode, because in legacy mode we don't re-use // the current tree; see previous branch.) primaryChildFragment.subtreeFlags = currentPrimaryChildFragment.subtreeFlags & StaticMask; } let fallbackChildFragment; if (currentFallbackChildFragment !== null) { fallbackChildFragment = createWorkInProgress( currentFallbackChildFragment, fallbackChildren, ); } else { fallbackChildFragment = createFiberFromFragment( fallbackChildren, mode, renderLanes, null, ); // Needs a placement effect because the parent (the Suspense boundary) already // mounted but this is a new fiber. fallbackChildFragment.flags |= Placement; } fallbackChildFragment.return = workInProgress; primaryChildFragment.return = workInProgress; primaryChildFragment.sibling = fallbackChildFragment; workInProgress.child = primaryChildFragment; return fallbackChildFragment; } function retrySuspenseComponentWithoutHydrating( current: Fiber, workInProgress: Fiber, renderLanes: Lanes, ) { // This will add the old fiber to the deletion list reconcileChildFibers(workInProgress, current.child, null, renderLanes); // We're now not suspended nor dehydrated. const nextProps = workInProgress.pendingProps; const primaryChildren = nextProps.children; const primaryChildFragment = mountSuspensePrimaryChildren( workInProgress, primaryChildren, renderLanes, ); // Needs a placement effect because the parent (the Suspense boundary) already // mounted but this is a new fiber. primaryChildFragment.flags |= Placement; workInProgress.memoizedState = null; return primaryChildFragment; } function mountSuspenseFallbackAfterRetryWithoutHydrating( current, workInProgress, primaryChildren, fallbackChildren, renderLanes, ) { const fiberMode = workInProgress.mode; const primaryChildProps: OffscreenProps = { mode: 'visible', children: primaryChildren, }; const primaryChildFragment = mountWorkInProgressOffscreenFiber( primaryChildProps, fiberMode, NoLanes, ); const fallbackChildFragment = createFiberFromFragment( fallbackChildren, fiberMode, renderLanes, null, ); // Needs a placement effect because the parent (the Suspense // boundary) already mounted but this is a new fiber. fallbackChildFragment.flags |= Placement; primaryChildFragment.return = workInProgress; fallbackChildFragment.return = workInProgress; primaryChildFragment.sibling = fallbackChildFragment; workInProgress.child = primaryChildFragment; if ((workInProgress.mode & ConcurrentMode) !== NoMode) { // We will have dropped the effect list which contains the // deletion. We need to reconcile to delete the current child. reconcileChildFibers(workInProgress, current.child, null, renderLanes); } return fallbackChildFragment; } function mountDehydratedSuspenseComponent( workInProgress: Fiber, suspenseInstance: SuspenseInstance, renderLanes: Lanes, ): null | Fiber { // During the first pass, we'll bail out and not drill into the children. // Instead, we'll leave the content in place and try to hydrate it later. if ((workInProgress.mode & ConcurrentMode) === NoMode) { if (__DEV__) { console.error( 'Cannot hydrate Suspense in legacy mode. Switch from ' + 'ReactDOM.hydrate(element, container) to ' + 'ReactDOM.hydrateRoot(container, <App />)' + '.render(element) or remove the Suspense components from ' + 'the server rendered components.', ); } workInProgress.lanes = laneToLanes(SyncLane); } else if (isSuspenseInstanceFallback(suspenseInstance)) { // This is a client-only boundary. Since we won't get any content from the server // for this, we need to schedule that at a higher priority based on when it would // have timed out. In theory we could render it in this pass but it would have the // wrong priority associated with it and will prevent hydration of parent path. // Instead, we'll leave work left on it to render it in a separate commit. // TODO This time should be the time at which the server rendered response that is // a parent to this boundary was displayed. However, since we currently don't have // a protocol to transfer that time, we'll just estimate it by using the current // time. This will mean that Suspense timeouts are slightly shifted to later than // they should be. // Schedule a normal pri update to render this content. workInProgress.lanes = laneToLanes(DefaultHydrationLane); } else { // We'll continue hydrating the rest at offscreen priority since we'll already // be showing the right content coming from the server, it is no rush. workInProgress.lanes = laneToLanes(OffscreenLane); } return null; } function updateDehydratedSuspenseComponent( current: Fiber, workInProgress: Fiber, suspenseInstance: SuspenseInstance, suspenseState: SuspenseState, renderLanes: Lanes, ): null | Fiber { // We should never be hydrating at this point because it is the first pass, // but after we've already committed once. warnIfHydrating(); if ((getExecutionContext() & RetryAfterError) !== NoContext) { return retrySuspenseComponentWithoutHydrating( current, workInProgress, renderLanes, ); } if ((workInProgress.mode & ConcurrentMode) === NoMode) { return retrySuspenseComponentWithoutHydrating( current, workInProgress, renderLanes, ); } if (isSuspenseInstanceFallback(suspenseInstance)) { // This boundary is in a permanent fallback state. In this case, we'll never // get an update and we'll never be able to hydrate the final content. Let's just try the // client side render instead. return retrySuspenseComponentWithoutHydrating( current, workInProgress, renderLanes, ); } if ( enableLazyContextPropagation && // TODO: Factoring is a little weird, since we check this right below, too. // But don't want to re-arrange the if-else chain until/unless this // feature lands. !didReceiveUpdate ) { // We need to check if any children have context before we decide to bail // out, so propagate the changes now. lazilyPropagateParentContextChanges(current, workInProgress, renderLanes); } // We use lanes to indicate that a child might depend on context, so if // any context has changed, we need to treat is as if the input might have changed. const hasContextChanged = includesSomeLane(renderLanes, current.childLanes); if (didReceiveUpdate || hasContextChanged) { // This boundary has changed since the first render. This means that we are now unable to // hydrate it. We might still be able to hydrate it using a higher priority lane. const root = getWorkInProgressRoot(); if (root !== null) { const attemptHydrationAtLane = getBumpedLaneForHydration( root, renderLanes, ); if ( attemptHydrationAtLane !== NoLane && attemptHydrationAtLane !== suspenseState.retryLane ) { // Intentionally mutating since this render will get interrupted. This // is one of the very rare times where we mutate the current tree // during the render phase. suspenseState.retryLane = attemptHydrationAtLane; // TODO: Ideally this would inherit the event time of the current render const eventTime = NoTimestamp; scheduleUpdateOnFiber(current, attemptHydrationAtLane, eventTime); } else { // We have already tried to ping at a higher priority than we're rendering with // so if we got here, we must have failed to hydrate at those levels. We must // now give up. Instead, we're going to delete the whole subtree and instead inject // a new real Suspense boundary to take its place, which may render content // or fallback. This might suspend for a while and if it does we might still have // an opportunity to hydrate before this pass commits. } } // If we have scheduled higher pri work above, this will probably just abort the render // since we now have higher priority work, but in case it doesn't, we need to prepare to // render something, if we time out. Even if that requires us to delete everything and // skip hydration. // Delay having to do this as long as the suspense timeout allows us. renderDidSuspendDelayIfPossible(); return retrySuspenseComponentWithoutHydrating( current, workInProgress, renderLanes, ); } else if (isSuspenseInstancePending(suspenseInstance)) { // This component is still pending more data from the server, so we can't hydrate its // content. We treat it as if this component suspended itself. It might seem as if // we could just try to render it client-side instead. However, this will perform a // lot of unnecessary work and is unlikely to complete since it often will suspend // on missing data anyway. Additionally, the server might be able to render more // than we can on the client yet. In that case we'd end up with more fallback states // on the client than if we just leave it alone. If the server times out or errors // these should update this boundary to the permanent Fallback state instead. // Mark it as having captured (i.e. suspended). workInProgress.flags |= DidCapture; // Leave the child in place. I.e. the dehydrated fragment. workInProgress.child = current.child; // Register a callback to retry this boundary once the server has sent the result. const retry = retryDehydratedSuspenseBoundary.bind(null, current); registerSuspenseInstanceRetry(suspenseInstance, retry); return null; } else { // This is the first attempt. reenterHydrationStateFromDehydratedSuspenseInstance( workInProgress, suspenseInstance, suspenseState.treeContext, ); const nextProps = workInProgress.pendingProps; const primaryChildren = nextProps.children; const primaryChildFragment = mountSuspensePrimaryChildren( workInProgress, primaryChildren, renderLanes, ); // Mark the children as hydrating. This is a fast path to know whether this // tree is part of a hydrating tree. This is used to determine if a child // node has fully mounted yet, and for scheduling event replaying. // Conceptually this is similar to Placement in that a new subtree is // inserted into the React tree here. It just happens to not need DOM // mutations because it already exists. primaryChildFragment.flags |= Hydrating; return primaryChildFragment; } } function scheduleSuspenseWorkOnFiber( fiber: Fiber, renderLanes: Lanes, propagationRoot: Fiber, ) { fiber.lanes = mergeLanes(fiber.lanes, renderLanes); const alternate = fiber.alternate; if (alternate !== null) { alternate.lanes = mergeLanes(alternate.lanes, renderLanes); } scheduleContextWorkOnParentPath(fiber.return, renderLanes, propagationRoot); } function propagateSuspenseContextChange( workInProgress: Fiber, firstChild: null | Fiber, renderLanes: Lanes, ): void { // Mark any Suspense boundaries with fallbacks as having work to do. // If they were previously forced into fallbacks, they may now be able // to unblock. let node = firstChild; while (node !== null) { if (node.tag === SuspenseComponent) { const state: SuspenseState | null = node.memoizedState; if (state !== null) { scheduleSuspenseWorkOnFiber(node, renderLanes, workInProgress); } } else if (node.tag === SuspenseListComponent) { // If the tail is hidden there might not be an Suspense boundaries // to schedule work on. In this case we have to schedule it on the // list itself. // We don't have to traverse to the children of the list since // the list will propagate the change when it rerenders. scheduleSuspenseWorkOnFiber(node, renderLanes, workInProgress); } else if (node.child !== null) { node.child.return = node; node = node.child; continue; } if (node === workInProgress) { return; } while (node.sibling === null) { if (node.return === null || node.return === workInProgress) { return; } node = node.return; } node.sibling.return = node.return; node = node.sibling; } } function findLastContentRow(firstChild: null | Fiber): null | Fiber { // This is going to find the last row among these children that is already // showing content on the screen, as opposed to being in fallback state or // new. If a row has multiple Suspense boundaries, any of them being in the // fallback state, counts as the whole row being in a fallback state. // Note that the "rows" will be workInProgress, but any nested children // will still be current since we haven't rendered them yet. The mounted // order may not be the same as the new order. We use the new order. let row = firstChild; let lastContentRow: null | Fiber = null; while (row !== null) { const currentRow = row.alternate; // New rows can't be content rows. if (currentRow !== null && findFirstSuspended(currentRow) === null) { lastContentRow = row; } row = row.sibling; } return lastContentRow; } type SuspenseListRevealOrder = 'forwards' | 'backwards' | 'together' | void; function validateRevealOrder(revealOrder: SuspenseListRevealOrder) { if (__DEV__) { if ( revealOrder !== undefined && revealOrder !== 'forwards' && revealOrder !== 'backwards' && revealOrder !== 'together' && !didWarnAboutRevealOrder[revealOrder] ) { didWarnAboutRevealOrder[revealOrder] = true; if (typeof revealOrder === 'string') { switch (revealOrder.toLowerCase()) { case 'together': case 'forwards': case 'backwards': { console.error( '"%s" is not a valid value for revealOrder on <SuspenseList />. ' + 'Use lowercase "%s" instead.', revealOrder, revealOrder.toLowerCase(), ); break; } case 'forward': case 'backward': { console.error( '"%s" is not a valid value for revealOrder on <SuspenseList />. ' + 'React uses the -s suffix in the spelling. Use "%ss" instead.', revealOrder, revealOrder.toLowerCase(), ); break; } default: console.error( '"%s" is not a supported revealOrder on <SuspenseList />. ' + 'Did you mean "together", "forwards" or "backwards"?', revealOrder, ); break; } } else { console.error( '%s is not a supported value for revealOrder on <SuspenseList />. ' + 'Did you mean "together", "forwards" or "backwards"?', revealOrder, ); } } } } function validateTailOptions( tailMode: SuspenseListTailMode, revealOrder: SuspenseListRevealOrder, ) { if (__DEV__) { if (tailMode !== undefined && !didWarnAboutTailOptions[tailMode]) { if (tailMode !== 'collapsed' && tailMode !== 'hidden') { didWarnAboutTailOptions[tailMode] = true; console.error( '"%s" is not a supported value for tail on <SuspenseList />. ' + 'Did you mean "collapsed" or "hidden"?', tailMode, ); } else if (revealOrder !== 'forwards' && revealOrder !== 'backwards') { didWarnAboutTailOptions[tailMode] = true; console.error( '<SuspenseList tail="%s" /> is only valid if revealOrder is ' + '"forwards" or "backwards". ' + 'Did you mean to specify revealOrder="forwards"?', tailMode, ); } } } } function validateSuspenseListNestedChild(childSlot: mixed, index: number) { if (__DEV__) { const isAnArray = isArray(childSlot); const isIterable = !isAnArray && typeof getIteratorFn(childSlot) === 'function'; if (isAnArray || isIterable) { const type = isAnArray ? 'array' : 'iterable'; console.error( 'A nested %s was passed to row #%s in <SuspenseList />. Wrap it in ' + 'an additional SuspenseList to configure its revealOrder: ' + '<SuspenseList revealOrder=...> ... ' + '<SuspenseList revealOrder=...>{%s}</SuspenseList> ... ' + '</SuspenseList>', type, index, type, ); return false; } } return true; } function validateSuspenseListChildren( children: mixed, revealOrder: SuspenseListRevealOrder, ) { if (__DEV__) { if ( (revealOrder === 'forwards' || revealOrder === 'backwards') && children !== undefined && children !== null && children !== false ) { if (isArray(children)) { for (let i = 0; i < children.length; i++) { if (!validateSuspenseListNestedChild(children[i], i)) { return; } } } else { const iteratorFn = getIteratorFn(children); if (typeof iteratorFn === 'function') { const childrenIterator = iteratorFn.call(children); if (childrenIterator) { let step = childrenIterator.next(); let i = 0; for (; !step.done; step = childrenIterator.next()) { if (!validateSuspenseListNestedChild(step.value, i)) { return; } i++; } } } else { console.error( 'A single row was passed to a <SuspenseList revealOrder="%s" />. ' + 'This is not useful since it needs multiple rows. ' + 'Did you mean to pass multiple children or an array?', revealOrder, ); } } } } } function initSuspenseListRenderState( workInProgress: Fiber, isBackwards: boolean, tail: null | Fiber, lastContentRow: null | Fiber, tailMode: SuspenseListTailMode, ): void { const renderState: null | SuspenseListRenderState = workInProgress.memoizedState; if (renderState === null) { workInProgress.memoizedState = ({ isBackwards: isBackwards, rendering: null, renderingStartTime: 0, last: lastContentRow, tail: tail, tailMode: tailMode, }: SuspenseListRenderState); } else { // We can reuse the existing object from previous renders. renderState.isBackwards = isBackwards; renderState.rendering = null; renderState.renderingStartTime = 0; renderState.last = lastContentRow; renderState.tail = tail; renderState.tailMode = tailMode; } } // This can end up rendering this component multiple passes. // The first pass splits the children fibers into two sets. A head and tail. // We first render the head. If anything is in fallback state, we do another // pass through beginWork to rerender all children (including the tail) with // the force suspend context. If the first render didn't have anything in // in fallback state. Then we render each row in the tail one-by-one. // That happens in the completeWork phase without going back to beginWork. function updateSuspenseListComponent( current: Fiber | null, workInProgress: Fiber, renderLanes: Lanes, ) { const nextProps = workInProgress.pendingProps; const revealOrder: SuspenseListRevealOrder = nextProps.revealOrder; const tailMode: SuspenseListTailMode = nextProps.tail; const newChildren = nextProps.children; validateRevealOrder(revealOrder); validateTailOptions(tailMode, revealOrder); validateSuspenseListChildren(newChildren, revealOrder); reconcileChildren(current, workInProgress, newChildren, renderLanes); let suspenseContext: SuspenseContext = suspenseStackCursor.current; const shouldForceFallback = hasSuspenseContext( suspenseContext, (ForceSuspenseFallback: SuspenseContext), ); if (shouldForceFallback) { suspenseContext = setShallowSuspenseContext( suspenseContext, ForceSuspenseFallback, ); workInProgress.flags |= DidCapture; } else { const didSuspendBefore = current !== null && (current.flags & DidCapture) !== NoFlags; if (didSuspendBefore) { // If we previously forced a fallback, we need to schedule work // on any nested boundaries to let them know to try to render // again. This is the same as context updating. propagateSuspenseContextChange( workInProgress, workInProgress.child, renderLanes, ); } suspenseContext = setDefaultShallowSuspenseContext(suspenseContext); } pushSuspenseContext(workInProgress, suspenseContext); if ((workInProgress.mode & ConcurrentMode) === NoMode) { // In legacy mode, SuspenseList doesn't work so we just // use make it a noop by treating it as the default revealOrder. workInProgress.memoizedState = null; } else { switch (revealOrder) { case 'forwards': { const lastContentRow = findLastContentRow(workInProgress.child); let tail; if (lastContentRow === null) { // The whole list is part of the tail. // TODO: We could fast path by just rendering the tail now. tail = workInProgress.child; workInProgress.child = null; } else { // Disconnect the tail rows after the content row. // We're going to render them separately later. tail = lastContentRow.sibling; lastContentRow.sibling = null; } initSuspenseListRenderState( workInProgress, false, // isBackwards tail, lastContentRow, tailMode, ); break; } case 'backwards': { // We're going to find the first row that has existing content. // At the same time we're going to reverse the list of everything // we pass in the meantime. That's going to be our tail in reverse // order. let tail = null; let row = workInProgress.child; workInProgress.child = null; while (row !== null) { const currentRow = row.alternate; // New rows can't be content rows. if (currentRow !== null && findFirstSuspended(currentRow) === null) { // This is the beginning of the main content. workInProgress.child = row; break; } const nextRow = row.sibling; row.sibling = tail; tail = row; row = nextRow; } // TODO: If workInProgress.child is null, we can continue on the tail immediately. initSuspenseListRenderState( workInProgress, true, // isBackwards tail, null, // last tailMode, ); break; } case 'together': { initSuspenseListRenderState( workInProgress, false, // isBackwards null, // tail null, // last undefined, ); break; } default: { // The default reveal order is the same as not having // a boundary. workInProgress.memoizedState = null; } } } return workInProgress.child; } function updatePortalComponent( current: Fiber | null, workInProgress: Fiber, renderLanes: Lanes, ) { pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo); const nextChildren = workInProgress.pendingProps; if (current === null) { // Portals are special because we don't append the children during mount // but at commit. Therefore we need to track insertions which the normal // flow doesn't do during mount. This doesn't happen at the root because // the root always starts with a "current" with a null child. // TODO: Consider unifying this with how the root works. workInProgress.child = reconcileChildFibers( workInProgress, null, nextChildren, renderLanes, ); } else { reconcileChildren(current, workInProgress, nextChildren, renderLanes); } return workInProgress.child; } let hasWarnedAboutUsingNoValuePropOnContextProvider = false; function updateContextProvider( current: Fiber | null, workInProgress: Fiber, renderLanes: Lanes, ) { const providerType: ReactProviderType<any> = workInProgress.type; const context: ReactContext<any> = providerType._context; const newProps = workInProgress.pendingProps; const oldProps = workInProgress.memoizedProps; const newValue = newProps.value; if (__DEV__) { if (!('value' in newProps)) { if (!hasWarnedAboutUsingNoValuePropOnContextProvider) { hasWarnedAboutUsingNoValuePropOnContextProvider = true; console.error( 'The `value` prop is required for the `<Context.Provider>`. Did you misspell it or forget to pass it?', ); } } const providerPropTypes = workInProgress.type.propTypes; if (providerPropTypes) { checkPropTypes(providerPropTypes, newProps, 'prop', 'Context.Provider'); } } pushProvider(workInProgress, context, newValue); if (enableLazyContextPropagation) { // In the lazy propagation implementation, we don't scan for matching // consumers until something bails out, because until something bails out // we're going to visit those nodes, anyway. The trade-off is that it shifts // responsibility to the consumer to track whether something has changed. } else { if (oldProps !== null) { const oldValue = oldProps.value; if (is(oldValue, newValue)) { // No change. Bailout early if children are the same. if ( oldProps.children === newProps.children && !hasLegacyContextChanged() ) { return bailoutOnAlreadyFinishedWork( current, workInProgress, renderLanes, ); } } else { // The context value changed. Search for matching consumers and schedule // them to update. propagateContextChange(workInProgress, context, renderLanes); } } } const newChildren = newProps.children; reconcileChildren(current, workInProgress, newChildren, renderLanes); return workInProgress.child; } let hasWarnedAboutUsingContextAsConsumer = false; function updateContextConsumer( current: Fiber | null, workInProgress: Fiber, renderLanes: Lanes, ) { let context: ReactContext<any> = workInProgress.type; // The logic below for Context differs depending on PROD or DEV mode. In // DEV mode, we create a separate object for Context.Consumer that acts // like a proxy to Context. This proxy object adds unnecessary code in PROD // so we use the old behaviour (Context.Consumer references Context) to // reduce size and overhead. The separate object references context via // a property called "_context", which also gives us the ability to check // in DEV mode if this property exists or not and warn if it does not. if (__DEV__) { if ((context: any)._context === undefined) { // This may be because it's a Context (rather than a Consumer). // Or it may be because it's older React where they're the same thing. // We only want to warn if we're sure it's a new React. if (context !== context.Consumer) { if (!hasWarnedAboutUsingContextAsConsumer) { hasWarnedAboutUsingContextAsConsumer = true; console.error( 'Rendering <Context> directly is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Consumer> instead?', ); } } } else { context = (context: any)._context; } } const newProps = workInProgress.pendingProps; const render = newProps.children; if (__DEV__) { if (typeof render !== 'function') { console.error( 'A context consumer was rendered with multiple children, or a child ' + "that isn't a function. A context consumer expects a single child " + 'that is a function. If you did pass a function, make sure there ' + 'is no trailing or leading whitespace around it.', ); } } prepareToReadContext(workInProgress, renderLanes); const newValue = readContext(context); if (enableSchedulingProfiler) { markComponentRenderStarted(workInProgress); } let newChildren; if (__DEV__) { ReactCurrentOwner.current = workInProgress; setIsRendering(true); newChildren = render(newValue); setIsRendering(false); } else { newChildren = render(newValue); } if (enableSchedulingProfiler) { markComponentRenderStopped(); } // React DevTools reads this flag. workInProgress.flags |= PerformedWork; reconcileChildren(current, workInProgress, newChildren, renderLanes); return workInProgress.child; } function updateScopeComponent(current, workInProgress, renderLanes) { const nextProps = workInProgress.pendingProps; const nextChildren = nextProps.children; reconcileChildren(current, workInProgress, nextChildren, renderLanes); return workInProgress.child; } export function markWorkInProgressReceivedUpdate() { didReceiveUpdate = true; } export function checkIfWorkInProgressReceivedUpdate() { return didReceiveUpdate; } function bailoutOnAlreadyFinishedWork( current: Fiber | null, workInProgress: Fiber, renderLanes: Lanes, ): Fiber | null { if (current !== null) { // Reuse previous dependencies workInProgress.dependencies = current.dependencies; } if (enableProfilerTimer) { // Don't update "base" render times for bailouts. stopProfilerTimerIfRunning(workInProgress); } markSkippedUpdateLanes(workInProgress.lanes); // Check if the children have any pending work. if (!includesSomeLane(renderLanes, workInProgress.childLanes)) { // The children don't have any work either. We can skip them. // TODO: Once we add back resuming, we should check if the children are // a work-in-progress set. If so, we need to transfer their effects. if (enableLazyContextPropagation && current !== null) { // Before bailing out, check if there are any context changes in // the children. lazilyPropagateParentContextChanges(current, workInProgress, renderLanes); if (!includesSomeLane(renderLanes, workInProgress.childLanes)) { return null; } } else { return null; } } // This fiber doesn't have work, but its subtree does. Clone the child // fibers and continue. cloneChildFibers(current, workInProgress); return workInProgress.child; } function remountFiber( current: Fiber, oldWorkInProgress: Fiber, newWorkInProgress: Fiber, ): Fiber | null { if (__DEV__) { const returnFiber = oldWorkInProgress.return; if (returnFiber === null) { // eslint-disable-next-line react-internal/prod-error-codes throw new Error('Cannot swap the root fiber.'); } // Disconnect from the old current. // It will get deleted. current.alternate = null; oldWorkInProgress.alternate = null; // Connect to the new tree. newWorkInProgress.index = oldWorkInProgress.index; newWorkInProgress.sibling = oldWorkInProgress.sibling; newWorkInProgress.return = oldWorkInProgress.return; newWorkInProgress.ref = oldWorkInProgress.ref; // Replace the child/sibling pointers above it. if (oldWorkInProgress === returnFiber.child) { returnFiber.child = newWorkInProgress; } else { let prevSibling = returnFiber.child; if (prevSibling === null) { // eslint-disable-next-line react-internal/prod-error-codes throw new Error('Expected parent to have a child.'); } while (prevSibling.sibling !== oldWorkInProgress) { prevSibling = prevSibling.sibling; if (prevSibling === null) { // eslint-disable-next-line react-internal/prod-error-codes throw new Error('Expected to find the previous sibling.'); } } prevSibling.sibling = newWorkInProgress; } // Delete the old fiber and place the new one. // Since the old fiber is disconnected, we have to schedule it manually. const deletions = returnFiber.deletions; if (deletions === null) { returnFiber.deletions = [current]; returnFiber.flags |= ChildDeletion; } else { deletions.push(current); } newWorkInProgress.flags |= Placement; // Restart work from the new fiber. return newWorkInProgress; } else { throw new Error( 'Did not expect this call in production. ' + 'This is a bug in React. Please file an issue.', ); } } function checkScheduledUpdateOrContext( current: Fiber, renderLanes: Lanes, ): boolean { // Before performing an early bailout, we must check if there are pending // updates or context. const updateLanes = current.lanes; if (includesSomeLane(updateLanes, renderLanes)) { return true; } // No pending update, but because context is propagated lazily, we need // to check for a context change before we bail out. if (enableLazyContextPropagation) { const dependencies = current.dependencies; if (dependencies !== null && checkIfContextChanged(dependencies)) { return true; } } return false; } function attemptEarlyBailoutIfNoScheduledUpdate( current: Fiber, workInProgress: Fiber, renderLanes: Lanes, ) { // This fiber does not have any pending work. Bailout without entering // the begin phase. There's still some bookkeeping we that needs to be done // in this optimized path, mostly pushing stuff onto the stack. switch (workInProgress.tag) { case HostRoot: pushHostRootContext(workInProgress); if (enableCache) { const root: FiberRoot = workInProgress.stateNode; const cache: Cache = current.memoizedState.cache; pushCacheProvider(workInProgress, cache); pushRootCachePool(root); } resetHydrationState(); break; case HostComponent: pushHostContext(workInProgress); break; case ClassComponent: { const Component = workInProgress.type; if (isLegacyContextProvider(Component)) { pushLegacyContextProvider(workInProgress); } break; } case HostPortal: pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo); break; case ContextProvider: { const newValue = workInProgress.memoizedProps.value; const context: ReactContext<any> = workInProgress.type._context; pushProvider(workInProgress, context, newValue); break; } case Profiler: if (enableProfilerTimer) { // Profiler should only call onRender when one of its descendants actually rendered. const hasChildWork = includesSomeLane( renderLanes, workInProgress.childLanes, ); if (hasChildWork) { workInProgress.flags |= Update; } if (enableProfilerCommitHooks) { // Reset effect durations for the next eventual effect phase. // These are reset during render to allow the DevTools commit hook a chance to read them, const stateNode = workInProgress.stateNode; stateNode.effectDuration = 0; stateNode.passiveEffectDuration = 0; } } break; case SuspenseComponent: { const state: SuspenseState | null = workInProgress.memoizedState; if (state !== null) { if (enableSuspenseServerRenderer) { if (state.dehydrated !== null) { pushSuspenseContext( workInProgress, setDefaultShallowSuspenseContext(suspenseStackCursor.current), ); // We know that this component will suspend again because if it has // been unsuspended it has committed as a resolved Suspense component. // If it needs to be retried, it should have work scheduled on it. workInProgress.flags |= DidCapture; // We should never render the children of a dehydrated boundary until we // upgrade it. We return null instead of bailoutOnAlreadyFinishedWork. return null; } } // If this boundary is currently timed out, we need to decide // whether to retry the primary children, or to skip over it and // go straight to the fallback. Check the priority of the primary // child fragment. const primaryChildFragment: Fiber = (workInProgress.child: any); const primaryChildLanes = primaryChildFragment.childLanes; if (includesSomeLane(renderLanes, primaryChildLanes)) { // The primary children have pending work. Use the normal path // to attempt to render the primary children again. return updateSuspenseComponent(current, workInProgress, renderLanes); } else { // The primary child fragment does not have pending work marked // on it pushSuspenseContext( workInProgress, setDefaultShallowSuspenseContext(suspenseStackCursor.current), ); // The primary children do not have pending work with sufficient // priority. Bailout. const child = bailoutOnAlreadyFinishedWork( current, workInProgress, renderLanes, ); if (child !== null) { // The fallback children have pending work. Skip over the // primary children and work on the fallback. return child.sibling; } else { // Note: We can return `null` here because we already checked // whether there were nested context consumers, via the call to // `bailoutOnAlreadyFinishedWork` above. return null; } } } else { pushSuspenseContext( workInProgress, setDefaultShallowSuspenseContext(suspenseStackCursor.current), ); } break; } case SuspenseListComponent: { const didSuspendBefore = (current.flags & DidCapture) !== NoFlags; let hasChildWork = includesSomeLane( renderLanes, workInProgress.childLanes, ); if (enableLazyContextPropagation && !hasChildWork) { // Context changes may not have been propagated yet. We need to do // that now, before we can decide whether to bail out. // TODO: We use `childLanes` as a heuristic for whether there is // remaining work in a few places, including // `bailoutOnAlreadyFinishedWork` and // `updateDehydratedSuspenseComponent`. We should maybe extract this // into a dedicated function. lazilyPropagateParentContextChanges( current, workInProgress, renderLanes, ); hasChildWork = includesSomeLane(renderLanes, workInProgress.childLanes); } if (didSuspendBefore) { if (hasChildWork) { // If something was in fallback state last time, and we have all the // same children then we're still in progressive loading state. // Something might get unblocked by state updates or retries in the // tree which will affect the tail. So we need to use the normal // path to compute the correct tail. return updateSuspenseListComponent( current, workInProgress, renderLanes, ); } // If none of the children had any work, that means that none of // them got retried so they'll still be blocked in the same way // as before. We can fast bail out. workInProgress.flags |= DidCapture; } // If nothing suspended before and we're rendering the same children, // then the tail doesn't matter. Anything new that suspends will work // in the "together" mode, so we can continue from the state we had. const renderState = workInProgress.memoizedState; if (renderState !== null) { // Reset to the "together" mode in case we've started a different // update in the past but didn't complete it. renderState.rendering = null; renderState.tail = null; renderState.lastEffect = null; } pushSuspenseContext(workInProgress, suspenseStackCursor.current); if (hasChildWork) { break; } else { // If none of the children had any work, that means that none of // them got retried so they'll still be blocked in the same way // as before. We can fast bail out. return null; } } case OffscreenComponent: case LegacyHiddenComponent: { // Need to check if the tree still needs to be deferred. This is // almost identical to the logic used in the normal update path, // so we'll just enter that. The only difference is we'll bail out // at the next level instead of this one, because the child props // have not changed. Which is fine. // TODO: Probably should refactor `beginWork` to split the bailout // path from the normal path. I'm tempted to do a labeled break here // but I won't :) workInProgress.lanes = NoLanes; return updateOffscreenComponent(current, workInProgress, renderLanes); } case CacheComponent: { if (enableCache) { const cache: Cache = current.memoizedState.cache; pushCacheProvider(workInProgress, cache); } break; } } return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); } function beginWork( current: Fiber | null, workInProgress: Fiber, renderLanes: Lanes, ): Fiber | null { if (__DEV__) { if (workInProgress._debugNeedsRemount && current !== null) { // This will restart the begin phase with a new fiber. return remountFiber( current, workInProgress, createFiberFromTypeAndProps( workInProgress.type, workInProgress.key, workInProgress.pendingProps, workInProgress._debugOwner || null, workInProgress.mode, workInProgress.lanes, ), ); } } if (current !== null) { const oldProps = current.memoizedProps; const newProps = workInProgress.pendingProps; if ( oldProps !== newProps || hasLegacyContextChanged() || // Force a re-render if the implementation changed due to hot reload: (__DEV__ ? workInProgress.type !== current.type : false) ) { // If props or context changed, mark the fiber as having performed work. // This may be unset if the props are determined to be equal later (memo). didReceiveUpdate = true; } else { // Neither props nor legacy context changes. Check if there's a pending // update or context change. const hasScheduledUpdateOrContext = checkScheduledUpdateOrContext( current, renderLanes, ); if ( !hasScheduledUpdateOrContext && // If this is the second pass of an error or suspense boundary, there // may not be work scheduled on `current`, so we check for this flag. (workInProgress.flags & DidCapture) === NoFlags ) { // No pending updates or context. Bail out now. didReceiveUpdate = false; return attemptEarlyBailoutIfNoScheduledUpdate( current, workInProgress, renderLanes, ); } if ((current.flags & ForceUpdateForLegacySuspense) !== NoFlags) { // This is a special case that only exists for legacy mode. // See https://github.com/facebook/react/pull/19216. didReceiveUpdate = true; } else { // An update was scheduled on this fiber, but there are no new props // nor legacy context. Set this to false. If an update queue or context // consumer produces a changed value, it will set this to true. Otherwise, // the component will assume the children have not changed and bail out. didReceiveUpdate = false; } } } else { didReceiveUpdate = false; if (getIsHydrating() && isForkedChild(workInProgress)) { // Check if this child belongs to a list of muliple children in // its parent. // // In a true multi-threaded implementation, we would render children on // parallel threads. This would represent the beginning of a new render // thread for this subtree. // // We only use this for id generation during hydration, which is why the // logic is located in this special branch. const slotIndex = workInProgress.index; const numberOfForks = getForksAtLevel(workInProgress); pushTreeId(workInProgress, numberOfForks, slotIndex); } } // Before entering the begin phase, clear pending update priority. // TODO: This assumes that we're about to evaluate the component and process // the update queue. However, there's an exception: SimpleMemoComponent // sometimes bails out later in the begin phase. This indicates that we should // move this assignment out of the common path and into each branch. workInProgress.lanes = NoLanes; switch (workInProgress.tag) { case IndeterminateComponent: { return mountIndeterminateComponent( current, workInProgress, workInProgress.type, renderLanes, ); } case LazyComponent: { const elementType = workInProgress.elementType; return mountLazyComponent( current, workInProgress, elementType, renderLanes, ); } case FunctionComponent: { const Component = workInProgress.type; const unresolvedProps = workInProgress.pendingProps; const resolvedProps = workInProgress.elementType === Component ? unresolvedProps : resolveDefaultProps(Component, unresolvedProps); return updateFunctionComponent( current, workInProgress, Component, resolvedProps, renderLanes, ); } case ClassComponent: { const Component = workInProgress.type; const unresolvedProps = workInProgress.pendingProps; const resolvedProps = workInProgress.elementType === Component ? unresolvedProps : resolveDefaultProps(Component, unresolvedProps); return updateClassComponent( current, workInProgress, Component, resolvedProps, renderLanes, ); } case HostRoot: return updateHostRoot(current, workInProgress, renderLanes); case HostComponent: return updateHostComponent(current, workInProgress, renderLanes); case HostText: return updateHostText(current, workInProgress); case SuspenseComponent: return updateSuspenseComponent(current, workInProgress, renderLanes); case HostPortal: return updatePortalComponent(current, workInProgress, renderLanes); case ForwardRef: { const type = workInProgress.type; const unresolvedProps = workInProgress.pendingProps; const resolvedProps = workInProgress.elementType === type ? unresolvedProps : resolveDefaultProps(type, unresolvedProps); return updateForwardRef( current, workInProgress, type, resolvedProps, renderLanes, ); } case Fragment: return updateFragment(current, workInProgress, renderLanes); case Mode: return updateMode(current, workInProgress, renderLanes); case Profiler: return updateProfiler(current, workInProgress, renderLanes); case ContextProvider: return updateContextProvider(current, workInProgress, renderLanes); case ContextConsumer: return updateContextConsumer(current, workInProgress, renderLanes); case MemoComponent: { const type = workInProgress.type; const unresolvedProps = workInProgress.pendingProps; // Resolve outer props first, then resolve inner props. let resolvedProps = resolveDefaultProps(type, unresolvedProps); if (__DEV__) { if (workInProgress.type !== workInProgress.elementType) { const outerPropTypes = type.propTypes; if (outerPropTypes) { checkPropTypes( outerPropTypes, resolvedProps, // Resolved for outer only 'prop', getComponentNameFromType(type), ); } } } resolvedProps = resolveDefaultProps(type.type, resolvedProps); return updateMemoComponent( current, workInProgress, type, resolvedProps, renderLanes, ); } case SimpleMemoComponent: { return updateSimpleMemoComponent( current, workInProgress, workInProgress.type, workInProgress.pendingProps, renderLanes, ); } case IncompleteClassComponent: { const Component = workInProgress.type; const unresolvedProps = workInProgress.pendingProps; const resolvedProps = workInProgress.elementType === Component ? unresolvedProps : resolveDefaultProps(Component, unresolvedProps); return mountIncompleteClassComponent( current, workInProgress, Component, resolvedProps, renderLanes, ); } case SuspenseListComponent: { return updateSuspenseListComponent(current, workInProgress, renderLanes); } case ScopeComponent: { if (enableScopeAPI) { return updateScopeComponent(current, workInProgress, renderLanes); } break; } case OffscreenComponent: { return updateOffscreenComponent(current, workInProgress, renderLanes); } case LegacyHiddenComponent: { return updateLegacyHiddenComponent(current, workInProgress, renderLanes); } case CacheComponent: { if (enableCache) { return updateCacheComponent(current, workInProgress, renderLanes); } break; } } throw new Error( `Unknown unit of work tag (${workInProgress.tag}). This error is likely caused by a bug in ` + 'React. Please file an issue.', ); } export {beginWork};
oc = oc || {}; oc.activity = oc.activity || {}; var $globalActivity; var $userActivity; $(document).ready(function() { $globalActivity = $('#global-activity'); $userActivity = $('#user-activity'); if ($globalActivity.length > 0) { oc.activity.loadGlobalActivity($globalActivity); } if ($userActivity.length > 0) { var username = $('#data-store').data('user'); oc.activity.loadUserActivity(username, $userActivity); } }); oc.activity.loadGlobalActivity = function($globalActivity) { $.ajax({ url: "/activity/global/" }).done(function(data) { data = JSON.parse(data); if (data.Error) { console.log(data); } var i; if (data.Activities) { var activities = data.Activities; $globalActivity.empty(); for (i = 0; i < activities.length; i++) { var a = activities[i]; var user = '<a class="user-link" href="/user/' + a.User + '">' + a.User + '</a>'; var timestamp = '[' + a.Time + ']'; var action = a.Action; var re = /(\/.*\/)(.*)/gi; action = action.replace(re, '<a href="$1$2">$2</a>'); $globalActivity.append('<div class="activity-item">' + timestamp + " " + user + ": " + action + '</div>'); } } }); }; oc.activity.loadUserActivity = function(username, $userActivity) { $.ajax({ url: "/activity/" + username + "/" }).done(function(data) { data = JSON.parse(data); if (data.Error) { console.log(data); } var i; if (data.Activities) { var activities = data.Activities; $userActivity.empty(); for (i = 0; i < activities.length; i++) { var a = activities[i]; var user = '<a class="user-link" href="/user/' + a.User + '">' + a.User + '</a>'; var timestamp = '[' + a.Time + ']'; var action = a.Action; var re = /(\/.*\/)(.*)/gi; action = action.replace(re, '<a href="$1$2">$2</a>'); $userActivity.append('<div class="activity-item">' + timestamp + " " + user + ": " + action + '</div>'); } } }); };
//Overloaded Handlebars Handlebars = require('handlebars'), Handlebars.registerHelper('toUpperCase', function(str) { return str.toUpperCase(); }); Handlebars.registerHelper('toLowerCase', function(str) { return str.toLowerCase(); }); Handlebars.registerHelper('lineBreakToBr', function(str) { return str.replace(/\n/g,'<br />'); }); Handlebars.registerHelper('lineBreak', function() { return '\n'; }); Handlebars.registerHelper('javaDocParams', function(columns, padding) { var str = ''; columns.forEach(function(val, i){ str += `${' '.repeat(padding)}* @param p_${val.column_name.toLowerCase()}: ${columns.length === i+1 ? '' : '\n'}` }); return str; }); Handlebars.registerHelper('initCap', function(str) { if (str) { return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase(); } else{ return str; } }); // From http://stackoverflow.com/questions/8853396/logical-operator-in-a-handlebars-js-if-conditional Handlebars.registerHelper('ifCond', function (v1, operator, v2, options) { switch (operator) { case '==': return (v1 == v2) ? options.fn(this) : options.inverse(this); case '===': return (v1 === v2) ? options.fn(this) : options.inverse(this); case '<': return (v1 < v2) ? options.fn(this) : options.inverse(this); case '<=': return (v1 <= v2) ? options.fn(this) : options.inverse(this); case '>': return (v1 > v2) ? options.fn(this) : options.inverse(this); case '>=': return (v1 >= v2) ? options.fn(this) : options.inverse(this); case '&&': return (v1 && v2) ? options.fn(this) : options.inverse(this); case '||': return (v1 || v2) ? options.fn(this) : options.inverse(this); case '!=': return (v1 != v2) ? options.fn(this) : options.inverse(this); case '!==': return (v1 !== v2) ? options.fn(this) : options.inverse(this); default: return options.inverse(this); } }); // TODO mdsouza: create functions for getTypes, getMethods, getConstants // TODO mdsouza: delete Handlebars.registerHelper('entityFilter', function(entityType, options) { var retEntities = [] ; console.log(entityType); options.data.root.entities.forEach(function(entity){ if (entity.type === 'typesBAD'){ retEntities.push(entity); } });//entities.forEach console.log(retEntities); return options.fn(retEntities); }); module.exports = Handlebars;
import find from 'lodash/find'; import get from 'lodash/get'; import isArray from 'lodash/isArray'; import includes from 'lodash/includes'; import padStart from 'lodash/padStart'; import escape from 'lodash/escape'; import moment from 'moment'; import { Helpers } from 'sonos'; import SonosService from '../services/SonosService'; import store from '../reducers'; import { withinEnvelope, stripNamespaces, NS } from '../../common/helpers'; const deviceProviderName = 'Sonos'; class MusicServiceClient { constructor(serviceDefinition, { authToken, privateKey } = {}) { this._serviceDefinition = serviceDefinition; this.name = serviceDefinition.Name; this.auth = serviceDefinition.Auth; this.authToken = authToken; this.key = privateKey; } setAuthToken(token) { this.authToken = token; } setKey(key) { this.key = key; } async _doRequest(uri, action, requestBody, headers, retry = false) { const soapHeaders = typeof headers === 'function' ? headers.call(this) : headers; const soapBody = withinEnvelope(requestBody, soapHeaders); const response = await fetch(uri, { method: 'POST', headers: { SOAPAction: `"${NS}#${action}"`, 'Content-type': 'text/xml; charset=utf8', 'Accept-Language': 'en,en-AU;q=0.9,en-US;q=0.5', }, body: soapBody, }); const body = await response.text(); const e = await Helpers.ParseXml(stripNamespaces(body)); const fault = get(e, 'Envelope.Body.Fault.faultstring'); if (response.status >= 400 || fault) { if ( !retry && fault && (includes(fault, 'TokenRefreshRequired') || includes(fault, 'tokenRefreshRequired')) ) { const refreshDetails = get( e, 'Envelope.Body.Fault.detail.refreshAuthTokenResult' ); this.setAuthToken(refreshDetails.authToken); this.setKey(refreshDetails.privateKey); return this._doRequest(uri, action, requestBody, headers, true); } if ( !retry && fault && includes(fault, 'Update your Sonos system') ) { return this._doRequest(uri, action, requestBody, headers, true); } throw new Error(fault); } return body; } getTrackURI(item, serviceId) { const trackId = item.id; const itemType = item.itemType; let protocol = 'x-sonos-http'; let suffix = '.mp3'; if (String(serviceId) === '12') { protocol = 'x-spotify'; suffix = ''; if ( trackId.startsWith('spotify:track:') || trackId.startsWith('spotify:artistRadio:') ) { return escape(trackId); } } if ( includes( ['playlist', 'playList', 'artistTrackList', 'albumList'], itemType ) ) { return 'x-rincon-cpcontainer:0006206c' + escape(trackId); } if (itemType === 'container') { return `x-rincon-cpcontainer:10fe206c${escape( trackId )}?sid=${serviceId}&flags=8300&sn=1`; } if (itemType === 'trackList') { return 'x-rincon-cpcontainer:000e206c' + escape(trackId); } if (itemType === 'album') { return 'x-rincon-cpcontainer:0004206c' + escape(trackId); } if (itemType === 'program') { return `x-sonosapi-radio:${escape( trackId )}?sid=${serviceId}&flags=8296&sn=17`; } if (itemType === 'stream') { return `x-sonosapi-stream:${escape( trackId )}?sid=${serviceId}&flags=8224&sn=14`; } return `${protocol}:${escape( trackId )}${suffix}?sid=${serviceId}&flags=8224&sn=1`; } // TODO: maybe we can use node-sonos Helpers.GenerateMetadata etc??? encodeItemMetadata(uri, item) { const serviceType = this._serviceDefinition.ServiceIDEncoded; const TYPE_MAPPINGS = { track: { type: 'object.item.audioItem.musicTrack', token: '00032020', serviceString: `SA_RINCON${serviceType}_X_#Svc${serviceType}-0-Token`, }, album: { type: 'object.container.album.musicAlbum', token: '0004206c', serviceString: `SA_RINCON${serviceType}_X_#Svc${serviceType}-0-Token`, }, trackList: { type: 'object.container.playlistContainer', token: '000e206c', serviceString: `SA_RINCON${serviceType}_X_#Svc${serviceType}-0-Token`, }, albumList: { type: 'object.container.playlistContainer', token: '0006206c', serviceString: `SA_RINCON${serviceType}_X_#Svc${serviceType}-0-Token`, }, playlist: { type: 'object.container.playlistContainer', token: '0006206c', serviceString: `SA_RINCON${serviceType}_X_#Svc${serviceType}-0-Token`, }, playList: { type: 'object.container.playlistContainer', token: '0006206c', serviceString: `SA_RINCON${serviceType}_X_#Svc${serviceType}-0-Token`, }, artistTrackList: { type: 'object.container.playlistContainer', token: '0006206c', serviceString: `SA_RINCON${serviceType}_X_#Svc${serviceType}-0-Token`, }, stream: { type: 'object.item.audioItem.audioBroadcast', token: '10092020', parentId: 'parentID="-1"', serviceString: `SA_RINCON${serviceType}_`, }, program: { type: 'object.item.audioItem.audioBroadcast.#' + item.displayType, token: '100c2068', parentId: 'parentID="0"', serviceString: `SA_RINCON${serviceType}_X_#Svc${serviceType}-0-Token`, }, container: { type: 'object.container.#DEFAULT', parentId: 'parentID="-1"', token: '10fe206c', serviceString: `SA_RINCON${serviceType}_X_#Svc${serviceType}-0-Token`, }, 'local-file': { type: 'object.item.audioItem.musicTrack', parentId: 'parentID="-1"', token: '00032020', }, }; let resourceString, id, trackData, parentId = ''; const serviceString = TYPE_MAPPINGS[item.itemType].serviceString; if (serviceString) { const prefix = TYPE_MAPPINGS[item.itemType].token; id = prefix + escape(item.id); parentId = TYPE_MAPPINGS[item.itemType].parentId || ''; resourceString = `<desc id="cdudn" nameSpace="urn:schemas-rinconnetworks-com:metadata-1-0/">${serviceString}</desc>`; } else if (get(item, 'trackMetadata.duration')) { id = '-1'; const d = moment.duration(item.trackMetadata.duration || 0); resourceString = `<res protocolInfo="${uri.match(/^[\w\-]+:/)[0]}*${ item.mimeType }*" duration="${padStart(d.hours(), 2, '0')}:${padStart( d.minutes(), 2, '0' )}:${padStart(d.seconds(), 2, '0')}">${escape(uri)}</res>`; } if (item.trackMetadata) { trackData = `<dc:creator>${escape( item.trackMetadata.artist )}</dc:creator> <upnp:albumArtURI>${ item.trackMetadata.albumArtURI || '' }</upnp:albumArtURI> <upnp:album>${escape(item.trackMetadata.album || '')}</upnp:album>`; } else if (item.albumArtURI) { trackData = `<upnp:albumArtURI>${ item.albumArtURI || '' }</upnp:albumArtURI> `; } const didl = `<DIDL-Lite xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:upnp="urn:schemas-upnp-org:metadata-1-0/upnp/" xmlns:r="urn:schemas-rinconnetworks-com:metadata-1-0/" xmlns="urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/"> <item id="${id}" restricted="true" ${parentId}> ${resourceString} <dc:title>${escape(item.title)}</dc:title> <upnp:class>${TYPE_MAPPINGS[item.itemType].type}</upnp:class> ${trackData || ''} </item> </DIDL-Lite>`; return { metadata: didl, class: TYPE_MAPPINGS[item.itemType].type, }; } getDeviceLinkCode() { const headers = [ '<ns:credentials>', '<ns:deviceId>', SonosService.deviceId, '</ns:deviceId>', '<ns:deviceProvider>', deviceProviderName, '</ns:deviceProvider>', '</ns:credentials>', ].join(''); const body = [ '<ns:getDeviceLinkCode>', '<ns:householdId>', SonosService.householdId, '</ns:householdId>', '</ns:getDeviceLinkCode>', ].join(''); return this._doRequest( this._serviceDefinition.SecureUri, 'getDeviceLinkCode', body, headers ).then(async (res) => { const resp = await Helpers.ParseXml(stripNamespaces(res)); const obj = resp['Envelope']['Body']['getDeviceLinkCodeResponse'][ 'getDeviceLinkCodeResult' ]; return obj; }); } getAppLink() { const headers = ['<ns:credentials>', '</ns:credentials>'].join(''); const body = [ '<ns:getAppLink>', '<ns:householdId>', SonosService.householdId, '</ns:householdId>', '</ns:getAppLink>', ].join(''); return this._doRequest( this._serviceDefinition.SecureUri, 'getAppLink', body, headers ).then(async (res) => { const resp = await Helpers.ParseXml(stripNamespaces(res)); const obj = resp['Envelope']['Body']['getAppLinkResponse'][ 'getAppLinkResult' ]; return obj.authorizeAccount.deviceLink; }); } getDeviceAuthToken(linkCode, linkDeviceId) { const headers = [ '<ns:credentials>', '<ns:deviceId>', SonosService.deviceId, '</ns:deviceId>', '<ns:deviceProvider>', deviceProviderName, '</ns:deviceProvider>', '</ns:credentials>', ].join(''); const body = [ '<ns:getDeviceAuthToken>', '<ns:householdId>', SonosService.householdId, '</ns:householdId>', '<ns:linkCode>', linkCode, '</ns:linkCode>', '<ns:linkDeviceId>', linkDeviceId, '</ns:linkDeviceId>', '</ns:getDeviceAuthToken>', ].join(''); return this._doRequest( this._serviceDefinition.SecureUri, 'getDeviceAuthToken', body, headers ) .then(async (res) => { const resp = await Helpers.ParseXml(stripNamespaces(res)); const obj = resp['Envelope']['Body']['getDeviceAuthTokenResponse'][ 'getDeviceAuthTokenResult' ]; return obj; }) .catch((err) => { if (err.message.indexOf('NOT_LINKED_RETRY') > -1) { // noop } throw err; }); } getMetadata(id, index = 0, count = 200) { const body = [ '<ns:getMetadata>', '<ns:id>', id, '</ns:id>', '<ns:index>', index, '</ns:index>', '<ns:count>', count, '</ns:count>', '<ns:recursive>false</ns:recursive>', '</ns:getMetadata>', ].join(''); return new Promise((resolve, reject) => { this._doRequest( this._serviceDefinition.SecureUri, 'getMetadata', body, this.getAuthHeaders ) .then(async (res) => { const resp = await Helpers.ParseXml(stripNamespaces(res)); const obj = resp['Envelope']['Body']['getMetadataResponse'][ 'getMetadataResult' ]; resolve(obj); }) .catch((response) => { reject(response); }); }); } getExtendedMetadata(id) { const body = [ '<ns:getExtendedMetadata>', '<ns:id>', id, '</ns:id>', '</ns:getExtendedMetadata>', ].join(''); return new Promise((resolve, reject) => { this._doRequest( this._serviceDefinition.SecureUri, 'getExtendedMetadata', body, this.getAuthHeaders ) .then(async (res) => { const resp = await Helpers.ParseXml(stripNamespaces(res)); const obj = resp['Envelope']['Body']['getExtendedMetadataResponse'][ 'getExtendedMetadataResult' ]; resolve(obj); }) .catch((response) => { reject(response); }); }); } search(id, term, index = 0, count = 200) { const body = [ '<ns:search>', '<ns:id>', id, '</ns:id>', '<ns:term>', escape(term), '</ns:term>', '<ns:index>', index, '</ns:index>', '<ns:count>', count, '</ns:count>', '</ns:search>', ].join(''); return new Promise((resolve, reject) => { return this._doRequest( this._serviceDefinition.SecureUri, 'search', body, this.getAuthHeaders ) .then(async (res) => { const resp = await Helpers.ParseXml(stripNamespaces(res)); const obj = resp['Envelope']['Body']['searchResponse'][ 'searchResult' ]; resolve(obj); }) .catch((response) => { reject(response); }); }); } getMediaURI(id) { const body = [ '<ns:getMediaURI>', '<ns:id>', id, '</ns:id>', '</ns:getMediaURI>', ].join(''); return new Promise((resolve, reject) => { return this._doRequest( this._serviceDefinition.SecureUri, 'getMediaURI', body, this.getAuthHeaders ) .then(async (res) => { const resp = await Helpers.ParseXml(stripNamespaces(res)); const obj = resp['Envelope']['Body']['getMediaURIResponse'][ 'getMediaURIResult' ]; return resolve(obj); }) .catch((response) => { reject(response); }); }); } getSessionId(username, password) { const headers = [ '<ns:credentials>', '<ns:deviceId>', SonosService.deviceId, '</ns:deviceId>', '<ns:deviceProvider>', deviceProviderName, '</ns:deviceProvider>', '</ns:credentials>', ].join(''); const body = [ '<ns:getSessionId>', '<ns:username>', username, '</ns:username>', '<ns:password>', password, '</ns:password>', '</ns:getSessionId>', ].join(''); return this._doRequest( this._serviceDefinition.SecureUri, 'getSessionId', body, headers ).then(async (res) => { const resp = await Helpers.ParseXml(stripNamespaces(res)); const obj = resp['Envelope']['Body']['getSessionIdResponse'][ 'getSessionIdResult' ]; return obj; }); } getAuthHeaders() { if (this.auth === 'UserId') { return [ '<ns:credentials>', '<ns:deviceId>', SonosService.deviceId, '</ns:deviceId>', '<ns:deviceProvider>', deviceProviderName, '</ns:deviceProvider>', '<ns:sessionId>', this.authToken, '</ns:sessionId>', '</ns:credentials>', ].join(''); } if (this.auth === 'DeviceLink' || this.auth === 'AppLink') { return [ '<ns:credentials>', '<ns:deviceId>', SonosService.deviceId, '</ns:deviceId>', '<ns:deviceProvider>', deviceProviderName, '</ns:deviceProvider>', '<ns:loginToken>', '<ns:token>', this.authToken, '</ns:token>', '<ns:key>', this.key, '</ns:key>', '<ns:householdId>', SonosService.householdId.split('.')[0], '</ns:householdId>', '</ns:loginToken>', '</ns:credentials>', ].join(''); } return [ '<ns:credentials>', '<ns:deviceId>', SonosService.deviceId, '</ns:deviceId>', '<ns:deviceProvider>', deviceProviderName, '</ns:deviceProvider>', '</ns:credentials>', ].join(''); } async getSearchTermMap() { let mapUri = this._serviceDefinition.presentation.mapUri; if (this._serviceDefinition.manifestUri) { const res = await fetch(this._serviceDefinition.manifestUri); const jsonRes = await res.json(); if (jsonRes.presentationMap.uri) { mapUri = jsonRes.presentationMap.uri; } } if (!this.searchTermMap && mapUri) { const res = await fetch(mapUri); if (res.status < 400) { const body = await res.text(); const e = await Helpers.ParseXml(stripNamespaces(body)); const map = find( e.Presentation.PresentationMap, (m) => !!get(m, 'Match.SearchCategories') ); let searchCategories = get(map, 'Match.SearchCategories'); if (isArray(searchCategories)) { searchCategories = searchCategories[0]; } this.searchTermMap = get(searchCategories, 'Category'); } // INFO: https://github.com/SoCo/SoCo/blob/daba00b93b939fb4079778b4ed5a9abe07922c85/soco/music_services/music_service.py#L528 if (res.status === 404 && this.name === 'TuneIn') { this.searchTermMap = [ { id: 'stations', mappedId: 'search:station' }, { id: 'shows', mappedId: 'search:show' }, { id: 'hosts', mappedId: 'search:host' }, ]; } } return this.searchTermMap; } } export const getByServiceId = (sid) => { const { musicServices: { active: activeServices }, } = store.getState(); const serviceDefinition = activeServices.find((s) => s.service.Id === sid); if (!serviceDefinition) { return null; } return new MusicServiceClient( serviceDefinition.service, serviceDefinition.authToken || {} ); }; export default MusicServiceClient;
module.exports = { root: true, env: { node: true }, extends: './lib/index.js' };
import React, {Component} from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types' import 'bootstrap/dist/css/bootstrap.css'; import Header from '../header'; import Footer from '../footer'; import SupportForm from './SupportForm'; import { moreInfo } from '../../action'; import styles from './SupportMain.scss'; class SupportMain extends Component{ constructor(props) { super(props) this.handleSubmit = this.handleSubmit.bind(this) } handleSubmit(values) { moreInfo(values) } render() { return( <div> <Header /> <section className={ styles['support']} > <div className={ styles['contact-for-more'] }> <h3 className={ styles['support-title'] }>Need Support?</h3> <div className={ styles['support-content'] }>We've got you! <div className={ styles['support-content-detail'] }>Enter message and request below</div> <div className={ styles['support-content-detail'] }>and we will get back to you </div> </div> <SupportForm onSubmit = { this.handleSubmit }/> </div> </section> <Footer /> </div> ) } } export default SupportMain;
// a fairly complex CLI defined using the yargs 3.0 API: var argv = require('yargs/yargs')(process.argv.slice(2)) .usage('Usage: $0 <cmd> [options]') // usage string of application. .command('install', 'install a package (name@version)') // describe commands available. .command('publish', 'publish the package inside the current working directory') .option('f', { // document options. array: true, // even single values will be wrapped in []. description: 'an array of files', default: 'test.js', alias: 'file' }) .alias('f', 'fil') .option('h', { alias: 'help', description: 'display help message' }) .string(['user', 'pass']) .implies('user', 'pass') // if 'user' is set 'pass' must be set. .help('help') .demand('q') // fail if 'q' not provided. .version('1.0.1', 'version', 'display version information') // the version string. .alias('version', 'v') // show examples of application in action. .example('npm install npm@latest -g', 'install the latest version of npm') // final message to display when successful. .epilog('for more information visit https://github.com/chevex/yargs') // disable showing help on failures, provide a final message // to display for errors. .showHelpOnFail(false, 'whoops, something went wrong! run with --help') .argv; // the parsed data is stored in argv. console.log(argv);
// import assign from 'lodash/assign'; import generateConstants from 'utils/asyncSagaConstants'; const fournisseurConst = generateConstants('app/Fournisseur', 'load_fournisseur'); export default fournisseurConst;
module.exports = function (module, extended, config) { "use strict"; let async = require('async'); let error = require('./error.js')({'module': module, 'extends': extended}); if (typeof config !== 'object' || !config) return; let code = require('../../code'); let scoped = function (code) { // add an extra tab in all lines code = code.replace(/\n/g, '\n '); code = ' ' + code + '\n'; // add script inside its own function let output = ''; output += '(function (params) {\n\n'; output += ' var module = params[0];\n'; output += ' var extending = params[1];\n\n'; output += code; output += '})(beyond.modules.get(\'' + module.ID + '\', \'libraries/' + extended + '\'));'; return output; }; /** * Returns the code of the extension * * @param language * @param overwrite is actually used only by the script "custom" */ this.code = async(function *(resolve, reject, language, overwrites) { if (!overwrites) overwrites = {}; let script = yield code(module, config, language, overwrites); let output = require('./header')(module); output += scoped(script); let Resource = require('path').join(require('main.lib'), 'resource'); Resource = require(Resource); let resource = new Resource({'content': output, 'contentType': '.js'}); resolve(resource); }); Object.defineProperty(this, 'multilanguage', { 'get': async(function *(resolve) { resolve(config.multilanguage); }) }); };
import TilemapPlus from "./tilemap-plus/TilemapPlus"; import TilemapLayerPlus from "./tilemap-plus/TilemapLayerPlus"; import TilesetPlus from "./tilemap-plus/TilesetPlus"; import SpritePlus from "./tilemap-plus/SpritePlus"; Phaser.Plugin.TilemapPlus = function (game, parent) { Phaser.Plugin.call(this, game, parent); const originalTilemapLoader = Phaser.Loader.prototype.tilemap; Phaser.Loader.prototype.tilemap = function(key, url, data, format) { originalTilemapLoader.call(this, key, url, data, format); this.json(jsonKey(key), url); }; const originalTilemapFactory = Phaser.GameObjectFactory.prototype.tilemap; Phaser.GameObjectFactory.prototype.tilemap = function(key, tileWidth, tileHeight, width, height) { const tilemap = originalTilemapFactory.call(this, key, tileWidth, tileHeight, width, height); const tilemapJson = this.game.cache.getJSON(jsonKey(key)); tilemap.plus = new TilemapPlus(tilemapJson, this.game.time, tilemap); return tilemap; }; const originalTilemapCreateLayer = Phaser.Tilemap.prototype.createLayer; Phaser.Tilemap.prototype.createLayer = function(layer, width, height, group) { const tilemapLayer = originalTilemapCreateLayer.call(this, layer, width, height, group); tilemapLayer.plus = new TilemapLayerPlus(tilemapLayer); return tilemapLayer; }; const originalTilemapAddTilesetImage = Phaser.Tilemap.prototype.addTilesetImage; Phaser.Tilemap.prototype.addTilesetImage = function(tileset, key, tileWidth, tileHeight, tileMargin, tileSpacing, gid) { const tilesetImage = originalTilemapAddTilesetImage.call(this, tileset, key, tileWidth, tileHeight, tileMargin, tileSpacing, gid); tilesetImage.plus = new TilesetPlus(tilesetImage); return tilesetImage; }; const originalSpriteFactory = Phaser.GameObjectFactory.prototype.sprite; Phaser.GameObjectFactory.prototype.sprite = function(x, y, key, frame, group) { const sprite = originalSpriteFactory.call(this, x, y, key, frame, group); sprite.plus = new SpritePlus(sprite); return sprite; }; function jsonKey(key) { return key + "-TilemapPlus"; } };
export { default } from './me-page';
/** * File: detailedCard.js * * This file allows the detailed item display to open and close * * Version 1 * Authors: Sarah Murphy */ // Get the elements var menuModal = document.getElementById('detailedMenuModal'); var span = document.getElementsByClassName("closeModal")[0]; // When the user clicks on x, close the modal span.onclick = function() { menuModal.style.display = "none"; } // When the user clicks anywhere outside of the modal, close it window.onclick = function(event) { if (event.target == menuModal) { menuModal.style.display = "none"; } }
/*global casper*/ /*jshint strict:false*/ var fs = require('fs'), testFile = '/tmp/__casper_test_capture.png'; if (fs.exists(testFile) && fs.isFile(testFile)) { fs.remove(testFile); } casper.start('tests/site/index.html', function() { this.viewport(300, 200); this.test.comment('Casper.capture()'); this.capture(testFile); this.test.assert(fs.isFile(testFile), 'Casper.capture() captured a screenshot'); }); if (phantom.version.major === 1 && phantom.version.minor >= 6) { casper.thenOpen('tests/site/index.html', function() { this.test.comment('Casper.captureBase64()'); this.test.assert(this.captureBase64('png').length > 0, 'Casper.captureBase64() rendered a page capture as base64'); this.test.assert(this.captureBase64('png', 'ul').length > 0, 'Casper.captureBase64() rendered a capture from a selector as base64'); this.test.assert(this.captureBase64('png', {top: 0, left: 0, width: 30, height: 30}).length > 0, 'Casper.captureBase64() rendered a capture from a clipRect as base64'); }); } casper.run(function() { try { fs.remove(testFile); } catch(e) {} this.test.done(); });
/* globals $ */ $().ready(() => { $('#userSignUpForm').validate({ rules: { username: { required: true, minlength: 2, maxlength: 15, regx: /^[a-zA-Z0-9_\\.]+$/ }, email: { required: true, email: true, regx: /^\w+([\\.-]?\w+)*@\w+([\\.-]?\w+)*(\.\w{2,3})+$/ }, address: { required: true, minlength: 15, maxlength: 60, regx: /^[a-zA-z\d\s\\.\-]+$/ }, password: { required: true, minlength: 4, maxlength: 12, regx: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{4,12}$/ }, }, messages: { username: { required: 'Username is required!', minlength: 'Username should be at least 2 symbols long!', maxlength: 'Username should not be more than 15 symbols long!', regx: 'Username should ' + 'contain only latin letters, numbers, . and _' }, email: 'Enter valid email please!', address: { required: 'Address is required!', minlength: 'Address should be at least 15 symbols long!', maxlength: 'Address should not be more than 30 symbols long!', regx: 'Address should contain only ' + 'latin letters, numbers, white spaces, (-), (.)!' }, password: { required: 'Password is required!', minlength: 'Password should be at least 4 symbols long!', maxlength: 'Password should not be more than 12 symbols long!', regx: 'Password should contain latin letters and numbers!' }, }, errorPlacement: function(error, element) { error.css({ 'color': 'red', 'font-size': '110%', 'font-style': 'italic', }); if (element.attr('name') === 'username' ) { error.insertAfter('#usernameInputGroup'); } else if (element.attr('name') === 'email' ) { error.insertAfter('#emailInputGroup'); } else if (element.attr('name') === 'address' ) { error.insertAfter('#addressInputGroup'); } else if (element.attr('name') === 'password' ) { error.insertAfter('#passwordInputGroup'); } } }); }); $.validator.addMethod('regx', function(value, element, regexpr) { return regexpr.test(value); });
/* ======================================================================== * Bootstrap: tooltip.js v3.4.0 * http://getbootstrap.com/javascript/#tooltip * Inspired by the original jQuery.tipsy by Jason Frame * ======================================================================== * Copyright 2011-2018 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // TOOLTIP PUBLIC CLASS DEFINITION // =============================== var Tooltip = function (element, options) { this.type = null this.options = null this.enabled = null this.timeout = null this.hoverState = null this.$element = null this.inState = null this.init('tooltip', element, options) } Tooltip.VERSION = '3.4.0' Tooltip.TRANSITION_DURATION = 150 Tooltip.DEFAULTS = { animation: true, placement: 'top', selector: false, template: '<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>', trigger: 'hover focus', title: '', delay: 0, html: false, container: false, viewport: { selector: 'body', padding: 0 } } Tooltip.prototype.init = function (type, element, options) { this.enabled = true this.type = type this.$element = $(element) this.options = this.getOptions(options) this.$viewport = this.options.viewport && $(document).find($.isFunction(this.options.viewport) ? this.options.viewport.call(this, this.$element) : (this.options.viewport.selector || this.options.viewport)) this.inState = { click: false, hover: false, focus: false } if (this.$element[0] instanceof document.constructor && !this.options.selector) { throw new Error('`selector` option must be specified when initializing ' + this.type + ' on the window.document object!') } var triggers = this.options.trigger.split(' ') for (var i = triggers.length; i--;) { var trigger = triggers[i] if (trigger == 'click') { this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this)) } else if (trigger != 'manual') { var eventIn = trigger == 'hover' ? 'mouseenter' : 'focusin' var eventOut = trigger == 'hover' ? 'mouseleave' : 'focusout' this.$element.on(eventIn + '.' + this.type, this.options.selector, $.proxy(this.enter, this)) this.$element.on(eventOut + '.' + this.type, this.options.selector, $.proxy(this.leave, this)) } } this.options.selector ? (this._options = $.extend({}, this.options, { trigger: 'manual', selector: '' })) : this.fixTitle() } Tooltip.prototype.getDefaults = function () { return Tooltip.DEFAULTS } Tooltip.prototype.getOptions = function (options) { options = $.extend({}, this.getDefaults(), this.$element.data(), options) if (options.delay && typeof options.delay == 'number') { options.delay = { show: options.delay, hide: options.delay } } return options } Tooltip.prototype.getDelegateOptions = function () { var options = {} var defaults = this.getDefaults() this._options && $.each(this._options, function (key, value) { if (defaults[key] != value) options[key] = value }) return options } Tooltip.prototype.enter = function (obj) { var self = obj instanceof this.constructor ? obj : $(obj.currentTarget).data('bs.' + this.type) if (!self) { self = new this.constructor(obj.currentTarget, this.getDelegateOptions()) $(obj.currentTarget).data('bs.' + this.type, self) } if (obj instanceof $.Event) { self.inState[obj.type == 'focusin' ? 'focus' : 'hover'] = true } if (self.tip().hasClass('in') || self.hoverState == 'in') { self.hoverState = 'in' return } clearTimeout(self.timeout) self.hoverState = 'in' if (!self.options.delay || !self.options.delay.show) return self.show() self.timeout = setTimeout(function () { if (self.hoverState == 'in') self.show() }, self.options.delay.show) } Tooltip.prototype.isInStateTrue = function () { for (var key in this.inState) { if (this.inState[key]) return true } return false } Tooltip.prototype.leave = function (obj) { var self = obj instanceof this.constructor ? obj : $(obj.currentTarget).data('bs.' + this.type) if (!self) { self = new this.constructor(obj.currentTarget, this.getDelegateOptions()) $(obj.currentTarget).data('bs.' + this.type, self) } if (obj instanceof $.Event) { self.inState[obj.type == 'focusout' ? 'focus' : 'hover'] = false } if (self.isInStateTrue()) return clearTimeout(self.timeout) self.hoverState = 'out' if (!self.options.delay || !self.options.delay.hide) return self.hide() self.timeout = setTimeout(function () { if (self.hoverState == 'out') self.hide() }, self.options.delay.hide) } Tooltip.prototype.show = function () { var e = $.Event('show.bs.' + this.type) if (this.hasContent() && this.enabled) { this.$element.trigger(e) var inDom = $.contains(this.$element[0].ownerDocument.documentElement, this.$element[0]) if (e.isDefaultPrevented() || !inDom) return var that = this var $tip = this.tip() var tipId = this.getUID(this.type) this.setContent() $tip.attr('id', tipId) this.$element.attr('aria-describedby', tipId) if (this.options.animation) $tip.addClass('fade') var placement = typeof this.options.placement == 'function' ? this.options.placement.call(this, $tip[0], this.$element[0]) : this.options.placement var autoToken = /\s?auto?\s?/i var autoPlace = autoToken.test(placement) if (autoPlace) placement = placement.replace(autoToken, '') || 'top' $tip .detach() .css({ top: 0, left: 0, display: 'block' }) .addClass(placement) .data('bs.' + this.type, this) this.options.container ? $tip.appendTo($(document).find(this.options.container)) : $tip.insertAfter(this.$element) this.$element.trigger('inserted.bs.' + this.type) var pos = this.getPosition() var actualWidth = $tip[0].offsetWidth var actualHeight = $tip[0].offsetHeight if (autoPlace) { var orgPlacement = placement var viewportDim = this.getPosition(this.$viewport) placement = placement == 'bottom' && pos.bottom + actualHeight > viewportDim.bottom ? 'top' : placement == 'top' && pos.top - actualHeight < viewportDim.top ? 'bottom' : placement == 'right' && pos.right + actualWidth > viewportDim.width ? 'left' : placement == 'left' && pos.left - actualWidth < viewportDim.left ? 'right' : placement $tip .removeClass(orgPlacement) .addClass(placement) } var calculatedOffset = this.getCalculatedOffset(placement, pos, actualWidth, actualHeight) this.applyPlacement(calculatedOffset, placement) var complete = function () { var prevHoverState = that.hoverState that.$element.trigger('shown.bs.' + that.type) that.hoverState = null if (prevHoverState == 'out') that.leave(that) } $.support.transition && this.$tip.hasClass('fade') ? $tip .one('bsTransitionEnd', complete) .emulateTransitionEnd(Tooltip.TRANSITION_DURATION) : complete() } } Tooltip.prototype.applyPlacement = function (offset, placement) { var $tip = this.tip() var width = $tip[0].offsetWidth var height = $tip[0].offsetHeight // manually read margins because getBoundingClientRect includes difference var marginTop = parseInt($tip.css('margin-top'), 10) var marginLeft = parseInt($tip.css('margin-left'), 10) // we must check for NaN for ie 8/9 if (isNaN(marginTop)) marginTop = 0 if (isNaN(marginLeft)) marginLeft = 0 offset.top += marginTop offset.left += marginLeft // $.fn.offset doesn't round pixel values // so we use setOffset directly with our own function B-0 $.offset.setOffset($tip[0], $.extend({ using: function (props) { $tip.css({ top: Math.round(props.top), left: Math.round(props.left) }) } }, offset), 0) $tip.addClass('in') // check to see if placing tip in new offset caused the tip to resize itself var actualWidth = $tip[0].offsetWidth var actualHeight = $tip[0].offsetHeight if (placement == 'top' && actualHeight != height) { offset.top = offset.top + height - actualHeight } var delta = this.getViewportAdjustedDelta(placement, offset, actualWidth, actualHeight) if (delta.left) offset.left += delta.left else offset.top += delta.top var isVertical = /top|bottom/.test(placement) var arrowDelta = isVertical ? delta.left * 2 - width + actualWidth : delta.top * 2 - height + actualHeight var arrowOffsetPosition = isVertical ? 'offsetWidth' : 'offsetHeight' $tip.offset(offset) this.replaceArrow(arrowDelta, $tip[0][arrowOffsetPosition], isVertical) } Tooltip.prototype.replaceArrow = function (delta, dimension, isVertical) { this.arrow() .css(isVertical ? 'left' : 'top', 50 * (1 - delta / dimension) + '%') .css(isVertical ? 'top' : 'left', '') } Tooltip.prototype.setContent = function () { var $tip = this.tip() var title = this.getTitle() $tip.find('.tooltip-inner')[this.options.html ? 'html' : 'text'](title) $tip.removeClass('fade in top bottom left right') } Tooltip.prototype.hide = function (callback) { var that = this var $tip = $(this.$tip) var e = $.Event('hide.bs.' + this.type) function complete() { if (that.hoverState != 'in') $tip.detach() if (that.$element) { // TODO: Check whether guarding this code with this `if` is really necessary. that.$element .removeAttr('aria-describedby') .trigger('hidden.bs.' + that.type) } callback && callback() } this.$element.trigger(e) if (e.isDefaultPrevented()) return $tip.removeClass('in') $.support.transition && $tip.hasClass('fade') ? $tip .one('bsTransitionEnd', complete) .emulateTransitionEnd(Tooltip.TRANSITION_DURATION) : complete() this.hoverState = null return this } Tooltip.prototype.fixTitle = function () { var $e = this.$element if ($e.attr('title') || typeof $e.attr('data-original-title') != 'string') { $e.attr('data-original-title', $e.attr('title') || '').attr('title', '') } } Tooltip.prototype.hasContent = function () { return this.getTitle() } Tooltip.prototype.getPosition = function ($element) { $element = $element || this.$element var el = $element[0] var isBody = el.tagName == 'BODY' var elRect = el.getBoundingClientRect() if (elRect.width == null) { // width and height are missing in IE8, so compute them manually; see https://github.com/twbs/bootstrap/issues/14093 elRect = $.extend({}, elRect, { width: elRect.right - elRect.left, height: elRect.bottom - elRect.top }) } var isSvg = window.SVGElement && el instanceof window.SVGElement // Avoid using $.offset() on SVGs since it gives incorrect results in jQuery 3. // See https://github.com/twbs/bootstrap/issues/20280 var elOffset = isBody ? { top: 0, left: 0 } : (isSvg ? null : $element.offset()) var scroll = { scroll: isBody ? document.documentElement.scrollTop || document.body.scrollTop : $element.scrollTop() } var outerDims = isBody ? { width: $(window).width(), height: $(window).height() } : null return $.extend({}, elRect, scroll, outerDims, elOffset) } Tooltip.prototype.getCalculatedOffset = function (placement, pos, actualWidth, actualHeight) { return placement == 'bottom' ? { top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2 } : placement == 'top' ? { top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2 } : placement == 'left' ? { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth } : /* placement == 'right' */ { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width } } Tooltip.prototype.getViewportAdjustedDelta = function (placement, pos, actualWidth, actualHeight) { var delta = { top: 0, left: 0 } if (!this.$viewport) return delta var viewportPadding = this.options.viewport && this.options.viewport.padding || 0 var viewportDimensions = this.getPosition(this.$viewport) if (/right|left/.test(placement)) { var topEdgeOffset = pos.top - viewportPadding - viewportDimensions.scroll var bottomEdgeOffset = pos.top + viewportPadding - viewportDimensions.scroll + actualHeight if (topEdgeOffset < viewportDimensions.top) { // top overflow delta.top = viewportDimensions.top - topEdgeOffset } else if (bottomEdgeOffset > viewportDimensions.top + viewportDimensions.height) { // bottom overflow delta.top = viewportDimensions.top + viewportDimensions.height - bottomEdgeOffset } } else { var leftEdgeOffset = pos.left - viewportPadding var rightEdgeOffset = pos.left + viewportPadding + actualWidth if (leftEdgeOffset < viewportDimensions.left) { // left overflow delta.left = viewportDimensions.left - leftEdgeOffset } else if (rightEdgeOffset > viewportDimensions.right) { // right overflow delta.left = viewportDimensions.left + viewportDimensions.width - rightEdgeOffset } } return delta } Tooltip.prototype.getTitle = function () { var title var $e = this.$element var o = this.options title = $e.attr('data-original-title') || (typeof o.title == 'function' ? o.title.call($e[0]) : o.title) return title } Tooltip.prototype.getUID = function (prefix) { do prefix += ~~(Math.random() * 1000000) while (document.getElementById(prefix)) return prefix } Tooltip.prototype.tip = function () { if (!this.$tip) { this.$tip = $(this.options.template) if (this.$tip.length != 1) { throw new Error(this.type + ' `template` option must consist of exactly 1 top-level element!') } } return this.$tip } Tooltip.prototype.arrow = function () { return (this.$arrow = this.$arrow || this.tip().find('.tooltip-arrow')) } Tooltip.prototype.enable = function () { this.enabled = true } Tooltip.prototype.disable = function () { this.enabled = false } Tooltip.prototype.toggleEnabled = function () { this.enabled = !this.enabled } Tooltip.prototype.toggle = function (e) { var self = this if (e) { self = $(e.currentTarget).data('bs.' + this.type) if (!self) { self = new this.constructor(e.currentTarget, this.getDelegateOptions()) $(e.currentTarget).data('bs.' + this.type, self) } } if (e) { self.inState.click = !self.inState.click if (self.isInStateTrue()) self.enter(self) else self.leave(self) } else { self.tip().hasClass('in') ? self.leave(self) : self.enter(self) } } Tooltip.prototype.destroy = function () { var that = this clearTimeout(this.timeout) this.hide(function () { that.$element.off('.' + that.type).removeData('bs.' + that.type) if (that.$tip) { that.$tip.detach() } that.$tip = null that.$arrow = null that.$viewport = null that.$element = null }) } // TOOLTIP PLUGIN DEFINITION // ========================= function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.tooltip') var options = typeof option == 'object' && option if (!data && /destroy|hide/.test(option)) return if (!data) $this.data('bs.tooltip', (data = new Tooltip(this, options))) if (typeof option == 'string') data[option]() }) } var old = $.fn.tooltip $.fn.tooltip = Plugin $.fn.tooltip.Constructor = Tooltip // TOOLTIP NO CONFLICT // =================== $.fn.tooltip.noConflict = function () { $.fn.tooltip = old return this } }(jQuery);
'use strict'; /** * FUNCTION: qmean( arr, clbk ) * Computes the quadratic mean of an array using an accessor function. * * @param {Array} arr - input array * @param {Function} clbk - accessor function for accessing array values * @returns {Number|Null} quadratic mean or null */ function qmean( arr, clbk ) { var len = arr.length, t = 0, s = 1, r, val, abs; if ( !len ) { return null; } for ( var i = 0; i < len; i++ ) { val = clbk( arr[ i ], i ); abs = val; if ( abs < 0 ) { abs = -abs; } if ( abs > 0 ) { if ( abs > t ) { r = t / val; s = 1 + s*r*r; t = abs; } else { r = val / t; s = s + r*r; } } } return t * Math.sqrt( s/len ); } // end FUNCTION qmean() // EXPORTS // module.exports = qmean;
(function (ns) { 'use strict'; ns.models.RmIssueModel = function () { return { system: undefined, //inject restClient: undefined, rmProjectModel: undefined, rmUserModel: undefined, dataService: undefined, configUtils: undefined, currentStart: 0, issues: [], step: 100, TYPE: 'issue', refresh: function(idProject){ var self = this; //Search for default filter self.configUtils.read(this.rmUserModel.CONFIG_ID, function(defaultFilter){ var additionalData = { project_id: idProject, sort: 'updated_on:desc' }; if(defaultFilter == 1) { additionalData.assigned_to_id = self.rmUserModel.currentUser.id; } self.dataService.paginatedRefresh(false, 'issues', 'Issue:refresh:success', function(issues){ self.issues = issues; }, additionalData); }); }, getById: function(id, callback, callbackError){ var self = this; this.restClient.call(this.restClient.methods.GET, 'issues/'+id, null, function(result){ if(callback) { callback(result.issue); } }, callbackError); }, reset: function(){ this.issues = []; } }; }; }(chalk));
'use strict'; var AssetPathService = function () { return ''; // '/android_asset/www/'; }; module.exports = AssetPathService;
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), Schema = mongoose.Schema; /** * Contact Schema */ var ContactSchema = new Schema({ username: { type: String, required: true, trim: true }, email: { type: String, required: true, trim: true }, msg: { type: String, required: true, trim: true }, ip: { type: String, trim: true }, referer: { type: String, trim: true }, created: { type: Date, required: true, default: Date.now } }); /** * Validations */ ContactSchema.path('username').validate(function(username) { if(typeof username !== 'undefined' && username !== null){ return username.length > 0; } return false; }, 'Username cannot be empty'); ContactSchema.path('email').validate(function(email) { if(typeof email !== 'undefined' && email !== null){ return email.length; } return false; }, 'Email cannot be empty'); ContactSchema.path('email').validate(function(email) { if(typeof email !== 'undefined' && email !== null){ var emailRegex = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/; return emailRegex.test(email); } return false; }, 'The email is not a valid email'); ContactSchema.path('msg').validate(function(msg) { if(typeof msg !== 'undefined' && msg !== null){ return msg.length > 0; } return false; }, 'The message cannot be empty'); mongoose.model('Contact', ContactSchema);
$(function(){ $("#close").click(function(){ $('#imgs').hide(); }); })
/*! jQuery UI - v1.10.3 - 2013-09-23 * http://jqueryui.com * Copyright 2013 jQuery Foundation and other contributors; Licensed MIT */ jQuery(function(t){t.datepicker.regional.he={closeText:"סגור",prevText:"&#x3C;הקודם",nextText:"הבא&#x3E;",currentText:"היום",monthNames:["ינואר","פברואר","מרץ","אפריל","מאי","יוני","יולי","אוגוסט","ספטמבר","אוקטובר","נובמבר","דצמבר"],monthNamesShort:["ינו","פבר","מרץ","אפר","מאי","יוני","יולי","אוג","ספט","אוק","נוב","דצמ"],dayNames:["ראשון","שני","שלישי","רביעי","חמישי","שישי","שבת"],dayNamesShort:["א'","ב'","ג'","ד'","ה'","ו'","שבת"],dayNamesMin:["א'","ב'","ג'","ד'","ה'","ו'","שבת"],weekHeader:"Wk",dateFormat:"dd/mm/yy",firstDay:0,isRTL:!0,showMonthAfterYear:!1,yearSuffix:""},t.datepicker.setDefaults(t.datepicker.regional.he)});
import { unprotect } from 'mobx-state-tree'; import { Stores, itemPost60, itemCat7 } from '../mocks'; let stores; beforeEach(() => { stores = Stores.create({}); unprotect(stores); }); describe('Analytics > GoogleAnalytics', () => { test('sendPageView', () => { window.ga = jest.fn(); stores.connection.selectedItem = itemPost60; stores.analytics.googleAnalytics.sendPageView(); expect(window.ga).toHaveBeenCalledTimes(2); stores.connection.selectedItem = itemCat7; stores.analytics.googleAnalytics.sendPageView(); expect(window.ga).toHaveBeenCalledTimes(4); expect(window.ga.mock.calls).toMatchSnapshot(); }); test('sendEvent', () => { const event = { category: 'test/category', action: 'test/action', label: 'test/label', }; window.ga = jest.fn(); stores.analytics.googleAnalytics.sendEvent(event); expect(window.ga).toHaveBeenCalledTimes(2); expect(window.ga.mock.calls).toMatchSnapshot(); }); test('ids', () => { stores.build = { channel: 'pwa' }; expect(stores.analytics.googleAnalytics.ids).toMatchSnapshot(); stores.build = { channel: 'amp' }; expect(stores.analytics.googleAnalytics.ids).toMatchSnapshot(); }); test('trackingOptions', () => { const { trackingOptions } = stores.analytics.googleAnalytics; let ids; stores.build = { channel: 'pwa' }; ({ ids } = stores.analytics.googleAnalytics); expect(ids.map(id => trackingOptions(id))).toMatchSnapshot(); stores.build = { channel: 'amp' }; ({ ids } = stores.analytics.googleAnalytics); expect(ids.map(id => trackingOptions(id))).toMatchSnapshot(); }); test('pageView', () => { stores.build = { channel: 'pwa' }; expect(stores.analytics.googleAnalytics.pageView).toMatchSnapshot(); stores.build = { channel: 'amp', isAmp: true }; expect(stores.analytics.googleAnalytics.pageView).toMatchSnapshot(); }); });
var Guides = require('../src/modules/Guides'); describe("Guides class tests", function() { var $element = $('<div>Test</div>', {position: 'fixed'}).appendTo('body'), guides; $element.width(window.innerWidth); $element.height(20); $element.offset({top: 0, left: 0}); beforeEach(function (done) { guides = new Guides($element, { guides: [{ element: $element, html: 'Welcome to Guides.js' }, { element: $element, html: 'Navigate through guides.js website' }, { element: $element, html: 'See how it works' }, { element: $element, html: 'Download guides.js' }, { element: $element, html: 'Check out how to get started with guides.js' }, { element: $element, html: 'Read the docs' }] }); done(); }); afterEach(function (done) { guides.destroy(); done(); }); it('only one element is created if start is called twice', function() { guides.start().start(); expect($('.guides-canvas').length).toBe(1); }); it('does not throw an error if a method other than start is called before start', function() { expect(guides.next).not.toThrow(Error); expect(guides.prev).not.toThrow(Error); expect(guides.end).not.toThrow(Error); expect(guides.destroy).not.toThrow(Error); }); it('sets the correct step when the start method is called', function() { guides.start(); expect(guides._current).toBe(0); }); it('sets the correct step when the next method is called', function() { guides.start().next(); expect(guides._current).toBe(1); }); it('sets the correct step when the prev method is called', function() { guides.start().next().prev(); expect(guides._current).toBe(0); }); it('removes dom elements when the end method is called', function() { guides.start().end(); expect(guides.$canvas).toBe(null); expect($('.guides-canvas').length).toBe(0); }); it('sets the new options correctly when setOptions method is called', function() { guides.setOptions({ start: function () {} }); expect(typeof guides.options.guides).toBe('object'); expect(typeof guides.options.start).toContain('function'); }); it('calls event handlers', function() { var test = 0; guides.setOptions({ start: function () { test = 1; } }); guides.start(); expect(test).toBe(1); }); it('uses guide color setting', function() { guides.options.color = 'red'; guides.options.guides[0].color = 'blue'; guides.start(); expect(guides._currentGuide._color).toBe('blue'); }); it('falls back to global color setting', function() { guides.setOptions({ color: 'red' }); guides.start(); expect(guides._currentGuide._color).toBe('red'); }); it('removes dom elements when destroy method is called', function() { guides.start().destroy(); expect(guides.$canvas).toBe(null); expect($('.guides-canvas').length).toBe(0); }); });
import { expect } from 'chai'; import * as helpers from './helpers'; import * as funcs from './ch2-q3'; for (let key in funcs) { let func = funcs[key]; describe('ch2-q3: ' + key, function() { it('throws an error if node is invalid', function() { expect(() => func(null)).to.throw('invalid node'); expect(() => func(undefined)).to.throw('invalid node'); expect(() => func(helpers.arrayToLinkedList([11]))).to.throw('invalid node'); }); it('can delete multiple in long list', function() { let list = helpers.arrayToLinkedList([8, 6, 4, 2, 1]); func(list); func(list); func(list); func(list); expect(list.val).to.equal(1); expect(list.next).to.be.null; }); [ { list: [5, 8], node: 0, expected: [8] }, { list: [5, 8, 3, 2, 7, 1, 4, 9, 15, 30], node: 8, expected: [5, 8, 3, 2, 7, 1, 4, 9, 30] }, { list: [5, 8, 3, 2, 7, 1, 4, 9, 15, 30], node: 4, expected: [5, 8, 3, 2, 1, 4, 9, 15, 30] }, { list: [5, 8, 3, 2, 7, 1, 4, 9, 15, 30], node: 1, expected: [5, 3, 2, 7, 1, 4, 9, 15, 30] }, { list: [5, 8, 3, 2, 7, 1, 4, 9, 15, 30], node: 2, expected: [5, 8, 2, 7, 1, 4, 9, 15, 30] } ].forEach(context => { it(`removing node ${context.node} from list ${context.list}`, function() { let list = helpers.arrayToLinkedList(context.list), node = list; for (let i = 0; i < context.node; ++i) { node = node.next; } func(node); expect(helpers.linkedListToArray(list)).to.eql(context.expected); }); }); }); }
/* */ (function(process) { 'use strict'; var version = require('../package.json!systemjs-json').version, tmplNew = require('../dist/tmpl').tmpl, tmpl22 = require('./v223/tmpl223').tmpl; var data = { num: 1, str: 'string', date: new Date(), bool: true, item: null }, tmplList = [[' { date }', ' ' + data.date], [' { num === 0 ? 0 : num } ', ' ' + data.num + ' '], ['<p>\n{str + num}\n</p>', '<p>\nstring1\n</p>'], [' "{ str.slice(0, 3).replace(/t/, \'T\') }" ', ' "sTr" '], [' "{this.num}" ', ' "1" '], ['{ !bool } ', ' '], ['{} ', ' ']], exprList = [['{ date }', data.date], ['{ num === 0 ? 0 : num }', data.num], ['<p>{str + num}</p>', '<p>string1</p>'], ['{ "-" + str.slice(0, 3).replace(/t/, \'T\') + "-" }', '-sTr-'], ['{this.num}', 1], ['{ !bool }', false], ['{}', undefined]], csList = [['{ foo: num }', 'foo'], ['{ foo: num, bar: item }', 'foo'], ['{ foo: date.getFullYear() > 2000, bar: str==this.str }', 'foo bar'], ['{ foo: str + num }', 'foo']], ex22a, ex22b, ex22c, mem22, tt22 = [], exNewa, exNewb, exNewc, memNew, tt23 = []; var LOOP = 50000, TMAX = 12, CPAD = 12, NPAD = 11; console.log(); console.log('Testing %d expressions %d times each.', exprList.length + csList.length, LOOP); console.log('tmpl v2.2.4 ...'); mem22 = [0, 0, 0]; testExpr(tmpl22, data, tt22, exprList, mem22); ex22a = tt22.reduce(numsum); testExpr(tmpl22, data, tt22, csList, mem22); ex22b = tt22.reduce(numsum); testExpr(tmpl22, data, tt22, tmplList, mem22); ex22c = tt22.reduce(numsum); console.log('tmpl v' + version + ' ...'); memNew = [0, 0, 0]; testExpr(tmplNew, data, tt23, exprList, memNew, 1); exNewa = tt23.reduce(numsum); testExpr(tmplNew, data, tt23, csList, memNew, 1); exNewb = tt23.reduce(numsum); testExpr(tmplNew, data, tt23, tmplList, memNew, 1); exNewc = tt23.reduce(numsum); console.log(); console.log('%s tmpl 2.2.4 new v' + version, padr('Results', CPAD)); console.log('%s ---------- ----------', replicate('-', CPAD)); console.log('%s: %s %s', padr('Expressions', CPAD), padl(ex22a, NPAD), padl(exNewa, NPAD)); console.log('%s: %s %s', padr('Shorthands', CPAD), padl(ex22b, NPAD), padl(exNewb, NPAD)); console.log('%s: %s %s', padr('Templates', CPAD), padl(ex22c, NPAD), padl(exNewc, NPAD)); console.log('%s: %s %s', padr('TOTAL', CPAD), padl(ex22a + ex22b + ex22c, NPAD), padl(exNewa + exNewb + exNewc, NPAD)); console.log(); console.log('Memory'); console.log('%s: %s %s', padr('Heap total', CPAD), padl(mem22[1], NPAD), padl(memNew[1], NPAD)); console.log('%s: %s %s', padr('Heap used', CPAD), padl(mem22[2], NPAD), padl(memNew[2], NPAD)); console.log(); console.log('NOTES:'); console.log('- Memory used is the difference during the test of the heapTotal info'); console.log(' provided by the node process.memoryUsage() function.'); console.log('- Execution time in both versions excludes expression compilation.'); console.log('- Minimum & maximum times are removed.'); function testExpr(tmpl, data, times, list, agc) { var ogc, gc1, gc2, gc3; times.length = 0; global.gc(); global.gc(); ogc = process.memoryUsage(); gc1 = ogc.rss; gc2 = ogc.heapTotal; gc3 = ogc.heapUsed; list.forEach(function(pair, idx) { var tt = new Array(TMAX), s, i, j, expr = pair[0]; s = tmpl(expr, data); if (s !== pair[1]) { throw new Error('`' + s + '` in #' + idx + ' is not `' + pair[1] + '`'); } for (i = 0; i < tt.length; ++i) { tt[i] = Date.now(); for (j = 0; j < LOOP; ++j) { s = tmpl(expr, data); } tt[i] = Date.now() - tt[i]; } tt.sort(numsort).pop(); tt.shift(); times[idx] = tt.reduce(numsum); }); ogc = process.memoryUsage(); agc[0] += ogc.rss - gc1; agc[1] += ogc.heapTotal - gc2; agc[2] += ogc.heapUsed - gc3; } function numsort(a, b) { return a - b; } function numsum(a, b) { return a + b; } function replicate(s, n) { return n < 1 ? '' : (new Array(n + 1)).join(s); } function padr(s, n) { s = '' + s; return s + replicate(' ', n - s.length); } function padl(s, n) { s = '' + s; return replicate(' ', n - s.length) + s; } })(require('process'));
/*! * devextreme-angular * Version: 16.2.5 * Build date: Tue Feb 28 2017 * * Copyright (c) 2012 - 2017 Developer Express Inc. ALL RIGHTS RESERVED * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file in the root of the project for details. * * https://github.com/DevExpress/devextreme-angular */ "use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var core_1 = require('@angular/core'); var tag_box_1 = require('devextreme/ui/tag_box'); var validator_1 = require('./validator'); var forms_1 = require('@angular/forms'); var component_1 = require('../core/component'); var template_host_1 = require('../core/template-host'); var template_1 = require('../core/template'); var nested_option_1 = require('../core/nested-option'); var watcher_helper_1 = require('../core/watcher-helper'); var iterable_differ_helper_1 = require('../core/iterable-differ-helper'); var item_dxi_1 = require('./nested/item-dxi'); var item_dxi_2 = require('./nested/item-dxi'); var CUSTOM_VALUE_ACCESSOR_PROVIDER = { provide: forms_1.NG_VALUE_ACCESSOR, useExisting: core_1.forwardRef(function () { return DxTagBoxComponent; }), multi: true }; var DxTagBoxComponent = (function (_super) { __extends(DxTagBoxComponent, _super); function DxTagBoxComponent(elementRef, ngZone, templateHost, _watcherHelper, _idh, optionHost) { _super.call(this, elementRef, ngZone, templateHost, _watcherHelper); this._watcherHelper = _watcherHelper; this._idh = _idh; this.touched = function () { }; this._createEventEmitters([ { subscribe: 'disposing', emit: 'onDisposing' }, { subscribe: 'initialized', emit: 'onInitialized' }, { subscribe: 'optionChanged', emit: 'onOptionChanged' }, { subscribe: 'focusIn', emit: 'onFocusIn' }, { subscribe: 'focusOut', emit: 'onFocusOut' }, { subscribe: 'valueChanged', emit: 'onValueChanged' }, { subscribe: 'change', emit: 'onChange' }, { subscribe: 'enterKey', emit: 'onEnterKey' }, { subscribe: 'input', emit: 'onInput' }, { subscribe: 'keyDown', emit: 'onKeyDown' }, { subscribe: 'keyPress', emit: 'onKeyPress' }, { subscribe: 'keyUp', emit: 'onKeyUp' }, { subscribe: 'closed', emit: 'onClosed' }, { subscribe: 'opened', emit: 'onOpened' }, { subscribe: 'contentReady', emit: 'onContentReady' }, { subscribe: 'itemClick', emit: 'onItemClick' }, { subscribe: 'selectionChanged', emit: 'onSelectionChanged' }, { subscribe: 'customItemCreating', emit: 'onCustomItemCreating' }, { subscribe: 'selectAllValueChanged', emit: 'onSelectAllValueChanged' }, { emit: 'dataSourceChange' }, { emit: 'displayExprChange' }, { emit: 'itemTemplateChange' }, { emit: 'valueExprChange' }, { emit: 'itemsChange' }, { emit: 'elementAttrChange' }, { emit: 'heightChange' }, { emit: 'rtlEnabledChange' }, { emit: 'widthChange' }, { emit: 'accessKeyChange' }, { emit: 'activeStateEnabledChange' }, { emit: 'disabledChange' }, { emit: 'focusStateEnabledChange' }, { emit: 'hintChange' }, { emit: 'hoverStateEnabledChange' }, { emit: 'tabIndexChange' }, { emit: 'visibleChange' }, { emit: 'isValidChange' }, { emit: 'nameChange' }, { emit: 'readOnlyChange' }, { emit: 'validationErrorChange' }, { emit: 'validationMessageModeChange' }, { emit: 'valueChange' }, { emit: 'attrChange' }, { emit: 'inputAttrChange' }, { emit: 'placeholderChange' }, { emit: 'showClearButtonChange' }, { emit: 'textChange' }, { emit: 'acceptCustomValueChange' }, { emit: 'applyValueModeChange' }, { emit: 'deferRenderingChange' }, { emit: 'fieldEditEnabledChange' }, { emit: 'openedChange' }, { emit: 'fieldTemplateChange' }, { emit: 'minSearchLengthChange' }, { emit: 'noDataTextChange' }, { emit: 'pagingEnabledChange' }, { emit: 'searchEnabledChange' }, { emit: 'searchExprChange' }, { emit: 'searchModeChange' }, { emit: 'searchTimeoutChange' }, { emit: 'showDataBeforeSearchChange' }, { emit: 'showSelectionControlsChange' }, { emit: 'hideSelectedItemsChange' }, { emit: 'multilineChange' }, { emit: 'selectAllModeChange' }, { emit: 'selectedItemsChange' }, { emit: 'tagTemplateChange' }, { emit: 'valuesChange' } ]); this._idh.setHost(this); optionHost.setHost(this); } Object.defineProperty(DxTagBoxComponent.prototype, "dataSource", { get: function () { return this._getOption('dataSource'); }, set: function (value) { this._setOption('dataSource', value); }, enumerable: true, configurable: true }); Object.defineProperty(DxTagBoxComponent.prototype, "displayExpr", { get: function () { return this._getOption('displayExpr'); }, set: function (value) { this._setOption('displayExpr', value); }, enumerable: true, configurable: true }); Object.defineProperty(DxTagBoxComponent.prototype, "itemTemplate", { get: function () { return this._getOption('itemTemplate'); }, set: function (value) { this._setOption('itemTemplate', value); }, enumerable: true, configurable: true }); Object.defineProperty(DxTagBoxComponent.prototype, "valueExpr", { get: function () { return this._getOption('valueExpr'); }, set: function (value) { this._setOption('valueExpr', value); }, enumerable: true, configurable: true }); Object.defineProperty(DxTagBoxComponent.prototype, "items", { get: function () { return this._getOption('items'); }, set: function (value) { this._setOption('items', value); }, enumerable: true, configurable: true }); Object.defineProperty(DxTagBoxComponent.prototype, "elementAttr", { get: function () { return this._getOption('elementAttr'); }, set: function (value) { this._setOption('elementAttr', value); }, enumerable: true, configurable: true }); Object.defineProperty(DxTagBoxComponent.prototype, "height", { get: function () { return this._getOption('height'); }, set: function (value) { this._setOption('height', value); }, enumerable: true, configurable: true }); Object.defineProperty(DxTagBoxComponent.prototype, "rtlEnabled", { get: function () { return this._getOption('rtlEnabled'); }, set: function (value) { this._setOption('rtlEnabled', value); }, enumerable: true, configurable: true }); Object.defineProperty(DxTagBoxComponent.prototype, "width", { get: function () { return this._getOption('width'); }, set: function (value) { this._setOption('width', value); }, enumerable: true, configurable: true }); Object.defineProperty(DxTagBoxComponent.prototype, "accessKey", { get: function () { return this._getOption('accessKey'); }, set: function (value) { this._setOption('accessKey', value); }, enumerable: true, configurable: true }); Object.defineProperty(DxTagBoxComponent.prototype, "activeStateEnabled", { get: function () { return this._getOption('activeStateEnabled'); }, set: function (value) { this._setOption('activeStateEnabled', value); }, enumerable: true, configurable: true }); Object.defineProperty(DxTagBoxComponent.prototype, "disabled", { get: function () { return this._getOption('disabled'); }, set: function (value) { this._setOption('disabled', value); }, enumerable: true, configurable: true }); Object.defineProperty(DxTagBoxComponent.prototype, "focusStateEnabled", { get: function () { return this._getOption('focusStateEnabled'); }, set: function (value) { this._setOption('focusStateEnabled', value); }, enumerable: true, configurable: true }); Object.defineProperty(DxTagBoxComponent.prototype, "hint", { get: function () { return this._getOption('hint'); }, set: function (value) { this._setOption('hint', value); }, enumerable: true, configurable: true }); Object.defineProperty(DxTagBoxComponent.prototype, "hoverStateEnabled", { get: function () { return this._getOption('hoverStateEnabled'); }, set: function (value) { this._setOption('hoverStateEnabled', value); }, enumerable: true, configurable: true }); Object.defineProperty(DxTagBoxComponent.prototype, "tabIndex", { get: function () { return this._getOption('tabIndex'); }, set: function (value) { this._setOption('tabIndex', value); }, enumerable: true, configurable: true }); Object.defineProperty(DxTagBoxComponent.prototype, "visible", { get: function () { return this._getOption('visible'); }, set: function (value) { this._setOption('visible', value); }, enumerable: true, configurable: true }); Object.defineProperty(DxTagBoxComponent.prototype, "isValid", { get: function () { return this._getOption('isValid'); }, set: function (value) { this._setOption('isValid', value); }, enumerable: true, configurable: true }); Object.defineProperty(DxTagBoxComponent.prototype, "name", { get: function () { return this._getOption('name'); }, set: function (value) { this._setOption('name', value); }, enumerable: true, configurable: true }); Object.defineProperty(DxTagBoxComponent.prototype, "readOnly", { get: function () { return this._getOption('readOnly'); }, set: function (value) { this._setOption('readOnly', value); }, enumerable: true, configurable: true }); Object.defineProperty(DxTagBoxComponent.prototype, "validationError", { get: function () { return this._getOption('validationError'); }, set: function (value) { this._setOption('validationError', value); }, enumerable: true, configurable: true }); Object.defineProperty(DxTagBoxComponent.prototype, "validationMessageMode", { get: function () { return this._getOption('validationMessageMode'); }, set: function (value) { this._setOption('validationMessageMode', value); }, enumerable: true, configurable: true }); Object.defineProperty(DxTagBoxComponent.prototype, "value", { get: function () { return this._getOption('value'); }, set: function (value) { this._setOption('value', value); }, enumerable: true, configurable: true }); Object.defineProperty(DxTagBoxComponent.prototype, "attr", { get: function () { return this._getOption('attr'); }, set: function (value) { this._setOption('attr', value); }, enumerable: true, configurable: true }); Object.defineProperty(DxTagBoxComponent.prototype, "inputAttr", { get: function () { return this._getOption('inputAttr'); }, set: function (value) { this._setOption('inputAttr', value); }, enumerable: true, configurable: true }); Object.defineProperty(DxTagBoxComponent.prototype, "placeholder", { get: function () { return this._getOption('placeholder'); }, set: function (value) { this._setOption('placeholder', value); }, enumerable: true, configurable: true }); Object.defineProperty(DxTagBoxComponent.prototype, "showClearButton", { get: function () { return this._getOption('showClearButton'); }, set: function (value) { this._setOption('showClearButton', value); }, enumerable: true, configurable: true }); Object.defineProperty(DxTagBoxComponent.prototype, "text", { get: function () { return this._getOption('text'); }, set: function (value) { this._setOption('text', value); }, enumerable: true, configurable: true }); Object.defineProperty(DxTagBoxComponent.prototype, "acceptCustomValue", { get: function () { return this._getOption('acceptCustomValue'); }, set: function (value) { this._setOption('acceptCustomValue', value); }, enumerable: true, configurable: true }); Object.defineProperty(DxTagBoxComponent.prototype, "applyValueMode", { get: function () { return this._getOption('applyValueMode'); }, set: function (value) { this._setOption('applyValueMode', value); }, enumerable: true, configurable: true }); Object.defineProperty(DxTagBoxComponent.prototype, "deferRendering", { get: function () { return this._getOption('deferRendering'); }, set: function (value) { this._setOption('deferRendering', value); }, enumerable: true, configurable: true }); Object.defineProperty(DxTagBoxComponent.prototype, "fieldEditEnabled", { get: function () { return this._getOption('fieldEditEnabled'); }, set: function (value) { this._setOption('fieldEditEnabled', value); }, enumerable: true, configurable: true }); Object.defineProperty(DxTagBoxComponent.prototype, "opened", { get: function () { return this._getOption('opened'); }, set: function (value) { this._setOption('opened', value); }, enumerable: true, configurable: true }); Object.defineProperty(DxTagBoxComponent.prototype, "fieldTemplate", { get: function () { return this._getOption('fieldTemplate'); }, set: function (value) { this._setOption('fieldTemplate', value); }, enumerable: true, configurable: true }); Object.defineProperty(DxTagBoxComponent.prototype, "minSearchLength", { get: function () { return this._getOption('minSearchLength'); }, set: function (value) { this._setOption('minSearchLength', value); }, enumerable: true, configurable: true }); Object.defineProperty(DxTagBoxComponent.prototype, "noDataText", { get: function () { return this._getOption('noDataText'); }, set: function (value) { this._setOption('noDataText', value); }, enumerable: true, configurable: true }); Object.defineProperty(DxTagBoxComponent.prototype, "pagingEnabled", { get: function () { return this._getOption('pagingEnabled'); }, set: function (value) { this._setOption('pagingEnabled', value); }, enumerable: true, configurable: true }); Object.defineProperty(DxTagBoxComponent.prototype, "searchEnabled", { get: function () { return this._getOption('searchEnabled'); }, set: function (value) { this._setOption('searchEnabled', value); }, enumerable: true, configurable: true }); Object.defineProperty(DxTagBoxComponent.prototype, "searchExpr", { get: function () { return this._getOption('searchExpr'); }, set: function (value) { this._setOption('searchExpr', value); }, enumerable: true, configurable: true }); Object.defineProperty(DxTagBoxComponent.prototype, "searchMode", { get: function () { return this._getOption('searchMode'); }, set: function (value) { this._setOption('searchMode', value); }, enumerable: true, configurable: true }); Object.defineProperty(DxTagBoxComponent.prototype, "searchTimeout", { get: function () { return this._getOption('searchTimeout'); }, set: function (value) { this._setOption('searchTimeout', value); }, enumerable: true, configurable: true }); Object.defineProperty(DxTagBoxComponent.prototype, "showDataBeforeSearch", { get: function () { return this._getOption('showDataBeforeSearch'); }, set: function (value) { this._setOption('showDataBeforeSearch', value); }, enumerable: true, configurable: true }); Object.defineProperty(DxTagBoxComponent.prototype, "showSelectionControls", { get: function () { return this._getOption('showSelectionControls'); }, set: function (value) { this._setOption('showSelectionControls', value); }, enumerable: true, configurable: true }); Object.defineProperty(DxTagBoxComponent.prototype, "hideSelectedItems", { get: function () { return this._getOption('hideSelectedItems'); }, set: function (value) { this._setOption('hideSelectedItems', value); }, enumerable: true, configurable: true }); Object.defineProperty(DxTagBoxComponent.prototype, "multiline", { get: function () { return this._getOption('multiline'); }, set: function (value) { this._setOption('multiline', value); }, enumerable: true, configurable: true }); Object.defineProperty(DxTagBoxComponent.prototype, "selectAllMode", { get: function () { return this._getOption('selectAllMode'); }, set: function (value) { this._setOption('selectAllMode', value); }, enumerable: true, configurable: true }); Object.defineProperty(DxTagBoxComponent.prototype, "selectedItems", { get: function () { return this._getOption('selectedItems'); }, set: function (value) { this._setOption('selectedItems', value); }, enumerable: true, configurable: true }); Object.defineProperty(DxTagBoxComponent.prototype, "tagTemplate", { get: function () { return this._getOption('tagTemplate'); }, set: function (value) { this._setOption('tagTemplate', value); }, enumerable: true, configurable: true }); Object.defineProperty(DxTagBoxComponent.prototype, "values", { get: function () { return this._getOption('values'); }, set: function (value) { this._setOption('values', value); }, enumerable: true, configurable: true }); DxTagBoxComponent.prototype.change = function (_) { }; Object.defineProperty(DxTagBoxComponent.prototype, "itemsChildren", { get: function () { return this._getOption('items'); }, set: function (value) { this.setChildren('items', value); }, enumerable: true, configurable: true }); DxTagBoxComponent.prototype._createInstance = function (element, options) { var widget = new tag_box_1.default(element, options); if (this.validator) { this.validator.createInstance(element); } return widget; }; DxTagBoxComponent.prototype.writeValue = function (value) { this.value = value; }; DxTagBoxComponent.prototype.setDisabledState = function (isDisabled) { this.disabled = isDisabled; }; DxTagBoxComponent.prototype.registerOnChange = function (fn) { this.change = fn; }; DxTagBoxComponent.prototype.registerOnTouched = function (fn) { this.touched = fn; }; DxTagBoxComponent.prototype.ngOnDestroy = function () { this._destroyWidget(); }; DxTagBoxComponent.prototype.ngOnChanges = function (changes) { this._idh.setup('dataSource', changes); this._idh.setup('items', changes); this._idh.setup('value', changes); this._idh.setup('searchExpr', changes); this._idh.setup('selectedItems', changes); }; DxTagBoxComponent.prototype.ngDoCheck = function () { this._idh.doCheck('dataSource'); this._idh.doCheck('items'); this._idh.doCheck('value'); this._idh.doCheck('searchExpr'); this._idh.doCheck('selectedItems'); this._watcherHelper.checkWatchers(); }; DxTagBoxComponent.prototype.ngAfterViewInit = function () { this._createWidget(this.element.nativeElement); }; DxTagBoxComponent.decorators = [ { type: core_1.Component, args: [{ selector: 'dx-tag-box', template: '', providers: [ template_host_1.DxTemplateHost, watcher_helper_1.WatcherHelper, CUSTOM_VALUE_ACCESSOR_PROVIDER, nested_option_1.NestedOptionHost, iterable_differ_helper_1.IterableDifferHelper ] },] }, ]; DxTagBoxComponent.ctorParameters = function () { return [ { type: core_1.ElementRef, }, { type: core_1.NgZone, }, { type: template_host_1.DxTemplateHost, }, { type: watcher_helper_1.WatcherHelper, }, { type: iterable_differ_helper_1.IterableDifferHelper, }, { type: nested_option_1.NestedOptionHost, }, ]; }; DxTagBoxComponent.propDecorators = { 'validator': [{ type: core_1.ContentChild, args: [validator_1.DxValidatorComponent,] },], 'dataSource': [{ type: core_1.Input },], 'displayExpr': [{ type: core_1.Input },], 'itemTemplate': [{ type: core_1.Input },], 'valueExpr': [{ type: core_1.Input },], 'items': [{ type: core_1.Input },], 'elementAttr': [{ type: core_1.Input },], 'height': [{ type: core_1.Input },], 'rtlEnabled': [{ type: core_1.Input },], 'width': [{ type: core_1.Input },], 'accessKey': [{ type: core_1.Input },], 'activeStateEnabled': [{ type: core_1.Input },], 'disabled': [{ type: core_1.Input },], 'focusStateEnabled': [{ type: core_1.Input },], 'hint': [{ type: core_1.Input },], 'hoverStateEnabled': [{ type: core_1.Input },], 'tabIndex': [{ type: core_1.Input },], 'visible': [{ type: core_1.Input },], 'isValid': [{ type: core_1.Input },], 'name': [{ type: core_1.Input },], 'readOnly': [{ type: core_1.Input },], 'validationError': [{ type: core_1.Input },], 'validationMessageMode': [{ type: core_1.Input },], 'value': [{ type: core_1.Input },], 'attr': [{ type: core_1.Input },], 'inputAttr': [{ type: core_1.Input },], 'placeholder': [{ type: core_1.Input },], 'showClearButton': [{ type: core_1.Input },], 'text': [{ type: core_1.Input },], 'acceptCustomValue': [{ type: core_1.Input },], 'applyValueMode': [{ type: core_1.Input },], 'deferRendering': [{ type: core_1.Input },], 'fieldEditEnabled': [{ type: core_1.Input },], 'opened': [{ type: core_1.Input },], 'fieldTemplate': [{ type: core_1.Input },], 'minSearchLength': [{ type: core_1.Input },], 'noDataText': [{ type: core_1.Input },], 'pagingEnabled': [{ type: core_1.Input },], 'searchEnabled': [{ type: core_1.Input },], 'searchExpr': [{ type: core_1.Input },], 'searchMode': [{ type: core_1.Input },], 'searchTimeout': [{ type: core_1.Input },], 'showDataBeforeSearch': [{ type: core_1.Input },], 'showSelectionControls': [{ type: core_1.Input },], 'hideSelectedItems': [{ type: core_1.Input },], 'multiline': [{ type: core_1.Input },], 'selectAllMode': [{ type: core_1.Input },], 'selectedItems': [{ type: core_1.Input },], 'tagTemplate': [{ type: core_1.Input },], 'values': [{ type: core_1.Input },], 'onDisposing': [{ type: core_1.Output },], 'onInitialized': [{ type: core_1.Output },], 'onOptionChanged': [{ type: core_1.Output },], 'onFocusIn': [{ type: core_1.Output },], 'onFocusOut': [{ type: core_1.Output },], 'onValueChanged': [{ type: core_1.Output },], 'onChange': [{ type: core_1.Output },], 'onEnterKey': [{ type: core_1.Output },], 'onInput': [{ type: core_1.Output },], 'onKeyDown': [{ type: core_1.Output },], 'onKeyPress': [{ type: core_1.Output },], 'onKeyUp': [{ type: core_1.Output },], 'onClosed': [{ type: core_1.Output },], 'onOpened': [{ type: core_1.Output },], 'onContentReady': [{ type: core_1.Output },], 'onItemClick': [{ type: core_1.Output },], 'onSelectionChanged': [{ type: core_1.Output },], 'onCustomItemCreating': [{ type: core_1.Output },], 'onSelectAllValueChanged': [{ type: core_1.Output },], 'dataSourceChange': [{ type: core_1.Output },], 'displayExprChange': [{ type: core_1.Output },], 'itemTemplateChange': [{ type: core_1.Output },], 'valueExprChange': [{ type: core_1.Output },], 'itemsChange': [{ type: core_1.Output },], 'elementAttrChange': [{ type: core_1.Output },], 'heightChange': [{ type: core_1.Output },], 'rtlEnabledChange': [{ type: core_1.Output },], 'widthChange': [{ type: core_1.Output },], 'accessKeyChange': [{ type: core_1.Output },], 'activeStateEnabledChange': [{ type: core_1.Output },], 'disabledChange': [{ type: core_1.Output },], 'focusStateEnabledChange': [{ type: core_1.Output },], 'hintChange': [{ type: core_1.Output },], 'hoverStateEnabledChange': [{ type: core_1.Output },], 'tabIndexChange': [{ type: core_1.Output },], 'visibleChange': [{ type: core_1.Output },], 'isValidChange': [{ type: core_1.Output },], 'nameChange': [{ type: core_1.Output },], 'readOnlyChange': [{ type: core_1.Output },], 'validationErrorChange': [{ type: core_1.Output },], 'validationMessageModeChange': [{ type: core_1.Output },], 'valueChange': [{ type: core_1.Output },], 'attrChange': [{ type: core_1.Output },], 'inputAttrChange': [{ type: core_1.Output },], 'placeholderChange': [{ type: core_1.Output },], 'showClearButtonChange': [{ type: core_1.Output },], 'textChange': [{ type: core_1.Output },], 'acceptCustomValueChange': [{ type: core_1.Output },], 'applyValueModeChange': [{ type: core_1.Output },], 'deferRenderingChange': [{ type: core_1.Output },], 'fieldEditEnabledChange': [{ type: core_1.Output },], 'openedChange': [{ type: core_1.Output },], 'fieldTemplateChange': [{ type: core_1.Output },], 'minSearchLengthChange': [{ type: core_1.Output },], 'noDataTextChange': [{ type: core_1.Output },], 'pagingEnabledChange': [{ type: core_1.Output },], 'searchEnabledChange': [{ type: core_1.Output },], 'searchExprChange': [{ type: core_1.Output },], 'searchModeChange': [{ type: core_1.Output },], 'searchTimeoutChange': [{ type: core_1.Output },], 'showDataBeforeSearchChange': [{ type: core_1.Output },], 'showSelectionControlsChange': [{ type: core_1.Output },], 'hideSelectedItemsChange': [{ type: core_1.Output },], 'multilineChange': [{ type: core_1.Output },], 'selectAllModeChange': [{ type: core_1.Output },], 'selectedItemsChange': [{ type: core_1.Output },], 'tagTemplateChange': [{ type: core_1.Output },], 'valuesChange': [{ type: core_1.Output },], 'change': [{ type: core_1.HostListener, args: ['valueChange', ['$event'],] },], 'itemsChildren': [{ type: core_1.ContentChildren, args: [item_dxi_2.DxiItemComponent,] },], }; return DxTagBoxComponent; }(component_1.DxComponent)); exports.DxTagBoxComponent = DxTagBoxComponent; var DxTagBoxModule = (function () { function DxTagBoxModule() { } DxTagBoxModule.decorators = [ { type: core_1.NgModule, args: [{ imports: [ item_dxi_1.DxiItemModule, template_1.DxTemplateModule ], declarations: [ DxTagBoxComponent ], exports: [ DxTagBoxComponent, item_dxi_1.DxiItemModule, template_1.DxTemplateModule ], },] }, ]; DxTagBoxModule.ctorParameters = function () { return []; }; return DxTagBoxModule; }()); exports.DxTagBoxModule = DxTagBoxModule; //# sourceMappingURL=tag-box.js.map
/** * Native String.prototype.trimStart method with fallback to String.prototype.trimLeft * Edge doesn't support the first one * @param {string} string - input string * @returns {string} trimmed output */ export default function trimStart(string) { return (string.trimStart || string.trimLeft).apply(string) }
'use strict'; var url = require('url'); var Tag = require('./TagService'); module.exports.tagGET = function tagGET (req, res, next) { Tag.tagGET(req.swagger.params, res, next); }; module.exports.tagIdDELETE = function tagIdDELETE (req, res, next) { Tag.tagIdDELETE(req.swagger.params, res, next); }; module.exports.tagIdPATCH = function tagIdPATCH (req, res, next) { Tag.tagIdPATCH(req.swagger.params, res, next); }; module.exports.tagPOST = function tagPOST (req, res, next) { Tag.tagPOST(req.swagger.params, res, next); };
var searchData= [ ['parameters',['Parameters',['../class_excimontec_1_1_parameters.html',1,'Excimontec']]], ['parameters_5flattice',['Parameters_Lattice',['../class_k_m_c___lattice_1_1_parameters___lattice.html',1,'KMC_Lattice']]], ['parameters_5fsimulation',['Parameters_Simulation',['../class_k_m_c___lattice_1_1_parameters___simulation.html',1,'KMC_Lattice']]], ['polaron',['Polaron',['../class_excimontec_1_1_polaron.html',1,'Excimontec']]], ['polaron_5fannihilation',['Polaron_Annihilation',['../class_excimontec_1_1_exciton_1_1_polaron___annihilation.html',1,'Excimontec::Exciton']]] ];
(function () { 'use strict'; // Roles controller angular .module('roles') .controller('RolesController', RolesController); RolesController.$inject = ['$scope', '$state', '$window', 'Authentication', 'roleResolve']; function RolesController ($scope, $state, $window, Authentication, role) { var vm = this; vm.authentication = Authentication; vm.role = role; vm.error = null; vm.form = {}; vm.remove = remove; vm.save = save; // Remove existing Role function remove() { if ($window.confirm('Are you sure you want to delete?')) { vm.role.$remove($state.go('roles.list')); } } // Save Role function save(isValid) { if (!isValid) { $scope.$broadcast('show-errors-check-validity', 'vm.form.roleForm'); return false; } // TODO: move create/update logic to service if (vm.role._id) { vm.role.$update(successCallback, errorCallback); } else { vm.role.$save(successCallback, errorCallback); } function successCallback(res) { $state.go('roles.view', { roleId: res._id }); } function errorCallback(res) { vm.error = res.data.message; } } } }());
uiFormModule.directive('uiFormInputText', ['$compile', 'uiFormService', 'uiFormValidationService', function($compile, uiFormService, uiFormValidationService){ return { restrict: 'E', transclude: false, replace: true, require: '^form', scope: { elementName: '@?', label: '=?', config: '=?', flush: '=?' }, template: '<div class="form-group"></div>', link: function(scope, element, attrs, formController) { if ('undefined' == typeof scope.config) { scope.config = {}; } if ('undefined' == typeof scope.config.type) { scope.config.type = 'text'; } if ('undefined' == typeof scope.config.isRequired) { scope.config.isRequired = false; } if ('undefined' == typeof scope.elementName) { scope.elementName = 'elementName_' + Math.random(new Date().getMilliseconds()); } if ('undefined' == typeof scope.flush) { scope.flush = false; } if (false == scope.flush && 'undefined' != typeof scope.label) { var labelElement = uiFormService.getLabel({label: scope.label, isRequired: scope.config.isRequired}); element.append(labelElement); } var inputEditModeElement = uiFormService.getText({ name: scope.elementName, type: scope.config.type, placeholder: scope.config.placeholder, ngModel: attrs.ngModel}); inputEditModeElement = uiFormValidationService.setValidationRules(inputEditModeElement, scope.config); inputEditModeElement = uiFormValidationService.setErrorPopover(inputEditModeElement); var inputViewModeElement = uiFormService.getTextViewMode(attrs.ngModel); var inputWrapperElement = uiFormService.getWrapperElement({type: scope.config.type, layout: scope.config.layout}); inputWrapperElement.appendChild(inputEditModeElement); inputWrapperElement.appendChild(inputViewModeElement); var elementGridSize = ' col-sm-8'; if (true == scope.flush || 'undefined' == typeof scope.label) { elementGridSize = ' col-sm-12'; } inputWrapperElement.setAttribute('class', inputWrapperElement.getAttribute('class') + elementGridSize); element.append(inputWrapperElement); var ngElement = angular.element(inputEditModeElement); scope.toggleErrorState = function() { if (formController[scope.elementName].$dirty && formController[scope.elementName].$invalid) { element.addClass('has-error'); } else { element.removeClass('has-error'); } } ngElement.bind('keyup', function() { scope.toggleErrorState(); }); $compile(element.contents())(scope.$parent); } }; }]);
// Game Format Style { "id": Parse.Object.Game.id "title": String, "owner": Parse.User.id, "status": String, // "preGame", "active", "completed" "players": [ Parse.User.id ], "mapId": Parse.Object.Map.id, "settings": Object({ turnLength: Number, // time for each player to submit orders supplyToWin: Number, // ranges from 50% to 100% of map's supply centers countries: String, // "random", "choose" preGameBuild: Boolean, // true means players choose which units to build, false means use map DefaultUnits fogOfWar: Boolean, }) "countriesToPlayers": [ Object({ country: String, // Matches country.name in the map player: Parse.User.id }) ], "currentMovePhase": Object({ // This object can be used to auto-generate the key for the turnPhases object year: Number, season: String, // "spring", "fall" phase: String, // "order", "retreat", "build" }), "armies": [ Object({ armyId: Number, player: Parse.User.id, location: Number, type: String, // "army", "navy" created: String, // Representation of turn phase destroyed: String || null, // Representation of turn phase }) ] "turnPhases": [ { player: Parse.User.id, phase: String, // Representation of turn phase spaces: [Number], orders: [Object({ orderId: Number, // Used to reference orders to provide more detailed feedback armyId: Number, type: String, // "move", "supportMove", "hold", "supportHold", "convoy", "retreat", "build", "destroy" at: Number, from: Number, to: Number, result: Object({ code: String, // "success", "blocked", with room for more codes in the future blockedBy: [Number] // Array of other orderIds that caused this order to fail }) })], }, "..." ] }
//Ce dialog est destiné à fonctionner avec tiny-mce //il ne recoit pas en input un conceptual-image, ni un concrete-image //il recoit l'url de l'image et fait un appel à l'api pour obtenir l'information nécessaire //en ce sens, il devrait peut-être être renommé (on pourrait éventullement avoir un vrai concrete-image-dialog) import ko from 'knockout'; import $ from 'jquery'; import ImageDialogBaseViewModel from '../image-dialog-ui-base'; import ContentDialogViewModel from 'content-dialog-base-viewmodel'; import koMappingUtilities from 'koco-mapping-utilities'; import emitter from 'koco-signal-emitter'; import i18n from 'i18next'; var defaultContentTypeId = '20'; var defaultItem = { id: null, alt: '', title: '', legend: '', imageCredits: '', pressAgency: '', imageCollection: '', concreteImages: [], contentTypeId: defaultContentTypeId }; var ConcreteImageDialogViewModel = function(settings /*, componentInfo*/ ) { var self = this; self.params = self.getParams(settings); self.api = self.params.api; self.i18n = i18n; var contentDialogViewModelParams = { dialogTitle: 'Images', originalItem: ko.observable(), defaultItem: defaultItem, close: settings.close, isSearchable: true, api: self.api, }; self.translated = { closeLabel: self.i18n.t('koco-image-dialogs.dialog-cancel'), saveLabel: self.i18n.t('koco-image-dialogs.dialog-save'), altLabel: self.i18n.t('koco-image-dialogs.concrete-dialog-edit-label-alt'), legendLabel: self.i18n.t('koco-image-dialogs.concrete-dialog-edit-label-legend'), creditsLabel: self.i18n.t('koco-image-dialogs.concrete-dialog-edit-label-credits'), agencyLabel: self.i18n.t('koco-image-dialogs.concrete-dialog-edit-label-agency'), alignmentLabel: self.i18n.t('koco-image-dialogs.concrete-dialog-edit-label-alignment'), leftLabel: self.i18n.t('koco-image-dialogs.concrete-dialog-edit-label-left'), centreLabel: self.i18n.t('koco-image-dialogs.concrete-dialog-edit-label-center'), rightLabel: self.i18n.t('koco-image-dialogs.concrete-dialog-edit-label-right') } ContentDialogViewModel.call(self, contentDialogViewModelParams); self.canDeleteImage = ko.pureComputed(self.canDeleteImage.bind(self)); self.koDisposer.add(self.canDeleteImage); var align = 'left'; if (self.params && self.params.align) { align = self.params.align; } self.align = ko.observable(align); self.imageForLineups = ko.observable(false); self.selectedConcreteImage = ko.observable(); self.isCloudinary = ko.pureComputed(self.getIsCloudinary.bind(self)); self.koDisposer.add(self.isCloudinary); self.activate(); }; ConcreteImageDialogViewModel.prototype = Object.create(ImageDialogBaseViewModel.prototype); ConcreteImageDialogViewModel.prototype.constructor = ConcreteImageDialogViewModel; ConcreteImageDialogViewModel.prototype.start = function() { var self = this; var concreteImageUrl = ko.unwrap(self.params.concreteImageUrl); if (concreteImageUrl) { return self.api.fetch(`images/selected?url=${concreteImageUrl}`) .then(conceptualImageWithSelectedImage => { if (conceptualImageWithSelectedImage && conceptualImageWithSelectedImage.conceptualImage) { var originalItem = conceptualImageWithSelectedImage.conceptualImage; if (self.params.alt) { originalItem.alt = self.params.alt; } if (self.params.legend) { originalItem.legend = self.params.legend; } if (self.params.pressAgency) { originalItem.pressAgency = self.params.pressAgency; } if (self.params.imageCredits) { originalItem.imageCredits = self.params.imageCredits; } self.selectedConcreteImage(conceptualImageWithSelectedImage.selectedImage); self.originalItem(originalItem); self.selectItem(originalItem); } else { self.selectItem(null); } }); } self.selectItem(null); return Promise.resolve(); }; ConcreteImageDialogViewModel.prototype.selectItem = function(inputModel) { var self = this; self.selectedConcreteImage(null); ImageDialogBaseViewModel.prototype.selectItem.call(self, inputModel); }; ConcreteImageDialogViewModel.prototype.getSearchOnDisplay = function() { var self = this; return !ko.unwrap(self.params.concreteImageUrl); }; ConcreteImageDialogViewModel.prototype.toOutputModel = function() { var self = this; var conceptualImage = ContentDialogViewModel.prototype.toOutputModel.call(self); var concreteImage = koMappingUtilities.toJS(self.selectedConcreteImage); if (self.imageForLineups()) { emitter.dispatch('image:imageForLineups', [conceptualImage]); } return { conceptualImage: conceptualImage, concreteImage: concreteImage, align: self.align() }; }; ConcreteImageDialogViewModel.prototype.validate = function() { var self = this; if (!self.selectedConcreteImage()) { return self.i18n.t('koco-image-dialogs.concrete-image-dialog-select-image-format'); } ContentDialogViewModel.prototype.validate.call(self); }; export default { viewModel: { createViewModel: function(params, componentInfo) { return new ConcreteImageDialogViewModel(params, componentInfo); } }, template: template };
cordova.define('cordova/plugin_list', function(require, exports, module) { module.exports = [ { "file": "plugins/org.apache.cordova.device/www/device.js", "id": "org.apache.cordova.device.device", "clobbers": [ "device" ] }, { "file": "plugins/org.apache.cordova.network-information/www/network.js", "id": "org.apache.cordova.network-information.network", "clobbers": [ "navigator.connection", "navigator.network.connection" ] }, { "file": "plugins/org.apache.cordova.network-information/www/Connection.js", "id": "org.apache.cordova.network-information.Connection", "clobbers": [ "Connection" ] }, { "file": "plugins/org.apache.cordova.battery-status/www/battery.js", "id": "org.apache.cordova.battery-status.battery", "clobbers": [ "navigator.battery" ] }, { "file": "plugins/org.apache.cordova.dialogs/www/notification.js", "id": "org.apache.cordova.dialogs.notification", "merges": [ "navigator.notification" ] }, { "file": "plugins/org.apache.cordova.dialogs/www/android/notification.js", "id": "org.apache.cordova.dialogs.notification_android", "merges": [ "navigator.notification" ] }, { "file": "plugins/org.apache.cordova.vibration/www/vibration.js", "id": "org.apache.cordova.vibration.notification", "merges": [ "navigator.notification" ] }, { "file": "plugins/org.apache.cordova.splashscreen/www/splashscreen.js", "id": "org.apache.cordova.splashscreen.SplashScreen", "clobbers": [ "navigator.splashscreen" ] } ]; module.exports.metadata = // TOP OF METADATA { "org.apache.cordova.device": "0.2.11-dev", "org.apache.cordova.network-information": "0.2.11-dev", "org.apache.cordova.battery-status": "0.2.10-dev", "org.apache.cordova.dialogs": "0.2.9-dev", "org.apache.cordova.vibration": "0.3.10-dev", "org.apache.cordova.splashscreen": "0.3.2-dev" } // BOTTOM OF METADATA });
import "../../define/PullToRefresh.js"; import { defaultState, firstRender, ids, render, setState, state, template, } from "../../src/base/internal.js"; import { updateChildNodes } from "../../src/core/dom.js"; import { templateFrom } from "../../src/core/htmlLiterals.js"; import ReactiveElement from "../../src/core/ReactiveElement.js"; const texts = [ `Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed molestie molestie enim porta dapibus. Phasellus dolor quam, egestas eu viverra at, porttitor in diam. Donec risus tellus, accumsan eget ipsum sed, vestibulum blandit ante. Nullam rhoncus leo nec lobortis convallis. Donec posuere tellus a nibh dignissim, rhoncus viverra neque rutrum. Suspendisse rutrum at massa vitae venenatis. Suspendisse ut risus pellentesque lacus dictum aliquet. Cras a arcu id odio molestie imperdiet.`, `Pellentesque vitae eros ac nulla aliquam eleifend. Nunc ornare sollicitudin arcu id suscipit. Donec sed nisl libero. Nulla facilisi. Proin ornare feugiat molestie. Mauris velit mi, volutpat sit amet posuere quis, tristique et urna. Donec sit amet tellus magna. Aenean feugiat suscipit neque, ut porttitor diam auctor in. Sed faucibus finibus ipsum et pharetra. In hac habitasse platea dictumst. Cras facilisis justo eu lectus luctus, et interdum velit aliquet.`, `Aliquam vitae nulla efficitur turpis viverra placerat. Mauris fermentum tellus vel elementum aliquet. Integer vitae arcu et mi tristique lacinia. Cras placerat ultrices velit, id interdum ipsum commodo efficitur. Maecenas maximus odio a nisi dapibus, non dapibus nisl venenatis. Morbi tristique interdum leo, non tincidunt sapien efficitur ac. Nunc hendrerit turpis eget enim rhoncus sagittis. Aenean ac euismod magna. Phasellus et posuere nisi.`, `Ut volutpat eget massa id viverra. Maecenas accumsan euismod lorem, ac tristique urna efficitur non. Cras ornare ultricies arcu eu dignissim. Curabitur varius ante eget arcu accumsan, ut lacinia lacus dignissim. Ut pellentesque nibh efficitur venenatis gravida. Phasellus varius lacus non ultricies imperdiet. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos.`, `Efficitur nisl vel metus vestibulum, quis rutrum sapien rutrum. Suspendisse non mi varius, tincidunt mauris non, dignissim odio. Proin aliquam eleifend vestibulum. Mauris porttitor neque vel ullamcorper suscipit. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Vivamus accumsan luctus commodo. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Pellentesque quis enim vel tortor molestie rhoncus ac eu eros.`, `Praesent semper turpis vel tortor lacinia accumsan. Cras facilisis varius leo, a pretium odio ultrices eget. Nunc felis leo, aliquam sit amet lobortis rutrum, lobortis porttitor dolor. Sed nisl lacus, placerat ac enim id, rhoncus molestie turpis. Aenean nibh justo, ultrices quis mollis id, semper a risus. Cras magna ipsum, sollicitudin ut pretium sed, ultricies at ante. Integer ultricies quis elit in efficitur. Nam ac felis sollicitudin, tincidunt lorem sit amet, convallis ligula.`, `Nam imperdiet id purus quis rutrum. Phasellus laoreet efficitur lorem, eu commodo tortor pretium sit amet. Etiam volutpat ex ac ex luctus maximus. Praesent in pharetra nunc, sed rhoncus eros. Nulla facilisi. Aenean commodo volutpat feugiat. Pellentesque egestas nulla ut facilisis efficitur. Praesent maximus diam ut suscipit mattis. Aenean eros turpis, vestibulum id sem vitae, suscipit molestie justo.`, `Nulla iaculis varius arcu, et rhoncus est lobortis et. Etiam convallis, velit ut tincidunt molestie, enim erat malesuada nunc, et ornare tortor velit et mi. Quisque nec felis nulla. Mauris sit amet nisi quis sapien pharetra tempor. Aenean fringilla nulla urna, sed tristique ipsum vulputate a. Ut lacus diam, volutpat id tincidunt a, condimentum eu odio. Nam justo orci, consectetur vitae nulla a, sagittis vestibulum erat. Mauris fringilla urna est, sit amet rutrum nulla facilisis a.`, `Sed in nulla eu nisl consectetur semper. Aliquam tristique ligula eu maximus porttitor. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nullam tempor sed ex sit amet egestas. Curabitur sapien est, rhoncus dignissim pharetra sit amet, viverra id lectus. Vestibulum semper leo porta mi viverra consectetur. Quisque imperdiet lectus eget volutpat bibendum. Vivamus in nunc enim. Morbi fringilla est velit.`, `Proin malesuada pharetra sapien, vitae blandit ante ultricies vitae. Curabitur tempus urna malesuada mauris pharetra feugiat. Duis augue nunc, porta et lorem dictum, interdum pellentesque risus. Donec leo dolor, sollicitudin a nunc non, consectetur interdum risus. Pellentesque feugiat magna libero, quis sollicitudin leo elementum in. Etiam urna risus, congue id placerat eu, fringilla lobortis diam. Sed id auctor nisi. Nunc sed ex eu neque sodales pharetra sit amet non libero.`, ]; class RefreshAppDemo extends ReactiveElement { // @ts-ignore get [defaultState]() { const paragraphs = createParagraphs(texts); return Object.assign(super[defaultState], { paragraphs, }); } refresh() { if ("vibrate" in navigator) { navigator.vibrate(5); } setTimeout(async () => { /** @type {any} */ (this[ids].pullToRefresh).refreshing = false; /** @type {any} */ const refreshSound = this[ids].refreshSound; await playSound(refreshSound); // Rotate last paragraph to first place. const paragraphs = [...this[state].paragraphs]; const last = paragraphs.pop(); paragraphs.unshift(last); Object.freeze(paragraphs); this[setState]({ paragraphs }); }, 1000); } [render](/** @type {PlainObject} */ changed) { super[render](changed); if (this[firstRender]) { this[ids].pullToRefresh.addEventListener("refreshingchange", (event) => { /** @type {any} */ const cast = event; if (cast.detail.refreshing) { this.refresh(); } }); } if (changed.paragraphs) { updateChildNodes(this[ids].pullToRefresh, this[state].paragraphs); } } get [template]() { return templateFrom.html` <style> :host { display: block; } #pullToRefresh { padding: 1em; } p { border-top: 1px solid #ccc; margin: 1em 0; padding-top: 0.75em; } p:first-of-type { border-top: none; margin-top: 0; padding-top: 0; } p:last-of-type { margin-bottom: 0; } </style> <elix-pull-to-refresh id="pullToRefresh" exportparts="indicator, pull-indicator, refresh-header, refreshing-indicator"></elix-pull-to-refresh> <audio id="refreshSound" src="resources/pop.mp3"></audio> `; } } function createParagraphs(/** @type {string[]} */ texts) { const paragraphs = texts.map((text) => { const paragraph = document.createElement("p"); paragraph.textContent = text; return paragraph; }); Object.freeze(paragraphs); return paragraphs; } async function playSound(/** @type {HTMLAudioElement} */ sound) { if (sound && sound.play) { try { await sound.play(); } catch (e) { if (e.name === "NotAllowedError") { // Webkit doesn't want to play sounds } else { throw e; } } } } customElements.define("refresh-app-demo", RefreshAppDemo); export default RefreshAppDemo;
(function() { 'use strict'; angular .module('canvas') .factory('dpCanvasTool', dpCanvasTool); dpCanvasTool.$inject = ['$rootScope', 'dpPaperScope', 'dpCanvas', 'dpCanvasConfig', 'dpCanvasFrames']; /* @ngInject */ function dpCanvasTool($rootScope, dpPaperScope, dpCanvas, dpCanvasConfig, dpCanvasFrames) { var tool, me, objectsToSelect, selectionRect, refreshHandlesPressed , canvasMode = dpCanvasConfig.mode , handleState = dpCanvasConfig.handleState , _ = $rootScope , c = dpCanvas , p = dpPaperScope , f = dpCanvasFrames; me = { init : init, attachKeyEvents : attachKeyEvents, detachKeyEvents : detachKeyEvents, destroy : destroy }; return me; //////////////// function init() { tool = new p.Tool(); me.attachKeyEvents(); tool.onMouseDown = onMouseDown; tool.onMouseDrag = onMouseDrag; tool.onMouseUp = onMouseUp; } function attachKeyEvents() { tool.onKeyDown = onKeyDown; tool.onKeyUp = onKeyUp; } function detachKeyEvents() { tool.off('keydown'); tool.off('keyup'); } function onMouseDown() { if (c.selected.handle) return; selectionRect = new p.Path.Rectangle(); _.extend(selectionRect, { selected : true }); selectionRect.bringToFront(); c.mode = canvasMode.SELECT; c.refreshHandles(); objectsToSelect = []; } function onMouseDrag(evt) { if (!selectionRect) return; var x, y, width, height, rect, object, overlappingHandles; x = Math.min(evt.point.x, evt.downPoint.x); y = Math.min(evt.point.y, evt.downPoint.y); width = Math.abs(evt.point.x - evt.downPoint.x); height = Math.abs(evt.point.y - evt.downPoint.y); rect = new p.Rectangle(x, y, width, height); selectionRect.segments = [ rect.topLeft, rect.topRight, rect.bottomRight, rect.bottomLeft ]; c.setHandlesState(objectsToSelect, handleState.BLUR); objectsToSelect = []; overlappingHandles = c.handles.dpGetOverlapping(rect); for (var i = 0; i < overlappingHandles.length; i++) { object = c.getPathByHandle(overlappingHandles[i]).dpGetRootObjectOfJoinedGroup(); objectsToSelect = objectsToSelect.concat(object.dpGetObjects()); } objectsToSelect = _.uniq(objectsToSelect, 'id'); c.setHandlesState(objectsToSelect, handleState.SELECTED); } function onMouseUp() { if (c.selected.handle) { c.mode = canvasMode.SELECT; c.selected.handle = false; } else { if (selectionRect) { selectionRect.remove(); selectionRect = false; } if (!_.isEmpty(objectsToSelect)) { $rootScope.$apply(function() { c.selected.objects = _.uniq(c.selected.objects.concat(objectsToSelect), 'id'); }); } } c.applyActiveLayer(); } function onKeyDown(evt) { /* jshint maxcomplexity: false */ var dir, step , shiftKey = evt.event.shiftKey , ctrlKey = evt.event.ctrlKey; switch (evt.key) { case 'left': case 'right': $rootScope.$apply(function() { f.next(evt.key === 'left' ? -1 : 1); }); break; case 'c' : if (shiftKey) { $rootScope.$apply(function() { f.clipboardFrame = f.currentFrame; }); } else if (ctrlKey) { c.copySelected(); } else { c.cloneSelected(); } break; case 'v': if (shiftKey) { $rootScope.$apply(function() { f.pasteFrame(f.clipboardFrame); }); } else { c.centerSelected(); } break; case 'f': c.flipSelected(); break; case 'j': c.joinMode(); break; case 'g': c.changeSelectedOrder('bringToFront'); break; case 'h': c.changeSelectedOrder('sendToBack'); break; case 'delete': c.removeSelected(); break; case 'p': case 'o': if (c.selected.objects.length) { dir = evt.key === 'o' ? 'x' : 'y'; c.selected.objects[0].data.scale[dir] += shiftKey ? -1 : 1; c.setSelectedScale(c.selected.objects[0].data.scale[dir], dir); } break; case 'i': if (c.selected.objects.length) { step = shiftKey ? -1 : 1; c.setSelectedStrokeWidth(c.selected.objects[0].strokeWidth + step); } break; case 'y': case 'u': if (c.isPathSettingVisible('scale')) { dir = evt.key === 'y' ? 'x' : 'y'; c.selected.path.data.scale[dir] += shiftKey ? -1 : 1; c.setSelectedPathScale(c.selected.path.data.scale[dir], dir); } break; case 't': if (c.isPathSettingVisible('strokeWidth')) { step = shiftKey ? -1 : 1; c.selected.path.strokeWidth += step; } break; case 'space': evt.event.preventDefault(); if (c.selected.handle) { c.selected.handle.emit('mouseup'); } objectsToSelect = []; tool.emit('mouseup'); $rootScope.$apply(function() { f.newFrame(); }); break; case 'x' : if (shiftKey) { c.pasteSelected(); } break; case 'z' : if (shiftKey) { c.copySelected(); } break; case 'b': if (shiftKey) { $rootScope.$apply(function() { f.pasteFrame(f.frames[f.currentFrameIndex - 1]); }); } break; case 'w': $rootScope.$apply(function() { c.onionLayers.enabled = !c.onionLayers.enabled; }); break; case 'e': $rootScope.$apply(function() { c.showHandles = !c.showHandles; }); break; case 'r': $rootScope.$apply(function() { c.showAllPaths = !c.showAllPaths; }); break; case 'a': c.initPlaying(); break; case 'm': if (!refreshHandlesPressed) { c.refreshHandles(true); refreshHandlesPressed = true; } break; } } function onKeyUp(evt) { /* jshint maxcomplexity: false */ switch (evt.key) { case 'm': c.refreshHandles(); refreshHandlesPressed = false; break; } } function destroy() { tool.remove(); } } })();
/** * Author: Umayr Shahid <[email protected]>, * Created: 05:43, 09/03/15. */ 'use strict'; module.exports = require('./classes/uranus');
/** * Test sagas */ import expect from 'expect'; // import { take, call, put, select } from 'redux-saga/effects'; // import { defaultSaga } from '../sagas'; // const generator = defaultSaga(); describe('defaultSaga Saga', () => { expect(true).toEqual(true); });
// Require mongoose var mongoose = require('mongoose'); // Configure conenction URL (only needs to happen once per app) mongoose.connect('mongodb://admin:[email protected]:31203/node-workshop'); // Create a database schema for our Post object, which will describe both it's // data and it's behavior. var postSchema = mongoose.Schema({ title:String, content:String }); // Create a model object constructor that will have ODM functionality like .save()... var Post = mongoose.model('Post', postSchema); // Expose out model as the module interface module.exports = Post;
define(['jquery','datepicker'], function (jQuery) { /* Greek (el) initialisation for the jQuery UI date picker plugin. */ /* Written by Alex Cicovic (http://www.alexcicovic.com) */ jQuery(function($){ $.datepicker.regional['el'] = { closeText: 'Κλείσιμο', prevText: 'Προηγούμενος', nextText: 'Επόμενος', currentText: 'Τρέχων Μήνας', monthNames: ['Ιανουάριος','Φεβρουάριος','Μάρτιος','Απρίλιος','Μάιος','Ιούνιος', 'Ιούλιος','Αύγουστος','Σεπτέμβριος','Οκτώβριος','Νοέμβριος','Δεκέμβριος'], monthNamesShort: ['Ιαν','Φεβ','Μαρ','Απρ','Μαι','Ιουν', 'Ιουλ','Αυγ','Σεπ','Οκτ','Νοε','Δεκ'], dayNames: ['Κυριακή','Δευτέρα','Τρίτη','Τετάρτη','Πέμπτη','Παρασκευή','Σάββατο'], dayNamesShort: ['Κυρ','Δευ','Τρι','Τετ','Πεμ','Παρ','Σαβ'], dayNamesMin: ['Κυ','Δε','Τρ','Τε','Πε','Πα','Σα'], weekHeader: 'Εβδ', dateFormat: 'dd/mm/yy', firstDay: 1, isRTL: false, showMonthAfterYear: false, yearSuffix: ''}; $.datepicker.setDefaults($.datepicker.regional['el']); }); });
'use strict'; import React from 'react'; import LaddaButton from 'react-ladda'; import ReactTagsInput from 'react-tagsinput'; import {Grid, Row, Col} from 'react-bootstrap'; import {Map} from 'immutable'; import Component from '../components/component.react'; import Tag from '../tags/tag'; import {search as tagsActionSearch} from '../tags/actions'; class Form extends Component { constructor(props) { super(props); this.state = { selected: this.props.tags, completions: Map() }; } isValid() { return true; } getData() { return { firstName: this.refs.firstName.getDOMNode().value, lastName: this.refs.lastName.getDOMNode().value, phoneNumber: this.refs.phoneNumber.getDOMNode().value, email: this.refs.email.getDOMNode().value, note: this.refs.note.getDOMNode().value, tags: this.refs.tags.getTags().map(el => { const tag = el.props.tag; return (tag instanceof Tag) ? tag.label : tag; }) }; } // React Tags Input addTag(item) { this.refs.tags.addTag(item); this.setState({ completions: Map() }); } validate(item) { const tag = item.props.tag; if (typeof tag === 'string' || tag instanceof String) return tag.trim().length > 0; return true; } complete(value) { if (!value || value === '') { this.setState({ completions: Map() }); return; } tagsActionSearch(value).then(() => { const { tagsSearch } = this.props; this.setState({ completions: tagsSearch }); }); } transform(item) { return ( <span tag={item}> {(item instanceof Tag) ? item.label : item} </span> ); } renderTag(key, element, removeTag) { return ( <span key={key} className="react-tagsinput-tag"> {element} {(() => { if (!removeTag) return null; return <a onClick={removeTag} className="react-tagsinput-remove" />; })()} </span> ); } // Render render() { let tags = []; if (this.props.data.tags) tags = this.props.data.tags.map(item => this.transform(item)); return ( <form onSubmit={e => this.props.onSubmit(e)}> <Grid fluid={true}> <Row> <Col md={3}> <div className="form-group"> <label>First name</label> <input type="text" name="firstName" ref="firstName" className="form-control" placeholder="First name" disabled={this.props.pending} defaultValue={this.props.data.firstName} required /> </div> <div className="form-group"> <label>Last name</label> <input type="text" name="lastName" ref="lastName" className="form-control" placeholder="Last name" disabled={this.props.pending} defaultValue={this.props.data.lastName} required /> </div> <div className="form-group"> <label>Phone number</label> <input type="text" name="phoneNumber" ref="phoneNumber" className="form-control" placeholder="Phone number" disabled={this.props.pending} defaultValue={this.props.data.phoneNumber} required /> </div> <div className="form-group"> <label>Email</label> <input type="email" name="email" ref="email" className="form-control" placeholder="Email" disabled={this.props.pending} defaultValue={this.props.data.email} /> </div> </Col> <Col md={3}> <div className="form-group"> <label>Note</label> <textarea name="note" ref="note" rows={5} className="form-control" disabled={this.props.pending} defaultValue={this.props.data.note}> </textarea> </div> </Col> <Col md={2}> <div className="form-group"> <label>Tags</label> <ReactTagsInput ref="tags" placeholder="Add tag" addOnBlur={true} defaultValue={tags} validate={tag => this.validate(tag)} transform={tag => this.transform(tag)} renderTag={(...props) => this.renderTag(...props)} onChangeInput={tag => this.complete(tag)} /> <div className="react-tagsinput-completion"> {this.state.completions.toArray().map((item, index) => { return React.cloneElement( this.renderTag(index, this.transform(item)), { onClick: () => this.addTag(item) } ); })} </div> </div> </Col> </Row> <Row> <Col md={3}> <LaddaButton active={this.props.pending} style="expand-right"> <button>{this.props.submitTitle}</button> </LaddaButton> </Col> </Row> </Grid> </form> ); } } Form.defaultProps = { pending: false, submitTitle: 'Create', data: {}, tags: [] }; Form.propTypes = { tagsSearch: React.PropTypes.instanceOf(Map).isRequired }; export default Form;
var /** async flow lib */ $q = require('q'), /** http request library */ request = require('superagent'), /** server utilities / helper fns */ util = require('../lib/util'); /* ========================================================================== Request - Class for making HTTP requests ========================================================================== */ /** * helper class for building HTTP requests * @returns {Request} * @constructor */ var Request = function(options) { if (!(this instanceof Request)) { return new Request(options); } var defaults = { // method: String // url: String // headers: Object // params: Object // data: Object method: 'GET' }; this.config = util.extend(defaults, options || {}); return this; }; /** * sets a header * @param key {String} name of header * @param val {String} value to set */ Request.prototype.setHeader = function(key, val) { if (!this.config.headers) { this.config.headers = {}; } this.config.headers[key] = val; return this; }; /** * remove header from request * @param key * @returns {Request} */ Request.prototype.removeHeader = function(key) { if (!this.config.headers) { this.config.headers = {}; } delete this.config.headers[key]; return this; } /** * add query parameter to request * @param key {String} name of query parameter * @param val {String} value of query parameter * @returns {Request} */ Request.prototype.setParam = function(key, val) { if (!this.config.params) { this.config.params = {}; } this.config.params[key] = val; return this; }; /** * removes a query parameter from request * @param key {String} name of query parameter to remove * @returns {Request} */ Request.prototype.removeParam = function(key) { if (!this.config.params) { this.config.params = {}; } delete this.config.params[key]; return this; }; /** * sets the HTTP request method * @param method {String} * @returns {Request} */ Request.prototype.setMethod = function(method) { // TODO: method validation this.config.method = method; return this; }; /** * sets the url for the HTTP request * @param url {String} * @returns {Request} */ Request.prototype.setUrl = function(url) { this.config.url = url; return this; }; /** * sets the relative path for the HTTP request * @param path {String} * @returns {Request} */ Request.prototype.setPath = function(path) { this.config.path = path; return this; }; /** * returns the request object's configuration * @returns {Object} */ Request.prototype.getConfig = function() { return this.config; }; /** * adds data to the request body * @param data {Object} data to send * @param shouldOverwrite {Boolean} specifies that existing data should be replaced * @returns {Request} */ Request.prototype.send = function(data, shouldOverwrite) { if (shouldOverwrite) { this.config.data = data; } else { if (!this.config.data) { this.config.data = {}; } for (var k in data) { this.config.data[k] = data[k]; } } return this; }; /** * attaches a file to be sent * @param filePath {String} path to file to upload * @returns {Request} */ Request.prototype.attach = function(name, filePath) { if (!this.config.attachments) { this.config.attachments = {}; } this.config.attachments[name] = filePath; return this; }; /** * executes the request * @returns {promise|*|Q.promise} */ Request.prototype.execute = function() { var deferred = $q.defer(); if (this.config.proxy) { require('superagent-proxy')(request); } var method = (this.config.method || 'GET').toLowerCase(), r = request[method](this.config.url); if (this.config.proxy) { r.proxy(this.config.proxy); } if (this.config.headers) { for (var k in (this.config.headers || {})) { r.set(k, this.config.headers[k]); } } if (this.config.data) { r.send(this.config.data); } if (this.config.attachments) { for (var k in this.config.attachments) { r.attach(k, this.config.attachments[k]); } } // TODO: add query parameters to request r.end(function(error, response) { if (error) { return deferred.reject(error); } return deferred.resolve(response); }); return deferred.promise; }; /* ========================================================================== Initialization / Exports ========================================================================== */ module.exports = Request;
'use strict'; module.exports = function() { if (!this.paused) return; this.paused = false; if (this.stopedAtTimeStamp) { this.previousStepTimeStamp = Date.now() - (this.stopedAtTimeStamp - this.previousStepTimeStamp); this.stopedAtTimeStamp = null; } var speed = this.speed || 5000; var step = this.animationStep || (speed < 500 ? 20 : (speed < 5000 ? 50 : 100)); this.refreshIntervalId = setInterval(this.updateGradient.bind(this), step); }
/** * ConfigItem Model **/ angular.module('mNodeView').factory('ConfigItem', function(){ function ConfigItem(id, val){ /* {string} Config id (e.g. hdfs-site) */ this.id = id; /* {string} value */ this.val = val; /* {int} status Diff status 1.Equal (val equal) 2.New (left=yes; right=no) 3.Change (val dif) (4.Removed (left=no; right=yes)) Default: 0 */ this.status = 0; } /** * Sets the new status of this config item by comparing it * to the passed value. If passed value = undefined => status = new (2) **/ ConfigItem.prototype.setStatus = function(difVal){ if(difVal === undefined){ this.status = 2; }else if(difVal === this.val){ this.status = 1; } else if(difVal !== this.val){ this.status = 3; console.warn('difval: ' + difVal + ' val:'+this.val); } }; return ConfigItem; });
var chai = require('chai'); var expect = chai.expect; var config = require('../config'); var path = require('path'); var utils = require('../../dist/utils/parse'); describe('utils/parse', () => { describe('getFiles', () => { it('should retrieve a file list from a glob', () => { var glob = config.fixturePath('helpers/**/*'); return utils.getFiles(glob).then(fileList => { expect(Array.isArray(fileList)).to.be.true; fileList.forEach(filePath => { // Ham-fisted test that everything is a file, not a directory expect(filePath).to.contain('.'); }); }); }); it('should should respect glob options', () => { var glob = config.fixturePath('helpers/**/*'); return utils.getFiles(glob, { nodir: false }).then(fileList => { // This fileList should contain at least one directory expect(Array.isArray(fileList)).to.be.true; expect( fileList.filter(listEntry => { return path.extname(listEntry).length === 0; }) ).to.have.length.of.at.least(1); }); }); }); describe('isGlob', () => { it('should correctly identify valid glob patterns', () => { var goodGlobs = [ config.fixturePath('helpers/**/*'), ['foo', 'bar', 'baz'], [config.fixturePath('helpers/**/*'), 'foo'], 'just a string' ]; var badGlobs = [ 5, { foo: 'bar', baz: 'boof' }, ['foo', 'bar', 5], '', [] ]; expect(goodGlobs.every(glob => utils.isGlob(glob))).to.be.true; expect(badGlobs.every(glob => utils.isGlob(glob))).to.be.false; }); }); describe('matchParser', () => { it('should return a default parser function', () => { var parser = utils.matchParser('/foo/bar/baz.txt'); expect(parser).to.be.a('function'); }); it('should accept a default parser function', () => { var defaultParsers = { default: { pattern: /.*/, parseFn: (contents, filepath) => 'foo' } }; var parser = utils.matchParser('/foo/bar/baz.txt', defaultParsers); expect(parser).to.be.a('function'); expect(parser('ding')).to.equal('foo'); }); }); describe('parseField', () => { var opts; before(() => { return config.init(config.fixtureOpts).then(options => { opts = options; }); }); it('should run fields through fieldParsers from options', () => { opts.fieldParsers.notes = 'markdown'; var parsedField = utils.parseField('notes', 'these are some notes', opts); expect(parsedField).to.be.an('object'); expect(parsedField).to.contain.keys('contents', 'data'); expect(parsedField.contents) .to.be.a('string') .and.to.contain('<p>'); }); it('should heed `parser` property in passed object', () => { var fieldData = { parser: 'markdown', contents: 'A nobler thing tis' }; var parsedField = utils.parseField('ding', fieldData, opts); expect(parsedField).to.be.an('object'); expect(parsedField).to.contain.keys('contents', 'data'); expect(parsedField.contents) .to.be.a('string') .and.to.contain('<p>'); }); }); describe('readFiles', () => { var parsers = { default: { parseFn: (contents, filepath) => 'foo' } }; it('should read files from a glob', () => { var glob = config.fixturePath('helpers/*.js'); return utils.readFiles(glob).then(allFileData => { expect(allFileData).to.have.length.of(3); expect(allFileData[0]).to.have.keys('path', 'contents'); }); }); it('should run passed function over content', () => { var glob = config.fixturePath('helpers/*.js'); return utils.readFiles(glob, { parsers }).then(allFileData => { expect(allFileData).to.have.length.of(3); expect(allFileData[0].contents).to.equal('foo'); }); }); it('should respect passed glob options', () => { var glob = config.fixturePath('files/*'); // Include dotfiles return utils .readFiles(glob, { parsers: parsers, globOpts: { dot: true } }) .then(allFileData => { expect(allFileData).to.have.length(2); }); }); }); describe('readFileTree', () => { var parsers = { default: { parseFn: (contents, filepath) => 'foo' } }; it('should be able to build a tree object of arbitrary files', () => { var src = { glob: config.fixturePath('helpers/**/*.js'), basedir: config.fixturePath('helpers') }; return utils .readFileTree(src, 'test', { parsers: parsers }) .then(fileTree => { expect(fileTree) .to.be.an('object') .and.to.contain.keys('moar-helpers', 'toFraction', 'toJSON'); expect(fileTree['moar-helpers']) .to.be.an('object') .and.to.contain.keys('random', 'toFixed'); expect(fileTree.toFraction) .to.be.an('object') .and.to.contain.keys('contents', 'path'); expect(fileTree.toFraction.contents).to.equal('foo'); }); }); }); });
/*! * jQuery Upload File Plugin * version: 3.1.10 * @requires jQuery v1.5 or later & form plugin * Copyright (c) 2013 Ravishanker Kusuma * http://hayageek.com/ * * Adapt by Chien-Yueh Lee ([email protected]) */ (function ($) { //if($.fn.ajaxForm == undefined) { // $.getScript(("https:" == document.location.protocol ? "https://" : "http://") + "malsup.github.io/jquery.form.js"); //} var feature = {}; feature.fileapi = $("<input type='file'/>").get(0).files !== undefined; feature.formdata = window.FormData !== undefined; $.fn.uploadFile = function (options) { // This is the easiest way to have default options. var s = $.extend({ // These are the defaults. url: "", method: "POST", enctype: "multipart/form-data", returnType: null, allowDuplicates: true, duplicateStrict: false, allowedTypes: "*", //For list of acceptFiles // http://stackoverflow.com/questions/11832930/html-input-file-accept-attribute-file-type-csv acceptFiles: "*", fileName: "file", formData: {}, dynamicFormData: function () { return {}; }, maxFileSize: -1, maxFileCount: -1, multiple: true, dragDrop: true, autoSubmit: true, showCancel: true, showAbort: true, showDone: true, showDelete: true, showSettings: true, showError: true, showStatusAfterSuccess: true, showStatusAfterError: true, showFileCounter: true, fileCounterStyle: "). ", showProgress: false, nestedForms: true, showDownload: false, onLoad: function (obj) {}, onSelect: function (files) { return true; }, onSubmit: function (files, xhr) {}, onSuccess: function (files, response, xhr, pd) {}, onError: function (files, status, message, pd) {}, onCancel: function (files, pd) {}, downloadCallback: false, checkCallback: false, deleteCallback: false, settingsCallback: false, afterUploadAll: false, abortButtonClass: "ajax-file-upload-abort", cancelButtonClass: "ajax-file-upload-cancel", dragDropContainerClass: "ajax-upload-dragdrop", dragDropHoverClass: "state-hover", errorClass: "ajax-file-upload-error", uploadButtonClass: "ajax-file-upload", dragDropStr: "<span><b>Drag &amp; Drop Files</b></span>", abortStr: "Abort", cancelStr: "Cancel", deletelStr: "Delete", doneStr: "Done", settingsStr: "Settings", multiDragErrorStr: "Multiple File Drag &amp; Drop is not allowed.", extErrorStr: "is not allowed. Allowed extensions: ", duplicateErrorStr: "is not allowed. File already exists.", sizeErrorStr: "is not allowed. Allowed Max size: ", uploadErrorStr: "Upload is not allowed", maxFileCountErrorStr: " is not allowed. Maximum allowed files are:", downloadStr: "Download", customErrorKeyStr: "jquery-upload-file-error", showQueueDiv: false, statusBarWidth: 800, dragdropWidth: 800, showPreview: false, previewHeight: "auto", previewWidth: "100%", uploadFolder:"uploads/" }, options); this.fileCounter = 1; this.selectedFiles = 0; this.fCounter = 0; //failed uploads this.sCounter = 0; //success uploads this.tCounter = 0; //total uploads var formGroup = "ajax-file-upload-" + (new Date().getTime()); this.formGroup = formGroup; this.hide(); this.errorLog = $("<div></div>"); //Writing errors this.after(this.errorLog); this.responses = []; this.existingFileNames = []; if(!feature.formdata) //check drag drop enabled. { s.dragDrop = false; } if(!feature.formdata) { s.multiple = false; } var obj = this; var uploadLabel = $('<div>' + $(this).html() + '</div>'); $(uploadLabel).addClass(s.uploadButtonClass); // wait form ajax Form plugin and initialize (function checkAjaxFormLoaded() { if($.fn.ajaxForm) { if(s.dragDrop) { var dragDrop = $('<div class="' + s.dragDropContainerClass + '" style="vertical-align:top;"></div>').width(s.dragdropWidth); $(obj).before(dragDrop); $(dragDrop).append(uploadLabel); $(dragDrop).append($(s.dragDropStr)); setDragDropHandlers(obj, s, dragDrop); } else { $(obj).before(uploadLabel); } s.onLoad.call(this, obj); createCutomInputFile(obj, formGroup, s, uploadLabel); } else window.setTimeout(checkAjaxFormLoaded, 10); })(); this.startUpload = function () { $("." + this.formGroup).each(function (i, items) { if($(this).is('form')) $(this).submit(); }); } this.getFileCount = function () { return obj.selectedFiles; } this.stopUpload = function () { $("." + s.abortButtonClass).each(function (i, items) { if($(this).hasClass(obj.formGroup)) $(this).click(); }); } this.cancelAll = function () { $("." + s.cancelButtonClass).each(function (i, items) { if($(this).hasClass(obj.formGroup)) $(this).click(); }); } this.update = function (settings) { //update new settings s = $.extend(s, settings); } //This is for showing Old files to user. this.createProgress = function (filename) { var pd = new createProgressDiv(this, s); pd.progressDiv.show(); pd.progressbar.width('100%'); var fileNameStr = ""; if(s.showFileCounter) fileNameStr = obj.fileCounter + s.fileCounterStyle + filename; else fileNameStr = filename; pd.filename.html(fileNameStr); obj.fileCounter++; obj.selectedFiles++; if(s.showPreview) { pd.preview.attr('src',s.uploadFolder+filename); pd.preview.show(); } if(s.showDownload) { pd.download.show(); pd.download.click(function () { if(s.downloadCallback) s.downloadCallback.call(obj, [filename]); }); } pd.del.show(); if(s.showDone) { pd.done.show(); pd.done.click(function () { if(s.checkCallback) s.checkCallback.call(this, filename); }); } pd.del.click(function () { var dlg_confirm = confirm('Remove file `'+filename+"'?"); if(dlg_confirm == true) { pd.statusbar.hide().remove(); var arr = [filename]; if(s.deleteCallback) s.deleteCallback.call(this, arr, pd); obj.selectedFiles -= 1; updateFileCounter(s, obj); } }); } this.getResponses = function () { return this.responses; } var checking = false; function checkPendingUploads() { if(s.afterUploadAll && !checking) { checking = true; (function checkPending() { if(obj.sCounter != 0 && (obj.sCounter + obj.fCounter == obj.tCounter)) { s.afterUploadAll(obj); checking = false; } else window.setTimeout(checkPending, 100); })(); } } function setDragDropHandlers(obj, s, ddObj) { ddObj.on('dragenter', function (e) { e.stopPropagation(); e.preventDefault(); $(this).addClass(s.dragDropHoverClass); }); ddObj.on('dragover', function (e) { e.stopPropagation(); e.preventDefault(); var that = $(this); if (that.hasClass(s.dragDropContainerClass) && !that.hasClass(s.dragDropHoverClass)) { that.addClass(s.dragDropHoverClass); } }); ddObj.on('drop', function (e) { e.preventDefault(); $(this).removeClass(s.dragDropHoverClass); obj.errorLog.html(""); var files = e.originalEvent.dataTransfer.files; if(!s.multiple && files.length > 1) { if(s.showError) $("<div class='" + s.errorClass + "'>" + s.multiDragErrorStr + "</div>").appendTo(obj.errorLog); return; } if(s.onSelect(files) == false) return; serializeAndUploadFiles(s, obj, files); }); ddObj.on('dragleave', function (e) { $(this).removeClass(s.dragDropHoverClass); }); $(document).on('dragenter', function (e) { e.stopPropagation(); e.preventDefault(); }); $(document).on('dragover', function (e) { e.stopPropagation(); e.preventDefault(); var that = $(this); if (!that.hasClass(s.dragDropContainerClass)) { that.removeClass(s.dragDropHoverClass); } }); $(document).on('drop', function (e) { e.stopPropagation(); e.preventDefault(); $(this).removeClass(s.dragDropHoverClass); }); } function getSizeStr(size) { var sizeStr = ""; var sizeKB = size / 1024; if(parseInt(sizeKB) > 1024) { var sizeMB = sizeKB / 1024; sizeStr = sizeMB.toFixed(2) + " MB"; } else { sizeStr = sizeKB.toFixed(2) + " KB"; } return sizeStr; } function serializeData(extraData) { var serialized = []; if(jQuery.type(extraData) == "string") { serialized = extraData.split('&'); } else { serialized = $.param(extraData).split('&'); } var len = serialized.length; var result = []; var i, part; for(i = 0; i < len; i++) { serialized[i] = serialized[i].replace(/\+/g, ' '); part = serialized[i].split('='); result.push([decodeURIComponent(part[0]), decodeURIComponent(part[1])]); } return result; } function serializeAndUploadFiles(s, obj, files) { for(var i = 0; i < files.length; i++) { if(!isFileTypeAllowed(obj, s, files[i].name)) { if(s.showError) $("<div class='" + s.errorClass + "'><b>" + files[i].name + "</b> " + s.extErrorStr + s.allowedTypes + "</div>").appendTo(obj.errorLog); continue; } if(!s.allowDuplicates && isFileDuplicate(obj, files[i].name)) { if(s.showError) $("<div class='" + s.errorClass + "'><b>" + files[i].name + "</b> " + s.duplicateErrorStr + "</div>").appendTo(obj.errorLog); continue; } if(s.maxFileSize != -1 && files[i].size > s.maxFileSize) { if(s.showError) $("<div class='" + s.errorClass + "'><b>" + files[i].name + "</b> " + s.sizeErrorStr + getSizeStr(s.maxFileSize) + "</div>").appendTo(obj.errorLog); continue; } if(s.maxFileCount != -1 && obj.selectedFiles >= s.maxFileCount) { if(s.showError) $("<div class='" + s.errorClass + "'><b>" + files[i].name + "</b> " + s.maxFileCountErrorStr + s.maxFileCount + "</div>").appendTo(obj.errorLog); continue; } obj.selectedFiles++; obj.existingFileNames.push(files[i].name); var ts = s; var fd = new FormData(); var fileName = s.fileName.replace("[]", ""); fd.append(fileName, files[i]); var extraData = s.formData; if(extraData) { var sData = serializeData(extraData); for(var j = 0; j < sData.length; j++) { if(sData[j]) { fd.append(sData[j][0], sData[j][1]); } } } ts.fileData = fd; var pd = new createProgressDiv(obj, s); var fileNameStr = ""; if(s.showFileCounter) fileNameStr = obj.fileCounter + s.fileCounterStyle + files[i].name else fileNameStr = files[i].name; pd.filename.html(fileNameStr); var form = $("<form style='display:block; position:absolute;left: 150px;' class='" + obj.formGroup + "' method='" + s.method + "' action='" + s.url + "' enctype='" + s.enctype + "'></form>"); form.appendTo('body'); var fileArray = []; fileArray.push(files[i].name); ajaxFormSubmit(form, ts, pd, fileArray, obj, files[i]); obj.fileCounter++; } } function isFileTypeAllowed(obj, s, fileName) { var fileExtensions = s.allowedTypes.toLowerCase().split(","); var ext = fileName.split('.').pop().toLowerCase(); if(s.allowedTypes != "*" && jQuery.inArray(ext, fileExtensions) < 0) { return false; } return true; } function isFileDuplicate(obj, filename) { var duplicate = false; if (obj.existingFileNames.length) { for (var x=0; x<obj.existingFileNames.length; x++) { if (obj.existingFileNames[x] == filename || s.duplicateStrict && obj.existingFileNames[x].toLowerCase() == filename.toLowerCase() ) { duplicate = true; } } } return duplicate; } function removeExistingFileName(obj, fileArr) { if (obj.existingFileNames.length) { for (var x=0; x<fileArr.length; x++) { var pos = obj.existingFileNames.indexOf(fileArr[x]); if (pos != -1) { obj.existingFileNames.splice(pos, 1); } } } } function getSrcToPreview(file, obj) { if(file) { obj.show(); var reader = new FileReader(); reader.onload = function (e) { obj.attr('src', e.target.result); }; reader.readAsDataURL(file); } } function updateFileCounter(s, obj) { if(s.showFileCounter) { var count = $(".ajax-file-upload-filename").length; obj.fileCounter = count + 1; $(".ajax-file-upload-filename").each(function (i, items) { var arr = $(this).html().split(s.fileCounterStyle); var fileNum = parseInt(arr[0]) - 1; //decrement; var name = (i+1) + s.fileCounterStyle + arr[1]; $(this).html(name); count--; }); } } function createCutomInputFile(obj, group, s, uploadLabel) { var fileUploadId = "ajax-upload-id-" + (new Date().getTime()); var form = $("<form method='" + s.method + "' action='" + s.url + "' enctype='" + s.enctype + "'></form>"); var fileInputStr = "<input type='file' id='" + fileUploadId + "' name='" + s.fileName + "' accept='" + s.acceptFiles + "'/>"; if(s.multiple) { if(s.fileName.indexOf("[]") != s.fileName.length - 2) // if it does not endwith { s.fileName += "[]"; } fileInputStr = "<input type='file' id='" + fileUploadId + "' name='" + s.fileName + "' accept='" + s.acceptFiles + "' multiple/>"; } var fileInput = $(fileInputStr).appendTo(form); fileInput.change(function () { obj.errorLog.html(""); var fileExtensions = s.allowedTypes.toLowerCase().split(","); var fileArray = []; if(this.files) //support reading files { for(i = 0; i < this.files.length; i++) { fileArray.push(this.files[i].name); } if(s.onSelect(this.files) == false) return; } else { var filenameStr = $(this).val(); var flist = []; fileArray.push(filenameStr); if(!isFileTypeAllowed(obj, s, filenameStr)) { if(s.showError) $("<div class='" + s.errorClass + "'><b>" + filenameStr + "</b> " + s.extErrorStr + s.allowedTypes + "</div>").appendTo(obj.errorLog); return; } //fallback for browser without FileAPI flist.push({ name: filenameStr, size: 'NA' }); if(s.onSelect(flist) == false) return; } updateFileCounter(s, obj); uploadLabel.unbind("click"); form.hide(); createCutomInputFile(obj, group, s, uploadLabel); form.addClass(group); if(feature.fileapi && feature.formdata) //use HTML5 support and split file submission { form.removeClass(group); //Stop Submitting when. var files = this.files; serializeAndUploadFiles(s, obj, files); } else { var fileList = ""; for(var i = 0; i < fileArray.length; i++) { if(s.showFileCounter) fileList += obj.fileCounter + s.fileCounterStyle + fileArray[i] + "<br>"; else fileList += fileArray[i] + "<br>";; obj.fileCounter++; } if(s.maxFileCount != -1 && (obj.selectedFiles + fileArray.length) > s.maxFileCount) { if(s.showError) $("<div class='" + s.errorClass + "'><b>" + fileList + "</b> " + s.maxFileCountErrorStr + s.maxFileCount + "</div>").appendTo(obj.errorLog); return; } obj.selectedFiles += fileArray.length; var pd = new createProgressDiv(obj, s); pd.filename.html(fileList); ajaxFormSubmit(form, s, pd, fileArray, obj, null); } }); if(s.nestedForms) { form.css({ 'margin': 0, 'padding': 0 }); uploadLabel.css({ position: 'relative', overflow: 'hidden', cursor: 'default' }); fileInput.css({ position: 'absolute', 'cursor': 'pointer', 'top': '0px', 'width': '100%', 'height': '100%', 'left': '0px', 'z-index': '100', 'opacity': '0.0', 'filter': 'alpha(opacity=0)', '-ms-filter': "alpha(opacity=0)", '-khtml-opacity': '0.0', '-moz-opacity': '0.0' }); form.appendTo(uploadLabel); } else { form.appendTo($('body')); form.css({ margin: 0, padding: 0, display: 'block', position: 'absolute', left: '-250px' }); if(navigator.appVersion.indexOf("MSIE ") != -1) //IE Browser { uploadLabel.attr('for', fileUploadId); } else { uploadLabel.click(function () { fileInput.click(); }); } } } function createProgressDiv(obj, s) { this.statusbar = $("<div class='ajax-file-upload-statusbar'></div>").width(s.statusBarWidth); this.preview = $("<img class='ajax-file-upload-preview' />").width(s.previewWidth).height(s.previewHeight).appendTo(this.statusbar).hide(); this.filename = $("<div class='ajax-file-upload-filename'></div>").appendTo(this.statusbar); this.progressDiv = $("<div class='ajax-file-upload-progress'>").appendTo(this.statusbar).hide(); this.progressbar = $("<div class='ajax-file-upload-bar " + obj.formGroup + "'></div>").appendTo(this.progressDiv); this.abort = $("<div class='ajax-file-upload-red " + s.abortButtonClass + " " + obj.formGroup + "'>" + s.abortStr + "</div>").appendTo(this.statusbar).hide(); this.cancel = $("<div class='ajax-file-upload-red " + s.cancelButtonClass + " " + obj.formGroup + "'>" + s.cancelStr + "</div>").appendTo(this.statusbar).hide(); this.del = $("<div class='ajax-file-upload-red'>" + s.deletelStr + "</div>").appendTo(this.statusbar).hide(); this.done = $("<div class='ajax-file-upload-green'>" + s.doneStr + "</div>").appendTo(this.statusbar).hide(); this.settings = $("<div class='ajax-file-upload-blue' id='div-settings-btn'>" + s.settingsStr + "</div>").appendTo(this.statusbar).hide(); this.download = $("<div class='ajax-file-upload-green'>" + s.downloadStr + "</div>").appendTo(this.statusbar).hide(); this.customDiv = $('<div id="div-custom" style="display:inline-block; float:right">').appendTo(this.statusbar); if(s.showQueueDiv) $("#" + s.showQueueDiv).append(this.statusbar); else obj.errorLog.before(this.statusbar); return this; } function ajaxFormSubmit(form, s, pd, fileArray, obj, file) { var currentXHR = null; var options = { cache: false, contentType: false, processData: false, forceSync: false, type: s.method, data: s.formData, formData: s.fileData, dataType: s.returnType, beforeSubmit: function (formData, $form, options) { if(s.onSubmit.call(this, fileArray) != false) { var dynData = s.dynamicFormData(); if(dynData) { var sData = serializeData(dynData); if(sData) { for(var j = 0; j < sData.length; j++) { if(sData[j]) { if(s.fileData != undefined) options.formData.append(sData[j][0], sData[j][1]); else options.data[sData[j][0]] = sData[j][1]; } } } } obj.tCounter += fileArray.length; //window.setTimeout(checkPendingUploads, 1000); //not so critical checkPendingUploads(); return true; } pd.statusbar.append("<div class='" + s.errorClass + "'>" + s.uploadErrorStr + "</div>"); pd.cancel.show() form.remove(); pd.cancel.click(function () { removeExistingFileName(obj, fileArray); pd.statusbar.remove(); s.onCancel.call(obj, fileArray, pd); obj.selectedFiles -= fileArray.length; //reduce selected File count updateFileCounter(s, obj); }); return false; }, beforeSend: function (xhr, o) { pd.progressDiv.show(); pd.cancel.hide(); pd.done.hide(); if(s.showAbort) { pd.abort.show(); pd.abort.click(function () { removeExistingFileName(obj, fileArray); xhr.abort(); obj.selectedFiles -= fileArray.length; //reduce selected File count }); } if(!feature.formdata) //For iframe based push { pd.progressbar.width('5%'); } else pd.progressbar.width('1%'); //Fix for small files }, uploadProgress: function (event, position, total, percentComplete) { //Fix for smaller file uploads in MAC if(percentComplete > 98) percentComplete = 98; var percentVal = percentComplete + '%'; if(percentComplete > 1) pd.progressbar.width(percentVal) if(s.showProgress) { pd.progressbar.html(percentVal); pd.progressbar.css('text-align', 'center'); } }, success: function (data, message, xhr) { //For custom errors. if(s.returnType == "json" && $.type(data) == "object" && data.hasOwnProperty(s.customErrorKeyStr)) { pd.abort.hide(); var msg = data[s.customErrorKeyStr]; s.onError.call(this, fileArray, 200, msg, pd); if(s.showStatusAfterError) { pd.progressDiv.hide(); pd.statusbar.append("<span class='" + s.errorClass + "'>ERROR: " + msg + "</span>"); } else { pd.statusbar.hide(); pd.statusbar.remove(); } obj.selectedFiles -= fileArray.length; //reduce selected File count form.remove(); obj.fCounter += fileArray.length; return; } obj.responses.push(data); pd.progressbar.width('100%') if(s.showProgress) { pd.progressbar.html('100%'); pd.progressbar.css('text-align', 'center'); } pd.abort.hide(); s.onSuccess.call(this, fileArray, data, xhr, pd); if(s.showStatusAfterSuccess) { if(s.showDone) { pd.done.show(); pd.done.click(function () { //pd.statusbar.hide("slow"); //pd.statusbar.remove(); if(s.checkCallback) s.checkCallback.call(this, data); }); } else { pd.done.hide(); } if(s.showSettings) { pd.settings.show(); pd.settings.click(function () { if(s.settingsCallback) s.settingsCallback.call(this); }); } else { pd.settings.hide(); } if(s.showDelete) { pd.del.show(); pd.del.click(function () { var dlg_confirm = confirm('Remove file '+data.replace(/\["(.+)"\]/g, "`$1'")+'?'); if(dlg_confirm == true) { pd.statusbar.hide().remove(); if(s.deleteCallback) s.deleteCallback.call(this, data, pd); obj.selectedFiles -= fileArray.length; //reduce selected File count updateFileCounter(s, obj); } }); } else { pd.del.hide(); } } else { pd.statusbar.hide("slow"); pd.statusbar.remove(); } if(s.showDownload) { pd.download.show(); pd.download.click(function () { if(s.downloadCallback) s.downloadCallback(data); }); } form.remove(); obj.sCounter += fileArray.length; }, error: function (xhr, status, errMsg) { pd.abort.hide(); if(xhr.statusText == "abort") //we aborted it { pd.statusbar.hide("slow").remove(); updateFileCounter(s, obj); } else { s.onError.call(this, fileArray, status, errMsg, pd); if(s.showStatusAfterError) { pd.progressDiv.hide(); pd.statusbar.append("<span class='" + s.errorClass + "'>ERROR: " + errMsg + "</span>"); } else { pd.statusbar.hide(); pd.statusbar.remove(); } obj.selectedFiles -= fileArray.length; //reduce selected File count } form.remove(); obj.fCounter += fileArray.length; } }; if(s.showPreview && file != null) { if(file.type.toLowerCase().split("/").shift() == "image") getSrcToPreview(file, pd.preview); } if(s.autoSubmit) { form.ajaxSubmit(options); } else { if(s.showCancel) { pd.cancel.show(); pd.cancel.click(function () { removeExistingFileName(obj, fileArray); form.remove(); pd.statusbar.remove(); s.onCancel.call(obj, fileArray, pd); obj.selectedFiles -= fileArray.length; //reduce selected File count updateFileCounter(s, obj); }); } form.ajaxForm(options); } } return this; } }(jQuery));
'use strict'; import { getDB } from './jsonDB'; import { stringToArray, getSorter, urlToId, loadJsonFile } from '../tools/functions'; import { getFilterbyNameMixin, getFilterbyClassificationMixin, getFilterbyDesignationMixin } from './dbMixin'; export default async function load() { const sorter = getSorter('name'); const items = (await loadJsonFile('./data/species.json')) .map(mapper) .sort(sorter); const db = getDB(items); return Object.assign( {}, db, getFilterbyNameMixin(), getFilterbyClassificationMixin(), getFilterbyDesignationMixin(), ); }; function mapper(item) { const { url, classification, eye_colors, hair_colors, skin_colors, homeworld, people, films, ...data } = item; const obj = Object.assign({}, data, { id: urlToId(url), eye_colors: stringToArray(eye_colors), hair_colors: stringToArray(hair_colors), skin_colors: stringToArray(skin_colors), classification: classification === 'mammals' ? 'mammal' : classification, homeworld: urlToId(homeworld), characters: people.map(urlToId), films: films.map(urlToId), }); return obj; };
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.LEVEL_ENUM = exports.TIME_PERIOD_ENUM = exports.RESERVED_WORDS_ENUM = void 0; exports.RESERVED_WORDS_ENUM = { defaction: true, function: true, return: true, not: true, setting: true, null: true, true: true, false: true }; exports.TIME_PERIOD_ENUM = { day: true, days: true, hour: true, hours: true, minute: true, minutes: true, month: true, months: true, second: true, seconds: true, week: true, weeks: true, year: true, years: true }; exports.LEVEL_ENUM = { error: true, warn: true, info: true, debug: true }; //# sourceMappingURL=types.js.map
'use strict'; module.exports = require('ridge/collection').extend({ model: require('../models/region'), url: '/api/regions' });
/** * Module dependencies. */ var express = require('express'), routes = require('./routes'), domain = require('./routes/domain'), engines = require('consolidate'), http = require('http'), path = require('path'); var app = express(); app.disable('x-powered-by'); app.engine('hbs', engines.handlebars); app.configure(function(){ app.set('port', process.env.PORT || 3000); app.set('views', __dirname + '/views'); app.set('view engine', 'hbs'); app.use(express.favicon()); app.use(express.logger('dev')); app.use(express.urlencoded()); app.use(express.json()); app.use(express.methodOverride()); app.use(app.router); app.use(express.static(path.join(__dirname, 'public'))); }); app.configure('development', function(){ app.use(express.errorHandler()); }); app.get('/', routes.index); app.get('/domain/:domain', domain.show); http.createServer(app).listen(app.get('port'), function(){ console.log('Express server listening on port ' + app.get('port')); });
Dagaz.Controller.persistense = "session"; Dagaz.Model.WIDTH = 5; Dagaz.Model.HEIGHT = 5; Dagaz.AI.FLAGS = 0xE0; ZRF = { JUMP: 0, IF: 1, FORK: 2, FUNCTION: 3, IN_ZONE: 4, FLAG: 5, SET_FLAG: 6, POS_FLAG: 7, SET_POS_FLAG: 8, ATTR: 9, SET_ATTR: 10, PROMOTE: 11, MODE: 12, ON_BOARD_DIR: 13, ON_BOARD_POS: 14, PARAM: 15, LITERAL: 16, VERIFY: 20 }; if (Dagaz.AI.SetParams) { Dagaz.AI.SetParams(Dagaz.Model.WIDTH, Dagaz.Model.HEIGHT, Dagaz.AI.FLAGS); } Dagaz.Model.BuildDesign = function(design) { design.checkVersion("z2j", "2"); design.checkVersion("animate-captures", "false"); design.checkVersion("smart-moves", "false"); design.checkVersion("show-blink", "false"); design.checkVersion("show-hints", "false"); design.checkVersion("advisor-wait", "5"); design.checkVersion("chess-invariant", "true"); design.addDirection("w"); design.addDirection("e"); design.addDirection("s"); design.addDirection("ne"); design.addDirection("n"); design.addDirection("se"); design.addDirection("sw"); design.addDirection("nw"); design.addPlayer("White", [1, 0, 4, 6, 2, 7, 3, 5]); design.addPlayer("Black", [1, 0, 4, 6, 2, 7, 3, 5]); design.addPosition("a5", [0, 1, 5, 0, 0, 6, 0, 0]); design.addPosition("b5", [-1, 1, 5, 0, 0, 6, 4, 0]); design.addPosition("c5", [-1, 1, 5, 0, 0, 6, 4, 0]); design.addPosition("d5", [-1, 1, 5, 0, 0, 6, 4, 0]); design.addPosition("e5", [-1, 0, 5, 0, 0, 0, 4, 0]); design.addPosition("a4", [0, 1, 5, -4, -5, 6, 0, 0]); design.addPosition("b4", [-1, 1, 5, -4, -5, 6, 4, -6]); design.addPosition("c4", [-1, 1, 5, -4, -5, 6, 4, -6]); design.addPosition("d4", [-1, 1, 5, -4, -5, 6, 4, -6]); design.addPosition("e4", [-1, 0, 5, 0, -5, 0, 4, -6]); design.addPosition("a3", [0, 1, 5, -4, -5, 6, 0, 0]); design.addPosition("b3", [-1, 1, 5, -4, -5, 6, 4, -6]); design.addPosition("c3", [-1, 1, 5, -4, -5, 6, 4, -6]); design.addPosition("d3", [-1, 1, 5, -4, -5, 6, 4, -6]); design.addPosition("e3", [-1, 0, 5, 0, -5, 0, 4, -6]); design.addPosition("a2", [0, 1, 5, -4, -5, 6, 0, 0]); design.addPosition("b2", [-1, 1, 5, -4, -5, 6, 4, -6]); design.addPosition("c2", [-1, 1, 5, -4, -5, 6, 4, -6]); design.addPosition("d2", [-1, 1, 5, -4, -5, 6, 4, -6]); design.addPosition("e2", [-1, 0, 5, 0, -5, 0, 4, -6]); design.addPosition("a1", [0, 1, 0, -4, -5, 0, 0, 0]); design.addPosition("b1", [-1, 1, 0, -4, -5, 0, 0, -6]); design.addPosition("c1", [-1, 1, 0, -4, -5, 0, 0, -6]); design.addPosition("d1", [-1, 1, 0, -4, -5, 0, 0, -6]); design.addPosition("e1", [-1, 0, 0, 0, -5, 0, 0, -6]); design.addPosition("X1", [0, 0, 0, 0, 0, 0, 0, 0]); design.addPosition("X2", [0, 0, 0, 0, 0, 0, 0, 0]); design.addPosition("X3", [0, 0, 0, 0, 0, 0, 0, 0]); design.addPosition("X4", [0, 0, 0, 0, 0, 0, 0, 0]); design.addZone("last-rank", 1, [0, 1, 2, 3, 4]); design.addZone("last-rank", 2, [20, 21, 22, 23, 24]); design.addCommand(0, ZRF.FUNCTION, 24); // from design.addCommand(0, ZRF.PARAM, 0); // $1 design.addCommand(0, ZRF.FUNCTION, 22); // navigate design.addCommand(0, ZRF.FUNCTION, 1); // empty? design.addCommand(0, ZRF.FUNCTION, 20); // verify design.addCommand(0, ZRF.IN_ZONE, 0); // last-rank design.addCommand(0, ZRF.FUNCTION, 0); // not design.addCommand(0, ZRF.IF, 4); design.addCommand(0, ZRF.PROMOTE, 4); // Queen design.addCommand(0, ZRF.FUNCTION, 25); // to design.addCommand(0, ZRF.JUMP, 2); design.addCommand(0, ZRF.FUNCTION, 25); // to design.addCommand(0, ZRF.FUNCTION, 28); // end design.addCommand(1, ZRF.FUNCTION, 24); // from design.addCommand(1, ZRF.PARAM, 0); // $1 design.addCommand(1, ZRF.FUNCTION, 22); // navigate design.addCommand(1, ZRF.FUNCTION, 2); // enemy? design.addCommand(1, ZRF.FUNCTION, 20); // verify design.addCommand(1, ZRF.IN_ZONE, 0); // last-rank design.addCommand(1, ZRF.FUNCTION, 0); // not design.addCommand(1, ZRF.IF, 4); design.addCommand(1, ZRF.PROMOTE, 4); // Queen design.addCommand(1, ZRF.FUNCTION, 25); // to design.addCommand(1, ZRF.JUMP, 2); design.addCommand(1, ZRF.FUNCTION, 25); // to design.addCommand(1, ZRF.FUNCTION, 28); // end design.addCommand(2, ZRF.FUNCTION, 24); // from design.addCommand(2, ZRF.PARAM, 0); // $1 design.addCommand(2, ZRF.FUNCTION, 22); // navigate design.addCommand(2, ZRF.FUNCTION, 1); // empty? design.addCommand(2, ZRF.FUNCTION, 0); // not design.addCommand(2, ZRF.IF, 7); design.addCommand(2, ZRF.FORK, 3); design.addCommand(2, ZRF.FUNCTION, 25); // to design.addCommand(2, ZRF.FUNCTION, 28); // end design.addCommand(2, ZRF.PARAM, 1); // $2 design.addCommand(2, ZRF.FUNCTION, 22); // navigate design.addCommand(2, ZRF.JUMP, -8); design.addCommand(2, ZRF.FUNCTION, 3); // friend? design.addCommand(2, ZRF.FUNCTION, 0); // not design.addCommand(2, ZRF.FUNCTION, 20); // verify design.addCommand(2, ZRF.FUNCTION, 25); // to design.addCommand(2, ZRF.FUNCTION, 28); // end design.addCommand(3, ZRF.FUNCTION, 24); // from design.addCommand(3, ZRF.PARAM, 0); // $1 design.addCommand(3, ZRF.FUNCTION, 22); // navigate design.addCommand(3, ZRF.PARAM, 1); // $2 design.addCommand(3, ZRF.FUNCTION, 22); // navigate design.addCommand(3, ZRF.FUNCTION, 3); // friend? design.addCommand(3, ZRF.FUNCTION, 0); // not design.addCommand(3, ZRF.FUNCTION, 20); // verify design.addCommand(3, ZRF.FUNCTION, 25); // to design.addCommand(3, ZRF.FUNCTION, 28); // end design.addCommand(4, ZRF.FUNCTION, 24); // from design.addCommand(4, ZRF.PARAM, 0); // $1 design.addCommand(4, ZRF.FUNCTION, 22); // navigate design.addCommand(4, ZRF.FUNCTION, 3); // friend? design.addCommand(4, ZRF.FUNCTION, 0); // not design.addCommand(4, ZRF.FUNCTION, 20); // verify design.addCommand(4, ZRF.FUNCTION, 25); // to design.addCommand(4, ZRF.FUNCTION, 28); // end design.addPiece("Pawn", 0, 100); design.addMove(0, 0, [4], 0); design.addMove(0, 1, [7], 0); design.addMove(0, 1, [3], 0); design.addPiece("Rook", 1, 500); design.addMove(1, 2, [4, 4], 0); design.addMove(1, 2, [2, 2], 0); design.addMove(1, 2, [0, 0], 0); design.addMove(1, 2, [1, 1], 0); design.addPiece("Knight", 2, 320); design.addMove(2, 3, [4, 7], 0); design.addMove(2, 3, [4, 3], 0); design.addMove(2, 3, [2, 6], 0); design.addMove(2, 3, [2, 5], 0); design.addMove(2, 3, [0, 7], 0); design.addMove(2, 3, [0, 6], 0); design.addMove(2, 3, [1, 3], 0); design.addMove(2, 3, [1, 5], 0); design.addPiece("Bishop", 3, 330); design.addMove(3, 2, [7, 7], 0); design.addMove(3, 2, [6, 6], 0); design.addMove(3, 2, [3, 3], 0); design.addMove(3, 2, [5, 5], 0); design.addPiece("Queen", 4, 900); design.addMove(4, 2, [4, 4], 0); design.addMove(4, 2, [2, 2], 0); design.addMove(4, 2, [0, 0], 0); design.addMove(4, 2, [1, 1], 0); design.addMove(4, 2, [7, 7], 0); design.addMove(4, 2, [6, 6], 0); design.addMove(4, 2, [3, 3], 0); design.addMove(4, 2, [5, 5], 0); design.addPiece("King", 5, 20000); design.addMove(5, 4, [4], 0); design.addMove(5, 4, [2], 0); design.addMove(5, 4, [0], 0); design.addMove(5, 4, [1], 0); design.addMove(5, 4, [7], 0); design.addMove(5, 4, [6], 0); design.addMove(5, 4, [3], 0); design.addMove(5, 4, [5], 0); design.setup("White", "Pawn", 15); design.setup("White", "Pawn", 16); design.setup("White", "Pawn", 17); design.setup("White", "Pawn", 18); design.setup("White", "Pawn", 19); design.setup("White", "Rook", 20); design.setup("White", "Knight", 21); design.setup("White", "Bishop", 22); design.setup("White", "Queen", 23); design.setup("White", "King", 24); design.setup("Black", "Pawn", 5); design.setup("Black", "Pawn", 6); design.setup("Black", "Pawn", 7); design.setup("Black", "Pawn", 8); design.setup("Black", "Pawn", 9); design.setup("Black", "Rook", 4); design.setup("Black", "Knight", 3); design.setup("Black", "Bishop", 2); design.setup("Black", "Queen", 1); design.setup("Black", "King", 0); } Dagaz.View.configure = function(view) { view.defBoard("Board"); view.defPiece("WhitePawn", "White Pawn"); view.defPiece("BlackPawn", "Black Pawn"); view.defPiece("WhiteRook", "White Rook"); view.defPiece("BlackRook", "Black Rook"); view.defPiece("WhiteKnight", "White Knight"); view.defPiece("BlackKnight", "Black Knight"); view.defPiece("WhiteBishop", "White Bishop"); view.defPiece("BlackBishop", "Black Bishop"); view.defPiece("WhiteQueen", "White Queen"); view.defPiece("BlackQueen", "Black Queen"); view.defPiece("WhiteKing", "White King"); view.defPiece("BlackKing", "Black King"); view.defPosition("a5", 2, 2, 68, 68); view.defPosition("b5", 70, 2, 68, 68); view.defPosition("c5", 138, 2, 68, 68); view.defPosition("d5", 206, 2, 68, 68); view.defPosition("e5", 274, 2, 68, 68); view.defPosition("a4", 2, 70, 68, 68); view.defPosition("b4", 70, 70, 68, 68); view.defPosition("c4", 138, 70, 68, 68); view.defPosition("d4", 206, 70, 68, 68); view.defPosition("e4", 274, 70, 68, 68); view.defPosition("a3", 2, 138, 68, 68); view.defPosition("b3", 70, 138, 68, 68); view.defPosition("c3", 138, 138, 68, 68); view.defPosition("d3", 206, 138, 68, 68); view.defPosition("e3", 274, 138, 68, 68); view.defPosition("a2", 2, 206, 68, 68); view.defPosition("b2", 70, 206, 68, 68); view.defPosition("c2", 138, 206, 68, 68); view.defPosition("d2", 206, 206, 68, 68); view.defPosition("e2", 274, 206, 68, 68); view.defPosition("a1", 2, 274, 68, 68); view.defPosition("b1", 70, 274, 68, 68); view.defPosition("c1", 138, 274, 68, 68); view.defPosition("d1", 206, 274, 68, 68); view.defPosition("e1", 274, 274, 68, 68); view.defPopup("Promote", 24, 50); view.defPopupPosition("X1", 10, 7, 68, 68); view.defPopupPosition("X2", 80, 7, 68, 68); view.defPopupPosition("X3", 150, 7, 68, 68); view.defPopupPosition("X4", 220, 7, 68, 68); }
import React from 'react'; import { storiesOf } from '@storybook/react-native'; import FlexedView from '@ui/FlexedView'; import TaggedContent from './'; storiesOf('TaggedContent', module) .add('group stories', () => ( <FlexedView> <TaggedContent tagName="community" sectionTitle="You can't do life alone" /> </FlexedView> )) .add('recent articles about giving', () => ( <FlexedView> <TaggedContent tagName="giving" sectionTitle="Recent articles about giving" /> </FlexedView> ));
/*! * Copyright (c) 2015-2017 Cisco Systems, Inc. See LICENSE file. */ /* eslint-disable indent */ import {assert} from '@ciscospark/test-helper-chai'; import {createBrowser} from '@ciscospark/test-helper-automation'; import testUsers from '@ciscospark/test-helper-test-users'; import pkg from '../../../package'; const redirectUri = process.env.CISCOSPARK_REDIRECT_URI || process.env.REDIRECT_URI; describe('plugin-authorization-browser', function () { this.timeout(120000); describe('Authorization', () => { describe('Authorization Code Grant', () => { let browser, user; before(() => testUsers.create({count: 1}) .then((users) => { user = users[0]; })); before(() => createBrowser(pkg) .then((b) => { browser = b; })); after(() => browser && browser.printLogs()); after(() => browser && browser.quit() .catch((reason) => { console.warn(reason); })); it('authorizes a user', () => browser .get(`${redirectUri}/${pkg.name}`) .waitForElementByClassName('ready') .title() .should.eventually.become('Authorization Automation Test') .waitForElementByCssSelector('[title="Login with Authorization Code Grant"]') .click() .login(user) .waitForElementByClassName('authorization-automation-test') .waitForElementById('refresh-token') .text() .should.eventually.not.be.empty .waitForElementByCssSelector('#ping-complete:not(:empty)') .text() .should.eventually.become('success')); it('is still logged in after reloading the page', () => browser .waitForElementById('access-token') .text() .should.eventually.not.be.empty .get(`${redirectUri}/${pkg.name}`) .sleep(500) .waitForElementById('access-token') .text() .should.eventually.not.be.empty); it('refreshes the user\'s access token', () => { let accessToken = ''; return browser .waitForElementByCssSelector('#access-token:not(:empty)') .text() .then((text) => { accessToken = text; assert.isString(accessToken); assert.isAbove(accessToken.length, 0); return browser; }) .waitForElementByCssSelector('[title="Refresh Access Token"]') .click() // Not thrilled by a sleep, but we just need to give the button click // enough time to clear the #access-token box .sleep(500) .waitForElementByCssSelector('#access-token:not(:empty)') .text() .then((text) => { assert.isString(text); assert.isAbove(text.length, 0); assert.notEqual(text, accessToken); return browser; }); }); it('logs out a user', () => browser .title() .should.eventually.become('Authorization Automation Test') .waitForElementByCssSelector('[title="Logout"]') .click() // We need to revoke three tokens before the window.location assignment. // So far, I haven't found any ques to wait for, so sleep seems to be // the only option. .sleep(3000) .title() .should.eventually.become('Redirect Dispatcher') .get(`${redirectUri}/${pkg.name}`) .title() .should.eventually.become('Authorization Automation Test') .waitForElementById('access-token') .text() .should.eventually.be.empty .waitForElementByCssSelector('[title="Login with Authorization Code Grant"]') .click() .waitForElementById('IDToken1')); }); }); });
'use strict';module.exports = function(css){var TokenType=require('../token-types');var tokens=[],urlMode=false,blockMode=0,c, // current character cn, // next character pos=0,tn=0,ln=1,col=1;var Punctuation={' ':TokenType.Space,'\n':TokenType.Newline,'\r':TokenType.Newline,'\t':TokenType.Tab,'!':TokenType.ExclamationMark,'"':TokenType.QuotationMark,'#':TokenType.NumberSign,'$':TokenType.DollarSign,'%':TokenType.PercentSign,'&':TokenType.Ampersand,'\'':TokenType.Apostrophe,'(':TokenType.LeftParenthesis,')':TokenType.RightParenthesis,'*':TokenType.Asterisk,'+':TokenType.PlusSign,',':TokenType.Comma,'-':TokenType.HyphenMinus,'.':TokenType.FullStop,'/':TokenType.Solidus,':':TokenType.Colon,';':TokenType.Semicolon,'<':TokenType.LessThanSign,'=':TokenType.EqualsSign,'>':TokenType.GreaterThanSign,'?':TokenType.QuestionMark,'@':TokenType.CommercialAt,'[':TokenType.LeftSquareBracket,']':TokenType.RightSquareBracket,'^':TokenType.CircumflexAccent,'_':TokenType.LowLine,'{':TokenType.LeftCurlyBracket,'|':TokenType.VerticalLine,'}':TokenType.RightCurlyBracket,'~':TokenType.Tilde}; /** * Add a token to the token list * @param {string} type * @param {string} value */function pushToken(type,value,column){tokens.push({tn:tn++,ln:ln,col:column,type:type,value:value});} /** * Check if a character is a decimal digit * @param {string} c Character * @returns {boolean} */function isDecimalDigit(c){return '0123456789'.indexOf(c) >= 0;} /** * Parse spaces * @param {string} css Unparsed part of CSS string */function parseSpaces(css){var start=pos; // Read the string until we meet a non-space character: for(;pos < css.length;pos++) {if(css.charAt(pos) !== ' ')break;} // Add a substring containing only spaces to tokens: pushToken(TokenType.Space,css.substring(start,pos--),col);col += pos - start;} /** * Parse a string within quotes * @param {string} css Unparsed part of CSS string * @param {string} q Quote (either `'` or `"`) */function parseString(css,q){var start=pos; // Read the string until we meet a matching quote: for(pos++;pos < css.length;pos++) { // Skip escaped quotes: if(css.charAt(pos) === '\\')pos++;else if(css.charAt(pos) === q)break;} // Add the string (including quotes) to tokens: pushToken(q === '"'?TokenType.StringDQ:TokenType.StringSQ,css.substring(start,pos + 1),col);col += pos - start;} /** * Parse numbers * @param {string} css Unparsed part of CSS string */function parseDecimalNumber(css){var start=pos; // Read the string until we meet a character that's not a digit: for(;pos < css.length;pos++) {if(!isDecimalDigit(css.charAt(pos)))break;} // Add the number to tokens: pushToken(TokenType.DecimalNumber,css.substring(start,pos--),col);col += pos - start;} /** * Parse identifier * @param {string} css Unparsed part of CSS string */function parseIdentifier(css){var start=pos; // Skip all opening slashes: while(css.charAt(pos) === '/') pos++; // Read the string until we meet a punctuation mark: for(;pos < css.length;pos++) { // Skip all '\': if(css.charAt(pos) === '\\')pos++;else if(css.charAt(pos) in Punctuation)break;}var ident=css.substring(start,pos--); // Enter url mode if parsed substring is `url`: urlMode = urlMode || ident === 'url'; // Add identifier to tokens: pushToken(TokenType.Identifier,ident,col);col += pos - start;} /** * Parse a multiline comment * @param {string} css Unparsed part of CSS string */function parseMLComment(css){var start=pos; // Read the string until we meet `*/`. // Since we already know first 2 characters (`/*`), start reading // from `pos + 2`: for(pos = pos + 2;pos < css.length;pos++) {if(css.charAt(pos) === '*' && css.charAt(pos + 1) === '/'){pos++;break;}} // Add full comment (including `/*` and `*/`) to the list of tokens: var comment=css.substring(start,pos + 1);pushToken(TokenType.CommentML,comment,col);var newlines=comment.split('\n');if(newlines.length > 1){ln += newlines.length - 1;col = newlines[newlines.length - 1].length;}else {col += pos - start;}} /** * Parse a single line comment * @param {string} css Unparsed part of CSS string */function parseSLComment(css){var start=pos; // Read the string until we meet line break. // Since we already know first 2 characters (`//`), start reading // from `pos + 2`: for(pos += 2;pos < css.length;pos++) {if(css.charAt(pos) === '\n' || css.charAt(pos) === '\r'){break;}} // Add comment (including `//` and line break) to the list of tokens: pushToken(TokenType.CommentSL,css.substring(start,pos--),col);col += pos - start;} /** * Convert a CSS string to a list of tokens * @param {string} css CSS string * @returns {Array} List of tokens * @private */function getTokens(css){ // Parse string, character by character: for(pos = 0;pos < css.length;col++,pos++) {c = css.charAt(pos);cn = css.charAt(pos + 1); // If we meet `/*`, it's a start of a multiline comment. // Parse following characters as a multiline comment: if(c === '/' && cn === '*'){parseMLComment(css);} // If we meet `//` and it is not a part of url: else if(!urlMode && c === '/' && cn === '/'){ // If we're currently inside a block, treat `//` as a start // of identifier. Else treat `//` as a start of a single-line // comment: parseSLComment(css);} // If current character is a double or single quote, it's a start // of a string: else if(c === '"' || c === "'"){parseString(css,c);} // If current character is a space: else if(c === ' '){parseSpaces(css);} // If current character is a punctuation mark: else if(c in Punctuation){ // Add it to the list of tokens: pushToken(Punctuation[c],c,col);if(c === '\n' || c === '\r'){ln++;col = 0;} // Go to next line if(c === ')')urlMode = false; // exit url mode if(c === '{')blockMode++; // enter a block if(c === '}')blockMode--; // exit a block } // If current character is a decimal digit: else if(isDecimalDigit(c)){parseDecimalNumber(css);} // If current character is anything else: else {parseIdentifier(css);}}return tokens;}return getTokens(css);};
/** * The Initial Developer of the Original Code is * Tarmo Alexander Sundström <[email protected]> * * Portions created by the Initial Developer are * Copyright (C) 2014 Tarmo Alexander Sundström <[email protected]> * * All Rights Reserved. * * Contributor(s): * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ var Media = { initUpload: function () { var _url = jQuery('#basehref').text(); var _token = jQuery('#token').text(); var _dropStr = jQuery('#translation-dragndrop').data('translation'); var _doneStr = jQuery('#translation-done').data('translation'); jQuery('#upload').uploadFile( { url: _url + '/content_media/store/?token=' + _token, multiple: true, fileName: 'files', uploadButtonClass: 'btn btn-info btn-lg', dragDropStr: '<span id="upload-drag">' + _dropStr + '</span>', dragdropWidth: 'auto', statusBarWidth: 'auto', doneStr: _doneStr, onSubmit:function (files) { Loader.show(); }, afterUploadAll:function () { Loader.hide(); } } ); }, initSearch: function () { jQuery('#filter').keyup( function () { var filter = jQuery(this).val(); jQuery('.filterable li').each( function () { if (jQuery(this).data('filter').search(new RegExp(filter, 'i')) < 0) { jQuery(this).fadeOut('fast'); } else { jQuery(this).show(); } } ); } ); }, initFolderBindings: function () { jQuery('.load-folder-listing').on( 'click', function (e) { e.preventDefault(); var _dir = jQuery(this).data('path'); Media. getFileList(_dir); } ) }, initConfirmBindings: function () { jQuery('.confirm-delete').click( function (e) { e.preventDefault(); var message = jQuery(this).attr('data-message'); if (confirm(message)) { Loader.show(); var _url = jQuery(this).attr('href'); var _path = jQuery('#append-path').text(); _request = jQuery.ajax( { type: "GET", url: _url } ); _request.done( function (response) { Media.getFileList(_path); Loader.hide(); } ); return true; } else { return false; } } ); }, initFileSelectorBindings: function () { jQuery('.file-selector').on( 'click', function () { var $selectedN = Media.countSelectedFileSelectors(); if($selectedN > 0) { jQuery('#move-button').removeClass('disabled'); jQuery('#delete-button').removeClass('disabled'); } else { jQuery('#move-button').addClass('disabled'); jQuery('#delete-button').addClass('disabled'); } } ); jQuery('.mediapicker-select-file').on( 'click', function (e) { e.preventDefault(); var _file = jQuery(this).data('file'); var _active = jQuery('.mediapicker-modal').data('active-mediapicker-uniqid'); jQuery('#mediapickerinput-' + _active).val(_file); jQuery('.mediapicker-modal').modal('hide'); } ); }, initMultipleFileDeletion: function () { jQuery('#delete-button').on( 'click', function () { var $selectedN = Media.countSelectedFileSelectors(); if(jQuery(this).hasClass('disabled')) { return false; } if($selectedN == 0) { return false; } var message = jQuery(this).attr('data-message'); if (!confirm(message)) { return false; } Loader.show(); var _path = jQuery('#append-path').text(); jQuery('.file-selector:checked').each( function () { var $p = jQuery(this).parent(); var $del = $p.find('.confirm-delete'); var $deleteUrl = jQuery($del).attr('href'); _request = jQuery.ajax( { type: "GET", url: $deleteUrl } ); } ); Media.getFileList(_path); Loader.hide(); } ); }, countSelectedFileSelectors: function () { return jQuery('.file-selector:checked').length; }, getFileList: function (srcPath) { Loader.show(); var _request; var _url = jQuery('#basehref').text(); var _mediapicker = jQuery('#mediapicker').text(); var _token = jQuery('#token').text(); _request = jQuery.ajax( { type: "POST", url: _url + '/content_media/listing?token=' + _token, data: { path: srcPath, mediapicker: _mediapicker } } ); _request.done( function (response) { jQuery('#file-listing').html(response); jQuery('img.lazy').show().lazyload(); jQuery('#append-path').text(srcPath); window.location.hash = srcPath; Media.initFileSelectorBindings(); Media.initConfirmBindings(); Media.initFileInfo(); Loader.hide(); } ); }, getFileInfo: function (_filename) { Loader.show(); jQuery('.file-info-dialog').html('').hide(); var _request; var _url = jQuery('#basehref').text(); var _token = jQuery('#token').text(); _request = jQuery.ajax( { type: "POST", url: _url + '/content_media/fileinfo?token=' + _token, data: { filename: _filename } } ); _request.done( function (response) { jQuery('.file-info-dialog[data-filename="'+_filename+'"]').html(response).toggle(); jQuery('.btn-save-fileinfo').on( 'click', function (e) { e.preventDefault(); var _filename = jQuery(this).parent().find('.filename-holder').val(); var _title = jQuery(this).parent().find('.title-holder').val(); var _alt = jQuery(this).parent().find('.alt-holder').val(); Media.saveFileInfo(_filename, _title, _alt); } ); Loader.hide(); } ); }, initFileInfo: function () { jQuery('.file-info-button').on( 'click', function (e) { e.preventDefault(); var _filename = jQuery(this).data('filename'); Media.getFileInfo(_filename); } ); }, saveFileInfo: function (_filename, _title, _alt) { Loader.show(); var _request; var _url = jQuery('#basehref').text(); var _token = jQuery('#token').text(); _request = jQuery.ajax( { type: "POST", url: _url + '/content_media/savefileinfo?token=' + _token, data: { filename: _filename, title: _title, alt: _alt } } ); _request.done( function (response) { jQuery('.file-info-dialog').html('').hide(); Loader.hide(); } ); } } jQuery(document).ready( function () { Media.initUpload(); Media.initSearch(); Media.initMultipleFileDeletion(); if(jQuery('#initFilelist').length > 0) { var dir = '/'; if(document.URL.indexOf('#') > -1) { dir = document.URL.substr(document.URL.indexOf('#') + 1); } Media.getFileList(dir); Media.initFolderBindings(); } } );
import $ from "jqmin"; import Autocomplete from "@AX6UI/AX6UIAutocomplete"; import "@AX6UI/AX6UIAutocomplete/style.scss"; let html = ` <div class="row"> <div class="input-field col s12"> <div data-ax6ui-autocomplete="ac1" data-ax6ui-autocomplete-config='{}'></div> </div> </div> `; let fn = { moduleRun: function ($body) { let options = []; options.push({value: "1", text: "string"}); options.push({value: "2", text: "number"}); options.push({value: "3", text: "substr"}); options.push({value: "4", text: "substring"}); options.push({value: "5", text: "search"}); options.push({value: "6", text: "parseInt"}); options.push({value: "7", text: "toFixed"}); options.push({value: "8", text: "min"}); options.push({value: "9", text: "max"}); options.push({value: "10", text: "장기영"}); options.push({value: "11", text: "장서우"}); options.push({value: "12", text: "이영희"}); options.push({value: "13", text: "황인서"}); options.push({value: "14", text: "황세진"}); options.push({value: "15", text: "이서연"}); options.push({value: "16", text: "액시스제이"}); options.push({value: "17", text: "ax5"}); options.push({value: "18", text: "ax5grid"}); options.push({value: "19", text: "ax5combobox"}); options.push({value: "20", text: "ax5autocomplete"}); options.push({value: "21", text: "ax5binder"}); options.push({value: "22", text: "ax5select"}); options.push({value: "23", text: "ax5mask"}); options.push({value: "24", text: "ax5toast"}); options.push({value: "25", text: "ax5dialog"}); options.push({value: "26", text: "ax5modal"}); let autocomplete = new Autocomplete({ removeIcon: '<i class="tiny material-icons">close</i>' }); autocomplete.bind({ target: $('[data-ax6ui-autocomplete="ac1"]'), height: 40, optionItemHeight: 30, onSearch: function (callback) { let searchWord = this.searchWord; setTimeout(function () { let regExp = new RegExp(searchWord); let myOptions = []; options.forEach(function (n) { if (n.text.match(regExp)) { myOptions.push({ value: n.value, text: n.text }); } }); callback({ options: myOptions }); }, 150); } }); }, moduleDestroy: function ($body) { $body.off("click"); } }; export default { html: html, fn: fn }
/* eslint-env mocha */ import Path from './Path' import assert from 'assert' describe('primitives', () => { it('should initiate correctly', () => { const payload = { foo: 'bar', } const path = new Path('path', payload) assert.ok(path instanceof Path) assert.strictEqual(path.path, 'path') assert.deepStrictEqual(path.payload, payload) assert.strictEqual(path.toJSON().path, 'path') assert.deepStrictEqual(path.toJSON().payload, payload) }) })
describe('Bases Loaded controllers', function () { describe('VotingFormCtrl', function () { var scope, $httpBackend; beforeEach(module('basesloaded')); beforeEach(inject(function(_$httpBackend_, $rootScope, $controller) { $httpBackend = _$httpBackend_; $httpBackend.expectGET('/api/ballot/options') .respond({ colors: [ {color_id: 1, name: 'Red'}, {color_id: 2, name: 'Green'}, {color_id: 3, name: 'Blue'} ], teamNames: [ {team_name_id: 1, name: 'BASES aren\'t the only thing LOADED'}, {team_name_id: 2, name: 'Bases (aren\'t the only thing) Loaded'} ], captains: [ {captain_id: 1, name: 'Carol'}, {captain_id: 2, name: 'Evan'} ] }); scope = $rootScope.$new(); ctrl = $controller('VotingFormCtrl', {$scope: scope}); })); it('should create the "colors" model with 3 colors fetched from XHR', function () { expect(scope.colors).toBeUndefined(); $httpBackend.flush(); expect(scope.colors).toEqual([ {color_id: 1, name: 'Red'}, {color_id: 2, name: 'Green'}, {color_id: 3, name: 'Blue'} ]); }); it('should create the "teamNames" model with 2 team names fetched from XHR', function () { expect(scope.teamNames).toBeUndefined(); $httpBackend.flush(); expect(scope.teamNames).toEqual([ {team_name_id: 1, name: 'BASES aren\'t the only thing LOADED'}, {team_name_id: 2, name: 'Bases (aren\'t the only thing) Loaded'} ]); }); it('should create the "captains" model with 2 captains fetched from XHR', function () { expect(scope.captains).toBeUndefined(); $httpBackend.flush(); expect(scope.captains).toEqual([ {captain_id: 1, name: 'Carol'}, {captain_id: 2, name: 'Evan'} ]); }); }); });
import gulp from 'gulp' import htmlmin from 'gulp-htmlmin' import uglify from 'gulp-uglify' import runSequence from 'run-sequence' gulp.task('minify-html', () => { return gulp.src('html/**/*.html') .pipe(htmlmin({ collapseWhitespace: true, minifyCSS: true, minifyJS: true, removeComments: true, useShortDoctype: true, })) .pipe(gulp.dest('./html')) }) gulp.task('minify-js', () => { return gulp.src('./html/**/*.js') .pipe(uglify()) .pipe(gulp.dest('./html')); }); gulp.task('build', (callback) => { runSequence('minify-html','minify-js', callback) })
'use strict' //Pass in path to root directory //returns object representation with all directories and files //directory properties have property structure //path: STRING, files: ARRAY, opened: BOOL (default false), type:STRING //file properties have property structure //path:STRING, type:STRING //separate out the proj info stuff into another module? and then put info in local storage instead of a local file? const fs = require('fs'); const path = require('path'); const { File, Directory } = require('./item-schema'); const projInfoPath = path.join(__dirname, '../lib/projInfo.js'); const projInfo = { htmlPath: '', hotLoad: false, webpack: false, rootPath: '', devServer: false, devServerScript: '', mainEntry: '', reactEntry: '', CRA: false, }; function insertSorted(fileOrDir, filesOrDirs) { // for (var i = 0; i < filesOrDirs.length; i++) { // for (var j = 0; j < fileOrDir.name.length; j++) { // if (fileOrDir.name[j] > filesOrDirs[i].name[j]) break; // else if (fileOrDir.name[j] < filesOrDirs[i].name[j]) filesOrDirs.splice(i, 0, fileOrDir); // } // } filesOrDirs.push(fileOrDir); } function init() { projInfo.htmlPath = ''; projInfo.hotLoad = false; projInfo.webpack = false; projInfo.rootPath = ''; projInfo.devServer = false; projInfo.devServerScript = ''; projInfo.mainEntry = ''; projInfo.reactEntry = ''; projInfo.CRA = false; } // return file extension by file name - Ryan Yang function getFileExt(fileName) { // todo: handle special file names (eg. .gitignore .babelrc) let arr = fileName.split('.'); if (arr.length == 1) return ''; else return arr[arr.length - 1]; } // return css class by file extension - Ryan Yang function getCssClassByFileExt(ext) { switch (ext.toUpperCase()) { case 'JS': return 'seti-javascript'; case 'JSX': return 'seti-react'; case 'CSS': return 'seti-css'; case 'LESS': return 'seti-less'; case 'SASS': case 'SCSS': return 'seti-sass'; case 'JSON': return 'seti-json'; case 'SVG': return 'seti-svg'; case 'EOT': case 'WOFF': case 'WOFF2': case 'TTF': return 'seti-font'; case 'XML': return 'seti-xml'; case 'YML': return 'seti-yml'; case 'MD': return 'seti-markdown'; case 'HTML': return 'seti-html'; case 'JPG': case 'PNG': case 'GIF': case 'JPEG': return 'seti-image'; default: return 'octi-file-text'; } } //getTree is a function expression that takes in 2x arguments //A 'rootDirPath' and a callback const getTree = (rootDirPath, callback) => { //init resets the values in the projInfo object back to their default values init(); //rootPath property inside of projInfo object is reassigned to the inputted rootDirPath projInfo.rootPath = rootDirPath; //fileTree is assigned the object returned from invoking Director constructor //Object returned has the following properties: //path, type, name, opened, files, subdirectories, & id //The path.basename() methods returns the last portion of a path, in this instance, the folder name let fileTree = new Directory(rootDirPath, path.basename(rootDirPath), true); //I'm not sure what the purpose of pending is let pending = 1; //recurseThroughFileTree is called and passed the object that exists at fileTree function recurseThroughFileTree(directory) { //Loop through files and fill files property array //fs.readdir reads the contents of a directory //entire directory exists at directory.path fs.readdir(directory.path, (err, files) => { //I'm not sure what the purpose of pending is pending += files.length; //this conditional is assessing pending after it's decremented to see if it's a false/falsy value //should only be true after being decremented several times if (!--pending) { //if it is, we call writeFileSync and pass the file stored at projInfoPath //we write the stringified value of projInfo to whatever file exists at projInfoPath fs.writeFileSync(projInfoPath, JSON.stringify(projInfo)); //inputted callback to getTree is then fired and passed the fileTree object callback(fileTree); } //files is an array of files that exist in the directory passed to the fs.readdir method //forEach is used to iterate over that array files.forEach((file) => { //filePath uses path.join() to join the path and file names together const filePath = path.join(directory.path, file); //fs.stat is a method that checks for file details associated with the inputted file //if status is good, it's details are available at the 'stats' variable fs.stat(filePath, (err, stats) => { if (err) { //this conditional is assessing pending after it's decremented to see if it's a false/falsy value //should only be true after being decremented several times if (!--pending) { //if it is, we call writeFileSync and pass the file stored at projInfoPath //we write the stringified value of projInfo to whatever file exists at projInfoPath fs.writeFileSync(projInfoPath, JSON.stringify(projInfo)); //inputted callback to getTree is then fired and passed the fileTree object callback(fileTree); } } //checks if stats is true or truthy & stats.isFile() resolves to true if (stats && stats.isFile()) { //insertSorted pushes an object into the directory.files array //object pushed into the array has the following parameters: //path, type, name, ext, id insertSorted(new File(filePath, file, getFileExt), directory.files); //checks if the filePath is the same as the resolved value as path.join(...) & if the file contains the text of webpack.config.js if (filePath === path.join(projInfo.rootPath, file) && file.search(/webpack.config.js/) !== -1) { //if it does, then we invoke the readFile method to access the data in the file fs.readFile(filePath, { encoding: 'utf-8' }, (err, data) => { //created a regExp to check for a pattern that matches entry... const regExp = new RegExp('entry(.*?),', 'g'); //file is stringified and then searched for the match assigned to the regExp let entry = JSON.stringify(data).match(regExp); //????? let reactEntry = String(entry[0].split('\'')[1]); //reactEntry property inside of the projInfo object is updated to the resolved value of path.join(...) projInfo.reactEntry = path.join(projInfo.rootPath, reactEntry); }) } //look for index.html not in node_modules, get path if (!projInfo.htmlPath && filePath.search(/.*node\_modules.*/) === -1 && file.search(/.*index\.html/) !== -1) { projInfo.htmlPath = filePath; } //look for package.json and see if webpack is installed and react-dev-server is installed else if (!projInfo.webpack && file.search(/package.json/) !== -1 && filePath === path.join(projInfo.rootPath, file)) { //if projInfo.webpack is false, the file contains package.json, and the filePath matches the resolved value of projInfo.rootPath & file, readFile is invoked and passed the filePath variable fs.readFile(filePath, { encoding: 'utf-8' }, (err, data) => { //data is parsed into a JS object data = JSON.parse(data); //checks if the parsed object has a property of react-scripts if (data.dependencies['react-scripts']) { //if it does, the property of devServerScript is reassigned to 'start' projInfo.devServerScript = 'start', //if it does, the property of CRA is reassigned to 'true' projInfo.CRA = true; //checks if the parsed object has a property of webpack-dev-server } else if (data.devDependencies['webpack-dev-server']) { //if it does, the property of devServerScript is reassigned to 'run dev-server' projInfo.devServerScript = 'run dev-server'; // console.log(projInfo.devServerScript, '$$$') } //checks if data.main is true or truthy if (data.main) { //if it is, the mainEntry property is reassigned to the resolved value of path.join(...) projInfo.mainEntry = path.join(filePath, data.main); } }) } //this conditional is assessing pending after it's decremented to see if it's a false/falsy value //should only be true after being decremented several times if (!--pending) { //if it is, we call writeFileSync and pass the file stored at projInfoPath //we write the stringified value of projInfo to whatever file exists at projInfoPath fs.writeFileSync(projInfoPath, JSON.stringify(projInfo)); //inputted callback to getTree is then fired and passed the fileTree object callback(fileTree); } } //checks if stats is true or truthy else if (stats) { //if it is, a const variable is declared and assigned the resolved value of invoking the Diretory constructor and passing it the filePath and file variables const subdirectory = new Directory(filePath, file); //put directories in front insertSorted(subdirectory, directory.subdirectories); recurseThroughFileTree(subdirectory); } }) }) }) } //calls recurseThroughFileTree on the newly found subdirectory recurseThroughFileTree(fileTree); return fileTree; } module.exports = { getTree, getCssClassByFileExt, getFileExt };
/** @module ember @submodule ember-testing */ import { checkWaiters } from '../test/waiters'; import RSVP from 'ember-runtime/ext/rsvp'; import run from 'ember-metal/run_loop'; import { pendingRequests } from '../test/pending_requests'; /** Causes the run loop to process any pending events. This is used to ensure that any async operations from other helpers (or your assertions) have been processed. This is most often used as the return value for the helper functions (see 'click', 'fillIn','visit',etc). Example: ```javascript Ember.Test.registerAsyncHelper('loginUser', function(app, username, password) { visit('secured/path/here') .fillIn('#username', username) .fillIn('#password', password) .click('.submit') return app.testHelpers.wait(); }); @method wait @param {Object} value The value to be returned. @return {RSVP.Promise} @public */ export default function wait(app, value) { return new RSVP.Promise(function(resolve) { let router = app.__container__.lookup('router:main'); // Every 10ms, poll for the async thing to have finished let watcher = setInterval(() => { // 1. If the router is loading, keep polling let routerIsLoading = router.router && !!router.router.activeTransition; if (routerIsLoading) { return; } // 2. If there are pending Ajax requests, keep polling if (pendingRequests()) { return; } // 3. If there are scheduled timers or we are inside of a run loop, keep polling if (run.hasScheduledTimers() || run.currentRunLoop) { return; } if (checkWaiters()) { return; } // Stop polling clearInterval(watcher); // Synchronously resolve the promise run(null, resolve, value); }, 10); }); }
define(['./transpiled/BootstrapMixin'], function (BootstrapMixin) { return BootstrapMixin.default; })
const m = require('mithril'); const Component = require('../../core/Component'); class SocialLink extends Component { view(vnode) { return m('li.social-link', [ m('a', { href: vnode.attrs.url, target: "_blank" }, [ m('i', { class: "fa fa-fw fa-2x " + vnode.attrs.icon }), ]) ]) } } module.exports = SocialLink;
/** * container组件 */ import React from 'react'; /** * Usage: * import {Container} from 'chameleon'; * * React.createClass({ * render() { * return ( * <Container> * </Container> * ); * } * }); */ export default React.createClass({ getDefaultProps() { return { fluid: false //类用于 100% 宽度,占据全部视口(viewport)的容器 }; }, render() { let fluid = this.props.fluid; return ( <div className={fluid ? 'container-fluid' : 'container'}> {this.props.children} </div> ); } });
import constants from './constants'; const keys = constants.taskKeys; export default ({ hasServer, hasClient, hasPackages }) => { const tasks = [{ /* Lint server code and build all Server artifacts to dist/ folder */ key: keys.buildServer, dependencies: [ keys.createEnvSettings, keys.createPackageJson, keys.compileServer, keys.copyServerViews, keys.copyFonts, keys.sassServer ] }, { /* Lint client code and bundle all code, dependencies and artifacts to bundle.js */ key: keys.buildClient, dependencies: [ keys.bundleClient ] }, { /* Lint packages code and compile all to dist/packages */ key: keys.buildPackages, dependencies: [keys.compilePackages] }, { /* Lint and build everything */ key: keys.buildAll, dependencies: [] }, { /* Full clean and rebuild everything */ key: keys.buildFull, sequence: [keys.clean, keys.buildAll, keys.finalise] }, { /* Incremental build of everything */ key: keys.buildIncremental, sequence: [keys.buildAll] }, { /* Build only static assets (for public folder) */ key: keys.buildStatic, dependencies: [keys.copyFonts, keys.sassServer] }]; const buildAllDeps = tasks[3].dependencies; if (hasServer) { buildAllDeps.push(constants.taskKeys.buildServer); } else { buildAllDeps.push(constants.taskKeys.copyFonts); buildAllDeps.push(constants.taskKeys.sassServer); } if (hasClient) { buildAllDeps.push(constants.taskKeys.buildClient); } if (hasPackages) { buildAllDeps.push(constants.taskKeys.buildPackages); } return tasks; };
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M9.4 16.6L4.8 12l4.6-4.6L8 6l-6 6 6 6 1.4-1.4zm5.2 0l4.6-4.6-4.6-4.6L16 6l6 6-6 6-1.4-1.4z" /> , 'CodeOutlined');
(function () { 'use strict'; describe('Employeeprofiles Controller Tests', function () { // Initialize global variables var EmployeeprofilesController, $scope, $httpBackend, $state, Authentication, EmployeeprofilesService, mockEmployeeprofile; // The $resource service augments the response object with methods for updating and deleting the resource. // If we were to use the standard toEqual matcher, our tests would fail because the test values would not match // the responses exactly. To solve the problem, we define a new toEqualData Jasmine matcher. // When the toEqualData matcher compares two objects, it takes only object properties into // account and ignores methods. beforeEach(function () { jasmine.addMatchers({ toEqualData: function (util, customEqualityTesters) { return { compare: function (actual, expected) { return { pass: angular.equals(actual, expected) }; } }; } }); }); // Then we can start by loading the main application module beforeEach(module(ApplicationConfiguration.applicationModuleName)); // The injector ignores leading and trailing underscores here (i.e. _$httpBackend_). // This allows us to inject a service but then attach it to a variable // with the same name as the service. beforeEach(inject(function ($controller, $rootScope, _$state_, _$httpBackend_, _Authentication_, _EmployeeprofilesService_) { // Set a new global scope $scope = $rootScope.$new(); // Point global variables to injected services $httpBackend = _$httpBackend_; $state = _$state_; Authentication = _Authentication_; EmployeeprofilesService = _EmployeeprofilesService_; // create mock Employeeprofile mockEmployeeprofile = new EmployeeprofilesService({ _id: '525a8422f6d0f87f0e407a33', name: 'Employeeprofile Name' }); // Mock logged in user Authentication.user = { roles: ['user'] }; // Initialize the Employeeprofiles controller. EmployeeprofilesController = $controller('EmployeeprofilesController as vm', { $scope: $scope, employeeprofileResolve: {} }); // Spy on state go spyOn($state, 'go'); })); describe('vm.save() as create', function () { var sampleEmployeeprofilePostData; beforeEach(function () { // Create a sample Employeeprofile object sampleEmployeeprofilePostData = new EmployeeprofilesService({ name: 'Employeeprofile Name' }); $scope.vm.employeeprofile = sampleEmployeeprofilePostData; }); it('should send a POST request with the form input values and then locate to new object URL', inject(function (EmployeeprofilesService) { // Set POST response $httpBackend.expectPOST('api/employeeprofiles', sampleEmployeeprofilePostData).respond(mockEmployeeprofile); // Run controller functionality $scope.vm.save(true); $httpBackend.flush(); // Test URL redirection after the Employeeprofile was created expect($state.go).toHaveBeenCalledWith('employeeprofiles.view', { employeeprofileId: mockEmployeeprofile._id }); })); it('should set $scope.vm.error if error', function () { var errorMessage = 'this is an error message'; $httpBackend.expectPOST('api/employeeprofiles', sampleEmployeeprofilePostData).respond(400, { message: errorMessage }); $scope.vm.save(true); $httpBackend.flush(); expect($scope.vm.error).toBe(errorMessage); }); }); describe('vm.save() as update', function () { beforeEach(function () { // Mock Employeeprofile in $scope $scope.vm.employeeprofile = mockEmployeeprofile; }); it('should update a valid Employeeprofile', inject(function (EmployeeprofilesService) { // Set PUT response $httpBackend.expectPUT(/api\/employeeprofiles\/([0-9a-fA-F]{24})$/).respond(); // Run controller functionality $scope.vm.save(true); $httpBackend.flush(); // Test URL location to new object expect($state.go).toHaveBeenCalledWith('employeeprofiles.view', { employeeprofileId: mockEmployeeprofile._id }); })); it('should set $scope.vm.error if error', inject(function (EmployeeprofilesService) { var errorMessage = 'error'; $httpBackend.expectPUT(/api\/employeeprofiles\/([0-9a-fA-F]{24})$/).respond(400, { message: errorMessage }); $scope.vm.save(true); $httpBackend.flush(); expect($scope.vm.error).toBe(errorMessage); })); }); describe('vm.remove()', function () { beforeEach(function () { // Setup Employeeprofiles $scope.vm.employeeprofile = mockEmployeeprofile; }); it('should delete the Employeeprofile and redirect to Employeeprofiles', function () { // Return true on confirm message spyOn(window, 'confirm').and.returnValue(true); $httpBackend.expectDELETE(/api\/employeeprofiles\/([0-9a-fA-F]{24})$/).respond(204); $scope.vm.remove(); $httpBackend.flush(); expect($state.go).toHaveBeenCalledWith('employeeprofiles.list'); }); it('should should not delete the Employeeprofile and not redirect', function () { // Return false on confirm message spyOn(window, 'confirm').and.returnValue(false); $scope.vm.remove(); expect($state.go).not.toHaveBeenCalled(); }); }); }); }());
define(['app', 'Backbone', 'dom'], function(app, Backbone, $) { return Backbone.View.extend({ tagName: 'article', className: 'issueList table', build: function() { return this; }, render: function() { return this; } }); });
'use strict'; const fs = require('fs'); const chalk = require('chalk'); const util = require('../util'); /** * The config object sets and gets the ./config/config.json * file locally and remotely. This file is used to ensure * we always know the URL for the remote docs, in case it * changes in the future. * * It also syncs the last update of the index.json file, * which in turn knows when all docs were last updated, * and so keeps the remote repo's docs and local docs * in sync. */ const config = { _config: undefined, _staticConfig: undefined, getStatic() { const self = this; let config; try { config = JSON.parse(fs.readFileSync(self.app.clerk.paths.static.config, {encoding: 'utf-8'})); this._staticConfig = config; /* istanbul ignore next */ } catch (e) { console.log(chalk.yellow(`\n\nHouston, we have a problem.\nWat can\'t read its static config file, which should be at ${this.app.clerk.paths.static.config}. Without this, Wat can\'t do much. Try re-installing Wat from scratch.\n\nIf that doesn\'t work, please file an issue.\n`)); throw new Error(e); } const tempStatic = this._staticConfig || {}; self.app.clerk.paths.remote.docs = tempStatic.remoteDocUrl || self.app.clerk.paths.remote.docs; self.app.clerk.paths.remote.autodocs = tempStatic.remoteAutodocUrl || self.app.clerk.paths.remote.autodocs; self.app.clerk.paths.remote.config = tempStatic.remoteConfigUrl || self.app.clerk.paths.remote.config; self.app.clerk.paths.remote.archive = tempStatic.remoteArchiveUrl || self.app.clerk.paths.remote.archive; return config; }, getLocal() { let config; if (!this._config) { try { config = JSON.parse(fs.readFileSync(this.app.clerk.paths.temp.config, {encoding: 'utf-8'})); this._config = config; } catch (e) { /* istanbul ignore next */ this._config = this.getStatic(); } } else { config = this._config; } return config; }, getRemote(callback) { callback = callback || function () {}; const self = this; const url = `${self.app.clerk.paths.remote.config}config.json`; util.fetchRemote(url, function (err, data) { if (!err) { try { const json = JSON.parse(data); callback(undefined, json); /* istanbul ignore next */ } catch (e) { callback(`Error parsing json: ${data}, Error: ${e}, url: ${url}`); } } else { /* istanbul ignore next */ callback(err); } }); }, setLocal(key, value) { const self = this; if (key && value) { this._config[key] = value; } fs.writeFileSync(self.app.clerk.paths.temp.config, JSON.stringify(this._config, null, ' ')); }, setStatic(key, value) { const self = this; if (key && value) { this._staticConfig[key] = value; } fs.writeFileSync(self.app.clerk.paths.static.config, JSON.stringify(this._staticConfig, null, ' ')); }, writeLocal(data) { data = data || this._config; this._config = data; fs.writeFileSync(this.app.clerk.paths.temp.config, JSON.stringify(data)); return this; } }; module.exports = function (app) { config.app = app; return config; };
/* * Created by orion on 12-06-15. */ 'use strict'; angular.module('myApp.util', []) .service('Util', function Util() { this.stripAfterSlash = function(s) { var pos = s.lastIndexOf('/'); if (pos === -1 || pos === s.length - 1) { return s; } return s.substr(0, pos + 1); }; this.stripBeforeSlash = function(s) { var pos = s.lastIndexOf('/'), toMatch; if (pos === -1) { return s; } toMatch = s.substr(pos + 1);//console.log(toMatch); return toMatch; }; //http://webdesign.about.com/library/bl_url_encoding_table.htm this.mapCoding = { '%28': '(', '%29': ')', '%7B': '{', '%7C': '|', '%3D': '=', '%27': '\'', '%3B': ';', '%3C': '<', '%3E': '>', '%2B': '+', '%7D': '}', '%3F': '?', '%26': '$', '%3A': ':', '%2F': '/', '%23': '#', '%24': '&', '%40': '%', '%20': ' ', '%2C': ',', '%25': '~', '%5E': '^', '%60': '`', '%5C': '\\', '%5B': '[', '%5D': ']', '%22': '"' //'\+': ' ' }; this.mapHooks = { '\\(': '<i>(</i>', '\\)': '<i>)</i>', '\\[': '<a>[</a>', '\\]': '<a>]</a>', '\\n': '<br>' }; this.replaceAll = function (str, mapObj) { var result = str; angular.forEach(mapObj, function (value, key) { //noinspection JSCheckFunctionSignatures result = result.replace(new RegExp(key, "gi"), value); }); return result; }; this.markHooks = function (s) { return this.replaceAll(s, this.mapHooks); }; this.urldecode = function (html) { return this.replaceAll(html, this.mapCoding); }; });
import 'babel-polyfill'; import React from 'react'; import {render} from 'react-dom'; import {Provider} from 'react-redux'; import {Router, hashHistory} from 'react-router'; import {syncHistoryWithStore} from 'react-router-redux'; import routes from './routes'; import configureStore from './store/configureStore'; import './app.global.css'; import './css/photon.css'; const store = configureStore(); const history = syncHistoryWithStore(hashHistory, store); render( <div className="window"> <Provider store={store}> <Router history={history} routes={routes}/> </Provider> </div>, document.getElementById('root') );
/* React */ import { render, unmountComponentAtNode } from 'react-dom' import Rtu from 'react-dom/test-utils' import React from 'react' /* Components to test */ import Element from '../components/Element.js'; import Link from '../components/Link.js'; import events from '../mixins/scroll-events.js'; /* Test */ import expect from 'expect'; import assert from 'assert'; import sinon from 'sinon'; import { renderHorizontal } from './utility.js'; const wait = (ms, cb) => { setTimeout(cb, ms); } describe('Page', () => { let node; let scrollDuration = 10; const component = (horizontal) => { const style = (() => { if (horizontal) { return { display: 'flex', flexDirection: 'row', flexWrap: 'nowrap' } } else { return undefined } })() const lastDivStyle = (() => { if (horizontal) { return { width: "2000px" } } else { return { height: "2000px" } } })() return ( <div style={style}> <ul> <li><Link to="test1" spy={true} smooth={true} duration={scrollDuration} horizontal={horizontal}>Test 1</Link></li> <li><Link to="test2" spy={true} smooth={true} duration={scrollDuration} horizontal={horizontal}>Test 2</Link></li> <li><Link to="test3" spy={true} smooth={true} duration={scrollDuration} horizontal={horizontal}>Test 3</Link></li> <li><Link to="test4" spy={true} smooth={true} duration={scrollDuration} horizontal={horizontal}>Test 4</Link></li> <li><Link to="test5" spy={true} smooth={true} duration={scrollDuration} horizontal={horizontal}>Test 5</Link></li> <li><Link to="test6" spy={true} smooth={true} duration={scrollDuration} horizontal={horizontal}>Test 6</Link></li> </ul> <Element name="test1" className="element">test 1</Element> <Element name="test2" className="element">test 2</Element> <Element name="test3" className="element">test 3</Element> <Element name="test4" className="element">test 4</Element> <Element name="test5" className="element">test 5</Element> <div id="test6" className="element" style={lastDivStyle}>test 6</div> </div> ) } beforeEach(() => { node = document.createElement('div'); document.body.appendChild(node) }); afterEach(function () { window.scrollTo(0, 0); events.scrollEvent.remove('begin'); events.scrollEvent.remove('end'); unmountComponentAtNode(node) document.body.removeChild(node); }); it('renders six elements of link/element', (done) => { render(component(false), node, () => { var allLinks = node.querySelectorAll('a'); var allTargets = node.querySelectorAll('.element'); expect(allLinks.length).toEqual(6); expect(allTargets.length).toEqual(6); done(); }); }) it('it is at top left in start', (done) => { expect(window.scrollX || window.pageXOffset).toEqual(0); expect(window.scrollY || window.pageYOffset).toEqual(0); done(); }); it('is active when clicked vertically', (done) => { render(component(false), node, () => { var link = node.querySelectorAll('a')[2]; var target = node.querySelectorAll('.element')[2]; var expectedScrollTo = target.getBoundingClientRect().top; Rtu.Simulate.click(link); var scrollStart = window.scrollY || window.pageYOffset; /* Let it scroll, duration is based on param sent to Link */ setTimeout(() => { var scrollStop = Math.round(scrollStart + expectedScrollTo) expect(window.scrollY || window.pageYOffset).toEqual(scrollStop); expect(link.className).toEqual('active'); done(); }, scrollDuration + 500); }); }) it('is active when clicked horizontally', (done) => { renderHorizontal(component(true), node, () => { var link = node.querySelectorAll('a')[2]; var target = node.querySelectorAll('.element')[2]; var expectedScrollTo = target.getBoundingClientRect().left; Rtu.Simulate.click(link); var scrollStart = window.scrollX || window.pageXOffset; /* Let it scroll, duration is based on param sent to Link */ setTimeout(() => { var scrollStop = Math.round(scrollStart + expectedScrollTo) expect(window.scrollX || window.pageXOffset).toEqual(scrollStop); expect(link.className).toEqual('active'); done(); }, scrollDuration + 500); }); }) it('is active when clicked to last (5) element vertically', (done) => { render(component(false), node, () => { var link = node.querySelectorAll('a')[5]; var target = node.querySelectorAll('.element')[5]; var expectedScrollTo = target.getBoundingClientRect().top; Rtu.Simulate.click(link); /* Let it scroll, duration is based on param sent to Link */ var scrollStart = window.scrollY || window.pageYOffset; setTimeout(() => { var scrollStop = Math.round(scrollStart + expectedScrollTo) expect(window.scrollY || window.pageYOffset).toEqual(scrollStop); expect(link.className).toEqual('active'); done(); }, scrollDuration + 500); }); }) it('is active when clicked to last (5) element horizontally', (done) => { renderHorizontal(component(true), node, () => { var link = node.querySelectorAll('a')[5]; var target = node.querySelectorAll('.element')[5]; var expectedScrollTo = target.getBoundingClientRect().left; Rtu.Simulate.click(link); /* Let it scroll, duration is based on param sent to Link */ var scrollStart = window.scrollX || window.pageXOffset; setTimeout(() => { var scrollStop = Math.round(scrollStart + expectedScrollTo) expect(window.scrollX || window.pageXOffset).toEqual(scrollStop); expect(link.className).toEqual('active'); done(); }, scrollDuration + 500); }); }) it('should call onSetActive vertically', (done) => { let onSetActive = sinon.spy(); let onSetInactive = sinon.spy(); let component = <div> <ul> <li><Link to="test1" spy={true} smooth={true} duration={scrollDuration}>Test 1</Link></li> <li><Link to="test2" spy={true} smooth={true} duration={scrollDuration}>Test 2</Link></li> <li><Link to="test3" spy={true} smooth={true} duration={scrollDuration}>Test 3</Link></li> <li><Link to="test4" spy={true} smooth={true} duration={scrollDuration} onSetActive={onSetActive} onSetInactive={onSetInactive}>Test 4</Link></li> <li><Link to="test5" spy={true} smooth={true} duration={scrollDuration}>Test 5</Link></li> <li><Link to="anchor" spy={true} smooth={true} duration={scrollDuration}>Test 6</Link></li> </ul> <Element name="test1" className="element">test 1</Element> <Element name="test2" className="element">test 2</Element> <Element name="test3" className="element">test 3</Element> <Element name="test4" className="element">test 4</Element> <Element name="test5" className="element">test 5</Element> <div id="anchor" className="element" style={{ height: "2000px" }}>test 6</div> </div> render(component, node); var link = node.querySelectorAll('a')[3]; Rtu.Simulate.click(link); wait(scrollDuration + 500, () => { expect(onSetActive.calledOnce).toEqual(true); link = node.querySelectorAll('a')[4]; Rtu.Simulate.click(link); wait(scrollDuration + 500, () => { expect(onSetInactive.calledOnce).toEqual(true); done(); }) }) }); it('should call onSetActive horizontally', (done) => { let onSetActive = sinon.spy(); let onSetInactive = sinon.spy(); let component = <div style={{ display: 'flex', flexDirection: 'row', flexWrap: 'nowrap' }}> <ul> <li><Link to="test1" spy={true} smooth={true} duration={scrollDuration} horizontal={true}>Test 1</Link></li> <li><Link to="test2" spy={true} smooth={true} duration={scrollDuration} horizontal={true}>Test 2</Link></li> <li><Link to="test3" spy={true} smooth={true} duration={scrollDuration} horizontal={true}>Test 3</Link></li> <li><Link to="test4" spy={true} smooth={true} duration={scrollDuration} onSetActive={onSetActive} onSetInactive={onSetInactive} horizontal={true}>Test 4</Link></li> <li><Link to="test5" spy={true} smooth={true} duration={scrollDuration} horizontal={true}>Test 5</Link></li> <li><Link to="anchor" spy={true} smooth={true} duration={scrollDuration} horizontal={true}>Test 6</Link></li> </ul> <Element name="test1" className="element">test 1</Element> <Element name="test2" className="element">test 2</Element> <Element name="test3" className="element">test 3</Element> <Element name="test4" className="element">test 4</Element> <Element name="test5" className="element">test 5</Element> <div id="anchor" className="element" style={{ width: "2000px" }}>test 6</div> </div> renderHorizontal(component, node); var link = node.querySelectorAll('a')[3]; Rtu.Simulate.click(link); wait(scrollDuration + 500, () => { expect(onSetActive.calledOnce).toEqual(true); link = node.querySelectorAll('a')[4]; Rtu.Simulate.click(link); wait(scrollDuration + 500, () => { expect(onSetInactive.calledOnce).toEqual(true); done(); }) }) }); });
import Ember from 'ember'; export function formatDate(params, hash) { return { params, hash }; } export default Ember.Helper.helper(formatDate);
export const FRAME_TYPE_NORMAL = 'normal'; export const FRAME_TYPE_STRIKE = 'strike'; export const FRAME_TYPE_SPARE = 'spare'; function detectType(roll1, roll2) { if (roll1 + roll2 > 10) { throw new Error('Invalid frame roll total'); } if (roll1 == 10) { return FRAME_TYPE_STRIKE; } if (roll1 + roll2 === 10) { return FRAME_TYPE_SPARE; } return FRAME_TYPE_NORMAL; } class Frame { constructor(roll1, roll2) { this.roll1 = roll1 || 0; this.roll2 = roll2 || 0; this.type = detectType(roll1, roll2); this.bonusPoints = 0; } getScore() { return this.roll1 + this.roll2 + this.bonusPoints; } } export default Frame;
import React, { Component } from 'react'; import reactMixin from 'react-mixin'; import {handleForms} from '../../components/Forms/FormDecorator'; import UserForms from '../../components/Users/UserForms.js'; import styles from './forgotReset.css'; @handleForms export default class ForgotPasswordRoute extends React.Component { constructor() { super(); this.handleSubmit = this.handleSubmit.bind(this); this.listenForEnter = this.listenForEnter.bind(this); this.state = { shakeBtn: false }; } render() { const inputsToUse = ["email"]; return ( <div className={styles.wrapper}> <h2 className={styles.title}>Recover your Password</h2> <h6 className={styles.subtitle}>Enter your email to reset your password</h6> <UserForms buttonText="Reset my Password" inputsToUse={inputsToUse} inputState={this.props.inputState} shakeBtn={this.state.shakeBtn} handleChange={this.props.handleChange} handleSubmit={this.handleSubmit} /> </div> ) } componentDidMount() { window.onkeydown = this.listenForEnter; } listenForEnter(e) { e = e || window.event; if (e.keyCode === 13) { e.preventDefault(); this.handleSubmit(); } } handleSubmit() { let errors = this.props.inputState.errors let values = this.props.inputState.values const {email} = values; //if errors showing don't submit if (_.some(errors, function(str){ return str !== '' && str !== undefined; })) { this.props.showToast('You have errors showing', 'error') this.setState({ shakeBtn: true }); window.setTimeout(() => { this.setState({ shakeBtn: false }); }, 1000); return false; } //if any values missing showing don't submit if (Object.keys(values).length < 1) { this.props.showToast('Please fill out all fields', 'error') this.setState({ shakeBtn: true }); window.setTimeout(() => { this.setState({ shakeBtn: false }); }, 1000); return false; } Accounts.forgotPassword({email: email}, (error) => { if (error) { this.props.showToast(error.reason, 'error') this.setState({ shakeBtn: true }); window.setTimeout(() => { this.setState({ shakeBtn: false }); }, 1000); return; } else { this.props.showToast('<h3>Success!</h3> <p>Please check your inbox for the link to finish resetting your password.</p>', 'success') } }); } }
/** 页面组件出口 **/ // 项目公共样式 import './style.less' // 导入页面组件 import Home from './Home/Home.jsx' import Counter from './Counter/Counter.jsx' import RouterDemo from './RouterDemo/RouterDemo.jsx' import NotFoundPage from './NotFoundPage/NotFoundPage.jsx' import Md5 from './Md5/Md5.jsx' import Bodymovin from './Bodymovin/Bodymovin.jsx' export { Home, Counter, RouterDemo, NotFoundPage, Md5, Bodymovin }
if (typeof define !== 'function') {var define = require('amdefine')(module)} /** * @module smpl * @submodule smpl.dom * @class smpl.dom * @static */ define(['./smpl.core'], function(smpl) { smpl.dom = {}; /** * Test if a `HTMLElement` as a given class * * @method hasClass * * @param {HTMLElement} ele `HTMLElement` to test on * @param {String} cls class to test * @return {Boolean} true if the `HTMLElement` has the class, false otherwise */ smpl.dom.hasClass = function(ele, cls) { return (' ' + ele.className + ' ').indexOf(' ' + cls + ' ') !== -1; }; /** * Add a class to a `HTMLElement` * * @method addClass * * @param {HTMLElement} ele `HTMLElement` to add the class to * @param {String} cls class to add * @return {Boolean} true if the class was added, false if it was already there */ smpl.dom.addClass = function(ele, cls) { if (!smpl.dom.hasClass(ele, cls)) { ele.className += ' ' + cls; return true; } return false; }; /** * Remove a class from a `HTMLElement` * * @method removeClass * * @param {HTMLElement} ele `HTMLElement` to remove the class from * @param {String} cls class to remove * @return {Boolean} true if the class was removed, false if it was not there */ smpl.dom.removeClass = function(ele, cls) { var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)'), className = ele.className; ele.className = className.replace(reg, ' '); return ele.className !== className; }; /** * Toggle a class on a `HTMLElement` * * @method toggleClass * * @param {HTMLElement} ele `HTMLElement` to toggle the class on * @param {String} cls class to toggle * @return {Boolean} true if the class was added, false if it was removed */ smpl.dom.toggleClass = function(ele, cls) { if (!smpl.dom.removeClass(ele, cls)) { ele.className += ' ' + cls; return true; } return false; }; /** * Simple method to stop an event. * * @method stopEvent */ smpl.dom.stopEvent = function(e) { e.preventDefault(); if (e.stopImmediatePropagation) { e.stopImmediatePropagation(); } else { e.stopPropagation(); } }; smpl.dom.stopEventPropagation = function(e) { e.stopPropagation(); }; return smpl; });
const makeConfig = require('./webpack/build'); const webpack = require('webpack'); const rimraf = require('rimraf'); const path = require('path'); const ALLOWED_MODES = { DEBUG: false, DIST: true, PROD: true, }; const BUILD_MODE = process.env.MODE; if (!(BUILD_MODE && ALLOWED_MODES[BUILD_MODE])) { console.log('Build mode was not defined.'); process.abort(); } const buildPath = path.join(__dirname, BUILD_MODE.toLowerCase()); function build() { const webpackConfig = makeConfig({ BUILD_MODE, IS_DEV: false, }); webpackConfig.output = { path: buildPath, filename: 'frassets/[name].bundle.[chunkhash].js', chunkFilename: 'frassets/[id].bundle.[chunkhash].js', }; webpack(webpackConfig, err => { if (err) { throw new Error(err); } console.log('Project build is complete'); }); } rimraf(buildPath, build);
class x509enrollment_cx509attribute_1 { constructor() { // string RawData (EncodingType) {get} this.Parameterized = undefined; // IObjectId ObjectId () {get} this.ObjectId = undefined; } // void Initialize (IObjectId, EncodingType, string) Initialize(IObjectId, EncodingType, string) { } } module.exports = x509enrollment_cx509attribute_1;
function User() { this.render(); this.a1(); } User.prototype = { render: function () { var config = this.a1(); var data = this.a2(); document.body.innerHTML = 'template + ' + JSON.stringify(data); }, a1: function () { console.log('a1'); }, a2: function () { console.log('a2'); } };
/** * Created by ovolodin on 12.05.2017. */ describe('userList', function() { // Load the module that contains the `phoneList` component before each test beforeEach(module('usersApp')); beforeEach(module('userList')); // Test the controller describe('UserListController', function() { var $httpBackend, ctrl; // The injector ignores leading and trailing underscores here (i.e. _$httpBackend_). // This allows us to inject a service and assign it to a variable with the same name // as the service while avoiding a name conflict. beforeEach(inject(function($componentController, _$httpBackend_) { $httpBackend = _$httpBackend_; $httpBackend.expectGET('api/users.json') .respond([{name: 'Bridget Valentine'}, {name: 'Galloway Bailey'}]); ctrl = $componentController('userList'); })); it('should create a `users` property with 2 users fetched with `$http`', function() { expect(ctrl.users).toBeUndefined(); $httpBackend.flush(); expect(ctrl.users).toEqual([{name: 'Bridget Valentine'}, {name: 'Galloway Bailey'}]); }); it('should set a default value for the `orderProp` property', function() { expect(ctrl.orderProp).toBe('age'); }); }); });
/** * @fileoverview Tests for no-empty-label rule. * @author Ilya Volodin */ //------------------------------------------------------------------------------ // Requirements //------------------------------------------------------------------------------ var eslintTester = require("../../../lib/tests/eslintTester"); //------------------------------------------------------------------------------ // Tests //------------------------------------------------------------------------------ eslintTester.addRuleTest("no-empty-label", { valid: [ "labeled: for (var i=10; i; i--) { }", "labeled: while(i) {}", "labeled: do {} while (i)", "labeled: switch(i) { case 1: break; default: break; }" ], invalid: [ { code: "labeled: var a = 10;", errors: [{ message: "Unexpected label labeled", type: "LabeledStatement"}] } ] });
jQuery.extend({ handleError: function( s, xhr, status, e ) { // If a local callback was specified, fire it if ( s.error ) { s.error.call( s.context || s, xhr, status, e ); } // Fire the global callback if ( s.global ) { (s.context ? jQuery(s.context) : jQuery.event).trigger( "ajaxError", [xhr, s, e] ); } }, createUploadIframe: function(id, uri) { var frameId = 'jUploadFrame' + id; if(window.ActiveXObject) { if(jQuery.browser.version=="9.0") { io = document.createElement('iframe'); io.id = frameId; io.name = frameId; } else if(jQuery.browser.version=="6.0" || jQuery.browser.version=="7.0" || jQuery.browser.version=="8.0") { var io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '" />'); if(typeof uri== 'boolean'){ io.src = 'javascript:false'; } else if(typeof uri== 'string'){ io.src = uri; } } } else { var io = document.createElement('iframe'); io.id = frameId; io.name = frameId; } io.style.position = 'absolute'; io.style.top = '-1000px'; io.style.left = '-1000px'; document.body.appendChild(io); return io; }, ajaxUpload:function(s,xml){ //if((fromFiles.nodeType&&!((fileList=fromFiles.files)&&fileList[0].name))) var uid = new Date().getTime(),idIO='jUploadFrame'+uid,_this=this; var jIO=$('<iframe name="'+idIO+'" id="'+idIO+'" style="display:none">').appendTo('body'); var jForm=$('<form action="'+s.url+'" target="'+idIO+'" method="post" enctype="multipart/form-data"></form>').appendTo('body'); var oldElement = $('#'+s.fileElementId); var newElement = $(oldElement).clone(); $(oldElement).attr('id', 'jUploadFile'+uid); $(oldElement).before(newElement); $(oldElement).appendTo(jForm); this.remove=function() { if(_this!==null) { jNewFile.before(jOldFile).remove(); jIO.remove();jForm.remove(); _this=null; } } this.onLoad=function(){ var data=$(jIO[0].contentWindow.document.body).text(); try{ if(data!=undefined){ data = eval('(' + data + ')'); try { if (s.success) s.success(data, status); // Fire the global callback if(s.global) jQuery.event.trigger("ajaxSuccess", [xml, s]); if (s.complete) s.complete(data, status); xml = null; } catch(e) { status = "error"; jQuery.handleError(s, xml, status, e); } // The request was completed if(s.global) jQuery.event.trigger( "ajaxComplete", [xml, s] ); // Handle the global AJAX counter if (s.global && ! --jQuery.active ) jQuery.event.trigger("ajaxStop"); // Process result } }catch(ex){ alert(ex.message); }; } this.start=function(){jForm.submit();jIO.load(_this.onLoad);}; return this; }, createUploadForm: function(id, url,fileElementId, data) { //create form var formId = 'jUploadForm' + id; var fileId = 'jUploadFile' + id; var form = jQuery('<form action="'+url+'" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>'); if(data) { for(var i in data) { jQuery('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendTo(form); } } var oldElement = jQuery('#' + fileElementId); var newElement = jQuery(oldElement).clone(); jQuery(oldElement).attr('id', fileId); jQuery(oldElement).before(newElement); jQuery(oldElement).appendTo(form); //set attributes jQuery(form).css('position', 'absolute'); jQuery(form).css('top', '-1200px'); jQuery(form).css('left', '-1200px'); jQuery(form).appendTo('body'); return form; }, ajaxFileUpload: function(s) { // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout // Create the request object var xml = {}; s = jQuery.extend({}, jQuery.ajaxSettings, s); if(window.ActiveXObject){ var upload = new jQuery.ajaxUpload(s,xml); upload.start(); }else{ var id = new Date().getTime(); var form = jQuery.createUploadForm(id,s.url, s.fileElementId, (typeof(s.data)=='undefined'?false:s.data)); var io = jQuery.createUploadIframe(id, s.secureuri); var frameId = 'jUploadFrame' + id; var formId = 'jUploadForm' + id; // Watch for a new set of requests if ( s.global && ! jQuery.active++ ) { jQuery.event.trigger( "ajaxStart" ); } var requestDone = false; if ( s.global ) jQuery.event.trigger("ajaxSend", [xml, s]); // Wait for a response to come back var uploadCallback = function(isTimeout) { var io = document.getElementById(frameId); try { if(io.contentWindow) { xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null; xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document; }else if(io.contentDocument) { xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null; xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document; } }catch(e) { jQuery.handleError(s, xml, null, e); } if ( xml || isTimeout == "timeout") { requestDone = true; var status; try { status = isTimeout != "timeout" ? "success" : "error"; // Make sure that the request was successful or notmodified if ( status != "error" ) { // process the data (runs the xml through httpData regardless of callback) var data = jQuery.uploadHttpData(xml, s.dataType); // If a local callback was specified, fire it and pass it the data if (s.success) s.success(data, status); // Fire the global callback if(s.global) jQuery.event.trigger("ajaxSuccess", [xml, s]); if (s.complete) s.complete(data, status); } else jQuery.handleError(s, xml, status); } catch(e) { status = "error"; jQuery.handleError(s, xml, status, e); } // The request was completed if(s.global) jQuery.event.trigger( "ajaxComplete", [xml, s] ); // Handle the global AJAX counter if (s.global && ! --jQuery.active ) jQuery.event.trigger("ajaxStop"); // Process result jQuery(io).unbind(); setTimeout(function() { try { jQuery(io).remove(); jQuery(form).remove(); } catch(e) { jQuery.handleError(s, xml, null, e); } }, 100); xml = null; } }; // Timeout checker if (s.timeout>0) { setTimeout(function(){ // Check to see if the request is still happening if( !requestDone ) uploadCallback("timeout"); }, s.timeout); } try { var form = jQuery('#' + formId); jQuery(form).attr('action', s.url); jQuery(form).attr('method', 'POST'); jQuery(form).attr('target', frameId); if(form.encoding) { jQuery(form).attr('encoding', 'multipart/form-data'); } else { jQuery(form).attr('enctype', 'multipart/form-data'); } jQuery(form).submit(); } catch(e) { jQuery.handleError(s, xml, null, e); } jQuery('#'+ frameId).load(uploadCallback); return {abort: function () {}}; } }, uploadHttpData: function( r, type ) { var data = !type; data = type == "xml" || data ? r.responseXML : r.responseText; // If the type is "script", eval it in global context if ( type == "script" ) jQuery.globalEval( data ); // Get the JavaScript object, if JSON is used. if ( type == "json" ){ eval( "data = " + $(data).html() ); } // evaluate scripts within html if ( type == "html" ) jQuery("<div>").html(data).evalScripts(); return data; } });
var TH = TH || {}; TH.players = (function() { return { players: {}, init : function() { this.createMainPlayer(); this.startPlayerPolling(); }, createMainPlayer: function() { this.players.red = new TH.MainPlayer(); this.players.red.assignCountry(TH.map.countries.red); }, startPlayerPolling: function(successCallback) { var self = this, firstRequest = true, ajaxRequest = true; function request() { return $.ajax({ type: 'GET', url: TH.global.endpoints.islands, contentType: "application/json; charset=utf-8", dataType: 'json', xhrFields: { withCredentials: true }, success: function(response) { self.ajaxRequest = null; self.pollHandler(response); if (firstRequest) { firstRequest = false; TH.ui.components.preloader.setLoadedStep('otherPlayers'); } }, error: function(error) { self.ajaxRequest = null; TH.global.errorHandler(error); } }); } setInterval(function() { if (!self.ajaxRequest) { self.ajaxRequest = request(); } }, 5000); }, countryMap: { 'west': 'green', 'north': 'yellow', 'east': 'blue' }, initData : { 'green' : { x : 120, y : 280 }, 'yellow' : { x : 550, y : 130 }, 'blue' : { x : 980, y : 300 } }, pollHandler: function(data) { var i, user; TH.players.players.red.setTrees(parseInt(data.trees), true); for (i = 0; user = data.users[i], i < data.users.length; i++) { var pos = this.countryMap[user.position]; if (!this.players[pos]) { this.players[pos] = new TH.Player( parseInt(user.id), user.avatar, this.initData[pos] ); this.players[pos].assignCountry(TH.map.countries[pos]); TH.global.stage.addChild(this.players[pos].container); } else { } this.players[pos].setTotalHealth(parseInt(user.degrading_sum)); if (user.askForHelp) { this.players[pos].showHelp(); } else { this.players[pos].hideHelp(); } } } } }());