code
stringlengths 2
1.05M
|
---|
/*!
* Copyright 2016 E.J.I.E., S.A.
*
* Licencia con arreglo a la EUPL, Versión 1.1 exclusivamente (la «Licencia»);
* Solo podrá usarse esta obra si se respeta la Licencia.
* Puede obtenerse una copia de la Licencia en
*
* http://ec.europa.eu/idabc/eupl.html
*
* Salvo cuando lo exija la legislación aplicable o se acuerde por escrito,
* el programa distribuido con arreglo a la Licencia se distribuye «TAL CUAL»,
* SIN GARANTÍAS NI CONDICIONES DE NINGÚN TIPO, ni expresas ni implícitas.
* Véase la Licencia en el idioma concreto que rige los permisos y limitaciones
* que establece la Licencia.
*/
/* eslint-env jquery,amd */
/* eslint-disable no-console */
import underscore from 'underscore';
import 'jquery';
import 'rup.base';
import 'popper.js';
import './external/bootstrap-calendar';
/**
* Componente de calendario para la visualización de eventos sobre una interfaz dinámica y personalizable.
*
* @summary Componente RUP Calendar.
* @module rup_calendar
* @example
* var properties = {
* day: 'now',
* classes: {
* months: {
* inmonth: 'cal-day-inmonth',
* outmonth: 'cal-day-outmonth',
* saturday: 'cal-day-weekend',
* sunday: 'cal-day-weekend',
* holidays: 'cal-day-holiday',
* today: 'cal-day-today'
* },
* week: {
* workday: 'cal-day-workday',
* saturday: 'cal-day-weekend',
* sunday: 'cal-day-weekend',
* holidays: 'cal-day-holiday',
* today: 'cal-day-today'
* }
* },
* weekbox: true
* };
*
* $('#calendar').rup_calendar(properties);
*/
//****************************************************************************************************************
// DEFINICIÓN BASE DEL PATRÓN (definición de la variable privada que contendrá los métodos y la función de jQuery)
//****************************************************************************************************************
var rup_calendar = {};
var calObj = {};
var errorstr = (str) => {
let estr = 'Cannot call methods on rup_calendar before init. tried to call method ' + str;
throw ReferenceError(estr);
};
var self;
////El componente subyacente requiere underscore en el scope de window
window._ = underscore;
//Se configura el arranque de UDA para que alberge el nuevo patrón
$.extend($.rup.iniRup, $.rup.rupSelectorObjectConstructor('rup_calendar', rup_calendar));
//*******************************
// DEFINICIÓN DE MÉTODOS PÚBLICOS
//*******************************
$.fn.rup_calendar('extend', {
/**
* Navega en el calendario al punto especificado
* Si el parámetro es un string las únicas opciones son:
* - next
* - prev
* - today
*
* @name navigate
* @param {(string|Date)} navigation Hacia dónde navegar
* @function
* @example
* $("#calendar").rup_calendar('navigate','next');
*/
navigate: function (navigation) {
var ctx = this;
if( !$(ctx).data('cal').options) {
errorstr('navigate');
}
// Si el valor es un objeto Date en función navegamos hasta la posición indicada
if( navigation instanceof Date ) {
if($(ctx).data('cal').options.date_range_start !== undefined ) {
if (navigation.getTime() < $(ctx).data('cal').options.date_range_start.getTime()) {
console.warn('Can´t navigate to an out of range time.');
return;
}
}
if($(ctx).data('cal').options.date_range_end !== undefined ) {
if (navigation.getTime() > $(ctx).data('cal').options.date_range_end.getTime()) {
console.warn('Can´t navigate to an out of range time.');
return;
}
}
let pos = $.extend({}, $(ctx).data('cal').options.position);
pos.start.setTime(navigation.getTime());
$(ctx).data('cal').options.day = pos.start.getFullYear() + '-' +
pos.start.getMonthFormatted() + '-' +
pos.start.getDateFormatted();
$(ctx).data('cal').view();
return;
}
// Si no hay valor se considera que por defecto es "today"
navigation = navigation ? navigation : 'today';
if ($.inArray(navigation, ['next', 'prev', 'today']) < 0) {
throw Error('Parámetro inválido');
}
$(ctx).data('cal').navigate(navigation);
},
/**
* Confirma si en la vista está el día actual.
* @name isToday
* @returns {boolean} true si el dia actual está en la vista. false en caso contrario
* @function
* @example
* $("#calendar").rup_calendar('isToday');
*/
isToday: function() {
var ctx = this;
if (!$(ctx).data('cal').options) {
errorstr('isToday');
}
return $(ctx).data('cal').isToday();
},
/**
* Devuelve la instancia del subyacente bootstrap-calendar
*
* @name instance
* @returns {object} instancia del calendar subyacente
* @function
* @example
* $("#calendar").rup_calendar('instance');
*/
instance: function() {
var ctx = this;
if( !$(ctx).data('cal').options) {
errorstr('instance');
}
return $(ctx).data('cal');
},
/**
* Oculta el menú contextual.
*
* @name setView
* @param {string} viewmode El modo de visualizacion a establecer
* @function
* @example
* $("#calendar").rup_calendar('setView','day');
*/
setView: function (viewmode) {
var ctx = this;
if( !$(ctx).data('cal').options) {
errorstr('setView');
}
// El valor por defecto es month.
viewmode = viewmode ? viewmode : 'month';
if ($.inArray(viewmode, ['year', 'month', 'week', 'day']) < 0) {
throw Error('Parámetro inválido');
}
$(ctx).data('cal').view(viewmode);
},
/**
* Obtiene el modo de visualización actual.
*
* @name getView
* @returns {string} modo de visualización
* @function
* @example
* $('#calendar').rup_calendar('getView');
*/
getView: function() {
var ctx = this;
if( !$(ctx).data('cal').options) {
errorstr('getView');
}
return $(ctx).data('cal').options.view;
},
/**
* Obtiene el año del calendario
* @name getYear
* @returns {number} el año del calendario
* @example
* $('#calendar').rup_calendar('getYear');
*/
getYear: function() {
var ctx = this;
if( !$(ctx).data('cal').options) {
errorstr('getYear');
}
return $(ctx).data('cal').getYear();
},
/**
* Obtiene el mes del calendario (Enero, Febrero, ..., Diciembre)
* @name getMonth
* @returns {string} el mes del calendario
* @example
* $('#calendar').rup_calendar('getMonth');
*/
getMonth: function() {
var ctx = this;
if( !$(ctx).data('cal').options) {
errorstr('getMonth');
}
return $(ctx).data('cal').getMonth();
},
/**
* Obtiene la semana del calendario
* @name getWeek
* @returns {number} la semana del calendario
* @example
* $('#calendar').rup_calendar('getWeek');
*/
getWeek: function() {
var ctx = this;
if( !$(ctx).data('cal').options) {
errorstr('getWeek');
}
let date = new Date($(ctx).data('cal').getStartDate());
return date.getWeek();
},
/**
* Obtiene el día de la semana (Lunes - Domingo)
* @name getDay
* @returns {string} el día de la semana
* @example
* $('#calendar').rup_calendar('getDay');
*/
getDay: function() {
var ctx = this;
if( !$(ctx).data('cal').options) {
errorstr('getDay');
}
return $(ctx).data('cal').getDay();
},
/**
* Obtiene el título de la vista de calendario.
*
* @name getTitle
* @function
* @returns {string} título de la vista
* @example
* $("#calendar").rup_calendar("getTitle");
*/
'getTitle': function() {
var ctx = this;
if( !$(ctx).data('cal').options) {
errorstr('getTitle');
}
return $(ctx).data('cal').getTitle();
},
/**
* Obtiene la fecha desde la que se muestra el calendario
* @name getStartDate
* @function
* @returns {Date} fecha
* @example
* $("#calendar").rup_calendar("getStartDate");
*/
getStartDate:function() {
var ctx = this;
if( !$(ctx).data('cal').options) {
errorstr('getStartDate');
}
return $(ctx).data('cal').getStartDate();
},
/**
* Obtiene la fecha hasta la que se muestra el calendario
* @name getEndDate
* @function
* @returns {Date} fecha
* @example
* $("#calendar").rup_calendar("getEndDate");
*/
getEndDate:function() {
var ctx = this;
if( !$(ctx).data('cal').options) {
errorstr('getEndDate');
}
return $(ctx).data('cal').getEndDate();
},
/**
* Método que establece y recarga las opciones
*
* @name option
* @function
* @param {string|object} opción Opcion a consultar/establecer u objeto para establecer las propiedades
* @param {any} value Si el primer parametro asigna este valor a la opción especificada
* @example
* $('#calendar').rup_calendar('weekbox', true);
* $('#calendar').rup_calendar({weekbox:true, view:'month'});
*/
option: function(opt, val) {
var ctx = this;
if( !$(ctx).data('cal').options) {
errorstr('option');
}
if(typeof opt === 'object'){
let optNames = Object.keys(opt);
$.each(optNames, (i,e) => {
$(ctx).data('cal').options[e] = opt[e];
$(ctx).data('cal')._render();
});
return;
}
if(val === undefined) {
return $(ctx).data('cal').options[opt];
}
else {
$(ctx).data('cal').options[opt] = val;
$(ctx).data('cal')._render();
}
},
/**
* Devuelve un listado de eventos entre las dos fechas introducidas
*
* @name getEventsBetween
* @function
* @param {Date} fechaDesde
* @param {Date} fechaHasta
* @returns {Array} listado de Eventos entre las fechas
*/
getEventsBetween: function(desde, hasta) {
var ctx = this;
if( !$(ctx).data('cal').options) {
errorstr('getEventsBetween');
}
return $(ctx).data('cal').getEventsBetween(desde,hasta);
},
/**
* Muestra los eventos de la casilla con la fecha especificada.
* @name showCell
* @function
* @param {Date} fecha fecha a consultar
* @returns {boolean} true si había eventos. false en caso contrario.
* @example
* $('#calendar').rup_calendar('showCell', new Date('2000-01-01'));
*/
showCell : function(date) {
var ctx = this;
if (!$(ctx).data('cal').options) {
errorstr('showCell');
}
if (!(date instanceof Date)) {
throw TypeError('Se requiere un Date como parámetro');
}
var getCell = (date) => {
let ts = date.getTime();
let col = $('.events-list');
let sel = col.filter( (i, e) => {
return $(e).attr('data-cal-start') <= ts && $(e).attr('data-cal-end') > ts;
});
if(sel.length === 0) {
return false;
}
return $(sel).parent();
};
let cell = getCell(date);
if( cell ) {
if ($('#cal-slide-box').css('display') === undefined ||
$('#cal-slide-box').css('display') === 'none' ){
$(ctx).trigger('beforeShowCell');
cell.mouseover();
cell.click();
}
}
else {
return false;
}
},
/**
* Oculta el div con los eventos si está desplegado
* @name hideCells
* @function
* @example
* $('#calendar').rup_calendar('hideCells');
*/
hideCells: function() {
var ctx = this;
if (!$(ctx).data('cal').options) {
errorstr('showCell');
}
$(ctx).trigger('beforeHideCell');
$('#cal-slide-box').css('display','none');
$(ctx).trigger('afterHideCell');
},
/**
* Recarga los eventos y aplica las opciones cambiadas
*
* @name refresh
* @function
* @example
* $('#calendar').rup_calendar('refresh');
*/
refresh: function() {
var ctx = this;
if( !$(ctx).data('cal').options) {
errorstr('refresh');
}
//Primero actualizamos las opciones (Por si se cambia events_source)
$(ctx).data('cal')._render();
//Actualizamos los eventos
$(ctx).data('cal')._loadEvents();
$(ctx).data('cal')._render();
setTimeout(function () {
$(ctx).trigger('afterRefresh');
}, 400);
},
/**
* Elimina el calendario y retorna a la estructura HTML anterior a la creación del calendario.
*
* @name destroy
* @function
* @example
* $("#contextMenu").rup_calendar("destroy");
*/
destroy: function () {
var ctx = this;
if($(ctx).data('cal') === undefined) {
errorstr('destroy');
}
if( !$(ctx).data('cal').options) {
errorstr('destroy');
}
$(ctx).data('cal').options.selector = undefined;
$(ctx).removeClass('cal-context');
$(ctx).removeData();
$(ctx).children().remove();
$(ctx).trigger('afterDestroy');
}
});
//*******************************
// DEFINICIÓN DE MÉTODOS PRIVADOS
//*******************************
$.fn.rup_calendar('extend', {
_callIfFunction: function (...args) {
if (args.length === 0) return false;
if (args.length > 1) {
let fnc = args[0];
let params = args.slice(1);
if (fnc !== undefined && typeof fnc === 'function') {
return fnc.apply(this, params);
} else {
return false;
}
} else {
if (args !== undefined && typeof (args) === 'function') {
return args.call(this);
}
}
},
/**
* Método de inicialización del componente.
*
* @name _init
* @function
* @private
* @param {object} args - Parámetros de inicialización del componente.
*/
_init: function (args) {
if (args.length > 1) {
$.rup.errorGestor($.rup.i18nParse($.rup.i18n.base, 'rup_global.initError') + $(this).attr('id'));
} else {
//Se recogen y cruzan las paremetrizaciones del objeto
self = this;
var customSettings = args[0];
var settings = $.extend({}, $.fn.rup_calendar.defaults, customSettings);
self._ADAPTER = $.rup.adapter[settings.adapter];
settings.onAfterEventsLoad = function (...args) {
self._callIfFunction.call(this, $.fn.rup_calendar.defaults.onAfterEventsLoad, args);
self._callIfFunction.call(this, customSettings.rupAfterEventsLoad, args);
$(self).trigger('afterEventsLoad');
};
settings.onAfterViewLoad = function (...args) {
self._callIfFunction.call(this, $.fn.rup_calendar.defaults.onAfterViewLoad, args);
self._callIfFunction.call(this, customSettings.rupAfterViewLoad, args);
$(self).trigger('afterViewLoad');
};
// if ($.rup_utils.aplicatioInPortal()) {
// settings.appendTo = '.r01gContainer';
// }
//El componente subyacente requiere i18n en una variable del scope de window
if (!window.calendar_languages) {
window.calendar_languages = {};
}
window.calendar_languages[settings.language] = $.rup.i18n.base.rup_calendar;
//Lanzar el plugin subyaciente
calObj = new $(self).calendar(settings);
this.data('cal',calObj);
this.trigger('afterInitCalendar');
// Se audita el componente
$.rup.auditComponent('rup_calendar', 'init');
}
}
});
//******************************************************
// DEFINICIÓN DE LA CONFIGURACION POR DEFECTO DEL PATRON
//******************************************************
/**
* @description Propiedades de configuración del componente. Todas son opcionales. Se puede crear un calendario con la funcionalidad básica sin especificar ninguna de estas opciones.
*
* @name defaults
* @property {string} tooltip_container - Container al que se le añade el tooltip.
* @property {(string|function|object)} events_source - Origen de los eventos a añadir en el calendario.
* @property {string} width - Ancho que ocupara el calendario.
* @property {string} view - vista que se mostrara por defecto (year/month/week/day).
* @property {string} day - Punto de inicio del calendario. puede ser 'now' o una fecha en formato (yyyy-mm-dd).
* @property {string} time_start - La hora a la que empieza la vista de día.
* @property {string} time_end - La hora a la que acaba la vista de day.
* @property {string} time_split - Cada cuantos minutos se muestra un separador en la vista de día.
* @property {boolean} format12 - Especifica si se usa o no el formato de 12H en lugar del de 24H.
* @property {string} am_suffix - En el formato de 12H especifica el sufijo para la mañana (default: AM).
* @property {string} pm_suffix - En el formato de 12H especifica el sufijo para la tarde (default: PM).
* @property {string} tmpl_path - Path a la ubicación de las tempaltes de calendar (Debe terminar en '/').
* @property {boolean} tmpl_cache - Indica si cachea o no las templates (default: true).
* @property {object} classes - Establece las clases para cada celda en funcion de la vista.
* @property {(string|null)} modal - ID de la ventana modal. Si se establece las url en los eventos se abrirán en la modal.
* @property {string} modal_type - Modo en el que aparece el modal (iframe/ajax/template).
* @property {function} modal_title - Función para establecer el título del modal. Recibe el evento como parámetro.
* @property {object} views - configuración de las vistas.
* @property {boolean} merge_holidays - Añade al calendario algunas festividades como año nuevo o el día de la independencia americana.
* @property {boolean} display_week_numbers - Determina si se muestra el número de la semana.
* @property {boolean} weekbox - Determina si se muestra o no un div con el número de la semana en la vista de mes.
* @property {object} headers - Cabeceras para las llamadas ajax realizadas desde el calendario.
* @property {boolean} cell_navigation - Determina si se cambia la vista al día o mes haciendo doble click en la celda o click en el número de dia o nombre de mes.
* @property {number} date_range_start - Indica la fecha mínima del rango de operación permitido del calendario. Para retirar esta opcion mediante el método 'options' hay que pasar el valor null.
* @property {number} date_range_end - Indica la fecha máxima del rango de operación permitido del calendario. Para retirar esta opcion mediante el método 'options' hay que padar el valor null.
* @property {function} onAfterEventsLoad - Callback que se ejecuta tras cargar los eventos (Recibe los eventos como parámetros).
* @property {function} onBeforeEventsLoad - Callback que se ejecuta antes de cargar los eventos.
* @property {function} onAfterViewLoad - Callback que se ejecuta tras cargar una nueva vista (Recibe la vista como parámetro).
* @property {function} onAfterModalShow - Callback que se ejecuta tras mostrar el modal (Recibe los eventos como parámetros).
* @property {function} onAfterModalHidden - Callback que se ejecuta tras esconder el modal.(Recibe los eventos como parámetros).
*/
/**
* @description Propiedades del objeto 'classes'
*
* @name classes
*
* @property {object} classes.month - Establece las clases en la vista de mes.
* @property {string} classes.month.inmonth - Establece las clases para las celdas que representan días del mes actual.
* @property {string} classes.month.outmonth - Establece las clases para las celdas que representan días ajenos al mes actual.
* @property {string} classes.month.saturday - Establece las clases para las celdas que representan los sábados.
* @property {string} classes.month.sunday - Establece las clases para las celdas que representan los domingos.
* @property {string} classes.month.holidays - Establece las clases para las celdas que representan los festivos.
* @property {string} classes.month.today - Establece las clases para la celda que representan el día actual.
* @property {object} classes.week - Establece las clases en la vista de semana.
* @property {string} classes.week.workday - Establece las clases para las celdas que representan días entre semana.
* @property {string} classes.week.saturday - Establece las clases para las celdas que representan los sábados.
* @property {string} classes.week.sunday - Establece las clases para las celdas que representan los domingos.
* @property {string} classes.week.holidays - Establece las clases para las celdas que representan los festivos.
* @property {string} classes.week.today - Establece las clases para la celda que representan el día actual.
*/
/**
* @description Propiedades del objeto 'views'
*
* @name views
*
* @property {object} views.year - Establece las opciones para la vista anual.
* @property {integer} views.year.slide_events - Si el valor es 1 permite desplegar los eventos desde las celdas.
* @property {integer} views.year.enable - Si el valor es 1 habilita la vista.
* @property {object} views.month - Establece las opciones para la vista mensual.
* @property {integer} views.month.slide_events - Si el valor es 1 permite desplegar los eventos desde las celdas.
* @property {integer} views.month.enable - Si el valor es 1 habilita la vista.
* @property {object} views.week - Establece las opciones para la vista semanal.
* @property {integer} views.week.enable - Si el valor es 1 habilita la vista.
* @property {object} views.day - Establece las opciones para la vista diaria.
* @property {integer} views.day.enable - Si el valor es 1 habilita la vista.
*/
/**
* @description Ya sea desde local o remoto el JSON con los eventos es un array de objetos en el que
* cada objeto tiene las siguientes propiedades:
*
* @name Eventos
*
* @property {string} id identificador único del evento.
* @property {string} title texto o html que aparecerá al desplegar la celda con el evento.
* @property {string} start la fecha en la que inicia el evento (En milisegundos).
* @property {string} class clase a añadir al evento (Sirve para la visualización del evento).
* @property {string} end la fecha en la que finaliza el evento.
* @property {string} url ruta a la que llevar cuando se haga click sobre el evento.
*
*/
$.fn.rup_calendar.defaults = {
events_source: () => {
return [];
},
language: $.rup.lang,
view: 'month',
tmpl_path: global.STATICS + '/rup/html/templates/rup_calendar/',
tmpl_cache: false,
day: 'now',
weekbox: false,
classes: {
months: {
general: 'label'
}
},
onAfterEventsLoad: () => {},
onAfterViewLoad: () => {},
adapter: 'calendar_bootstrap'
};
|
/*
License
Copyright (c) 2015 Nathan Cahill
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.
*/
'use strict';
(function() {
var global = this
, addEventListener = 'addEventListener'
, removeEventListener = 'removeEventListener'
, getBoundingClientRect = 'getBoundingClientRect'
, isIE8 = global.attachEvent && !global[addEventListener]
, document = global.document
, calc = (function () {
var el
, prefixes = ["", "-webkit-", "-moz-", "-o-"]
for (var i = 0; i < prefixes.length; i++) {
el = document.createElement('div')
el.style.cssText = "width:" + prefixes[i] + "calc(9px)"
if (el.style.length) {
return prefixes[i] + "calc"
}
}
})()
, elementOrSelector = function (el) {
if (typeof el === 'string' || el instanceof String) {
return document.querySelector(el)
} else {
return el
}
}
, Split = function (ids, options) {
var dimension
, i
, clientDimension
, clientAxis
, position
, gutterClass
, paddingA
, paddingB
, pairs = []
// Set defaults
options = typeof options !== 'undefined' ? options : {}
if (!options.gutterSize) options.gutterSize = 10
if (!options.minSize) options.minSize = 100
if (!options.snapOffset) options.snapOffset = 30
if (!options.direction) options.direction = 'horizontal'
if (options.direction == 'horizontal') {
dimension = 'width'
clientDimension = 'clientWidth'
clientAxis = 'clientX'
position = 'left'
gutterClass = 'gutter gutter-horizontal'
paddingA = 'paddingLeft'
paddingB = 'paddingRight'
if (!options.cursor) options.cursor = 'ew-resize'
} else if (options.direction == 'vertical') {
dimension = 'height'
clientDimension = 'clientHeight'
clientAxis = 'clientY'
position = 'top'
gutterClass = 'gutter gutter-vertical'
paddingA = 'paddingTop'
paddingB = 'paddingBottom'
if (!options.cursor) options.cursor = 'ns-resize'
}
// Event listeners for drag events, bound to a pair object.
// Calculate the pair's position and size when dragging starts.
// Prevent selection on start and re-enable it when done.
var startDragging = function (e) {
var self = this
, a = self.a
, b = self.b
if (!self.dragging && options.onDragStart) {
options.onDragStart()
}
e.preventDefault()
self.dragging = true
self.move = drag.bind(self)
self.stop = stopDragging.bind(self)
global[addEventListener]('mouseup', self.stop)
global[addEventListener]('touchend', self.stop)
global[addEventListener]('touchcancel', self.stop)
self.parent[addEventListener]('mousemove', self.move)
self.parent[addEventListener]('touchmove', self.move)
a[addEventListener]('selectstart', preventSelection)
a[addEventListener]('dragstart', preventSelection)
b[addEventListener]('selectstart', preventSelection)
b[addEventListener]('dragstart', preventSelection)
a.style.userSelect = 'none'
a.style.webkitUserSelect = 'none'
a.style.MozUserSelect = 'none'
a.style.pointerEvents = 'none'
b.style.userSelect = 'none'
b.style.webkitUserSelect = 'none'
b.style.MozUserSelect = 'none'
b.style.pointerEvents = 'none'
self.gutter.style.cursor = options.cursor
self.parent.style.cursor = options.cursor
calculateSizes.call(self)
}
, stopDragging = function () {
var self = this
, a = self.a
, b = self.b
if (self.dragging && options.onDragEnd) {
options.onDragEnd()
}
self.dragging = false
global[removeEventListener]('mouseup', self.stop)
global[removeEventListener]('touchend', self.stop)
global[removeEventListener]('touchcancel', self.stop)
self.parent[removeEventListener]('mousemove', self.move)
self.parent[removeEventListener]('touchmove', self.move)
delete self.stop
delete self.move
a[removeEventListener]('selectstart', preventSelection)
a[removeEventListener]('dragstart', preventSelection)
b[removeEventListener]('selectstart', preventSelection)
b[removeEventListener]('dragstart', preventSelection)
a.style.userSelect = ''
a.style.webkitUserSelect = ''
a.style.MozUserSelect = ''
a.style.pointerEvents = ''
b.style.userSelect = ''
b.style.webkitUserSelect = ''
b.style.MozUserSelect = ''
b.style.pointerEvents = ''
self.gutter.style.cursor = ''
self.parent.style.cursor = ''
}
, drag = function (e) {
var offset
if (!this.dragging) return
// Get the relative position of the event from the first side of the
// pair.
if ('touches' in e) {
offset = e.touches[0][clientAxis] - this.start
} else {
offset = e[clientAxis] - this.start
}
// If within snapOffset of min or max, set offset to min or max
if (offset <= this.aMin + options.snapOffset) {
offset = this.aMin
} else if (offset >= this.size - this.bMin - options.snapOffset) {
offset = this.size - this.bMin
}
adjust.call(this, offset)
if (options.onDrag) {
options.onDrag()
}
}
, calculateSizes = function () {
// Calculate the pairs size, and percentage of the parent size
var computedStyle = global.getComputedStyle(this.parent)
, parentSize = this.parent[clientDimension] - parseFloat(computedStyle[paddingA]) - parseFloat(computedStyle[paddingB])
this.size = this.a[getBoundingClientRect]()[dimension] + this.b[getBoundingClientRect]()[dimension] + this.aGutterSize + this.bGutterSize
this.percentage = Math.min(this.size / parentSize * 100, 100)
this.start = this.a[getBoundingClientRect]()[position]
}
, adjust = function (offset) {
// A size is the same as offset. B size is total size - A size.
// Both sizes are calculated from the initial parent percentage.
this.a.style[dimension] = calc + '(' + (offset / this.size * this.percentage) + '% - ' + this.aGutterSize + 'px)'
this.b.style[dimension] = calc + '(' + (this.percentage - (offset / this.size * this.percentage)) + '% - ' + this.bGutterSize + 'px)'
}
, fitMin = function () {
var self = this
, a = self.a
, b = self.b
if (a[getBoundingClientRect]()[dimension] < self.aMin) {
a.style[dimension] = (self.aMin - self.aGutterSize) + 'px'
b.style[dimension] = (self.size - self.aMin - self.aGutterSize) + 'px'
} else if (b[getBoundingClientRect]()[dimension] < self.bMin) {
a.style[dimension] = (self.size - self.bMin - self.bGutterSize) + 'px'
b.style[dimension] = (self.bMin - self.bGutterSize) + 'px'
}
}
, fitMinReverse = function () {
var self = this
, a = self.a
, b = self.b
if (b[getBoundingClientRect]()[dimension] < self.bMin) {
a.style[dimension] = (self.size - self.bMin - self.bGutterSize) + 'px'
b.style[dimension] = (self.bMin - self.bGutterSize) + 'px'
} else if (a[getBoundingClientRect]()[dimension] < self.aMin) {
a.style[dimension] = (self.aMin - self.aGutterSize) + 'px'
b.style[dimension] = (self.size - self.aMin - self.aGutterSize) + 'px'
}
}
, balancePairs = function (pairs) {
for (var i = 0; i < pairs.length; i++) {
calculateSizes.call(pairs[i])
fitMin.call(pairs[i])
}
for (i = pairs.length - 1; i >= 0; i--) {
calculateSizes.call(pairs[i])
fitMinReverse.call(pairs[i])
}
}
, preventSelection = function () { return false }
, parent = elementOrSelector(ids[0]).parentNode
if (!options.sizes) {
var percent = 100 / ids.length
options.sizes = []
for (i = 0; i < ids.length; i++) {
options.sizes.push(percent)
}
}
if (!Array.isArray(options.minSize)) {
var minSizes = []
for (i = 0; i < ids.length; i++) {
minSizes.push(options.minSize)
}
options.minSize = minSizes
}
for (i = 0; i < ids.length; i++) {
var el = elementOrSelector(ids[i])
, isFirst = (i == 1)
, isLast = (i == ids.length - 1)
, size
, gutterSize = options.gutterSize
, pair
if (i > 0) {
pair = {
a: elementOrSelector(ids[i - 1]),
b: el,
aMin: options.minSize[i - 1],
bMin: options.minSize[i],
dragging: false,
parent: parent,
isFirst: isFirst,
isLast: isLast,
direction: options.direction
}
// For first and last pairs, first and last gutter width is half.
pair.aGutterSize = options.gutterSize
pair.bGutterSize = options.gutterSize
if (isFirst) {
pair.aGutterSize = options.gutterSize / 2
}
if (isLast) {
pair.bGutterSize = options.gutterSize / 2
}
}
// IE9 and above
if (!isIE8) {
if (i > 0) {
var gutter = document.createElement('div')
gutter.className = gutterClass
gutter.style[dimension] = options.gutterSize + 'px'
gutter[addEventListener]('mousedown', startDragging.bind(pair))
gutter[addEventListener]('touchstart', startDragging.bind(pair))
parent.insertBefore(gutter, el)
pair.gutter = gutter
}
if (i === 0 || i == ids.length - 1) {
gutterSize = options.gutterSize / 2
}
if (typeof options.sizes[i] === 'string' || options.sizes[i] instanceof String) {
size = options.sizes[i]
} else {
size = calc + '(' + options.sizes[i] + '% - ' + gutterSize + 'px)'
}
// IE8 and below
} else {
if (typeof options.sizes[i] === 'string' || options.sizes[i] instanceof String) {
size = options.sizes[i]
} else {
size = options.sizes[i] + '%'
}
}
el.style[dimension] = size
if (i > 0) {
pairs.push(pair)
}
}
balancePairs(pairs)
}
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
exports = module.exports = Split
}
exports.Split = Split
} else {
global.Split = Split
}
}).call(window)
|
/**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* @category Phoenix
* @package Phoenix_Moneybookers
* @copyright Copyright (c) 2016 Phoenix Medien GmbH & Co. KG (http://www.phoenix-medien.de)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
Event.observe(window, 'load', function() {
initMoneybookers();
});
Moneybookers = Class.create();
Moneybookers.prototype = {
initialize: function(bannerUrl, activateemailUrl, checksecretUrl, checkemailUrl){
this.bannerUrl = bannerUrl;
this.activateemailUrl = activateemailUrl;
this.checksecretUrl = checksecretUrl;
this.checkemailUrl = checkemailUrl;
this.txtBtnStatus0 = this.translate('Validate Email');
this.txtBtnStatus1 = this.translate('Activate Moneybookers Quick Checkout');
this.txtBtnStatus2 = this.translate('Validate Secret Word');
this.txtErrStatus0 = this.translate('This email address is not registered.');
this.txtErrStatus2 = this.translate('This Secret Word is incorrect. After activation Moneybookers will give you access to a new section in your Moneybookers account called "Merchant tools". Please choose a secret word (do not use your password for this) and provide it in your Moneybookers admin area and above.');
this.txtInfStatus0 = this.translate('<strong><a href="http://www.moneybookers.com/" target="_blank">Moneybookers</a></strong> is an all in one payments solution that enables a merchant to accept debit and credit card payments, bank transfers and the largest range of local payments directly on your website.<ul style="list-style-position: inside;list-style-type: disc;"><li>Widest network of international and local payment options in the world.</li><li>One interface including payments, banking and marketing.</li><li>Direct payments without the need for direct registration.</li><li>Moneybookers stands for a highly converting payment gateway that turns payment processing into a simple, fast and customer friendly operation.</li><li>Highly competitive rates. Please <a href="http://www.moneybookers.com/app/help.pl?s=m_fees" target="_blank">click here</a> for more detailed information.</li></ul>') + '<img src="' + this.bannerUrl + '" alt="" />';
this.txtInfStatus1 = this.translate('<strong>Moneybookers Quick Checkout</strong> enables you to take <strong>direct</strong> payments from credit cards, debit cards and over 50 other local payment options in over 200 countries for customers without an existing Moneybookers eWallet.');
this.txtNotSavechanges = this.translate('Please save the configuration before continuing.');
this.txtNotStatus0 = this.translate('Email was validated by Moneybookers.');
this.txtNotStatus1 = this.translate('Activation email was sent to Moneybookers. Please be aware that the verification process to use Moneybookers Quick Checkout takes some time. You will be contacted by Moneybookers when the verification process has been completed.');
this.txtNotStatus2 = this.translate('Secret Word was validated by Moneybookers. Your installation is completed and you are ready to receive international and local payments.');
$("moneybookers_settings_moneybookers_email").setAttribute("onchange", "moneybookers.setStatus(0); moneybookers.changeUi(); document.getElementById('moneybookers_settings_customer_id').value = ''; document.getElementById('moneybookers_settings_customer_id_hidden').value = '';");
$("moneybookers_settings_customer_id").disabled = true;
$("moneybookers_settings_customer_id_hidden").name = document.getElementById("moneybookers_settings_customer_id").name;
$("moneybookers_settings_customer_id_hidden").value = document.getElementById("moneybookers_settings_customer_id").value;
$("moneybookers_settings_secret_key").setAttribute("onchange", "moneybookers.setStatus(2); moneybookers.changeUi();");
if (this.isStoreView()) {
this.infoOrig = {
email: $("moneybookers_settings_moneybookers_email").value,
customerId: $("moneybookers_settings_customer_id").value,
key: $("moneybookers_settings_secret_key").value,
status: this.getStatus(),
useDefult: $("moneybookers_settings_moneybookers_email_inherit").checked
};
var defaults = $$("#row_moneybookers_settings_customer_id .use-default, #row_moneybookers_settings_secret_key .use-default, #row_moneybookers_settings_activationstatus .use-default");
if (Object.isArray(defaults)) {
for (var i=0; i<defaults.length; i++) {
defaults[i].hide();
}
}
$("moneybookers_settings_moneybookers_email_inherit").setAttribute("onchange", "moneybookers.changeStore();");
}
this.changeUi();
},
translate: function(text) {
try {
if(Translator){
return Translator.translate(text);
}
}
catch(e){}
return text;
},
button: function () {
var status, response, result;
status = this.getStatus();
if (status < 1) {
response = this.getHttp(this.checkemailUrl + "?email=" + $("moneybookers_settings_moneybookers_email").value);
result = response.split(',');
if (result[0] == "OK") {
$("moneybookers_settings_customer_id").value = result[1];
$("moneybookers_settings_customer_id_hidden").value = result[1];
this.setStatus(1);
status = 1;
alert(this.txtNotStatus0);
}
else {
$("moneybookers_settings_customer_id").value = "";
alert(this.txtErrStatus0 + "\n("+response+")");
}
}
if (status == 1) {
this.getHttp(this.activateemailUrl);
this.setStatus(2);
alert(this.txtNotStatus1);
this.alertSaveChanges();
}
if (status == 2) {
response = this.getHttp(this.checksecretUrl + "?email=" + $("moneybookers_settings_moneybookers_email").value
+ "&secret=" + $("moneybookers_settings_secret_key").value
+ "&cust_id=" + $("moneybookers_settings_customer_id").value);
if (response == "OK") {
this.setStatus(3);
alert(this.txtNotStatus2);
this.alertSaveChanges();
}
else {
alert(this.txtErrStatus2 + "\n("+response+")");
}
}
},
alertSaveChanges: function () {
$("moneybookers_multifuncbutton").style.display = "none";
alert(this.txtNotSavechanges);
},
getHttp: function (url) {
var response;
new Ajax.Request(
url,
{
method: "get",
onComplete: function(transport) {response = transport.responseText;},
asynchronous: false
});
return response;
},
getInteger: function (number) {
number = parseInt(number);
if (isNaN(number)) return 0;
return number;
},
getStatus: function () {
var status = this.getInteger($("moneybookers_settings_activationstatus").value);
if (status == 1 && $("moneybookers_settings_customer_id").value != '' && $("moneybookers_settings_secret_key").value == '') {
status = 2;
this.setStatus(status);
}
return status;
},
setStatus: function (number) {
number = this.getInteger(number);
if (number < 0) number = 0;
else if (number > 3) number = 3;
$("moneybookers_settings_activationstatus").value = number;
},
changeUi: function () {
var status = this.getStatus();
if (status < 1) {
$("moneybookers_inf_div").update(this.txtInfStatus0);
$("moneybookers_multifuncbutton_label").update(this.txtBtnStatus0);
}
if (status == 1) {
$("moneybookers_inf_div").update(this.txtInfStatus1);
$("moneybookers_multifuncbutton_label").update(this.txtBtnStatus1);
}
if (status < 2) {
$("moneybookers_inf_div").style.display = "block";
$("moneybookers_settings_secret_key").disabled = true;
}
if (status == 2) {
$("moneybookers_multifuncbutton_label").update(this.txtBtnStatus2);
if (this.isStoreView()) {
$("moneybookers_settings_secret_key").enable();
$("moneybookers_settings_secret_key_inherit").removeAttribute('checked');
}
}
if (status > 2) {
$("moneybookers_multifuncbutton").style.display = "none";
} else {
$("moneybookers_multifuncbutton").style.display = "block";
}
},
changeStore: function () {
if (!$("moneybookers_settings_moneybookers_email_inherit").checked) {
if (this.infoOrig.useDefult) {
$("moneybookers_settings_customer_id_inherit").click();
$("moneybookers_settings_customer_id").clear();
$("moneybookers_settings_secret_key_inherit").click();
$("moneybookers_settings_secret_key").clear();
$("moneybookers_settings_activationstatus_inherit").click();
this.setStatus(0);
}
}
else {
if (this.infoOrig.useDefult) {
$("moneybookers_settings_customer_id").setValue(this.infoOrig.customerId);
$("moneybookers_settings_customer_id_inherit").click();
$("moneybookers_settings_secret_key").setValue(this.infoOrig.key);
$("moneybookers_settings_secret_key_inherit").click();
$("moneybookers_settings_activationstatus_inherit").click();
this.setStatus(this.infoOrig.status);
}
}
this.changeUi();
},
isStoreView: function() {
return $("moneybookers_settings_moneybookers_email_inherit") != undefined;
}
};
|
import createSvgIcon from './utils/createSvgIcon';
import { jsx as _jsx } from "react/jsx-runtime";
export default createSvgIcon([/*#__PURE__*/_jsx("path", {
d: "M20 4H4v13.17L5.17 16H20V4zm-6 10H6v-2h8v2zm4-3H6V9h12v2zm0-3H6V6h12v2z",
opacity: ".3"
}, "0"), /*#__PURE__*/_jsx("path", {
d: "M20 18c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2H4c-1.1 0-1.99.9-1.99 2L2 22l4-4h14zm-16-.83V4h16v12H5.17L4 17.17zM6 12h8v2H6zm0-3h12v2H6zm0-3h12v2H6z"
}, "1")], 'ChatTwoTone'); |
import Ember from 'ember';
import { moduleForComponent, test } from 'ember-qunit';
import startApp from '../../helpers/start-app';
var App;
moduleForComponent('zip-code-input', 'zip-code-input component', {
setup: function() {
App = startApp();
},
teardown: function() {
Ember.run(App, 'destroy');
},
unit: true
});
test('values are correct', function(assert) {
assert.expect(2);
var component = this.subject();
// append the component to the DOM
this.render();
// testing filled in value
fillIn('input', '12345');
triggerEvent('input', 'blur');
andThen(function() { // wait for async helpers to complete
assert.equal(find('input').val(), '12345');
assert.equal(component.get('unmaskedValue'), 12345);
});
});
test('full code works', function(assert) {
assert.expect(2);
var component = this.subject();
// append the component to the DOM
this.render();
Ember.run(function(){
component.set('fullCode', true);
});
// testing filled in value
fillIn('input', '123451234');
triggerEvent('input', 'blur');
andThen(function() { // wait for async helpers to complete
assert.equal(find('input').val(), '12345-1234');
assert.equal(component.get('unmaskedValue'), 123451234);
});
});
|
var grow = grow || {};
window.grow = grow;
(function(grow){
var toolConfig = {};
grow.ui = grow.ui || {};
grow.ui.showNotice = function(text) {
var notice = document.createElement('div');
notice.classList.add('grow_tool__notice');
if (text) {
notice.appendChild(document.createTextNode(text));
}
document.body.appendChild(notice);
return notice;
};
grow.ui.toolConfig = function(tool, options) {
toolConfig[tool] = options;
};
grow.ui.tools = grow.ui.tools || [];
grow.ui.main = function(settings) {
var el = document.createElement('div');
var buttonsEl = document.createElement('div');
buttonsEl.setAttribute('class', 'grow__buttons');
buttonsEl.appendChild(createButton_('primary', null, null, {
'click': function() {
buttonsEl.classList.toggle('grow__expand');
}
}));
buttonsEl.appendChild(createButton_('close', null, null, {
'click': function() {
el.parentNode.removeChild(el);
}
}));
if (settings.injectEditUrl) {
buttonsEl.appendChild(
createButton_('edit', 'Edit', settings.injectEditUrl));
}
if (settings.injectTranslateUrl) {
buttonsEl.appendChild(createButton_(
'translate', 'Translate', settings.injectTranslateUrl));
}
for(i in grow.ui.tools) {
tool = grow.ui.tools[i];
if (tool['init']) {
tool['init'](toolConfig[tool['kind']] || {});
}
if (tool['button']) {
buttonsEl.appendChild(createButton_(
tool['kind'], tool['name'], tool['button']['link'] || null,
tool['button']['events'] || {}));
}
}
// If there is nothing to do, do not show the menu at all.
if (buttonsEl.children.length <= 2) {
return;
}
el.setAttribute('id', 'grow-utils');
el.appendChild(buttonsEl);
document.body.appendChild(el);
};
var createButton_ = function(kind, label, url, events) {
var containerEl = document.createElement('div');
containerEl.classList.add('grow__button');
var buttonEl = document.createElement('a');
buttonEl.classList.add('grow__icon');
buttonEl.classList.add('grow__icon_' + kind);
if (url) {
buttonEl.setAttribute('href', url);
buttonEl.setAttribute('target', '_blank');
} else {
buttonEl.setAttribute('href', 'javascript:void(0)');
}
if (events) {
for (var prop in events) {
buttonEl.addEventListener(prop, events[prop]);
}
}
containerEl.appendChild(buttonEl);
if (label) {
var labelEl = document.createElement('p');
labelEl.appendChild(document.createTextNode(label));
labelEl.classList.add('grow__label');
containerEl.appendChild(labelEl);
}
return containerEl;
};
})(grow);
|
var RELANG = {};
RELANG['sq'] = {
html: 'HTML',
video: 'Video',
image: 'Fotografi',
table: 'Tabelë',
link: 'Link',
link_insert: 'Lidh linq ...',
unlink: 'Hiq linkun',
formatting: 'Stilet',
paragraph: 'Paragraf',
quote: 'Kuotë',
code: 'Kod',
header1: 'Header 1',
header2: 'Header 2',
header3: 'Header 3',
header4: 'Header 4',
bold: 'Te trasha / Bold',
italic: 'Kursive / Italic',
fontcolor: 'Ngjyra e shkronjave',
backcolor: 'Ngjyra e mbrapavisë së shkronjave',
unorderedlist: 'Liste pa renditje',
orderedlist: 'Liste me renditje',
outdent: 'Outdent',
indent: 'Indent',
redo: 'Ribëj',
undo: 'Zhbëj',
cut: 'Cut',
cancel: 'Anulo',
insert: 'Insert',
save: 'Ruaje',
_delete: 'Fshije',
insert_table: 'Shto tabelë',
insert_row_above: 'Shto rresht sipër',
insert_row_below: 'Shto rresht përfundi',
insert_column_left: 'Shto kolonë majtas',
insert_column_right: 'Shto kolonë djathtas',
delete_column: 'Fshije kolonën',
delete_row: 'Fshije rreshtin',
delete_table: 'Fshije tabelën',
rows: 'Rreshta',
columns: 'Kolona',
add_head: 'Shto titujt e tabelës',
delete_head: 'Fshije titujt e tabelës',
title: 'Titulli',
image_position: 'Pozita',
none: 'Normale',
left: 'Majtas',
right: 'Djathtas',
image_web_link: 'Linku i fotografisë në internet',
text: 'Teksti',
mailto: 'Email',
web: 'URL',
video_html_code: 'Video embed code',
file: 'Fajll',
upload: 'Ngarko',
download: 'Shkarko',
choose: 'Zgjedh',
or_choose: 'Ose zgjedh',
drop_file_here: 'Gjuaje fajllin këtu',
align_left: 'Rreshtoje majtas',
align_center: 'Rreshtoje në mes',
align_right: 'Rreshtoje djathtas',
align_justify: 'Rreshtoje të gjithin njejt',
horizontalrule: 'Vizë horizontale',
fullscreen: 'Pamje e plotë',
deleted: 'E fshirë',
anchor: 'Anchor',
link_new_tab: 'Open link in new tab'
};
|
'use strict';
const chalk = require('chalk');
const Task = require('../models/task');
const Watcher = require('../models/watcher');
const Builder = require('../models/builder');
const pDefer = require('p-defer');
class BuildWatchTask extends Task {
constructor(options) {
super(options);
this._builder = null;
this._runDeferred = null;
}
async run(options) {
let { ui } = this;
ui.startProgress(chalk.green('Building'), chalk.green('.'));
this._runDeferred = pDefer();
let builder = (this._builder =
options._builder ||
new Builder({
ui,
outputPath: options.outputPath,
environment: options.environment,
project: this.project,
}));
ui.writeLine(`Environment: ${options.environment}`);
let watcher =
options._watcher ||
new Watcher({
ui,
builder,
analytics: this.analytics,
options,
});
await watcher;
// Run until failure or signal to exit
return this._runDeferred.promise;
}
/**
* Exit silently
*
* @private
* @method onInterrupt
*/
async onInterrupt() {
await this._builder.cleanup();
this._runDeferred.resolve();
}
}
module.exports = BuildWatchTask;
|
module.exports={A:{A:{"1":"E A B","2":"H C G EB"},B:{"1":"D p x J L N I"},C:{"1":"0 1 2 3 4 5 6 8 9 R S T U V W X Y Z b c d e f g h i j k l m n o M q r s t u v w y","2":"YB BB","132":"F K H C G E A B D p x J L N I O P Q WB QB"},D:{"1":"0 1 2 3 4 5 6 8 9 F K H C G E A B D p x J L N I O P Q R S T U V W X Y Z b c d e f g h i j k l m n o M q r s t u v w y KB aB FB a GB HB IB"},E:{"1":"F K H C G E A B LB MB NB OB PB z RB","2":"JB CB"},F:{"1":"0 J L N I O P Q R S T U V W X Y Z b c d e f g h i j k l m n o M q r s t u v w","2":"7 E B D SB TB UB VB z AB XB"},G:{"1":"G ZB DB bB cB dB eB fB gB hB iB jB kB","2":"CB"},H:{"2":"lB"},I:{"1":"BB F a oB pB DB qB rB","2":"mB nB"},J:{"1":"C A"},K:{"1":"7 B D M z AB","2":"A"},L:{"1":"a"},M:{"1":"y"},N:{"1":"A B"},O:{"1":"sB"},P:{"1":"F K tB"},Q:{"1":"uB"},R:{"1":"vB"}},B:6,C:"MP3 audio format"};
|
/**
* Imports
*/
import React from 'react';
import {FormattedMessage} from 'react-intl';
// Flux
import IntlStore from '../../../stores/Application/IntlStore';
// Required components
import Button from '../buttons/Button';
import Text from '../typography/Text';
// Translation data for this component
import intlData from './AddressPreview.intl';
/**
* Component
*/
class AddressPreview extends React.Component {
static contextTypes = {
getStore: React.PropTypes.func.isRequired
};
//*** Component Lifecycle ***//
componentDidMount() {
// Component styles
require('./AddressPreview.scss');
}
//*** Template ***//
render() {
let intlStore = this.context.getStore(IntlStore);
return (
<div className="address-preview">
<div className="address-preview__name">
<Text weight="bold">{this.props.address.name}</Text>
</div>
{this.props.address.phone ?
<div className="address-preview__phone">
<Text size="small">{this.props.address.phone}</Text>
</div>
:
null
}
{this.props.address.vatin ?
<div className="address-preview__vatin">
<Text>
<FormattedMessage
message={intlStore.getMessage(intlData, 'vatLabel')}
locales={intlStore.getCurrentLocale()} />: {this.props.address.vatin}
</Text>
</div>
:
null
}
<div className="address-preview__address-line-1">
<Text>{this.props.address.addressLine1}</Text>
</div>
{this.props.address.addressLine2 ?
<div className="address-preview__address-line-2">
<Text>{this.props.address.addressLine2}</Text>
</div>
:
null
}
<div className="address-preview__postal-code">
<Text>{this.props.address.postalCode}</Text>
</div>
<div className="address-preview__city">
<Text>{this.props.address.city}</Text>
</div>
{this.props.address.state ?
<div className="address-preview__state">
<Text>{this.props.address.state}</Text>
</div>
:
null
}
<div className="address-preview__country">
<Text>{this.props.address.country}</Text>
</div>
<div className="address-preview__actions">
{this.props.onEditClick ?
<div className="address-preview__edit" onClick={this.props.onEditClick}>
<Text weight="bold">
<FormattedMessage
message={intlStore.getMessage(intlData, 'edit')}
locales={intlStore.getCurrentLocale()} />
</Text>
</div>
:
null
}
{this.props.onDeleteClick ?
<div className="address-preview__delete" onClick={this.props.onDeleteClick}>
<Text>
<FormattedMessage
message={intlStore.getMessage(intlData, 'delete')}
locales={intlStore.getCurrentLocale()} />
</Text>
</div>
:
null
}
</div>
</div>
);
}
}
/**
* Exports
*/
export default AddressPreview;
|
'use strict';
var constants = require('../../lifx').constants;
var Packet = {
size: 21
};
/**
* Converts packet specific data from a buffer to an object
* @param {Buffer} buf Buffer containing only packet specific data no header
* @return {Object} Information contained in packet
*/
Packet.toObject = function(buf) {
var obj = {};
var offset = 0;
if (buf.length !== this.size) {
throw new Error('Invalid length given for setWaveform LIFX packet');
}
obj.stream = buf.readUInt8(offset);
offset += 1;
obj.isTransient = buf.readUInt8(offset);
offset += 1;
obj.color = {};
obj.color.hue = buf.readUInt16LE(offset);
offset += 2;
obj.color.saturation = buf.readUInt16LE(offset);
offset += 2;
obj.color.brightness = buf.readUInt16LE(offset);
offset += 2;
obj.color.kelvin = buf.readUInt16LE(offset);
offset += 2;
obj.period = buf.readUInt32LE(offset);
offset += 4;
obj.cycles = buf.readFloatLE(offset);
offset += 4;
obj.skewRatio = buf.readUInt16LE(offset);
offset += 2;
obj.waveform = buf.readUInt8(offset);
offset += 1;
return obj;
};
/**
* Converts the given packet specific object into a packet
* @param {Object} obj object with configuration data
* @param {Boolean} obj.isTransient restore color used before effect
* @param {Object} obj.color an objects with colors to set
* @param {Number} obj.color.hue between 0 and 65535
* @param {Number} obj.color.saturation between 0 and 65535
* @param {Number} obj.color.brightness between 0 and 65535
* @param {Number} [obj.color.kelvin=3500] between 2500 and 9000
* @param {Number} obj.period length of one cycle in milliseconds
* @param {Number} obj.cycles how often to repeat through effect
* @param {Number} obj.skewRatio distribution between time on original and new color , positive is for more new color, negative for original color
* @param {Number} obj.waveform between 0 and 4 for form of effect
* @return {Buffer} packet
*/
Packet.toBuffer = function(obj) {
var buf = new Buffer(this.size);
buf.fill(0);
var offset = 0;
// obj.stream field has unknown function so leave it as 0
offset += 1;
if (obj.isTransient === undefined) {
throw new TypeError('obj.isTransient value must be given for setWaveform LIFX packet');
}
if (typeof obj.isTransient !== 'boolean') {
throw new TypeError('Invalid isTransient value given for setWaveform LIFX packet, must be boolean');
}
buf.writeUInt8(obj.isTransient, offset);
offset += 1;
if (typeof obj.color !== 'object') {
throw new TypeError('Invalid object for color given for setWaveform LIFX packet');
}
if (typeof obj.color.hue !== 'number' && obj.color.hue < 0 || obj.color.hue > 65535) {
throw new RangeError('Invalid color hue given for setWaveform LIFX packet, must be a number between 0 and 65535');
}
buf.writeUInt16LE(obj.color.hue, offset);
offset += 2;
if (typeof obj.color.saturation !== 'number' && obj.color.saturation < 0 || obj.color.saturation > 65535) {
throw new RangeError('Invalid color saturation given for setWaveform LIFX packet, must be a number between 0 and 65535');
}
buf.writeUInt16LE(obj.color.saturation, offset);
offset += 2;
if (typeof obj.color.brightness !== 'number' && obj.color.brightness < 0 || obj.color.brightness > 65535) {
throw new RangeError('Invalid color brightness given for setWaveform LIFX packet, must be a number between 0 and 65535');
}
buf.writeUInt16LE(obj.color.brightness, offset);
offset += 2;
if (obj.color.kelvin === undefined) {
obj.color.kelvin = constants.HSBK_DEFAULT_KELVIN;
}
if (typeof obj.color.kelvin !== 'number' && obj.color.kelvin < 2500 || obj.color.kelvin > 9000) {
throw new RangeError('Invalid color kelvin given for setWaveform LIFX packet, must be a number between 2500 and 9000');
}
buf.writeUInt16LE(obj.color.kelvin, offset);
offset += 2;
if (obj.period === undefined) {
throw new TypeError('obj.period value must be given for setWaveform LIFX packet');
}
if (typeof obj.period !== 'number') {
throw new TypeError('Invalid period type given for setWaveform LIFX packet, must be a number');
}
buf.writeUInt32LE(obj.period, offset);
offset += 4;
if (obj.cycles === undefined) {
throw new TypeError('obj.cycles value must be given for setWaveform LIFX packet');
}
if (typeof obj.cycles !== 'number') {
throw new TypeError('Invalid cycles type given for setWaveform LIFX packet, must be a number');
}
buf.writeFloatLE(obj.cycles, offset);
offset += 4;
if (obj.skewRatio === undefined) {
throw new TypeError('obj.skewRatio value must be given for setWaveform LIFX packet');
}
if (typeof obj.skewRatio !== 'number') {
throw new TypeError('Invalid skewRatio type given for setWaveform LIFX packet, must be a number');
}
buf.writeInt16LE(obj.skewRatio, offset);
offset += 2;
if (obj.waveform === undefined) {
throw new TypeError('obj.waveform value must be given for setWaveform LIFX packet');
}
if (typeof obj.waveform !== 'number' && obj.waveform < 0 || obj.waveform > (constants.LIGHT_WAVEFORMS.length - 1)) {
throw new RangeError('Invalid waveform value given for setWaveform LIFX packet, must be a number between 0 and ' + (constants.LIGHT_WAVEFORMS.length - 1));
}
buf.writeUInt8(obj.waveform, offset);
offset += 1;
return buf;
};
module.exports = Packet;
|
import { createReducer } from 'redux-act';
import { fetchSystemStatus } from 'actions';
import { loadState, loadStart, loadError, loadComplete } from 'reducers/util';
const initialState = loadState();
export default createReducer({
[fetchSystemStatus.START]: state => loadStart(state),
[fetchSystemStatus.ERROR]: (state, { error }) => loadError(state, error),
[fetchSystemStatus.COMPLETE]: (state, { status }) => loadComplete(status),
}, initialState);
|
define(['durandal/app','lib/pagelayout', 'lib/prettify'], function (app, pagelayout, prettify) {
var activePage = ko.observable(),
hash = "",
oc;
return {
compositionComplete : function() {
var that = this;
oc = Stashy.OffCanvas("#sticky", { enableTouch : true });
pagelayout.offcanvasLayout(oc);
prettyPrint();
Stashy.Utils.ScrollTo('#' + that.hash);
},
activePage : activePage,
activate: function (page) {
var that = this;
if (page != undefined) {
that.hash = page;
Stashy.Utils.ScrollTo('#sticky #' + that.hash);
}
ga('send', 'pageview');
}
};
}); |
/*
to package
"eslint": "^1.7.3",
"eslint-config-rackt": "^1.1.0",
"eslint-plugin-react": "^3.6.3",
*/
require('es6-promise').polyfill(); // old node 0.10
var path = require('path');
var webpack = require('webpack');
module.exports = {
externals: {
jquery: "jQuery",
autobahn: "autobahn"
},
plugins: [
// new webpack.optimize.UglifyJsPlugin({minimize: true}),
new webpack.optimize.CommonsChunkPlugin(
/* chunkName= */'vendor',
/* filename= */'vendor.js'
),
/* new webpack.ProvidePlugin({ // If you use "_", underscore is automatically required
"$": "jquery",
"_": "underscore",
}) */
],
resolve: {
alias: {
"lodash": path.resolve("./node_modules/lodash"),
"react": path.resolve("./node_modules/react/react.js"),
"react-dom": path.resolve("./node_modules/react/lib/ReactDOM.js"),
"react-router": path.resolve("./node_modules/react-router"),
"reflux": path.resolve("./node_modules/reflux/src/index.js"),
"object-assign":path.resolve("./node_modules/object-assign/index.js"),
}
},
entry: {
// demoshop: [
// './demoshop/app.js'
// ],
// employee: [
// 'employee/views/contact.js'
// ],
navbar: [
'./navbar/app.js'
],
vendor: [
'lodash',
'react',
'react-dom',
'reflux',
'object-assign'
]
},
output: {
path: 'www/app',
filename: '[name].js',
publicPath: '/app/'
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel',
query: {
presets: ['es2015', 'stage-0', 'react']
}
},
{ test: /\.css$/, loader: 'style!css' },
{ test: /\.jpg$/, loader: "file-loader" },
{ test: /\.png$/, loader: "url-loader?mimetype=image/png" }
]
},
// devtool: 'source-map',
devtool: 'inline-source-map',
// scripts: {
// watch: "webpack --watch -d --display-error-details"
// }
};
|
require('uppercase-core');
require('./DIST/NODE.js');
|
define("foo", [ "./bar", "./baz/baz" ], function(require, exports, module) {
require("./bar");
require("./baz/baz");
}); |
exports.config = {
specs: require('./index-webdriver.js').specs(),
framework: 'qunit',
baseUrl: './',
capabilities: [{
browserName: 'phantomjs',
exclude: require('./index-webdriver.js').exclude('phantomjs')
}],
updateJob: false,
waitforTimeout: 1000,
logLevel: 'silent',
coloredLogs: true,
screenshotPath: 'build/webdriver/failed',
onPrepare: require('./index-webdriver.js').onPrepare,
before: require('./index-webdriver.js').before,
after: require('./index-webdriver.js').after,
onComplete: require('./index-webdriver.js').onComplete
};
|
var equal = require('assert').equal,
notEqual = require('assert').notEqual,
Pool = require('../lib').Pool;
describe('Pool', function () {
it('should run multiple scripts', function (finished) {
var pool = new Pool({numberOfInstances: 5});
var scriptsExited = 0;
for (var i = 0; i < 20; ++i) {
var script = pool.createScript("\
exports.main = function() {\n\
exit(testGlobal);\n\
}\n\
"
);
script.on('exit', function (err, result) {
scriptsExited++;
if (scriptsExited == 10) {
pool.kill();
equal(10, result);
finished();
}
});
script.run({testGlobal: 10});
}
});
it('should run scripts on non blocking instances', function (finished) {
var pool = new Pool({numberOfInstances: 2});
var exited = false;
// Create blocking script.
var script = pool.createScript("\
exports.main = function() {\n\
while(true);\
}\n\
"
);
script.run();
var scriptsExited = 0;
for (var i = 0; i < 10; ++i) {
var script2 = pool.createScript("\
exports.main = function() {\n\
exit(10);\n\
}\n\
"
);
script2.on('exit', function (err, result) {
scriptsExited++;
if (scriptsExited == 10) {
pool.kill();
equal(10, result);
exited = true;
finished();
}
});
script2.run();
}
setTimeout(function () {
if (!exited) {
equal(false, true);
}
}, 3000);
});
it('should not be created if there are zero or negative amount of specified instances', function (finished) {
var pool = null;
try {
pool = new Pool({numberOfInstances: 0});
equal(false, true);
} catch (error) {
notEqual(-1, error.indexOf("Can't create a pool with zero instances"));
finished();
}
});
});
|
//////////////////////////////////////////
//
// ONLY EDIT babel-plugin.js at ./src/babel-plugin.js, not ./babel-plugin.js!
//
//////////////////////////////////////////
var plugin = function(babel) {
return {
visitor: {
ObjectExpression(path) {
path.node.properties.forEach(function(prop){
if (prop.key.type === "Identifier") {
var keyLoc = prop.key.loc
prop.key = babel.types.stringLiteral(prop.key.name)
prop.key.loc = keyLoc
}
})
var call = babel.types.callExpression(
babel.types.identifier("__ohdMakeObject"), [babel.types.arrayExpression(
path.node.properties.map(function(prop) {
var type = babel.types.stringLiteral(prop.type)
type.ignore = true
if (prop.type === "ObjectMethod") {
// getter/setter
var kind = babel.types.stringLiteral(prop.kind);
kind.ignore = true;
var propArray = babel.types.arrayExpression([
type,
prop.key,
kind,
babel.types.functionExpression(
null,
prop.params,
prop.body
)
])
return propArray
} else {
var propArray = babel.types.arrayExpression([
type,
prop.key,
prop.value
])
return propArray
}
console.log("continue with type", prop.type)
})
)]
)
path.replaceWith(call)
},
AssignmentExpression(path) {
if (path.node.ignore) {
return
}
if (["+=", "-=", "/=", "*="].indexOf(path.node.operator) !== -1){
// I don't think this replacement is always going to be 100% equivalent
// to the +=/... operation, but it's close enough for now
// e.g. maybe there'd be props if path.node.left is sth like a.sth().aa would
// call sth twice
var operator = {"+=": "+", "-=": "-", "/=": "/", "*=": "*"}[path.node.operator]
var value = babel.types.binaryExpression(operator, path.node.left, path.node.right)
var replacement = babel.types.assignmentExpression("=", path.node.left, value)
path.replaceWith(replacement)
}
if (path.node.operator === "=" && path.node.left.type === "MemberExpression") {
var property;
if (path.node.left.computed === true) {
property = path.node.left.property
} else {
property = babel.types.stringLiteral(path.node.left.property.name)
property.loc = path.node.left.property.loc
}
var assignExpression = babel.types.callExpression(
babel.types.identifier("__ohdAssign"), [
path.node.left.object,
property,
path.node.right
]
)
assignExpression.loc = path.node.loc
path.replaceWith(assignExpression)
}
},
UnaryExpression(path) {
if (path.node.operator === "delete"){
var prop = path.node.argument.property
if (prop.type === "Identifier"){
prop = babel.types.stringLiteral(prop.name)
}
var call = babel.types.callExpression(
babel.types.identifier("__ohdDeleteProperty"),
[
path.node.argument.object,
prop
]
)
path.replaceWith(call)
}
}
}
}
}
if (typeof module === "undefined"){
window.babelPlugin = plugin;
} else {
module.exports = plugin
}
|
'use strict';
module.exports = function(app) {
var users = require('../../app/controllers/users.server.controller');
var companies = require('../../app/controllers/companies.server.controller');
var fields = require('../../app/controllers/fields.server.controller');
var schedules = require('../../app/controllers/schedules.server.controller');
// Companies Routes
app.route('/companies')
.get(companies.list)
.post(users.requiresLogin, companies.create);
app.route('/companies/:companyId')
.get(companies.read)
.put(users.requiresLogin, users.requiresAdmin, companies.update)
.delete(users.requiresLogin, users.requiresAdmin, companies.delete);
app.route('/companies/:companyId/fields')
.get(fields.list)
app.route('/companies/:companyId/schedules')
.get(schedules.list)
// Finish by binding the Company middleware
app.param('companyId', companies.companyByID);
};
|
import phantom from 'phantom';
import logger from '../Logger';
export default class PhantomFetcher {
initialize() {
if (this.instance && this.page) {
return Promise.resolve(this.page);
}
logger.info('Creating new PhantomJS instance');
return phantom.create()
.then(
(instance) => {
this.instance = instance;
return instance.createPage();
}
)
.then((page) => {
this.page = page;
// page.on('onResourceRequested', (requestData) => {
// console.info('Requesting', requestData.url);
// });
})
;
}
get(url) {
return new Promise((resolve, reject) => {
this.page.property('onError', (msg) => {
reject(msg);
});
this.page.open(url)
.then(
(/* status */) => {
// console.log(status);
return this.page.property('content');
},
(err) => {
reject(err);
}
)
.then(
(content) => {
// console.log(content);
this.page.evaluate(() => {
return document.location;
}).then((location) => {
resolve({
text: content,
location
});
}).catch((err) => {
reject(err);
});
}
);
});
}
}
|
const path = require('path');
const env = require('yargs').argv.mode;
const webpack = require('webpack');
const projectRoot = path.resolve(__dirname, '/');
const UglifyJsPlugin = webpack.optimize.UglifyJsPlugin;
const libraryName = '<%= libraryName %>';
const plugins = [];
let outputFile;
if (env === 'build') {
plugins.push(new UglifyJsPlugin({ minimize: true }));
outputFile = `${libraryName}.min.js`;
} else {
outputFile = `${libraryName}.js`;
}
const config = {
entry: `${__dirname}/src/index.js`,
devtool: 'source-map',
output: {
path: `${__dirname}/dist`,
filename: outputFile,
library: libraryName,
libraryTarget: 'umd',
umdNamedDefine: true
},
module: {
preLoaders: [
{
test: /(\.jsx|\.js)$/,
loader: 'eslint',
include: projectRoot,
exclude: /(node_modules|bower_components)/
}
],
loaders: [
{
test: /(\.jsx|\.js)$/,
loader: 'babel',
include: projectRoot,
exclude: /(node_modules|bower_components)/
}
]
},
resolve: {
root: path.resolve('./src'),
extensions: ['', '.js']
},
plugins
};
module.exports = config;
|
var searchData=
[
['makeexternal',['MakeExternal',['../classv8_1_1String.html#a5efd1eba40c1fa8a6aae2c4a175a63be',1,'v8::String::MakeExternal(ExternalStringResource *resource)'],['../classv8_1_1String.html#a19db11c97e2ce01244e06f5cbcd094f2',1,'v8::String::MakeExternal(ExternalAsciiStringResource *resource)']]],
['markasundetectable',['MarkAsUndetectable',['../classv8_1_1ObjectTemplate.html#a7e40ef313b44c2ad336c73051523b4f8',1,'v8::ObjectTemplate']]],
['markindependent',['MarkIndependent',['../classv8_1_1PersistentBase.html#aed12b0a54bc5ade1fb44e3bdb3a1fe74',1,'v8::PersistentBase']]],
['markpartiallydependent',['MarkPartiallyDependent',['../classv8_1_1PersistentBase.html#a4a876d30dda0dfb812e82bb240e4686e',1,'v8::PersistentBase']]],
['maybe',['Maybe',['../structv8_1_1Maybe.html',1,'v8']]],
['message',['Message',['../classv8_1_1Message.html',1,'v8']]],
['message',['Message',['../classv8_1_1Debug_1_1Message.html',1,'v8::Debug']]],
['message',['Message',['../classv8_1_1TryCatch.html#a2811e500fbb906ee505895a3d94fc66f',1,'v8::TryCatch']]],
['messagehandler',['MessageHandler',['../classv8_1_1Debug.html#a526826b857bd3e3efa184e12bcebc694',1,'v8::Debug']]]
];
|
AUTOBAHN_DEBUG = true;
var autobahn = require('autobahn');
var program = require('commander');
program
.option('-p, --port <port>', 'Server IP port', parseInt,9000)
.option('-i, --ip <ip>', 'Server IP address','127.0.0.1')
.parse(process.argv);
var connection = new autobahn.Connection({
url: 'ws://' + program.ip + ':' + program.port,
realm: 'realm1'}
);
connection.onopen = function (session) {
// Define an event handler
function onEvent(publishArgs, kwargs) {
console.log('Event received args', publishArgs, 'kwargs ',kwargs);
}
// Subscribe to a topic
session.subscribe('com.myapp.topic1', onEvent).then(
function(subscription) {
console.log("subscription successfull", subscription);
currentSubscription = subscription;
},
function(error) {
console.log("subscription failed", error);
}
);
// Exit after 5 minutes
setTimeout(
function() {
console.log("Terminating subscriber");
session.unsubscribe(currentSubscription).then(
function(gone) {
console.log("unsubscribe successfull");
connection.close();
},
function(error) {
console.log("unsubscribe failed", error);
connection.close();
}
);
},
300000
);
};
connection.open();
|
'use strict';
((window, document) => {
})(window, document);
|
/*
Time Count
TimeCount class, useful for incremental games
By Luke Nickerson, 2015
*/
(function(){
var TimeCount = function(){
this.lastTime = null;
}
TimeCount.prototype.setLastTime = function(){
}
// Install into RocketBoots if it exists, otherwise make global
if (typeof RocketBoots == "object") {
RocketBoots.installComponent(
"time_count", // file name
"TimeCount", // class name
TimeCount // class
);
} else window["TimeCount"] = TimeCount;
})(); |
import createSvgIcon from './utils/createSvgIcon';
import { jsx as _jsx } from "react/jsx-runtime";
export default createSvgIcon( /*#__PURE__*/_jsx("path", {
d: "M19 3h-4.18C14.4 1.84 13.3 1 12 1s-2.4.84-2.82 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-7 0c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zm1 14H8c-.55 0-1-.45-1-1s.45-1 1-1h5c.55 0 1 .45 1 1s-.45 1-1 1zm3-4H8c-.55 0-1-.45-1-1s.45-1 1-1h8c.55 0 1 .45 1 1s-.45 1-1 1zm0-4H8c-.55 0-1-.45-1-1s.45-1 1-1h8c.55 0 1 .45 1 1s-.45 1-1 1z"
}), 'AssignmentRounded'); |
//>>built
define({descTemplate:"${2} - ${3}/${1} ${0}",firstTip:"\uccab \ud398\uc774\uc9c0",lastTip:"\ub9c8\uc9c0\ub9c9 \ud398\uc774\uc9c0",nextTip:"\ub2e4\uc74c \ud398\uc774\uc9c0",prevTip:"\uc774\uc804 \ud398\uc774\uc9c0",itemTitle:"\ud56d\ubaa9",singularItemTitle:"\ud56d\ubaa9",pageStepLabelTemplate:"${0} \ud398\uc774\uc9c0",pageSizeLabelTemplate:"\ud398\uc774\uc9c0\ub2f9 ${0}\uac1c \ud56d\ubaa9",allItemsLabelTemplate:"\ubaa8\ub4e0 \ud56d\ubaa9",gotoButtonTitle:"\ud2b9\uc815 \ud398\uc774\uc9c0\ub85c \uc774\ub3d9",
dialogTitle:"\ud398\uc774\uc9c0 \uc774\ub3d9",dialogIndication:"\ud398\uc774\uc9c0 \ubc88\ud638 \uc9c0\uc815",pageCountIndication:" (${0}\ud398\uc774\uc9c0)",dialogConfirm:"\uc774\ub3d9",dialogCancel:"\ucde8\uc18c",all:"\ubaa8\ub450"}); |
/*
Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'indent', 'eu', {
indent: 'Handitu koska',
outdent: 'Txikitu koska'
} );
|
const path = require('path');
const consoleLogger = require('./logger');
const _ = require('lodash');
module.exports = (config, logger, metrics, next) => {
if (!next) { next = metrics; metrics = { increment: _.noop }; }
if (!next) { next = logger; logger = consoleLogger; }
require('../db')(config, logger, (err, client) => {
if (err) { return next(err); }
const messaging = require('../db/messaging')(config);
const urls = require('./urls');
const visibility = require('./visibility');
const api = {
logger,
metrics,
client,
config,
messaging,
urls,
visibility,
};
const modules = ['auth', 'common', 'user', 'post', 'like', 'feed', 'friend', 'follow', 'group', 'comment', 'moderate', 'interest', '../db/migrations'];
modules.forEach((module) => {
const moduleName = path.basename(module);
api[moduleName] = require(path.resolve(__dirname, module))(api);
});
next(null, api);
});
};
|
'use strict';
describe('Service: Location', function () {
// load the service's module
beforeEach(module('treasuremapApp'));
// instantiate service
var Location;
beforeEach(inject(function (_Location_) {
Location = _Location_;
}));
it('should do something', function () {
expect(!!Location).toBe(true);
});
});
|
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0z" /><path d="M23.64 7c-.45-.34-4.93-4-11.64-4-1.5 0-2.89.19-4.15.48L18.18 13.8 23.64 7zm-6.6 8.22L3.27 1.44 2 2.72l2.05 2.06C1.91 5.76.59 6.82.36 7l11.63 14.49.01.01.01-.01 3.9-4.86 3.32 3.32 1.27-1.27-3.46-3.46z" /></React.Fragment>
, 'SignalWifiOff');
|
(function() {
var checkVersion = Dagaz.Model.checkVersion;
Dagaz.Model.checkVersion = function(design, name, value) {
if (name != "magyar-no-pass") {
checkVersion(design, name, value);
}
}
var CheckInvariants = Dagaz.Model.CheckInvariants;
Dagaz.Model.CheckInvariants = function(board) {
var design = Dagaz.Model.design;
_.each(board.moves, function(move) {
if (move.isSimpleMove() && (move.actions[0][0][0] == move.actions[0][1][0])) {
move.failed = true;
}
});
CheckInvariants(board);
}
})();
|
/*
* UserLogin Messages
*
* This contains all the text for the UserLogin component.
*/
import { defineMessages } from 'react-intl';
export default defineMessages({
header: {
id: 'app.containers.UserLogin.header',
defaultMessage: 'This is UserLogin container !',
},
usernameInput: {
id: 'app.containers.login_page.username',
defaultMessage: 'Username',
},
passwordInput: {
id: 'app.containers.login_page.password',
defaultMessage: 'Password',
},
rememberMe: {
id: 'app.containers.login_page.rememberMe',
defaultMessage: 'Remember Login',
},
isPrivateComputer: {
id: 'app.containers.login_page.computer_is_private',
defaultMessage: 'if this is a private computer',
},
logInButton: {
id: 'app.containers.login_page.log_in',
defaultMessage: 'Log In',
},
// Eventually the backend should be returning a constant
defaultLoginError: {
id: 'app.containers.login_page.log_in',
defaultMessage: 'Wrong username or password.',
},
});
|
"use babel";
// @flow
export function filterAtomEnv(env: Object) {
const filteredVars = ["ATOM_HOME", "NODE_PATH"];
return Object.entries(env).reduce((newEnv, [key, value]) => {
if (filteredVars.find(v => v === key) != null) return newEnv;
return { ...newEnv, [key]: value };
}, {});
}
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = clean;
var _path = require('path');
var _del = require('del');
var _del2 = _interopRequireDefault(_del);
var _config = require('../config');
var _config2 = _interopRequireDefault(_config);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function clean(dir) {
var dist = (0, _config2.default)(dir).distDir;
return (0, _del2.default)((0, _path.resolve)(dir, dist), { force: true });
} |
import { expect } from 'chai';
import { Promise } from 'es6-promise';
import { Db } from 'mongodb';
import { Factory } from '../src/index';
import { hooks } from '../src/hooks';
describe('API spec', function() {
const Adapter = Factory();
it('Adapter object API', function() {
expect(Adapter).to.have.all.keys('connect', 'close', 'query');
[
Adapter.connect,
Adapter.close,
Adapter.query,
].forEach(function(func) {
expect(func).to.be.ok.and.to.be.a('function');
});
});
it('Query object API', function() {
const Query = Factory().query();
expect(Query).to.have.all.keys('insert', 'find', 'findOne', 'deleteOne', 'deleteMany', 'updateOne', 'updateMany');
[
Query.insert,
Query.find,
Query.findOne,
Query.updateOne,
Query.updateMany,
Query.deleteOne,
Query.deleteMany,
].forEach(function(func) {
expect(func).to.be.ok.and.to.be.a('function');
});
});
});
describe('Connection behavior', function() {
it('should be connected and disconnected', function(done) {
const connectedFactory = Factory({
database: 'test',
});
connectedFactory.connect().catch(done).then(function(adapter) {
expect(adapter.getDatabase()).to.be.instanceof(Db);
adapter.close().catch(done).then(done);
});
});
});
describe('Create documents', function() {
const Adapter = Factory({
database: 'test',
});
before(function(done) {
Adapter.connect().catch(done).then(function() {
done();
});
});
it('should return Promise', function() {
const Query = Adapter.query('orm_test');
expect(Query.insert({
key: 'value'
}).exec()).to.be.instanceof(Promise);
expect(Query.insert([{
key: 'value'
},
{
key: 'value'
}]).exec()).to.be.instanceof(Promise);
});
});
describe('Read documents', function() {
const Adapter = Factory({
database: 'test',
});
before(function(done) {
Adapter.connect().catch(done).then(function() {
done();
});
});
it('should return Promise and be equal inserted data', function(done) {
const Query = Adapter.query('orm_test');
Promise.resolve(null)
.then(function() {
return Query.find({
key: 'value'
}).exec().then(function(data) {
expect(data.slice).to.be.ok.and.to.be.a('function');
expect(data[0].key).to.be.ok.and.to.be.eql('value');
});
})
.then(function() {
Query.findOne({
key: 'value'
}).exec().then(function(data) {
expect(data.key).to.be.ok.and.to.be.eql('value');
Adapter.close();
done();
});
});
});
});
describe('Update documents', function(done) {
const Adapter = Factory({
database: 'test',
});
before(function(done) {
Adapter.connect().catch(done).then(function() {
done();
});
});
it('should return Promise and data must be updated', function(done) {
const Query = Adapter.query('orm_test');
Promise.resolve(null).then(function() {
return Query.updateMany({
key: 'value',
}, {
$set: {
param: 'value',
}
}).exec().then(function(data) {
expect(data.modifiedCount).to.be.ok.and.to.be.not.equal(0);
});
}).then(function() {
return Query.updateOne({
key: 'value',
}, {
$set: {
only: 'value',
}
}).exec().then(function(data) {
expect(data.modifiedCount).to.be.ok.and.to.be.not.equal(0);
Adapter.close();
done();
});
});
});
});
describe('Delete documents', function(done) {
const Adapter = Factory({
database: 'test',
});
before(function(done) {
Adapter.connect().catch(done).then(function() {
done();
});
});
it('should return Promise and data must be deleted', function(done) {
const Query = Adapter.query('orm_test');
Promise.resolve(null)
.then(function() {
const result = Query.deleteOne({
key: 'value',
}).exec().then(function(data) {
expect(data.deletedCount).to.be.ok.and.to.be.eql(1);
expect(result).to.be.instanceof(Promise);
});
}).then(function() {
const result = Query.deleteMany({
key: 'value',
}).exec().then(function(data) {
expect(data.deletedCount).to.be.ok.and.to.be.eql(2);
expect(result).to.be.instanceof(Promise);
Adapter.close();
done();
});
});
});
});
describe('Hooks test', function() {
const Adapter = Factory({
database: 'test',
});
before(function(done) {
Adapter.connect().catch(done).then(function() {
done();
});
});
it('Hooks should process passing data', function(done) {
const Query = Adapter.query('orm_test');
hooks.registerBeforeHook('insert', function(value) {
value.before = 'before';
return value;
});
hooks.registerAfterHook('insert', function(value) {
return value.insertedCount;
});
hooks.registerBeforeHook('find', function(value) {
value.key = 'value';
return value;
});
hooks.registerAfterHook('find', function(value) {
value.after = 'after';
return value;
});
Query.insert({
key: 'value',
}).exec().then(function(data) {
expect(data).to.be.ok.and.to.be.eql(1);
});
Query.findOne({}).exec().then(function(data) {
expect(data.key).to.be.ok.and.to.be.eql('value');
expect(data.before).to.be.ok.and.to.be.eql('before');
expect(data.after).to.be.ok.and.to.be.eql('after');
clearHooks('insert');
clearHooks('find')
});
Query.deleteMany({
key: 'value',
}).exec().then(function(data) {
Adapter.close();
done();
});
});
});
|
import { checkTest } from './utils';
var MethodCallTracker = function(env, methodName) {
this._env = env;
this._methodName = methodName;
this._isExpectingNoCalls = false;
this._expecteds = [];
this._actuals = [];
};
MethodCallTracker.prototype = {
stubMethod() {
if (this._originalMethod) {
// Method is already stubbed
return;
}
let env = this._env;
let methodName = this._methodName;
this._originalMethod = env.getDebugFunction(methodName);
env.setDebugFunction(methodName, (message, test) => {
let resultOfTest = checkTest(test);
this._actuals.push([message, resultOfTest]);
});
},
restoreMethod() {
if (this._originalMethod) {
this._env.setDebugFunction(this._methodName, this._originalMethod);
}
},
expectCall(message) {
this.stubMethod();
this._expecteds.push(message || /.*/);
},
expectNoCalls() {
this.stubMethod();
this._isExpectingNoCalls = true;
},
isExpectingNoCalls() {
return this._isExpectingNoCalls;
},
isExpectingCalls() {
return !this._isExpectingNoCalls && this._expecteds.length;
},
assert() {
let { assert } = QUnit.config.current;
let env = this._env;
let methodName = this._methodName;
let isExpectingNoCalls = this._isExpectingNoCalls;
let expecteds = this._expecteds;
let actuals = this._actuals;
let o, i;
if (!isExpectingNoCalls && expecteds.length === 0 && actuals.length === 0) {
return;
}
if (env.runningProdBuild) {
assert.ok(true, `calls to Ember.${methodName} disabled in production builds.`);
return;
}
if (isExpectingNoCalls) {
let actualMessages = [];
for (i = 0; i < actuals.length; i++) {
if (!actuals[i][1]) {
actualMessages.push(actuals[i][0]);
}
}
assert.ok(
actualMessages.length === 0,
`Expected no Ember.${methodName} calls, got ${actuals.length}: ${actualMessages.join(', ')}`
);
return;
}
let expected, actual, match;
for (o = 0; o < expecteds.length; o++) {
expected = expecteds[o];
for (i = 0; i < actuals.length; i++) {
actual = actuals[i];
if (!actual[1]) {
if (expected instanceof RegExp) {
if (expected.test(actual[0])) {
match = actual;
break;
}
} else {
if (expected === actual[0]) {
match = actual;
break;
}
}
}
}
if (!actual) {
assert.ok(false, `Received no Ember.${methodName} calls at all, expecting: ${expected}`);
} else if (match && !match[1]) {
assert.ok(true, `Received failing Ember.${methodName} call with message: ${match[0]}`);
} else if (match && match[1]) {
assert.ok(
false,
`Expected failing Ember.${methodName} call, got succeeding with message: ${match[0]}`
);
} else if (actual[1]) {
assert.ok(
false,
`Did not receive failing Ember.${methodName} call matching '${expected}', last was success with '${
actual[0]
}'`
);
} else if (!actual[1]) {
assert.ok(
false,
`Did not receive failing Ember.${methodName} call matching '${expected}', last was failure with '${
actual[0]
}'`
);
}
}
},
};
export default MethodCallTracker;
|
/**
* Example on how to use regular NodeJS files, the (module)exports is used
*/
var config = require('../../index')();
console.log(config.message);
// $> node example.js -> "We are in development"
// $> NODE_ENV=production node example.js -> "We are in production" |
!function(e){if("object"==typeof exports)module.exports=e();else if("function"==typeof define&&define.amd)define(e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.qs=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
/**
* Object#toString() ref for stringify().
*/
var toString = Object.prototype.toString;
/**
* Object#hasOwnProperty ref
*/
var hasOwnProperty = Object.prototype.hasOwnProperty;
/**
* Array#indexOf shim.
*/
var indexOf = typeof Array.prototype.indexOf === 'function'
? function(arr, el) { return arr.indexOf(el); }
: function(arr, el) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] === el) return i;
}
return -1;
};
/**
* Array.isArray shim.
*/
var isArray = Array.isArray || function(arr) {
return toString.call(arr) == '[object Array]';
};
/**
* Object.keys shim.
*/
var objectKeys = Object.keys || function(obj) {
var ret = [];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
ret.push(key);
}
}
return ret;
};
/**
* Array#forEach shim.
*/
var forEach = typeof Array.prototype.forEach === 'function'
? function(arr, fn) { return arr.forEach(fn); }
: function(arr, fn) {
for (var i = 0; i < arr.length; i++) fn(arr[i]);
};
/**
* Array#reduce shim.
*/
var reduce = function(arr, fn, initial) {
if (typeof arr.reduce === 'function') return arr.reduce(fn, initial);
var res = initial;
for (var i = 0; i < arr.length; i++) res = fn(res, arr[i]);
return res;
};
/**
* Cache non-integer test regexp.
*/
var isint = /^[0-9]+$/;
function promote(parent, key) {
if (parent[key].length == 0) return parent[key] = {}
var t = {};
for (var i in parent[key]) {
if (hasOwnProperty.call(parent[key], i)) {
t[i] = parent[key][i];
}
}
parent[key] = t;
return t;
}
function parse(parts, parent, key, val) {
var part = parts.shift();
// illegal
if (Object.getOwnPropertyDescriptor(Object.prototype, key)) return;
// end
if (!part) {
if (isArray(parent[key])) {
parent[key].push(val);
} else if ('object' == typeof parent[key]) {
parent[key] = val;
} else if ('undefined' == typeof parent[key]) {
parent[key] = val;
} else {
parent[key] = [parent[key], val];
}
// array
} else {
var obj = parent[key] = parent[key] || [];
if (']' == part) {
if (isArray(obj)) {
if ('' != val) obj.push(val);
} else if ('object' == typeof obj) {
obj[objectKeys(obj).length] = val;
} else {
obj = parent[key] = [parent[key], val];
}
// prop
} else if (~indexOf(part, ']')) {
part = part.substr(0, part.length - 1);
if (!isint.test(part) && isArray(obj)) obj = promote(parent, key);
parse(parts, obj, part, val);
// key
} else {
if (!isint.test(part) && isArray(obj)) obj = promote(parent, key);
parse(parts, obj, part, val);
}
}
}
/**
* Merge parent key/val pair.
*/
function merge(parent, key, val){
if (~indexOf(key, ']')) {
var parts = key.split('[')
, len = parts.length
, last = len - 1;
parse(parts, parent, 'base', val);
// optimize
} else {
if (!isint.test(key) && isArray(parent.base)) {
var t = {};
for (var k in parent.base) t[k] = parent.base[k];
parent.base = t;
}
set(parent.base, key, val);
}
return parent;
}
/**
* Compact sparse arrays.
*/
function compact(obj) {
if ('object' != typeof obj) return obj;
if (isArray(obj)) {
var ret = [];
for (var i in obj) {
if (hasOwnProperty.call(obj, i)) {
ret.push(obj[i]);
}
}
return ret;
}
for (var key in obj) {
obj[key] = compact(obj[key]);
}
return obj;
}
/**
* Parse the given obj.
*/
function parseObject(obj){
var ret = { base: {} };
forEach(objectKeys(obj), function(name){
merge(ret, name, obj[name]);
});
return compact(ret.base);
}
/**
* Parse the given str.
*/
function parseString(str){
var ret = reduce(String(str).split('&'), function(ret, pair){
var eql = indexOf(pair, '=')
, brace = lastBraceInKey(pair)
, key = pair.substr(0, brace || eql)
, val = pair.substr(brace || eql, pair.length)
, val = val.substr(indexOf(val, '=') + 1, val.length);
// ?foo
if ('' == key) key = pair, val = '';
if ('' == key) return ret;
return merge(ret, decode(key), decode(val));
}, { base: {} }).base;
return compact(ret);
}
/**
* Parse the given query `str` or `obj`, returning an object.
*
* @param {String} str | {Object} obj
* @return {Object}
* @api public
*/
exports.parse = function(str){
if (null == str || '' == str) return {};
return 'object' == typeof str
? parseObject(str)
: parseString(str);
};
/**
* Turn the given `obj` into a query string
*
* @param {Object} obj
* @return {String}
* @api public
*/
var stringify = exports.stringify = function(obj, prefix) {
if (isArray(obj)) {
return stringifyArray(obj, prefix);
} else if ('[object Object]' == toString.call(obj)) {
return stringifyObject(obj, prefix);
} else if ('string' == typeof obj) {
return stringifyString(obj, prefix);
} else {
return prefix + '=' + encodeURIComponent(String(obj));
}
};
/**
* Stringify the given `str`.
*
* @param {String} str
* @param {String} prefix
* @return {String}
* @api private
*/
function stringifyString(str, prefix) {
if (!prefix) throw new TypeError('stringify expects an object');
return prefix + '=' + encodeURIComponent(str);
}
/**
* Stringify the given `arr`.
*
* @param {Array} arr
* @param {String} prefix
* @return {String}
* @api private
*/
function stringifyArray(arr, prefix) {
var ret = [];
if (!prefix) throw new TypeError('stringify expects an object');
for (var i = 0; i < arr.length; i++) {
ret.push(stringify(arr[i], prefix + '[' + i + ']'));
}
return ret.join('&');
}
/**
* Stringify the given `obj`.
*
* @param {Object} obj
* @param {String} prefix
* @return {String}
* @api private
*/
function stringifyObject(obj, prefix) {
var ret = []
, keys = objectKeys(obj)
, key;
for (var i = 0, len = keys.length; i < len; ++i) {
key = keys[i];
if ('' == key) continue;
if (null == obj[key]) {
ret.push(encodeURIComponent(key) + '=');
} else {
ret.push(stringify(obj[key], prefix
? prefix + '[' + encodeURIComponent(key) + ']'
: encodeURIComponent(key)));
}
}
return ret.join('&');
}
/**
* Set `obj`'s `key` to `val` respecting
* the weird and wonderful syntax of a qs,
* where "foo=bar&foo=baz" becomes an array.
*
* @param {Object} obj
* @param {String} key
* @param {String} val
* @api private
*/
function set(obj, key, val) {
var v = obj[key];
if (Object.getOwnPropertyDescriptor(Object.prototype, key)) return;
if (undefined === v) {
obj[key] = val;
} else if (isArray(v)) {
v.push(val);
} else {
obj[key] = [v, val];
}
}
/**
* Locate last brace in `str` within the key.
*
* @param {String} str
* @return {Number}
* @api private
*/
function lastBraceInKey(str) {
var len = str.length
, brace
, c;
for (var i = 0; i < len; ++i) {
c = str[i];
if (']' == c) brace = false;
if ('[' == c) brace = true;
if ('=' == c && !brace) return i;
}
}
/**
* Decode `str`.
*
* @param {String} str
* @return {String}
* @api private
*/
function decode(str) {
try {
return decodeURIComponent(str.replace(/\+/g, ' '));
} catch (err) {
return str;
}
}
},{}]},{},[1])
(1)
});
|
var env = require('./environment.js');
exports.config = {
seleniumAddress: env.seleniumAddress,
framework: 'jasmine',
specs: ['pass_spec.js'],
baseUrl: env.baseUrl,
plugins: [{
path: '../index.js',
failOnWarning: false,
failOnError: false
}]
};
|
#!/usr/bin/env node
/*
*
* Copyright 2013 Anis Kadri
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
// copyright (c) 2013 Andrew Lunny, Adobe Systems
var path = require('path')
, url = require('url')
, package = require(path.join(__dirname, 'package'))
, nopt = require('nopt')
, plugins = require('./src/util/plugins')
, Q = require('q')
, plugman = require('./plugman');
var known_opts = { 'platform' : [ 'ios', 'android', 'amazon-fireos', 'blackberry10', 'wp7', 'wp8' , 'windows8', 'firefoxos' ]
, 'project' : path
, 'plugin' : [String, path, url, Array]
, 'version' : Boolean
, 'help' : Boolean
, 'debug' : Boolean
, 'silent' : Boolean
, 'plugins': path
, 'link': Boolean
, 'variable' : Array
, 'www': path
, 'searchpath' : [path, Array]
}, shortHands = { 'var' : ['--variable'], 'v': ['--version'], 'h': ['--help'] };
var cli_opts = nopt(known_opts, shortHands);
var cmd = cli_opts.argv.remain.shift();
// Without these arguments, the commands will fail and print the usage anyway.
if (cli_opts.plugins_dir || cli_opts.project) {
cli_opts.plugins_dir = typeof cli_opts.plugins_dir == 'string' ?
cli_opts.plugins_dir :
path.join(cli_opts.project, 'cordova', 'plugins');
}
process.on('uncaughtException', function(error) {
if (cli_opts.debug) {
console.error(error.stack);
} else {
console.error(error.message);
}
process.exit(1);
});
// Set up appropriate logging based on events
if (cli_opts.debug) {
plugman.on('verbose', console.log);
}
if (!cli_opts.silent) {
plugman.on('log', console.log);
plugman.on('warn', console.warn);
plugman.on('results', console.log);
}
plugman.on('error', console.error);
if (cli_opts.version) {
console.log(package.version);
} else if (cli_opts.help) {
console.log(plugman.help());
} else if (plugman.commands[cmd]) {
var result = plugman.commands[cmd](cli_opts);
if (result && Q.isPromise(result)) {
result.done();
}
} else {
console.log(plugman.help());
}
|
import {CYCLE_STATES, PRACTICE, REFLECTION, COMPLETE} from 'src/common/models/cycle'
import {userCan} from 'src/common/util'
import getUser from 'src/server/actions/getUser'
import assertUserIsMember from 'src/server/actions/assertUserIsMember'
import createNextCycleForChapter from 'src/server/actions/createNextCycleForChapter'
import {Cycle, getCyclesInStateForChapter, getLatestCycleForChapter} from 'src/server/services/dataService'
import {
LGCLIUsageError,
LGNotAuthorizedError,
LGForbiddenError,
LGBadRequestError,
} from 'src/server/util/error'
const subcommands = {
async init(args, {user}) {
const mergedUser = await getUser(user.id)
const currentCycle = await getLatestCycleForChapter(mergedUser.chapterId)
if (currentCycle.state !== REFLECTION && currentCycle.state !== COMPLETE) {
throw new LGBadRequestError('Failed to initialize a new cycle because the current cycle is still in progress.')
}
await _createCycle(mergedUser)
return {
text: '🔃 Initializing Cycle ... stand by.'
}
},
async launch(args, {user}) {
await _changeCycleState(user, PRACTICE)
return {
text: '🚀 Initiating Launch ... stand by.',
}
},
async reflect(args, {user}) {
await _changeCycleState(user, REFLECTION)
return {
text: '🤔 Initiating Reflection... stand by.',
}
},
}
export async function invoke(args, options) {
if (args._.length >= 1) {
const subcommand = args._[0]
return await subcommands[subcommand](args.$[subcommand], options)
}
throw new LGCLIUsageError()
}
async function _createCycle(user) {
if (!userCan(user, 'createCycle')) {
throw new LGNotAuthorizedError()
}
const member = await assertUserIsMember(user.id)
return await createNextCycleForChapter(member.chapterId)
}
async function _changeCycleState(user, newState) {
const newStateIndex = CYCLE_STATES.indexOf(newState)
if (!userCan(user, 'updateCycle')) {
throw new LGNotAuthorizedError()
}
const member = await assertUserIsMember(user.id)
if (newStateIndex === -1) {
throw new LGBadRequestError(`Invalid cycle state ${newState}`)
}
if (newStateIndex === 0) {
throw new LGForbiddenError(`You cannot change the cycle state back to ${newState}`)
}
const validOriginState = CYCLE_STATES[newStateIndex - 1]
const cycles = await getCyclesInStateForChapter(member.chapterId, validOriginState)
if (cycles.length === 0) {
throw new LGForbiddenError(`No cycles for the chapter in ${validOriginState} state`)
}
return Cycle.get(cycles[0].id).updateWithTimestamp({state: newState})
}
|
/**
* Created by sunNode on 16/10/16.
*/
var should = require('should')
var app = require('../app')
var request = require('supertest')
describe('upload temporyary testing', function () {
it('uploadTemporyary should be return success', function (done) {
request(app)
.get('/admin/crawler')
.end(function (err, res) {
if (err) throw err
should.exist(res.text)
done()
})
})
})
|
module.exports = { str: "7.5.0" };
|
/**
* AUTOMATICALLY GENERATED FILE, DO NOT EDIT MANUALLY!
* Update this file by running `lerna run webpack-updater` in the monorepo root folder.
*/
var ClientSideRowModelModule = require('../../community-modules/client-side-row-model');
var GridCoreModule = require('../../community-modules/core');
var CsvExportModule = require('../../community-modules/csv-export');
var InfiniteRowModelModule = require('../../community-modules/infinite-row-model');
var agGrid = require('./dist/es6/main');
Object.keys(agGrid).forEach(function(key) {
exports[key] = agGrid[key];
});
agGrid.ModuleRegistry.register(ClientSideRowModelModule.ClientSideRowModelModule);
agGrid.ModuleRegistry.register(CsvExportModule.CsvExportModule);
agGrid.ModuleRegistry.register(InfiniteRowModelModule.InfiniteRowModelModule);
|
"use strict";var __importDefault=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(exports,"__esModule",{value:!0});const d3_selection_1=require("d3-selection"),d3_color_1=require("d3-color"),utils_1=__importDefault(require("../utils")),evaluate_1=__importDefault(require("../evaluate"));function scatter(t){const e=t.meta.xScale,r=t.meta.yScale;return function(l){l.each(function(l){let o,a;const c=l.index,i=utils_1.default.color(l,c),u=evaluate_1.default(t,l),n=[];for(o=0;o<u.length;o+=1)for(a=0;a<u[o].length;a+=1)n.push(u[o][a]);const s=d3_selection_1.select(this).selectAll(":scope > circle").data(n),_=s.enter().append("circle");s.merge(_).attr("fill",d3_color_1.hsl(i.toString()).brighter(1.5).hex()).attr("stroke",i).attr("opacity",.7).attr("r",1).attr("cx",function(t){return e(t[0])}).attr("cy",function(t){return r(t[1])}).attr(l.attr),s.exit().remove()})}}exports.default=scatter; |
/* *
*
* (c) 2009-2019 Øystein Moseng
*
* Accessibility component for chart info region and table.
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from '../../../parts/Globals.js';
var doc = H.win.document, format = H.format;
import U from '../../../parts/Utilities.js';
var extend = U.extend, pick = U.pick;
import AccessibilityComponent from '../AccessibilityComponent.js';
import ChartUtilities from '../utils/chartUtilities.js';
var unhideChartElementFromAT = ChartUtilities.unhideChartElementFromAT, getChartTitle = ChartUtilities.getChartTitle, getAxisDescription = ChartUtilities.getAxisDescription;
import HTMLUtilities from '../utils/htmlUtilities.js';
var addClass = HTMLUtilities.addClass, setElAttrs = HTMLUtilities.setElAttrs, escapeStringForHTML = HTMLUtilities.escapeStringForHTML, stripHTMLTagsFromString = HTMLUtilities.stripHTMLTagsFromString, getElement = HTMLUtilities.getElement, visuallyHideElement = HTMLUtilities.visuallyHideElement;
/* eslint-disable no-invalid-this, valid-jsdoc */
/**
* @private
*/
function getTypeDescForMapChart(chart, formatContext) {
return formatContext.mapTitle ?
chart.langFormat('accessibility.chartTypes.mapTypeDescription', formatContext) :
chart.langFormat('accessibility.chartTypes.unknownMap', formatContext);
}
/**
* @private
*/
function getTypeDescForCombinationChart(chart, formatContext) {
return chart.langFormat('accessibility.chartTypes.combinationChart', formatContext);
}
/**
* @private
*/
function getTypeDescForEmptyChart(chart, formatContext) {
return chart.langFormat('accessibility.chartTypes.emptyChart', formatContext);
}
/**
* @private
*/
function buildTypeDescriptionFromSeries(chart, types, context) {
var firstType = types[0], typeExplaination = chart.langFormat('accessibility.seriesTypeDescriptions.' + firstType, context), multi = chart.series && chart.series.length < 2 ? 'Single' : 'Multiple';
return (chart.langFormat('accessibility.chartTypes.' + firstType + multi, context) ||
chart.langFormat('accessibility.chartTypes.default' + multi, context)) + (typeExplaination ? ' ' + typeExplaination : '');
}
/**
* @private
*/
function getTableSummary(chart) {
return chart.langFormat('accessibility.table.tableSummary', { chart: chart });
}
/**
* @private
*/
function stripEmptyHTMLTags(str) {
return str.replace(/<(\w+)[^>]*?>\s*<\/\1>/g, '');
}
/**
* @private
*/
function enableSimpleHTML(str) {
return str
.replace(/<(h[1-7]|p|div)>/g, '<$1>')
.replace(/</(h[1-7]|p|div|a|button)>/g, '</$1>')
.replace(/<(div|a|button) id="([a-zA-Z\-0-9#]*?)">/g, '<$1 id="$2">');
}
/**
* @private
*/
function stringToSimpleHTML(str) {
return stripEmptyHTMLTags(enableSimpleHTML(escapeStringForHTML(str)));
}
/**
* Return simplified explaination of chart type. Some types will not be familiar
* to most users, but in those cases we try to add an explaination of the type.
*
* @private
* @function Highcharts.Chart#getTypeDescription
* @param {Array<string>} types The series types in this chart.
* @return {string} The text description of the chart type.
*/
H.Chart.prototype.getTypeDescription = function (types) {
var firstType = types[0], firstSeries = this.series && this.series[0] || {}, formatContext = {
numSeries: this.series.length,
numPoints: firstSeries.points && firstSeries.points.length,
chart: this,
mapTitle: firstSeries.mapTitle
};
if (!firstType) {
return getTypeDescForEmptyChart(this, formatContext);
}
if (firstType === 'map') {
return getTypeDescForMapChart(this, formatContext);
}
if (this.types.length > 1) {
return getTypeDescForCombinationChart(this, formatContext);
}
return buildTypeDescriptionFromSeries(this, types, formatContext);
};
/**
* The InfoRegionsComponent class
*
* @private
* @class
* @name Highcharts.InfoRegionsComponent
*/
var InfoRegionsComponent = function () { };
InfoRegionsComponent.prototype = new AccessibilityComponent();
extend(InfoRegionsComponent.prototype, /** @lends Highcharts.InfoRegionsComponent */ {
/**
* Init the component
* @private
*/
init: function () {
var chart = this.chart, component = this;
this.initRegionsDefinitions();
this.addEvent(chart, 'afterGetTable', function (e) {
component.onDataTableCreated(e);
});
this.addEvent(chart, 'afterViewData', function (tableDiv) {
component.dataTableDiv = tableDiv;
// Use small delay to give browsers & AT time to register new table
setTimeout(function () {
component.focusDataTable();
}, 300);
});
},
/**
* @private
*/
initRegionsDefinitions: function () {
var component = this;
this.screenReaderSections = {
before: {
element: null,
buildContent: function (chart) {
var formatter = chart.options.accessibility
.screenReaderSection.beforeChartFormatter;
return formatter ? formatter(chart) :
component.defaultBeforeChartFormatter(chart);
},
insertIntoDOM: function (el, chart) {
chart.renderTo.insertBefore(el, chart.renderTo.firstChild);
},
afterInserted: function () {
if (typeof component.dataTableButtonId !== 'undefined') {
component.initDataTableButton(component.dataTableButtonId);
}
}
},
after: {
element: null,
buildContent: function (chart) {
var formatter = chart.options.accessibility.screenReaderSection
.afterChartFormatter;
return formatter ? formatter(chart) :
component.defaultAfterChartFormatter();
},
insertIntoDOM: function (el, chart) {
chart.renderTo.insertBefore(el, chart.container.nextSibling);
}
}
};
},
/**
* Called on first render/updates to the chart, including options changes.
*/
onChartUpdate: function () {
var component = this;
this.linkedDescriptionElement = this.getLinkedDescriptionElement();
this.setLinkedDescriptionAttrs();
Object.keys(this.screenReaderSections).forEach(function (regionKey) {
component.updateScreenReaderSection(regionKey);
});
},
/**
* @private
*/
getLinkedDescriptionElement: function () {
var chartOptions = this.chart.options, linkedDescOption = chartOptions.accessibility.linkedDescription;
if (!linkedDescOption) {
return;
}
if (typeof linkedDescOption !== 'string') {
return linkedDescOption;
}
var query = format(linkedDescOption, this.chart), queryMatch = doc.querySelectorAll(query);
if (queryMatch.length === 1) {
return queryMatch[0];
}
},
/**
* @private
*/
setLinkedDescriptionAttrs: function () {
var el = this.linkedDescriptionElement;
if (el) {
el.setAttribute('aria-hidden', 'true');
addClass(el, 'highcharts-linked-description');
}
},
/**
* @private
* @param {string} regionKey The name/key of the region to update
*/
updateScreenReaderSection: function (regionKey) {
var chart = this.chart, region = this.screenReaderSections[regionKey], content = region.buildContent(chart), sectionDiv = region.element = (region.element || this.createElement('div')), hiddenDiv = (sectionDiv.firstChild || this.createElement('div'));
this.setScreenReaderSectionAttribs(sectionDiv, regionKey);
hiddenDiv.innerHTML = content;
sectionDiv.appendChild(hiddenDiv);
region.insertIntoDOM(sectionDiv, chart);
visuallyHideElement(hiddenDiv);
unhideChartElementFromAT(chart, hiddenDiv);
if (region.afterInserted) {
region.afterInserted();
}
},
/**
* @private
* @param {Highcharts.HTMLDOMElement} sectionDiv The section element
* @param {string} regionKey Name/key of the region we are setting attrs for
*/
setScreenReaderSectionAttribs: function (sectionDiv, regionKey) {
var labelLangKey = ('accessibility.screenReaderSection.' + regionKey + 'RegionLabel'), chart = this.chart, labelText = chart.langFormat(labelLangKey, { chart: chart }), sectionId = 'highcharts-screen-reader-region-' + regionKey + '-' +
chart.index;
setElAttrs(sectionDiv, {
id: sectionId,
'aria-label': labelText
});
// Sections are wrapped to be positioned relatively to chart in case
// elements inside are tabbed to.
sectionDiv.style.position = 'relative';
if (chart.options.accessibility.landmarkVerbosity === 'all' &&
labelText) {
sectionDiv.setAttribute('role', 'region');
}
},
/**
* @private
* @return {string}
*/
defaultBeforeChartFormatter: function () {
var chart = this.chart, format = chart.options.accessibility
.screenReaderSection.beforeChartFormat, axesDesc = this.getAxesDescription(), dataTableButtonId = 'hc-linkto-highcharts-data-table-' +
chart.index, context = {
chartTitle: getChartTitle(chart),
typeDescription: this.getTypeDescriptionText(),
chartSubtitle: this.getSubtitleText(),
chartLongdesc: this.getLongdescText(),
xAxisDescription: axesDesc.xAxis,
yAxisDescription: axesDesc.yAxis,
viewTableButton: chart.getCSV ?
this.getDataTableButtonText(dataTableButtonId) : ''
}, formattedString = H.i18nFormat(format, context, chart);
this.dataTableButtonId = dataTableButtonId;
return stringToSimpleHTML(formattedString);
},
/**
* @private
* @return {string}
*/
defaultAfterChartFormatter: function () {
var chart = this.chart, format = chart.options.accessibility
.screenReaderSection.afterChartFormat, context = {
endOfChartMarker: this.getEndOfChartMarkerText()
}, formattedString = H.i18nFormat(format, context, chart);
return stringToSimpleHTML(formattedString);
},
/**
* @private
* @return {string}
*/
getLinkedDescription: function () {
var el = this.linkedDescriptionElement, content = el && el.innerHTML || '';
return stripHTMLTagsFromString(content);
},
/**
* @private
* @return {string}
*/
getLongdescText: function () {
var chartOptions = this.chart.options, captionOptions = chartOptions.caption, captionText = captionOptions && captionOptions.text, linkedDescription = this.getLinkedDescription();
return (chartOptions.accessibility.description ||
linkedDescription ||
captionText ||
'');
},
/**
* @private
* @return {string}
*/
getTypeDescriptionText: function () {
var chart = this.chart;
return chart.types ?
chart.options.accessibility.typeDescription ||
chart.getTypeDescription(chart.types) : '';
},
/**
* @private
* @param {string} buttonId
* @return {string}
*/
getDataTableButtonText: function (buttonId) {
var chart = this.chart, buttonText = chart.langFormat('accessibility.table.viewAsDataTableButtonText', { chart: chart, chartTitle: getChartTitle(chart) });
return '<a id="' + buttonId + '">' + buttonText + '</a>';
},
/**
* @private
* @return {string}
*/
getSubtitleText: function () {
var subtitle = (this.chart.options.subtitle);
return stripHTMLTagsFromString(subtitle && subtitle.text || '');
},
/**
* @private
* @return {string}
*/
getEndOfChartMarkerText: function () {
var chart = this.chart, markerText = chart.langFormat('accessibility.screenReaderSection.endOfChartMarker', { chart: chart }), id = 'highcharts-end-of-chart-marker-' + chart.index;
return '<div id="' + id + '">' + markerText + '</div>';
},
/**
* @private
* @param {Highcharts.Dictionary<string>} e
*/
onDataTableCreated: function (e) {
var chart = this.chart;
if (chart.options.accessibility.enabled) {
if (this.viewDataTableButton) {
this.viewDataTableButton.setAttribute('aria-expanded', 'true');
}
e.html = e.html.replace('<table ', '<table tabindex="0" summary="' + getTableSummary(chart) + '"');
}
},
/**
* @private
*/
focusDataTable: function () {
var tableDiv = this.dataTableDiv, table = tableDiv && tableDiv.getElementsByTagName('table')[0];
if (table && table.focus) {
table.focus();
}
},
/**
* Set attribs and handlers for default viewAsDataTable button if exists.
* @private
* @param {string} tableButtonId
*/
initDataTableButton: function (tableButtonId) {
var el = this.viewDataTableButton = getElement(tableButtonId), chart = this.chart, tableId = tableButtonId.replace('hc-linkto-', '');
if (el) {
setElAttrs(el, {
role: 'button',
tabindex: '-1',
'aria-expanded': !!getElement(tableId),
href: '#' + tableId
});
el.onclick = chart.options.accessibility
.screenReaderSection.onViewDataTableClick ||
function () {
chart.viewData();
};
}
},
/**
* Return object with text description of each of the chart's axes.
* @private
* @return {Highcharts.Dictionary<string>}
*/
getAxesDescription: function () {
var chart = this.chart, shouldDescribeColl = function (collectionKey, defaultCondition) {
var axes = chart[collectionKey];
return axes.length > 1 || axes[0] &&
pick(axes[0].options.accessibility &&
axes[0].options.accessibility.enabled, defaultCondition);
}, hasNoMap = !!chart.types && chart.types.indexOf('map') < 0, hasCartesian = !!chart.hasCartesianSeries, showXAxes = shouldDescribeColl('xAxis', !chart.angular && hasCartesian && hasNoMap), showYAxes = shouldDescribeColl('yAxis', hasCartesian && hasNoMap), desc = {};
if (showXAxes) {
desc.xAxis = this.getAxisDescriptionText('xAxis');
}
if (showYAxes) {
desc.yAxis = this.getAxisDescriptionText('yAxis');
}
return desc;
},
/**
* @private
* @param {string} collectionKey
* @return {string}
*/
getAxisDescriptionText: function (collectionKey) {
var component = this, chart = this.chart, axes = chart[collectionKey];
return chart.langFormat('accessibility.axis.' + collectionKey + 'Description' + (axes.length > 1 ? 'Plural' : 'Singular'), {
chart: chart,
names: axes.map(function (axis) {
return getAxisDescription(axis);
}),
ranges: axes.map(function (axis) {
return component.getAxisRangeDescription(axis);
}),
numAxes: axes.length
});
},
/**
* Return string with text description of the axis range.
* @private
* @param {Highcharts.Axis} axis The axis to get range desc of.
* @return {string} A string with the range description for the axis.
*/
getAxisRangeDescription: function (axis) {
var axisOptions = axis.options || {};
// Handle overridden range description
if (axisOptions.accessibility &&
typeof axisOptions.accessibility.rangeDescription !== 'undefined') {
return axisOptions.accessibility.rangeDescription;
}
// Handle category axes
if (axis.categories) {
return this.getCategoryAxisRangeDesc(axis);
}
// Use time range, not from-to?
if (axis.isDatetimeAxis && (axis.min === 0 || axis.dataMin === 0)) {
return this.getAxisTimeLengthDesc(axis);
}
// Just use from and to.
// We have the range and the unit to use, find the desc format
return this.getAxisFromToDescription(axis);
},
/**
* @private
* @param {Highcharts.Axis} axis
* @return {string}
*/
getCategoryAxisRangeDesc: function (axis) {
var chart = this.chart;
if (axis.dataMax && axis.dataMin) {
return chart.langFormat('accessibility.axis.rangeCategories', {
chart: chart,
axis: axis,
numCategories: axis.dataMax - axis.dataMin + 1
});
}
return '';
},
/**
* @private
* @param {Highcharts.Axis} axis
* @return {string}
*/
getAxisTimeLengthDesc: function (axis) {
var chart = this.chart, range = {}, rangeUnit = 'Seconds';
range.Seconds = ((axis.max || 0) - (axis.min || 0)) / 1000;
range.Minutes = range.Seconds / 60;
range.Hours = range.Minutes / 60;
range.Days = range.Hours / 24;
['Minutes', 'Hours', 'Days'].forEach(function (unit) {
if (range[unit] > 2) {
rangeUnit = unit;
}
});
var rangeValue = range[rangeUnit].toFixed(rangeUnit !== 'Seconds' &&
rangeUnit !== 'Minutes' ? 1 : 0 // Use decimals for days/hours
);
// We have the range and the unit to use, find the desc format
return chart.langFormat('accessibility.axis.timeRange' + rangeUnit, {
chart: chart,
axis: axis,
range: rangeValue.replace('.0', '')
});
},
/**
* @private
* @param {Highcharts.Axis} axis
* @return {string}
*/
getAxisFromToDescription: function (axis) {
var chart = this.chart, dateRangeFormat = chart.options.accessibility
.screenReaderSection.axisRangeDateFormat, format = function (axisKey) {
return axis.isDatetimeAxis ? chart.time.dateFormat(dateRangeFormat, axis[axisKey]) : axis[axisKey];
};
return chart.langFormat('accessibility.axis.rangeFromTo', {
chart: chart,
axis: axis,
rangeFrom: format('min'),
rangeTo: format('max')
});
}
});
export default InfoRegionsComponent;
|
/*global require, module*/
var webpack = require('webpack');
var webpackConfig = require('./webpack.config.js');
webpackConfig.plugins = webpackConfig.plugins || [];
webpackConfig.plugins.push(new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('production')
}
}));
module.exports = function(grunt) {
grunt.loadNpmTasks('grunt-webpack');
grunt.loadNpmTasks('grunt-karma');
grunt.initConfig({
webpack: {
options: webpackConfig,
build: {}
},
karma: {
singleRun: {
configFile: 'karma.conf.js',
singleRun: true
}
}
});
grunt.registerTask('build', ['webpack:build']);
grunt.registerTask('test', ['karma:singleRun']);
grunt.registerTask('default', ['build', 'test']);
};
|
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import {accumulateEnterLeaveDispatches} from 'events/EventPropagators';
import {
TOP_MOUSE_OUT,
TOP_MOUSE_OVER,
TOP_POINTER_OUT,
TOP_POINTER_OVER,
} from './DOMTopLevelEventTypes';
import SyntheticMouseEvent from './SyntheticMouseEvent';
import SyntheticPointerEvent from './SyntheticPointerEvent';
import {
getClosestInstanceFromNode,
getNodeFromInstance,
} from '../client/ReactDOMComponentTree';
const eventTypes = {
mouseEnter: {
registrationName: 'onMouseEnter',
dependencies: [TOP_MOUSE_OUT, TOP_MOUSE_OVER],
},
mouseLeave: {
registrationName: 'onMouseLeave',
dependencies: [TOP_MOUSE_OUT, TOP_MOUSE_OVER],
},
pointerEnter: {
registrationName: 'onPointerEnter',
dependencies: [TOP_POINTER_OUT, TOP_POINTER_OVER],
},
pointerLeave: {
registrationName: 'onPointerLeave',
dependencies: [TOP_POINTER_OUT, TOP_POINTER_OVER],
},
};
const EnterLeaveEventPlugin = {
eventTypes: eventTypes,
/**
* For almost every interaction we care about, there will be both a top-level
* `mouseover` and `mouseout` event that occurs. Only use `mouseout` so that
* we do not extract duplicate events. However, moving the mouse into the
* browser from outside will not fire a `mouseout` event. In this case, we use
* the `mouseover` top-level event.
*/
extractEvents: function(
topLevelType,
targetInst,
nativeEvent,
nativeEventTarget,
) {
const isOverEvent =
topLevelType === TOP_MOUSE_OVER || topLevelType === TOP_POINTER_OVER;
const isOutEvent =
topLevelType === TOP_MOUSE_OUT || topLevelType === TOP_POINTER_OUT;
if (isOverEvent && (nativeEvent.relatedTarget || nativeEvent.fromElement)) {
return null;
}
if (!isOutEvent && !isOverEvent) {
// Must not be a mouse or pointer in or out - ignoring.
return null;
}
let win;
if (nativeEventTarget.window === nativeEventTarget) {
// `nativeEventTarget` is probably a window object.
win = nativeEventTarget;
} else {
// TODO: Figure out why `ownerDocument` is sometimes undefined in IE8.
const doc = nativeEventTarget.ownerDocument;
if (doc) {
win = doc.defaultView || doc.parentWindow;
} else {
win = window;
}
}
let from;
let to;
if (isOutEvent) {
from = targetInst;
const related = nativeEvent.relatedTarget || nativeEvent.toElement;
to = related ? getClosestInstanceFromNode(related) : null;
} else {
// Moving to a node from outside the window.
from = null;
to = targetInst;
}
if (from === to) {
// Nothing pertains to our managed components.
return null;
}
let eventInterface, leaveEventType, enterEventType, eventTypePrefix;
if (topLevelType === TOP_MOUSE_OUT || topLevelType === TOP_MOUSE_OVER) {
eventInterface = SyntheticMouseEvent;
leaveEventType = eventTypes.mouseLeave;
enterEventType = eventTypes.mouseEnter;
eventTypePrefix = 'mouse';
} else if (
topLevelType === TOP_POINTER_OUT ||
topLevelType === TOP_POINTER_OVER
) {
eventInterface = SyntheticPointerEvent;
leaveEventType = eventTypes.pointerLeave;
enterEventType = eventTypes.pointerEnter;
eventTypePrefix = 'pointer';
}
const fromNode = from == null ? win : getNodeFromInstance(from);
const toNode = to == null ? win : getNodeFromInstance(to);
const leave = eventInterface.getPooled(
leaveEventType,
from,
nativeEvent,
nativeEventTarget,
);
leave.type = eventTypePrefix + 'leave';
leave.target = fromNode;
leave.relatedTarget = toNode;
const enter = eventInterface.getPooled(
enterEventType,
to,
nativeEvent,
nativeEventTarget,
);
enter.type = eventTypePrefix + 'enter';
enter.target = toNode;
enter.relatedTarget = fromNode;
accumulateEnterLeaveDispatches(leave, enter, from, to);
return [leave, enter];
},
};
export default EnterLeaveEventPlugin;
|
/**
* Tools.js
*
* Released under LGPL License.
* Copyright (c) 1999-2017 Ephox Corp. All rights reserved
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
/**
* This class contains various utlity functions. These are also exposed
* directly on the tinymce namespace.
*
* @class tinymce.util.Tools
*/
define(
'tinymce.core.util.Tools',
[
'global!window',
'tinymce.core.Env',
'tinymce.core.util.Arr'
],
function (window, Env, Arr) {
/**
* Removes whitespace from the beginning and end of a string.
*
* @method trim
* @param {String} s String to remove whitespace from.
* @return {String} New string with removed whitespace.
*/
var whiteSpaceRegExp = /^\s*|\s*$/g;
var trim = function (str) {
return (str === null || str === undefined) ? '' : ("" + str).replace(whiteSpaceRegExp, '');
};
/**
* Checks if a object is of a specific type for example an array.
*
* @method is
* @param {Object} obj Object to check type of.
* @param {string} type Optional type to check for.
* @return {Boolean} true/false if the object is of the specified type.
*/
var is = function (obj, type) {
if (!type) {
return obj !== undefined;
}
if (type == 'array' && Arr.isArray(obj)) {
return true;
}
return typeof obj == type;
};
/**
* Makes a name/object map out of an array with names.
*
* @method makeMap
* @param {Array/String} items Items to make map out of.
* @param {String} delim Optional delimiter to split string by.
* @param {Object} map Optional map to add items to.
* @return {Object} Name/value map of items.
*/
var makeMap = function (items, delim, map) {
var i;
items = items || [];
delim = delim || ',';
if (typeof items == "string") {
items = items.split(delim);
}
map = map || {};
i = items.length;
while (i--) {
map[items[i]] = {};
}
return map;
};
/**
* JavaScript does not protect hasOwnProperty method, so it is possible to overwrite it. This is
* object independent version.
*
* @param {Object} obj
* @param {String} prop
* @returns {Boolean}
*/
var hasOwnProperty = function (obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
};
/**
* Creates a class, subclass or static singleton.
* More details on this method can be found in the Wiki.
*
* @method create
* @param {String} s Class name, inheritance and prefix.
* @param {Object} p Collection of methods to add to the class.
* @param {Object} root Optional root object defaults to the global window object.
* @example
* // Creates a basic class
* tinymce.create('tinymce.somepackage.SomeClass', {
* SomeClass: function() {
* // Class constructor
* },
*
* method: function() {
* // Some method
* }
* });
*
* // Creates a basic subclass class
* tinymce.create('tinymce.somepackage.SomeSubClass:tinymce.somepackage.SomeClass', {
* SomeSubClass: function() {
* // Class constructor
* this.parent(); // Call parent constructor
* },
*
* method: function() {
* // Some method
* this.parent(); // Call parent method
* },
*
* 'static': {
* staticMethod: function() {
* // Static method
* }
* }
* });
*
* // Creates a singleton/static class
* tinymce.create('static tinymce.somepackage.SomeSingletonClass', {
* method: function() {
* // Some method
* }
* });
*/
var create = function (s, p, root) {
var self = this, sp, ns, cn, scn, c, de = 0;
// Parse : <prefix> <class>:<super class>
s = /^((static) )?([\w.]+)(:([\w.]+))?/.exec(s);
cn = s[3].match(/(^|\.)(\w+)$/i)[2]; // Class name
// Create namespace for new class
ns = self.createNS(s[3].replace(/\.\w+$/, ''), root);
// Class already exists
if (ns[cn]) {
return;
}
// Make pure static class
if (s[2] == 'static') {
ns[cn] = p;
if (this.onCreate) {
this.onCreate(s[2], s[3], ns[cn]);
}
return;
}
// Create default constructor
if (!p[cn]) {
p[cn] = function () { };
de = 1;
}
// Add constructor and methods
ns[cn] = p[cn];
self.extend(ns[cn].prototype, p);
// Extend
if (s[5]) {
sp = self.resolve(s[5]).prototype;
scn = s[5].match(/\.(\w+)$/i)[1]; // Class name
// Extend constructor
c = ns[cn];
if (de) {
// Add passthrough constructor
ns[cn] = function () {
return sp[scn].apply(this, arguments);
};
} else {
// Add inherit constructor
ns[cn] = function () {
this.parent = sp[scn];
return c.apply(this, arguments);
};
}
ns[cn].prototype[cn] = ns[cn];
// Add super methods
self.each(sp, function (f, n) {
ns[cn].prototype[n] = sp[n];
});
// Add overridden methods
self.each(p, function (f, n) {
// Extend methods if needed
if (sp[n]) {
ns[cn].prototype[n] = function () {
this.parent = sp[n];
return f.apply(this, arguments);
};
} else {
if (n != cn) {
ns[cn].prototype[n] = f;
}
}
});
}
// Add static methods
/*jshint sub:true*/
/*eslint dot-notation:0*/
self.each(p['static'], function (f, n) {
ns[cn][n] = f;
});
};
var extend = function (obj, ext) {
var i, l, name, args = arguments, value;
for (i = 1, l = args.length; i < l; i++) {
ext = args[i];
for (name in ext) {
if (ext.hasOwnProperty(name)) {
value = ext[name];
if (value !== undefined) {
obj[name] = value;
}
}
}
}
return obj;
};
/**
* Executed the specified function for each item in a object tree.
*
* @method walk
* @param {Object} o Object tree to walk though.
* @param {function} f Function to call for each item.
* @param {String} n Optional name of collection inside the objects to walk for example childNodes.
* @param {String} s Optional scope to execute the function in.
*/
var walk = function (o, f, n, s) {
s = s || this;
if (o) {
if (n) {
o = o[n];
}
Arr.each(o, function (o, i) {
if (f.call(s, o, i, n) === false) {
return false;
}
walk(o, f, n, s);
});
}
};
/**
* Creates a namespace on a specific object.
*
* @method createNS
* @param {String} n Namespace to create for example a.b.c.d.
* @param {Object} o Optional object to add namespace to, defaults to window.
* @return {Object} New namespace object the last item in path.
* @example
* // Create some namespace
* tinymce.createNS('tinymce.somepackage.subpackage');
*
* // Add a singleton
* var tinymce.somepackage.subpackage.SomeSingleton = {
* method: function() {
* // Some method
* }
* };
*/
var createNS = function (n, o) {
var i, v;
o = o || window;
n = n.split('.');
for (i = 0; i < n.length; i++) {
v = n[i];
if (!o[v]) {
o[v] = {};
}
o = o[v];
}
return o;
};
/**
* Resolves a string and returns the object from a specific structure.
*
* @method resolve
* @param {String} n Path to resolve for example a.b.c.d.
* @param {Object} o Optional object to search though, defaults to window.
* @return {Object} Last object in path or null if it couldn't be resolved.
* @example
* // Resolve a path into an object reference
* var obj = tinymce.resolve('a.b.c.d');
*/
var resolve = function (n, o) {
var i, l;
o = o || window;
n = n.split('.');
for (i = 0, l = n.length; i < l; i++) {
o = o[n[i]];
if (!o) {
break;
}
}
return o;
};
/**
* Splits a string but removes the whitespace before and after each value.
*
* @method explode
* @param {string} s String to split.
* @param {string} d Delimiter to split by.
* @example
* // Split a string into an array with a,b,c
* var arr = tinymce.explode('a, b, c');
*/
var explode = function (s, d) {
if (!s || is(s, 'array')) {
return s;
}
return Arr.map(s.split(d || ','), trim);
};
var _addCacheSuffix = function (url) {
var cacheSuffix = Env.cacheSuffix;
if (cacheSuffix) {
url += (url.indexOf('?') === -1 ? '?' : '&') + cacheSuffix;
}
return url;
};
return {
trim: trim,
/**
* Returns true/false if the object is an array or not.
*
* @method isArray
* @param {Object} obj Object to check.
* @return {boolean} true/false state if the object is an array or not.
*/
isArray: Arr.isArray,
is: is,
/**
* Converts the specified object into a real JavaScript array.
*
* @method toArray
* @param {Object} obj Object to convert into array.
* @return {Array} Array object based in input.
*/
toArray: Arr.toArray,
makeMap: makeMap,
/**
* Performs an iteration of all items in a collection such as an object or array. This method will execure the
* callback function for each item in the collection, if the callback returns false the iteration will terminate.
* The callback has the following format: cb(value, key_or_index).
*
* @method each
* @param {Object} o Collection to iterate.
* @param {function} cb Callback function to execute for each item.
* @param {Object} s Optional scope to execute the callback in.
* @example
* // Iterate an array
* tinymce.each([1,2,3], function(v, i) {
* console.debug("Value: " + v + ", Index: " + i);
* });
*
* // Iterate an object
* tinymce.each({a: 1, b: 2, c: 3], function(v, k) {
* console.debug("Value: " + v + ", Key: " + k);
* });
*/
each: Arr.each,
/**
* Creates a new array by the return value of each iteration function call. This enables you to convert
* one array list into another.
*
* @method map
* @param {Array} array Array of items to iterate.
* @param {function} callback Function to call for each item. It's return value will be the new value.
* @return {Array} Array with new values based on function return values.
*/
map: Arr.map,
/**
* Filters out items from the input array by calling the specified function for each item.
* If the function returns false the item will be excluded if it returns true it will be included.
*
* @method grep
* @param {Array} a Array of items to loop though.
* @param {function} f Function to call for each item. Include/exclude depends on it's return value.
* @return {Array} New array with values imported and filtered based in input.
* @example
* // Filter out some items, this will return an array with 4 and 5
* var items = tinymce.grep([1,2,3,4,5], function(v) {return v > 3;});
*/
grep: Arr.filter,
/**
* Returns an index of the item or -1 if item is not present in the array.
*
* @method inArray
* @param {any} item Item to search for.
* @param {Array} arr Array to search in.
* @return {Number} index of the item or -1 if item was not found.
*/
inArray: Arr.indexOf,
hasOwn: hasOwnProperty,
extend: extend,
create: create,
walk: walk,
createNS: createNS,
resolve: resolve,
explode: explode,
_addCacheSuffix: _addCacheSuffix
};
}
); |
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
'use strict';
const glob = require('glob');
const path = require('path');
/**
* Find the main file for the C# project
*
* @param {String} folder Name of the folder where to seek
* @return {String}
*/
module.exports = function findMainFile(folder) {
let mainFilePath = glob.sync('MainReactNativeHost.cs', {
cwd: folder,
ignore: ['node_modules/**', '**/build/**', 'Examples/**', 'examples/**'],
});
if (mainFilePath.length === 0) {
mainFilePath = glob.sync('MainPage.cs', {
cwd: folder,
ignore: ['node_modules/**', '**/build/**', 'Examples/**', 'examples/**'],
});
}
return mainFilePath && mainFilePath.length > 0 ? path.join(folder, mainFilePath[0]) : null;
};
|
module.exports = {
settings: {
},
commands: {
},
};
|
var fs = require('fs');
var pkg = require('../package.json');
console.log('Creating dist/js-data-debug.js...');
var file = fs.readFileSync('dist/js-data-debug.js', { encoding: 'utf-8' });
var lines = file.split('\n');
var newLines = [];
lines.forEach(function (line) {
if (line.indexOf('logFn(') === -1) {
newLines.push(line);
}
});
file = newLines.join('\n');
file += '\n';
fs.writeFileSync('dist/js-data.js', file, { encoding: 'utf-8' });
console.log('Done!');
|
// "Borrowed" from node-inspector
var CallbackHandler = {
/**
* Create a callback container
* @return {Object} that wraps callbacks and returns a one-time id.
*/
create: function () {
var lastId = 1,
callbacks = {}
return Object.create({}, {
wrap: {
value: function (callback) {
var callbackId = lastId++
callbacks[callbackId] = callback || function () {
}
return callbackId
}
},
processResponse: {
value: function (callbackId, args) {
var callback = callbacks[callbackId]
if (callback) {
callback.apply(null, args)
}
delete callbacks[callbackId]
}
},
removeResponseCallbackEntry: {
value: function (callbackId) {
delete callbacks[callbackId]
}
}
})
}
}
var Net = require('net'),
Protocol = require('_debugger').Protocol,
inherits = require('util').inherits,
EventEmitter = require('events').EventEmitter,
debugProtocol = require('debug')('node-inspector:protocol:v8-debug'),
callbackHandler = CallbackHandler.create()
/**
* @param {Number} port
*/
function Debugger(port) {
this._port = port
this._connected = false
this._connection = null
this._lastError = null
this._setupConnection()
}
inherits(Debugger, EventEmitter)
Object.defineProperties(Debugger.prototype, {
/** @type {boolean} */
isRunning: {writable: true, value: true},
/** @type {boolean} */
connected: {
get: function () {
return this._connected
}
}
})
Debugger.prototype._setupConnection = function () {
var connection = Net.createConnection(this._port),
protocol = new Protocol()
protocol.onResponse = this._processResponse.bind(this)
connection
.on('connect', this._onConnectionOpen.bind(this))
.on('data', protocol.execute.bind(protocol))
.on('error', this._onConnectionError.bind(this))
.on('end', this.close.bind(this))
.on('close', this._onConnectionClose.bind(this))
.setEncoding('utf8')
this._connection = connection
}
Debugger.prototype._onConnectionOpen = function () {
this._connected = true
this.emit('connect')
}
/**
* @param {Error} err
*/
Debugger.prototype._onConnectionError = function (err) {
if (err.code == 'ECONNREFUSED') {
err.helpString = 'Is node running with --debug port ' + this._port + '?'
} else if (err.code == 'ECONNRESET') {
err.helpString = 'Check there is no other debugger client attached to port ' + this._port + '.'
}
this._lastError = err.toString()
if (err.helpString) {
this._lastError += '. ' + err.helpString
}
this.emit('error', err)
}
Debugger.prototype._onConnectionClose = function (hadError) {
this.emit('close', hadError ? this._lastError : 'Debugged process exited.')
this._port = null
this._connected = false
this._connection = null
this._lastError = null
}
Debugger.prototype._processResponse = function (message) {
var obj = message.body
if (typeof obj.running === 'boolean') {
this.isRunning = obj.running
}
if (obj.type === 'response' && obj.request_seq > 0) {
debugProtocol('response: ' + JSON.stringify(message.body))
callbackHandler.processResponse(obj.request_seq, [obj])
} else if (obj.type === 'event') {
debugProtocol('event: ' + JSON.stringify(message.body))
if (['break', 'exception'].indexOf(obj.event) > -1) {
this.isRunning = false
}
this.emit(obj.event, obj)
} else {
debugProtocol('unknown: ' + JSON.stringify(message.body))
}
}
/**
* @param {string} data
*/
Debugger.prototype.send = function (data) {
debugProtocol('request: ' + data)
if (this.connected) {
this._connection.write('Content-Length: ' + Buffer.byteLength(data, 'utf8') + '\r\n\r\n' + data)
}
}
/**
* @param {string} command
* @param {Object} params
* @param {function} callback
*/
Debugger.prototype.request = function (command, params, callback) {
var message = {
seq: 0,
type: 'request',
command: command
}
if (typeof callback === 'function') {
message.seq = callbackHandler.wrap(callback)
}
if (params) {
Object.keys(params).forEach(function (key) {
message[key] = params[key]
})
}
this.send(JSON.stringify(message))
}
/**
*/
Debugger.prototype.close = function () {
this._connection.end()
}
module.exports = function (debugPort, callback) {
// give the process time to start up
setTimeout(function () {
var debuggerClient = new Debugger(debugPort)
debuggerClient.on('error', callback)
debuggerClient.on('connect', function () {
debuggerClient.request('continue', undefined, function (response) {
debuggerClient.close()
if (!response.success) return callback(new Error('Could not continue process'))
callback()
})
})
}, 1000)
}
|
version https://git-lfs.github.com/spec/v1
oid sha256:a5b63c6dfd15dccd31cce53e9713057b4a280de478598a0046a6b1221e6564d0
size 42396
|
import baseCallback from '../internal/baseCallback';
import basePullAt from '../internal/basePullAt';
/**
* Removes all elements from `array` that `predicate` returns truthy for
* and returns an array of the removed elements. The predicate is bound to
* `thisArg` and invoked with three arguments: (value, index, array).
*
* If a property name is provided for `predicate` the created `_.property`
* style callback returns the property value of the given element.
*
* If a value is also provided for `thisArg` the created `_.matchesProperty`
* style callback returns `true` for elements that have a matching property
* value, else `false`.
*
* If an object is provided for `predicate` the created `_.matches` style
* callback returns `true` for elements that have the properties of the given
* object, else `false`.
*
* **Note:** Unlike `_.filter`, this method mutates `array`.
*
* @static
* @memberOf _
* @category Array
* @param {Array} array The array to modify.
* @param {Function|Object|string} [predicate=_.identity] The function invoked
* per iteration.
* @param {*} [thisArg] The `this` binding of `predicate`.
* @returns {Array} Returns the new array of removed elements.
* @example
*
* var array = [1, 2, 3, 4];
* var evens = _.remove(array, function(n) {
* return n % 2 == 0;
* });
*
* console.log(array);
* // => [1, 3]
*
* console.log(evens);
* // => [2, 4]
*/
function remove(array, predicate, thisArg) {
var result = [];
if (!(array && array.length)) {
return result;
}
var index = -1,
indexes = [],
length = array.length;
predicate = baseCallback(predicate, thisArg, 3);
while (++index < length) {
var value = array[index];
if (predicate(value, index, array)) {
result.push(value);
indexes.push(index);
}
}
basePullAt(array, indexes);
return result;
}
export default remove;
|
var roundTrip = module.exports = require('azure-mobile-apps').table();
roundTrip.update(function (context) {
return context.execute()
.catch(function (error) {
if(context.req.query.conflictPolicy === 'clientWins') {
context.item.version = error.item.version;
return context.execute();
} else if (context.req.query.conflictPolicy === 'serverWins') {
return error.item;
} else {
throw error;
}
});
});
roundTrip.columns = { name: 'string', date1: 'date', bool: 'boolean', integer: 'number', number: 'number' };
roundTrip.dynamicSchema = false;
|
/**
* @fileoverview This option sets a specific tab width for your code
* @author Dmitriy Shekhovtsov
* @author Gyandeep Singh
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const rule = require("../../../lib/rules/indent"),
{ RuleTester } = require("../../../lib/rule-tester");
const fs = require("fs");
const path = require("path");
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
const fixture = fs.readFileSync(path.join(__dirname, "../../fixtures/rules/indent/indent-invalid-fixture-1.js"), "utf8");
const fixedFixture = fs.readFileSync(path.join(__dirname, "../../fixtures/rules/indent/indent-valid-fixture-1.js"), "utf8");
const parser = require("../../fixtures/fixture-parser");
const { unIndent } = require("../../_utils");
/**
* Create error message object for failure cases with a single 'found' indentation type
* @param {string} providedIndentType indent type of string or tab
* @param {Array} providedErrors error info
* @returns {Object} returns the error messages collection
* @private
*/
function expectedErrors(providedIndentType, providedErrors) {
let indentType;
let errors;
if (Array.isArray(providedIndentType)) {
errors = Array.isArray(providedIndentType[0]) ? providedIndentType : [providedIndentType];
indentType = "space";
} else {
errors = Array.isArray(providedErrors[0]) ? providedErrors : [providedErrors];
indentType = providedIndentType;
}
return errors.map(err => ({
messageId: "wrongIndentation",
data: {
expected: typeof err[1] === "string" && typeof err[2] === "string"
? err[1]
: `${err[1]} ${indentType}${err[1] === 1 ? "" : "s"}`,
actual: err[2]
},
type: err[3],
line: err[0]
}));
}
//------------------------------------------------------------------------------
// Tests
//------------------------------------------------------------------------------
const ruleTester = new RuleTester({ parserOptions: { ecmaVersion: 8, ecmaFeatures: { jsx: true } } });
ruleTester.run("indent", rule, {
valid: [
{
code: unIndent`
bridge.callHandler(
'getAppVersion', 'test23', function(responseData) {
window.ah.mobileAppVersion = responseData;
}
);
`,
options: [2]
},
{
code: unIndent`
bridge.callHandler(
'getAppVersion', 'test23', function(responseData) {
window.ah.mobileAppVersion = responseData;
});
`,
options: [2]
},
{
code: unIndent`
bridge.callHandler(
'getAppVersion',
null,
function responseCallback(responseData) {
window.ah.mobileAppVersion = responseData;
}
);
`,
options: [2]
},
{
code: unIndent`
bridge.callHandler(
'getAppVersion',
null,
function responseCallback(responseData) {
window.ah.mobileAppVersion = responseData;
});
`,
options: [2]
},
{
code: unIndent`
function doStuff(keys) {
_.forEach(
keys,
key => {
doSomething(key);
}
);
}
`,
options: [4]
},
{
code: unIndent`
example(
function () {
console.log('example');
}
);
`,
options: [4]
},
{
code: unIndent`
let foo = somethingList
.filter(x => {
return x;
})
.map(x => {
return 100 * x;
});
`,
options: [4]
},
{
code: unIndent`
var x = 0 &&
{
a: 1,
b: 2
};
`,
options: [4]
},
{
code: unIndent`
var x = 0 &&
\t{
\t\ta: 1,
\t\tb: 2
\t};
`,
options: ["tab"]
},
{
code: unIndent`
var x = 0 &&
{
a: 1,
b: 2
}||
{
c: 3,
d: 4
};
`,
options: [4]
},
{
code: unIndent`
var x = [
'a',
'b',
'c'
];
`,
options: [4]
},
{
code: unIndent`
var x = ['a',
'b',
'c',
];
`,
options: [4]
},
{
code: "var x = 0 && 1;",
options: [4]
},
{
code: "var x = 0 && { a: 1, b: 2 };",
options: [4]
},
{
code: unIndent`
var x = 0 &&
(
1
);
`,
options: [4]
},
{
code: unIndent`
require('http').request({hostname: 'localhost',
port: 80}, function(res) {
res.end();
});
`,
options: [2]
},
{
code: unIndent`
function test() {
return client.signUp(email, PASSWORD, { preVerified: true })
.then(function (result) {
// hi
})
.then(function () {
return FunctionalHelpers.clearBrowserState(self, {
contentServer: true,
contentServer1: true
});
});
}
`,
options: [2]
},
{
code: unIndent`
it('should... some lengthy test description that is forced to be' +
'wrapped into two lines since the line length limit is set', () => {
expect(true).toBe(true);
});
`,
options: [2]
},
{
code: unIndent`
function test() {
return client.signUp(email, PASSWORD, { preVerified: true })
.then(function (result) {
var x = 1;
var y = 1;
}, function(err){
var o = 1 - 2;
var y = 1 - 2;
return true;
})
}
`,
options: [4]
},
{
// https://github.com/eslint/eslint/issues/11802
code: unIndent`
import foo from "foo"
;(() => {})()
`,
options: [4],
parserOptions: { ecmaVersion: 6, sourceType: "module" }
},
{
code: unIndent`
function test() {
return client.signUp(email, PASSWORD, { preVerified: true })
.then(function (result) {
var x = 1;
var y = 1;
}, function(err){
var o = 1 - 2;
var y = 1 - 2;
return true;
});
}
`,
options: [4, { MemberExpression: 0 }]
},
{
code: "// hi",
options: [2, { VariableDeclarator: 1, SwitchCase: 1 }]
},
{
code: unIndent`
var Command = function() {
var fileList = [],
files = []
files.concat(fileList)
};
`,
options: [2, { VariableDeclarator: { var: 2, let: 2, const: 3 } }]
},
{
code: " ",
options: [2, { VariableDeclarator: 1, SwitchCase: 1 }]
},
{
code: unIndent`
if(data) {
console.log('hi');
b = true;};
`,
options: [2, { VariableDeclarator: 1, SwitchCase: 1 }]
},
{
code: unIndent`
foo = () => {
console.log('hi');
return true;};
`,
options: [2, { VariableDeclarator: 1, SwitchCase: 1 }]
},
{
code: unIndent`
function test(data) {
console.log('hi');
return true;};
`,
options: [2, { VariableDeclarator: 1, SwitchCase: 1 }]
},
{
code: unIndent`
var test = function(data) {
console.log('hi');
};
`,
options: [2, { VariableDeclarator: 1, SwitchCase: 1 }]
},
{
code: unIndent`
arr.forEach(function(data) {
otherdata.forEach(function(zero) {
console.log('hi');
}) });
`,
options: [2, { VariableDeclarator: 1, SwitchCase: 1 }]
},
{
code: unIndent`
a = [
,3
]
`,
options: [4, { VariableDeclarator: 1, SwitchCase: 1 }]
},
{
code: unIndent`
[
['gzip', 'gunzip'],
['gzip', 'unzip'],
['deflate', 'inflate'],
['deflateRaw', 'inflateRaw'],
].forEach(function(method) {
console.log(method);
});
`,
options: [2, { SwitchCase: 1, VariableDeclarator: 2 }]
},
{
code: unIndent`
test(123, {
bye: {
hi: [1,
{
b: 2
}
]
}
});
`,
options: [4, { VariableDeclarator: 1, SwitchCase: 1 }]
},
{
code: unIndent`
var xyz = 2,
lmn = [
{
a: 1
}
];
`,
options: [4, { VariableDeclarator: 1, SwitchCase: 1 }]
},
{
code: unIndent`
lmnn = [{
a: 1
},
{
b: 2
}, {
x: 2
}];
`,
options: [4, { VariableDeclarator: 1, SwitchCase: 1 }]
},
unIndent`
[{
foo: 1
}, {
foo: 2
}, {
foo: 3
}]
`,
unIndent`
foo([
bar
], [
baz
], [
qux
]);
`,
{
code: unIndent`
abc({
test: [
[
c,
xyz,
2
].join(',')
]
});
`,
options: [4, { VariableDeclarator: 1, SwitchCase: 1 }]
},
{
code: unIndent`
abc = {
test: [
[
c,
xyz,
2
]
]
};
`,
options: [2, { VariableDeclarator: 1, SwitchCase: 1 }]
},
{
code: unIndent`
abc(
{
a: 1,
b: 2
}
);
`,
options: [2, { VariableDeclarator: 1, SwitchCase: 1 }]
},
{
code: unIndent`
abc({
a: 1,
b: 2
});
`,
options: [4, { VariableDeclarator: 1, SwitchCase: 1 }]
},
{
code: unIndent`
var abc =
[
c,
xyz,
{
a: 1,
b: 2
}
];
`,
options: [2, { VariableDeclarator: 1, SwitchCase: 1 }]
},
{
code: unIndent`
var abc = [
c,
xyz,
{
a: 1,
b: 2
}
];
`,
options: [2, { VariableDeclarator: 1, SwitchCase: 1 }]
},
{
code: unIndent`
var abc = 5,
c = 2,
xyz =
{
a: 1,
b: 2
};
`,
options: [2, { VariableDeclarator: 2, SwitchCase: 1 }]
},
unIndent`
var
x = {
a: 1,
},
y = {
b: 2
}
`,
unIndent`
const
x = {
a: 1,
},
y = {
b: 2
}
`,
unIndent`
let
x = {
a: 1,
},
y = {
b: 2
}
`,
unIndent`
var foo = { a: 1 }, bar = {
b: 2
};
`,
unIndent`
var foo = { a: 1 }, bar = {
b: 2
},
baz = {
c: 3
}
`,
unIndent`
const {
foo
} = 1,
bar = 2
`,
{
code: unIndent`
var foo = 1,
bar =
2
`,
options: [2, { VariableDeclarator: 1 }]
},
{
code: unIndent`
var foo = 1,
bar
= 2
`,
options: [2, { VariableDeclarator: 1 }]
},
{
code: unIndent`
var foo
= 1,
bar
= 2
`,
options: [2, { VariableDeclarator: 1 }]
},
{
code: unIndent`
var foo
=
1,
bar
=
2
`,
options: [2, { VariableDeclarator: 1 }]
},
{
code: unIndent`
var foo
= (1),
bar
= (2)
`,
options: [2, { VariableDeclarator: 1 }]
},
{
code: unIndent`
let foo = 'foo',
bar = bar;
const a = 'a',
b = 'b';
`,
options: [2, { VariableDeclarator: "first" }]
},
{
code: unIndent`
let foo = 'foo',
bar = bar // <-- no semicolon here
const a = 'a',
b = 'b' // <-- no semicolon here
`,
options: [2, { VariableDeclarator: "first" }]
},
{
code: unIndent`
var foo = 1,
bar = 2,
baz = 3
;
`,
options: [2, { VariableDeclarator: { var: 2 } }]
},
{
code: unIndent`
var foo = 1,
bar = 2,
baz = 3
;
`,
options: [2, { VariableDeclarator: { var: 2 } }]
},
{
code: unIndent`
var foo = 'foo',
bar = bar;
`,
options: [2, { VariableDeclarator: { var: "first" } }]
},
{
code: unIndent`
var foo = 'foo',
bar = 'bar' // <-- no semicolon here
`,
options: [2, { VariableDeclarator: { var: "first" } }]
},
{
code: unIndent`
let foo = 1,
bar = 2,
baz
`,
options: [2, { VariableDeclarator: "first" }]
},
{
code: unIndent`
let
foo
`,
options: [4, { VariableDeclarator: "first" }]
},
{
code: unIndent`
let foo = 1,
bar =
2
`,
options: [2, { VariableDeclarator: "first" }]
},
{
code: unIndent`
var abc =
{
a: 1,
b: 2
};
`,
options: [2, { VariableDeclarator: 2, SwitchCase: 1 }]
},
{
code: unIndent`
var a = new abc({
a: 1,
b: 2
}),
b = 2;
`,
options: [4, { VariableDeclarator: 1, SwitchCase: 1 }]
},
{
code: unIndent`
var a = 2,
c = {
a: 1,
b: 2
},
b = 2;
`,
options: [2, { VariableDeclarator: 1, SwitchCase: 1 }]
},
{
code: unIndent`
var x = 2,
y = {
a: 1,
b: 2
},
b = 2;
`,
options: [2, { VariableDeclarator: 2, SwitchCase: 1 }]
},
{
code: unIndent`
var e = {
a: 1,
b: 2
},
b = 2;
`,
options: [2, { VariableDeclarator: 2, SwitchCase: 1 }]
},
{
code: unIndent`
var a = {
a: 1,
b: 2
};
`,
options: [2, { VariableDeclarator: 2, SwitchCase: 1 }]
},
{
code: unIndent`
function test() {
if (true ||
false){
console.log(val);
}
}
`,
options: [2, { VariableDeclarator: 2, SwitchCase: 1 }]
},
unIndent`
var foo = bar ||
!(
baz
);
`,
unIndent`
for (var foo = 1;
foo < 10;
foo++) {}
`,
unIndent`
for (
var foo = 1;
foo < 10;
foo++
) {}
`,
{
code: unIndent`
for (var val in obj)
if (true)
console.log(val);
`,
options: [2, { VariableDeclarator: 2, SwitchCase: 1 }]
},
{
code: unIndent`
if(true)
if (true)
if (true)
console.log(val);
`,
options: [2, { VariableDeclarator: 2, SwitchCase: 1 }]
},
{
code: unIndent`
function hi(){ var a = 1;
y++; x++;
}
`,
options: [2, { VariableDeclarator: 2, SwitchCase: 1 }]
},
{
code: unIndent`
for(;length > index; index++)if(NO_HOLES || index in self){
x++;
}
`,
options: [2, { VariableDeclarator: 2, SwitchCase: 1 }]
},
{
code: unIndent`
function test(){
switch(length){
case 1: return function(a){
return fn.call(that, a);
};
}
}
`,
options: [2, { VariableDeclarator: 2, SwitchCase: 1 }]
},
{
code: unIndent`
var geometry = 2,
rotate = 2;
`,
options: [2, { VariableDeclarator: 0 }]
},
{
code: unIndent`
var geometry,
rotate;
`,
options: [4, { VariableDeclarator: 1 }]
},
{
code: unIndent`
var geometry,
\trotate;
`,
options: ["tab", { VariableDeclarator: 1 }]
},
{
code: unIndent`
var geometry,
rotate;
`,
options: [2, { VariableDeclarator: 1 }]
},
{
code: unIndent`
var geometry,
rotate;
`,
options: [2, { VariableDeclarator: 2 }]
},
{
code: unIndent`
let geometry,
rotate;
`,
options: [2, { VariableDeclarator: 2 }]
},
{
code: unIndent`
const geometry = 2,
rotate = 3;
`,
options: [2, { VariableDeclarator: 2 }]
},
{
code: unIndent`
var geometry, box, face1, face2, colorT, colorB, sprite, padding, maxWidth,
height, rotate;
`,
options: [2, { SwitchCase: 1 }]
},
{
code: "var geometry, box, face1, face2, colorT, colorB, sprite, padding, maxWidth;",
options: [2, { SwitchCase: 1 }]
},
{
code: unIndent`
if (1 < 2){
//hi sd
}
`,
options: [2]
},
{
code: unIndent`
while (1 < 2){
//hi sd
}
`,
options: [2]
},
{
code: "while (1 < 2) console.log('hi');",
options: [2]
},
{
code: unIndent`
[a, boop,
c].forEach((index) => {
index;
});
`,
options: [4]
},
{
code: unIndent`
[a, b,
c].forEach(function(index){
return index;
});
`,
options: [4]
},
{
code: unIndent`
[a, b, c].forEach((index) => {
index;
});
`,
options: [4]
},
{
code: unIndent`
[a, b, c].forEach(function(index){
return index;
});
`,
options: [4]
},
{
code: unIndent`
(foo)
.bar([
baz
]);
`,
options: [4, { MemberExpression: 1 }]
},
{
code: unIndent`
switch (x) {
case "foo":
a();
break;
case "bar":
switch (y) {
case "1":
break;
case "2":
a = 6;
break;
}
case "test":
break;
}
`,
options: [4, { SwitchCase: 1 }]
},
{
code: unIndent`
switch (x) {
case "foo":
a();
break;
case "bar":
switch (y) {
case "1":
break;
case "2":
a = 6;
break;
}
case "test":
break;
}
`,
options: [4, { SwitchCase: 2 }]
},
unIndent`
switch (a) {
case "foo":
a();
break;
case "bar":
switch(x){
case '1':
break;
case '2':
a = 6;
break;
}
}
`,
unIndent`
switch (a) {
case "foo":
a();
break;
case "bar":
if(x){
a = 2;
}
else{
a = 6;
}
}
`,
unIndent`
switch (a) {
case "foo":
a();
break;
case "bar":
if(x){
a = 2;
}
else
a = 6;
}
`,
unIndent`
switch (a) {
case "foo":
a();
break;
case "bar":
a(); break;
case "baz":
a(); break;
}
`,
unIndent`
switch (0) {
}
`,
unIndent`
function foo() {
var a = "a";
switch(a) {
case "a":
return "A";
case "b":
return "B";
}
}
foo();
`,
{
code: unIndent`
switch(value){
case "1":
case "2":
a();
break;
default:
a();
break;
}
switch(value){
case "1":
a();
break;
case "2":
break;
default:
break;
}
`,
options: [4, { SwitchCase: 1 }]
},
unIndent`
var obj = {foo: 1, bar: 2};
with (obj) {
console.log(foo + bar);
}
`,
unIndent`
if (a) {
(1 + 2 + 3); // no error on this line
}
`,
"switch(value){ default: a(); break; }",
{
code: unIndent`
import {addons} from 'react/addons'
import React from 'react'
`,
options: [2],
parserOptions: { ecmaVersion: 6, sourceType: "module" }
},
{
code: unIndent`
import {
foo,
bar,
baz
} from 'qux';
`,
parserOptions: { ecmaVersion: 6, sourceType: "module" }
},
{
code: unIndent`
var foo = 0, bar = 0; baz = 0;
export {
foo,
bar,
baz
} from 'qux';
`,
parserOptions: { ecmaVersion: 6, sourceType: "module" }
},
{
code: unIndent`
var a = 1,
b = 2,
c = 3;
`,
options: [4]
},
{
code: unIndent`
var a = 1
,b = 2
,c = 3;
`,
options: [4]
},
{
code: "while (1 < 2) console.log('hi')",
options: [2]
},
{
code: unIndent`
function salutation () {
switch (1) {
case 0: return console.log('hi')
case 1: return console.log('hey')
}
}
`,
options: [2, { SwitchCase: 1 }]
},
{
code: unIndent`
var items = [
{
foo: 'bar'
}
];
`,
options: [2, { VariableDeclarator: 2 }]
},
{
code: unIndent`
const a = 1,
b = 2;
const items1 = [
{
foo: 'bar'
}
];
const items2 = Items(
{
foo: 'bar'
}
);
`,
options: [2, { VariableDeclarator: 3 }]
},
{
code: unIndent`
const geometry = 2,
rotate = 3;
var a = 1,
b = 2;
let light = true,
shadow = false;
`,
options: [2, { VariableDeclarator: { const: 3, let: 2 } }]
},
{
code: unIndent`
const abc = 5,
c = 2,
xyz =
{
a: 1,
b: 2
};
let abc2 = 5,
c2 = 2,
xyz2 =
{
a: 1,
b: 2
};
var abc3 = 5,
c3 = 2,
xyz3 =
{
a: 1,
b: 2
};
`,
options: [2, { VariableDeclarator: { var: 2, const: 3 }, SwitchCase: 1 }]
},
{
code: unIndent`
module.exports = {
'Unit tests':
{
rootPath: './',
environment: 'node',
tests:
[
'test/test-*.js'
],
sources:
[
'*.js',
'test/**.js'
]
}
};
`,
options: [2]
},
{
code: unIndent`
foo =
bar;
`,
options: [2]
},
{
code: unIndent`
foo = (
bar
);
`,
options: [2]
},
{
code: unIndent`
var path = require('path')
, crypto = require('crypto')
;
`,
options: [2]
},
unIndent`
var a = 1
,b = 2
;
`,
{
code: unIndent`
export function create (some,
argument) {
return Object.create({
a: some,
b: argument
});
};
`,
options: [2, { FunctionDeclaration: { parameters: "first" } }],
parserOptions: { ecmaVersion: 6, sourceType: "module" }
},
{
code: unIndent`
export function create (id, xfilter, rawType,
width=defaultWidth, height=defaultHeight,
footerHeight=defaultFooterHeight,
padding=defaultPadding) {
// ... function body, indented two spaces
}
`,
options: [2, { FunctionDeclaration: { parameters: "first" } }],
parserOptions: { ecmaVersion: 6, sourceType: "module" }
},
{
code: unIndent`
var obj = {
foo: function () {
return new p()
.then(function (ok) {
return ok;
}, function () {
// ignore things
});
}
};
`,
options: [2]
},
{
code: unIndent`
a.b()
.c(function(){
var a;
}).d.e;
`,
options: [2]
},
{
code: unIndent`
const YO = 'bah',
TE = 'mah'
var res,
a = 5,
b = 4
`,
options: [2, { VariableDeclarator: { var: 2, let: 2, const: 3 } }]
},
{
code: unIndent`
const YO = 'bah',
TE = 'mah'
var res,
a = 5,
b = 4
if (YO) console.log(TE)
`,
options: [2, { VariableDeclarator: { var: 2, let: 2, const: 3 } }]
},
{
code: unIndent`
var foo = 'foo',
bar = 'bar',
baz = function() {
}
function hello () {
}
`,
options: [2]
},
{
code: unIndent`
var obj = {
send: function () {
return P.resolve({
type: 'POST'
})
.then(function () {
return true;
}, function () {
return false;
});
}
};
`,
options: [2]
},
{
code: unIndent`
var obj = {
send: function () {
return P.resolve({
type: 'POST'
})
.then(function () {
return true;
}, function () {
return false;
});
}
};
`,
options: [2, { MemberExpression: 0 }]
},
unIndent`
const someOtherFunction = argument => {
console.log(argument);
},
someOtherValue = 'someOtherValue';
`,
{
code: unIndent`
[
'a',
'b'
].sort().should.deepEqual([
'x',
'y'
]);
`,
options: [2]
},
{
code: unIndent`
var a = 1,
B = class {
constructor(){}
a(){}
get b(){}
};
`,
options: [2, { VariableDeclarator: 2, SwitchCase: 1 }]
},
{
code: unIndent`
var a = 1,
B =
class {
constructor(){}
a(){}
get b(){}
},
c = 3;
`,
options: [2, { VariableDeclarator: 2, SwitchCase: 1 }]
},
{
code: unIndent`
class A{
constructor(){}
a(){}
get b(){}
}
`,
options: [4, { VariableDeclarator: 1, SwitchCase: 1 }]
},
{
code: unIndent`
var A = class {
constructor(){}
a(){}
get b(){}
}
`,
options: [4, { VariableDeclarator: 1, SwitchCase: 1 }]
},
{
code: unIndent`
var a = {
some: 1
, name: 2
};
`,
options: [2]
},
{
code: unIndent`
a.c = {
aa: function() {
'test1';
return 'aa';
}
, bb: function() {
return this.bb();
}
};
`,
options: [4]
},
{
code: unIndent`
var a =
{
actions:
[
{
name: 'compile'
}
]
};
`,
options: [4, { VariableDeclarator: 0, SwitchCase: 1 }]
},
{
code: unIndent`
var a =
[
{
name: 'compile'
}
];
`,
options: [4, { VariableDeclarator: 0, SwitchCase: 1 }]
},
unIndent`
[[
], function(
foo
) {}
]
`,
unIndent`
define([
'foo'
], function(
bar
) {
baz;
}
)
`,
{
code: unIndent`
const func = function (opts) {
return Promise.resolve()
.then(() => {
[
'ONE', 'TWO'
].forEach(command => { doSomething(); });
});
};
`,
options: [4, { MemberExpression: 0 }]
},
{
code: unIndent`
const func = function (opts) {
return Promise.resolve()
.then(() => {
[
'ONE', 'TWO'
].forEach(command => { doSomething(); });
});
};
`,
options: [4]
},
{
code: unIndent`
var haveFun = function () {
SillyFunction(
{
value: true,
},
{
_id: true,
}
);
};
`,
options: [4]
},
{
code: unIndent`
var haveFun = function () {
new SillyFunction(
{
value: true,
},
{
_id: true,
}
);
};
`,
options: [4]
},
{
code: unIndent`
let object1 = {
doThing() {
return _.chain([])
.map(v => (
{
value: true,
}
))
.value();
}
};
`,
options: [2]
},
{
code: unIndent`
var foo = {
bar: 1,
baz: {
qux: 2
}
},
bar = 1;
`,
options: [2]
},
{
code: unIndent`
class Foo
extends Bar {
baz() {}
}
`,
options: [2]
},
{
code: unIndent`
class Foo extends
Bar {
baz() {}
}
`,
options: [2]
},
{
code: unIndent`
class Foo extends
(
Bar
) {
baz() {}
}
`,
options: [2]
},
{
code: unIndent`
fs.readdirSync(path.join(__dirname, '../rules')).forEach(name => {
files[name] = foo;
});
`,
options: [2, { outerIIFEBody: 0 }]
},
{
code: unIndent`
(function(){
function foo(x) {
return x + 1;
}
})();
`,
options: [2, { outerIIFEBody: 0 }]
},
{
code: unIndent`
(function(){
function foo(x) {
return x + 1;
}
})();
`,
options: [4, { outerIIFEBody: 2 }]
},
{
code: unIndent`
(function(x, y){
function foo(x) {
return x + 1;
}
})(1, 2);
`,
options: [2, { outerIIFEBody: 0 }]
},
{
code: unIndent`
(function(){
function foo(x) {
return x + 1;
}
}());
`,
options: [2, { outerIIFEBody: 0 }]
},
{
code: unIndent`
!function(){
function foo(x) {
return x + 1;
}
}();
`,
options: [2, { outerIIFEBody: 0 }]
},
{
code: unIndent`
!function(){
\t\t\tfunction foo(x) {
\t\t\t\treturn x + 1;
\t\t\t}
}();
`,
options: ["tab", { outerIIFEBody: 3 }]
},
{
code: unIndent`
var out = function(){
function fooVar(x) {
return x + 1;
}
};
`,
options: [2, { outerIIFEBody: 0 }]
},
{
code: unIndent`
var ns = function(){
function fooVar(x) {
return x + 1;
}
}();
`,
options: [2, { outerIIFEBody: 0 }]
},
{
code: unIndent`
ns = function(){
function fooVar(x) {
return x + 1;
}
}();
`,
options: [2, { outerIIFEBody: 0 }]
},
{
code: unIndent`
var ns = (function(){
function fooVar(x) {
return x + 1;
}
}(x));
`,
options: [2, { outerIIFEBody: 0 }]
},
{
code: unIndent`
var ns = (function(){
function fooVar(x) {
return x + 1;
}
}(x));
`,
options: [4, { outerIIFEBody: 2 }]
},
{
code: unIndent`
var obj = {
foo: function() {
return true;
}
};
`,
options: [2, { outerIIFEBody: 0 }]
},
{
code: unIndent`
while (
function() {
return true;
}()) {
x = x + 1;
};
`,
options: [2, { outerIIFEBody: 20 }]
},
{
code: unIndent`
(() => {
function foo(x) {
return x + 1;
}
})();
`,
options: [2, { outerIIFEBody: 0 }]
},
{
code: unIndent`
function foo() {
}
`,
options: ["tab", { outerIIFEBody: 0 }]
},
{
code: unIndent`
;(() => {
function foo(x) {
return x + 1;
}
})();
`,
options: [2, { outerIIFEBody: 0 }]
},
{
code: unIndent`
if(data) {
console.log('hi');
}
`,
options: [2, { outerIIFEBody: 0 }]
},
{
code: unIndent`
(function(x) {
return x + 1;
})();
`,
options: [4, { outerIIFEBody: "off" }]
},
{
code: unIndent`
(function(x) {
return x + 1;
})();
`,
options: [4, { outerIIFEBody: "off" }]
},
{
code: unIndent`
;(() => {
function x(y) {
return y + 1;
}
})();
`,
options: [4, { outerIIFEBody: "off" }]
},
{
code: unIndent`
;(() => {
function x(y) {
return y + 1;
}
})();
`,
options: [4, { outerIIFEBody: "off" }]
},
{
code: unIndent`
function foo() {
}
`,
options: [4, { outerIIFEBody: "off" }]
},
{
code: "Buffer.length",
options: [4, { MemberExpression: 1 }]
},
{
code: unIndent`
Buffer
.indexOf('a')
.toString()
`,
options: [4, { MemberExpression: 1 }]
},
{
code: unIndent`
Buffer.
length
`,
options: [4, { MemberExpression: 1 }]
},
{
code: unIndent`
Buffer
.foo
.bar
`,
options: [4, { MemberExpression: 1 }]
},
{
code: unIndent`
Buffer
\t.foo
\t.bar
`,
options: ["tab", { MemberExpression: 1 }]
},
{
code: unIndent`
Buffer
.foo
.bar
`,
options: [2, { MemberExpression: 2 }]
},
unIndent`
(
foo
.bar
)
`,
unIndent`
(
(
foo
.bar
)
)
`,
unIndent`
(
foo
)
.bar
`,
unIndent`
(
(
foo
)
.bar
)
`,
unIndent`
(
(
foo
)
[
(
bar
)
]
)
`,
unIndent`
(
foo[bar]
)
.baz
`,
unIndent`
(
(foo.bar)
)
.baz
`,
{
code: unIndent`
MemberExpression
.can
.be
.turned
.off();
`,
options: [4, { MemberExpression: "off" }]
},
{
code: unIndent`
foo = bar.baz()
.bip();
`,
options: [4, { MemberExpression: 1 }]
},
unIndent`
function foo() {
new
.target
}
`,
unIndent`
function foo() {
new.
target
}
`,
{
code: unIndent`
if (foo) {
bar();
} else if (baz) {
foobar();
} else if (qux) {
qux();
}
`,
options: [2]
},
{
code: unIndent`
function foo(aaa,
bbb, ccc, ddd) {
bar();
}
`,
options: [2, { FunctionDeclaration: { parameters: 1, body: 2 } }]
},
{
code: unIndent`
function foo(aaa, bbb,
ccc, ddd) {
bar();
}
`,
options: [2, { FunctionDeclaration: { parameters: 3, body: 1 } }]
},
{
code: unIndent`
function foo(aaa,
bbb,
ccc) {
bar();
}
`,
options: [4, { FunctionDeclaration: { parameters: 1, body: 3 } }]
},
{
code: unIndent`
function foo(aaa,
bbb, ccc,
ddd, eee, fff) {
bar();
}
`,
options: [2, { FunctionDeclaration: { parameters: "first", body: 1 } }]
},
{
code: unIndent`
function foo(aaa, bbb)
{
bar();
}
`,
options: [2, { FunctionDeclaration: { body: 3 } }]
},
{
code: unIndent`
function foo(
aaa,
bbb) {
bar();
}
`,
options: [2, { FunctionDeclaration: { parameters: "first", body: 2 } }]
},
{
code: unIndent`
var foo = function(aaa,
bbb,
ccc,
ddd) {
bar();
}
`,
options: [2, { FunctionExpression: { parameters: 2, body: 0 } }]
},
{
code: unIndent`
var foo = function(aaa,
bbb,
ccc) {
bar();
}
`,
options: [2, { FunctionExpression: { parameters: 1, body: 10 } }]
},
{
code: unIndent`
var foo = function(aaa,
bbb, ccc, ddd,
eee, fff) {
bar();
}
`,
options: [4, { FunctionExpression: { parameters: "first", body: 1 } }]
},
{
code: unIndent`
var foo = function(
aaa, bbb, ccc,
ddd, eee) {
bar();
}
`,
options: [2, { FunctionExpression: { parameters: "first", body: 3 } }]
},
{
code: unIndent`
foo.bar(
baz, qux, function() {
qux;
}
);
`,
options: [2, { FunctionExpression: { body: 3 }, CallExpression: { arguments: 3 } }]
},
{
code: unIndent`
function foo() {
bar();
\tbaz();
\t \t\t\t \t\t\t \t \tqux();
}
`,
options: [2]
},
{
code: unIndent`
function foo() {
function bar() {
baz();
}
}
`,
options: [2, { FunctionDeclaration: { body: 1 } }]
},
{
code: unIndent`
function foo() {
bar();
\t\t}
`,
options: [2]
},
{
code: unIndent`
function foo() {
function bar(baz,
qux) {
foobar();
}
}
`,
options: [2, { FunctionDeclaration: { body: 1, parameters: 2 } }]
},
{
code: unIndent`
((
foo
))
`,
options: [4]
},
// ternary expressions (https://github.com/eslint/eslint/issues/7420)
{
code: unIndent`
foo
? bar
: baz
`,
options: [2]
},
{
code: unIndent`
foo = (bar ?
baz :
qux
);
`,
options: [2]
},
{
code: unIndent`
condition
? () => {
return true
}
: condition2
? () => {
return true
}
: () => {
return false
}
`,
options: [2]
},
{
code: unIndent`
condition
? () => {
return true
}
: condition2
? () => {
return true
}
: () => {
return false
}
`,
options: [2, { offsetTernaryExpressions: false }]
},
{
code: unIndent`
condition
? () => {
return true
}
: condition2
? () => {
return true
}
: () => {
return false
}
`,
options: [2, { offsetTernaryExpressions: true }]
},
{
code: unIndent`
condition
? () => {
return true
}
: condition2
? () => {
return true
}
: () => {
return false
}
`,
options: [4, { offsetTernaryExpressions: true }]
},
{
code: unIndent`
condition1
? condition2
? Promise.resolve(1)
: Promise.resolve(2)
: Promise.resolve(3)
`,
options: [2, { offsetTernaryExpressions: true }]
},
{
code: unIndent`
condition1
? Promise.resolve(1)
: condition2
? Promise.resolve(2)
: Promise.resolve(3)
`,
options: [2, { offsetTernaryExpressions: true }]
},
{
code: unIndent`
condition
\t? () => {
\t\t\treturn true
\t\t}
\t: condition2
\t\t? () => {
\t\t\t\treturn true
\t\t\t}
\t\t: () => {
\t\t\t\treturn false
\t\t\t}
`,
options: ["tab", { offsetTernaryExpressions: true }]
},
unIndent`
[
foo ?
bar :
baz,
qux
];
`,
{
/*
* Checking comments:
* https://github.com/eslint/eslint/issues/3845, https://github.com/eslint/eslint/issues/6571
*/
code: unIndent`
foo();
// Line
/* multiline
Line */
bar();
// trailing comment
`,
options: [2]
},
{
code: unIndent`
switch (foo) {
case bar:
baz();
// call the baz function
}
`,
options: [2, { SwitchCase: 1 }]
},
{
code: unIndent`
switch (foo) {
case bar:
baz();
// no default
}
`,
options: [2, { SwitchCase: 1 }]
},
unIndent`
[
// no elements
]
`,
{
/*
* Destructuring assignments:
* https://github.com/eslint/eslint/issues/6813
*/
code: unIndent`
var {
foo,
bar,
baz: qux,
foobar: baz = foobar
} = qux;
`,
options: [2]
},
{
code: unIndent`
var [
foo,
bar,
baz,
foobar = baz
] = qux;
`,
options: [2]
},
{
code: unIndent`
const {
a
}
=
{
a: 1
}
`,
options: [2]
},
{
code: unIndent`
const {
a
} = {
a: 1
}
`,
options: [2]
},
{
code: unIndent`
const
{
a
} = {
a: 1
};
`,
options: [2]
},
{
code: unIndent`
const
foo = {
bar: 1
}
`,
options: [2]
},
{
code: unIndent`
const [
a
] = [
1
]
`,
options: [2]
},
{
// https://github.com/eslint/eslint/issues/7233
code: unIndent`
var folder = filePath
.foo()
.bar;
`,
options: [2, { MemberExpression: 2 }]
},
{
code: unIndent`
for (const foo of bar)
baz();
`,
options: [2]
},
{
code: unIndent`
var x = () =>
5;
`,
options: [2]
},
unIndent`
(
foo
)(
bar
)
`,
unIndent`
(() =>
foo
)(
bar
)
`,
unIndent`
(() => {
foo();
})(
bar
)
`,
{
// Don't lint the indentation of the first token after a :
code: unIndent`
({code:
"foo.bar();"})
`,
options: [2]
},
{
// Don't lint the indentation of the first token after a :
code: unIndent`
({code:
"foo.bar();"})
`,
options: [2]
},
unIndent`
({
foo:
bar
})
`,
unIndent`
({
[foo]:
bar
})
`,
{
// Comments in switch cases
code: unIndent`
switch (foo) {
// comment
case study:
// comment
bar();
case closed:
/* multiline comment
*/
}
`,
options: [2, { SwitchCase: 1 }]
},
{
// Comments in switch cases
code: unIndent`
switch (foo) {
// comment
case study:
// the comment can also be here
case closed:
}
`,
options: [2, { SwitchCase: 1 }]
},
{
// BinaryExpressions with parens
code: unIndent`
foo && (
bar
)
`,
options: [4]
},
{
// BinaryExpressions with parens
code: unIndent`
foo && ((
bar
))
`,
options: [4]
},
{
code: unIndent`
foo &&
(
bar
)
`,
options: [4]
},
unIndent`
foo &&
!bar(
)
`,
unIndent`
foo &&
![].map(() => {
bar();
})
`,
{
code: unIndent`
foo =
bar;
`,
options: [4]
},
{
code: unIndent`
function foo() {
var bar = function(baz,
qux) {
foobar();
};
}
`,
options: [2, { FunctionExpression: { parameters: 3 } }]
},
unIndent`
function foo() {
return (bar === 1 || bar === 2 &&
(/Function/.test(grandparent.type))) &&
directives(parent).indexOf(node) >= 0;
}
`,
{
code: unIndent`
function foo() {
return (foo === bar || (
baz === qux && (
foo === foo ||
bar === bar ||
baz === baz
)
))
}
`,
options: [4]
},
unIndent`
if (
foo === 1 ||
bar === 1 ||
// comment
(baz === 1 && qux === 1)
) {}
`,
{
code: unIndent`
foo =
(bar + baz);
`,
options: [2]
},
{
code: unIndent`
function foo() {
return (bar === 1 || bar === 2) &&
(z === 3 || z === 4);
}
`,
options: [2]
},
{
code: unIndent`
/* comment */ if (foo) {
bar();
}
`,
options: [2]
},
{
// Comments at the end of if blocks that have `else` blocks can either refer to the lines above or below them
code: unIndent`
if (foo) {
bar();
// Otherwise, if foo is false, do baz.
// baz is very important.
} else {
baz();
}
`,
options: [2]
},
{
code: unIndent`
function foo() {
return ((bar === 1 || bar === 2) &&
(z === 3 || z === 4));
}
`,
options: [2]
},
{
code: unIndent`
foo(
bar,
baz,
qux
);
`,
options: [2, { CallExpression: { arguments: 1 } }]
},
{
code: unIndent`
foo(
\tbar,
\tbaz,
\tqux
);
`,
options: ["tab", { CallExpression: { arguments: 1 } }]
},
{
code: unIndent`
foo(bar,
baz,
qux);
`,
options: [4, { CallExpression: { arguments: 2 } }]
},
{
code: unIndent`
foo(
bar,
baz,
qux
);
`,
options: [2, { CallExpression: { arguments: 0 } }]
},
{
code: unIndent`
foo(bar,
baz,
qux
);
`,
options: [2, { CallExpression: { arguments: "first" } }]
},
{
code: unIndent`
foo(bar, baz,
qux, barbaz,
barqux, bazqux);
`,
options: [2, { CallExpression: { arguments: "first" } }]
},
{
code: unIndent`
foo(bar,
1 + 2,
!baz,
new Car('!')
);
`,
options: [2, { CallExpression: { arguments: 4 } }]
},
unIndent`
foo(
(bar)
);
`,
{
code: unIndent`
foo(
(bar)
);
`,
options: [4, { CallExpression: { arguments: 1 } }]
},
// https://github.com/eslint/eslint/issues/7484
{
code: unIndent`
var foo = function() {
return bar(
[{
}].concat(baz)
);
};
`,
options: [2]
},
// https://github.com/eslint/eslint/issues/7573
{
code: unIndent`
return (
foo
);
`,
parserOptions: { ecmaFeatures: { globalReturn: true } }
},
{
code: unIndent`
return (
foo
)
`,
parserOptions: { ecmaFeatures: { globalReturn: true } }
},
unIndent`
var foo = [
bar,
baz
]
`,
unIndent`
var foo = [bar,
baz,
qux
]
`,
{
code: unIndent`
var foo = [bar,
baz,
qux
]
`,
options: [2, { ArrayExpression: 0 }]
},
{
code: unIndent`
var foo = [bar,
baz,
qux
]
`,
options: [2, { ArrayExpression: 8 }]
},
{
code: unIndent`
var foo = [bar,
baz,
qux
]
`,
options: [2, { ArrayExpression: "first" }]
},
{
code: unIndent`
var foo = [bar,
baz, qux
]
`,
options: [2, { ArrayExpression: "first" }]
},
{
code: unIndent`
var foo = [
{ bar: 1,
baz: 2 },
{ bar: 3,
baz: 4 }
]
`,
options: [4, { ArrayExpression: 2, ObjectExpression: "first" }]
},
{
code: unIndent`
var foo = {
bar: 1,
baz: 2
};
`,
options: [2, { ObjectExpression: 0 }]
},
{
code: unIndent`
var foo = { foo: 1, bar: 2,
baz: 3 }
`,
options: [2, { ObjectExpression: "first" }]
},
{
code: unIndent`
var foo = [
{
foo: 1
}
]
`,
options: [4, { ArrayExpression: 2 }]
},
{
code: unIndent`
function foo() {
[
foo
]
}
`,
options: [2, { ArrayExpression: 4 }]
},
{
code: "[\n]",
options: [2, { ArrayExpression: "first" }]
},
{
code: "[\n]",
options: [2, { ArrayExpression: 1 }]
},
{
code: "{\n}",
options: [2, { ObjectExpression: "first" }]
},
{
code: "{\n}",
options: [2, { ObjectExpression: 1 }]
},
{
code: unIndent`
var foo = [
[
1
]
]
`,
options: [2, { ArrayExpression: "first" }]
},
{
code: unIndent`
var foo = [ 1,
[
2
]
];
`,
options: [2, { ArrayExpression: "first" }]
},
{
code: unIndent`
var foo = bar(1,
[ 2,
3
]
);
`,
options: [4, { ArrayExpression: "first", CallExpression: { arguments: "first" } }]
},
{
code: unIndent`
var foo =
[
]()
`,
options: [4, { CallExpression: { arguments: "first" }, ArrayExpression: "first" }]
},
// https://github.com/eslint/eslint/issues/7732
{
code: unIndent`
const lambda = foo => {
Object.assign({},
filterName,
{
display
}
);
}
`,
options: [2, { ObjectExpression: 1 }]
},
{
code: unIndent`
const lambda = foo => {
Object.assign({},
filterName,
{
display
}
);
}
`,
options: [2, { ObjectExpression: "first" }]
},
// https://github.com/eslint/eslint/issues/7733
{
code: unIndent`
var foo = function() {
\twindow.foo('foo',
\t\t{
\t\t\tfoo: 'bar',
\t\t\tbar: {
\t\t\t\tfoo: 'bar'
\t\t\t}
\t\t}
\t);
}
`,
options: ["tab"]
},
{
code: unIndent`
echo = spawn('cmd.exe',
['foo', 'bar',
'baz']);
`,
options: [2, { ArrayExpression: "first", CallExpression: { arguments: "first" } }]
},
{
code: unIndent`
if (foo)
bar();
// Otherwise, if foo is false, do baz.
// baz is very important.
else {
baz();
}
`,
options: [2]
},
{
code: unIndent`
if (
foo && bar ||
baz && qux // This line is ignored because BinaryExpressions are not checked.
) {
qux();
}
`,
options: [4]
},
unIndent`
[
] || [
]
`,
unIndent`
(
[
] || [
]
)
`,
unIndent`
1
+ (
1
)
`,
unIndent`
(
foo && (
bar ||
baz
)
)
`,
unIndent`
foo
|| (
bar
)
`,
unIndent`
foo
|| (
bar
)
`,
{
code: unIndent`
var foo =
1;
`,
options: [4, { VariableDeclarator: 2 }]
},
{
code: unIndent`
var foo = 1,
bar =
2;
`,
options: [4]
},
{
code: unIndent`
switch (foo) {
case bar:
{
baz();
}
}
`,
options: [2, { SwitchCase: 1 }]
},
// Template curlies
{
code: unIndent`
\`foo\${
bar}\`
`,
options: [2]
},
{
code: unIndent`
\`foo\${
\`bar\${
baz}\`}\`
`,
options: [2]
},
{
code: unIndent`
\`foo\${
\`bar\${
baz
}\`
}\`
`,
options: [2]
},
{
code: unIndent`
\`foo\${
(
bar
)
}\`
`,
options: [2]
},
unIndent`
foo(\`
bar
\`, {
baz: 1
});
`,
unIndent`
function foo() {
\`foo\${bar}baz\${
qux}foo\${
bar}baz\`
}
`,
unIndent`
JSON
.stringify(
{
ok: true
}
);
`,
// Don't check AssignmentExpression assignments
unIndent`
foo =
bar =
baz;
`,
unIndent`
foo =
bar =
baz;
`,
unIndent`
function foo() {
const template = \`this indentation is not checked
because it's part of a template literal.\`;
}
`,
unIndent`
function foo() {
const template = \`the indentation of a \${
node.type
} node is checked.\`;
}
`,
{
// https://github.com/eslint/eslint/issues/7320
code: unIndent`
JSON
.stringify(
{
test: 'test'
}
);
`,
options: [4, { CallExpression: { arguments: 1 } }]
},
unIndent`
[
foo,
// comment
// another comment
bar
]
`,
unIndent`
if (foo) {
/* comment */ bar();
}
`,
unIndent`
function foo() {
return (
1
);
}
`,
unIndent`
function foo() {
return (
1
)
}
`,
unIndent`
if (
foo &&
!(
bar
)
) {}
`,
{
// https://github.com/eslint/eslint/issues/6007
code: unIndent`
var abc = [
(
''
),
def,
]
`,
options: [2]
},
{
code: unIndent`
var abc = [
(
''
),
(
'bar'
)
]
`,
options: [2]
},
unIndent`
function f() {
return asyncCall()
.then(
'some string',
[
1,
2,
3
]
);
}
`,
{
// https://github.com/eslint/eslint/issues/6670
code: unIndent`
function f() {
return asyncCall()
.then(
'some string',
[
1,
2,
3
]
);
}
`,
options: [4, { MemberExpression: 1 }]
},
// https://github.com/eslint/eslint/issues/7242
unIndent`
var x = [
[1],
[2]
]
`,
unIndent`
var y = [
{a: 1},
{b: 2}
]
`,
unIndent`
foo(
)
`,
{
// https://github.com/eslint/eslint/issues/7616
code: unIndent`
foo(
bar,
{
baz: 1
}
)
`,
options: [4, { CallExpression: { arguments: "first" } }]
},
"new Foo",
"new (Foo)",
unIndent`
if (Foo) {
new Foo
}
`,
{
code: unIndent`
var foo = 0, bar = 0, baz = 0;
export {
foo,
bar,
baz
}
`,
parserOptions: { ecmaVersion: 6, sourceType: "module" }
},
{
code: unIndent`
foo
? bar
: baz
`,
options: [4, { flatTernaryExpressions: true }]
},
{
code: unIndent`
foo ?
bar :
baz
`,
options: [4, { flatTernaryExpressions: true }]
},
{
code: unIndent`
foo ?
bar
: baz
`,
options: [4, { flatTernaryExpressions: true }]
},
{
code: unIndent`
foo
? bar :
baz
`,
options: [4, { flatTernaryExpressions: true }]
},
{
code: unIndent`
foo
? bar
: baz
? qux
: foobar
? boop
: beep
`,
options: [4, { flatTernaryExpressions: true }]
},
{
code: unIndent`
foo ?
bar :
baz ?
qux :
foobar ?
boop :
beep
`,
options: [4, { flatTernaryExpressions: true }]
},
{
code: unIndent`
var a =
foo ? bar :
baz ? qux :
foobar ? boop :
/*else*/ beep
`,
options: [4, { flatTernaryExpressions: true }]
},
{
code: unIndent`
var a = foo
? bar
: baz
`,
options: [4, { flatTernaryExpressions: true }]
},
{
code: unIndent`
var a =
foo
? bar
: baz
`,
options: [4, { flatTernaryExpressions: true }]
},
{
code: unIndent`
a =
foo ? bar :
baz ? qux :
foobar ? boop :
/*else*/ beep
`,
options: [4, { flatTernaryExpressions: true }]
},
{
code: unIndent`
a = foo
? bar
: baz
`,
options: [4, { flatTernaryExpressions: true }]
},
{
code: unIndent`
a =
foo
? bar
: baz
`,
options: [4, { flatTernaryExpressions: true }]
},
{
code: unIndent`
foo(
foo ? bar :
baz ? qux :
foobar ? boop :
/*else*/ beep
)
`,
options: [4, { flatTernaryExpressions: true }]
},
{
code: unIndent`
function wrap() {
return (
foo ? bar :
baz ? qux :
foobar ? boop :
/*else*/ beep
)
}
`,
options: [4, { flatTernaryExpressions: true }]
},
{
code: unIndent`
function wrap() {
return foo
? bar
: baz
}
`,
options: [4, { flatTernaryExpressions: true }]
},
{
code: unIndent`
function wrap() {
return (
foo
? bar
: baz
)
}
`,
options: [4, { flatTernaryExpressions: true }]
},
{
code: unIndent`
foo(
foo
? bar
: baz
)
`,
options: [4, { flatTernaryExpressions: true }]
},
{
code: unIndent`
foo(foo
? bar
: baz
)
`,
options: [4, { flatTernaryExpressions: true }]
},
{
code: unIndent`
foo
? bar
: baz
? qux
: foobar
? boop
: beep
`,
options: [4, { flatTernaryExpressions: false }]
},
{
code: unIndent`
foo ?
bar :
baz ?
qux :
foobar ?
boop :
beep
`,
options: [4, { flatTernaryExpressions: false }]
},
{
code: "[,]",
options: [2, { ArrayExpression: "first" }]
},
{
code: "[,]",
options: [2, { ArrayExpression: "off" }]
},
{
code: unIndent`
[
,
foo
]
`,
options: [4, { ArrayExpression: "first" }]
},
{
code: "[sparse, , array];",
options: [2, { ArrayExpression: "first" }]
},
{
code: unIndent`
foo.bar('baz', function(err) {
qux;
});
`,
options: [2, { CallExpression: { arguments: "first" } }]
},
{
code: unIndent`
foo.bar(function() {
cookies;
}).baz(function() {
cookies;
});
`,
options: [2, { MemberExpression: 1 }]
},
{
code: unIndent`
foo.bar().baz(function() {
cookies;
}).qux(function() {
cookies;
});
`,
options: [2, { MemberExpression: 1 }]
},
{
code: unIndent`
(
{
foo: 1,
baz: 2
}
);
`,
options: [2, { ObjectExpression: "first" }]
},
{
code: unIndent`
foo(() => {
bar;
}, () => {
baz;
})
`,
options: [4, { CallExpression: { arguments: "first" } }]
},
{
code: unIndent`
[ foo,
bar ].forEach(function() {
baz;
})
`,
options: [2, { ArrayExpression: "first", MemberExpression: 1 }]
},
unIndent`
foo = bar[
baz
];
`,
{
code: unIndent`
foo[
bar
];
`,
options: [4, { MemberExpression: 1 }]
},
{
code: unIndent`
foo[
(
bar
)
];
`,
options: [4, { MemberExpression: 1 }]
},
unIndent`
if (foo)
bar;
else if (baz)
qux;
`,
unIndent`
if (foo) bar()
; [1, 2, 3].map(baz)
`,
unIndent`
if (foo)
;
`,
"x => {}",
{
code: unIndent`
import {foo}
from 'bar';
`,
parserOptions: { ecmaVersion: 6, sourceType: "module" }
},
{
code: "import 'foo'",
parserOptions: { ecmaVersion: 6, sourceType: "module" }
},
{
code: unIndent`
import { foo,
bar,
baz,
} from 'qux';
`,
options: [4, { ImportDeclaration: 1 }],
parserOptions: { ecmaVersion: 6, sourceType: "module" }
},
{
code: unIndent`
import {
foo,
bar,
baz,
} from 'qux';
`,
options: [4, { ImportDeclaration: 1 }],
parserOptions: { ecmaVersion: 6, sourceType: "module" }
},
{
code: unIndent`
import { apple as a,
banana as b } from 'fruits';
import { cat } from 'animals';
`,
options: [4, { ImportDeclaration: "first" }],
parserOptions: { ecmaVersion: 6, sourceType: "module" }
},
{
code: unIndent`
import { declaration,
can,
be,
turned } from 'off';
`,
options: [4, { ImportDeclaration: "off" }],
parserOptions: { ecmaVersion: 6, sourceType: "module" }
},
// https://github.com/eslint/eslint/issues/8455
unIndent`
(
a
) => b => {
c
}
`,
unIndent`
(
a
) => b => c => d => {
e
}
`,
unIndent`
(
a
) =>
(
b
) => {
c
}
`,
unIndent`
if (
foo
) bar(
baz
);
`,
unIndent`
if (foo)
{
bar();
}
`,
unIndent`
function foo(bar)
{
baz();
}
`,
unIndent`
() =>
({})
`,
unIndent`
() =>
(({}))
`,
unIndent`
(
() =>
({})
)
`,
unIndent`
var x = function foop(bar)
{
baz();
}
`,
unIndent`
var x = (bar) =>
{
baz();
}
`,
unIndent`
class Foo
{
constructor()
{
foo();
}
bar()
{
baz();
}
}
`,
unIndent`
class Foo
extends Bar
{
constructor()
{
foo();
}
bar()
{
baz();
}
}
`,
unIndent`
(
class Foo
{
constructor()
{
foo();
}
bar()
{
baz();
}
}
)
`,
{
code: unIndent`
switch (foo)
{
case 1:
bar();
}
`,
options: [4, { SwitchCase: 1 }]
},
unIndent`
foo
.bar(function() {
baz
})
`,
{
code: unIndent`
foo
.bar(function() {
baz
})
`,
options: [4, { MemberExpression: 2 }]
},
unIndent`
foo
[bar](function() {
baz
})
`,
unIndent`
foo.
bar.
baz
`,
{
code: unIndent`
foo
.bar(function() {
baz
})
`,
options: [4, { MemberExpression: "off" }]
},
{
code: unIndent`
foo
.bar(function() {
baz
})
`,
options: [4, { MemberExpression: "off" }]
},
{
code: unIndent`
foo
[bar](function() {
baz
})
`,
options: [4, { MemberExpression: "off" }]
},
{
code: unIndent`
foo.
bar.
baz
`,
options: [4, { MemberExpression: "off" }]
},
{
code: unIndent`
foo = bar(
).baz(
)
`,
options: [4, { MemberExpression: "off" }]
},
{
code: unIndent`
foo[
bar ? baz :
qux
]
`,
options: [4, { flatTernaryExpressions: true }]
},
{
code: unIndent`
function foo() {
return foo ? bar :
baz
}
`,
options: [4, { flatTernaryExpressions: true }]
},
{
code: unIndent`
throw foo ? bar :
baz
`,
options: [4, { flatTernaryExpressions: true }]
},
{
code: unIndent`
foo(
bar
) ? baz :
qux
`,
options: [4, { flatTernaryExpressions: true }]
},
unIndent`
foo
[
bar
]
.baz(function() {
quz();
})
`,
unIndent`
[
foo
][
"map"](function() {
qux();
})
`,
unIndent`
(
a.b(function() {
c;
})
)
`,
unIndent`
(
foo
).bar(function() {
baz();
})
`,
unIndent`
new Foo(
bar
.baz
.qux
)
`,
unIndent`
const foo = a.b(),
longName =
(baz(
'bar',
'bar'
));
`,
unIndent`
const foo = a.b(),
longName =
(baz(
'bar',
'bar'
));
`,
unIndent`
const foo = a.b(),
longName =
baz(
'bar',
'bar'
);
`,
unIndent`
const foo = a.b(),
longName =
baz(
'bar',
'bar'
);
`,
unIndent`
const foo = a.b(),
longName
= baz(
'bar',
'bar'
);
`,
unIndent`
const foo = a.b(),
longName
= baz(
'bar',
'bar'
);
`,
unIndent`
const foo = a.b(),
longName =
('fff');
`,
unIndent`
const foo = a.b(),
longName =
('fff');
`,
unIndent`
const foo = a.b(),
longName
= ('fff');
`,
unIndent`
const foo = a.b(),
longName
= ('fff');
`,
unIndent`
const foo = a.b(),
longName =
(
'fff'
);
`,
unIndent`
const foo = a.b(),
longName =
(
'fff'
);
`,
unIndent`
const foo = a.b(),
longName
=(
'fff'
);
`,
unIndent`
const foo = a.b(),
longName
=(
'fff'
);
`,
//----------------------------------------------------------------------
// Ignore Unknown Nodes
//----------------------------------------------------------------------
{
code: unIndent`
interface Foo {
bar: string;
baz: number;
}
`,
parser: parser("unknown-nodes/interface")
},
{
code: unIndent`
namespace Foo {
const bar = 3,
baz = 2;
if (true) {
const bax = 3;
}
}
`,
parser: parser("unknown-nodes/namespace-valid")
},
{
code: unIndent`
abstract class Foo {
public bar() {
let aaa = 4,
boo;
if (true) {
boo = 3;
}
boo = 3 + 2;
}
}
`,
parser: parser("unknown-nodes/abstract-class-valid")
},
{
code: unIndent`
function foo() {
function bar() {
abstract class X {
public baz() {
if (true) {
qux();
}
}
}
}
}
`,
parser: parser("unknown-nodes/functions-with-abstract-class-valid")
},
{
code: unIndent`
namespace Unknown {
function foo() {
function bar() {
abstract class X {
public baz() {
if (true) {
qux();
}
}
}
}
}
}
`,
parser: parser("unknown-nodes/namespace-with-functions-with-abstract-class-valid")
},
{
code: unIndent`
type httpMethod = 'GET'
| 'POST'
| 'PUT';
`,
options: [2, { VariableDeclarator: 0 }],
parser: parser("unknown-nodes/variable-declarator-type-indent-two-spaces")
},
{
code: unIndent`
type httpMethod = 'GET'
| 'POST'
| 'PUT';
`,
options: [2, { VariableDeclarator: 1 }],
parser: parser("unknown-nodes/variable-declarator-type-no-indent")
},
unIndent`
foo(\`foo
\`, {
ok: true
},
{
ok: false
})
`,
unIndent`
foo(tag\`foo
\`, {
ok: true
},
{
ok: false
}
)
`,
// https://github.com/eslint/eslint/issues/8815
unIndent`
async function test() {
const {
foo,
bar,
} = await doSomethingAsync(
1,
2,
3,
);
}
`,
unIndent`
function* test() {
const {
foo,
bar,
} = yield doSomethingAsync(
1,
2,
3,
);
}
`,
unIndent`
({
a: b
} = +foo(
bar
));
`,
unIndent`
const {
foo,
bar,
} = typeof foo(
1,
2,
3,
);
`,
unIndent`
const {
foo,
bar,
} = +(
foo
);
`,
//----------------------------------------------------------------------
// JSX tests
// https://github.com/eslint/eslint/issues/8425
// Some of the following tests are adapted from the tests in eslint-plugin-react.
// License: https://github.com/yannickcr/eslint-plugin-react/blob/7ca9841f22d599f447a27ef5b2a97def9229d6c8/LICENSE
//----------------------------------------------------------------------
"<Foo a=\"b\" c=\"d\"/>;",
unIndent`
<Foo
a="b"
c="d"
/>;
`,
"var foo = <Bar a=\"b\" c=\"d\"/>;",
unIndent`
var foo = <Bar
a="b"
c="d"
/>;
`,
unIndent`
var foo = (<Bar
a="b"
c="d"
/>);
`,
unIndent`
var foo = (
<Bar
a="b"
c="d"
/>
);
`,
unIndent`
<
Foo
a="b"
c="d"
/>;
`,
unIndent`
<Foo
a="b"
c="d"/>;
`,
unIndent`
<
Foo
a="b"
c="d"/>;
`,
"<a href=\"foo\">bar</a>;",
unIndent`
<a href="foo">
bar
</a>;
`,
unIndent`
<a
href="foo"
>
bar
</a>;
`,
unIndent`
<a
href="foo">
bar
</a>;
`,
unIndent`
<
a
href="foo">
bar
</a>;
`,
unIndent`
<a
href="foo">
bar
</
a>;
`,
unIndent`
<a
href="foo">
bar
</a
>;
`,
unIndent`
var foo = <a href="bar">
baz
</a>;
`,
unIndent`
var foo = <a
href="bar"
>
baz
</a>;
`,
unIndent`
var foo = <a
href="bar">
baz
</a>;
`,
unIndent`
var foo = <
a
href="bar">
baz
</a>;
`,
unIndent`
var foo = <a
href="bar">
baz
</
a>;
`,
unIndent`
var foo = <a
href="bar">
baz
</a
>
`,
unIndent`
var foo = (<a
href="bar">
baz
</a>);
`,
unIndent`
var foo = (
<a href="bar">baz</a>
);
`,
unIndent`
var foo = (
<a href="bar">
baz
</a>
);
`,
unIndent`
var foo = (
<a
href="bar">
baz
</a>
);
`,
"var foo = <a href=\"bar\">baz</a>;",
unIndent`
<a>
{
}
</a>
`,
unIndent`
<a>
{
foo
}
</a>
`,
unIndent`
function foo() {
return (
<a>
{
b.forEach(() => {
// comment
a = c
.d()
.e();
})
}
</a>
);
}
`,
"<App></App>",
unIndent`
<App>
</App>
`,
{
code: unIndent`
<App>
<Foo />
</App>
`,
options: [2]
},
{
code: unIndent`
<App>
<Foo />
</App>
`,
options: [0]
},
{
code: unIndent`
<App>
\t<Foo />
</App>
`,
options: ["tab"]
},
{
code: unIndent`
function App() {
return <App>
<Foo />
</App>;
}
`,
options: [2]
},
{
code: unIndent`
function App() {
return (<App>
<Foo />
</App>);
}
`,
options: [2]
},
{
code: unIndent`
function App() {
return (
<App>
<Foo />
</App>
);
}
`,
options: [2]
},
{
code: unIndent`
it(
(
<div>
<span />
</div>
)
)
`,
options: [2]
},
{
code: unIndent`
it(
(<div>
<span />
<span />
<span />
</div>)
)
`,
options: [2]
},
{
code: unIndent`
(
<div>
<span />
</div>
)
`,
options: [2]
},
{
code: unIndent`
{
head.title &&
<h1>
{head.title}
</h1>
}
`,
options: [2]
},
{
code: unIndent`
{
head.title &&
<h1>
{head.title}
</h1>
}
`,
options: [2]
},
{
code: unIndent`
{
head.title && (
<h1>
{head.title}
</h1>)
}
`,
options: [2]
},
{
code: unIndent`
{
head.title && (
<h1>
{head.title}
</h1>
)
}
`,
options: [2]
},
{
code: unIndent`
[
<div />,
<div />
]
`,
options: [2]
},
unIndent`
<div>
{
[
<Foo />,
<Bar />
]
}
</div>
`,
unIndent`
<div>
{foo &&
[
<Foo />,
<Bar />
]
}
</div>
`,
unIndent`
<div>
bar <div>
bar
bar {foo}
bar </div>
</div>
`,
unIndent`
foo ?
<Foo /> :
<Bar />
`,
unIndent`
foo ?
<Foo />
: <Bar />
`,
unIndent`
foo ?
<Foo />
:
<Bar />
`,
unIndent`
<div>
{!foo ?
<Foo
onClick={this.onClick}
/>
:
<Bar
onClick={this.onClick}
/>
}
</div>
`,
{
code: unIndent`
<span>
{condition ?
<Thing
foo={\`bar\`}
/> :
<Thing/>
}
</span>
`,
options: [2]
},
{
code: unIndent`
<span>
{condition ?
<Thing
foo={"bar"}
/> :
<Thing/>
}
</span>
`,
options: [2]
},
{
code: unIndent`
function foo() {
<span>
{condition ?
<Thing
foo={bar}
/> :
<Thing/>
}
</span>
}
`,
options: [2]
},
unIndent`
<App foo
/>
`,
{
code: unIndent`
<App
foo
/>
`,
options: [2]
},
{
code: unIndent`
<App
foo
/>
`,
options: [0]
},
{
code: unIndent`
<App
\tfoo
/>
`,
options: ["tab"]
},
unIndent`
<App
foo
/>
`,
unIndent`
<App
foo
></App>
`,
{
code: unIndent`
<App
foo={function() {
console.log('bar');
}}
/>
`,
options: [2]
},
{
code: unIndent`
<App foo={function() {
console.log('bar');
}}
/>
`,
options: [2]
},
{
code: unIndent`
var x = function() {
return <App
foo={function() {
console.log('bar');
}}
/>
}
`,
options: [2]
},
{
code: unIndent`
var x = <App
foo={function() {
console.log('bar');
}}
/>
`,
options: [2]
},
{
code: unIndent`
<Provider
store
>
<App
foo={function() {
console.log('bar');
}}
/>
</Provider>
`,
options: [2]
},
{
code: unIndent`
<Provider
store
>
{baz && <App
foo={function() {
console.log('bar');
}}
/>}
</Provider>
`,
options: [2]
},
{
code: unIndent`
<App
\tfoo
/>
`,
options: ["tab"]
},
{
code: unIndent`
<App
\tfoo
></App>
`,
options: ["tab"]
},
{
code: unIndent`
<App foo={function() {
\tconsole.log('bar');
}}
/>
`,
options: ["tab"]
},
{
code: unIndent`
var x = <App
\tfoo={function() {
\t\tconsole.log('bar');
\t}}
/>
`,
options: ["tab"]
},
unIndent`
<App
foo />
`,
unIndent`
<div>
unrelated{
foo
}
</div>
`,
unIndent`
<div>unrelated{
foo
}
</div>
`,
unIndent`
<
foo
.bar
.baz
>
foo
</
foo.
bar.
baz
>
`,
unIndent`
<
input
type=
"number"
/>
`,
unIndent`
<
input
type=
{'number'}
/>
`,
unIndent`
<
input
type
="number"
/>
`,
unIndent`
foo ? (
bar
) : (
baz
)
`,
unIndent`
foo ? (
<div>
</div>
) : (
<span>
</span>
)
`,
unIndent`
<div>
{
/* foo */
}
</div>
`,
/*
* JSX Fragments
* https://github.com/eslint/eslint/issues/12208
*/
unIndent`
<>
<A />
</>
`,
unIndent`
<
>
<A />
</>
`,
unIndent`
<>
<A />
<
/>
`,
unIndent`
<>
<A />
</
>
`,
unIndent`
<
>
<A />
</
>
`,
unIndent`
<
>
<A />
<
/>
`,
unIndent`
< // Comment
>
<A />
</>
`,
unIndent`
<
// Comment
>
<A />
</>
`,
unIndent`
<
// Comment
>
<A />
</>
`,
unIndent`
<>
<A />
< // Comment
/>
`,
unIndent`
<>
<A />
<
// Comment
/>
`,
unIndent`
<>
<A />
<
// Comment
/>
`,
unIndent`
<>
<A />
</ // Comment
>
`,
unIndent`
<>
<A />
</
// Comment
>
`,
unIndent`
<>
<A />
</
// Comment
>
`,
unIndent`
< /* Comment */
>
<A />
</>
`,
unIndent`
<
/* Comment */
>
<A />
</>
`,
unIndent`
<
/* Comment */
>
<A />
</>
`,
unIndent`
<
/*
* Comment
*/
>
<A />
</>
`,
unIndent`
<
/*
* Comment
*/
>
<A />
</>
`,
unIndent`
<>
<A />
< /* Comment */
/>
`,
unIndent`
<>
<A />
<
/* Comment */ />
`,
unIndent`
<>
<A />
<
/* Comment */ />
`,
unIndent`
<>
<A />
<
/* Comment */
/>
`,
unIndent`
<>
<A />
<
/* Comment */
/>
`,
unIndent`
<>
<A />
</ /* Comment */
>
`,
unIndent`
<>
<A />
</
/* Comment */ >
`,
unIndent`
<>
<A />
</
/* Comment */ >
`,
unIndent`
<>
<A />
</
/* Comment */
>
`,
unIndent`
<>
<A />
</
/* Comment */
>
`,
// https://github.com/eslint/eslint/issues/8832
unIndent`
<div>
{
(
1
)
}
</div>
`,
unIndent`
function A() {
return (
<div>
{
b && (
<div>
</div>
)
}
</div>
);
}
`,
unIndent`
<div>foo
<div>bar</div>
</div>
`,
unIndent`
<small>Foo bar
<a>baz qux</a>.
</small>
`,
unIndent`
<div
{...props}
/>
`,
unIndent`
<div
{
...props
}
/>
`,
{
code: unIndent`
a(b
, c
)
`,
options: [2, { CallExpression: { arguments: "off" } }]
},
{
code: unIndent`
a(
new B({
c,
})
);
`,
options: [2, { CallExpression: { arguments: "off" } }]
},
{
code: unIndent`
foo
? bar
: baz
`,
options: [4, { ignoredNodes: ["ConditionalExpression"] }]
},
{
code: unIndent`
class Foo {
foo() {
bar();
}
}
`,
options: [4, { ignoredNodes: ["ClassBody"] }]
},
{
code: unIndent`
class Foo {
foo() {
bar();
}
}
`,
options: [4, { ignoredNodes: ["ClassBody", "BlockStatement"] }]
},
{
code: unIndent`
foo({
bar: 1
},
{
baz: 2
},
{
qux: 3
})
`,
options: [4, { ignoredNodes: ["CallExpression > ObjectExpression"] }]
},
{
code: unIndent`
foo
.bar
`,
options: [4, { ignoredNodes: ["MemberExpression"] }]
},
{
code: unIndent`
$(function() {
foo();
bar();
});
`,
options: [4, {
ignoredNodes: ["Program > ExpressionStatement > CallExpression[callee.name='$'] > FunctionExpression > BlockStatement"]
}]
},
{
code: unIndent`
<Foo
bar="1" />
`,
options: [4, { ignoredNodes: ["JSXOpeningElement"] }]
},
{
code: unIndent`
foo &&
<Bar
>
</Bar>
`,
options: [4, { ignoredNodes: ["JSXElement", "JSXOpeningElement"] }]
},
{
code: unIndent`
(function($) {
$(function() {
foo;
});
}())
`,
options: [4, { ignoredNodes: ["ExpressionStatement > CallExpression > FunctionExpression.callee > BlockStatement"] }]
},
{
code: unIndent`
const value = (
condition ?
valueIfTrue :
valueIfFalse
);
`,
options: [4, { ignoredNodes: ["ConditionalExpression"] }]
},
{
code: unIndent`
var a = 0, b = 0, c = 0;
export default foo(
a,
b, {
c
}
)
`,
options: [4, { ignoredNodes: ["ExportDefaultDeclaration > CallExpression > ObjectExpression"] }],
parserOptions: { ecmaVersion: 6, sourceType: "module" }
},
{
code: unIndent`
foobar = baz
? qux
: boop
`,
options: [4, { ignoredNodes: ["ConditionalExpression"] }]
},
{
code: unIndent`
\`
SELECT
\${
foo
} FROM THE_DATABASE
\`
`,
options: [4, { ignoredNodes: ["TemplateLiteral"] }]
},
{
code: unIndent`
<foo
prop='bar'
>
Text
</foo>
`,
options: [4, { ignoredNodes: ["JSXOpeningElement"] }]
},
{
code: unIndent`
{
\tvar x = 1,
\t y = 2;
}
`,
options: ["tab"]
},
{
code: unIndent`
var x = 1,
y = 2;
var z;
`,
options: ["tab", { ignoredNodes: ["VariableDeclarator"] }]
},
{
code: unIndent`
[
foo(),
bar
]
`,
options: ["tab", { ArrayExpression: "first", ignoredNodes: ["CallExpression"] }]
},
{
code: unIndent`
if (foo) {
doSomething();
// Intentionally unindented comment
doSomethingElse();
}
`,
options: [4, { ignoreComments: true }]
},
{
code: unIndent`
if (foo) {
doSomething();
/* Intentionally unindented comment */
doSomethingElse();
}
`,
options: [4, { ignoreComments: true }]
},
unIndent`
const obj = {
foo () {
return condition ? // comment
1 :
2
}
}
`,
//----------------------------------------------------------------------
// Comment alignment tests
//----------------------------------------------------------------------
unIndent`
if (foo) {
// Comment can align with code immediately above even if "incorrect" alignment
doSomething();
}
`,
unIndent`
if (foo) {
doSomething();
// Comment can align with code immediately below even if "incorrect" alignment
}
`,
unIndent`
if (foo) {
// Comment can be in correct alignment even if not aligned with code above/below
}
`,
unIndent`
if (foo) {
// Comment can be in correct alignment even if gaps between (and not aligned with) code above/below
}
`,
unIndent`
[{
foo
},
// Comment between nodes
{
bar
}];
`,
unIndent`
[{
foo
},
// Comment between nodes
{ // comment
bar
}];
`,
unIndent`
let foo
// comment
;(async () => {})()
`,
unIndent`
let foo
// comment
;(async () => {})()
`,
unIndent`
let foo
// comment
;(async () => {})()
`,
unIndent`
let foo
// comment
;(async () => {})()
`,
unIndent`
let foo
/* comment */;
(async () => {})()
`,
unIndent`
let foo
/* comment */;
(async () => {})()
`,
unIndent`
let foo
/* comment */;
(async () => {})()
`,
unIndent`
let foo
/* comment */;
(async () => {})()
`,
unIndent`
let foo
/* comment */;
(async () => {})()
`,
unIndent`
let foo
/* comment */;
(async () => {})()
`,
unIndent`
// comment
;(async () => {})()
`,
unIndent`
// comment
;(async () => {})()
`,
unIndent`
{
let foo
// comment
;(async () => {})()
}
`,
unIndent`
{
let foo
// comment
;(async () => {})()
}
`,
unIndent`
{
// comment
;(async () => {})()
}
`,
unIndent`
{
// comment
;(async () => {})()
}
`,
unIndent`
const foo = 1
const bar = foo
/* comment */
;[1, 2, 3].forEach(() => {})
`,
unIndent`
const foo = 1
const bar = foo
/* comment */
;[1, 2, 3].forEach(() => {})
`,
unIndent`
const foo = 1
const bar = foo
/* comment */
;[1, 2, 3].forEach(() => {})
`,
unIndent`
const foo = 1
const bar = foo
/* comment */
;[1, 2, 3].forEach(() => {})
`,
unIndent`
const foo = 1
const bar = foo
/* comment */;
[1, 2, 3].forEach(() => {})
`,
unIndent`
const foo = 1
const bar = foo
/* comment */;
[1, 2, 3].forEach(() => {})
`,
unIndent`
const foo = 1
const bar = foo
/* comment */;
[1, 2, 3].forEach(() => {})
`,
unIndent`
const foo = 1
const bar = foo
/* comment */;
[1, 2, 3].forEach(() => {})
`,
unIndent`
const foo = 1
const bar = foo
/* comment */;
[1, 2, 3].forEach(() => {})
`,
unIndent`
const foo = 1
const bar = foo
/* comment */;
[1, 2, 3].forEach(() => {})
`,
unIndent`
/* comment */
;[1, 2, 3].forEach(() => {})
`,
unIndent`
/* comment */
;[1, 2, 3].forEach(() => {})
`,
unIndent`
{
const foo = 1
const bar = foo
/* comment */
;[1, 2, 3].forEach(() => {})
}
`,
unIndent`
{
const foo = 1
const bar = foo
/* comment */
;[1, 2, 3].forEach(() => {})
}
`,
unIndent`
{
/* comment */
;[1, 2, 3].forEach(() => {})
}
`,
unIndent`
{
/* comment */
;[1, 2, 3].forEach(() => {})
}
`,
// import expressions
{
code: unIndent`
import(
// before
source
// after
)
`,
parserOptions: { ecmaVersion: 2020 }
},
// https://github.com/eslint/eslint/issues/12122
{
code: unIndent`
foo(() => {
tag\`
multiline
template
literal
\`(() => {
bar();
});
});
`,
parserOptions: { ecmaVersion: 2015 }
},
{
code: unIndent`
{
tag\`
multiline
template
\${a} \${b}
literal
\`(() => {
bar();
});
}
`,
parserOptions: { ecmaVersion: 2015 }
},
{
code: unIndent`
foo(() => {
tagOne\`
multiline
template
literal
\${a} \${b}
\`(() => {
tagTwo\`
multiline
template
literal
\`(() => {
bar();
});
baz();
});
});
`,
parserOptions: { ecmaVersion: 2015 }
},
{
code: unIndent`
{
tagOne\`
\${a} \${b}
multiline
template
literal
\`(() => {
tagTwo\`
multiline
template
literal
\`(() => {
bar();
});
baz();
});
};
`,
parserOptions: { ecmaVersion: 2015 }
},
{
code: unIndent`
tagOne\`multiline
\${a} \${b}
template
literal
\`(() => {
foo();
tagTwo\`multiline
template
literal
\`({
bar: 1,
baz: 2
});
});
`,
parserOptions: { ecmaVersion: 2015 }
},
{
code: unIndent`
tagOne\`multiline
template
literal
\${a} \${b}\`({
foo: 1,
bar: tagTwo\`multiline
template
literal\`(() => {
baz();
})
});
`,
parserOptions: { ecmaVersion: 2015 }
},
{
code: unIndent`
foo.bar\` template literal \`(() => {
baz();
})
`,
parserOptions: { ecmaVersion: 2015 }
},
{
code: unIndent`
foo.bar.baz\` template literal \`(() => {
baz();
})
`,
parserOptions: { ecmaVersion: 2015 }
},
{
code: unIndent`
foo
.bar\` template
literal \`(() => {
baz();
})
`,
parserOptions: { ecmaVersion: 2015 }
},
{
code: unIndent`
foo
.bar
.baz\` template
literal \`(() => {
baz();
})
`,
parserOptions: { ecmaVersion: 2015 }
},
{
code: unIndent`
foo.bar\`
\${a} \${b}
\`(() => {
baz();
})
`,
parserOptions: { ecmaVersion: 2015 }
},
{
code: unIndent`
foo.bar1.bar2\`
\${a} \${b}
\`(() => {
baz();
})
`,
parserOptions: { ecmaVersion: 2015 }
},
{
code: unIndent`
foo
.bar1
.bar2\`
\${a} \${b}
\`(() => {
baz();
})
`,
parserOptions: { ecmaVersion: 2015 }
},
{
code: unIndent`
foo
.bar\`
\${a} \${b}
\`(() => {
baz();
})
`,
parserOptions: { ecmaVersion: 2015 }
},
{
code: unIndent`
foo
.test\`
\${a} \${b}
\`(() => {
baz();
})
`,
options: [4, { MemberExpression: 0 }],
parserOptions: { ecmaVersion: 2015 }
},
{
code: unIndent`
foo
.test\`
\${a} \${b}
\`(() => {
baz();
})
`,
options: [4, { MemberExpression: 2 }],
parserOptions: { ecmaVersion: 2015 }
},
{
code: unIndent`
const foo = async (arg1,
arg2) =>
{
return arg1 + arg2;
}
`,
options: [2, { FunctionDeclaration: { parameters: "first" }, FunctionExpression: { parameters: "first" } }]
},
{
code: unIndent`
const foo = async /* some comments */(arg1,
arg2) =>
{
return arg1 + arg2;
}
`,
options: [2, { FunctionDeclaration: { parameters: "first" }, FunctionExpression: { parameters: "first" } }]
},
{
code: unIndent`
const a = async
b => {}
`,
options: [2]
},
{
code: unIndent`
const foo = (arg1,
arg2) => async (arr1,
arr2) =>
{
return arg1 + arg2;
}
`,
options: [2, { FunctionDeclaration: { parameters: "first" }, FunctionExpression: { parameters: "first" } }]
},
{
code: unIndent`
const foo = async (arg1,
arg2) =>
{
return arg1 + arg2;
}
`,
options: [2]
},
{
code: unIndent`
const foo = async /*comments*/(arg1,
arg2) =>
{
return arg1 + arg2;
}
`,
options: [2]
},
{
code: unIndent`
const foo = async (arg1,
arg2) =>
{
return arg1 + arg2;
}
`,
options: [2, { FunctionDeclaration: { parameters: 4 }, FunctionExpression: { parameters: 4 } }]
},
{
code: unIndent`
const foo = (arg1,
arg2) =>
{
return arg1 + arg2;
}
`,
options: [2, { FunctionDeclaration: { parameters: 4 }, FunctionExpression: { parameters: 4 } }]
},
{
code: unIndent`
async function fn(ar1,
ar2){}
`,
options: [2, { FunctionDeclaration: { parameters: "first" }, FunctionExpression: { parameters: "first" } }]
},
{
code: unIndent`
async function /* some comments */ fn(ar1,
ar2){}
`,
options: [2, { FunctionDeclaration: { parameters: "first" }, FunctionExpression: { parameters: "first" } }]
},
{
code: unIndent`
async /* some comments */ function fn(ar1,
ar2){}
`,
options: [2, { FunctionDeclaration: { parameters: "first" }, FunctionExpression: { parameters: "first" } }]
},
{
code: unIndent`
class C {
static {
foo();
bar();
}
}
`,
options: [2],
parserOptions: { ecmaVersion: 2022 }
},
{
code: unIndent`
class C {
static {
foo();
bar();
}
}
`,
options: [4],
parserOptions: { ecmaVersion: 2022 }
},
{
code: unIndent`
class C {
static {
foo();
bar();
}
}
`,
options: [4, { StaticBlock: { body: 2 } }],
parserOptions: { ecmaVersion: 2022 }
},
{
code: unIndent`
class C {
static {
foo();
bar();
}
}
`,
options: [4, { StaticBlock: { body: 0 } }],
parserOptions: { ecmaVersion: 2022 }
},
{
code: unIndent`
class C {
\tstatic {
\t\tfoo();
\t\tbar();
\t}
}
`,
options: ["tab"],
parserOptions: { ecmaVersion: 2022 }
},
{
code: unIndent`
class C {
\tstatic {
\t\t\tfoo();
\t\t\tbar();
\t}
}
`,
options: ["tab", { StaticBlock: { body: 2 } }],
parserOptions: { ecmaVersion: 2022 }
},
{
code: unIndent`
class C {
static
{
foo();
bar();
}
}
`,
options: [4],
parserOptions: { ecmaVersion: 2022 }
},
{
code: unIndent`
class C {
static {
var x,
y;
}
}
`,
options: [4],
parserOptions: { ecmaVersion: 2022 }
},
{
code: unIndent`
class C {
static
{
var x,
y;
}
}
`,
options: [4],
parserOptions: { ecmaVersion: 2022 }
},
{
code: unIndent`
class C {
static {
if (foo) {
bar;
}
}
}
`,
options: [4],
parserOptions: { ecmaVersion: 2022 }
},
{
code: unIndent`
class C {
static {
{
bar;
}
}
}
`,
options: [4],
parserOptions: { ecmaVersion: 2022 }
},
{
code: unIndent`
class C {
static {}
static {
}
static
{
}
}
`,
options: [4],
parserOptions: { ecmaVersion: 2022 }
},
{
code: unIndent`
class C {
static {
foo;
}
static {
bar;
}
}
`,
options: [4],
parserOptions: { ecmaVersion: 2022 }
},
{
code: unIndent`
class C {
x = 1;
static {
foo;
}
y = 2;
}
`,
options: [4],
parserOptions: { ecmaVersion: 2022 }
},
{
code: unIndent`
class C {
method1(param) {
foo;
}
static {
bar;
}
method2(param) {
foo;
}
}
`,
options: [4],
parserOptions: { ecmaVersion: 2022 }
},
{
code: unIndent`
function f() {
class C {
static {
foo();
bar();
}
}
}
`,
options: [4],
parserOptions: { ecmaVersion: 2022 }
},
{
code: unIndent`
class C {
method() {
foo;
}
static {
bar;
}
}
`,
options: [4, { FunctionExpression: { body: 2 }, StaticBlock: { body: 2 } }],
parserOptions: { ecmaVersion: 2022 }
}
],
invalid: [
{
code: unIndent`
var a = b;
if (a) {
b();
}
`,
output: unIndent`
var a = b;
if (a) {
b();
}
`,
options: [2],
errors: expectedErrors([[3, 2, 0, "Identifier"]])
},
{
code: unIndent`
require('http').request({hostname: 'localhost',
port: 80}, function(res) {
res.end();
});
`,
output: unIndent`
require('http').request({hostname: 'localhost',
port: 80}, function(res) {
res.end();
});
`,
options: [2],
errors: expectedErrors([[2, 2, 18, "Identifier"], [3, 2, 4, "Identifier"], [4, 0, 2, "Punctuator"]])
},
{
code: unIndent`
if (array.some(function(){
return true;
})) {
a++; // ->
b++;
c++; // <-
}
`,
output: unIndent`
if (array.some(function(){
return true;
})) {
a++; // ->
b++;
c++; // <-
}
`,
options: [2],
errors: expectedErrors([[4, 2, 0, "Identifier"], [6, 2, 4, "Identifier"]])
},
{
code: unIndent`
if (a){
\tb=c;
\t\tc=d;
e=f;
}
`,
output: unIndent`
if (a){
\tb=c;
\tc=d;
\te=f;
}
`,
options: ["tab"],
errors: expectedErrors("tab", [[3, 1, 2, "Identifier"], [4, 1, 0, "Identifier"]])
},
{
code: unIndent`
if (a){
b=c;
c=d;
e=f;
}
`,
output: unIndent`
if (a){
b=c;
c=d;
e=f;
}
`,
options: [4],
errors: expectedErrors([[3, 4, 6, "Identifier"], [4, 4, 1, "Identifier"]])
},
{
code: fixture,
output: fixedFixture,
options: [2, { SwitchCase: 1, MemberExpression: 1, CallExpression: { arguments: "off" } }],
errors: expectedErrors([
[5, 2, 4, "Keyword"],
[6, 2, 0, "Line"],
[10, 4, 6, "Punctuator"],
[11, 2, 4, "Punctuator"],
[15, 4, 2, "Identifier"],
[16, 2, 4, "Punctuator"],
[23, 2, 4, "Punctuator"],
[29, 2, 4, "Keyword"],
[30, 4, 6, "Identifier"],
[36, 4, 6, "Identifier"],
[38, 2, 4, "Punctuator"],
[39, 4, 2, "Identifier"],
[40, 2, 0, "Punctuator"],
[54, 2, 4, "Punctuator"],
[114, 4, 2, "Keyword"],
[120, 4, 6, "Keyword"],
[124, 4, 2, "Keyword"],
[134, 4, 6, "Keyword"],
[138, 2, 3, "Punctuator"],
[139, 2, 3, "Punctuator"],
[143, 4, 0, "Identifier"],
[144, 6, 2, "Punctuator"],
[145, 6, 2, "Punctuator"],
[151, 4, 6, "Identifier"],
[152, 6, 8, "Punctuator"],
[153, 6, 8, "Punctuator"],
[159, 4, 2, "Identifier"],
[161, 4, 6, "Identifier"],
[175, 2, 0, "Identifier"],
[177, 2, 4, "Identifier"],
[189, 2, 0, "Keyword"],
[192, 6, 18, "Identifier"],
[193, 6, 4, "Identifier"],
[195, 6, 8, "Identifier"],
[228, 5, 4, "Identifier"],
[231, 3, 2, "Punctuator"],
[245, 0, 2, "Punctuator"],
[248, 0, 2, "Punctuator"],
[304, 4, 6, "Identifier"],
[306, 4, 8, "Identifier"],
[307, 2, 4, "Punctuator"],
[308, 2, 4, "Identifier"],
[311, 4, 6, "Identifier"],
[312, 4, 6, "Identifier"],
[313, 4, 6, "Identifier"],
[314, 2, 4, "Punctuator"],
[315, 2, 4, "Identifier"],
[318, 4, 6, "Identifier"],
[319, 4, 6, "Identifier"],
[320, 4, 6, "Identifier"],
[321, 2, 4, "Punctuator"],
[322, 2, 4, "Identifier"],
[326, 2, 1, "Numeric"],
[327, 2, 1, "Numeric"],
[328, 2, 1, "Numeric"],
[329, 2, 1, "Numeric"],
[330, 2, 1, "Numeric"],
[331, 2, 1, "Numeric"],
[332, 2, 1, "Numeric"],
[333, 2, 1, "Numeric"],
[334, 2, 1, "Numeric"],
[335, 2, 1, "Numeric"],
[340, 2, 4, "Identifier"],
[341, 2, 0, "Identifier"],
[344, 2, 4, "Identifier"],
[345, 2, 0, "Identifier"],
[348, 2, 4, "Identifier"],
[349, 2, 0, "Identifier"],
[355, 2, 0, "Identifier"],
[357, 2, 4, "Identifier"],
[361, 4, 6, "Identifier"],
[362, 2, 4, "Punctuator"],
[363, 2, 4, "Identifier"],
[368, 2, 0, "Keyword"],
[370, 2, 4, "Keyword"],
[374, 4, 6, "Keyword"],
[376, 4, 2, "Keyword"],
[383, 2, 0, "Identifier"],
[385, 2, 4, "Identifier"],
[390, 2, 0, "Identifier"],
[392, 2, 4, "Identifier"],
[409, 2, 0, "Identifier"],
[410, 2, 4, "Identifier"],
[416, 2, 0, "Identifier"],
[417, 2, 4, "Identifier"],
[418, 0, 4, "Punctuator"],
[422, 2, 4, "Identifier"],
[423, 2, 0, "Identifier"],
[427, 2, 6, "Identifier"],
[428, 2, 8, "Identifier"],
[429, 2, 4, "Identifier"],
[430, 0, 4, "Punctuator"],
[433, 2, 4, "Identifier"],
[434, 0, 4, "Punctuator"],
[437, 2, 0, "Identifier"],
[438, 0, 4, "Punctuator"],
[442, 2, 4, "Identifier"],
[443, 2, 4, "Identifier"],
[444, 0, 2, "Punctuator"],
[451, 2, 0, "Identifier"],
[453, 2, 4, "Identifier"],
[499, 6, 8, "Punctuator"],
[500, 8, 6, "Identifier"],
[504, 4, 6, "Punctuator"],
[505, 6, 8, "Identifier"],
[506, 4, 8, "Punctuator"]
])
},
{
code: unIndent`
switch(value){
case "1":
a();
break;
case "2":
a();
break;
default:
a();
break;
}
`,
output: unIndent`
switch(value){
case "1":
a();
break;
case "2":
a();
break;
default:
a();
break;
}
`,
options: [4, { SwitchCase: 1 }],
errors: expectedErrors([[4, 8, 4, "Keyword"], [7, 8, 4, "Keyword"]])
},
{
code: unIndent`
var x = 0 &&
{
a: 1,
b: 2
};
`,
output: unIndent`
var x = 0 &&
{
a: 1,
b: 2
};
`,
options: [4],
errors: expectedErrors([[3, 8, 7, "Identifier"], [4, 8, 10, "Identifier"]])
},
{
code: unIndent`
switch(value){
case "1":
a();
break;
case "2":
a();
break;
default:
break;
}
`,
output: unIndent`
switch(value){
case "1":
a();
break;
case "2":
a();
break;
default:
break;
}
`,
options: [4, { SwitchCase: 1 }],
errors: expectedErrors([9, 8, 4, "Keyword"])
},
{
code: unIndent`
switch(value){
case "1":
case "2":
a();
break;
default:
break;
}
switch(value){
case "1":
break;
case "2":
a();
break;
default:
a();
break;
}
`,
output: unIndent`
switch(value){
case "1":
case "2":
a();
break;
default:
break;
}
switch(value){
case "1":
break;
case "2":
a();
break;
default:
a();
break;
}
`,
options: [4, { SwitchCase: 1 }],
errors: expectedErrors([[11, 8, 4, "Keyword"], [14, 8, 4, "Keyword"], [17, 8, 4, "Keyword"]])
},
{
code: unIndent`
switch(value){
case "1":
a();
break;
case "2":
break;
default:
break;
}
`,
output: unIndent`
switch(value){
case "1":
a();
break;
case "2":
break;
default:
break;
}
`,
options: [4],
errors: expectedErrors([
[3, 4, 8, "Identifier"],
[4, 4, 8, "Keyword"],
[5, 0, 4, "Keyword"],
[6, 4, 8, "Keyword"],
[7, 0, 4, "Keyword"],
[8, 4, 8, "Keyword"]
])
},
{
code: unIndent`
var obj = {foo: 1, bar: 2};
with (obj) {
console.log(foo + bar);
}
`,
output: unIndent`
var obj = {foo: 1, bar: 2};
with (obj) {
console.log(foo + bar);
}
`,
errors: expectedErrors([3, 4, 0, "Identifier"])
},
{
code: unIndent`
switch (a) {
case '1':
b();
break;
default:
c();
break;
}
`,
output: unIndent`
switch (a) {
case '1':
b();
break;
default:
c();
break;
}
`,
options: [4, { SwitchCase: 1 }],
errors: expectedErrors([
[2, 4, 0, "Keyword"],
[3, 8, 0, "Identifier"],
[4, 8, 0, "Keyword"],
[5, 4, 0, "Keyword"],
[6, 8, 0, "Identifier"],
[7, 8, 0, "Keyword"]
])
},
{
code: unIndent`
var foo = function(){
foo
.bar
}
`,
output: unIndent`
var foo = function(){
foo
.bar
}
`,
options: [4, { MemberExpression: 1 }],
errors: expectedErrors(
[3, 8, 10, "Punctuator"]
)
},
{
code: unIndent`
(
foo
.bar
)
`,
output: unIndent`
(
foo
.bar
)
`,
errors: expectedErrors([3, 8, 4, "Punctuator"])
},
{
code: unIndent`
var foo = function(){
foo
.bar
}
`,
output: unIndent`
var foo = function(){
foo
.bar
}
`,
options: [4, { MemberExpression: 2 }],
errors: expectedErrors(
[3, 12, 13, "Punctuator"]
)
},
{
code: unIndent`
var foo = () => {
foo
.bar
}
`,
output: unIndent`
var foo = () => {
foo
.bar
}
`,
options: [4, { MemberExpression: 2 }],
errors: expectedErrors(
[3, 12, 13, "Punctuator"]
)
},
{
code: unIndent`
TestClass.prototype.method = function () {
return Promise.resolve(3)
.then(function (x) {
return x;
});
};
`,
output: unIndent`
TestClass.prototype.method = function () {
return Promise.resolve(3)
.then(function (x) {
return x;
});
};
`,
options: [2, { MemberExpression: 1 }],
errors: expectedErrors([3, 4, 6, "Punctuator"])
},
{
code: unIndent`
while (a)
b();
`,
output: unIndent`
while (a)
b();
`,
options: [4],
errors: expectedErrors([
[2, 4, 0, "Identifier"]
])
},
{
code: unIndent`
lmn = [{
a: 1
},
{
b: 2
},
{
x: 2
}];
`,
output: unIndent`
lmn = [{
a: 1
},
{
b: 2
},
{
x: 2
}];
`,
errors: expectedErrors([
[2, 4, 8, "Identifier"],
[3, 0, 4, "Punctuator"],
[4, 0, 4, "Punctuator"],
[5, 4, 8, "Identifier"],
[6, 0, 4, "Punctuator"],
[7, 0, 4, "Punctuator"],
[8, 4, 8, "Identifier"]
])
},
{
code: unIndent`
for (var foo = 1;
foo < 10;
foo++) {}
`,
output: unIndent`
for (var foo = 1;
foo < 10;
foo++) {}
`,
errors: expectedErrors([[2, 4, 0, "Identifier"], [3, 4, 0, "Identifier"]])
},
{
code: unIndent`
for (
var foo = 1;
foo < 10;
foo++
) {}
`,
output: unIndent`
for (
var foo = 1;
foo < 10;
foo++
) {}
`,
errors: expectedErrors([[2, 4, 0, "Keyword"], [3, 4, 0, "Identifier"], [4, 4, 0, "Identifier"], [5, 0, 4, "Punctuator"]])
},
{
code: unIndent`
for (;;)
b();
`,
output: unIndent`
for (;;)
b();
`,
options: [4],
errors: expectedErrors([
[2, 4, 0, "Identifier"]
])
},
{
code: unIndent`
for (a in x)
b();
`,
output: unIndent`
for (a in x)
b();
`,
options: [4],
errors: expectedErrors([
[2, 4, 0, "Identifier"]
])
},
{
code: unIndent`
do
b();
while(true)
`,
output: unIndent`
do
b();
while(true)
`,
options: [4],
errors: expectedErrors([
[2, 4, 0, "Identifier"]
])
},
{
code: unIndent`
if(true)
b();
`,
output: unIndent`
if(true)
b();
`,
options: [4],
errors: expectedErrors([
[2, 4, 0, "Identifier"]
])
},
{
code: unIndent`
var test = {
a: 1,
b: 2
};
`,
output: unIndent`
var test = {
a: 1,
b: 2
};
`,
options: [2],
errors: expectedErrors([
[2, 2, 6, "Identifier"],
[3, 2, 4, "Identifier"],
[4, 0, 4, "Punctuator"]
])
},
{
code: unIndent`
var a = function() {
a++;
b++;
c++;
},
b;
`,
output: unIndent`
var a = function() {
a++;
b++;
c++;
},
b;
`,
options: [4],
errors: expectedErrors([
[2, 8, 6, "Identifier"],
[3, 8, 4, "Identifier"],
[4, 8, 10, "Identifier"]
])
},
{
code: unIndent`
var a = 1,
b = 2,
c = 3;
`,
output: unIndent`
var a = 1,
b = 2,
c = 3;
`,
options: [4],
errors: expectedErrors([
[2, 4, 0, "Identifier"],
[3, 4, 0, "Identifier"]
])
},
{
code: unIndent`
[a, b,
c].forEach((index) => {
index;
});
`,
output: unIndent`
[a, b,
c].forEach((index) => {
index;
});
`,
options: [4],
errors: expectedErrors([
[3, 4, 8, "Identifier"],
[4, 0, 4, "Punctuator"]
])
},
{
code: unIndent`
[a, b,
c].forEach(function(index){
return index;
});
`,
output: unIndent`
[a, b,
c].forEach(function(index){
return index;
});
`,
options: [4],
errors: expectedErrors([
[2, 4, 0, "Identifier"],
[3, 4, 2, "Keyword"]
])
},
{
code: unIndent`
[a, b, c].forEach(function(index){
return index;
});
`,
output: unIndent`
[a, b, c].forEach(function(index){
return index;
});
`,
options: [4],
errors: expectedErrors([
[2, 4, 2, "Keyword"]
])
},
{
code: unIndent`
(foo)
.bar([
baz
]);
`,
output: unIndent`
(foo)
.bar([
baz
]);
`,
options: [4, { MemberExpression: 1 }],
errors: expectedErrors([[3, 8, 4, "Identifier"], [4, 4, 0, "Punctuator"]])
},
{
code: unIndent`
var x = ['a',
'b',
'c'
];
`,
output: unIndent`
var x = ['a',
'b',
'c'
];
`,
options: [4],
errors: expectedErrors([
[2, 4, 9, "String"],
[3, 4, 9, "String"]
])
},
{
code: unIndent`
var x = [
'a',
'b',
'c'
];
`,
output: unIndent`
var x = [
'a',
'b',
'c'
];
`,
options: [4],
errors: expectedErrors([
[2, 4, 9, "String"],
[3, 4, 9, "String"],
[4, 4, 9, "String"]
])
},
{
code: unIndent`
var x = [
'a',
'b',
'c',
'd'];
`,
output: unIndent`
var x = [
'a',
'b',
'c',
'd'];
`,
options: [4],
errors: expectedErrors([
[2, 4, 9, "String"],
[3, 4, 9, "String"],
[4, 4, 9, "String"],
[5, 4, 0, "String"]
])
},
{
code: unIndent`
var x = [
'a',
'b',
'c'
];
`,
output: unIndent`
var x = [
'a',
'b',
'c'
];
`,
options: [4],
errors: expectedErrors([
[2, 4, 9, "String"],
[3, 4, 9, "String"],
[4, 4, 9, "String"],
[5, 0, 2, "Punctuator"]
])
},
{
code: unIndent`
[[
], function(
foo
) {}
]
`,
output: unIndent`
[[
], function(
foo
) {}
]
`,
errors: expectedErrors([[3, 4, 8, "Identifier"], [4, 0, 4, "Punctuator"]])
},
{
code: unIndent`
define([
'foo'
], function(
bar
) {
baz;
}
)
`,
output: unIndent`
define([
'foo'
], function(
bar
) {
baz;
}
)
`,
errors: expectedErrors([[4, 4, 8, "Identifier"], [5, 0, 4, "Punctuator"]])
},
{
code: unIndent`
while (1 < 2)
console.log('foo')
console.log('bar')
`,
output: unIndent`
while (1 < 2)
console.log('foo')
console.log('bar')
`,
options: [2],
errors: expectedErrors([
[2, 2, 0, "Identifier"],
[3, 0, 2, "Identifier"]
])
},
{
code: unIndent`
function salutation () {
switch (1) {
case 0: return console.log('hi')
case 1: return console.log('hey')
}
}
`,
output: unIndent`
function salutation () {
switch (1) {
case 0: return console.log('hi')
case 1: return console.log('hey')
}
}
`,
options: [2, { SwitchCase: 1 }],
errors: expectedErrors([
[3, 4, 2, "Keyword"]
])
},
{
code: unIndent`
var geometry, box, face1, face2, colorT, colorB, sprite, padding, maxWidth,
height, rotate;
`,
output: unIndent`
var geometry, box, face1, face2, colorT, colorB, sprite, padding, maxWidth,
height, rotate;
`,
options: [2, { SwitchCase: 1 }],
errors: expectedErrors([
[2, 2, 0, "Identifier"]
])
},
{
code: unIndent`
switch (a) {
case '1':
b();
break;
default:
c();
break;
}
`,
output: unIndent`
switch (a) {
case '1':
b();
break;
default:
c();
break;
}
`,
options: [4, { SwitchCase: 2 }],
errors: expectedErrors([
[2, 8, 0, "Keyword"],
[3, 12, 0, "Identifier"],
[4, 12, 0, "Keyword"],
[5, 8, 0, "Keyword"],
[6, 12, 0, "Identifier"],
[7, 12, 0, "Keyword"]
])
},
{
code: unIndent`
var geometry,
rotate;
`,
output: unIndent`
var geometry,
rotate;
`,
options: [2, { VariableDeclarator: 1 }],
errors: expectedErrors([
[2, 2, 0, "Identifier"]
])
},
{
code: unIndent`
var geometry,
rotate;
`,
output: unIndent`
var geometry,
rotate;
`,
options: [2, { VariableDeclarator: 2 }],
errors: expectedErrors([
[2, 4, 2, "Identifier"]
])
},
{
code: unIndent`
var geometry,
\trotate;
`,
output: unIndent`
var geometry,
\t\trotate;
`,
options: ["tab", { VariableDeclarator: 2 }],
errors: expectedErrors("tab", [
[2, 2, 1, "Identifier"]
])
},
{
code: unIndent`
let geometry,
rotate;
`,
output: unIndent`
let geometry,
rotate;
`,
options: [2, { VariableDeclarator: 2 }],
errors: expectedErrors([
[2, 4, 2, "Identifier"]
])
},
{
code: unIndent`
let foo = 'foo',
bar = bar;
const a = 'a',
b = 'b';
`,
output: unIndent`
let foo = 'foo',
bar = bar;
const a = 'a',
b = 'b';
`,
options: [2, { VariableDeclarator: "first" }],
errors: expectedErrors([
[2, 4, 2, "Identifier"],
[4, 6, 2, "Identifier"]
])
},
{
code: unIndent`
var foo = 'foo',
bar = bar;
`,
output: unIndent`
var foo = 'foo',
bar = bar;
`,
options: [2, { VariableDeclarator: { var: "first" } }],
errors: expectedErrors([
[2, 4, 2, "Identifier"]
])
},
{
code: unIndent`
if(true)
if (true)
if (true)
console.log(val);
`,
output: unIndent`
if(true)
if (true)
if (true)
console.log(val);
`,
options: [2, { VariableDeclarator: 2, SwitchCase: 1 }],
errors: expectedErrors([
[4, 6, 4, "Identifier"]
])
},
{
code: unIndent`
var a = {
a: 1,
b: 2
}
`,
output: unIndent`
var a = {
a: 1,
b: 2
}
`,
options: [2, { VariableDeclarator: 2, SwitchCase: 1 }],
errors: expectedErrors([
[2, 2, 4, "Identifier"],
[3, 2, 4, "Identifier"]
])
},
{
code: unIndent`
var a = [
a,
b
]
`,
output: unIndent`
var a = [
a,
b
]
`,
options: [2, { VariableDeclarator: 2, SwitchCase: 1 }],
errors: expectedErrors([
[2, 2, 4, "Identifier"],
[3, 2, 4, "Identifier"]
])
},
{
code: unIndent`
let a = [
a,
b
]
`,
output: unIndent`
let a = [
a,
b
]
`,
options: [2, { VariableDeclarator: { let: 2 }, SwitchCase: 1 }],
errors: expectedErrors([
[2, 2, 4, "Identifier"],
[3, 2, 4, "Identifier"]
])
},
{
code: unIndent`
var a = new Test({
a: 1
}),
b = 4;
`,
output: unIndent`
var a = new Test({
a: 1
}),
b = 4;
`,
options: [4],
errors: expectedErrors([
[2, 8, 6, "Identifier"],
[3, 4, 2, "Punctuator"]
])
},
{
code: unIndent`
var a = new Test({
a: 1
}),
b = 4;
const c = new Test({
a: 1
}),
d = 4;
`,
output: unIndent`
var a = new Test({
a: 1
}),
b = 4;
const c = new Test({
a: 1
}),
d = 4;
`,
options: [2, { VariableDeclarator: { var: 2 } }],
errors: expectedErrors([
[6, 4, 6, "Identifier"],
[7, 2, 4, "Punctuator"],
[8, 2, 4, "Identifier"]
])
},
{
code: unIndent`
var abc = 5,
c = 2,
xyz =
{
a: 1,
b: 2
};
`,
output: unIndent`
var abc = 5,
c = 2,
xyz =
{
a: 1,
b: 2
};
`,
options: [2, { VariableDeclarator: 2, SwitchCase: 1 }],
errors: expectedErrors([6, 6, 7, "Identifier"])
},
{
code: unIndent`
var abc =
{
a: 1,
b: 2
};
`,
output: unIndent`
var abc =
{
a: 1,
b: 2
};
`,
options: [2, { VariableDeclarator: 2, SwitchCase: 1 }],
errors: expectedErrors([4, 7, 8, "Identifier"])
},
{
code: unIndent`
var foo = {
bar: 1,
baz: {
qux: 2
}
},
bar = 1;
`,
output: unIndent`
var foo = {
bar: 1,
baz: {
qux: 2
}
},
bar = 1;
`,
options: [2],
errors: expectedErrors([[4, 6, 8, "Identifier"], [5, 4, 6, "Punctuator"]])
},
{
code: unIndent`
var path = require('path')
, crypto = require('crypto')
;
`,
output: unIndent`
var path = require('path')
, crypto = require('crypto')
;
`,
options: [2],
errors: expectedErrors([
[2, 2, 1, "Punctuator"]
])
},
{
code: unIndent`
var a = 1
,b = 2
;
`,
output: unIndent`
var a = 1
,b = 2
;
`,
errors: expectedErrors([
[2, 4, 3, "Punctuator"]
])
},
{
code: unIndent`
class A{
constructor(){}
a(){}
get b(){}
}
`,
output: unIndent`
class A{
constructor(){}
a(){}
get b(){}
}
`,
options: [4, { VariableDeclarator: 1, SwitchCase: 1 }],
errors: expectedErrors([[2, 4, 2, "Identifier"]])
},
{
code: unIndent`
var A = class {
constructor(){}
a(){}
get b(){}
};
`,
output: unIndent`
var A = class {
constructor(){}
a(){}
get b(){}
};
`,
options: [4, { VariableDeclarator: 1, SwitchCase: 1 }],
errors: expectedErrors([[2, 4, 2, "Identifier"], [4, 4, 2, "Identifier"]])
},
{
code: unIndent`
var a = 1,
B = class {
constructor(){}
a(){}
get b(){}
};
`,
output: unIndent`
var a = 1,
B = class {
constructor(){}
a(){}
get b(){}
};
`,
options: [2, { VariableDeclarator: 2, SwitchCase: 1 }],
errors: expectedErrors([[3, 6, 4, "Identifier"]])
},
{
code: unIndent`
{
if(a){
foo();
}
else{
bar();
}
}
`,
output: unIndent`
{
if(a){
foo();
}
else{
bar();
}
}
`,
options: [4],
errors: expectedErrors([[5, 4, 2, "Keyword"]])
},
{
code: unIndent`
{
if(a){
foo();
}
else
bar();
}
`,
output: unIndent`
{
if(a){
foo();
}
else
bar();
}
`,
options: [4],
errors: expectedErrors([[5, 4, 2, "Keyword"]])
},
{
code: unIndent`
{
if(a)
foo();
else
bar();
}
`,
output: unIndent`
{
if(a)
foo();
else
bar();
}
`,
options: [4],
errors: expectedErrors([[4, 4, 2, "Keyword"]])
},
{
code: unIndent`
(function(){
function foo(x) {
return x + 1;
}
})();
`,
output: unIndent`
(function(){
function foo(x) {
return x + 1;
}
})();
`,
options: [2, { outerIIFEBody: 0 }],
errors: expectedErrors([[2, 0, 2, "Keyword"], [3, 2, 4, "Keyword"], [4, 0, 2, "Punctuator"]])
},
{
code: unIndent`
(function(){
function foo(x) {
return x + 1;
}
})();
`,
output: unIndent`
(function(){
function foo(x) {
return x + 1;
}
})();
`,
options: [4, { outerIIFEBody: 2 }],
errors: expectedErrors([[2, 8, 4, "Keyword"], [3, 12, 8, "Keyword"], [4, 8, 4, "Punctuator"]])
},
{
code: unIndent`
if(data) {
console.log('hi');
}
`,
output: unIndent`
if(data) {
console.log('hi');
}
`,
options: [2, { outerIIFEBody: 0 }],
errors: expectedErrors([[2, 2, 0, "Identifier"]])
},
{
code: unIndent`
var ns = function(){
function fooVar(x) {
return x + 1;
}
}(x);
`,
output: unIndent`
var ns = function(){
function fooVar(x) {
return x + 1;
}
}(x);
`,
options: [4, { outerIIFEBody: 2 }],
errors: expectedErrors([[2, 8, 4, "Keyword"], [3, 12, 8, "Keyword"], [4, 8, 4, "Punctuator"]])
},
{
code: unIndent`
var obj = {
foo: function() {
return true;
}()
};
`,
output: unIndent`
var obj = {
foo: function() {
return true;
}()
};
`,
options: [2, { outerIIFEBody: 0 }],
errors: expectedErrors([[3, 4, 2, "Keyword"]])
},
{
code: unIndent`
typeof function() {
function fooVar(x) {
return x + 1;
}
}();
`,
output: unIndent`
typeof function() {
function fooVar(x) {
return x + 1;
}
}();
`,
options: [2, { outerIIFEBody: 2 }],
errors: expectedErrors([[2, 2, 4, "Keyword"], [3, 4, 6, "Keyword"], [4, 2, 4, "Punctuator"]])
},
{
code: unIndent`
{
\t!function(x) {
\t\t\t\treturn x + 1;
\t}()
};
`,
output: unIndent`
{
\t!function(x) {
\t\treturn x + 1;
\t}()
};
`,
options: ["tab", { outerIIFEBody: 3 }],
errors: expectedErrors("tab", [[3, 2, 4, "Keyword"]])
},
{
code: unIndent`
(function(){
function foo(x) {
return x + 1;
}
})();
`,
output: unIndent`
(function(){
function foo(x) {
return x + 1;
}
})();
`,
options: [4, { outerIIFEBody: "off" }],
errors: expectedErrors([[3, 8, 4, "Keyword"]])
},
{
code: unIndent`
(function(){
function foo(x) {
return x + 1;
}
})();
`,
output: unIndent`
(function(){
function foo(x) {
return x + 1;
}
})();
`,
options: [4, { outerIIFEBody: "off" }],
errors: expectedErrors([[3, 4, 0, "Keyword"]])
},
{
code: unIndent`
(() => {
function foo(x) {
return x + 1;
}
})();
`,
output: unIndent`
(() => {
function foo(x) {
return x + 1;
}
})();
`,
options: [4, { outerIIFEBody: "off" }],
errors: expectedErrors([[3, 8, 4, "Keyword"]])
},
{
code: unIndent`
(() => {
function foo(x) {
return x + 1;
}
})();
`,
output: unIndent`
(() => {
function foo(x) {
return x + 1;
}
})();
`,
options: [4, { outerIIFEBody: "off" }],
errors: expectedErrors([[3, 4, 0, "Keyword"]])
},
{
code: unIndent`
Buffer
.toString()
`,
output: unIndent`
Buffer
.toString()
`,
options: [4, { MemberExpression: 1 }],
errors: expectedErrors([[2, 4, 0, "Punctuator"]])
},
{
code: unIndent`
Buffer
.indexOf('a')
.toString()
`,
output: unIndent`
Buffer
.indexOf('a')
.toString()
`,
options: [4, { MemberExpression: 1 }],
errors: expectedErrors([[3, 4, 0, "Punctuator"]])
},
{
code: unIndent`
Buffer.
length
`,
output: unIndent`
Buffer.
length
`,
options: [4, { MemberExpression: 1 }],
errors: expectedErrors([[2, 4, 0, "Identifier"]])
},
{
code: unIndent`
Buffer.
\t\tlength
`,
output: unIndent`
Buffer.
\tlength
`,
options: ["tab", { MemberExpression: 1 }],
errors: expectedErrors("tab", [[2, 1, 2, "Identifier"]])
},
{
code: unIndent`
Buffer
.foo
.bar
`,
output: unIndent`
Buffer
.foo
.bar
`,
options: [2, { MemberExpression: 2 }],
errors: expectedErrors([[2, 4, 2, "Punctuator"], [3, 4, 2, "Punctuator"]])
},
{
code: unIndent`
function foo() {
new
.target
}
`,
output: unIndent`
function foo() {
new
.target
}
`,
errors: expectedErrors([3, 8, 4, "Punctuator"])
},
{
code: unIndent`
function foo() {
new.
target
}
`,
output: unIndent`
function foo() {
new.
target
}
`,
errors: expectedErrors([3, 8, 4, "Identifier"])
},
{
// Indentation with multiple else statements: https://github.com/eslint/eslint/issues/6956
code: unIndent`
if (foo) bar();
else if (baz) foobar();
else if (qux) qux();
`,
output: unIndent`
if (foo) bar();
else if (baz) foobar();
else if (qux) qux();
`,
options: [2],
errors: expectedErrors([3, 0, 2, "Keyword"])
},
{
code: unIndent`
if (foo) bar();
else if (baz) foobar();
else qux();
`,
output: unIndent`
if (foo) bar();
else if (baz) foobar();
else qux();
`,
options: [2],
errors: expectedErrors([3, 0, 2, "Keyword"])
},
{
code: unIndent`
foo();
if (baz) foobar();
else qux();
`,
output: unIndent`
foo();
if (baz) foobar();
else qux();
`,
options: [2],
errors: expectedErrors([[2, 0, 2, "Keyword"], [3, 0, 2, "Keyword"]])
},
{
code: unIndent`
if (foo) bar();
else if (baz) foobar();
else if (bip) {
qux();
}
`,
output: unIndent`
if (foo) bar();
else if (baz) foobar();
else if (bip) {
qux();
}
`,
options: [2],
errors: expectedErrors([[3, 0, 5, "Keyword"], [4, 2, 7, "Identifier"], [5, 0, 5, "Punctuator"]])
},
{
code: unIndent`
if (foo) bar();
else if (baz) {
foobar();
} else if (boop) {
qux();
}
`,
output: unIndent`
if (foo) bar();
else if (baz) {
foobar();
} else if (boop) {
qux();
}
`,
options: [2],
errors: expectedErrors([[3, 2, 4, "Identifier"], [4, 0, 5, "Punctuator"], [5, 2, 7, "Identifier"], [6, 0, 5, "Punctuator"]])
},
{
code: unIndent`
function foo(aaa,
bbb, ccc, ddd) {
bar();
}
`,
output: unIndent`
function foo(aaa,
bbb, ccc, ddd) {
bar();
}
`,
options: [2, { FunctionDeclaration: { parameters: 1, body: 2 } }],
errors: expectedErrors([[2, 2, 4, "Identifier"], [3, 4, 6, "Identifier"]])
},
{
code: unIndent`
function foo(aaa, bbb,
ccc, ddd) {
bar();
}
`,
output: unIndent`
function foo(aaa, bbb,
ccc, ddd) {
bar();
}
`,
options: [2, { FunctionDeclaration: { parameters: 3, body: 1 } }],
errors: expectedErrors([[2, 6, 2, "Identifier"], [3, 2, 0, "Identifier"]])
},
{
code: unIndent`
function foo(aaa,
bbb,
ccc) {
bar();
}
`,
output: unIndent`
function foo(aaa,
bbb,
ccc) {
bar();
}
`,
options: [4, { FunctionDeclaration: { parameters: 1, body: 3 } }],
errors: expectedErrors([[2, 4, 8, "Identifier"], [3, 4, 2, "Identifier"], [4, 12, 6, "Identifier"]])
},
{
code: unIndent`
function foo(aaa,
bbb, ccc,
ddd, eee, fff) {
bar();
}
`,
output: unIndent`
function foo(aaa,
bbb, ccc,
ddd, eee, fff) {
bar();
}
`,
options: [2, { FunctionDeclaration: { parameters: "first", body: 1 } }],
errors: expectedErrors([[2, 13, 2, "Identifier"], [3, 13, 19, "Identifier"], [4, 2, 3, "Identifier"]])
},
{
code: unIndent`
function foo(aaa, bbb)
{
bar();
}
`,
output: unIndent`
function foo(aaa, bbb)
{
bar();
}
`,
options: [2, { FunctionDeclaration: { body: 3 } }],
errors: expectedErrors([3, 6, 0, "Identifier"])
},
{
code: unIndent`
function foo(
aaa,
bbb) {
bar();
}
`,
output: unIndent`
function foo(
aaa,
bbb) {
bar();
}
`,
options: [2, { FunctionDeclaration: { parameters: "first", body: 2 } }],
errors: expectedErrors([[2, 2, 0, "Identifier"], [3, 2, 4, "Identifier"], [4, 4, 0, "Identifier"]])
},
{
code: unIndent`
var foo = function(aaa,
bbb,
ccc,
ddd) {
bar();
}
`,
output: unIndent`
var foo = function(aaa,
bbb,
ccc,
ddd) {
bar();
}
`,
options: [2, { FunctionExpression: { parameters: 2, body: 0 } }],
errors: expectedErrors([[2, 4, 2, "Identifier"], [4, 4, 6, "Identifier"], [5, 0, 2, "Identifier"]])
},
{
code: unIndent`
var foo = function(aaa,
bbb,
ccc) {
bar();
}
`,
output: unIndent`
var foo = function(aaa,
bbb,
ccc) {
bar();
}
`,
options: [2, { FunctionExpression: { parameters: 1, body: 10 } }],
errors: expectedErrors([[2, 2, 3, "Identifier"], [3, 2, 1, "Identifier"], [4, 20, 2, "Identifier"]])
},
{
code: unIndent`
var foo = function(aaa,
bbb, ccc, ddd,
eee, fff) {
bar();
}
`,
output: unIndent`
var foo = function(aaa,
bbb, ccc, ddd,
eee, fff) {
bar();
}
`,
options: [4, { FunctionExpression: { parameters: "first", body: 1 } }],
errors: expectedErrors([[2, 19, 2, "Identifier"], [3, 19, 24, "Identifier"], [4, 4, 8, "Identifier"]])
},
{
code: unIndent`
var foo = function(
aaa, bbb, ccc,
ddd, eee) {
bar();
}
`,
output: unIndent`
var foo = function(
aaa, bbb, ccc,
ddd, eee) {
bar();
}
`,
options: [2, { FunctionExpression: { parameters: "first", body: 3 } }],
errors: expectedErrors([[2, 2, 0, "Identifier"], [3, 2, 4, "Identifier"], [4, 6, 2, "Identifier"]])
},
{
code: unIndent`
var foo = bar;
\t\t\tvar baz = qux;
`,
output: unIndent`
var foo = bar;
var baz = qux;
`,
options: [2],
errors: expectedErrors([2, "0 spaces", "3 tabs", "Keyword"])
},
{
code: unIndent`
function foo() {
\tbar();
baz();
qux();
}
`,
output: unIndent`
function foo() {
\tbar();
\tbaz();
\tqux();
}
`,
options: ["tab"],
errors: expectedErrors("tab", [[3, "1 tab", "2 spaces", "Identifier"], [4, "1 tab", "14 spaces", "Identifier"]])
},
{
code: unIndent`
function foo() {
bar();
\t\t}
`,
output: unIndent`
function foo() {
bar();
}
`,
options: [2],
errors: expectedErrors([[3, "0 spaces", "2 tabs", "Punctuator"]])
},
{
code: unIndent`
function foo() {
function bar() {
baz();
}
}
`,
output: unIndent`
function foo() {
function bar() {
baz();
}
}
`,
options: [2, { FunctionDeclaration: { body: 1 } }],
errors: expectedErrors([3, 4, 8, "Identifier"])
},
{
code: unIndent`
function foo() {
function bar(baz,
qux) {
foobar();
}
}
`,
output: unIndent`
function foo() {
function bar(baz,
qux) {
foobar();
}
}
`,
options: [2, { FunctionDeclaration: { body: 1, parameters: 2 } }],
errors: expectedErrors([3, 6, 4, "Identifier"])
},
{
code: unIndent`
function foo() {
var bar = function(baz,
qux) {
foobar();
};
}
`,
output: unIndent`
function foo() {
var bar = function(baz,
qux) {
foobar();
};
}
`,
options: [2, { FunctionExpression: { parameters: 3 } }],
errors: expectedErrors([3, 8, 10, "Identifier"])
},
{
code: unIndent`
foo.bar(
baz, qux, function() {
qux;
}
);
`,
output: unIndent`
foo.bar(
baz, qux, function() {
qux;
}
);
`,
options: [2, { FunctionExpression: { body: 3 }, CallExpression: { arguments: 3 } }],
errors: expectedErrors([3, 12, 8, "Identifier"])
},
{
code: unIndent`
{
try {
}
catch (err) {
}
finally {
}
}
`,
output: unIndent`
{
try {
}
catch (err) {
}
finally {
}
}
`,
errors: expectedErrors([
[4, 4, 0, "Keyword"],
[6, 4, 0, "Keyword"]
])
},
{
code: unIndent`
{
do {
}
while (true)
}
`,
output: unIndent`
{
do {
}
while (true)
}
`,
errors: expectedErrors([4, 4, 0, "Keyword"])
},
{
code: unIndent`
function foo() {
return (
1
)
}
`,
output: unIndent`
function foo() {
return (
1
)
}
`,
options: [2],
errors: expectedErrors([[4, 2, 4, "Punctuator"]])
},
{
code: unIndent`
function foo() {
return (
1
);
}
`,
output: unIndent`
function foo() {
return (
1
);
}
`,
options: [2],
errors: expectedErrors([[4, 2, 4, "Punctuator"]])
},
{
code: unIndent`
function test(){
switch(length){
case 1: return function(a){
return fn.call(that, a);
};
}
}
`,
output: unIndent`
function test(){
switch(length){
case 1: return function(a){
return fn.call(that, a);
};
}
}
`,
options: [2, { VariableDeclarator: 2, SwitchCase: 1 }],
errors: expectedErrors([[4, 6, 4, "Keyword"]])
},
{
code: unIndent`
function foo() {
return 1
}
`,
output: unIndent`
function foo() {
return 1
}
`,
options: [2],
errors: expectedErrors([[2, 2, 3, "Keyword"]])
},
{
code: unIndent`
foo(
bar,
baz,
qux);
`,
output: unIndent`
foo(
bar,
baz,
qux);
`,
options: [2, { CallExpression: { arguments: 1 } }],
errors: expectedErrors([[2, 2, 0, "Identifier"], [4, 2, 4, "Identifier"]])
},
{
code: unIndent`
foo(
\tbar,
\tbaz);
`,
output: unIndent`
foo(
bar,
baz);
`,
options: [2, { CallExpression: { arguments: 2 } }],
errors: expectedErrors([[2, "4 spaces", "1 tab", "Identifier"], [3, "4 spaces", "1 tab", "Identifier"]])
},
{
code: unIndent`
foo(bar,
\t\tbaz,
\t\tqux);
`,
output: unIndent`
foo(bar,
\tbaz,
\tqux);
`,
options: ["tab", { CallExpression: { arguments: 1 } }],
errors: expectedErrors("tab", [[2, 1, 2, "Identifier"], [3, 1, 2, "Identifier"]])
},
{
code: unIndent`
foo(bar, baz,
qux);
`,
output: unIndent`
foo(bar, baz,
qux);
`,
options: [2, { CallExpression: { arguments: "first" } }],
errors: expectedErrors([2, 4, 9, "Identifier"])
},
{
code: unIndent`
foo(
bar,
baz);
`,
output: unIndent`
foo(
bar,
baz);
`,
options: [2, { CallExpression: { arguments: "first" } }],
errors: expectedErrors([[2, 2, 10, "Identifier"], [3, 2, 4, "Identifier"]])
},
{
code: unIndent`
foo(bar,
1 + 2,
!baz,
new Car('!')
);
`,
output: unIndent`
foo(bar,
1 + 2,
!baz,
new Car('!')
);
`,
options: [2, { CallExpression: { arguments: 3 } }],
errors: expectedErrors([[2, 6, 2, "Numeric"], [3, 6, 14, "Punctuator"], [4, 6, 8, "Keyword"]])
},
// https://github.com/eslint/eslint/issues/7573
{
code: unIndent`
return (
foo
);
`,
output: unIndent`
return (
foo
);
`,
parserOptions: { ecmaFeatures: { globalReturn: true } },
errors: expectedErrors([3, 0, 4, "Punctuator"])
},
{
code: unIndent`
return (
foo
)
`,
output: unIndent`
return (
foo
)
`,
parserOptions: { ecmaFeatures: { globalReturn: true } },
errors: expectedErrors([3, 0, 4, "Punctuator"])
},
// https://github.com/eslint/eslint/issues/7604
{
code: unIndent`
if (foo) {
/* comment */bar();
}
`,
output: unIndent`
if (foo) {
/* comment */bar();
}
`,
errors: expectedErrors([2, 4, 8, "Block"])
},
{
code: unIndent`
foo('bar',
/** comment */{
ok: true
});
`,
output: unIndent`
foo('bar',
/** comment */{
ok: true
});
`,
errors: expectedErrors([2, 4, 8, "Block"])
},
{
code: unIndent`
foo(
(bar)
);
`,
output: unIndent`
foo(
(bar)
);
`,
options: [4, { CallExpression: { arguments: 1 } }],
errors: expectedErrors([2, 4, 0, "Punctuator"])
},
{
code: unIndent`
((
foo
))
`,
output: unIndent`
((
foo
))
`,
options: [4],
errors: expectedErrors([2, 4, 0, "Identifier"])
},
// ternary expressions (https://github.com/eslint/eslint/issues/7420)
{
code: unIndent`
foo
? bar
: baz
`,
output: unIndent`
foo
? bar
: baz
`,
options: [2],
errors: expectedErrors([[2, 2, 0, "Punctuator"], [3, 2, 4, "Punctuator"]])
},
{
code: unIndent`
[
foo ?
bar :
baz,
qux
]
`,
output: unIndent`
[
foo ?
bar :
baz,
qux
]
`,
errors: expectedErrors([5, 4, 8, "Identifier"])
},
{
code: unIndent`
condition
? () => {
return true
}
: condition2
? () => {
return true
}
: () => {
return false
}
`,
output: unIndent`
condition
? () => {
return true
}
: condition2
? () => {
return true
}
: () => {
return false
}
`,
options: [2, { offsetTernaryExpressions: true }],
errors: expectedErrors([
[2, 2, 0, "Punctuator"],
[3, 6, 0, "Keyword"],
[4, 4, 0, "Punctuator"],
[5, 2, 0, "Punctuator"],
[6, 4, 0, "Punctuator"],
[7, 8, 0, "Keyword"],
[8, 6, 0, "Punctuator"],
[9, 4, 0, "Punctuator"],
[10, 8, 0, "Keyword"],
[11, 6, 0, "Punctuator"]
])
},
{
code: unIndent`
condition
? () => {
return true
}
: condition2
? () => {
return true
}
: () => {
return false
}
`,
output: unIndent`
condition
? () => {
return true
}
: condition2
? () => {
return true
}
: () => {
return false
}
`,
options: [2, { offsetTernaryExpressions: false }],
errors: expectedErrors([
[2, 2, 0, "Punctuator"],
[3, 4, 0, "Keyword"],
[4, 2, 0, "Punctuator"],
[5, 2, 0, "Punctuator"],
[6, 4, 0, "Punctuator"],
[7, 6, 0, "Keyword"],
[8, 4, 0, "Punctuator"],
[9, 4, 0, "Punctuator"],
[10, 6, 0, "Keyword"],
[11, 4, 0, "Punctuator"]
])
},
{
/*
* Checking comments:
* https://github.com/eslint/eslint/issues/6571
*/
code: unIndent`
foo();
// comment
/* multiline
comment */
bar();
// trailing comment
`,
output: unIndent`
foo();
// comment
/* multiline
comment */
bar();
// trailing comment
`,
options: [2],
errors: expectedErrors([[2, 0, 2, "Line"], [3, 0, 4, "Block"], [6, 0, 1, "Line"]])
},
{
code: " // comment",
output: "// comment",
errors: expectedErrors([1, 0, 2, "Line"])
},
{
code: unIndent`
foo
// comment
`,
output: unIndent`
foo
// comment
`,
errors: expectedErrors([2, 0, 2, "Line"])
},
{
code: unIndent`
// comment
foo
`,
output: unIndent`
// comment
foo
`,
errors: expectedErrors([1, 0, 2, "Line"])
},
{
code: unIndent`
[
// no elements
]
`,
output: unIndent`
[
// no elements
]
`,
errors: expectedErrors([2, 4, 8, "Line"])
},
{
/*
* Destructuring assignments:
* https://github.com/eslint/eslint/issues/6813
*/
code: unIndent`
var {
foo,
bar,
baz: qux,
foobar: baz = foobar
} = qux;
`,
output: unIndent`
var {
foo,
bar,
baz: qux,
foobar: baz = foobar
} = qux;
`,
options: [2],
errors: expectedErrors([[2, 2, 0, "Identifier"], [4, 2, 4, "Identifier"], [5, 2, 6, "Identifier"], [6, 0, 2, "Punctuator"]])
},
{
code: unIndent`
const {
a
} = {
a: 1
}
`,
output: unIndent`
const {
a
} = {
a: 1
}
`,
options: [2],
errors: expectedErrors([[4, 2, 4, "Identifier"], [5, 0, 2, "Punctuator"]])
},
{
code: unIndent`
var foo = [
bar,
baz
]
`,
output: unIndent`
var foo = [
bar,
baz
]
`,
errors: expectedErrors([[2, 4, 11, "Identifier"], [3, 4, 2, "Identifier"], [4, 0, 10, "Punctuator"]])
},
{
code: unIndent`
var foo = [bar,
baz,
qux
]
`,
output: unIndent`
var foo = [bar,
baz,
qux
]
`,
errors: expectedErrors([2, 4, 0, "Identifier"])
},
{
code: unIndent`
var foo = [bar,
baz,
qux
]
`,
output: unIndent`
var foo = [bar,
baz,
qux
]
`,
options: [2, { ArrayExpression: 0 }],
errors: expectedErrors([[2, 0, 2, "Identifier"], [3, 0, 2, "Identifier"]])
},
{
code: unIndent`
var foo = [bar,
baz,
qux
]
`,
output: unIndent`
var foo = [bar,
baz,
qux
]
`,
options: [2, { ArrayExpression: 8 }],
errors: expectedErrors([[2, 16, 2, "Identifier"], [3, 16, 2, "Identifier"]])
},
{
code: unIndent`
var foo = [bar,
baz,
qux
]
`,
output: unIndent`
var foo = [bar,
baz,
qux
]
`,
options: [2, { ArrayExpression: "first" }],
errors: expectedErrors([[2, 11, 4, "Identifier"], [3, 11, 4, "Identifier"]])
},
{
code: unIndent`
var foo = [bar,
baz, qux
]
`,
output: unIndent`
var foo = [bar,
baz, qux
]
`,
options: [2, { ArrayExpression: "first" }],
errors: expectedErrors([2, 11, 4, "Identifier"])
},
{
code: unIndent`
var foo = [
{ bar: 1,
baz: 2 },
{ bar: 3,
qux: 4 }
]
`,
output: unIndent`
var foo = [
{ bar: 1,
baz: 2 },
{ bar: 3,
qux: 4 }
]
`,
options: [4, { ArrayExpression: 2, ObjectExpression: "first" }],
errors: expectedErrors([[3, 10, 12, "Identifier"], [5, 10, 12, "Identifier"]])
},
{
code: unIndent`
var foo = {
bar: 1,
baz: 2
};
`,
output: unIndent`
var foo = {
bar: 1,
baz: 2
};
`,
options: [2, { ObjectExpression: 0 }],
errors: expectedErrors([[2, 0, 2, "Identifier"], [3, 0, 2, "Identifier"]])
},
{
code: unIndent`
var quux = { foo: 1, bar: 2,
baz: 3 }
`,
output: unIndent`
var quux = { foo: 1, bar: 2,
baz: 3 }
`,
options: [2, { ObjectExpression: "first" }],
errors: expectedErrors([2, 13, 0, "Identifier"])
},
{
code: unIndent`
function foo() {
[
foo
]
}
`,
output: unIndent`
function foo() {
[
foo
]
}
`,
options: [2, { ArrayExpression: 4 }],
errors: expectedErrors([[2, 2, 4, "Punctuator"], [3, 10, 12, "Identifier"], [4, 2, 4, "Punctuator"]])
},
{
code: unIndent`
var [
foo,
bar,
baz,
foobar = baz
] = qux;
`,
output: unIndent`
var [
foo,
bar,
baz,
foobar = baz
] = qux;
`,
options: [2],
errors: expectedErrors([[2, 2, 0, "Identifier"], [4, 2, 4, "Identifier"], [5, 2, 6, "Identifier"], [6, 0, 2, "Punctuator"]])
},
{
code: unIndent`
import {
foo,
bar,
baz
} from 'qux';
`,
output: unIndent`
import {
foo,
bar,
baz
} from 'qux';
`,
parserOptions: { ecmaVersion: 6, sourceType: "module" },
errors: expectedErrors([[2, 4, 0, "Identifier"], [3, 4, 2, "Identifier"]])
},
{
code: unIndent`
import { foo,
bar,
baz,
} from 'qux';
`,
output: unIndent`
import { foo,
bar,
baz,
} from 'qux';
`,
options: [4, { ImportDeclaration: "first" }],
parserOptions: { ecmaVersion: 6, sourceType: "module" },
errors: expectedErrors([[3, 9, 10, "Identifier"]])
},
{
code: unIndent`
import { foo,
bar,
baz,
} from 'qux';
`,
output: unIndent`
import { foo,
bar,
baz,
} from 'qux';
`,
options: [2, { ImportDeclaration: 2 }],
parserOptions: { ecmaVersion: 6, sourceType: "module" },
errors: expectedErrors([[3, 4, 5, "Identifier"]])
},
{
code: unIndent`
var foo = 0, bar = 0, baz = 0;
export {
foo,
bar,
baz
};
`,
output: unIndent`
var foo = 0, bar = 0, baz = 0;
export {
foo,
bar,
baz
};
`,
parserOptions: { ecmaVersion: 6, sourceType: "module" },
errors: expectedErrors([[3, 4, 0, "Identifier"], [4, 4, 2, "Identifier"]])
},
{
code: unIndent`
var foo = 0, bar = 0, baz = 0;
export {
foo,
bar,
baz
} from 'qux';
`,
output: unIndent`
var foo = 0, bar = 0, baz = 0;
export {
foo,
bar,
baz
} from 'qux';
`,
parserOptions: { ecmaVersion: 6, sourceType: "module" },
errors: expectedErrors([[3, 4, 0, "Identifier"], [4, 4, 2, "Identifier"]])
},
{
// https://github.com/eslint/eslint/issues/7233
code: unIndent`
var folder = filePath
.foo()
.bar;
`,
output: unIndent`
var folder = filePath
.foo()
.bar;
`,
options: [2, { MemberExpression: 2 }],
errors: expectedErrors([[2, 4, 2, "Punctuator"], [3, 4, 6, "Punctuator"]])
},
{
code: unIndent`
for (const foo of bar)
baz();
`,
output: unIndent`
for (const foo of bar)
baz();
`,
options: [2],
errors: expectedErrors([2, 2, 4, "Identifier"])
},
{
code: unIndent`
var x = () =>
5;
`,
output: unIndent`
var x = () =>
5;
`,
options: [2],
errors: expectedErrors([2, 2, 4, "Numeric"])
},
{
// BinaryExpressions with parens
code: unIndent`
foo && (
bar
)
`,
output: unIndent`
foo && (
bar
)
`,
options: [4],
errors: expectedErrors([2, 4, 8, "Identifier"])
},
{
code: unIndent`
foo &&
!bar(
)
`,
output: unIndent`
foo &&
!bar(
)
`,
errors: expectedErrors([3, 4, 0, "Punctuator"])
},
{
code: unIndent`
foo &&
![].map(() => {
bar();
})
`,
output: unIndent`
foo &&
![].map(() => {
bar();
})
`,
errors: expectedErrors([[3, 8, 4, "Identifier"], [4, 4, 0, "Punctuator"]])
},
{
code: unIndent`
[
] || [
]
`,
output: unIndent`
[
] || [
]
`,
errors: expectedErrors([3, 0, 4, "Punctuator"])
},
{
code: unIndent`
foo
|| (
bar
)
`,
output: unIndent`
foo
|| (
bar
)
`,
errors: expectedErrors([[3, 12, 16, "Identifier"], [4, 8, 12, "Punctuator"]])
},
{
code: unIndent`
1
+ (
1
)
`,
output: unIndent`
1
+ (
1
)
`,
errors: expectedErrors([[3, 4, 8, "Numeric"], [4, 0, 4, "Punctuator"]])
},
// Template curlies
{
code: unIndent`
\`foo\${
bar}\`
`,
output: unIndent`
\`foo\${
bar}\`
`,
options: [2],
errors: expectedErrors([2, 2, 0, "Identifier"])
},
{
code: unIndent`
\`foo\${
\`bar\${
baz}\`}\`
`,
output: unIndent`
\`foo\${
\`bar\${
baz}\`}\`
`,
options: [2],
errors: expectedErrors([[2, 2, 4, "Template"], [3, 4, 0, "Identifier"]])
},
{
code: unIndent`
\`foo\${
\`bar\${
baz
}\`
}\`
`,
output: unIndent`
\`foo\${
\`bar\${
baz
}\`
}\`
`,
options: [2],
errors: expectedErrors([[2, 2, 4, "Template"], [3, 4, 2, "Identifier"], [4, 2, 4, "Template"], [5, 0, 2, "Template"]])
},
{
code: unIndent`
\`foo\${
(
bar
)
}\`
`,
output: unIndent`
\`foo\${
(
bar
)
}\`
`,
options: [2],
errors: expectedErrors([[2, 2, 0, "Punctuator"], [3, 4, 2, "Identifier"], [4, 2, 0, "Punctuator"]])
},
{
code: unIndent`
function foo() {
\`foo\${bar}baz\${
qux}foo\${
bar}baz\`
}
`,
output: unIndent`
function foo() {
\`foo\${bar}baz\${
qux}foo\${
bar}baz\`
}
`,
errors: expectedErrors([[3, 8, 0, "Identifier"], [4, 8, 2, "Identifier"]])
},
{
code: unIndent`
function foo() {
const template = \`the indentation of
a curly element in a \${
node.type
} node is checked.\`;
}
`,
output: unIndent`
function foo() {
const template = \`the indentation of
a curly element in a \${
node.type
} node is checked.\`;
}
`,
errors: expectedErrors([[4, 4, 8, "Identifier"], [5, 0, 4, "Template"]])
},
{
code: unIndent`
function foo() {
const template = \`this time the
closing curly is at the end of the line \${
foo}
so the spaces before this line aren't removed.\`;
}
`,
output: unIndent`
function foo() {
const template = \`this time the
closing curly is at the end of the line \${
foo}
so the spaces before this line aren't removed.\`;
}
`,
errors: expectedErrors([4, 4, 12, "Identifier"])
},
{
/*
* https://github.com/eslint/eslint/issues/1801
* Note: This issue also mentioned checking the indentation for the 2 below. However,
* this is intentionally ignored because everyone seems to have a different idea of how
* BinaryExpressions should be indented.
*/
code: unIndent`
if (true) {
a = (
1 +
2);
}
`,
output: unIndent`
if (true) {
a = (
1 +
2);
}
`,
errors: expectedErrors([3, 8, 0, "Numeric"])
},
{
// https://github.com/eslint/eslint/issues/3737
code: unIndent`
if (true) {
for (;;) {
b();
}
}
`,
output: unIndent`
if (true) {
for (;;) {
b();
}
}
`,
options: [2],
errors: expectedErrors([[2, 2, 4, "Keyword"], [3, 4, 6, "Identifier"]])
},
{
// https://github.com/eslint/eslint/issues/6670
code: unIndent`
function f() {
return asyncCall()
.then(
'some string',
[
1,
2,
3
]
);
}
`,
output: unIndent`
function f() {
return asyncCall()
.then(
'some string',
[
1,
2,
3
]
);
}
`,
options: [4, { MemberExpression: 1, CallExpression: { arguments: 1 } }],
errors: expectedErrors([
[3, 8, 4, "Punctuator"],
[4, 12, 15, "String"],
[5, 12, 14, "Punctuator"],
[6, 16, 14, "Numeric"],
[7, 16, 9, "Numeric"],
[8, 16, 35, "Numeric"],
[9, 12, 22, "Punctuator"],
[10, 8, 0, "Punctuator"],
[11, 0, 1, "Punctuator"]
])
},
// https://github.com/eslint/eslint/issues/7242
{
code: unIndent`
var x = [
[1],
[2]
]
`,
output: unIndent`
var x = [
[1],
[2]
]
`,
errors: expectedErrors([[2, 4, 6, "Punctuator"], [3, 4, 2, "Punctuator"]])
},
{
code: unIndent`
var y = [
{a: 1},
{b: 2}
]
`,
output: unIndent`
var y = [
{a: 1},
{b: 2}
]
`,
errors: expectedErrors([[2, 4, 6, "Punctuator"], [3, 4, 2, "Punctuator"]])
},
{
code: unIndent`
echo = spawn('cmd.exe',
['foo', 'bar',
'baz']);
`,
output: unIndent`
echo = spawn('cmd.exe',
['foo', 'bar',
'baz']);
`,
options: [2, { ArrayExpression: "first", CallExpression: { arguments: "first" } }],
errors: expectedErrors([[2, 13, 12, "Punctuator"], [3, 14, 13, "String"]])
},
{
// https://github.com/eslint/eslint/issues/7522
code: unIndent`
foo(
)
`,
output: unIndent`
foo(
)
`,
errors: expectedErrors([2, 0, 2, "Punctuator"])
},
{
// https://github.com/eslint/eslint/issues/7616
code: unIndent`
foo(
bar,
{
baz: 1
}
)
`,
output: unIndent`
foo(
bar,
{
baz: 1
}
)
`,
options: [4, { CallExpression: { arguments: "first" } }],
errors: expectedErrors([[2, 4, 8, "Identifier"]])
},
{
code: " new Foo",
output: "new Foo",
errors: expectedErrors([1, 0, 2, "Keyword"])
},
{
code: unIndent`
var foo = 0, bar = 0, baz = 0;
export {
foo,
bar,
baz
}
`,
output: unIndent`
var foo = 0, bar = 0, baz = 0;
export {
foo,
bar,
baz
}
`,
parserOptions: { ecmaVersion: 6, sourceType: "module" },
errors: expectedErrors([[3, 4, 0, "Identifier"], [4, 4, 8, "Identifier"], [5, 4, 2, "Identifier"]])
},
{
code: unIndent`
foo
? bar
: baz
`,
output: unIndent`
foo
? bar
: baz
`,
options: [4, { flatTernaryExpressions: true }],
errors: expectedErrors([3, 4, 0, "Punctuator"])
},
{
code: unIndent`
foo ?
bar :
baz
`,
output: unIndent`
foo ?
bar :
baz
`,
options: [4, { flatTernaryExpressions: true }],
errors: expectedErrors([3, 4, 0, "Identifier"])
},
{
code: unIndent`
foo ?
bar
: baz
`,
output: unIndent`
foo ?
bar
: baz
`,
options: [4, { flatTernaryExpressions: true }],
errors: expectedErrors([3, 4, 2, "Punctuator"])
},
{
code: unIndent`
foo
? bar :
baz
`,
output: unIndent`
foo
? bar :
baz
`,
options: [4, { flatTernaryExpressions: true }],
errors: expectedErrors([3, 4, 0, "Identifier"])
},
{
code: unIndent`
foo ? bar
: baz ? qux
: foobar ? boop
: beep
`,
output: unIndent`
foo ? bar
: baz ? qux
: foobar ? boop
: beep
`,
options: [4, { flatTernaryExpressions: true }],
errors: expectedErrors([
[3, 4, 8, "Punctuator"],
[4, 4, 12, "Punctuator"]
])
},
{
code: unIndent`
foo ? bar :
baz ? qux :
foobar ? boop :
beep
`,
output: unIndent`
foo ? bar :
baz ? qux :
foobar ? boop :
beep
`,
options: [4, { flatTernaryExpressions: true }],
errors: expectedErrors([
[3, 4, 8, "Identifier"],
[4, 4, 12, "Identifier"]
])
},
{
code: unIndent`
var a =
foo ? bar :
baz ? qux :
foobar ? boop :
/*else*/ beep
`,
output: unIndent`
var a =
foo ? bar :
baz ? qux :
foobar ? boop :
/*else*/ beep
`,
options: [4, { flatTernaryExpressions: true }],
errors: expectedErrors([
[3, 4, 6, "Identifier"],
[4, 4, 2, "Identifier"]
])
},
{
code: unIndent`
var a =
foo
? bar
: baz
`,
output: unIndent`
var a =
foo
? bar
: baz
`,
options: [4, { flatTernaryExpressions: true }],
errors: expectedErrors([
[3, 8, 4, "Punctuator"],
[4, 8, 4, "Punctuator"]
])
},
{
code: unIndent`
foo ? bar
: baz ? qux
: foobar ? boop
: beep
`,
output: unIndent`
foo ? bar
: baz ? qux
: foobar ? boop
: beep
`,
options: [4, { flatTernaryExpressions: false }],
errors: expectedErrors([
[3, 8, 4, "Punctuator"],
[4, 12, 4, "Punctuator"]
])
},
{
code: unIndent`
foo ? bar :
baz ? qux :
foobar ? boop :
beep
`,
output: unIndent`
foo ? bar :
baz ? qux :
foobar ? boop :
beep
`,
options: [4, { flatTernaryExpressions: false }],
errors: expectedErrors([
[3, 8, 4, "Identifier"],
[4, 12, 4, "Identifier"]
])
},
{
code: unIndent`
foo
? bar
: baz
? qux
: foobar
? boop
: beep
`,
output: unIndent`
foo
? bar
: baz
? qux
: foobar
? boop
: beep
`,
options: [4, { flatTernaryExpressions: false }],
errors: expectedErrors([
[4, 8, 4, "Punctuator"],
[5, 8, 4, "Punctuator"],
[6, 12, 4, "Punctuator"],
[7, 12, 4, "Punctuator"]
])
},
{
code: unIndent`
foo ?
bar :
baz ?
qux :
foobar ?
boop :
beep
`,
output: unIndent`
foo ?
bar :
baz ?
qux :
foobar ?
boop :
beep
`,
options: [4, { flatTernaryExpressions: false }],
errors: expectedErrors([
[4, 8, 4, "Identifier"],
[5, 8, 4, "Identifier"],
[6, 12, 4, "Identifier"],
[7, 12, 4, "Identifier"]
])
},
{
code: unIndent`
foo.bar('baz', function(err) {
qux;
});
`,
output: unIndent`
foo.bar('baz', function(err) {
qux;
});
`,
options: [2, { CallExpression: { arguments: "first" } }],
errors: expectedErrors([2, 2, 10, "Identifier"])
},
{
code: unIndent`
foo.bar(function() {
cookies;
}).baz(function() {
cookies;
});
`,
output: unIndent`
foo.bar(function() {
cookies;
}).baz(function() {
cookies;
});
`,
options: [2, { MemberExpression: 1 }],
errors: expectedErrors([[4, 2, 4, "Identifier"], [5, 0, 2, "Punctuator"]])
},
{
code: unIndent`
foo.bar().baz(function() {
cookies;
}).qux(function() {
cookies;
});
`,
output: unIndent`
foo.bar().baz(function() {
cookies;
}).qux(function() {
cookies;
});
`,
options: [2, { MemberExpression: 1 }],
errors: expectedErrors([[4, 2, 4, "Identifier"], [5, 0, 2, "Punctuator"]])
},
{
code: unIndent`
[ foo,
bar ].forEach(function() {
baz;
})
`,
output: unIndent`
[ foo,
bar ].forEach(function() {
baz;
})
`,
options: [2, { ArrayExpression: "first", MemberExpression: 1 }],
errors: expectedErrors([[3, 2, 4, "Identifier"], [4, 0, 2, "Punctuator"]])
},
{
code: unIndent`
foo[
bar
];
`,
output: unIndent`
foo[
bar
];
`,
options: [4, { MemberExpression: 1 }],
errors: expectedErrors([3, 0, 4, "Punctuator"])
},
{
code: unIndent`
foo({
bar: 1,
baz: 2
})
`,
output: unIndent`
foo({
bar: 1,
baz: 2
})
`,
options: [4, { ObjectExpression: "first" }],
errors: expectedErrors([[2, 4, 0, "Identifier"], [3, 4, 0, "Identifier"]])
},
{
code: unIndent`
foo(
bar, baz,
qux);
`,
output: unIndent`
foo(
bar, baz,
qux);
`,
options: [2, { CallExpression: { arguments: "first" } }],
errors: expectedErrors([[2, 2, 24, "Identifier"], [3, 2, 24, "Identifier"]])
},
{
code: unIndent`
if (foo) bar()
; [1, 2, 3].map(baz)
`,
output: unIndent`
if (foo) bar()
; [1, 2, 3].map(baz)
`,
errors: expectedErrors([3, 0, 4, "Punctuator"])
},
{
code: unIndent`
if (foo)
;
`,
output: unIndent`
if (foo)
;
`,
errors: expectedErrors([2, 4, 0, "Punctuator"])
},
{
code: unIndent`
import {foo}
from 'bar';
`,
output: unIndent`
import {foo}
from 'bar';
`,
parserOptions: { ecmaVersion: 6, sourceType: "module" },
errors: expectedErrors([2, 4, 0, "Identifier"])
},
{
code: unIndent`
export {foo}
from 'bar';
`,
output: unIndent`
export {foo}
from 'bar';
`,
parserOptions: { ecmaVersion: 6, sourceType: "module" },
errors: expectedErrors([2, 4, 0, "Identifier"])
},
{
code: unIndent`
(
a
) => b => {
c
}
`,
output: unIndent`
(
a
) => b => {
c
}
`,
errors: expectedErrors([[4, 4, 8, "Identifier"], [5, 0, 4, "Punctuator"]])
},
{
code: unIndent`
(
a
) => b => c => d => {
e
}
`,
output: unIndent`
(
a
) => b => c => d => {
e
}
`,
errors: expectedErrors([[4, 4, 8, "Identifier"], [5, 0, 4, "Punctuator"]])
},
{
code: unIndent`
if (
foo
) bar(
baz
);
`,
output: unIndent`
if (
foo
) bar(
baz
);
`,
errors: expectedErrors([[4, 4, 8, "Identifier"], [5, 0, 4, "Punctuator"]])
},
{
code: unIndent`
(
foo
)(
bar
)
`,
output: unIndent`
(
foo
)(
bar
)
`,
errors: expectedErrors([[4, 4, 8, "Identifier"], [5, 0, 4, "Punctuator"]])
},
{
code: unIndent`
(() =>
foo
)(
bar
)
`,
output: unIndent`
(() =>
foo
)(
bar
)
`,
errors: expectedErrors([[4, 4, 8, "Identifier"], [5, 0, 4, "Punctuator"]])
},
{
code: unIndent`
(() => {
foo();
})(
bar
)
`,
output: unIndent`
(() => {
foo();
})(
bar
)
`,
errors: expectedErrors([[4, 4, 8, "Identifier"], [5, 0, 4, "Punctuator"]])
},
{
code: unIndent`
foo.
bar.
baz
`,
output: unIndent`
foo.
bar.
baz
`,
errors: expectedErrors([[2, 4, 2, "Identifier"], [3, 4, 6, "Identifier"]])
},
{
code: unIndent`
const foo = a.b(),
longName
= (baz(
'bar',
'bar'
));
`,
output: unIndent`
const foo = a.b(),
longName
= (baz(
'bar',
'bar'
));
`,
errors: expectedErrors([[4, 8, 12, "String"], [5, 8, 12, "String"], [6, 4, 8, "Punctuator"]])
},
{
code: unIndent`
const foo = a.b(),
longName =
(baz(
'bar',
'bar'
));
`,
output: unIndent`
const foo = a.b(),
longName =
(baz(
'bar',
'bar'
));
`,
errors: expectedErrors([[4, 8, 12, "String"], [5, 8, 12, "String"], [6, 4, 8, "Punctuator"]])
},
{
code: unIndent`
const foo = a.b(),
longName
=baz(
'bar',
'bar'
);
`,
output: unIndent`
const foo = a.b(),
longName
=baz(
'bar',
'bar'
);
`,
errors: expectedErrors([[6, 8, 4, "Punctuator"]])
},
{
code: unIndent`
const foo = a.b(),
longName
=(
'fff'
);
`,
output: unIndent`
const foo = a.b(),
longName
=(
'fff'
);
`,
errors: expectedErrors([[4, 12, 8, "String"]])
},
//----------------------------------------------------------------------
// Ignore Unknown Nodes
//----------------------------------------------------------------------
{
code: unIndent`
namespace Foo {
const bar = 3,
baz = 2;
if (true) {
const bax = 3;
}
}
`,
output: unIndent`
namespace Foo {
const bar = 3,
baz = 2;
if (true) {
const bax = 3;
}
}
`,
parser: parser("unknown-nodes/namespace-invalid"),
errors: expectedErrors([[3, 8, 4, "Identifier"], [6, 8, 4, "Keyword"]])
},
{
code: unIndent`
abstract class Foo {
public bar() {
let aaa = 4,
boo;
if (true) {
boo = 3;
}
boo = 3 + 2;
}
}
`,
output: unIndent`
abstract class Foo {
public bar() {
let aaa = 4,
boo;
if (true) {
boo = 3;
}
boo = 3 + 2;
}
}
`,
parser: parser("unknown-nodes/abstract-class-invalid"),
errors: expectedErrors([[4, 12, 8, "Identifier"], [7, 12, 8, "Identifier"], [10, 8, 4, "Identifier"]])
},
{
code: unIndent`
function foo() {
function bar() {
abstract class X {
public baz() {
if (true) {
qux();
}
}
}
}
}
`,
output: unIndent`
function foo() {
function bar() {
abstract class X {
public baz() {
if (true) {
qux();
}
}
}
}
}
`,
parser: parser("unknown-nodes/functions-with-abstract-class-invalid"),
errors: expectedErrors([
[4, 12, 8, "Keyword"],
[5, 16, 8, "Keyword"],
[6, 20, 8, "Identifier"],
[7, 16, 8, "Punctuator"],
[8, 12, 8, "Punctuator"]
])
},
{
code: unIndent`
namespace Unknown {
function foo() {
function bar() {
abstract class X {
public baz() {
if (true) {
qux();
}
}
}
}
}
}
`,
output: unIndent`
namespace Unknown {
function foo() {
function bar() {
abstract class X {
public baz() {
if (true) {
qux();
}
}
}
}
}
}
`,
parser: parser("unknown-nodes/namespace-with-functions-with-abstract-class-invalid"),
errors: expectedErrors([
[3, 8, 4, "Keyword"],
[7, 24, 20, "Identifier"]
])
},
//----------------------------------------------------------------------
// JSX tests
// Some of the following tests are adapted from the tests in eslint-plugin-react.
// License: https://github.com/yannickcr/eslint-plugin-react/blob/7ca9841f22d599f447a27ef5b2a97def9229d6c8/LICENSE
//----------------------------------------------------------------------
{
code: unIndent`
<App>
<Foo />
</App>
`,
output: unIndent`
<App>
<Foo />
</App>
`,
errors: expectedErrors([2, 4, 2, "Punctuator"])
},
{
code: unIndent`
<App>
<Foo />
</App>
`,
output: unIndent`
<App>
<Foo />
</App>
`,
options: [2],
errors: expectedErrors([2, 2, 4, "Punctuator"])
},
{
code: unIndent`
<App>
<Foo />
</App>
`,
output: unIndent`
<App>
\t<Foo />
</App>
`,
options: ["tab"],
errors: expectedErrors([2, "1 tab", "4 spaces", "Punctuator"])
},
{
code: unIndent`
function App() {
return <App>
<Foo />
</App>;
}
`,
output: unIndent`
function App() {
return <App>
<Foo />
</App>;
}
`,
options: [2],
errors: expectedErrors([4, 2, 9, "Punctuator"])
},
{
code: unIndent`
function App() {
return (<App>
<Foo />
</App>);
}
`,
output: unIndent`
function App() {
return (<App>
<Foo />
</App>);
}
`,
options: [2],
errors: expectedErrors([4, 2, 4, "Punctuator"])
},
{
code: unIndent`
function App() {
return (
<App>
<Foo />
</App>
);
}
`,
output: unIndent`
function App() {
return (
<App>
<Foo />
</App>
);
}
`,
options: [2],
errors: expectedErrors([[3, 4, 0, "Punctuator"], [4, 6, 2, "Punctuator"], [5, 4, 0, "Punctuator"]])
},
{
code: unIndent`
<App>
{test}
</App>
`,
output: unIndent`
<App>
{test}
</App>
`,
errors: expectedErrors([2, 4, 1, "Punctuator"])
},
{
code: unIndent`
<App>
{options.map((option, index) => (
<option key={index} value={option.key}>
{option.name}
</option>
))}
</App>
`,
output: unIndent`
<App>
{options.map((option, index) => (
<option key={index} value={option.key}>
{option.name}
</option>
))}
</App>
`,
errors: expectedErrors([4, 12, 11, "Punctuator"])
},
{
code: unIndent`
[
<div />,
<div />
]
`,
output: unIndent`
[
<div />,
<div />
]
`,
options: [2],
errors: expectedErrors([3, 2, 4, "Punctuator"])
},
{
code: unIndent`
<App>
<Foo />
</App>
`,
output: unIndent`
<App>
\t<Foo />
</App>
`,
options: ["tab"],
errors: expectedErrors([3, "1 tab", "1 space", "Punctuator"])
},
{
/*
* Multiline ternary
* (colon at the end of the first expression)
*/
code: unIndent`
foo ?
<Foo /> :
<Bar />
`,
output: unIndent`
foo ?
<Foo /> :
<Bar />
`,
errors: expectedErrors([3, 4, 0, "Punctuator"])
},
{
/*
* Multiline ternary
* (colon on its own line)
*/
code: unIndent`
foo ?
<Foo />
:
<Bar />
`,
output: unIndent`
foo ?
<Foo />
:
<Bar />
`,
errors: expectedErrors([[3, 4, 0, "Punctuator"], [4, 4, 0, "Punctuator"]])
},
{
/*
* Multiline ternary
* (colon at the end of the first expression, parenthesized first expression)
*/
code: unIndent`
foo ? (
<Foo />
) :
<Bar />
`,
output: unIndent`
foo ? (
<Foo />
) :
<Bar />
`,
errors: expectedErrors([4, 4, 0, "Punctuator"])
},
{
code: unIndent`
<App
foo
/>
`,
output: unIndent`
<App
foo
/>
`,
errors: expectedErrors([2, 4, 2, "JSXIdentifier"])
},
{
code: unIndent`
<App
foo
/>
`,
output: unIndent`
<App
foo
/>
`,
options: [2],
errors: expectedErrors([3, 0, 2, "Punctuator"])
},
{
code: unIndent`
<App
foo
></App>
`,
output: unIndent`
<App
foo
></App>
`,
options: [2],
errors: expectedErrors([3, 0, 2, "Punctuator"])
},
{
code: unIndent`
const Button = function(props) {
return (
<Button
size={size}
onClick={onClick}
>
Button Text
</Button>
);
};
`,
output: unIndent`
const Button = function(props) {
return (
<Button
size={size}
onClick={onClick}
>
Button Text
</Button>
);
};
`,
options: [2],
errors: expectedErrors([6, 4, 36, "Punctuator"])
},
{
code: unIndent`
var x = function() {
return <App
foo
/>
}
`,
output: unIndent`
var x = function() {
return <App
foo
/>
}
`,
options: [2],
errors: expectedErrors([4, 2, 9, "Punctuator"])
},
{
code: unIndent`
var x = <App
foo
/>
`,
output: unIndent`
var x = <App
foo
/>
`,
options: [2],
errors: expectedErrors([3, 0, 8, "Punctuator"])
},
{
code: unIndent`
var x = (
<Something
/>
)
`,
output: unIndent`
var x = (
<Something
/>
)
`,
options: [2],
errors: expectedErrors([3, 2, 4, "Punctuator"])
},
{
code: unIndent`
<App
\tfoo
\t/>
`,
output: unIndent`
<App
\tfoo
/>
`,
options: ["tab"],
errors: expectedErrors("tab", [3, 0, 1, "Punctuator"])
},
{
code: unIndent`
<App
\tfoo
\t></App>
`,
output: unIndent`
<App
\tfoo
></App>
`,
options: ["tab"],
errors: expectedErrors("tab", [3, 0, 1, "Punctuator"])
},
{
code: unIndent`
<
foo
.bar
.baz
>
foo
</
foo.
bar.
baz
>
`,
output: unIndent`
<
foo
.bar
.baz
>
foo
</
foo.
bar.
baz
>
`,
errors: expectedErrors([
[3, 8, 4, "Punctuator"],
[4, 8, 4, "Punctuator"],
[9, 8, 4, "JSXIdentifier"],
[10, 8, 4, "JSXIdentifier"]
])
},
{
code: unIndent`
<
input
type=
"number"
/>
`,
output: unIndent`
<
input
type=
"number"
/>
`,
errors: expectedErrors([4, 8, 4, "JSXText"])
},
{
code: unIndent`
<
input
type=
{'number'}
/>
`,
output: unIndent`
<
input
type=
{'number'}
/>
`,
errors: expectedErrors([4, 8, 4, "Punctuator"])
},
{
code: unIndent`
<
input
type
="number"
/>
`,
output: unIndent`
<
input
type
="number"
/>
`,
errors: expectedErrors([4, 8, 4, "Punctuator"])
},
{
code: unIndent`
foo ? (
bar
) : (
baz
)
`,
output: unIndent`
foo ? (
bar
) : (
baz
)
`,
errors: expectedErrors([[4, 4, 8, "Identifier"], [5, 0, 4, "Punctuator"]])
},
{
code: unIndent`
foo ? (
<div>
</div>
) : (
<span>
</span>
)
`,
output: unIndent`
foo ? (
<div>
</div>
) : (
<span>
</span>
)
`,
errors: expectedErrors([[5, 4, 8, "Punctuator"], [6, 4, 8, "Punctuator"], [7, 0, 4, "Punctuator"]])
},
{
code: unIndent`
<div>
{
(
1
)
}
</div>
`,
output: unIndent`
<div>
{
(
1
)
}
</div>
`,
errors: expectedErrors([[3, 8, 4, "Punctuator"], [4, 12, 8, "Numeric"], [5, 8, 4, "Punctuator"]])
},
{
code: unIndent`
<div>
{
/* foo */
}
</div>
`,
output: unIndent`
<div>
{
/* foo */
}
</div>
`,
errors: expectedErrors([3, 8, 6, "Block"])
},
{
code: unIndent`
<div
{...props}
/>
`,
output: unIndent`
<div
{...props}
/>
`,
errors: expectedErrors([2, 4, 0, "Punctuator"])
},
{
code: unIndent`
<div
{
...props
}
/>
`,
output: unIndent`
<div
{
...props
}
/>
`,
errors: expectedErrors([3, 8, 6, "Punctuator"])
},
{
code: unIndent`
<div>foo
<div>bar</div>
</div>
`,
output: unIndent`
<div>foo
<div>bar</div>
</div>
`,
errors: expectedErrors([2, 4, 0, "Punctuator"])
},
{
code: unIndent`
<small>Foo bar
<a>baz qux</a>.
</small>
`,
output: unIndent`
<small>Foo bar
<a>baz qux</a>.
</small>
`,
errors: expectedErrors([2, 4, 0, "Punctuator"])
},
/*
* JSX Fragments
* https://github.com/eslint/eslint/issues/12208
*/
{
code: unIndent`
<>
<A />
</>
`,
output: unIndent`
<>
<A />
</>
`,
errors: expectedErrors([2, 4, 0, "Punctuator"])
},
{
code: unIndent`
<
>
<A />
</>
`,
output: unIndent`
<
>
<A />
</>
`,
errors: expectedErrors([2, 0, 4, "Punctuator"])
},
{
code: unIndent`
<>
<A />
<
/>
`,
output: unIndent`
<>
<A />
<
/>
`,
errors: expectedErrors([4, 0, 4, "Punctuator"])
},
{
code: unIndent`
<>
<A />
</
>
`,
output: unIndent`
<>
<A />
</
>
`,
errors: expectedErrors([4, 0, 4, "Punctuator"])
},
{
code: unIndent`
<
>
<A />
</
>
`,
output: unIndent`
<
>
<A />
</
>
`,
errors: expectedErrors([
[2, 0, 4, "Punctuator"],
[5, 0, 4, "Punctuator"]
])
},
{
code: unIndent`
<
>
<A />
<
/>
`,
output: unIndent`
<
>
<A />
<
/>
`,
errors: expectedErrors([
[2, 0, 4, "Punctuator"],
[5, 0, 4, "Punctuator"]
])
},
{
code: unIndent`
< // Comment
>
<A />
</>
`,
output: unIndent`
< // Comment
>
<A />
</>
`,
errors: expectedErrors([2, 0, 4, "Punctuator"])
},
{
code: unIndent`
<>
<A />
< // Comment
/>
`,
output: unIndent`
<>
<A />
< // Comment
/>
`,
errors: expectedErrors([4, 0, 4, "Punctuator"])
},
{
code: unIndent`
<>
<A />
</ // Comment
>
`,
output: unIndent`
<>
<A />
</ // Comment
>
`,
errors: expectedErrors([4, 0, 4, "Punctuator"])
},
{
code: unIndent`
< /* Comment */
>
<A />
</>
`,
output: unIndent`
< /* Comment */
>
<A />
</>
`,
errors: expectedErrors([2, 0, 4, "Punctuator"])
},
{
code: unIndent`
<>
<A />
< /* Comment */
/>
`,
output: unIndent`
<>
<A />
< /* Comment */
/>
`,
errors: expectedErrors([4, 0, 4, "Punctuator"])
},
{
code: unIndent`
<>
<A />
</ /* Comment */
>
`,
output: unIndent`
<>
<A />
</ /* Comment */
>
`,
errors: expectedErrors([4, 0, 4, "Punctuator"])
},
{
code: unIndent`
({
foo
}: bar) => baz
`,
output: unIndent`
({
foo
}: bar) => baz
`,
parser: require.resolve("../../fixtures/parsers/babel-eslint7/object-pattern-with-annotation"),
errors: expectedErrors([3, 0, 4, "Punctuator"])
},
{
code: unIndent`
([
foo
]: bar) => baz
`,
output: unIndent`
([
foo
]: bar) => baz
`,
parser: require.resolve("../../fixtures/parsers/babel-eslint7/array-pattern-with-annotation"),
errors: expectedErrors([3, 0, 4, "Punctuator"])
},
{
code: unIndent`
({
foo
}: {}) => baz
`,
output: unIndent`
({
foo
}: {}) => baz
`,
parser: require.resolve("../../fixtures/parsers/babel-eslint7/object-pattern-with-object-annotation"),
errors: expectedErrors([3, 0, 4, "Punctuator"])
},
{
code: unIndent`
class Foo {
foo() {
bar();
}
}
`,
output: unIndent`
class Foo {
foo() {
bar();
}
}
`,
options: [4, { ignoredNodes: ["ClassBody"] }],
errors: expectedErrors([3, 4, 0, "Identifier"])
},
{
code: unIndent`
$(function() {
foo();
bar();
foo(function() {
baz();
});
});
`,
output: unIndent`
$(function() {
foo();
bar();
foo(function() {
baz();
});
});
`,
options: [4, {
ignoredNodes: ["ExpressionStatement > CallExpression[callee.name='$'] > FunctionExpression > BlockStatement"]
}],
errors: expectedErrors([7, 4, 0, "Identifier"])
},
{
code: unIndent`
(function($) {
$(function() {
foo;
});
})()
`,
output: unIndent`
(function($) {
$(function() {
foo;
});
})()
`,
options: [4, {
ignoredNodes: ["ExpressionStatement > CallExpression > FunctionExpression.callee > BlockStatement"]
}],
errors: expectedErrors([3, 4, 0, "Identifier"])
},
{
code: unIndent`
if (foo) {
doSomething();
// Intentionally unindented comment
doSomethingElse();
}
`,
output: unIndent`
if (foo) {
doSomething();
// Intentionally unindented comment
doSomethingElse();
}
`,
options: [4, { ignoreComments: false }],
errors: expectedErrors([4, 4, 0, "Line"])
},
{
code: unIndent`
if (foo) {
doSomething();
/* Intentionally unindented comment */
doSomethingElse();
}
`,
output: unIndent`
if (foo) {
doSomething();
/* Intentionally unindented comment */
doSomethingElse();
}
`,
options: [4, { ignoreComments: false }],
errors: expectedErrors([4, 4, 0, "Block"])
},
{
code: unIndent`
const obj = {
foo () {
return condition ? // comment
1 :
2
}
}
`,
output: unIndent`
const obj = {
foo () {
return condition ? // comment
1 :
2
}
}
`,
errors: expectedErrors([4, 12, 8, "Numeric"])
},
//----------------------------------------------------------------------
// Comment alignment tests
//----------------------------------------------------------------------
{
code: unIndent`
if (foo) {
// Comment cannot align with code immediately above if there is a whitespace gap
doSomething();
}
`,
output: unIndent`
if (foo) {
// Comment cannot align with code immediately above if there is a whitespace gap
doSomething();
}
`,
errors: expectedErrors([3, 4, 0, "Line"])
},
{
code: unIndent`
if (foo) {
foo(
bar);
// Comment cannot align with code immediately below if there is a whitespace gap
}
`,
output: unIndent`
if (foo) {
foo(
bar);
// Comment cannot align with code immediately below if there is a whitespace gap
}
`,
errors: expectedErrors([4, 4, 0, "Line"])
},
{
code: unIndent`
[{
foo
},
// Comment between nodes
{
bar
}];
`,
output: unIndent`
[{
foo
},
// Comment between nodes
{
bar
}];
`,
errors: expectedErrors([5, 0, 4, "Line"])
},
{
code: unIndent`
let foo
// comment
;(async () => {})()
`,
output: unIndent`
let foo
// comment
;(async () => {})()
`,
errors: expectedErrors([3, 0, 4, "Line"])
},
{
code: unIndent`
let foo
// comment
;(async () => {})()
`,
output: unIndent`
let foo
// comment
;(async () => {})()
`,
errors: expectedErrors([2, 0, 4, "Line"])
},
{
code: unIndent`
let foo
/* comment */;
(async () => {})()
`,
output: unIndent`
let foo
/* comment */;
(async () => {})()
`,
errors: expectedErrors([3, 4, 0, "Block"])
},
{
code: unIndent`
// comment
;(async () => {})()
`,
output: unIndent`
// comment
;(async () => {})()
`,
errors: expectedErrors([1, 0, 4, "Line"])
},
{
code: unIndent`
// comment
;(async () => {})()
`,
output: unIndent`
// comment
;(async () => {})()
`,
errors: expectedErrors([1, 0, 4, "Line"])
},
{
code: unIndent`
{
let foo
// comment
;(async () => {})()
}
`,
output: unIndent`
{
let foo
// comment
;(async () => {})()
}
`,
errors: expectedErrors([4, 4, 8, "Line"])
},
{
code: unIndent`
{
let foo
// comment
;(async () => {})()
}
`,
output: unIndent`
{
let foo
// comment
;(async () => {})()
}
`,
errors: expectedErrors([3, 4, 8, "Line"])
},
{
code: unIndent`
{
let foo
/* comment */;
(async () => {})()
}
`,
output: unIndent`
{
let foo
/* comment */;
(async () => {})()
}
`,
errors: expectedErrors([4, 8, 4, "Block"])
},
{
code: unIndent`
const foo = 1
const bar = foo
/* comment */
;[1, 2, 3].forEach(() => {})
`,
output: unIndent`
const foo = 1
const bar = foo
/* comment */
;[1, 2, 3].forEach(() => {})
`,
errors: expectedErrors([4, 0, 4, "Block"])
},
{
code: unIndent`
const foo = 1
const bar = foo
/* comment */
;[1, 2, 3].forEach(() => {})
`,
output: unIndent`
const foo = 1
const bar = foo
/* comment */
;[1, 2, 3].forEach(() => {})
`,
errors: expectedErrors([3, 0, 4, "Block"])
},
{
code: unIndent`
const foo = 1
const bar = foo
/* comment */;
[1, 2, 3].forEach(() => {})
`,
output: unIndent`
const foo = 1
const bar = foo
/* comment */;
[1, 2, 3].forEach(() => {})
`,
errors: expectedErrors([4, 4, 0, "Block"])
},
{
code: unIndent`
/* comment */
;[1, 2, 3].forEach(() => {})
`,
output: unIndent`
/* comment */
;[1, 2, 3].forEach(() => {})
`,
errors: expectedErrors([1, 0, 4, "Block"])
},
{
code: unIndent`
/* comment */
;[1, 2, 3].forEach(() => {})
`,
output: unIndent`
/* comment */
;[1, 2, 3].forEach(() => {})
`,
errors: expectedErrors([1, 0, 4, "Block"])
},
{
code: unIndent`
{
const foo = 1
const bar = foo
/* comment */
;[1, 2, 3].forEach(() => {})
}
`,
output: unIndent`
{
const foo = 1
const bar = foo
/* comment */
;[1, 2, 3].forEach(() => {})
}
`,
errors: expectedErrors([5, 4, 8, "Block"])
},
{
code: unIndent`
{
const foo = 1
const bar = foo
/* comment */
;[1, 2, 3].forEach(() => {})
}
`,
output: unIndent`
{
const foo = 1
const bar = foo
/* comment */
;[1, 2, 3].forEach(() => {})
}
`,
errors: expectedErrors([4, 4, 8, "Block"])
},
{
code: unIndent`
{
const foo = 1
const bar = foo
/* comment */;
[1, 2, 3].forEach(() => {})
}
`,
output: unIndent`
{
const foo = 1
const bar = foo
/* comment */;
[1, 2, 3].forEach(() => {})
}
`,
errors: expectedErrors([5, 8, 4, "Block"])
},
// import expressions
{
code: unIndent`
import(
source
)
`,
output: unIndent`
import(
source
)
`,
parserOptions: { ecmaVersion: 2020 },
errors: expectedErrors([
[2, 4, 0, "Identifier"],
[3, 0, 4, "Punctuator"]
])
},
// https://github.com/eslint/eslint/issues/12122
{
code: unIndent`
foo(() => {
tag\`
multiline
template\${a} \${b}
literal
\`(() => {
bar();
});
});
`,
output: unIndent`
foo(() => {
tag\`
multiline
template\${a} \${b}
literal
\`(() => {
bar();
});
});
`,
parserOptions: { ecmaVersion: 2015 },
errors: expectedErrors([
[7, 8, 4, "Identifier"]
])
},
{
code: unIndent`
{
tag\`
multiline
template
literal
\${a} \${b}\`(() => {
bar();
});
}
`,
output: unIndent`
{
tag\`
multiline
template
literal
\${a} \${b}\`(() => {
bar();
});
}
`,
parserOptions: { ecmaVersion: 2015 },
errors: expectedErrors([
[2, 4, 8, "Identifier"],
[7, 8, 12, "Identifier"],
[8, 4, 8, "Punctuator"]
])
},
{
code: unIndent`
foo(() => {
tagOne\`\${a} \${b}
multiline
template
literal
\`(() => {
tagTwo\`
multiline
template
literal
\`(() => {
bar();
});
baz();
});
});
`,
output: unIndent`
foo(() => {
tagOne\`\${a} \${b}
multiline
template
literal
\`(() => {
tagTwo\`
multiline
template
literal
\`(() => {
bar();
});
baz();
});
});
`,
parserOptions: { ecmaVersion: 2015 },
errors: expectedErrors([
[7, 8, 12, "Identifier"],
[15, 8, 12, "Identifier"],
[16, 4, 0, "Punctuator"]
])
},
{
code: unIndent`
{
tagOne\`
multiline
template
literal
\${a} \${b}\`(() => {
tagTwo\`
multiline
template
literal
\`(() => {
bar();
});
baz();
});
}
`,
output: unIndent`
{
tagOne\`
multiline
template
literal
\${a} \${b}\`(() => {
tagTwo\`
multiline
template
literal
\`(() => {
bar();
});
baz();
});
}
`,
parserOptions: { ecmaVersion: 2015 },
errors: expectedErrors([
[7, 8, 12, "Identifier"],
[15, 8, 12, "Identifier"],
[16, 4, 0, "Punctuator"]
])
},
{
code: unIndent`
tagOne\`multiline \${a} \${b}
template
literal
\`(() => {
foo();
tagTwo\`multiline
template
literal
\`({
bar: 1,
baz: 2
});
});
`,
output: unIndent`
tagOne\`multiline \${a} \${b}
template
literal
\`(() => {
foo();
tagTwo\`multiline
template
literal
\`({
bar: 1,
baz: 2
});
});
`,
parserOptions: { ecmaVersion: 2015 },
errors: expectedErrors([
[5, 4, 0, "Identifier"],
[11, 8, 4, "Identifier"]
])
},
{
code: unIndent`
tagOne\`multiline
template \${a} \${b}
literal\`({
foo: 1,
bar: tagTwo\`multiline
template
literal\`(() => {
baz();
})
});
`,
output: unIndent`
tagOne\`multiline
template \${a} \${b}
literal\`({
foo: 1,
bar: tagTwo\`multiline
template
literal\`(() => {
baz();
})
});
`,
parserOptions: { ecmaVersion: 2015 },
errors: expectedErrors([
[4, 4, 8, "Identifier"],
[5, 4, 0, "Identifier"],
[9, 8, 0, "Identifier"]
])
},
{
code: unIndent`
foo.bar\` template literal \`(() => {
baz();
})
`,
output: unIndent`
foo.bar\` template literal \`(() => {
baz();
})
`,
parserOptions: { ecmaVersion: 2015 },
errors: expectedErrors([
[2, 4, 8, "Identifier"]
])
},
{
code: unIndent`
foo.bar.baz\` template literal \`(() => {
baz();
})
`,
output: unIndent`
foo.bar.baz\` template literal \`(() => {
baz();
})
`,
parserOptions: { ecmaVersion: 2015 },
errors: expectedErrors([
[2, 4, 0, "Identifier"],
[3, 0, 4, "Punctuator"]
])
},
{
code: unIndent`
foo
.bar\` template
literal \`(() => {
baz();
})
`,
output: unIndent`
foo
.bar\` template
literal \`(() => {
baz();
})
`,
parserOptions: { ecmaVersion: 2015 },
errors: expectedErrors([
[5, 4, 0, "Punctuator"]
])
},
{
code: unIndent`
foo
.test\`
\${a} \${b}
\`(() => {
bar();
})
`,
output: unIndent`
foo
.test\`
\${a} \${b}
\`(() => {
bar();
})
`,
parserOptions: { ecmaVersion: 2015 },
errors: expectedErrors([
[5, 8, 0, "Identifier"]
])
},
{
code: unIndent`
foo
.test\`
\${a} \${b}
\`(() => {
bar();
})
`,
output: unIndent`
foo
.test\`
\${a} \${b}
\`(() => {
bar();
})
`,
options: [4, { MemberExpression: 0 }],
parserOptions: { ecmaVersion: 2015 },
errors: expectedErrors([
[2, 0, 4, "Punctuator"],
[5, 4, 0, "Identifier"],
[6, 0, 4, "Punctuator"]
])
},
// Optional chaining
{
code: unIndent`
obj
?.prop
?.[key]
?.
[key]
`,
output: unIndent`
obj
?.prop
?.[key]
?.
[key]
`,
options: [4],
parserOptions: { ecmaVersion: 2020 },
errors: expectedErrors([
[2, 4, 0, "Punctuator"],
[3, 4, 0, "Punctuator"],
[4, 4, 0, "Punctuator"],
[5, 8, 0, "Punctuator"]
])
},
{
code: unIndent`
(
longSomething
?.prop
?.[key]
)
?.prop
?.[key]
`,
output: unIndent`
(
longSomething
?.prop
?.[key]
)
?.prop
?.[key]
`,
options: [4],
parserOptions: { ecmaVersion: 2020 },
errors: expectedErrors([
[6, 4, 0, "Punctuator"],
[7, 4, 0, "Punctuator"]
])
},
{
code: unIndent`
obj
?.(arg)
?.
(arg)
`,
output: unIndent`
obj
?.(arg)
?.
(arg)
`,
options: [4],
parserOptions: { ecmaVersion: 2020 },
errors: expectedErrors([
[2, 4, 0, "Punctuator"],
[3, 4, 0, "Punctuator"],
[4, 4, 0, "Punctuator"]
])
},
{
code: unIndent`
(
longSomething
?.(arg)
?.(arg)
)
?.(arg)
?.(arg)
`,
output: unIndent`
(
longSomething
?.(arg)
?.(arg)
)
?.(arg)
?.(arg)
`,
options: [4],
parserOptions: { ecmaVersion: 2020 },
errors: expectedErrors([
[6, 4, 0, "Punctuator"],
[7, 4, 0, "Punctuator"]
])
},
{
code: unIndent`
const foo = async (arg1,
arg2) =>
{
return arg1 + arg2;
}
`,
output: unIndent`
const foo = async (arg1,
arg2) =>
{
return arg1 + arg2;
}
`,
options: [2, { FunctionDeclaration: { parameters: "first" }, FunctionExpression: { parameters: "first" } }],
parserOptions: { ecmaVersion: 2020 },
errors: expectedErrors([
[2, 19, 20, "Identifier"]
])
},
{
code: unIndent`
const a = async
b => {}
`,
output: unIndent`
const a = async
b => {}
`,
options: [2],
errors: expectedErrors([
[2, 0, 1, "Identifier"]
])
},
{
code: unIndent`
class C {
field1;
static field2;
}
`,
output: unIndent`
class C {
field1;
static field2;
}
`,
options: [4],
parserOptions: { ecmaVersion: 2022 },
errors: expectedErrors([
[2, 4, 0, "Identifier"],
[3, 4, 0, "Keyword"]
])
},
{
code: unIndent`
class C {
field1
=
0
;
static
field2
=
0
;
}
`,
output: unIndent`
class C {
field1
=
0
;
static
field2
=
0
;
}
`,
options: [4],
parserOptions: { ecmaVersion: 2022 },
errors: expectedErrors([
[2, 4, 0, "Identifier"],
[3, 8, 0, "Punctuator"],
[4, 12, 0, "Numeric"],
[5, 12, 0, "Punctuator"],
[6, 4, 0, "Keyword"],
[7, 8, 0, "Identifier"],
[8, 12, 0, "Punctuator"],
[9, 16, 0, "Numeric"],
[10, 16, 0, "Punctuator"]
])
},
{
code: unIndent`
class C {
[
field1
]
=
0
;
static
[
field2
]
=
0
;
[
field3
] =
0;
[field4] =
0;
}
`,
output: unIndent`
class C {
[
field1
]
=
0
;
static
[
field2
]
=
0
;
[
field3
] =
0;
[field4] =
0;
}
`,
options: [4],
parserOptions: { ecmaVersion: 2022 },
errors: expectedErrors([
[2, 4, 0, "Punctuator"],
[3, 8, 0, "Identifier"],
[4, 4, 0, "Punctuator"],
[5, 8, 0, "Punctuator"],
[6, 12, 0, "Numeric"],
[7, 12, 0, "Punctuator"],
[8, 4, 0, "Keyword"],
[9, 4, 0, "Punctuator"],
[10, 8, 0, "Identifier"],
[11, 4, 0, "Punctuator"],
[12, 8, 0, "Punctuator"],
[13, 12, 0, "Numeric"],
[14, 12, 0, "Punctuator"],
[15, 4, 0, "Punctuator"],
[16, 8, 0, "Identifier"],
[17, 4, 0, "Punctuator"],
[18, 8, 0, "Numeric"],
[19, 4, 0, "Punctuator"],
[20, 8, 0, "Numeric"]
])
},
{
code: unIndent`
class C {
field1 = (
foo
+ bar
);
}
`,
output: unIndent`
class C {
field1 = (
foo
+ bar
);
}
`,
options: [4],
parserOptions: { ecmaVersion: 2022 },
errors: expectedErrors([
[2, 4, 0, "Identifier"],
[3, 8, 0, "Identifier"],
[5, 4, 0, "Punctuator"]
])
},
{
code: unIndent`
class C {
#aaa
foo() {
return this.#aaa
}
}
`,
output: unIndent`
class C {
#aaa
foo() {
return this.#aaa
}
}
`,
options: [4],
parserOptions: { ecmaVersion: 2022 },
errors: expectedErrors([
[2, 4, 0, "PrivateIdentifier"],
[3, 4, 0, "Identifier"],
[4, 8, 0, "Keyword"],
[5, 4, 0, "Punctuator"]
])
},
{
code: unIndent`
class C {
static {
foo();
bar();
}
}
`,
output: unIndent`
class C {
static {
foo();
bar();
}
}
`,
options: [2],
parserOptions: { ecmaVersion: 2022 },
errors: expectedErrors([
[2, 2, 0, "Keyword"],
[3, 4, 0, "Identifier"],
[4, 4, 0, "Identifier"],
[5, 2, 0, "Punctuator"]
])
},
{
code: unIndent`
class C {
static {
foo();
bar();
}
}
`,
output: unIndent`
class C {
static {
foo();
bar();
}
}
`,
options: [4],
parserOptions: { ecmaVersion: 2022 },
errors: expectedErrors([
[2, 4, 0, "Keyword"],
[3, 8, 0, "Identifier"],
[4, 8, 0, "Identifier"],
[5, 4, 0, "Punctuator"]
])
},
{
code: unIndent`
class C {
static {
foo();
bar();
}
}
`,
output: unIndent`
class C {
static {
foo();
bar();
}
}
`,
options: [4],
parserOptions: { ecmaVersion: 2022 },
errors: expectedErrors([
[2, 4, 8, "Keyword"],
[3, 8, 4, "Identifier"],
[4, 8, 0, "Identifier"],
[5, 4, 8, "Punctuator"]
])
},
{
code: unIndent`
class C {
static {
foo();
bar();
}
}
`,
output: unIndent`
class C {
static {
foo();
bar();
}
}
`,
options: [4, { StaticBlock: { body: 2 } }],
parserOptions: { ecmaVersion: 2022 },
errors: expectedErrors([
[2, 4, 0, "Keyword"],
[3, 12, 0, "Identifier"],
[4, 12, 0, "Identifier"],
[5, 4, 0, "Punctuator"]
])
},
{
code: unIndent`
class C {
static {
foo();
bar();
}
}
`,
output: unIndent`
class C {
static {
foo();
bar();
}
}
`,
options: [4, { StaticBlock: { body: 0 } }],
parserOptions: { ecmaVersion: 2022 },
errors: expectedErrors([
[2, 4, 0, "Keyword"],
[3, 4, 0, "Identifier"],
[4, 4, 0, "Identifier"],
[5, 4, 0, "Punctuator"]
])
},
{
code: unIndent`
class C {
static {
foo();
bar();
}
}
`,
output: unIndent`
class C {
\tstatic {
\t\tfoo();
\t\tbar();
\t}
}
`,
options: ["tab"],
parserOptions: { ecmaVersion: 2022 },
errors: expectedErrors("tab", [
[2, 1, 0, "Keyword"],
[3, 2, 0, "Identifier"],
[4, 2, 0, "Identifier"],
[5, 1, 0, "Punctuator"]
])
},
{
code: unIndent`
class C {
static {
foo();
bar();
}
}
`,
output: unIndent`
class C {
\tstatic {
\t\t\tfoo();
\t\t\tbar();
\t}
}
`,
options: ["tab", { StaticBlock: { body: 2 } }],
parserOptions: { ecmaVersion: 2022 },
errors: expectedErrors("tab", [
[2, 1, 0, "Keyword"],
[3, 3, 0, "Identifier"],
[4, 3, 0, "Identifier"],
[5, 1, 0, "Punctuator"]
])
},
{
code: unIndent`
class C {
static
{
foo();
bar();
}
}
`,
output: unIndent`
class C {
static
{
foo();
bar();
}
}
`,
options: [4],
parserOptions: { ecmaVersion: 2022 },
errors: expectedErrors([
[2, 4, 0, "Keyword"],
[3, 4, 0, "Punctuator"],
[4, 8, 0, "Identifier"],
[5, 8, 0, "Identifier"],
[6, 4, 0, "Punctuator"]
])
},
{
code: unIndent`
class C {
static
{
foo();
bar();
}
}
`,
output: unIndent`
class C {
static
{
foo();
bar();
}
}
`,
options: [4],
parserOptions: { ecmaVersion: 2022 },
errors: expectedErrors([
[3, 4, 8, "Punctuator"],
[6, 4, 8, "Punctuator"]
])
},
{
code: unIndent`
class C {
static {
var x,
y;
}
}
`,
output: unIndent`
class C {
static {
var x,
y;
}
}
`,
options: [4],
parserOptions: { ecmaVersion: 2022 },
errors: expectedErrors([
[2, 4, 0, "Keyword"],
[3, 8, 0, "Keyword"],
[4, 12, 0, "Identifier"],
[5, 4, 0, "Punctuator"]
])
},
{
code: unIndent`
class C {
static
{
var x,
y;
}
}
`,
output: unIndent`
class C {
static
{
var x,
y;
}
}
`,
options: [4],
parserOptions: { ecmaVersion: 2022 },
errors: expectedErrors([
[2, 4, 0, "Keyword"],
[3, 4, 0, "Punctuator"],
[4, 8, 0, "Keyword"],
[5, 12, 0, "Identifier"],
[6, 4, 0, "Punctuator"]
])
},
{
code: unIndent`
class C {
static {
if (foo) {
bar;
}
}
}
`,
output: unIndent`
class C {
static {
if (foo) {
bar;
}
}
}
`,
options: [4],
parserOptions: { ecmaVersion: 2022 },
errors: expectedErrors([
[2, 4, 0, "Keyword"],
[3, 8, 0, "Keyword"],
[4, 12, 0, "Identifier"],
[5, 8, 0, "Punctuator"],
[6, 4, 0, "Punctuator"]
])
},
{
code: unIndent`
class C {
static {
{
bar;
}
}
}
`,
output: unIndent`
class C {
static {
{
bar;
}
}
}
`,
options: [4],
parserOptions: { ecmaVersion: 2022 },
errors: expectedErrors([
[2, 4, 0, "Keyword"],
[3, 8, 0, "Punctuator"],
[4, 12, 0, "Identifier"],
[5, 8, 0, "Punctuator"],
[6, 4, 0, "Punctuator"]
])
},
{
code: unIndent`
class C {
static {}
static {
}
static
{
}
}
`,
output: unIndent`
class C {
static {}
static {
}
static
{
}
}
`,
options: [4],
parserOptions: { ecmaVersion: 2022 },
errors: expectedErrors([
[2, 4, 0, "Keyword"],
[4, 4, 0, "Keyword"],
[5, 4, 0, "Punctuator"],
[7, 4, 0, "Keyword"],
[8, 4, 0, "Punctuator"],
[9, 4, 0, "Punctuator"]
])
},
{
code: unIndent`
class C {
static {
foo;
}
static {
bar;
}
}
`,
output: unIndent`
class C {
static {
foo;
}
static {
bar;
}
}
`,
options: [4],
parserOptions: { ecmaVersion: 2022 },
errors: expectedErrors([
[3, 4, 0, "Keyword"],
[4, 8, 4, "Identifier"],
[5, 4, 0, "Punctuator"],
[7, 4, 0, "Keyword"],
[8, 8, 4, "Identifier"],
[9, 4, 0, "Punctuator"]
])
},
{
code: unIndent`
class C {
x = 1;
static {
foo;
}
y = 2;
}
`,
output: unIndent`
class C {
x = 1;
static {
foo;
}
y = 2;
}
`,
options: [4],
parserOptions: { ecmaVersion: 2022 },
errors: expectedErrors([
[3, 4, 0, "Identifier"],
[5, 4, 0, "Keyword"],
[6, 8, 4, "Identifier"],
[7, 4, 0, "Punctuator"],
[9, 4, 0, "Identifier"]
])
},
{
code: unIndent`
class C {
method1(param) {
foo;
}
static {
bar;
}
method2(param) {
foo;
}
}
`,
output: unIndent`
class C {
method1(param) {
foo;
}
static {
bar;
}
method2(param) {
foo;
}
}
`,
options: [4],
parserOptions: { ecmaVersion: 2022 },
errors: expectedErrors([
[3, 4, 0, "Identifier"],
[4, 8, 4, "Identifier"],
[5, 4, 0, "Punctuator"],
[7, 4, 0, "Keyword"],
[8, 8, 4, "Identifier"],
[9, 4, 0, "Punctuator"],
[11, 4, 0, "Identifier"],
[12, 8, 4, "Identifier"],
[13, 4, 0, "Punctuator"]
])
},
{
code: unIndent`
function f() {
class C {
static {
foo();
bar();
}
}
}
`,
output: unIndent`
function f() {
class C {
static {
foo();
bar();
}
}
}
`,
options: [4],
parserOptions: { ecmaVersion: 2022 },
errors: expectedErrors([
[2, 4, 0, "Keyword"],
[3, 8, 0, "Keyword"],
[4, 12, 0, "Identifier"],
[5, 12, 0, "Identifier"],
[6, 8, 0, "Punctuator"],
[7, 4, 0, "Punctuator"]
])
},
{
code: unIndent`
class C {
method() {
foo;
}
static {
bar;
}
}
`,
output: unIndent`
class C {
method() {
foo;
}
static {
bar;
}
}
`,
options: [4, { FunctionExpression: { body: 2 }, StaticBlock: { body: 2 } }],
parserOptions: { ecmaVersion: 2022 },
errors: expectedErrors([
[2, 4, 0, "Identifier"],
[3, 12, 0, "Identifier"],
[4, 4, 0, "Punctuator"],
[5, 4, 0, "Keyword"],
[6, 12, 0, "Identifier"],
[7, 4, 0, "Punctuator"]
])
}
]
});
|
app.service('programmingLandingService', function ($http) {
//get user profile information
this.getGymObj = function (gymId) {
return $http({
method: 'GET',
url: 'api/gyms/pathway/' + gymId,
})
.then(function (response) {
return response.data;
});
};
this.getStages = function (pathwayObj) {
return $http({
method: 'POST',
url: 'api/gyms/stage',
data: pathwayObj
})
.then(function (response) {
return response.data;
});
};
this.getEvals = function (stageObj) {
return $http({
method: 'POST',
url: 'api/gyms/evaluations',
data: stageObj
})
.then(function (response) {
return response.data;
});
};
this.getEvalDetails = function (evalObj) {
return $http({
method: 'POST',
url: '/api/gyms/evaluation/specifics',
data: evalObj
})
.then(function (response) {
return response.data;
});
};
this.addEvalObj = function (evalObj) {
return $http({
method: 'POST',
url: '/api/gyms/add/evaluation',
data: evalObj
})
.then(function (response) {
return response;
});
};
this.editEvaluation = function (evalObj) {
return $http({
method: 'PUT',
url: '/api/gyms/edit/evaluation',
data: evalObj
})
.then(function (response) {
return response.data;
});
};
this.deleteEval = function (evalObj) {
return $http({
method: 'PUT',
url: '/api/gyms/removeById',
data: evalObj
})
.then(function (response) {
return response;
});
};
});
|
define({
"add": "Κάντε κλικ για προσθήκη νέου",
"title": "Τίτλος",
"placeholderBookmarkName": "Όνομα σελιδοδείκτη",
"ok": "ΟΚ",
"cancel": "Ακύρωση",
"warning": "Ολοκληρώστε την επεξεργασία!",
"edit": "Επεξεργασία σελιδοδείκτη",
"errorNameExist": "Ο σελιδοδείκτης υπάρχει!",
"errorNameNull": "Μη έγκυρο όνομα σελιδοδείκτη!",
"addBookmark": "Δημιουργία νέου",
"thumbnail": "Μικρογραφία",
"thumbnailHint": "Κάντε κλικ στην εικόνα για ενημέρωση",
"displayBookmarksAs": "Παρουσίαση σελιδοδεικτών ως",
"cards": "Κάρτες",
"list": "Λίστα",
"cardsTips": "Προβολή σε κάρτες",
"listTips": "Προβολή σε λίστα",
"makeAsDefault": "Καθορισμός ως προεπιλεγμένης ρύθμισης",
"default": "Προεπιλεγμένη ρύθμιση",
"editable": "Να επιτρέπεται η προσθήκη σελιδοδεικτών στο widget.",
"alwaysSync": "Παρουσίαση σελιδοδεικτών από διαδικτυακό χάρτη",
"configCustom": "Παρουσίαση εξατομικευμένων σελιδοδεικτών",
"import": "Εισαγωγή",
"create": "Δημιουργία",
"importTitle": "Εισαγωγή σελιδοδεικτών",
"importFromWeb": "Εισαγωγή σελιδοδεικτών από τον τρέχοντα διαδικτυακό χάρτη",
"selectAll": "Επιλογή όλων",
"noBookmarkInConfig": "Για να προσθέσετε σελιδοδείκτες, κάντε κλικ στην επιλογή «Εισαγωγή» ή στην επιλογή «Δημιουργία νέου».",
"noBookmarkInWebMap": "Δεν έχει διαμορφωθεί κανένας σελιδοδείκτης στον χάρτη.",
"extent": "Έκταση",
"saveExtent": "Αποθήκευση έκτασης χάρτη στον σελιδοδείκτη",
"savelayers": "Αποθήκευση ορατότητας θεματικού επιπέδου",
"withVisibility": "Με ορατότητα θεματικών επιπέδων",
"bookmark": "Σελιδοδείκτης",
"addBtn": "Προσθήκη",
"deleteBtn": "Διαγραφή",
"editBtn": "Επεξεργασία",
"dragReorderTip": "Πιέστε παρατεταμένα και σύρετε για αναδιάταξη.",
"deleteBtnTip": "Διαγραφή του σελιδοδείκτη",
"editBtnTip": "Επεξεργασία του σελιδοδείκτη"
}); |
const DrawCard = require('../../drawcard.js');
class BrothersRobes extends DrawCard {
setupCardAbilities() {
this.attachmentRestriction({ trait: 'The Seven' });
this.reaction({
when: {
onCardKneeled: event => event.card === this.parent
},
target: {
activePrompTitle: 'Select a location or attachment',
cardCondition: card => card.location === 'play area' && ['location', 'attachment'].includes(card.getType())
},
handler: context => {
this.untilEndOfPhase(ability => ({
match: context.target,
effect: ability.effects.blankExcludingTraits
}));
this.game.addMessage('{0} uses {1} to treat the text box of {2} as blank until the end of the phase',
context.player, this, context.target);
}
});
}
}
BrothersRobes.code = '10043';
module.exports = BrothersRobes;
|
module.exports = {
tests: {
unit: ['test/unit/helpers/**/*.coffee', 'test/unit/**/*.coffee'],
integration: ['test/integration/**/*.coffee']
},
helpers: ['test/unit/helpers/**/*.coffee'],
lib: ['lib/**/*.js']
};
|
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.dialog.add( 'paste', function( editor )
{
var lang = editor.lang.clipboard;
var isCustomDomain = CKEDITOR.env.isCustomDomain();
function onPasteFrameLoad( win )
{
var doc = new CKEDITOR.dom.document( win.document ),
docElement = doc.$;
var script = doc.getById( 'cke_actscrpt' );
script && script.remove();
CKEDITOR.env.ie ?
docElement.body.contentEditable = "true" :
docElement.designMode = "on";
// IE before version 8 will leave cursor blinking inside the document after
// editor blurred unless we clean up the selection. (#4716)
if ( CKEDITOR.env.ie && CKEDITOR.env.version < 8 )
{
doc.getWindow().on( 'blur', function()
{
docElement.selection.empty();
} );
}
doc.on( "keydown", function( e )
{
var domEvent = e.data,
key = domEvent.getKeystroke(),
processed;
switch( key )
{
case 27 :
this.hide();
processed = 1;
break;
case 9 :
case CKEDITOR.SHIFT + 9 :
this.changeFocus( true );
processed = 1;
}
processed && domEvent.preventDefault();
}, this );
editor.fire( 'ariaWidget', new CKEDITOR.dom.element( win.frameElement ) );
}
return {
title : lang.title,
minWidth : CKEDITOR.env.ie && CKEDITOR.env.quirks ? 370 : 350,
minHeight : CKEDITOR.env.quirks ? 250 : 245,
onShow : function()
{
// FIREFOX BUG: Force the browser to render the dialog to make the to-be-
// inserted iframe editable. (#3366)
this.parts.dialog.$.offsetHeight;
this.setupContent();
},
onHide : function()
{
if ( CKEDITOR.env.ie )
this.getParentEditor().document.getBody().$.contentEditable = 'true';
},
onLoad : function()
{
if ( ( CKEDITOR.env.ie7Compat || CKEDITOR.env.ie6Compat ) && editor.lang.dir == 'rtl' )
this.parts.contents.setStyle( 'overflow', 'hidden' );
},
onOk : function()
{
this.commitContent();
},
contents : [
{
id : 'general',
label : editor.lang.common.generalTab,
elements : [
{
type : 'html',
id : 'securityMsg',
html : '<div style="white-space:normal;width:340px;">' + lang.securityMsg + '</div>'
},
{
type : 'html',
id : 'pasteMsg',
html : '<div style="white-space:normal;width:340px;">'+lang.pasteMsg +'</div>'
},
{
type : 'html',
id : 'editing_area',
style : 'width: 100%; height: 100%;',
html : '',
focus : function()
{
var win = this.getInputElement().$.contentWindow;
// #3291 : JAWS needs the 500ms delay to detect that the editor iframe
// iframe is no longer editable. So that it will put the focus into the
// Paste from Word dialog's editable area instead.
setTimeout( function()
{
win.focus();
}, 500 );
},
setup : function()
{
var dialog = this.getDialog();
var htmlToLoad =
'<html dir="' + editor.config.contentsLangDirection + '"' +
' lang="' + ( editor.config.contentsLanguage || editor.langCode ) + '">' +
'<head><style>body { margin: 3px; height: 95%; } </style></head><body>' +
'<script id="cke_actscrpt" type="text/javascript">' +
'window.parent.CKEDITOR.tools.callFunction( ' + CKEDITOR.tools.addFunction( onPasteFrameLoad, dialog ) + ', this );' +
'</script></body>' +
'</html>';
var src =
CKEDITOR.env.air ?
'javascript:void(0)' :
isCustomDomain ?
'javascript:void((function(){' +
'document.open();' +
'document.domain=\'' + document.domain + '\';' +
'document.close();' +
'})())"'
:
'';
var iframe = CKEDITOR.dom.element.createFromHtml(
'<iframe' +
' class="cke_pasteframe"' +
' frameborder="0" ' +
' allowTransparency="true"' +
' src="' + src + '"' +
' role="region"' +
' aria-label="' + lang.pasteArea + '"' +
' aria-describedby="' + dialog.getContentElement( 'general', 'pasteMsg' ).domId + '"' +
' aria-multiple="true"' +
'></iframe>' );
iframe.on( 'load', function( e )
{
e.removeListener();
var doc = iframe.getFrameDocument();
doc.write( htmlToLoad );
if ( CKEDITOR.env.air )
onPasteFrameLoad.call( this, doc.getWindow().$ );
}, dialog );
iframe.setCustomData( 'dialog', dialog );
var container = this.getElement();
container.setHtml( '' );
container.append( iframe );
// IE need a redirect on focus to make
// the cursor blinking inside iframe. (#5461)
if ( CKEDITOR.env.ie )
{
var focusGrabber = CKEDITOR.dom.element.createFromHtml( '<span tabindex="-1" style="position:absolute;" role="presentation"></span>' );
focusGrabber.on( 'focus', function()
{
iframe.$.contentWindow.focus();
});
container.append( focusGrabber );
// Override focus handler on field.
this.focus = function()
{
focusGrabber.focus();
this.fire( 'focus' );
};
}
this.getInputElement = function(){ return iframe; };
// Force container to scale in IE.
if ( CKEDITOR.env.ie )
{
container.setStyle( 'display', 'block' );
container.setStyle( 'height', ( iframe.$.offsetHeight + 2 ) + 'px' );
}
},
commit : function( data )
{
var container = this.getElement(),
editor = this.getDialog().getParentEditor(),
body = this.getInputElement().getFrameDocument().getBody(),
bogus = body.getBogus(),
html;
bogus && bogus.remove();
// Saving the contents so changes until paste is complete will not take place (#7500)
html = body.getHtml();
setTimeout( function(){
editor.fire( 'paste', { 'html' : html } );
}, 0 );
}
}
]
}
]
};
});
|
var Tape = function() {
var pos = 0, tape = [0];
this.inc = function() { tape[pos]++; }
this.dec = function() { tape[pos]--; }
this.advance = function() { pos++; if (tape.length <= pos) tape.push(0); }
this.devance = function() { if (pos > 0) pos--; }
this.get = function() { return tape[pos]; }
}
var Brainfuck = function(text) {
var me = this;
me.code = "";
me.bracket_map = function(text) {
var leftstack = [];
var bm = {};
for (var i = 0, pc = 0; i < text.length; i++) {
var c = text.charAt(i);
if ("+-<>[].,".indexOf(c) === -1) continue;
if (c === '[') leftstack.push(pc);
if (c === ']' && leftstack.length > 0) {
var left = leftstack.pop();
bm[left] = pc;
bm[pc] = left;
}
me.code += c;
pc++;
}
return bm;
}(text);
me.run = function() {
var pc = 0;
var tape = new Tape();
var code = this.code;
var bm = this.bracket_map;
for (var pc = 0; pc < code.length; pc++)
switch(code[pc]) {
case '+': tape.inc(); break;
case '-': tape.dec(); break;
case '>': tape.advance(); break;
case '<': tape.devance(); break;
case '[': if (tape.get() == 0) pc = bm[pc]; break;
case ']': if (tape.get() != 0) pc = bm[pc]; break;
case '.': process.stdout.write(String.fromCharCode(tape.get()));
default:
}
};
}
var text = require('fs').readFileSync(process.argv[2]).toString();
var brainfuck = new Brainfuck(text);
brainfuck.run();
|
var Image = require('./image');
var imageFields = ["fieldname", "originalname", "encoding", "mimetype", "destination",
"filename", "path", "size"];
module.exports = {
create: function (req, cb) {
var newImage = new Image();
//go through array fields which are the fields that are
//given from mutler and are part of the schema
for (var i = 0; i < imageFields.length; i++) {
newImage[imageFields[i]] = req.file[imageFields[i]];
};
newImage.save(function(err, image) {
if(err) {
req.flash('error', "Error Creating Image");
cb(err);
}
cb(null, image);
});
}, //close create
get: function (id, cb) {
Image.findById(id, function(err, image) {
if(err) {
cb(err);
}
if (!image) {
var error= new Error("Image not found");
error.type="image";
error.http_code = 404;
error.arguments ={id: id};
error.message="Image not found";
cb(error);
}
cb(null, image);
});
},
all: function (cb) {
Image.find(function(err, images) {
if(err) {
cb(err);
}
cb(null, images);
});
},
put: function (req, cb) {
Image.findById(req.params.id, function(err, image) {
if(err) {
cb(err);
}
//go through array fields which are the fields that are
//given from mutler and are part of the schema
for (var i = 0; i < imageFields.length; i++) {
newImage[imageFields[i]] = req.file[imageFields[i]];
};
image.save(function(err, image) {
if(err) {
cb(err);
}
cb(null,image);
});
});
},
delete: function (id, cb) {
Image.remove({
_id: id
}, function(err) {
if(err) {
cb(err);
}
});
}
} |
/**
* @desc notify()
* - http://notifyjs.com/ for examples / docs
*
* @param {Function} fn - the function to curry
* @param {Number} [len] - specifies the number of arguments needed to call the function
*
* @return {Function} - the curried function
*/
const url = '//rawgit.com/clearhead/clearhead/master/bower_components/notifyjs/dist/notify-combined.min.js';
let script = null;
function notify(...args) {
// only notify in debug mode
if (!/clearhead-debug=true/.test(document.cookie)) {
return;
}
// wait for jQuery
if (!window.jQuery) {
return setTimeout(notify.bind(this, ...args), 1000);
}
script = script || jQuery.getScript(url); // promise
script.done(function () {
jQuery.notify.call(jQuery, args.join(': '));
});
}
export default notify;
|
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"nt\u0254\u0301ng\u0254\u0301",
"mp\u00f3kwa"
],
"DAY": [
"eyenga",
"mok\u0254l\u0254 mwa yambo",
"mok\u0254l\u0254 mwa m\u00edbal\u00e9",
"mok\u0254l\u0254 mwa m\u00eds\u00e1to",
"mok\u0254l\u0254 ya m\u00edn\u00e9i",
"mok\u0254l\u0254 ya m\u00edt\u00e1no",
"mp\u0254\u0301s\u0254"
],
"FIRSTDAYOFWEEK": 0,
"MONTH": [
"s\u00e1nz\u00e1 ya yambo",
"s\u00e1nz\u00e1 ya m\u00edbal\u00e9",
"s\u00e1nz\u00e1 ya m\u00eds\u00e1to",
"s\u00e1nz\u00e1 ya m\u00ednei",
"s\u00e1nz\u00e1 ya m\u00edt\u00e1no",
"s\u00e1nz\u00e1 ya mot\u00f3b\u00e1",
"s\u00e1nz\u00e1 ya nsambo",
"s\u00e1nz\u00e1 ya mwambe",
"s\u00e1nz\u00e1 ya libwa",
"s\u00e1nz\u00e1 ya z\u00f3mi",
"s\u00e1nz\u00e1 ya z\u00f3mi na m\u0254\u030ck\u0254\u0301",
"s\u00e1nz\u00e1 ya z\u00f3mi na m\u00edbal\u00e9"
],
"SHORTDAY": [
"eye",
"ybo",
"mbl",
"mst",
"min",
"mtn",
"mps"
],
"SHORTMONTH": [
"yan",
"fbl",
"msi",
"apl",
"mai",
"yun",
"yul",
"agt",
"stb",
"\u0254tb",
"nvb",
"dsb"
],
"WEEKENDRANGE": [
5,
6
],
"fullDate": "EEEE d MMMM y",
"longDate": "d MMMM y",
"medium": "d MMM y HH:mm:ss",
"mediumDate": "d MMM y",
"mediumTime": "HH:mm:ss",
"short": "d/M/y HH:mm",
"shortDate": "d/M/y",
"shortTime": "HH:mm"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "FrCD",
"DECIMAL_SEP": ",",
"GROUP_SEP": ".",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "-",
"negSuf": "\u00a0\u00a4",
"posPre": "",
"posSuf": "\u00a0\u00a4"
}
]
},
"id": "ln-cd",
"pluralCat": function(n, opt_precision) { if (n >= 0 && n <= 1) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]);
|
/*!
* jQuery JavaScript Library v@VERSION
* http://jquery.com/
*
* Includes Sizzle.js
* http://sizzlejs.com/
*
* Copyright 2005, 2014 jQuery Foundation, Inc. and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: @DATE
*/
(function( global, factory ) {
if ( typeof module === "object" && typeof module.exports === "object" ) {
// For CommonJS and CommonJS-like environments where a proper window is present,
// execute the factory and get jQuery
// For environments that do not inherently posses a window with a document
// (such as Node.js), expose a jQuery-making factory as module.exports
// This accentuates the need for the creation of a real window
// e.g. var jQuery = require("jquery")(window);
// See ticket #14549 for more info
module.exports = global.document ?
factory( global, true ) :
function( w ) {
if ( !w.document ) {
throw new Error( "jQuery requires a window with a document" );
}
return factory( w );
};
} else {
factory( global );
}
// Pass this if window is not defined yet
}(typeof window !== "undefined" ? window : this, function( window, noGlobal ) {
// Can't do this because several apps including ASP.NET trace
// the stack via arguments.caller.callee and Firefox dies if
// you try to trace through "use strict" call chains. (#13335)
// Support: Firefox 18+
//
|
'use strict';
const chalk = require('chalk');
const detect = require('detect-port-alt');
const getProcessForPort = require('./getProcessForPort');
function isRoot() {
return process.getuid && process.getuid() === 0;
}
function checkDetectPort(port, host) {
port = parseInt(port, 10) || 0;
return new Promise((resolve, reject) => {
detect(port, host, (err, _port) => {
if (err) {
reject(err);
} else {
if (port === _port) {
resolve(port);
} else {
let message = `目前 ${chalk.bold(port)} 端口被占用`;
if (
process.platform !== 'win32' &&
port < 1024 &&
!isRoot()
) {
message =
'`在1024以下的端口上运行服务器需要管理员权限`';
}
const existingProcess = getProcessForPort(port);
if (existingProcess) {
message += `,该端口使用情况:\n ${existingProcess}`;
}
reject({
message: chalk.yellow(message),
});
}
}
});
});
}
module.exports = checkDetectPort;
|
// Copyright 2012 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Ordinal rules.
*
* This file is autogenerated by script:
* http://go/generate_pluralrules.py
* File generated from CLDR ver. 24
*
* Before check in, this file could have been manually edited. This is to
* incorporate changes before we could fix CLDR. All manual modification must be
* documented in this section, and should be removed after those changes land to
* CLDR.
*/
goog.provide('goog.i18n.ordinalRules');
/**
* Ordinal pattern keyword
* @enum {string}
*/
goog.i18n.ordinalRules.Keyword = {
ZERO: 'zero',
ONE: 'one',
TWO: 'two',
FEW: 'few',
MANY: 'many',
OTHER: 'other'
};
/**
* Default Ordinal select rule.
* @param {number} n The count of items.
* @param {number=} opt_precision optional, precision.
* @return {goog.i18n.ordinalRules.Keyword} Default value.
* @private
*/
goog.i18n.ordinalRules.defaultSelect_ = function(n, opt_precision) {
return goog.i18n.ordinalRules.Keyword.OTHER;
};
/**
* Returns the fractional part of a number (3.1416 => 1416)
* @param {number} n The count of items.
* @return {number} The fractional part.
* @private
*/
goog.i18n.ordinalRules.decimals_ = function(n) {
var str = n + '';
var result = str.indexOf('.');
return (result == -1) ? 0 : str.length - result - 1;
};
/**
* Calculates v and f as per CLDR plural rules.
* @param {number} n The count of items.
* @param {number=} opt_precision optional, precision.
* @return {Object} The v and f.
* @private
*/
goog.i18n.ordinalRules.get_vf_ = function(n, opt_precision) {
var DEFAULT_DIGITS = 3;
if (undefined === opt_precision) {
var v = Math.min(goog.i18n.ordinalRules.decimals_(n), DEFAULT_DIGITS);
} else {
var v = opt_precision;
}
var base = Math.pow(10, v);
var f = ((n * base) | 0) % base;
return {'v': v, 'f': f};
};
/**
* Calculates w and t as per CLDR plural rules.
* @param {number} v Calculated previously.
* @param {number} f Calculated previously.
* @return {Object} The w and t.
* @private
*/
goog.i18n.ordinalRules.get_wt_ = function(v, f) {
if (f === 0) {
return {'w': 0, 't': 0};
}
while ((f % 10) === 0) {
f /= 10;
v--;
}
return {'w': v, 't': f};
};
/**
* Ordinal select rules for en locale
*
* @param {number} n The count of items.
* @param {number=} opt_precision Precision for number formatting, if not default.
* @return {goog.i18n.ordinalRules.Keyword} Locale-specific ordinal value.
* @private
*/
goog.i18n.ordinalRules.enSelect_ = function(n, opt_precision) {
if (n % 10 == 1 && n % 100 != 11) {
return goog.i18n.ordinalRules.Keyword.ONE;
}
if (n % 10 == 2 && n % 100 != 12) {
return goog.i18n.ordinalRules.Keyword.TWO;
}
if (n % 10 == 3 && n % 100 != 13) {
return goog.i18n.ordinalRules.Keyword.FEW;
}
return goog.i18n.ordinalRules.Keyword.OTHER;
};
/**
* Ordinal select rules for sv locale
*
* @param {number} n The count of items.
* @param {number=} opt_precision Precision for number formatting, if not default.
* @return {goog.i18n.ordinalRules.Keyword} Locale-specific ordinal value.
* @private
*/
goog.i18n.ordinalRules.svSelect_ = function(n, opt_precision) {
if ((n % 10 == 1 || n % 10 == 2) && n % 100 != 11 && n % 100 != 12) {
return goog.i18n.ordinalRules.Keyword.ONE;
}
return goog.i18n.ordinalRules.Keyword.OTHER;
};
/**
* Ordinal select rules for fr locale
*
* @param {number} n The count of items.
* @param {number=} opt_precision Precision for number formatting, if not default.
* @return {goog.i18n.ordinalRules.Keyword} Locale-specific ordinal value.
* @private
*/
goog.i18n.ordinalRules.frSelect_ = function(n, opt_precision) {
if (n == 1) {
return goog.i18n.ordinalRules.Keyword.ONE;
}
return goog.i18n.ordinalRules.Keyword.OTHER;
};
/**
* Ordinal select rules for hu locale
*
* @param {number} n The count of items.
* @param {number=} opt_precision Precision for number formatting, if not default.
* @return {goog.i18n.ordinalRules.Keyword} Locale-specific ordinal value.
* @private
*/
goog.i18n.ordinalRules.huSelect_ = function(n, opt_precision) {
if (n == 1 || n == 5) {
return goog.i18n.ordinalRules.Keyword.ONE;
}
return goog.i18n.ordinalRules.Keyword.OTHER;
};
/**
* Ordinal select rules for zu locale
*
* @param {number} n The count of items.
* @param {number=} opt_precision Precision for number formatting, if not default.
* @return {goog.i18n.ordinalRules.Keyword} Locale-specific ordinal value.
* @private
*/
goog.i18n.ordinalRules.zuSelect_ = function(n, opt_precision) {
if (n == 1) {
return goog.i18n.ordinalRules.Keyword.ONE;
}
if (n >= 2 && n <= 9) {
return goog.i18n.ordinalRules.Keyword.FEW;
}
if (n >= 10 && n <= 19 || n >= 100 && n <= 199 || n >= 1000 && n <= 1999) {
return goog.i18n.ordinalRules.Keyword.MANY;
}
return goog.i18n.ordinalRules.Keyword.OTHER;
};
/**
* Ordinal select rules for mr locale
*
* @param {number} n The count of items.
* @param {number=} opt_precision Precision for number formatting, if not default.
* @return {goog.i18n.ordinalRules.Keyword} Locale-specific ordinal value.
* @private
*/
goog.i18n.ordinalRules.mrSelect_ = function(n, opt_precision) {
if (n == 1) {
return goog.i18n.ordinalRules.Keyword.ONE;
}
if (n == 2 || n == 3) {
return goog.i18n.ordinalRules.Keyword.TWO;
}
if (n == 4) {
return goog.i18n.ordinalRules.Keyword.FEW;
}
return goog.i18n.ordinalRules.Keyword.OTHER;
};
/**
* Ordinal select rules for ca locale
*
* @param {number} n The count of items.
* @param {number=} opt_precision Precision for number formatting, if not default.
* @return {goog.i18n.ordinalRules.Keyword} Locale-specific ordinal value.
* @private
*/
goog.i18n.ordinalRules.caSelect_ = function(n, opt_precision) {
if (n == 1 || n == 3) {
return goog.i18n.ordinalRules.Keyword.ONE;
}
if (n == 2) {
return goog.i18n.ordinalRules.Keyword.TWO;
}
if (n == 4) {
return goog.i18n.ordinalRules.Keyword.FEW;
}
return goog.i18n.ordinalRules.Keyword.OTHER;
};
/**
* Ordinal select rules for bn locale
*
* @param {number} n The count of items.
* @param {number=} opt_precision Precision for number formatting, if not default.
* @return {goog.i18n.ordinalRules.Keyword} Locale-specific ordinal value.
* @private
*/
goog.i18n.ordinalRules.bnSelect_ = function(n, opt_precision) {
if (n == 1 || n == 5 || n == 7 || n == 8 || n == 9 || n == 10) {
return goog.i18n.ordinalRules.Keyword.ONE;
}
if (n == 2 || n == 3) {
return goog.i18n.ordinalRules.Keyword.TWO;
}
if (n == 4) {
return goog.i18n.ordinalRules.Keyword.FEW;
}
if (n == 6) {
return goog.i18n.ordinalRules.Keyword.MANY;
}
return goog.i18n.ordinalRules.Keyword.OTHER;
};
/**
* Ordinal select rules for it locale
*
* @param {number} n The count of items.
* @param {number=} opt_precision Precision for number formatting, if not default.
* @return {goog.i18n.ordinalRules.Keyword} Locale-specific ordinal value.
* @private
*/
goog.i18n.ordinalRules.itSelect_ = function(n, opt_precision) {
if (n == 11 || n == 8 || n == 80 || n == 800) {
return goog.i18n.ordinalRules.Keyword.MANY;
}
return goog.i18n.ordinalRules.Keyword.OTHER;
};
/**
* Ordinal select rules for gu locale
*
* @param {number} n The count of items.
* @param {number=} opt_precision Precision for number formatting, if not default.
* @return {goog.i18n.ordinalRules.Keyword} Locale-specific ordinal value.
* @private
*/
goog.i18n.ordinalRules.guSelect_ = function(n, opt_precision) {
if (n == 1) {
return goog.i18n.ordinalRules.Keyword.ONE;
}
if (n == 2 || n == 3) {
return goog.i18n.ordinalRules.Keyword.TWO;
}
if (n == 4) {
return goog.i18n.ordinalRules.Keyword.FEW;
}
if (n == 6) {
return goog.i18n.ordinalRules.Keyword.MANY;
}
return goog.i18n.ordinalRules.Keyword.OTHER;
};
/**
* Selected Ordinal rules by locale.
*/
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.enSelect_;
if (goog.LOCALE == 'af') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;
}
if (goog.LOCALE == 'am') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;
}
if (goog.LOCALE == 'ar') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;
}
if (goog.LOCALE == 'bg') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;
}
if (goog.LOCALE == 'bn') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.bnSelect_;
}
if (goog.LOCALE == 'br') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;
}
if (goog.LOCALE == 'ca') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.caSelect_;
}
if (goog.LOCALE == 'chr') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;
}
if (goog.LOCALE == 'cs') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;
}
if (goog.LOCALE == 'cy') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;
}
if (goog.LOCALE == 'da') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;
}
if (goog.LOCALE == 'de') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;
}
if (goog.LOCALE == 'de_AT' || goog.LOCALE == 'de-AT') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;
}
if (goog.LOCALE == 'de_CH' || goog.LOCALE == 'de-CH') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;
}
if (goog.LOCALE == 'el') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;
}
if (goog.LOCALE == 'en') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.enSelect_;
}
if (goog.LOCALE == 'en_AU' || goog.LOCALE == 'en-AU') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.enSelect_;
}
if (goog.LOCALE == 'en_GB' || goog.LOCALE == 'en-GB') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.enSelect_;
}
if (goog.LOCALE == 'en_IE' || goog.LOCALE == 'en-IE') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.enSelect_;
}
if (goog.LOCALE == 'en_IN' || goog.LOCALE == 'en-IN') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.enSelect_;
}
if (goog.LOCALE == 'en_ISO' || goog.LOCALE == 'en-ISO') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.enSelect_;
}
if (goog.LOCALE == 'en_SG' || goog.LOCALE == 'en-SG') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.enSelect_;
}
if (goog.LOCALE == 'en_US' || goog.LOCALE == 'en-US') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.enSelect_;
}
if (goog.LOCALE == 'en_ZA' || goog.LOCALE == 'en-ZA') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.enSelect_;
}
if (goog.LOCALE == 'es') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;
}
if (goog.LOCALE == 'es_419' || goog.LOCALE == 'es-419') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;
}
if (goog.LOCALE == 'es_ES' || goog.LOCALE == 'es-ES') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;
}
if (goog.LOCALE == 'et') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;
}
if (goog.LOCALE == 'eu') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;
}
if (goog.LOCALE == 'fa') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;
}
if (goog.LOCALE == 'fi') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;
}
if (goog.LOCALE == 'fil') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.frSelect_;
}
if (goog.LOCALE == 'fr') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.frSelect_;
}
if (goog.LOCALE == 'fr_CA' || goog.LOCALE == 'fr-CA') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.frSelect_;
}
if (goog.LOCALE == 'gl') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;
}
if (goog.LOCALE == 'gsw') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;
}
if (goog.LOCALE == 'gu') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.guSelect_;
}
if (goog.LOCALE == 'haw') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;
}
if (goog.LOCALE == 'he') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;
}
if (goog.LOCALE == 'hi') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.guSelect_;
}
if (goog.LOCALE == 'hr') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;
}
if (goog.LOCALE == 'hu') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.huSelect_;
}
if (goog.LOCALE == 'id') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;
}
if (goog.LOCALE == 'in') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;
}
if (goog.LOCALE == 'is') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;
}
if (goog.LOCALE == 'it') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.itSelect_;
}
if (goog.LOCALE == 'iw') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;
}
if (goog.LOCALE == 'ja') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;
}
if (goog.LOCALE == 'kn') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;
}
if (goog.LOCALE == 'ko') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;
}
if (goog.LOCALE == 'ln') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;
}
if (goog.LOCALE == 'lt') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;
}
if (goog.LOCALE == 'lv') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;
}
if (goog.LOCALE == 'ml') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;
}
if (goog.LOCALE == 'mo') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.frSelect_;
}
if (goog.LOCALE == 'mr') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.mrSelect_;
}
if (goog.LOCALE == 'ms') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.frSelect_;
}
if (goog.LOCALE == 'mt') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;
}
if (goog.LOCALE == 'nb') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;
}
if (goog.LOCALE == 'nl') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;
}
if (goog.LOCALE == 'no') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;
}
if (goog.LOCALE == 'or') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;
}
if (goog.LOCALE == 'pl') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;
}
if (goog.LOCALE == 'pt') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;
}
if (goog.LOCALE == 'pt_BR' || goog.LOCALE == 'pt-BR') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;
}
if (goog.LOCALE == 'pt_PT' || goog.LOCALE == 'pt-PT') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;
}
if (goog.LOCALE == 'ro') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.frSelect_;
}
if (goog.LOCALE == 'ru') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;
}
if (goog.LOCALE == 'sk') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;
}
if (goog.LOCALE == 'sl') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;
}
if (goog.LOCALE == 'sq') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;
}
if (goog.LOCALE == 'sr') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;
}
if (goog.LOCALE == 'sv') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.svSelect_;
}
if (goog.LOCALE == 'sw') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;
}
if (goog.LOCALE == 'ta') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;
}
if (goog.LOCALE == 'te') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;
}
if (goog.LOCALE == 'th') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;
}
if (goog.LOCALE == 'tl') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.frSelect_;
}
if (goog.LOCALE == 'tr') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;
}
if (goog.LOCALE == 'uk') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;
}
if (goog.LOCALE == 'ur') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;
}
if (goog.LOCALE == 'vi') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.frSelect_;
}
if (goog.LOCALE == 'zh') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;
}
if (goog.LOCALE == 'zh_CN' || goog.LOCALE == 'zh-CN') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;
}
if (goog.LOCALE == 'zh_HK' || goog.LOCALE == 'zh-HK') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;
}
if (goog.LOCALE == 'zh_TW' || goog.LOCALE == 'zh-TW') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_;
}
if (goog.LOCALE == 'zu') {
goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.zuSelect_;
}
|
const middleware = {}
export default middleware
|
// Generated by CoffeeScript 1.3.3
(function() {
var nock, should, wd;
wd = require('../common/wd-with-cov');
nock = require('nock');
should = require('should');
describe("wd", function() {
return describe("unit", function() {
return describe("callback tests", function() {
var server;
server = null;
before(function(done) {
server = nock('http://127.0.0.1:5555').filteringRequestBody(/.*/, '*');
if (process.env.WD_COV == null) {
server.log(console.log);
}
server.post('/wd/hub/session', '*').reply(303, "OK", {
'Location': '/wd/hub/session/1234'
});
return done(null);
});
return describe("simplecallback empty returns", function() {
var browser;
browser = null;
describe("browser initialization", function() {
return it("should initialize browser", function(done) {
browser = wd.remote({
port: 5555
});
return browser.init({}, function(err) {
should.not.exist(err);
return done(null);
});
});
});
describe("simplecallback with empty return", function() {
return it("should get url", function(done) {
server.post('/wd/hub/session/1234/url', '*').reply(200, "");
return browser.get("www.google.com", function(err) {
should.not.exist(err);
return done(null);
});
});
});
describe("simplecallback with 200 OK", function() {
return it("should get url", function(done) {
server.post('/wd/hub/session/1234/url', '*').reply(200, "OK");
return browser.get("www.google.com", function(err) {
should.not.exist(err);
return done(null);
});
});
});
return describe("simplecallback with empty JSON data", function() {
return it("should get url", function(done) {
server.post('/wd/hub/session/1234/url', '*').reply(200, '{"sessionId":"1234","status":0,"value":{}}');
return browser.get("www.google.com", function(err) {
should.not.exist(err);
return done(null);
});
});
});
});
});
});
});
}).call(this);
|
'use strict';
const path = require('path');
const webpack = require('webpack');
const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin');
module.exports = {
bail : true,
entry : path.join(__dirname, 'src/main/main.js'),
target: 'electron-main',
output: {
path : path.join(__dirname, 'dist'),
filename : 'main.js',
publicPath : '/dist/',
libraryTarget: 'commonjs2'
},
resolve: {
modules : ['node_modules'],
extensions : ['.js'],
descriptionFiles: ['package.json']
},
externals: {
'7zip': '7zip'
},
plugins: [
new webpack.NamedModulesPlugin(),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
}),
new CaseSensitivePathsPlugin()
],
node: {
__dirname : false,
__filename: false
}
};
|
//分页插件
/**
2014-08-05 ch
**/
(function($){
var ms = {
init:function(obj,args){
return (function(){
ms.fillHtml(obj,args);
ms.bindEvent(obj,args);
})();
},
//填充html
fillHtml:function(obj,args){
return (function(){
obj.empty();
//上一页
if(args.current > 1){
obj.append('<a href="javascript:;" class="prevPage">上一页</a>');
}else{
obj.remove('.prevPage');
obj.append('<span class="disabled">上一页</span>');
}
//中间页码
if(args.current != 1 && args.current >= 4 && args.pageCount != 4){
obj.append('<a href="javascript:;" class="tcdNumber">'+1+'</a>');
}
if(args.current-2 > 2 && args.current <= args.pageCount && args.pageCount > 5){
obj.append('<span>...</span>');
}
var start = args.current -2,end = args.current+2;
if((start > 1 && args.current < 4)||args.current == 1){
end++;
}
if(args.current > args.pageCount-4 && args.current >= args.pageCount){
start--;
}
for (;start <= end; start++) {
if(start <= args.pageCount && start >= 1){
if(start != args.current){
obj.append('<a href="javascript:;" class="tcdNumber">'+ start +'</a>');
}else{
obj.append('<span class="current">'+ start +'</span>');
}
}
}
if(args.current + 2 < args.pageCount - 1 && args.current >= 1 && args.pageCount > 5){
obj.append('<span>...</span>');
}
if(args.current != args.pageCount && args.current < args.pageCount -2 && args.pageCount != 4){
obj.append('<a href="javascript:;" class="tcdNumber">'+args.pageCount+'</a>');
}
//下一页
if(args.current < args.pageCount){
obj.append('<a href="javascript:;" class="nextPage">下一页</a>');
}else{
obj.remove('.nextPage');
obj.append('<span class="disabled">下一页</span>');
}
})();
},
//绑定事件
bindEvent:function(obj,args){
return (function(){
obj.on("click","a.tcdNumber",function(){
var current = parseInt($(this).text());
ms.fillHtml(obj,{"current":current,"pageCount":args.pageCount});
if(typeof(args.backFn)=="function"){
args.backFn(current);
}
});
//上一页
obj.on("click","a.prevPage",function(){
var current = parseInt(obj.children("span.current").text());
ms.fillHtml(obj,{"current":current-1,"pageCount":args.pageCount});
if(typeof(args.backFn)=="function"){
args.backFn(current-1);
}
});
//下一页
obj.on("click","a.nextPage",function(){
var current = parseInt(obj.children("span.current").text());
ms.fillHtml(obj,{"current":current+1,"pageCount":args.pageCount});
if(typeof(args.backFn)=="function"){
args.backFn(current+1);
}
});
})();
}
}
$.fn.createPage = function(options){
var args = $.extend({
pageCount : 10,
current : 1,
backFn : function(){}
},options);
ms.init(this,args);
}
})(jQuery);
//代码整理:懒人之家 www.lanrenzhijia.com |
var files = {
"webgl": [
"webgl_animation_cloth",
"webgl_animation_keyframes",
"webgl_animation_skinning_blending",
"webgl_animation_skinning_morph",
"webgl_animation_multiple",
"webgl_camera",
"webgl_camera_array",
"webgl_camera_cinematic",
"webgl_camera_logarithmicdepthbuffer",
"webgl_clipping",
"webgl_clipping_advanced",
"webgl_clipping_intersection",
"webgl_clipping_stencil",
"webgl_decals",
"webgl_depth_texture",
"webgl_effects_anaglyph",
"webgl_effects_ascii",
"webgl_effects_parallaxbarrier",
"webgl_effects_peppersghost",
"webgl_effects_stereo",
"webgl_framebuffer_texture",
"webgl_geometries",
"webgl_geometries_parametric",
"webgl_geometry_colors",
"webgl_geometry_colors_lookuptable",
"webgl_geometry_convex",
"webgl_geometry_cube",
"webgl_geometry_dynamic",
"webgl_geometry_extrude_shapes",
"webgl_geometry_extrude_shapes2",
"webgl_geometry_extrude_splines",
"webgl_geometry_hierarchy",
"webgl_geometry_hierarchy2",
"webgl_geometry_minecraft",
"webgl_geometry_minecraft_ao",
"webgl_geometry_normals",
"webgl_geometry_nurbs",
"webgl_geometry_shapes",
"webgl_geometry_spline_editor",
"webgl_geometry_teapot",
"webgl_geometry_terrain",
"webgl_geometry_terrain_fog",
"webgl_geometry_terrain_raycast",
"webgl_geometry_text",
"webgl_geometry_text_shapes",
"webgl_geometry_text_stroke",
"webgl_helpers",
"webgl_instancing_dynamic",
"webgl_instancing_performance",
"webgl_instancing_raycast",
"webgl_instancing_scatter",
"webgl_interactive_buffergeometry",
"webgl_interactive_cubes",
"webgl_interactive_cubes_gpu",
"webgl_interactive_cubes_ortho",
"webgl_interactive_lines",
"webgl_interactive_points",
"webgl_interactive_raycasting_points",
"webgl_interactive_voxelpainter",
"webgl_kinect",
"webgl_layers",
"webgl_lensflares",
"webgl_lightprobe",
"webgl_lightprobe_cubecamera",
"webgl_lights_hemisphere",
"webgl_lights_physical",
"webgl_lights_pointlights",
"webgl_lights_pointlights2",
"webgl_lights_spotlight",
"webgl_lights_spotlights",
"webgl_lights_rectarealight",
"webgl_lines_colors",
"webgl_lines_dashed",
"webgl_lines_fat",
"webgl_lines_fat_wireframe",
"webgl_lines_sphere",
"webgl_loader_3ds",
"webgl_loader_3mf",
"webgl_loader_3mf_materials",
"webgl_loader_amf",
"webgl_loader_assimp",
"webgl_loader_bvh",
"webgl_loader_collada",
"webgl_loader_collada_kinematics",
"webgl_loader_collada_skinning",
"webgl_loader_draco",
"webgl_loader_fbx",
"webgl_loader_fbx_nurbs",
"webgl_loader_gcode",
"webgl_loader_gltf",
"webgl_loader_gltf_extensions",
"webgl_loader_imagebitmap",
"webgl_loader_json_claraio",
"webgl_loader_kmz",
"webgl_loader_ldraw",
"webgl_loader_lwo",
"webgl_loader_md2",
"webgl_loader_md2_control",
"webgl_loader_mdd",
"webgl_loader_mmd",
"webgl_loader_mmd_pose",
"webgl_loader_mmd_audio",
"webgl_loader_nrrd",
"webgl_loader_obj",
"webgl_loader_obj_mtl",
"webgl_loader_obj2",
"webgl_loader_obj2_options",
"webgl_loader_pcd",
"webgl_loader_pdb",
"webgl_loader_ply",
"webgl_loader_prwm",
"webgl_loader_stl",
"webgl_loader_svg",
"webgl_loader_texture_basis",
"webgl_loader_texture_dds",
"webgl_loader_texture_exr",
"webgl_loader_texture_hdr",
"webgl_loader_texture_ktx",
"webgl_loader_texture_pvrtc",
"webgl_loader_texture_rgbm",
"webgl_loader_texture_tga",
"webgl_loader_ttf",
"webgl_loader_vrm",
"webgl_loader_vrml",
"webgl_loader_vtk",
"webgl_loader_x",
"webgl_lod",
"webgl_marchingcubes",
"webgl_materials",
"webgl_materials_blending",
"webgl_materials_blending_custom",
"webgl_materials_bumpmap",
"webgl_materials_car",
"webgl_materials_channels",
"webgl_materials_cubemap",
"webgl_materials_cubemap_balls_reflection",
"webgl_materials_cubemap_balls_refraction",
"webgl_materials_cubemap_dynamic",
"webgl_materials_cubemap_refraction",
"webgl_materials_cubemap_mipmaps",
"webgl_materials_curvature",
"webgl_materials_displacementmap",
"webgl_materials_envmaps",
"webgl_materials_envmaps_exr",
"webgl_materials_envmaps_hdr",
"webgl_materials_envmaps_parallax",
"webgl_materials_grass",
"webgl_materials_lightmap",
"webgl_materials_matcap",
"webgl_materials_normalmap",
"webgl_materials_normalmap_object_space",
"webgl_materials_parallaxmap",
"webgl_materials_physical_clearcoat",
"webgl_materials_physical_reflectivity",
"webgl_materials_physical_sheen",
"webgl_materials_physical_transparency",
"webgl_materials_shaders_fresnel",
"webgl_materials_standard",
"webgl_materials_texture_anisotropy",
"webgl_materials_texture_canvas",
"webgl_materials_texture_filters",
"webgl_materials_texture_manualmipmap",
"webgl_materials_texture_partialupdate",
"webgl_materials_texture_rotation",
"webgl_materials_translucency",
"webgl_materials_variations_basic",
"webgl_materials_variations_lambert",
"webgl_materials_variations_phong",
"webgl_materials_variations_standard",
"webgl_materials_variations_physical",
"webgl_materials_variations_toon",
"webgl_materials_video",
"webgl_materials_video_webcam",
"webgl_materials_wireframe",
"webgl_math_obb",
"webgl_math_orientation_transform",
"webgl_mirror",
"webgl_modifier_simplifier",
"webgl_modifier_subdivision",
"webgl_modifier_tessellation",
"webgl_morphtargets",
"webgl_morphtargets_horse",
"webgl_morphtargets_sphere",
"webgl_multiple_canvases_circle",
"webgl_multiple_canvases_complex",
"webgl_multiple_canvases_grid",
"webgl_multiple_elements",
"webgl_multiple_elements_text",
"webgl_multiple_renderers",
"webgl_multiple_scenes_comparison",
"webgl_multiple_views",
"webgl_nearestneighbour",
"webgl_panorama_cube",
"webgl_panorama_dualfisheye",
"webgl_panorama_equirectangular",
"webgl_performance",
"webgl_performance_doublesided",
"webgl_performance_static",
"webgl_points_billboards",
"webgl_points_dynamic",
"webgl_points_sprites",
"webgl_points_waves",
"webgl_raycast_sprite",
"webgl_raycast_texture",
"webgl_read_float_buffer",
"webgl_refraction",
"webgl_rtt",
"webgl_sandbox",
"webgl_shader",
"webgl_shader_lava",
"webgl_shader2",
"webgl_shaders_ocean",
"webgl_shaders_ocean2",
"webgl_shaders_sky",
"webgl_shaders_tonemapping",
"webgl_shaders_vector",
"webgl_shading_physical",
"webgl_shadow_contact",
"webgl_shadowmap",
"webgl_shadowmap_performance",
"webgl_shadowmap_pointlight",
"webgl_shadowmap_viewer",
"webgl_shadowmap_vsm",
"webgl_shadowmesh",
"webgl_skinning_simple",
"webgl_sprites",
"webgl_test_memory",
"webgl_test_memory2",
"webgl_tonemapping",
"webgl_trails",
"webgl_video_panorama_equirectangular",
"webgl_water",
"webgl_water_flowmap"
],
"webgl / nodes": [
"webgl_loader_nodes",
"webgl_materials_compile",
"webgl_materials_envmaps_hdr_nodes",
"webgl_materials_envmaps_pmrem_nodes",
"webgl_materials_nodes",
"webgl_mirror_nodes",
"webgl_performance_nodes",
"webgl_postprocessing_nodes",
"webgl_postprocessing_nodes_pass",
"webgl_sprites_nodes",
],
"webgl / postprocessing": [
"webgl_postprocessing",
"webgl_postprocessing_advanced",
"webgl_postprocessing_afterimage",
"webgl_postprocessing_backgrounds",
"webgl_postprocessing_crossfade",
"webgl_postprocessing_dof",
"webgl_postprocessing_dof2",
"webgl_postprocessing_fxaa",
"webgl_postprocessing_glitch",
"webgl_postprocessing_godrays",
"webgl_postprocessing_rgb_halftone",
"webgl_postprocessing_masking",
"webgl_postprocessing_ssaa",
"webgl_postprocessing_ssaa_unbiased",
"webgl_postprocessing_outline",
"webgl_postprocessing_pixel",
"webgl_postprocessing_procedural",
"webgl_postprocessing_sao",
"webgl_postprocessing_smaa",
"webgl_postprocessing_sobel",
"webgl_postprocessing_ssao",
"webgl_postprocessing_taa",
"webgl_postprocessing_unreal_bloom",
"webgl_postprocessing_unreal_bloom_selective"
],
"webgl / advanced": [
"webgl_buffergeometry",
"webgl_buffergeometry_compression",
"webgl_buffergeometry_constructed_from_geometry",
"webgl_buffergeometry_custom_attributes_particles",
"webgl_buffergeometry_drawrange",
"webgl_buffergeometry_indexed",
"webgl_buffergeometry_instancing",
"webgl_buffergeometry_instancing_billboards",
"webgl_buffergeometry_instancing_interleaved",
"webgl_buffergeometry_lines",
"webgl_buffergeometry_lines_indexed",
"webgl_buffergeometry_morphtargets",
"webgl_buffergeometry_points",
"webgl_buffergeometry_points_interleaved",
"webgl_buffergeometry_rawshader",
"webgl_buffergeometry_selective_draw",
"webgl_buffergeometry_uint",
"webgl_custom_attributes",
"webgl_custom_attributes_lines",
"webgl_custom_attributes_points",
"webgl_custom_attributes_points2",
"webgl_custom_attributes_points3",
"webgl_fire",
"webgl_gpgpu_birds",
"webgl_gpgpu_water",
"webgl_gpgpu_protoplanet",
"webgl_instancing_modified",
"webgl_lightningstrike",
"webgl_materials_modified",
"webgl_raymarching_reflect",
"webgl_shadowmap_csm",
"webgl_shadowmap_pcss",
"webgl_simple_gi",
"webgl_tiled_forward",
"webgl_worker_offscreencanvas"
],
"webgl2": [
"webgl2_materials_texture2darray",
"webgl2_materials_texture3d",
"webgl2_multisampled_renderbuffers",
"webgl2_sandbox"
],
"webaudio": [
"webaudio_orientation",
"webaudio_sandbox",
"webaudio_timing",
"webaudio_visualizer"
],
"webxr": [
"webxr_ar_cones",
"webxr_ar_hittest",
"webxr_ar_paint",
"webxr_vr_ballshooter",
"webxr_vr_cubes",
"webxr_vr_dragging",
"webxr_vr_lorenzattractor",
"webxr_vr_panorama",
"webxr_vr_panorama_depth",
"webxr_vr_paint",
"webxr_vr_rollercoaster",
"webxr_vr_sandbox",
"webxr_vr_sculpt",
"webxr_vr_video"
],
"physics": [
"physics_ammo_break",
"physics_ammo_cloth",
"physics_ammo_rope",
"physics_ammo_terrain",
"physics_ammo_volume",
"physics_cannon_instancing"
],
"misc": [
"misc_animation_authoring",
"misc_animation_groups",
"misc_animation_keys",
"misc_boxselection",
"misc_controls_deviceorientation",
"misc_controls_drag",
"misc_controls_fly",
"misc_controls_map",
"misc_controls_orbit",
"misc_controls_pointerlock",
"misc_controls_trackball",
"misc_controls_transform",
"misc_exporter_collada",
"misc_exporter_draco",
"misc_exporter_gltf",
"misc_exporter_obj",
"misc_exporter_ply",
"misc_exporter_stl",
"misc_lookat",
],
"css2d": [
"css2d_label"
],
"css3d": [
"css3d_molecules",
"css3d_orthographic",
"css3d_panorama",
"css3d_panorama_deviceorientation",
"css3d_periodictable",
"css3d_sandbox",
"css3d_sprites",
"css3d_youtube"
],
"svg": [
"svg_lines",
"svg_sandbox"
],
"tests": [
"webgl_furnace_test",
"webgl_pmrem_test",
"misc_uv_tests"
]
};
|
/*
* Copyright (C) 2010 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
WebInspector.AuditRules.IPAddressRegexp = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
WebInspector.AuditRules.CacheableResponseCodes =
{
200: true,
203: true,
206: true,
300: true,
301: true,
410: true,
304: true // Underlying request is cacheable
}
/**
* @param {!Array.<!WebInspector.NetworkRequest>} requests
* @param {Array.<!WebInspector.resourceTypes>} types
* @param {boolean} needFullResources
* @return {(Object.<string, !Array.<!WebInspector.NetworkRequest>>|Object.<string, !Array.<string>>)}
*/
WebInspector.AuditRules.getDomainToResourcesMap = function(requests, types, needFullResources)
{
var domainToResourcesMap = {};
for (var i = 0, size = requests.length; i < size; ++i) {
var request = requests[i];
if (types && types.indexOf(request.type) === -1)
continue;
var parsedURL = request.url.asParsedURL();
if (!parsedURL)
continue;
var domain = parsedURL.host;
var domainResources = domainToResourcesMap[domain];
if (domainResources === undefined) {
domainResources = [];
domainToResourcesMap[domain] = domainResources;
}
domainResources.push(needFullResources ? request : request.url);
}
return domainToResourcesMap;
}
/**
* @constructor
* @extends {WebInspector.AuditRule}
*/
WebInspector.AuditRules.GzipRule = function()
{
WebInspector.AuditRule.call(this, "network-gzip", "Enable gzip compression");
}
WebInspector.AuditRules.GzipRule.prototype = {
/**
* @param {!Array.<!WebInspector.NetworkRequest>} requests
* @param {!WebInspector.AuditRuleResult} result
* @param {function(WebInspector.AuditRuleResult)} callback
* @param {!WebInspector.Progress} progress
*/
doRun: function(requests, result, callback, progress)
{
var totalSavings = 0;
var compressedSize = 0;
var candidateSize = 0;
var summary = result.addChild("", true);
for (var i = 0, length = requests.length; i < length; ++i) {
var request = requests[i];
if (request.cached || request.statusCode === 304)
continue; // Do not test cached resources.
if (this._shouldCompress(request)) {
var size = request.resourceSize;
candidateSize += size;
if (this._isCompressed(request)) {
compressedSize += size;
continue;
}
var savings = 2 * size / 3;
totalSavings += savings;
summary.addFormatted("%r could save ~%s", request.url, Number.bytesToString(savings));
result.violationCount++;
}
}
if (!totalSavings)
return callback(null);
summary.value = String.sprintf("Compressing the following resources with gzip could reduce their transfer size by about two thirds (~%s):", Number.bytesToString(totalSavings));
callback(result);
},
_isCompressed: function(request)
{
var encodingHeader = request.responseHeaderValue("Content-Encoding");
if (!encodingHeader)
return false;
return /\b(?:gzip|deflate)\b/.test(encodingHeader);
},
_shouldCompress: function(request)
{
return request.type.isTextType() && request.parsedURL.host && request.resourceSize !== undefined && request.resourceSize > 150;
},
__proto__: WebInspector.AuditRule.prototype
}
/**
* @constructor
* @extends {WebInspector.AuditRule}
*/
WebInspector.AuditRules.CombineExternalResourcesRule = function(id, name, type, resourceTypeName, allowedPerDomain)
{
WebInspector.AuditRule.call(this, id, name);
this._type = type;
this._resourceTypeName = resourceTypeName;
this._allowedPerDomain = allowedPerDomain;
}
WebInspector.AuditRules.CombineExternalResourcesRule.prototype = {
/**
* @param {!Array.<!WebInspector.NetworkRequest>} requests
* @param {!WebInspector.AuditRuleResult} result
* @param {function(WebInspector.AuditRuleResult)} callback
* @param {!WebInspector.Progress} progress
*/
doRun: function(requests, result, callback, progress)
{
var domainToResourcesMap = WebInspector.AuditRules.getDomainToResourcesMap(requests, [this._type], false);
var penalizedResourceCount = 0;
// TODO: refactor according to the chosen i18n approach
var summary = result.addChild("", true);
for (var domain in domainToResourcesMap) {
var domainResources = domainToResourcesMap[domain];
var extraResourceCount = domainResources.length - this._allowedPerDomain;
if (extraResourceCount <= 0)
continue;
penalizedResourceCount += extraResourceCount - 1;
summary.addChild(String.sprintf("%d %s resources served from %s.", domainResources.length, this._resourceTypeName, WebInspector.AuditRuleResult.resourceDomain(domain)));
result.violationCount += domainResources.length;
}
if (!penalizedResourceCount)
return callback(null);
summary.value = "There are multiple resources served from same domain. Consider combining them into as few files as possible.";
callback(result);
},
__proto__: WebInspector.AuditRule.prototype
}
/**
* @constructor
* @extends {WebInspector.AuditRules.CombineExternalResourcesRule}
*/
WebInspector.AuditRules.CombineJsResourcesRule = function(allowedPerDomain) {
WebInspector.AuditRules.CombineExternalResourcesRule.call(this, "page-externaljs", "Combine external JavaScript", WebInspector.resourceTypes.Script, "JavaScript", allowedPerDomain);
}
WebInspector.AuditRules.CombineJsResourcesRule.prototype = {
__proto__: WebInspector.AuditRules.CombineExternalResourcesRule.prototype
}
/**
* @constructor
* @extends {WebInspector.AuditRules.CombineExternalResourcesRule}
*/
WebInspector.AuditRules.CombineCssResourcesRule = function(allowedPerDomain) {
WebInspector.AuditRules.CombineExternalResourcesRule.call(this, "page-externalcss", "Combine external CSS", WebInspector.resourceTypes.Stylesheet, "CSS", allowedPerDomain);
}
WebInspector.AuditRules.CombineCssResourcesRule.prototype = {
__proto__: WebInspector.AuditRules.CombineExternalResourcesRule.prototype
}
/**
* @constructor
* @extends {WebInspector.AuditRule}
*/
WebInspector.AuditRules.MinimizeDnsLookupsRule = function(hostCountThreshold) {
WebInspector.AuditRule.call(this, "network-minimizelookups", "Minimize DNS lookups");
this._hostCountThreshold = hostCountThreshold;
}
WebInspector.AuditRules.MinimizeDnsLookupsRule.prototype = {
/**
* @param {!Array.<!WebInspector.NetworkRequest>} requests
* @param {!WebInspector.AuditRuleResult} result
* @param {function(WebInspector.AuditRuleResult)} callback
* @param {!WebInspector.Progress} progress
*/
doRun: function(requests, result, callback, progress)
{
var summary = result.addChild("");
var domainToResourcesMap = WebInspector.AuditRules.getDomainToResourcesMap(requests, null, false);
for (var domain in domainToResourcesMap) {
if (domainToResourcesMap[domain].length > 1)
continue;
var parsedURL = domain.asParsedURL();
if (!parsedURL)
continue;
if (!parsedURL.host.search(WebInspector.AuditRules.IPAddressRegexp))
continue; // an IP address
summary.addSnippet(domain);
result.violationCount++;
}
if (!summary.children || summary.children.length <= this._hostCountThreshold)
return callback(null);
summary.value = "The following domains only serve one resource each. If possible, avoid the extra DNS lookups by serving these resources from existing domains.";
callback(result);
},
__proto__: WebInspector.AuditRule.prototype
}
/**
* @constructor
* @extends {WebInspector.AuditRule}
*/
WebInspector.AuditRules.ParallelizeDownloadRule = function(optimalHostnameCount, minRequestThreshold, minBalanceThreshold)
{
WebInspector.AuditRule.call(this, "network-parallelizehosts", "Parallelize downloads across hostnames");
this._optimalHostnameCount = optimalHostnameCount;
this._minRequestThreshold = minRequestThreshold;
this._minBalanceThreshold = minBalanceThreshold;
}
WebInspector.AuditRules.ParallelizeDownloadRule.prototype = {
/**
* @param {!Array.<!WebInspector.NetworkRequest>} requests
* @param {!WebInspector.AuditRuleResult} result
* @param {function(WebInspector.AuditRuleResult)} callback
* @param {!WebInspector.Progress} progress
*/
doRun: function(requests, result, callback, progress)
{
function hostSorter(a, b)
{
var aCount = domainToResourcesMap[a].length;
var bCount = domainToResourcesMap[b].length;
return (aCount < bCount) ? 1 : (aCount == bCount) ? 0 : -1;
}
var domainToResourcesMap = WebInspector.AuditRules.getDomainToResourcesMap(
requests,
[WebInspector.resourceTypes.Stylesheet, WebInspector.resourceTypes.Image],
true);
var hosts = [];
for (var url in domainToResourcesMap)
hosts.push(url);
if (!hosts.length)
return callback(null); // no hosts (local file or something)
hosts.sort(hostSorter);
var optimalHostnameCount = this._optimalHostnameCount;
if (hosts.length > optimalHostnameCount)
hosts.splice(optimalHostnameCount);
var busiestHostResourceCount = domainToResourcesMap[hosts[0]].length;
var requestCountAboveThreshold = busiestHostResourceCount - this._minRequestThreshold;
if (requestCountAboveThreshold <= 0)
return callback(null);
var avgResourcesPerHost = 0;
for (var i = 0, size = hosts.length; i < size; ++i)
avgResourcesPerHost += domainToResourcesMap[hosts[i]].length;
// Assume optimal parallelization.
avgResourcesPerHost /= optimalHostnameCount;
avgResourcesPerHost = Math.max(avgResourcesPerHost, 1);
var pctAboveAvg = (requestCountAboveThreshold / avgResourcesPerHost) - 1.0;
var minBalanceThreshold = this._minBalanceThreshold;
if (pctAboveAvg < minBalanceThreshold)
return callback(null);
var requestsOnBusiestHost = domainToResourcesMap[hosts[0]];
var entry = result.addChild(String.sprintf("This page makes %d parallelizable requests to %s. Increase download parallelization by distributing the following requests across multiple hostnames.", busiestHostResourceCount, hosts[0]), true);
for (var i = 0; i < requestsOnBusiestHost.length; ++i)
entry.addURL(requestsOnBusiestHost[i].url);
result.violationCount = requestsOnBusiestHost.length;
callback(result);
},
__proto__: WebInspector.AuditRule.prototype
}
/**
* The reported CSS rule size is incorrect (parsed != original in WebKit),
* so use percentages instead, which gives a better approximation.
* @constructor
* @extends {WebInspector.AuditRule}
*/
WebInspector.AuditRules.UnusedCssRule = function()
{
WebInspector.AuditRule.call(this, "page-unusedcss", "Remove unused CSS rules");
}
WebInspector.AuditRules.UnusedCssRule.prototype = {
/**
* @param {!Array.<!WebInspector.NetworkRequest>} requests
* @param {!WebInspector.AuditRuleResult} result
* @param {function(WebInspector.AuditRuleResult)} callback
* @param {!WebInspector.Progress} progress
*/
doRun: function(requests, result, callback, progress)
{
var self = this;
function evalCallback(styleSheets) {
if (progress.isCanceled())
return;
if (!styleSheets.length)
return callback(null);
var selectors = [];
var testedSelectors = {};
for (var i = 0; i < styleSheets.length; ++i) {
var styleSheet = styleSheets[i];
for (var curRule = 0; curRule < styleSheet.rules.length; ++curRule) {
var selectorText = styleSheet.rules[curRule].selectorText;
if (testedSelectors[selectorText])
continue;
selectors.push(selectorText);
testedSelectors[selectorText] = 1;
}
}
function selectorsCallback(callback, styleSheets, testedSelectors, foundSelectors)
{
if (progress.isCanceled())
return;
var inlineBlockOrdinal = 0;
var totalStylesheetSize = 0;
var totalUnusedStylesheetSize = 0;
var summary;
for (var i = 0; i < styleSheets.length; ++i) {
var styleSheet = styleSheets[i];
var unusedRules = [];
for (var curRule = 0; curRule < styleSheet.rules.length; ++curRule) {
var rule = styleSheet.rules[curRule];
if (!testedSelectors[rule.selectorText] || foundSelectors[rule.selectorText])
continue;
unusedRules.push(rule.selectorText);
}
totalStylesheetSize += styleSheet.rules.length;
totalUnusedStylesheetSize += unusedRules.length;
if (!unusedRules.length)
continue;
var resource = WebInspector.resourceForURL(styleSheet.sourceURL);
var isInlineBlock = resource && resource.request && resource.request.type == WebInspector.resourceTypes.Document;
var url = !isInlineBlock ? WebInspector.AuditRuleResult.linkifyDisplayName(styleSheet.sourceURL) : String.sprintf("Inline block #%d", ++inlineBlockOrdinal);
var pctUnused = Math.round(100 * unusedRules.length / styleSheet.rules.length);
if (!summary)
summary = result.addChild("", true);
var entry = summary.addFormatted("%s: %d% is not used by the current page.", url, pctUnused);
for (var j = 0; j < unusedRules.length; ++j)
entry.addSnippet(unusedRules[j]);
result.violationCount += unusedRules.length;
}
if (!totalUnusedStylesheetSize)
return callback(null);
var totalUnusedPercent = Math.round(100 * totalUnusedStylesheetSize / totalStylesheetSize);
summary.value = String.sprintf("%s rules (%d%) of CSS not used by the current page.", totalUnusedStylesheetSize, totalUnusedPercent);
callback(result);
}
var foundSelectors = {};
function queryCallback(boundSelectorsCallback, selector, styleSheets, testedSelectors, nodeId)
{
if (nodeId)
foundSelectors[selector] = true;
if (boundSelectorsCallback)
boundSelectorsCallback(foundSelectors);
}
function documentLoaded(selectors, document) {
var pseudoSelectorRegexp = /::?(?:[\w-]+)(?:\(.*?\))?/g;
for (var i = 0; i < selectors.length; ++i) {
if (progress.isCanceled())
return;
var effectiveSelector = selectors[i].replace(pseudoSelectorRegexp, "");
WebInspector.domAgent.querySelector(document.id, effectiveSelector, queryCallback.bind(null, i === selectors.length - 1 ? selectorsCallback.bind(null, callback, styleSheets, testedSelectors) : null, selectors[i], styleSheets, testedSelectors));
}
}
WebInspector.domAgent.requestDocument(documentLoaded.bind(null, selectors));
}
function styleSheetCallback(styleSheets, sourceURL, continuation, styleSheet)
{
if (progress.isCanceled())
return;
if (styleSheet) {
styleSheet.sourceURL = sourceURL;
styleSheets.push(styleSheet);
}
if (continuation)
continuation(styleSheets);
}
function allStylesCallback(error, styleSheetInfos)
{
if (progress.isCanceled())
return;
if (error || !styleSheetInfos || !styleSheetInfos.length)
return evalCallback([]);
var styleSheets = [];
for (var i = 0; i < styleSheetInfos.length; ++i) {
var info = styleSheetInfos[i];
WebInspector.CSSStyleSheet.createForId(info.styleSheetId, styleSheetCallback.bind(null, styleSheets, info.sourceURL, i == styleSheetInfos.length - 1 ? evalCallback : null));
}
}
CSSAgent.getAllStyleSheets(allStylesCallback);
},
__proto__: WebInspector.AuditRule.prototype
}
/**
* @constructor
* @extends {WebInspector.AuditRule}
*/
WebInspector.AuditRules.CacheControlRule = function(id, name)
{
WebInspector.AuditRule.call(this, id, name);
}
WebInspector.AuditRules.CacheControlRule.MillisPerMonth = 1000 * 60 * 60 * 24 * 30;
WebInspector.AuditRules.CacheControlRule.prototype = {
/**
* @param {!Array.<!WebInspector.NetworkRequest>} requests
* @param {!WebInspector.AuditRuleResult} result
* @param {function(WebInspector.AuditRuleResult)} callback
* @param {!WebInspector.Progress} progress
*/
doRun: function(requests, result, callback, progress)
{
var cacheableAndNonCacheableResources = this._cacheableAndNonCacheableResources(requests);
if (cacheableAndNonCacheableResources[0].length)
this.runChecks(cacheableAndNonCacheableResources[0], result);
this.handleNonCacheableResources(cacheableAndNonCacheableResources[1], result);
callback(result);
},
handleNonCacheableResources: function(requests, result)
{
},
_cacheableAndNonCacheableResources: function(requests)
{
var processedResources = [[], []];
for (var i = 0; i < requests.length; ++i) {
var request = requests[i];
if (!this.isCacheableResource(request))
continue;
if (this._isExplicitlyNonCacheable(request))
processedResources[1].push(request);
else
processedResources[0].push(request);
}
return processedResources;
},
execCheck: function(messageText, requestCheckFunction, requests, result)
{
var requestCount = requests.length;
var urls = [];
for (var i = 0; i < requestCount; ++i) {
if (requestCheckFunction.call(this, requests[i]))
urls.push(requests[i].url);
}
if (urls.length) {
var entry = result.addChild(messageText, true);
entry.addURLs(urls);
result.violationCount += urls.length;
}
},
freshnessLifetimeGreaterThan: function(request, timeMs)
{
var dateHeader = this.responseHeader(request, "Date");
if (!dateHeader)
return false;
var dateHeaderMs = Date.parse(dateHeader);
if (isNaN(dateHeaderMs))
return false;
var freshnessLifetimeMs;
var maxAgeMatch = this.responseHeaderMatch(request, "Cache-Control", "max-age=(\\d+)");
if (maxAgeMatch)
freshnessLifetimeMs = (maxAgeMatch[1]) ? 1000 * maxAgeMatch[1] : 0;
else {
var expiresHeader = this.responseHeader(request, "Expires");
if (expiresHeader) {
var expDate = Date.parse(expiresHeader);
if (!isNaN(expDate))
freshnessLifetimeMs = expDate - dateHeaderMs;
}
}
return (isNaN(freshnessLifetimeMs)) ? false : freshnessLifetimeMs > timeMs;
},
responseHeader: function(request, header)
{
return request.responseHeaderValue(header);
},
hasResponseHeader: function(request, header)
{
return request.responseHeaderValue(header) !== undefined;
},
isCompressible: function(request)
{
return request.type.isTextType();
},
isPubliclyCacheable: function(request)
{
if (this._isExplicitlyNonCacheable(request))
return false;
if (this.responseHeaderMatch(request, "Cache-Control", "public"))
return true;
return request.url.indexOf("?") == -1 && !this.responseHeaderMatch(request, "Cache-Control", "private");
},
responseHeaderMatch: function(request, header, regexp)
{
return request.responseHeaderValue(header)
? request.responseHeaderValue(header).match(new RegExp(regexp, "im"))
: undefined;
},
hasExplicitExpiration: function(request)
{
return this.hasResponseHeader(request, "Date") &&
(this.hasResponseHeader(request, "Expires") || this.responseHeaderMatch(request, "Cache-Control", "max-age"));
},
_isExplicitlyNonCacheable: function(request)
{
var hasExplicitExp = this.hasExplicitExpiration(request);
return this.responseHeaderMatch(request, "Cache-Control", "(no-cache|no-store|must-revalidate)") ||
this.responseHeaderMatch(request, "Pragma", "no-cache") ||
(hasExplicitExp && !this.freshnessLifetimeGreaterThan(request, 0)) ||
(!hasExplicitExp && request.url && request.url.indexOf("?") >= 0) ||
(!hasExplicitExp && !this.isCacheableResource(request));
},
isCacheableResource: function(request)
{
return request.statusCode !== undefined && WebInspector.AuditRules.CacheableResponseCodes[request.statusCode];
},
__proto__: WebInspector.AuditRule.prototype
}
/**
* @constructor
* @extends {WebInspector.AuditRules.CacheControlRule}
*/
WebInspector.AuditRules.BrowserCacheControlRule = function()
{
WebInspector.AuditRules.CacheControlRule.call(this, "http-browsercache", "Leverage browser caching");
}
WebInspector.AuditRules.BrowserCacheControlRule.prototype = {
handleNonCacheableResources: function(requests, result)
{
if (requests.length) {
var entry = result.addChild("The following resources are explicitly non-cacheable. Consider making them cacheable if possible:", true);
result.violationCount += requests.length;
for (var i = 0; i < requests.length; ++i)
entry.addURL(requests[i].url);
}
},
runChecks: function(requests, result, callback)
{
this.execCheck("The following resources are missing a cache expiration. Resources that do not specify an expiration may not be cached by browsers:",
this._missingExpirationCheck, requests, result);
this.execCheck("The following resources specify a \"Vary\" header that disables caching in most versions of Internet Explorer:",
this._varyCheck, requests, result);
this.execCheck("The following cacheable resources have a short freshness lifetime:",
this._oneMonthExpirationCheck, requests, result);
// Unable to implement the favicon check due to the WebKit limitations.
this.execCheck("To further improve cache hit rate, specify an expiration one year in the future for the following cacheable resources:",
this._oneYearExpirationCheck, requests, result);
},
_missingExpirationCheck: function(request)
{
return this.isCacheableResource(request) && !this.hasResponseHeader(request, "Set-Cookie") && !this.hasExplicitExpiration(request);
},
_varyCheck: function(request)
{
var varyHeader = this.responseHeader(request, "Vary");
if (varyHeader) {
varyHeader = varyHeader.replace(/User-Agent/gi, "");
varyHeader = varyHeader.replace(/Accept-Encoding/gi, "");
varyHeader = varyHeader.replace(/[, ]*/g, "");
}
return varyHeader && varyHeader.length && this.isCacheableResource(request) && this.freshnessLifetimeGreaterThan(request, 0);
},
_oneMonthExpirationCheck: function(request)
{
return this.isCacheableResource(request) &&
!this.hasResponseHeader(request, "Set-Cookie") &&
!this.freshnessLifetimeGreaterThan(request, WebInspector.AuditRules.CacheControlRule.MillisPerMonth) &&
this.freshnessLifetimeGreaterThan(request, 0);
},
_oneYearExpirationCheck: function(request)
{
return this.isCacheableResource(request) &&
!this.hasResponseHeader(request, "Set-Cookie") &&
!this.freshnessLifetimeGreaterThan(request, 11 * WebInspector.AuditRules.CacheControlRule.MillisPerMonth) &&
this.freshnessLifetimeGreaterThan(request, WebInspector.AuditRules.CacheControlRule.MillisPerMonth);
},
__proto__: WebInspector.AuditRules.CacheControlRule.prototype
}
/**
* @constructor
* @extends {WebInspector.AuditRules.CacheControlRule}
*/
WebInspector.AuditRules.ProxyCacheControlRule = function() {
WebInspector.AuditRules.CacheControlRule.call(this, "http-proxycache", "Leverage proxy caching");
}
WebInspector.AuditRules.ProxyCacheControlRule.prototype = {
runChecks: function(requests, result, callback)
{
this.execCheck("Resources with a \"?\" in the URL are not cached by most proxy caching servers:",
this._questionMarkCheck, requests, result);
this.execCheck("Consider adding a \"Cache-Control: public\" header to the following resources:",
this._publicCachingCheck, requests, result);
this.execCheck("The following publicly cacheable resources contain a Set-Cookie header. This security vulnerability can cause cookies to be shared by multiple users.",
this._setCookieCacheableCheck, requests, result);
},
_questionMarkCheck: function(request)
{
return request.url.indexOf("?") >= 0 && !this.hasResponseHeader(request, "Set-Cookie") && this.isPubliclyCacheable(request);
},
_publicCachingCheck: function(request)
{
return this.isCacheableResource(request) &&
!this.isCompressible(request) &&
!this.responseHeaderMatch(request, "Cache-Control", "public") &&
!this.hasResponseHeader(request, "Set-Cookie");
},
_setCookieCacheableCheck: function(request)
{
return this.hasResponseHeader(request, "Set-Cookie") && this.isPubliclyCacheable(request);
},
__proto__: WebInspector.AuditRules.CacheControlRule.prototype
}
/**
* @constructor
* @extends {WebInspector.AuditRule}
*/
WebInspector.AuditRules.ImageDimensionsRule = function()
{
WebInspector.AuditRule.call(this, "page-imagedims", "Specify image dimensions");
}
WebInspector.AuditRules.ImageDimensionsRule.prototype = {
/**
* @param {!Array.<!WebInspector.NetworkRequest>} requests
* @param {!WebInspector.AuditRuleResult} result
* @param {function(WebInspector.AuditRuleResult)} callback
* @param {!WebInspector.Progress} progress
*/
doRun: function(requests, result, callback, progress)
{
var urlToNoDimensionCount = {};
function doneCallback()
{
for (var url in urlToNoDimensionCount) {
var entry = entry || result.addChild("A width and height should be specified for all images in order to speed up page display. The following image(s) are missing a width and/or height:", true);
var format = "%r";
if (urlToNoDimensionCount[url] > 1)
format += " (%d uses)";
entry.addFormatted(format, url, urlToNoDimensionCount[url]);
result.violationCount++;
}
callback(entry ? result : null);
}
function imageStylesReady(imageId, styles, isLastStyle, computedStyle)
{
if (progress.isCanceled())
return;
const node = WebInspector.domAgent.nodeForId(imageId);
var src = node.getAttribute("src");
if (!src.asParsedURL()) {
for (var frameOwnerCandidate = node; frameOwnerCandidate; frameOwnerCandidate = frameOwnerCandidate.parentNode) {
if (frameOwnerCandidate.baseURL) {
var completeSrc = WebInspector.ParsedURL.completeURL(frameOwnerCandidate.baseURL, src);
break;
}
}
}
if (completeSrc)
src = completeSrc;
if (computedStyle.getPropertyValue("position") === "absolute") {
if (isLastStyle)
doneCallback();
return;
}
if (styles.attributesStyle) {
var widthFound = !!styles.attributesStyle.getLiveProperty("width");
var heightFound = !!styles.attributesStyle.getLiveProperty("height");
}
var inlineStyle = styles.inlineStyle;
if (inlineStyle) {
if (inlineStyle.getPropertyValue("width") !== "")
widthFound = true;
if (inlineStyle.getPropertyValue("height") !== "")
heightFound = true;
}
for (var i = styles.matchedCSSRules.length - 1; i >= 0 && !(widthFound && heightFound); --i) {
var style = styles.matchedCSSRules[i].style;
if (style.getPropertyValue("width") !== "")
widthFound = true;
if (style.getPropertyValue("height") !== "")
heightFound = true;
}
if (!widthFound || !heightFound) {
if (src in urlToNoDimensionCount)
++urlToNoDimensionCount[src];
else
urlToNoDimensionCount[src] = 1;
}
if (isLastStyle)
doneCallback();
}
function getStyles(nodeIds)
{
if (progress.isCanceled())
return;
var targetResult = {};
function inlineCallback(inlineStyle, attributesStyle)
{
targetResult.inlineStyle = inlineStyle;
targetResult.attributesStyle = attributesStyle;
}
function matchedCallback(result)
{
if (result)
targetResult.matchedCSSRules = result.matchedCSSRules;
}
if (!nodeIds || !nodeIds.length)
doneCallback();
for (var i = 0; nodeIds && i < nodeIds.length; ++i) {
WebInspector.cssModel.getMatchedStylesAsync(nodeIds[i], false, false, matchedCallback);
WebInspector.cssModel.getInlineStylesAsync(nodeIds[i], inlineCallback);
WebInspector.cssModel.getComputedStyleAsync(nodeIds[i], imageStylesReady.bind(null, nodeIds[i], targetResult, i === nodeIds.length - 1));
}
}
function onDocumentAvailable(root)
{
if (progress.isCanceled())
return;
WebInspector.domAgent.querySelectorAll(root.id, "img[src]", getStyles);
}
if (progress.isCanceled())
return;
WebInspector.domAgent.requestDocument(onDocumentAvailable);
},
__proto__: WebInspector.AuditRule.prototype
}
/**
* @constructor
* @extends {WebInspector.AuditRule}
*/
WebInspector.AuditRules.CssInHeadRule = function()
{
WebInspector.AuditRule.call(this, "page-cssinhead", "Put CSS in the document head");
}
WebInspector.AuditRules.CssInHeadRule.prototype = {
/**
* @param {!Array.<!WebInspector.NetworkRequest>} requests
* @param {!WebInspector.AuditRuleResult} result
* @param {function(WebInspector.AuditRuleResult)} callback
* @param {!WebInspector.Progress} progress
*/
doRun: function(requests, result, callback, progress)
{
function evalCallback(evalResult)
{
if (progress.isCanceled())
return;
if (!evalResult)
return callback(null);
var summary = result.addChild("");
var outputMessages = [];
for (var url in evalResult) {
var urlViolations = evalResult[url];
if (urlViolations[0]) {
result.addFormatted("%s style block(s) in the %r body should be moved to the document head.", urlViolations[0], url);
result.violationCount += urlViolations[0];
}
for (var i = 0; i < urlViolations[1].length; ++i)
result.addFormatted("Link node %r should be moved to the document head in %r", urlViolations[1][i], url);
result.violationCount += urlViolations[1].length;
}
summary.value = String.sprintf("CSS in the document body adversely impacts rendering performance.");
callback(result);
}
function externalStylesheetsReceived(root, inlineStyleNodeIds, nodeIds)
{
if (progress.isCanceled())
return;
if (!nodeIds)
return;
var externalStylesheetNodeIds = nodeIds;
var result = null;
if (inlineStyleNodeIds.length || externalStylesheetNodeIds.length) {
var urlToViolationsArray = {};
var externalStylesheetHrefs = [];
for (var j = 0; j < externalStylesheetNodeIds.length; ++j) {
var linkNode = WebInspector.domAgent.nodeForId(externalStylesheetNodeIds[j]);
var completeHref = WebInspector.ParsedURL.completeURL(linkNode.ownerDocument.baseURL, linkNode.getAttribute("href"));
externalStylesheetHrefs.push(completeHref || "<empty>");
}
urlToViolationsArray[root.documentURL] = [inlineStyleNodeIds.length, externalStylesheetHrefs];
result = urlToViolationsArray;
}
evalCallback(result);
}
function inlineStylesReceived(root, nodeIds)
{
if (progress.isCanceled())
return;
if (!nodeIds)
return;
WebInspector.domAgent.querySelectorAll(root.id, "body link[rel~='stylesheet'][href]", externalStylesheetsReceived.bind(null, root, nodeIds));
}
function onDocumentAvailable(root)
{
if (progress.isCanceled())
return;
WebInspector.domAgent.querySelectorAll(root.id, "body style", inlineStylesReceived.bind(null, root));
}
WebInspector.domAgent.requestDocument(onDocumentAvailable);
},
__proto__: WebInspector.AuditRule.prototype
}
/**
* @constructor
* @extends {WebInspector.AuditRule}
*/
WebInspector.AuditRules.StylesScriptsOrderRule = function()
{
WebInspector.AuditRule.call(this, "page-stylescriptorder", "Optimize the order of styles and scripts");
}
WebInspector.AuditRules.StylesScriptsOrderRule.prototype = {
/**
* @param {!Array.<!WebInspector.NetworkRequest>} requests
* @param {!WebInspector.AuditRuleResult} result
* @param {function(WebInspector.AuditRuleResult)} callback
* @param {!WebInspector.Progress} progress
*/
doRun: function(requests, result, callback, progress)
{
function evalCallback(resultValue)
{
if (progress.isCanceled())
return;
if (!resultValue)
return callback(null);
var lateCssUrls = resultValue[0];
var cssBeforeInlineCount = resultValue[1];
if (lateCssUrls.length) {
var entry = result.addChild("The following external CSS files were included after an external JavaScript file in the document head. To ensure CSS files are downloaded in parallel, always include external CSS before external JavaScript.", true);
entry.addURLs(lateCssUrls);
result.violationCount += lateCssUrls.length;
}
if (cssBeforeInlineCount) {
result.addChild(String.sprintf(" %d inline script block%s found in the head between an external CSS file and another resource. To allow parallel downloading, move the inline script before the external CSS file, or after the next resource.", cssBeforeInlineCount, cssBeforeInlineCount > 1 ? "s were" : " was"));
result.violationCount += cssBeforeInlineCount;
}
callback(result);
}
function cssBeforeInlineReceived(lateStyleIds, nodeIds)
{
if (progress.isCanceled())
return;
if (!nodeIds)
return;
var cssBeforeInlineCount = nodeIds.length;
var result = null;
if (lateStyleIds.length || cssBeforeInlineCount) {
var lateStyleUrls = [];
for (var i = 0; i < lateStyleIds.length; ++i) {
var lateStyleNode = WebInspector.domAgent.nodeForId(lateStyleIds[i]);
var completeHref = WebInspector.ParsedURL.completeURL(lateStyleNode.ownerDocument.baseURL, lateStyleNode.getAttribute("href"));
lateStyleUrls.push(completeHref || "<empty>");
}
result = [ lateStyleUrls, cssBeforeInlineCount ];
}
evalCallback(result);
}
function lateStylesReceived(root, nodeIds)
{
if (progress.isCanceled())
return;
if (!nodeIds)
return;
WebInspector.domAgent.querySelectorAll(root.id, "head link[rel~='stylesheet'][href] ~ script:not([src])", cssBeforeInlineReceived.bind(null, nodeIds));
}
function onDocumentAvailable(root)
{
if (progress.isCanceled())
return;
WebInspector.domAgent.querySelectorAll(root.id, "head script[src] ~ link[rel~='stylesheet'][href]", lateStylesReceived.bind(null, root));
}
WebInspector.domAgent.requestDocument(onDocumentAvailable);
},
__proto__: WebInspector.AuditRule.prototype
}
/**
* @constructor
* @extends {WebInspector.AuditRule}
*/
WebInspector.AuditRules.CSSRuleBase = function(id, name)
{
WebInspector.AuditRule.call(this, id, name);
}
WebInspector.AuditRules.CSSRuleBase.prototype = {
/**
* @param {!Array.<!WebInspector.NetworkRequest>} requests
* @param {!WebInspector.AuditRuleResult} result
* @param {function(WebInspector.AuditRuleResult)} callback
* @param {!WebInspector.Progress} progress
*/
doRun: function(requests, result, callback, progress)
{
CSSAgent.getAllStyleSheets(sheetsCallback.bind(this));
function sheetsCallback(error, headers)
{
if (error)
return callback(null);
if (!headers.length)
return callback(null);
for (var i = 0; i < headers.length; ++i) {
var header = headers[i];
if (header.disabled)
continue; // Do not check disabled stylesheets.
this._visitStyleSheet(header.styleSheetId, i === headers.length - 1 ? finishedCallback : null, result, progress);
}
}
function finishedCallback()
{
callback(result);
}
},
_visitStyleSheet: function(styleSheetId, callback, result, progress)
{
WebInspector.CSSStyleSheet.createForId(styleSheetId, sheetCallback.bind(this));
function sheetCallback(styleSheet)
{
if (progress.isCanceled())
return;
if (!styleSheet) {
if (callback)
callback();
return;
}
this.visitStyleSheet(styleSheet, result);
for (var i = 0; i < styleSheet.rules.length; ++i)
this._visitRule(styleSheet, styleSheet.rules[i], result);
this.didVisitStyleSheet(styleSheet, result);
if (callback)
callback();
}
},
_visitRule: function(styleSheet, rule, result)
{
this.visitRule(styleSheet, rule, result);
var allProperties = rule.style.allProperties;
for (var i = 0; i < allProperties.length; ++i)
this.visitProperty(styleSheet, allProperties[i], result);
this.didVisitRule(styleSheet, rule, result);
},
visitStyleSheet: function(styleSheet, result)
{
// Subclasses can implement.
},
didVisitStyleSheet: function(styleSheet, result)
{
// Subclasses can implement.
},
visitRule: function(styleSheet, rule, result)
{
// Subclasses can implement.
},
didVisitRule: function(styleSheet, rule, result)
{
// Subclasses can implement.
},
visitProperty: function(styleSheet, property, result)
{
// Subclasses can implement.
},
__proto__: WebInspector.AuditRule.prototype
}
/**
* @constructor
* @extends {WebInspector.AuditRules.CSSRuleBase}
*/
WebInspector.AuditRules.VendorPrefixedCSSProperties = function()
{
WebInspector.AuditRules.CSSRuleBase.call(this, "page-vendorprefixedcss", "Use normal CSS property names instead of vendor-prefixed ones");
this._webkitPrefix = "-webkit-";
}
WebInspector.AuditRules.VendorPrefixedCSSProperties.supportedProperties = [
"background-clip", "background-origin", "background-size",
"border-radius", "border-bottom-left-radius", "border-bottom-right-radius", "border-top-left-radius", "border-top-right-radius",
"box-shadow", "box-sizing", "opacity", "text-shadow"
].keySet();
WebInspector.AuditRules.VendorPrefixedCSSProperties.prototype = {
didVisitStyleSheet: function(styleSheet)
{
delete this._styleSheetResult;
},
visitRule: function(rule)
{
this._mentionedProperties = {};
},
didVisitRule: function()
{
delete this._ruleResult;
delete this._mentionedProperties;
},
visitProperty: function(styleSheet, property, result)
{
if (!property.name.startsWith(this._webkitPrefix))
return;
var normalPropertyName = property.name.substring(this._webkitPrefix.length).toLowerCase(); // Start just after the "-webkit-" prefix.
if (WebInspector.AuditRules.VendorPrefixedCSSProperties.supportedProperties[normalPropertyName] && !this._mentionedProperties[normalPropertyName]) {
var style = property.ownerStyle;
var liveProperty = style.getLiveProperty(normalPropertyName);
if (liveProperty && !liveProperty.styleBased)
return; // WebCore can provide normal versions of prefixed properties automatically, so be careful to skip only normal source-based properties.
var rule = style.parentRule;
this._mentionedProperties[normalPropertyName] = true;
if (!this._styleSheetResult)
this._styleSheetResult = result.addChild(rule.sourceURL ? WebInspector.linkifyResourceAsNode(rule.sourceURL) : "<unknown>");
if (!this._ruleResult) {
var anchor = WebInspector.linkifyURLAsNode(rule.sourceURL, rule.selectorText);
anchor.preferredPanel = "resources";
anchor.lineNumber = rule.lineNumberInSource();
this._ruleResult = this._styleSheetResult.addChild(anchor);
}
++result.violationCount;
this._ruleResult.addSnippet(String.sprintf("\"" + this._webkitPrefix + "%s\" is used, but \"%s\" is supported.", normalPropertyName, normalPropertyName));
}
},
__proto__: WebInspector.AuditRules.CSSRuleBase.prototype
}
/**
* @constructor
* @extends {WebInspector.AuditRule}
*/
WebInspector.AuditRules.CookieRuleBase = function(id, name)
{
WebInspector.AuditRule.call(this, id, name);
}
WebInspector.AuditRules.CookieRuleBase.prototype = {
/**
* @param {!Array.<!WebInspector.NetworkRequest>} requests
* @param {!WebInspector.AuditRuleResult} result
* @param {function(WebInspector.AuditRuleResult)} callback
* @param {!WebInspector.Progress} progress
*/
doRun: function(requests, result, callback, progress)
{
var self = this;
function resultCallback(receivedCookies) {
if (progress.isCanceled())
return;
self.processCookies(receivedCookies, requests, result);
callback(result);
}
WebInspector.Cookies.getCookiesAsync(resultCallback);
},
mapResourceCookies: function(requestsByDomain, allCookies, callback)
{
for (var i = 0; i < allCookies.length; ++i) {
for (var requestDomain in requestsByDomain) {
if (WebInspector.Cookies.cookieDomainMatchesResourceDomain(allCookies[i].domain(), requestDomain))
this._callbackForResourceCookiePairs(requestsByDomain[requestDomain], allCookies[i], callback);
}
}
},
_callbackForResourceCookiePairs: function(requests, cookie, callback)
{
if (!requests)
return;
for (var i = 0; i < requests.length; ++i) {
if (WebInspector.Cookies.cookieMatchesResourceURL(cookie, requests[i].url))
callback(requests[i], cookie);
}
},
__proto__: WebInspector.AuditRule.prototype
}
/**
* @constructor
* @extends {WebInspector.AuditRules.CookieRuleBase}
*/
WebInspector.AuditRules.CookieSizeRule = function(avgBytesThreshold)
{
WebInspector.AuditRules.CookieRuleBase.call(this, "http-cookiesize", "Minimize cookie size");
this._avgBytesThreshold = avgBytesThreshold;
this._maxBytesThreshold = 1000;
}
WebInspector.AuditRules.CookieSizeRule.prototype = {
_average: function(cookieArray)
{
var total = 0;
for (var i = 0; i < cookieArray.length; ++i)
total += cookieArray[i].size();
return cookieArray.length ? Math.round(total / cookieArray.length) : 0;
},
_max: function(cookieArray)
{
var result = 0;
for (var i = 0; i < cookieArray.length; ++i)
result = Math.max(cookieArray[i].size(), result);
return result;
},
processCookies: function(allCookies, requests, result)
{
function maxSizeSorter(a, b)
{
return b.maxCookieSize - a.maxCookieSize;
}
function avgSizeSorter(a, b)
{
return b.avgCookieSize - a.avgCookieSize;
}
var cookiesPerResourceDomain = {};
function collectorCallback(request, cookie)
{
var cookies = cookiesPerResourceDomain[request.parsedURL.host];
if (!cookies) {
cookies = [];
cookiesPerResourceDomain[request.parsedURL.host] = cookies;
}
cookies.push(cookie);
}
if (!allCookies.length)
return;
var sortedCookieSizes = [];
var domainToResourcesMap = WebInspector.AuditRules.getDomainToResourcesMap(requests,
null,
true);
var matchingResourceData = {};
this.mapResourceCookies(domainToResourcesMap, allCookies, collectorCallback.bind(this));
for (var requestDomain in cookiesPerResourceDomain) {
var cookies = cookiesPerResourceDomain[requestDomain];
sortedCookieSizes.push({
domain: requestDomain,
avgCookieSize: this._average(cookies),
maxCookieSize: this._max(cookies)
});
}
var avgAllCookiesSize = this._average(allCookies);
var hugeCookieDomains = [];
sortedCookieSizes.sort(maxSizeSorter);
for (var i = 0, len = sortedCookieSizes.length; i < len; ++i) {
var maxCookieSize = sortedCookieSizes[i].maxCookieSize;
if (maxCookieSize > this._maxBytesThreshold)
hugeCookieDomains.push(WebInspector.AuditRuleResult.resourceDomain(sortedCookieSizes[i].domain) + ": " + Number.bytesToString(maxCookieSize));
}
var bigAvgCookieDomains = [];
sortedCookieSizes.sort(avgSizeSorter);
for (var i = 0, len = sortedCookieSizes.length; i < len; ++i) {
var domain = sortedCookieSizes[i].domain;
var avgCookieSize = sortedCookieSizes[i].avgCookieSize;
if (avgCookieSize > this._avgBytesThreshold && avgCookieSize < this._maxBytesThreshold)
bigAvgCookieDomains.push(WebInspector.AuditRuleResult.resourceDomain(domain) + ": " + Number.bytesToString(avgCookieSize));
}
result.addChild(String.sprintf("The average cookie size for all requests on this page is %s", Number.bytesToString(avgAllCookiesSize)));
var message;
if (hugeCookieDomains.length) {
var entry = result.addChild("The following domains have a cookie size in excess of 1KB. This is harmful because requests with cookies larger than 1KB typically cannot fit into a single network packet.", true);
entry.addURLs(hugeCookieDomains);
result.violationCount += hugeCookieDomains.length;
}
if (bigAvgCookieDomains.length) {
var entry = result.addChild(String.sprintf("The following domains have an average cookie size in excess of %d bytes. Reducing the size of cookies for these domains can reduce the time it takes to send requests.", this._avgBytesThreshold), true);
entry.addURLs(bigAvgCookieDomains);
result.violationCount += bigAvgCookieDomains.length;
}
},
__proto__: WebInspector.AuditRules.CookieRuleBase.prototype
}
/**
* @constructor
* @extends {WebInspector.AuditRules.CookieRuleBase}
*/
WebInspector.AuditRules.StaticCookielessRule = function(minResources)
{
WebInspector.AuditRules.CookieRuleBase.call(this, "http-staticcookieless", "Serve static content from a cookieless domain");
this._minResources = minResources;
}
WebInspector.AuditRules.StaticCookielessRule.prototype = {
processCookies: function(allCookies, requests, result)
{
var domainToResourcesMap = WebInspector.AuditRules.getDomainToResourcesMap(requests,
[WebInspector.resourceTypes.Stylesheet,
WebInspector.resourceTypes.Image],
true);
var totalStaticResources = 0;
for (var domain in domainToResourcesMap)
totalStaticResources += domainToResourcesMap[domain].length;
if (totalStaticResources < this._minResources)
return;
var matchingResourceData = {};
this.mapResourceCookies(domainToResourcesMap, allCookies, this._collectorCallback.bind(this, matchingResourceData));
var badUrls = [];
var cookieBytes = 0;
for (var url in matchingResourceData) {
badUrls.push(url);
cookieBytes += matchingResourceData[url]
}
if (badUrls.length < this._minResources)
return;
var entry = result.addChild(String.sprintf("%s of cookies were sent with the following static resources. Serve these static resources from a domain that does not set cookies:", Number.bytesToString(cookieBytes)), true);
entry.addURLs(badUrls);
result.violationCount = badUrls.length;
},
_collectorCallback: function(matchingResourceData, request, cookie)
{
matchingResourceData[request.url] = (matchingResourceData[request.url] || 0) + cookie.size();
},
__proto__: WebInspector.AuditRules.CookieRuleBase.prototype
}
|
var optionValueKeyMarkdown = require('../markdown/js/properties/optionValueKey').body;
var optionValueKeyProp = {
nameAttr: "optionValueKey",
renderString: optionValueKeyMarkdown
};
module.exports = optionValueKeyProp;
|
// ----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// ----------------------------------------------------------------------------
module.exports = function () {
return {
sql: "CREATE TABLE [__types] ([table] TEXT, [name] TEXT, [type] TEXT)"
};
};
|
module.exports = {
description: 'auto-indents with indent: true',
options: {
moduleName: 'foo',
indent: true
}
};
|
TEST('GRAPHICSMAGICK_READ_METADATA', (check) => {
GRAPHICSMAGICK_READ_METADATA('UPPERCASE-CORE/sample.png', (metadata) => {
console.log(metadata);
});
GRAPHICSMAGICK_READ_METADATA('UPPERCASE-CORE/sample.png', {
error : () => {
console.log('ERROR!');
},
success : (metadata) => {
console.log(metadata);
}
});
});
|
/**
* Created by Pencroff on 04-Sep-16.
*/
window.test = {
id: '384A61CA-DA2E-4FD2-A113-080010D4A42B',
name: 'object literal iteration',
description: 'Performance case for iteration object properties. Comparison for StackOverflow question: How do I loop through or enumerate a JavaScript object? (<a href=\"https://goo.gl/0QEGHB\" target=\"_blank\">link</a>)',
tags: ['object', 'iteration', 'basic'],
url: 'tests/object-iteration.js',
fill: function (suite) {
return new Promise(function (resolve) {
var result, a, b, c;
var obj;
suite.add('by Object.keys', function () {
result = '';
var arr = Object.keys(obj);
var len = arr.length;
var i, key;
for (i = 0; i < len; i += 1) {
key = arr[i];
result += key + ': ' + obj[key] + ' ';
}
a = b;
b = c;
c = result;
});
suite.add('by Object.keys with native forEach', function () {
result = '';
Object.keys(obj).forEach(function(key) {
result += key + ': ' + obj[key] + ' ';
});
a = b;
b = c;
c = result;
});
suite.add('by for..in', function () {
result = '';
for (var key in obj) {
result += key + ': ' + obj[key] + ' ';
}
a = b;
b = c;
c = result;
});
suite.add('by for..in and hasOwnProperty', function () {
result = '';
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
result += key + ': ' + obj[key] + ' ';
}
}
a = b;
b = c;
c = result;
});
suite.add('lodash v4.15.0 - _.forEach', function () {
result = '';
_.forEach(obj, function (value, key) {
result += key + ': ' + value + ' ';
});
a = b;
b = c;
c = result;
});
suite.on('start cycle', function () {
var len = 100;
var i;
obj = {};
for (i = 0; i < len; i += 1) {
obj['prop'+i] = 'value' + i;
}
});
suite.on('cycle', function () {
console.log('cycle', result);
});
resolve(suite);
});
}
};
|
(function(){
up.Font = Font;
up.Font.NORMAL = "normal";
up.Font.ITALIC = "italic";
up.Font.OBLIQUE = "oblique";
up.Font.BOLD = "bold";
up.Font.SMALL_CAPS = "small-caps";
function Font(_family, _size, _lineHeight, _style, _weight, _variant){
this.family = "Arial";
this.size = 12;
this.lineHeight = 12;
this.style = up.Font.NORMAL;
this.variant = up.Font.NORMAL;
this.weight = up.Font.NORMAL;
if(_family!=null) this.family = _family;
if(_size!=null) this.size = _size;
if(_lineHeight!=null) this.lineHeight = _lineHeight;
else this.lineHeight = this.size;
if(_style!=null) this.style = _style;
if(_weight!=null) this.weight = _weight;
if(_variant!=null) this.variant = _variant;
}//constructor
Font.prototype.toCssString = function(){
return this.style+' '+this.variant+' '+this.weight+' '+this.size+'px/'+this.lineHeight+'px '+this.family+' ';
}//toCssString
Font.loadFont = function(_name, _url){
var fontFace =
"@font-face {"+
"font-family: '"+_name+"';"+
"src: url('"+_url+"/"+_name+".ttf') format('truetype');"+
"}";
var styleNode = document.createElement('style');
styleNode.type = "text/css";
if(styleNode.styleSheet){
styleNode.styleSheet.cssText = fontFace;
}else{
styleNode.appendChild(document.createTextNode(fontFace));
}
document.head.appendChild(styleNode);
}//loadFont
})(); |
import Ember from 'ember';
export default Ember.Component.extend({
classNames: ['pending-invitation']
});
|
/* Browser holds the browser main object */
function Browser(container){
this.$container = $(container);
this.ready = false;
this.rows = [];
this.data = Global.data;
this.parser = Global.parser;
this.offline = window.location.hash == '#random' || window.location.hash == '#disney';
this.resizeTimer;
this.scrollTimer;
this.animationDuration = Global.animationDuration;
this.allowAnimation = Global.allowAnimation;
this.hiddenWidth = 5;
this.entityLimit = Global.data.entityLimit;
this.$rowHolder;
this.$scrollUpButton;
this.$scrollDownButton;
this.init();
}
/* INIT */
/* init browser */
Browser.prototype.init = function(){
this.build();
}
/* build browser html */
Browser.prototype.build = function(){
this.$rowHolder = $(document.createElement('div')).addClass('row-holder');
this.$container.append(this.$rowHolder);
this.$scrollUpButton = $(document.createElement('div')).attr('id','scrollup-button').addClass('scrollButton');
this.$scrollDownButton = $(document.createElement('div')).attr('id','scrolldown-button').addClass('scrollButton');
this.$container.append(this.$scrollUpButton);
this.$container.append(this.$scrollDownButton);
this.$container.attr('unselectable','on')
.css({'-moz-user-select':'-moz-none',
'-moz-user-select':'none',
'-o-user-select':'none',
'-khtml-user-select':'none',
'-webkit-user-select':'none',
'-ms-user-select':'none',
'user-select':'none'
}).bind('selectstart', function(){ return false; });
}
/* init interactions */
Browser.prototype.initInteraction = function(){
/* listen to window resize*/
$(window).resize(this.resize.bind(this));
$(window).on('deviceorientation',this.resize.bind(this));
/* listen to topbar*/
$('#topbar').on('click',this.scrollTo.bind(this,0));
/* listen to scrollupbutton*/
this.$scrollUpButton.on('click',this.scrollRowUp.bind(this));
/* listen to scrolldownbutton*/
this.$scrollDownButton.on('click',this.scrollRowDown.bind(this));
/* listen to window scroll */
$(window).scroll(this.scrollEvent.bind(this));
this.ready = true;
}
/* listen to window resize */
Browser.prototype.resize = function(){
clearTimeout(this.resizeTimer);
this.resizeTimer = setTimeout(function(){
for (var i=0, len = this.rows.length; i<len;i++){
this.rows[i].calcMinWidth(false);
this.rows[i].calcWidth();
this.rows[i].zoomAction(1, 0);
if(this.rows[i].currentEntity){
this.rows[i].growEntity(this.rows[i].currentEntity);
}
this.dockRows();
}
}.bind(this),250);
}
/* User is updated (login/logout) */
Browser.prototype.userUpdate =function(){
for(var i =0, len = this.rows.length; i< len; i++){
for (var j =0, elen = this.rows[i].entities.length; j<elen; j++){
if (this.rows[i].entities[j].comments) { this.rows[i].entities[j].comments.userUpdate(); }
if (this.rows[i].entities[j].collections){ this.rows[i].entities[j].collections.userUpdate(); }
}
}
}
/* clear browser */
Browser.prototype.clear = function(){
while(this.rows.length){
this.removeRow(this.rows[0]);
}
this.rows = [];
$('body').css('background-image','none');
this.$rowHolder.empty();
}
/* get container */
Browser.prototype.getContainer = function(){
return this.$container;
}
/* ROWS */
/* add a new row */
Browser.prototype.addRow = function(entity){
// if entity row is not the last row, remove previous rows
if (entity){
var position = this.rows.indexOf(entity.getRow());
var len = this.rows.length;
while(position < --len){
this.rows[len].remove();
this.rows.splice(len,1);
}
} else{
/* clear browser */
this.clear();
}
var row = new Row(this, entity);
this.rows.push(row);
this.$rowHolder.append(row.getContainer());
this.dockRows();
return row;
}
/* remove a row */
Browser.prototype.removeRow = function(row){
row.remove();
var position = this.rows.indexOf(row);
this.rows.splice(position,1);
}
/* DOCK ROWS */
Browser.prototype.dockRows = function(){
for(var i=0,len = this.rows.length; i<len; i++){
if (i < len - 2){
this.rows[i].dock();
} else{
this.rows[i].undock();
}
}
}
// /* INIT */
// Browser.prototype.getData = function(){
// return this.data;
// }
/* Add a row with related entities for an entity */
Browser.prototype.addRelated = function(entity){
console.log('add related');
if (this.offline) { this.addRandom(entity); return; }
var row = this.addRow(entity);
if (entity.isCollection()){
// load collection
this.data.getCollection(entity.data.uid.replace('Collection:',''),row.addResults.bind(row));
} else{
// check for preloaded related entities
if (entity.data.relatedEntities){
// reuse preloaded related entities
row.addResults({data:entity.data.relatedEntities});
} else{
// request new related entities
this.data.getRelated(entity.data.uid,0,this.entityLimit,row.addResults.bind(row),row, true);
}
}
}
/* Add a row with search results for some keywords */
Browser.prototype.addSearch = function(keywords){
if (this.offline) { this.addRandom(); return; }
var row = this.addRow();
if (keywords == 'My collections'){
//row.relatedness = 'My collections';
row.relatedness = 'Search';
Global.data.getSearchCollections(Global.search.keywords,0,this.entityLimit,row.addCollectionResults.bind(row),row.finishedLoading.bind(row));
} else{
if (keywords.indexOf('Collection:')==0){
//row.relatedness = 'Collection';
row.relatedness = 'Search';
Global.data.getSearchCollections(Global.search.keywords,0,this.entityLimit,row.addCollectionResults.bind(row),row.finishedLoading.bind(row));
} else
{ if (keywords.indexOf('Entity:')==0){
row.relatedness = 'Search';
var entity = new Entity(this);
entity.setData(new DataEntity());
row.entity = entity;
row.entity.data.uid = (Global.search.keywords.replace('Entity:',''));
console.log(row.entity.data);
Global.data.getEntity(row.entity.data.uid,row.addResults.bind(row),true);
} else{
row.relatedness = 'Search';
this.data.getSearch(keywords,0,this.entityLimit,row.addResults.bind(row));
}
}
}
}
/* Add a row with a manual selected entity/entities from a collection */
Browser.prototype.addEntities = function(entities){
var row = this.addRow();
row.relatedness = 'Collection';
for(var i =0, len = entities.length; i< len; i++){
var entity = new Entity(this);
entity.setData(entities[i]);
if (!row.hasEntity(entity)){
if (!row.addEntity(entity)){
break;
}
}
}
row.finishedLoading();
if (entities.length == 1){
row.growEntity(row.entities[0],true);
}
}
/* dev: add random entities */
Browser.prototype.addRandom = function(entity){
var row = this.addRow(entity);
setTimeout(function(){
for(var i =0; i< 10 + Math.random() * 15; i++){
var entity = new Entity(this);
entity.setData(row.getBrowser().parser.populateEntityData({}));
if (!row.hasEntity(entity)){
if (!row.addEntity(entity)){
break;
}
}
}
row.finishedLoading();
}.bind(this), 400);
if (entity && entity.status == entity.STATUS_INROW){
this.scrollToBottom();
}
}
/* SCROLLING */
/* scroll to bottom */
Browser.prototype.scrollToBottom = function(){
if ($('body').hasClass('scrolling') || $('body').hasClass('drag-scrolling')){ return; }
this.scrollTo(document.body.scrollHeight);
}
/* scroll vertically a certain amount */
Browser.prototype.scrollBy = function(scroll){
if ($('body').hasClass('scrolling')){ return; }
window.scrollBy(0,scroll);
}
/* scroll vertical to a certain scrolltop position */
Browser.prototype.scrollTo = function(scrollTop){
if ($('body').hasClass('scrolling')){ return; }
if ($(window).scrollTop() == scrollTop){ return;}
$('body').addClass('scrolling');
if (this.allowAnimation){
$('html, body').stop().animate({
scrollTop: scrollTop
}, this.animationDuration, function(){
$('body').removeClass('scrolling');
});
} else{
$('html, body').scrollTop(scrollTop);
$('body').removeClass('scrolling');
}
}
/* scroll up a row or a screen (?) */
Browser.prototype.scrollRowUp = function(){
var newTop = 0;
var scrollTop = $(window).scrollTop();
var position;
var contentTop = $('#content').position().top;
for (var i=0, len = this.rows.length; i <len; i++){
position = this.rows[i].getContainer().position()
if (position.top + contentTop < scrollTop){
newTop = position.top + contentTop;
}
}
this.scrollTo(newTop - $('#topbar').height());
}
/* scroll up a row */
Browser.prototype.scrollRowDown = function(){
var newTop = 0;
var scrollTop = $(window).scrollTop();
var position;
var topbarHeight = $('#topbar').height();
var contentTop = $('#content').position().top;
for (var i=0, len = this.rows.length; i <len; i++){
position = this.rows[i].getContainer().position();
if (position.top + contentTop > scrollTop + topbarHeight){
newTop = position.top + contentTop;
break;
}
}
if(!newTop){
newTop = position.top;
}
this.scrollTo(newTop - topbarHeight);
}
/* listen to browser scroll, change scroll button colors */
Browser.prototype.scrollEvent = function(){
clearTimeout(this.scrollTimer);
this.scrollTimer = setTimeout(this.checkScroll.bind(this),200);
}
Browser.prototype.checkScroll = function(){
/* show/hide scroll buttons */
var scrollTop = $(window).scrollTop();
if (scrollTop > 50){
this.$scrollUpButton.show();
this.$scrollDownButton.show();
}
/* get prev/next items to set scroll button border colors */
//if (this.rows.length < 1){ return;}
var prevRow = false, nextRow = false;
var position;
var topbarHeight = $('#topbar').height();
var contentTop = $('#content').position().top;
for (var i=0, len = this.rows.length; i <len; i++){
position = this.rows[i].getContainer().position();
if (position.top + contentTop > scrollTop){
if (i < this.rows.length - 1){
nextRow = this.rows[i+1];
} else{
nextRow = false;
}
if (!prevRow && scrollTop < 100){
nextRow = this.rows[0];
}
break;
}
prevRow = this.rows[i];
}
this.$scrollUpButton.removeClass(this.getBorderClass.bind(this));
this.$scrollUpButton.addClass(prevRow ? (prevRow.currentEntity ? 'border-' + prevRow.currentEntity.getType() : 'border-Search') : 'border-None');
this.$scrollDownButton.removeClass(this.getBorderClass.bind(this));
this.$scrollDownButton.addClass(nextRow ? (nextRow.currentEntity ? 'border-' + nextRow.currentEntity.getType() : 'border-Search') : 'border-None');
}
Browser.prototype.getBorderClass = function(index,css){
return (css.match (/(^|\s)border-\S+/g) || []).join(' ');
}
Browser.prototype.show = function(){
if (!this.ready){
this.initInteraction();
}
$('#gallery').hide();
Global.collectionMenu.$savePathButton.show();
Global.user.refresh();
$(this.$container).show();
}
/* update entity content of changed entity */
Browser.prototype.updateEntity = function(entityId,title,description,isPublic){
var entity;
for(var i = 0, len1 = this.rows.length; i < len1; i++){
for(var j = 0, len2 = Global.browser.rows[i].entities.length; j < len2; j++){
entity = this.rows[i].entities[j];
if (entity.getUID() == entityId){
entity.update(title,description,isPublic);
}
}
}
}
/* update entity content of changed entity */
Browser.prototype.deleteEntity = function(entityId){
var entity;
for(var i = 0, len1 = this.rows.length; i < len1; i++){
var removes = [];
for(var j = 0, len2 = Global.browser.rows[i].entities.length; j < len2; j++){
entity = this.rows[i].entities[j];
if (entity.getUID() == entityId){
entity.$container.remove();
removes.push(entity);
}
}
for (var r = 0, len3 = removes.length; r < len3; r++){
for(var j = 0, len2 = Global.browser.rows[i].entities.length; j < len2; j++){
if (removes[r] == Global.browser.rows[i].entities[j]){
Global.browser.rows[i].entities.splice(j,1);
break;
}
}
}
Global.browser.rows[i].showAllEntities();
}
}
/* TESTS/DEV */
/* remove all images and put colors in place */
Browser.prototype.testColor = function(){
$('.visual-holder').css('backgroundImage','none').each(function(){$(this).css('backgroundColor','rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')');});
}
|
import React from 'react'
import styles from './weather.less'
function Weather (props) {
const {city, icon, dateTime, temperature, name} = props
return <div className={styles.weather}>
<div className={styles.left}>
<div className={styles.icon} style={{
backgroundImage: `url(${icon})`
}} />
<p>{name}</p>
</div>
<div className={styles.right}>
<h1 className={styles.temperature}>{temperature + '°'}</h1>
<p className={styles.description}>{city},{dateTime}</p>
</div>
</div>
}
export default Weather
|
/**
* Copyright 2013 Ionică Bizău
*
* A Node.JS module, which provides an object oriented wrapper for the Youtube v3 API.
* Author: Ionică Bizău <[email protected]>
*
**/
var Util = require("../../util");
function list (options, callback) {
var self = this;
var url = Util.createUrl.apply(self, ["playlists", options]);
var reqOptions = {
url: url,
};
self.Client.request(reqOptions, callback);
}
function insert (options, callback) {
callback(null, {"error": "Not yet implemented"});
}
function update (options, callback) {
callback(null, {"error": "Not yet implemented"});
}
function deleteItem (options, callback) {
callback(null, {"error": "Not yet implemented"});
}
module.exports = {
list: list,
insert: insert,
update: update,
delete: deleteItem
};
|
// Copyright 2014 the V8 project authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Flags: --harmony-symbols
var v0 = new WeakMap;
var v1 = {};
v0.set(v1, 1);
var sym = Symbol();
v1[sym] = 1;
var symbols = Object.getOwnPropertySymbols(v1);
assertArrayEquals([sym], symbols);
|
module.exports = {
description: 'throw an error when accessing members of null or undefined'
};
|
var $path = require('path');
module.exports = function(grunt) {
grunt.initConfig({
localBase : $path.resolve(__dirname),
pkg: grunt.file.readJSON('package.json'),
litheConcat : {
options : {
cwd: '<%=localBase%>'
},
publish : {
src : 'public/js/',
dest : 'public/js/dist/',
walk : true,
alias : 'config.js',
global : 'conf/global.js',
withoutGlobal : [
],
target : 'conf/'
}
},
litheCompress : {
options : {
cwd: '<%=localBase%>'
},
publish : {
src : 'public/js/dist/',
dest : 'public/js/dist/'
}
}
});
grunt.loadTasks('tasks/lithe');
grunt.registerTask(
'publish',
'[COMMON] pack and compress files, then distribute',
[
'litheConcat:publish',
'litheCompress:publish'
]
);
grunt.registerTask(
'default',
'the default task is publish',
[
'publish'
]
);
};
|
flock.synth({
synthDef: {
ugen: "flock.ugen.sin",
freq: {
ugen: "flock.ugen.value",
rate: "audio",
value: 400,
add: {
ugen: "flock.ugen.sin",
freq: {
ugen: "flock.ugen.mouse.cursor",
mul: 124,
add: 62,
},
mul: {
ugen: "flock.ugen.mouse.cursor",
mul: 100,
add: 100,
options: {
axis: "y"
}
}
}
},
mul: 0.3
}
});
|
import cn from 'classnames'
import Image from 'next/image'
import Link from 'next/link'
export default function CoverImage({ title, url, slug }) {
const image = (
<Image
width={2000}
height={1000}
alt={`Cover Image for ${title}`}
src={url}
className={cn('shadow-small', {
'hover:shadow-medium transition-shadow duration-200': slug,
})}
/>
)
return (
<div className="sm:mx-0">
{slug ? (
<Link href={slug}>
<a aria-label={title}>{image}</a>
</Link>
) : (
image
)}
</div>
)
}
|
{
"ALLOWED_FILE_TYPE": "Only following files are allowed : ",
"AUTHORIZATION_REQUIRED": "No estás autorizado para usar el administrador de archivos.",
"DIRECTORY_ALREADY_EXISTS": "La carpeta '%s' ya existe.",
"DIRECTORY_NOT_EXIST": "La carpeta %s no existe.",
"DISALLOWED_FILE_TYPE": "Following files are not allowed : ",
"ERROR_RENAMING_DIRECTORY": "Error al intentar renombrar la carpeta %s a %s.",
"ERROR_RENAMING_FILE": "Error al intentar renombrar el archivo %s a %s.",
"FILE_ALREADY_EXISTS": "El archivo '%s' ya existe.",
"FILE_DOES_NOT_EXIST": "El archivo %s no existe.",
"INVALID_ACTION": "Acción inválida.",
"INVALID_DIRECTORY_OR_FILE": "Carpeta o archivo invalido.",
"INVALID_FILE_TYPE": "File upload is not allowed.",
"INVALID_FILE_UPLOAD": "Transferencia de archivo inválida.",
"INVALID_VAR": "Variable %s inválida.",
"LANGUAGE_FILE_NOT_FOUND": "Archivo de idioma no encontrado.",
"MODE_ERROR": "Error de modo.",
"UNABLE_TO_CREATE_DIRECTORY": "No se ha podido crear la carpeta %s.",
"UNABLE_TO_OPEN_DIRECTORY": "No se ha podido abrir la carpeta %s.",
"UPLOAD_FILES_SMALLER_THAN": "Por favor, sube solo imágenes con tamaño inferior a %s.",
"UPLOAD_IMAGES_ONLY": "Por favor, sube solo imágenes, no se admiten otro tipo de archivos.",
"UPLOAD_IMAGES_TYPE_JPEG_GIF_PNG": "Por favor, sube solo imágenes de tipo JPEG, GIF o PNG.",
"browse": "Browse...",
"bytes": " bytes",
"cancel": "Cancelar",
"confirmation_delete": "¿Estás seguro de eliminar este archivo?",
"could_not_retrieve_folder": "No se ha podido recuperar el contenido de la carpeta.",
"create_folder": "Crear carpeta",
"created": "Creado",
"current_folder": "Carpeta actual: ",
"default_foldername": "Mi carpeta",
"del": "Eliminar",
"dimensions": "Dimensiones",
"download": "Descargar",
"fck_select_integration": "La función 'Seleccionar' solo se puede utilizar desde FCKEditor.",
"file_size_limit": "The file size limit is : ",
"file_too_big": "The file is too big.",
"gb": "gb",
"grid_view": "Cambiar a vista de cuadrícula.",
"kb": "kb",
"list_view": "Cambiar a vista de lista.",
"loading_data": "Transferring data ...",
"mb": "mb",
"modified": "Modificado",
"move": "Move to ...",
"name": "Nombre",
"new_filename": "Introduce un nuevo nombre para el archivo",
"new_folder": "Nueva carpeta",
"no": "No",
"no_foldername": "No se ha indicado un nombre para la carpeta.",
"parentfolder": "Directorio padre",
"prompt_foldername": "Introduce el nombre de la nueva carpeta",
"rename": "Renombrar",
"search": "Search",
"search_reset": "Reset",
"select": "Seleccionar",
"select_from_left": "Selecciona un elemento de la izquierda.",
"size": "tamaño",
"successful_added_file": "Nuevo archivo añadido.",
"successful_added_folder": "Nueva carpeta creada.",
"successful_delete": "Eliminación completada.",
"successful_moved": "Move successful.",
"successful_rename": "Renombrado con éxito.",
"upload": "Subir",
"yes": "Sí"
} |
export default function promiseMiddleware() {
return next => action => {
const { promise, type, ...rest } = action;
if (!promise) return next(action);
const SUCCESS = type + '_SUCCESS';
const REQUEST = type + '_REQUEST';
const FAILURE = type + '_FAILURE';
next({ ...rest, type: REQUEST });
return promise
.then(req => {
next({ ...rest, req, type: SUCCESS });
return true;
})
.catch(error => {
next({ ...rest, error, type: FAILURE });
console.log(error);
return false;
});
};
} |
// These properties are special and can open client libraries to security
// issues
var ignoreProperties = ['__proto__', 'constructor', 'prototype'];
/**
* Returns the value of object `o` at the given `path`.
*
* ####Example:
*
* var obj = {
* comments: [
* { title: 'exciting!', _doc: { title: 'great!' }}
* , { title: 'number dos' }
* ]
* }
*
* mpath.get('comments.0.title', o) // 'exciting!'
* mpath.get('comments.0.title', o, '_doc') // 'great!'
* mpath.get('comments.title', o) // ['exciting!', 'number dos']
*
* // summary
* mpath.get(path, o)
* mpath.get(path, o, special)
* mpath.get(path, o, map)
* mpath.get(path, o, special, map)
*
* @param {String} path
* @param {Object} o
* @param {String} [special] When this property name is present on any object in the path, walking will continue on the value of this property.
* @param {Function} [map] Optional function which receives each individual found value. The value returned from `map` is used in the original values place.
*/
exports.get = function (path, o, special, map) {
var lookup;
if ('function' == typeof special) {
if (special.length < 2) {
map = special;
special = undefined;
} else {
lookup = special;
special = undefined;
}
}
map || (map = K);
var parts = 'string' == typeof path
? path.split('.')
: path
if (!Array.isArray(parts)) {
throw new TypeError('Invalid `path`. Must be either string or array');
}
var obj = o
, part;
for (var i = 0; i < parts.length; ++i) {
part = parts[i];
if (Array.isArray(obj) && !/^\d+$/.test(part)) {
// reading a property from the array items
var paths = parts.slice(i);
// Need to `concat()` to avoid `map()` calling a constructor of an array
// subclass
return [].concat(obj).map(function (item) {
return item
? exports.get(paths, item, special || lookup, map)
: map(undefined);
});
}
if (lookup) {
obj = lookup(obj, part);
} else {
var _from = special && obj[special] ? obj[special] : obj;
obj = _from instanceof Map ?
_from.get(part) :
_from[part];
}
if (!obj) return map(obj);
}
return map(obj);
};
/**
* Returns true if `in` returns true for every piece of the path
*
* @param {String} path
* @param {Object} o
*/
exports.has = function (path, o) {
var parts = typeof path === 'string' ?
path.split('.') :
path;
if (!Array.isArray(parts)) {
throw new TypeError('Invalid `path`. Must be either string or array');
}
var len = parts.length;
var cur = o;
for (var i = 0; i < len; ++i) {
if (cur == null || typeof cur !== 'object' || !(parts[i] in cur)) {
return false;
}
cur = cur[parts[i]];
}
return true;
};
/**
* Deletes the last piece of `path`
*
* @param {String} path
* @param {Object} o
*/
exports.unset = function (path, o) {
var parts = typeof path === 'string' ?
path.split('.') :
path;
if (!Array.isArray(parts)) {
throw new TypeError('Invalid `path`. Must be either string or array');
}
var len = parts.length;
var cur = o;
for (var i = 0; i < len; ++i) {
if (cur == null || typeof cur !== 'object' || !(parts[i] in cur)) {
return false;
}
// Disallow any updates to __proto__ or special properties.
if (ignoreProperties.indexOf(parts[i]) !== -1) {
return false;
}
if (i === len - 1) {
delete cur[parts[i]];
return true;
}
cur = cur instanceof Map ? cur.get(parts[i]) : cur[parts[i]];
}
return true;
};
/**
* Sets the `val` at the given `path` of object `o`.
*
* @param {String} path
* @param {Anything} val
* @param {Object} o
* @param {String} [special] When this property name is present on any object in the path, walking will continue on the value of this property.
* @param {Function} [map] Optional function which is passed each individual value before setting it. The value returned from `map` is used in the original values place.
*/
exports.set = function (path, val, o, special, map, _copying) {
var lookup;
if ('function' == typeof special) {
if (special.length < 2) {
map = special;
special = undefined;
} else {
lookup = special;
special = undefined;
}
}
map || (map = K);
var parts = 'string' == typeof path
? path.split('.')
: path
if (!Array.isArray(parts)) {
throw new TypeError('Invalid `path`. Must be either string or array');
}
if (null == o) return;
for (var i = 0; i < parts.length; ++i) {
// Silently ignore any updates to `__proto__`, these are potentially
// dangerous if using mpath with unsanitized data.
if (ignoreProperties.indexOf(parts[i]) !== -1) {
return;
}
}
// the existance of $ in a path tells us if the user desires
// the copying of an array instead of setting each value of
// the array to the one by one to matching positions of the
// current array. Unless the user explicitly opted out by passing
// false, see Automattic/mongoose#6273
var copy = _copying || (/\$/.test(path) && _copying !== false)
, obj = o
, part
for (var i = 0, len = parts.length - 1; i < len; ++i) {
part = parts[i];
if ('$' == part) {
if (i == len - 1) {
break;
} else {
continue;
}
}
if (Array.isArray(obj) && !/^\d+$/.test(part)) {
var paths = parts.slice(i);
if (!copy && Array.isArray(val)) {
for (var j = 0; j < obj.length && j < val.length; ++j) {
// assignment of single values of array
exports.set(paths, val[j], obj[j], special || lookup, map, copy);
}
} else {
for (var j = 0; j < obj.length; ++j) {
// assignment of entire value
exports.set(paths, val, obj[j], special || lookup, map, copy);
}
}
return;
}
if (lookup) {
obj = lookup(obj, part);
} else {
var _to = special && obj[special] ? obj[special] : obj;
obj = _to instanceof Map ?
_to.get(part) :
_to[part];
}
if (!obj) return;
}
// process the last property of the path
part = parts[len];
// use the special property if exists
if (special && obj[special]) {
obj = obj[special];
}
// set the value on the last branch
if (Array.isArray(obj) && !/^\d+$/.test(part)) {
if (!copy && Array.isArray(val)) {
_setArray(obj, val, part, lookup, special, map);
} else {
for (var j = 0; j < obj.length; ++j) {
item = obj[j];
if (item) {
if (lookup) {
lookup(item, part, map(val));
} else {
if (item[special]) item = item[special];
item[part] = map(val);
}
}
}
}
} else {
if (lookup) {
lookup(obj, part, map(val));
} else if (obj instanceof Map) {
obj.set(part, map(val));
} else {
obj[part] = map(val);
}
}
}
/*!
* Recursively set nested arrays
*/
function _setArray(obj, val, part, lookup, special, map) {
for (var item, j = 0; j < obj.length && j < val.length; ++j) {
item = obj[j];
if (Array.isArray(item) && Array.isArray(val[j])) {
_setArray(item, val[j], part, lookup, special, map);
} else if (item) {
if (lookup) {
lookup(item, part, map(val[j]));
} else {
if (item[special]) item = item[special];
item[part] = map(val[j]);
}
}
}
}
/*!
* Returns the value passed to it.
*/
function K (v) {
return v;
}
|
(function() {
var def,
__indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };
def = require('./utils').def;
Object["new"] = function(a) {
var o;
o = {};
a.step(2, function(k, v) {
return o[k] = v;
});
return o;
};
def(Object, {
concat: function(m) {
var k, o, v;
o = {};
for (k in this) {
v = this[k];
o[k] = v;
}
return o.merge(m || {});
}
});
def(Object, {
destroy: function(key) {
var res;
if (this.hasKey(key)) {
res = this[key];
delete this[key];
return res;
}
return null;
}
});
def(Object, {
each: function(f) {
var k, v;
if (f != null) {
for (k in this) {
v = this[k];
f(k, v);
}
}
return this;
}
});
def(Object, {
empty: function() {
return this.keys().empty();
}
});
def(Object, {
first: function() {
if (this.empty()) {
return null;
} else {
return this.flatten().group(2).first();
}
}
});
def(Object, {
flatten: function() {
var a, k, v;
a = [];
for (k in this) {
v = this[k];
a = a.concat([k, v]);
}
return a;
}
});
def(Object, {
has: function(value) {
return __indexOf.call(this.values(), value) >= 0;
}
});
def(Object, {
hasKey: function(key) {
return this[key] != null;
}
});
def(Object, {
keys: function() {
var k, _results;
_results = [];
for (k in this) {
_results.push(k);
}
return _results;
}
});
def(Object, {
length: function() {
return this.keys().length;
}
});
def(Object, {
last: function() {
if (this.empty()) {
return null;
} else {
return this.flatten().group(2).last();
}
}
});
def(Object, {
map: function(f) {
var k, v;
return Object["new"](((function() {
var _results;
_results = [];
for (k in this) {
v = this[k];
_results.push(f(k, v));
}
return _results;
}).call(this)).flatten());
}
});
def(Object, {
merge: function(o) {
var k, v;
for (k in o) {
v = o[k];
this[k] = v;
}
return this;
}
});
def(Object, {
reject: function(f) {
var k, o, v;
o = {};
for (k in this) {
v = this[k];
if (!(typeof f === "function" ? f(k, v) : void 0)) {
o[k] = v;
}
}
return o;
}
});
def(Object, {
select: function(f) {
var k, o, v;
o = {};
for (k in this) {
v = this[k];
if (typeof f === "function" ? f(k, v) : void 0) {
o[k] = v;
}
}
return o;
}
});
def(Object, {
size: function() {
return this.length();
}
});
def(Object, {
sort: function(f) {
var k, o, _i, _len, _ref;
if ((f == null) || typeof f !== 'function') {
f = function(a, b) {
if (a > b) {
return 1;
} else if (b < a) {
return -1;
} else {
return 0;
}
};
}
o = {};
_ref = this.keys().sort(f);
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
k = _ref[_i];
o[k] = this[k];
}
return o;
}
});
def(Object, {
sortedKeys: function() {
return this.keys().sort();
}
});
def(Object, {
sortedValues: function() {
var k, _i, _len, _ref, _results;
_ref = this.sortedKeys();
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
k = _ref[_i];
_results.push(this[k]);
}
return _results;
}
});
def(Object, {
tap: function(block) {
block.call(this, this);
return this;
}
});
def(Object, {
type: function() {
return Object.prototype.toString.call(this).toLowerCase().replace(/\[object (\w+)\]/, "$1");
}
});
def(Object, {
update: Object.prototype.merge
});
def(Object, {
values: function() {
var k, _i, _len, _ref, _results;
_ref = this.keys();
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
k = _ref[_i];
_results.push(this[k]);
}
return _results;
}
});
def(Object, {
quacksLike: function(type) {
var definition, k, v, _ref;
if (type.__definition__ != null) {
definition = type.__definition__;
if (typeof definition === "function") {
return definition(this);
}
for (k in definition) {
v = definition[k];
switch (typeof v) {
case "function":
if (!v(this[k])) {
return false;
}
break;
default:
if (!(v === "*" || ((_ref = this[k]) != null ? _ref.type() : void 0) === v)) {
return false;
}
}
}
return true;
} else {
return false;
}
}
});
}).call(this);
|
describe('CreateController', function() {
beforeEach(module('mainModule'));
var $scope, $controller, $httpBackend, $state;
beforeEach(inject(function(_$controller_, _$httpBackend_, _$state_) {
$httpBackend = _$httpBackend_;
$state = _$state_;
$scope = {};
$controller = _$controller_('CreateController', { $scope: $scope });
$httpBackend.whenGET('/header').respond(200);
$httpBackend.whenGET('/filters').respond(200);
$httpBackend.flush();
}));
afterEach(function() {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
it('initial parameter of cleanNewCheck is custom object', function() {
expect($scope.cleanNewCheck).toBeDefined();
});
it('function resetNewCheck should copy to object custom template', function() {
$scope.cheque = {};
$scope.resetNewCheck();
expect($scope.cheque).toEqual($scope.cleanNewCheck);
});
it('function addKit should return object with key "kit"', function() {
expect($scope.addKit('example')).toEqual({'kit': 'example'});
});
it('should add note and diagnostic to cheque and send items to server', function() {
$scope.cheque = {"id":1, "name":'Bob', "notes":[], diagnostics:[]};
$scope.note = {"text":'text'};
$scope.diagnostic = {"text":'text'};
$httpBackend.expectPOST('/cheques', {"id":1, "name":'Bob', "notes":[{"text":'text'}], diagnostics:[{"text":'text'}]}).respond(200);
$scope.sendCheque();
$httpBackend.flush();
});
it('should create mdDialog for datepicker and take response', inject(function($mdDialog, $q, $rootScope) {
angular.extend($scope, {$new: function() {} });
var deferred = $q.defer();
spyOn($mdDialog, 'show').and.returnValue(deferred.promise);
$scope.introducedPicker();
$scope.guaranteePicker();
deferred.resolve('test');
$rootScope.$apply();
expect($scope.cheque.introducedFrom).toEqual('test');
expect($scope.cheque.guarantee).toEqual('test');
expect($mdDialog.show).toHaveBeenCalled();
}));
}); |
// Generated by CoffeeScript 1.4.0
(function() {
var $, Ajax, Base, Collection, Extend, Include, Model, Queue, Singleton, Spine,
__bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
__slice = [].slice;
Spine = this.Spine || require('spine');
$ = Spine.$;
Model = Spine.Model;
Queue = $({});
Ajax = {
getURL: function(object) {
return object && (typeof object.url === "function" ? object.url() : void 0) || object.url;
},
enabled: true,
disable: function(callback) {
if (this.enabled) {
this.enabled = false;
try {
return callback();
} catch (e) {
throw e;
} finally {
this.enabled = true;
}
} else {
return callback();
}
},
queue: function(request) {
if (request) {
return Queue.queue(request);
} else {
return Queue.queue();
}
},
clearQueue: function() {
return this.queue([]);
}
};
Base = (function() {
function Base() {}
Base.prototype.defaults = {
contentType: 'application/json',
dataType: 'json',
processData: false,
headers: {
'X-Requested-With': 'XMLHttpRequest'
}
};
Base.prototype.queue = Ajax.queue;
Base.prototype.ajax = function(params, defaults) {
return $.ajax(this.ajaxSettings(params, defaults));
};
Base.prototype.ajaxQueue = function(params, defaults) {
var deferred, jqXHR, promise, request, settings;
jqXHR = null;
deferred = $.Deferred();
promise = deferred.promise();
if (!Ajax.enabled) {
return promise;
}
settings = this.ajaxSettings(params, defaults);
request = function(next) {
return jqXHR = $.ajax(settings).done(deferred.resolve).fail(deferred.reject).then(next, next);
};
promise.abort = function(statusText) {
var index;
if (jqXHR) {
return jqXHR.abort(statusText);
}
index = $.inArray(request, this.queue());
if (index > -1) {
this.queue().splice(index, 1);
}
deferred.rejectWith(settings.context || settings, [promise, statusText, '']);
return promise;
};
this.queue(request);
return promise;
};
Base.prototype.ajaxSettings = function(params, defaults) {
return $.extend({}, this.defaults, defaults, params);
};
return Base;
})();
Collection = (function(_super) {
__extends(Collection, _super);
function Collection(model) {
this.model = model;
this.failResponse = __bind(this.failResponse, this);
this.recordsResponse = __bind(this.recordsResponse, this);
}
Collection.prototype.find = function(id, params) {
var record;
record = new this.model({
id: id
});
return this.ajaxQueue(params, {
type: 'GET',
url: Ajax.getURL(record)
}).done(this.recordsResponse).fail(this.failResponse);
};
Collection.prototype.all = function(params) {
return this.ajaxQueue(params, {
type: 'GET',
url: Ajax.getURL(this.model)
}).done(this.recordsResponse).fail(this.failResponse);
};
Collection.prototype.fetch = function(params, options) {
var id,
_this = this;
if (params == null) {
params = {};
}
if (options == null) {
options = {};
}
if (id = params.id) {
delete params.id;
return this.find(id, params).done(function(record) {
return _this.model.refresh(record, options);
});
} else {
return this.all(params).done(function(records) {
return _this.model.refresh(records, options);
});
}
};
Collection.prototype.recordsResponse = function(data, status, xhr) {
return this.model.trigger('ajaxSuccess', null, status, xhr);
};
Collection.prototype.failResponse = function(xhr, statusText, error) {
return this.model.trigger('ajaxError', null, xhr, statusText, error);
};
return Collection;
})(Base);
Singleton = (function(_super) {
__extends(Singleton, _super);
function Singleton(record) {
this.record = record;
this.failResponse = __bind(this.failResponse, this);
this.recordResponse = __bind(this.recordResponse, this);
this.model = this.record.constructor;
}
Singleton.prototype.reload = function(params, options) {
return this.ajaxQueue(params, {
type: 'GET',
url: Ajax.getURL(this.record)
}).done(this.recordResponse(options)).fail(this.failResponse(options));
};
Singleton.prototype.create = function(params, options) {
return this.ajaxQueue(params, {
type: 'POST',
data: JSON.stringify(this.record),
url: Ajax.getURL(this.model)
}).done(this.recordResponse(options)).fail(this.failResponse(options));
};
Singleton.prototype.update = function(params, options) {
return this.ajaxQueue(params, {
type: 'PUT',
data: JSON.stringify(this.record),
url: Ajax.getURL(this.record)
}).done(this.recordResponse(options)).fail(this.failResponse(options));
};
Singleton.prototype.destroy = function(params, options) {
return this.ajaxQueue(params, {
type: 'DELETE',
url: Ajax.getURL(this.record)
}).done(this.recordResponse(options)).fail(this.failResponse(options));
};
Singleton.prototype.recordResponse = function(options) {
var _this = this;
if (options == null) {
options = {};
}
return function(data, status, xhr) {
var _ref, _ref1;
if (Spine.isBlank(data) || _this.record.destroyed) {
data = false;
} else {
data = _this.model.fromJSON(data);
}
Ajax.disable(function() {
if (data) {
if (data.id && _this.record.id !== data.id) {
_this.record.changeID(data.id);
}
return _this.record.updateAttributes(data.attributes());
}
});
_this.record.trigger('ajaxSuccess', data, status, xhr);
if ((_ref = options.success) != null) {
_ref.apply(_this.record);
}
return (_ref1 = options.done) != null ? _ref1.apply(_this.record) : void 0;
};
};
Singleton.prototype.failResponse = function(options) {
var _this = this;
if (options == null) {
options = {};
}
return function(xhr, statusText, error) {
var _ref, _ref1;
_this.record.trigger('ajaxError', xhr, statusText, error);
if ((_ref = options.error) != null) {
_ref.apply(_this.record);
}
return (_ref1 = options.fail) != null ? _ref1.apply(_this.record) : void 0;
};
};
return Singleton;
})(Base);
Model.host = '';
Include = {
ajax: function() {
return new Singleton(this);
},
url: function() {
var args, url;
args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
url = Ajax.getURL(this.constructor);
if (url.charAt(url.length - 1) !== '/') {
url += '/';
}
url += encodeURIComponent(this.id);
args.unshift(url);
return args.join('/');
}
};
Extend = {
ajax: function() {
return new Collection(this);
},
url: function() {
var args;
args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
args.unshift(this.className.toLowerCase() + 's');
args.unshift(Model.host);
return args.join('/');
}
};
Model.Ajax = {
extended: function() {
this.fetch(this.ajaxFetch);
this.change(this.ajaxChange);
this.extend(Extend);
return this.include(Include);
},
ajaxFetch: function() {
var _ref;
return (_ref = this.ajax()).fetch.apply(_ref, arguments);
},
ajaxChange: function(record, type, options) {
if (options == null) {
options = {};
}
if (options.ajax === false) {
return;
}
return record.ajax()[type](options.ajax, options);
}
};
Model.Ajax.Methods = {
extended: function() {
this.extend(Extend);
return this.include(Include);
}
};
Ajax.defaults = Base.prototype.defaults;
Spine.Ajax = Ajax;
if (typeof module !== "undefined" && module !== null) {
module.exports = Ajax;
}
}).call(this);
|
/* *
*
* (c) 2010-2021 Torstein Honsi
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
import ColorMapMixin from '../../Mixins/ColorMapSeries.js';
var colorMapSeriesMixin = ColorMapMixin.colorMapSeriesMixin;
import H from '../../Core/Globals.js';
var noop = H.noop;
import LegendSymbol from '../../Core/Legend/LegendSymbol.js';
import MapChart from '../../Core/Chart/MapChart.js';
var maps = MapChart.maps, splitPath = MapChart.splitPath;
import MapPoint from './MapPoint.js';
import palette from '../../Core/Color/Palette.js';
import Series from '../../Core/Series/Series.js';
import SeriesRegistry from '../../Core/Series/SeriesRegistry.js';
var
// indirect dependency to keep product size low
_a = SeriesRegistry.seriesTypes, ColumnSeries = _a.column, ScatterSeries = _a.scatter;
import SVGRenderer from '../../Core/Renderer/SVG/SVGRenderer.js';
import U from '../../Core/Utilities.js';
var extend = U.extend, fireEvent = U.fireEvent, getNestedProperty = U.getNestedProperty, isArray = U.isArray, isNumber = U.isNumber, merge = U.merge, objectEach = U.objectEach, pick = U.pick, splat = U.splat;
/* *
*
* Class
*
* */
/**
* @private
* @class
* @name Highcharts.seriesTypes.map
*
* @augments Highcharts.Series
*/
var MapSeries = /** @class */ (function (_super) {
__extends(MapSeries, _super);
function MapSeries() {
/* *
*
* Static Properties
*
* */
var _this = _super !== null && _super.apply(this, arguments) || this;
/* *
*
* Properties
*
* */
_this.baseTrans = void 0;
_this.chart = void 0;
_this.data = void 0;
_this.group = void 0;
_this.joinBy = void 0;
_this.options = void 0;
_this.points = void 0;
_this.transformGroup = void 0;
return _this;
/* eslint-enable valid-jsdoc */
}
/* *
*
* Functions
*
* */
/* eslint-disable valid-jsdoc */
/**
* The initial animation for the map series. By default, animation is
* disabled. Animation of map shapes is not at all supported in VML
* browsers.
* @private
*/
MapSeries.prototype.animate = function (init) {
var chart = this.chart, animation = this.options.animation, group = this.group, xAxis = this.xAxis, yAxis = this.yAxis, left = xAxis.pos, top = yAxis.pos;
if (chart.renderer.isSVG) {
if (animation === true) {
animation = {
duration: 1000
};
}
// Initialize the animation
if (init) {
// Scale down the group and place it in the center
group.attr({
translateX: left + xAxis.len / 2,
translateY: top + yAxis.len / 2,
scaleX: 0.001,
scaleY: 0.001
});
// Run the animation
}
else {
group.animate({
translateX: left,
translateY: top,
scaleX: 1,
scaleY: 1
}, animation);
}
}
};
/**
* Animate in the new series from the clicked point in the old series.
* Depends on the drilldown.js module
* @private
*/
MapSeries.prototype.animateDrilldown = function (init) {
var toBox = this.chart.plotBox, level = this.chart.drilldownLevels[this.chart.drilldownLevels.length - 1], fromBox = level.bBox, animationOptions = this.chart.options.drilldown.animation, scale;
if (!init) {
scale = Math.min(fromBox.width / toBox.width, fromBox.height / toBox.height);
level.shapeArgs = {
scaleX: scale,
scaleY: scale,
translateX: fromBox.x,
translateY: fromBox.y
};
this.points.forEach(function (point) {
if (point.graphic) {
point.graphic
.attr(level.shapeArgs)
.animate({
scaleX: 1,
scaleY: 1,
translateX: 0,
translateY: 0
}, animationOptions);
}
});
}
};
/**
* When drilling up, pull out the individual point graphics from the lower
* series and animate them into the origin point in the upper series.
* @private
*/
MapSeries.prototype.animateDrillupFrom = function (level) {
ColumnSeries.prototype.animateDrillupFrom.call(this, level);
};
/**
* When drilling up, keep the upper series invisible until the lower series
* has moved into place.
* @private
*/
MapSeries.prototype.animateDrillupTo = function (init) {
ColumnSeries.prototype.animateDrillupTo.call(this, init);
};
/**
* Allow a quick redraw by just translating the area group. Used for zooming
* and panning in capable browsers.
* @private
*/
MapSeries.prototype.doFullTranslate = function () {
return (this.isDirtyData ||
this.chart.isResizing ||
this.chart.renderer.isVML ||
!this.baseTrans);
};
/**
* Draw the data labels. Special for maps is the time that the data labels
* are drawn (after points), and the clipping of the dataLabelsGroup.
* @private
*/
MapSeries.prototype.drawMapDataLabels = function () {
Series.prototype.drawDataLabels.call(this);
if (this.dataLabelsGroup) {
this.dataLabelsGroup.clip(this.chart.clipRect);
}
};
/**
* Use the drawPoints method of column, that is able to handle simple
* shapeArgs. Extend it by assigning the tooltip position.
* @private
*/
MapSeries.prototype.drawPoints = function () {
var series = this, xAxis = series.xAxis, yAxis = series.yAxis, group = series.group, chart = series.chart, renderer = chart.renderer, scaleX, scaleY, translateX, translateY, baseTrans = this.baseTrans, transformGroup, startTranslateX, startTranslateY, startScaleX, startScaleY;
// Set a group that handles transform during zooming and panning in
// order to preserve clipping on series.group
if (!series.transformGroup) {
series.transformGroup = renderer.g()
.attr({
scaleX: 1,
scaleY: 1
})
.add(group);
series.transformGroup.survive = true;
}
// Draw the shapes again
if (series.doFullTranslate()) {
// Individual point actions.
if (chart.hasRendered && !chart.styledMode) {
series.points.forEach(function (point) {
// Restore state color on update/redraw (#3529)
if (point.shapeArgs) {
point.shapeArgs.fill = series.pointAttribs(point, point.state).fill;
}
});
}
// Draw them in transformGroup
series.group = series.transformGroup;
ColumnSeries.prototype.drawPoints.apply(series);
series.group = group; // Reset
// Add class names
series.points.forEach(function (point) {
if (point.graphic) {
var className = '';
if (point.name) {
className +=
'highcharts-name-' +
point.name.replace(/ /g, '-').toLowerCase();
}
if (point.properties &&
point.properties['hc-key']) {
className +=
' highcharts-key-' +
point.properties['hc-key'].toLowerCase();
}
if (className) {
point.graphic.addClass(className);
}
// In styled mode, apply point colors by CSS
if (chart.styledMode) {
point.graphic.css(series.pointAttribs(point, point.selected && 'select' || void 0));
}
}
});
// Set the base for later scale-zooming. The originX and originY
// properties are the axis values in the plot area's upper left
// corner.
this.baseTrans = {
originX: (xAxis.min -
xAxis.minPixelPadding / xAxis.transA),
originY: (yAxis.min -
yAxis.minPixelPadding / yAxis.transA +
(yAxis.reversed ? 0 : yAxis.len / yAxis.transA)),
transAX: xAxis.transA,
transAY: yAxis.transA
};
// Reset transformation in case we're doing a full translate
// (#3789)
this.transformGroup.animate({
translateX: 0,
translateY: 0,
scaleX: 1,
scaleY: 1
});
// Just update the scale and transform for better performance
}
else {
scaleX = xAxis.transA / baseTrans.transAX;
scaleY = yAxis.transA / baseTrans.transAY;
translateX = xAxis.toPixels(baseTrans.originX, true);
translateY = yAxis.toPixels(baseTrans.originY, true);
// Handle rounding errors in normal view (#3789)
if (scaleX > 0.99 &&
scaleX < 1.01 &&
scaleY > 0.99 &&
scaleY < 1.01) {
scaleX = 1;
scaleY = 1;
translateX = Math.round(translateX);
translateY = Math.round(translateY);
}
/* Animate or move to the new zoom level. In order to prevent
flickering as the different transform components are set out
of sync (#5991), we run a fake animator attribute and set
scale and translation synchronously in the same step.
A possible improvement to the API would be to handle this in
the renderer or animation engine itself, to ensure that when
we are animating multiple properties, we make sure that each
step for each property is performed in the same step. Also,
for symbols and for transform properties, it should induce a
single updateTransform and symbolAttr call. */
transformGroup = this.transformGroup;
if (chart.renderer.globalAnimation) {
startTranslateX = transformGroup.attr('translateX');
startTranslateY = transformGroup.attr('translateY');
startScaleX = transformGroup.attr('scaleX');
startScaleY = transformGroup.attr('scaleY');
transformGroup
.attr({ animator: 0 })
.animate({
animator: 1
}, {
step: function (now, fx) {
transformGroup.attr({
translateX: (startTranslateX +
(translateX - startTranslateX) * fx.pos),
translateY: (startTranslateY +
(translateY - startTranslateY) * fx.pos),
scaleX: (startScaleX +
(scaleX - startScaleX) *
fx.pos),
scaleY: (startScaleY +
(scaleY - startScaleY) * fx.pos)
});
}
});
// When dragging, animation is off.
}
else {
transformGroup.attr({
translateX: translateX,
translateY: translateY,
scaleX: scaleX,
scaleY: scaleY
});
}
}
/* Set the stroke-width directly on the group element so the
children inherit it. We need to use setAttribute directly,
because the stroke-widthSetter method expects a stroke color also
to be set. */
if (!chart.styledMode) {
group.element.setAttribute('stroke-width', (pick(series.options[(series.pointAttrToOptions &&
series.pointAttrToOptions['stroke-width']) || 'borderWidth'], 1 // Styled mode
) / (scaleX || 1)));
}
this.drawMapDataLabels();
};
/**
* Get the bounding box of all paths in the map combined.
* @private
*/
MapSeries.prototype.getBox = function (paths) {
var MAX_VALUE = Number.MAX_VALUE, maxX = -MAX_VALUE, minX = MAX_VALUE, maxY = -MAX_VALUE, minY = MAX_VALUE, minRange = MAX_VALUE, xAxis = this.xAxis, yAxis = this.yAxis, hasBox;
// Find the bounding box
(paths || []).forEach(function (point) {
if (point.path) {
if (typeof point.path === 'string') {
point.path = splitPath(point.path);
// Legacy one-dimensional array
}
else if (point.path[0] === 'M') {
point.path = SVGRenderer.prototype.pathToSegments(point.path);
}
var path = point.path || [], pointMaxX_1 = -MAX_VALUE, pointMinX_1 = MAX_VALUE, pointMaxY_1 = -MAX_VALUE, pointMinY_1 = MAX_VALUE, properties = point.properties;
// The first time a map point is used, analyze its box
if (!point._foundBox) {
path.forEach(function (seg) {
var x = seg[seg.length - 2];
var y = seg[seg.length - 1];
if (typeof x === 'number' && typeof y === 'number') {
pointMinX_1 = Math.min(pointMinX_1, x);
pointMaxX_1 = Math.max(pointMaxX_1, x);
pointMinY_1 = Math.min(pointMinY_1, y);
pointMaxY_1 = Math.max(pointMaxY_1, y);
}
});
// Cache point bounding box for use to position data
// labels, bubbles etc
point._midX = (pointMinX_1 + (pointMaxX_1 - pointMinX_1) * pick(point.middleX, properties &&
properties['hc-middle-x'], 0.5));
point._midY = (pointMinY_1 + (pointMaxY_1 - pointMinY_1) * pick(point.middleY, properties &&
properties['hc-middle-y'], 0.5));
point._maxX = pointMaxX_1;
point._minX = pointMinX_1;
point._maxY = pointMaxY_1;
point._minY = pointMinY_1;
point.labelrank = pick(point.labelrank, (pointMaxX_1 - pointMinX_1) * (pointMaxY_1 - pointMinY_1));
point._foundBox = true;
}
maxX = Math.max(maxX, point._maxX);
minX = Math.min(minX, point._minX);
maxY = Math.max(maxY, point._maxY);
minY = Math.min(minY, point._minY);
minRange = Math.min(point._maxX - point._minX, point._maxY - point._minY, minRange);
hasBox = true;
}
});
// Set the box for the whole series
if (hasBox) {
this.minY = Math.min(minY, pick(this.minY, MAX_VALUE));
this.maxY = Math.max(maxY, pick(this.maxY, -MAX_VALUE));
this.minX = Math.min(minX, pick(this.minX, MAX_VALUE));
this.maxX = Math.max(maxX, pick(this.maxX, -MAX_VALUE));
// If no minRange option is set, set the default minimum zooming
// range to 5 times the size of the smallest element
if (xAxis && typeof xAxis.options.minRange === 'undefined') {
xAxis.minRange = Math.min(5 * minRange, (this.maxX - this.minX) / 5, xAxis.minRange || MAX_VALUE);
}
if (yAxis && typeof yAxis.options.minRange === 'undefined') {
yAxis.minRange = Math.min(5 * minRange, (this.maxY - this.minY) / 5, yAxis.minRange || MAX_VALUE);
}
}
};
MapSeries.prototype.getExtremes = function () {
// Get the actual value extremes for colors
var _a = Series.prototype.getExtremes
.call(this, this.valueData), dataMin = _a.dataMin, dataMax = _a.dataMax;
// Recalculate box on updated data
if (this.chart.hasRendered && this.isDirtyData) {
this.getBox(this.options.data);
}
if (isNumber(dataMin)) {
this.valueMin = dataMin;
}
if (isNumber(dataMax)) {
this.valueMax = dataMax;
}
// Extremes for the mock Y axis
return { dataMin: this.minY, dataMax: this.maxY };
};
/**
* Define hasData function for non-cartesian series. Returns true if the
* series has points at all.
* @private
*/
MapSeries.prototype.hasData = function () {
return !!this.processedXData.length; // != 0
};
/**
* Get presentational attributes. In the maps series this runs in both
* styled and non-styled mode, because colors hold data when a colorAxis is
* used.
* @private
*/
MapSeries.prototype.pointAttribs = function (point, state) {
var attr = point.series.chart.styledMode ?
this.colorAttribs(point) :
ColumnSeries.prototype.pointAttribs.call(this, point, state);
// Set the stroke-width on the group element and let all point
// graphics inherit. That way we don't have to iterate over all
// points to update the stroke-width on zooming.
attr['stroke-width'] = pick(point.options[(this.pointAttrToOptions &&
this.pointAttrToOptions['stroke-width']) || 'borderWidth'], 'inherit');
return attr;
};
/**
* Override render to throw in an async call in IE8. Otherwise it chokes on
* the US counties demo.
* @private
*/
MapSeries.prototype.render = function () {
var series = this, render = Series.prototype.render;
// Give IE8 some time to breathe.
if (series.chart.renderer.isVML && series.data.length > 3000) {
setTimeout(function () {
render.call(series);
});
}
else {
render.call(series);
}
};
/**
* Extend setData to join in mapData. If the allAreas option is true, all
* areas from the mapData are used, and those that don't correspond to a
* data value are given null values.
* @private
*/
MapSeries.prototype.setData = function (data, redraw, animation, updatePoints) {
var options = this.options, chartOptions = this.chart.options.chart, globalMapData = chartOptions && chartOptions.map, mapData = options.mapData, joinBy = this.joinBy, pointArrayMap = options.keys || this.pointArrayMap, dataUsed = [], mapMap = {}, mapPoint, mapTransforms = this.chart.mapTransforms, props, i;
// Collect mapData from chart options if not defined on series
if (!mapData && globalMapData) {
mapData = typeof globalMapData === 'string' ?
maps[globalMapData] :
globalMapData;
}
// Pick up numeric values, add index
// Convert Array point definitions to objects using pointArrayMap
if (data) {
data.forEach(function (val, i) {
var ix = 0;
if (isNumber(val)) {
data[i] = {
value: val
};
}
else if (isArray(val)) {
data[i] = {};
// Automatically copy first item to hc-key if there is
// an extra leading string
if (!options.keys &&
val.length > pointArrayMap.length &&
typeof val[0] === 'string') {
data[i]['hc-key'] = val[0];
++ix;
}
// Run through pointArrayMap and what's left of the
// point data array in parallel, copying over the values
for (var j = 0; j < pointArrayMap.length; ++j, ++ix) {
if (pointArrayMap[j] &&
typeof val[ix] !== 'undefined') {
if (pointArrayMap[j].indexOf('.') > 0) {
MapPoint.prototype.setNestedProperty(data[i], val[ix], pointArrayMap[j]);
}
else {
data[i][pointArrayMap[j]] =
val[ix];
}
}
}
}
if (joinBy && joinBy[0] === '_i') {
data[i]._i = i;
}
});
}
this.getBox(data);
// Pick up transform definitions for chart
this.chart.mapTransforms = mapTransforms =
chartOptions.mapTransforms ||
mapData && mapData['hc-transform'] ||
mapTransforms;
// Cache cos/sin of transform rotation angle
if (mapTransforms) {
objectEach(mapTransforms, function (transform) {
if (transform.rotation) {
transform.cosAngle = Math.cos(transform.rotation);
transform.sinAngle = Math.sin(transform.rotation);
}
});
}
if (mapData) {
if (mapData.type === 'FeatureCollection') {
this.mapTitle = mapData.title;
mapData = H.geojson(mapData, this.type, this);
}
this.mapData = mapData;
this.mapMap = {};
for (i = 0; i < mapData.length; i++) {
mapPoint = mapData[i];
props = mapPoint.properties;
mapPoint._i = i;
// Copy the property over to root for faster access
if (joinBy[0] && props && props[joinBy[0]]) {
mapPoint[joinBy[0]] = props[joinBy[0]];
}
mapMap[mapPoint[joinBy[0]]] = mapPoint;
}
this.mapMap = mapMap;
// Registered the point codes that actually hold data
if (data && joinBy[1]) {
var joinKey_1 = joinBy[1];
data.forEach(function (pointOptions) {
var mapKey = getNestedProperty(joinKey_1, pointOptions);
if (mapMap[mapKey]) {
dataUsed.push(mapMap[mapKey]);
}
});
}
if (options.allAreas) {
this.getBox(mapData);
data = data || [];
// Registered the point codes that actually hold data
if (joinBy[1]) {
var joinKey_2 = joinBy[1];
data.forEach(function (pointOptions) {
dataUsed.push(getNestedProperty(joinKey_2, pointOptions));
});
}
// Add those map points that don't correspond to data, which
// will be drawn as null points
dataUsed = ('|' + dataUsed.map(function (point) {
return point && point[joinBy[0]];
}).join('|') + '|'); // Faster than array.indexOf
mapData.forEach(function (mapPoint) {
if (!joinBy[0] ||
dataUsed.indexOf('|' + mapPoint[joinBy[0]] + '|') === -1) {
data.push(merge(mapPoint, { value: null }));
// #5050 - adding all areas causes the update
// optimization of setData to kick in, even though
// the point order has changed
updatePoints = false;
}
});
}
else {
this.getBox(dataUsed); // Issue #4784
}
}
Series.prototype.setData.call(this, data, redraw, animation, updatePoints);
};
/**
* Extend setOptions by picking up the joinBy option and applying it to a
* series property.
* @private
*/
MapSeries.prototype.setOptions = function (itemOptions) {
var options = Series.prototype.setOptions.call(this, itemOptions), joinBy = options.joinBy, joinByNull = joinBy === null;
if (joinByNull) {
joinBy = '_i';
}
joinBy = this.joinBy = splat(joinBy);
if (!joinBy[1]) {
joinBy[1] = joinBy[0];
}
return options;
};
/**
* Add the path option for data points. Find the max value for color
* calculation.
* @private
*/
MapSeries.prototype.translate = function () {
var series = this, xAxis = series.xAxis, yAxis = series.yAxis, doFullTranslate = series.doFullTranslate();
series.generatePoints();
series.data.forEach(function (point) {
// Record the middle point (loosely based on centroid),
// determined by the middleX and middleY options.
if (isNumber(point._midX) && isNumber(point._midY)) {
point.plotX = xAxis.toPixels(point._midX, true);
point.plotY = yAxis.toPixels(point._midY, true);
}
if (doFullTranslate) {
point.shapeType = 'path';
point.shapeArgs = {
d: series.translatePath(point.path)
};
}
});
fireEvent(series, 'afterTranslate');
};
/**
* Translate the path, so it automatically fits into the plot area box.
* @private
*/
MapSeries.prototype.translatePath = function (path) {
var series = this, xAxis = series.xAxis, yAxis = series.yAxis, xMin = xAxis.min, xTransA = xAxis.transA, xMinPixelPadding = xAxis.minPixelPadding, yMin = yAxis.min, yTransA = yAxis.transA, yMinPixelPadding = yAxis.minPixelPadding, ret = []; // Preserve the original
// Do the translation
if (path) {
path.forEach(function (seg) {
if (seg[0] === 'M') {
ret.push([
'M',
(seg[1] - (xMin || 0)) * xTransA + xMinPixelPadding,
(seg[2] - (yMin || 0)) * yTransA + yMinPixelPadding
]);
}
else if (seg[0] === 'L') {
ret.push([
'L',
(seg[1] - (xMin || 0)) * xTransA + xMinPixelPadding,
(seg[2] - (yMin || 0)) * yTransA + yMinPixelPadding
]);
}
else if (seg[0] === 'C') {
ret.push([
'C',
(seg[1] - (xMin || 0)) * xTransA + xMinPixelPadding,
(seg[2] - (yMin || 0)) * yTransA + yMinPixelPadding,
(seg[3] - (xMin || 0)) * xTransA + xMinPixelPadding,
(seg[4] - (yMin || 0)) * yTransA + yMinPixelPadding,
(seg[5] - (xMin || 0)) * xTransA + xMinPixelPadding,
(seg[6] - (yMin || 0)) * yTransA + yMinPixelPadding
]);
}
else if (seg[0] === 'Q') {
ret.push([
'Q',
(seg[1] - (xMin || 0)) * xTransA + xMinPixelPadding,
(seg[2] - (yMin || 0)) * yTransA + yMinPixelPadding,
(seg[3] - (xMin || 0)) * xTransA + xMinPixelPadding,
(seg[4] - (yMin || 0)) * yTransA + yMinPixelPadding
]);
}
else if (seg[0] === 'Z') {
ret.push(['Z']);
}
});
}
return ret;
};
/**
* The map series is used for basic choropleth maps, where each map area has
* a color based on its value.
*
* @sample maps/demo/all-maps/
* Choropleth map
*
* @extends plotOptions.scatter
* @excluding marker, cluster
* @product highmaps
* @optionparent plotOptions.map
*/
MapSeries.defaultOptions = merge(ScatterSeries.defaultOptions, {
animation: false,
dataLabels: {
crop: false,
formatter: function () {
var numberFormatter = this.series.chart.numberFormatter;
var value = this.point.value;
return isNumber(value) ? numberFormatter(value, -1) : '';
},
inside: true,
overflow: false,
padding: 0,
verticalAlign: 'middle'
},
/**
* @ignore-option
*
* @private
*/
marker: null,
/**
* The color to apply to null points.
*
* In styled mode, the null point fill is set in the
* `.highcharts-null-point` class.
*
* @sample maps/demo/all-areas-as-null/
* Null color
*
* @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject}
*
* @private
*/
nullColor: palette.neutralColor3,
/**
* Whether to allow pointer interaction like tooltips and mouse events
* on null points.
*
* @type {boolean}
* @since 4.2.7
* @apioption plotOptions.map.nullInteraction
*
* @private
*/
stickyTracking: false,
tooltip: {
followPointer: true,
pointFormat: '{point.name}: {point.value}<br/>'
},
/**
* @ignore-option
*
* @private
*/
turboThreshold: 0,
/**
* Whether all areas of the map defined in `mapData` should be rendered.
* If `true`, areas which don't correspond to a data point, are rendered
* as `null` points. If `false`, those areas are skipped.
*
* @sample maps/plotoptions/series-allareas-false/
* All areas set to false
*
* @type {boolean}
* @default true
* @product highmaps
* @apioption plotOptions.series.allAreas
*
* @private
*/
allAreas: true,
/**
* The border color of the map areas.
*
* In styled mode, the border stroke is given in the `.highcharts-point`
* class.
*
* @sample {highmaps} maps/plotoptions/series-border/
* Borders demo
*
* @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject}
* @default #cccccc
* @product highmaps
* @apioption plotOptions.series.borderColor
*
* @private
*/
borderColor: palette.neutralColor20,
/**
* The border width of each map area.
*
* In styled mode, the border stroke width is given in the
* `.highcharts-point` class.
*
* @sample maps/plotoptions/series-border/
* Borders demo
*
* @type {number}
* @default 1
* @product highmaps
* @apioption plotOptions.series.borderWidth
*
* @private
*/
borderWidth: 1,
/**
* @type {string}
* @default value
* @apioption plotOptions.map.colorKey
*/
/**
* What property to join the `mapData` to the value data. For example,
* if joinBy is "code", the mapData items with a specific code is merged
* into the data with the same code. For maps loaded from GeoJSON, the
* keys may be held in each point's `properties` object.
*
* The joinBy option can also be an array of two values, where the first
* points to a key in the `mapData`, and the second points to another
* key in the `data`.
*
* When joinBy is `null`, the map items are joined by their position in
* the array, which performs much better in maps with many data points.
* This is the recommended option if you are printing more than a
* thousand data points and have a backend that can preprocess the data
* into a parallel array of the mapData.
*
* @sample maps/plotoptions/series-border/
* Joined by "code"
* @sample maps/demo/geojson/
* GeoJSON joined by an array
* @sample maps/series/joinby-null/
* Simple data joined by null
*
* @type {string|Array<string>}
* @default hc-key
* @product highmaps
* @apioption plotOptions.series.joinBy
*
* @private
*/
joinBy: 'hc-key',
/**
* Define the z index of the series.
*
* @type {number}
* @product highmaps
* @apioption plotOptions.series.zIndex
*/
/**
* @apioption plotOptions.series.states
*
* @private
*/
states: {
/**
* @apioption plotOptions.series.states.hover
*/
hover: {
/** @ignore-option */
halo: null,
/**
* The color of the shape in this state.
*
* @sample maps/plotoptions/series-states-hover/
* Hover options
*
* @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject}
* @product highmaps
* @apioption plotOptions.series.states.hover.color
*/
/**
* The border color of the point in this state.
*
* @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject}
* @product highmaps
* @apioption plotOptions.series.states.hover.borderColor
*/
/**
* The border width of the point in this state
*
* @type {number}
* @product highmaps
* @apioption plotOptions.series.states.hover.borderWidth
*/
/**
* The relative brightness of the point when hovered, relative
* to the normal point color.
*
* @type {number}
* @product highmaps
* @default 0.2
* @apioption plotOptions.series.states.hover.brightness
*/
brightness: 0.2
},
/**
* @apioption plotOptions.series.states.normal
*/
normal: {
/**
* @productdesc {highmaps}
* The animation adds some latency in order to reduce the effect
* of flickering when hovering in and out of for example an
* uneven coastline.
*
* @sample {highmaps} maps/plotoptions/series-states-animation-false/
* No animation of fill color
*
* @apioption plotOptions.series.states.normal.animation
*/
animation: true
},
/**
* @apioption plotOptions.series.states.select
*/
select: {
/**
* @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject}
* @default ${palette.neutralColor20}
* @product highmaps
* @apioption plotOptions.series.states.select.color
*/
color: palette.neutralColor20
},
inactive: {
opacity: 1
}
}
});
return MapSeries;
}(ScatterSeries));
extend(MapSeries.prototype, {
type: 'map',
axisTypes: colorMapSeriesMixin.axisTypes,
colorAttribs: colorMapSeriesMixin.colorAttribs,
colorKey: colorMapSeriesMixin.colorKey,
// When tooltip is not shared, this series (and derivatives) requires
// direct touch/hover. KD-tree does not apply.
directTouch: true,
// We need the points' bounding boxes in order to draw the data labels,
// so we skip it now and call it from drawPoints instead.
drawDataLabels: noop,
// No graph for the map series
drawGraph: noop,
drawLegendSymbol: LegendSymbol.drawRectangle,
forceDL: true,
getExtremesFromAll: true,
getSymbol: colorMapSeriesMixin.getSymbol,
parallelArrays: colorMapSeriesMixin.parallelArrays,
pointArrayMap: colorMapSeriesMixin.pointArrayMap,
pointClass: MapPoint,
// X axis and Y axis must have same translation slope
preserveAspectRatio: true,
searchPoint: noop,
trackerGroups: colorMapSeriesMixin.trackerGroups,
// Get axis extremes from paths, not values
useMapGeometry: true
});
SeriesRegistry.registerSeriesType('map', MapSeries);
/* *
*
* Default Export
*
* */
export default MapSeries;
/* *
*
* API Options
*
* */
/**
* A map data object containing a `path` definition and optionally additional
* properties to join in the data as per the `joinBy` option.
*
* @sample maps/demo/category-map/
* Map data and joinBy
*
* @type {Array<Highcharts.SeriesMapDataOptions>|*}
* @product highmaps
* @apioption series.mapData
*/
/**
* A `map` series. If the [type](#series.map.type) option is not specified, it
* is inherited from [chart.type](#chart.type).
*
* @extends series,plotOptions.map
* @excluding dataParser, dataURL, marker
* @product highmaps
* @apioption series.map
*/
/**
* An array of data points for the series. For the `map` series type, points can
* be given in the following ways:
*
* 1. An array of numerical values. In this case, the numerical values will be
* interpreted as `value` options. Example:
* ```js
* data: [0, 5, 3, 5]
* ```
*
* 2. An array of arrays with 2 values. In this case, the values correspond to
* `[hc-key, value]`. Example:
* ```js
* data: [
* ['us-ny', 0],
* ['us-mi', 5],
* ['us-tx', 3],
* ['us-ak', 5]
* ]
* ```
*
* 3. An array of objects with named values. The following snippet shows only a
* few settings, see the complete options set below. If the total number of
* data points exceeds the series'
* [turboThreshold](#series.map.turboThreshold),
* this option is not available.
* ```js
* data: [{
* value: 6,
* name: "Point2",
* color: "#00FF00"
* }, {
* value: 6,
* name: "Point1",
* color: "#FF00FF"
* }]
* ```
*
* @type {Array<number|Array<string,(number|null)>|null|*>}
* @product highmaps
* @apioption series.map.data
*/
/**
* Individual color for the point. By default the color is either used
* to denote the value, or pulled from the global `colors` array.
*
* @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject}
* @product highmaps
* @apioption series.map.data.color
*/
/**
* Individual data label for each point. The options are the same as
* the ones for [plotOptions.series.dataLabels](
* #plotOptions.series.dataLabels).
*
* @sample maps/series/data-datalabels/
* Disable data labels for individual areas
*
* @type {Highcharts.DataLabelsOptions}
* @product highmaps
* @apioption series.map.data.dataLabels
*/
/**
* The `id` of a series in the [drilldown.series](#drilldown.series)
* array to use for a drilldown for this point.
*
* @sample maps/demo/map-drilldown/
* Basic drilldown
*
* @type {string}
* @product highmaps
* @apioption series.map.data.drilldown
*/
/**
* An id for the point. This can be used after render time to get a
* pointer to the point object through `chart.get()`.
*
* @sample maps/series/data-id/
* Highlight a point by id
*
* @type {string}
* @product highmaps
* @apioption series.map.data.id
*/
/**
* When data labels are laid out on a map, Highmaps runs a simplified
* algorithm to detect collision. When two labels collide, the one with
* the lowest rank is hidden. By default the rank is computed from the
* area.
*
* @type {number}
* @product highmaps
* @apioption series.map.data.labelrank
*/
/**
* The relative mid point of an area, used to place the data label.
* Ranges from 0 to 1\. When `mapData` is used, middleX can be defined
* there.
*
* @type {number}
* @default 0.5
* @product highmaps
* @apioption series.map.data.middleX
*/
/**
* The relative mid point of an area, used to place the data label.
* Ranges from 0 to 1\. When `mapData` is used, middleY can be defined
* there.
*
* @type {number}
* @default 0.5
* @product highmaps
* @apioption series.map.data.middleY
*/
/**
* The name of the point as shown in the legend, tooltip, dataLabel
* etc.
*
* @sample maps/series/data-datalabels/
* Point names
*
* @type {string}
* @product highmaps
* @apioption series.map.data.name
*/
/**
* For map and mapline series types, the SVG path for the shape. For
* compatibily with old IE, not all SVG path definitions are supported,
* but M, L and C operators are safe.
*
* To achieve a better separation between the structure and the data,
* it is recommended to use `mapData` to define that paths instead
* of defining them on the data points themselves.
*
* @sample maps/series/data-path/
* Paths defined in data
*
* @type {string}
* @product highmaps
* @apioption series.map.data.path
*/
/**
* The numeric value of the data point.
*
* @type {number|null}
* @product highmaps
* @apioption series.map.data.value
*/
/**
* Individual point events
*
* @extends plotOptions.series.point.events
* @product highmaps
* @apioption series.map.data.events
*/
''; // adds doclets above to the transpiled file
|
import * as React from 'react';
import { assert } from 'chai';
function assertDOMNode(node) {
// duck typing a DOM node
assert.ok(node.nodeName);
}
/**
* Utility method to make assertions about the ref on an element
* @param {React.ReactElement} element - The element should have a component wrapped
* in withStyles as the root
* @param {function} mount - Should be returnvalue of createMount
* @param {function} onRef - Callback, first arg is the ref.
* Assert that the ref is a DOM node by default
*/
export default function testRef(element, mount, onRef = assertDOMNode) {
const ref = React.createRef();
const wrapper = mount(React.createElement(React.Fragment, null, React.cloneElement(element, {
ref
})));
onRef(ref.current, wrapper);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.