code
stringlengths 2
1.05M
|
---|
import { ClientFunction } from 'testcafe';
import helper from '../test-helper';
const getTestVariableValue = ClientFunction(() => window.test);
fixture `Fixture`
.clientScripts({ content: 'window.test = true;' })
.after(() => {
helper.counter++;
helper.emitter.emit('tests-completed');
});
test('test', async () => {
helper.data[helper.counter] = await getTestVariableValue();
});
|
// Place your application-specific JavaScript functions and classes for
// the admin panel here.
$(function() {
$("#quicksearch").searchField();
});
|
/*
Highcharts JS v7.0.3 (2019-02-06)
Indicator series type for Highstock
(c) 2010-2019 Daniel Studencki
License: www.highcharts.com/license
*/
(function(d){"object"===typeof module&&module.exports?(d["default"]=d,module.exports=d):"function"===typeof define&&define.amd?define(function(){return d}):d("undefined"!==typeof Highcharts?Highcharts:void 0)})(function(d){var t=function(b){var d=b.each,k=b.merge,q=b.error,r=b.defined,h=b.seriesTypes.sma;return{pointArrayMap:["top","bottom"],pointValKey:"top",linesApiNames:["bottomLine"],getTranslatedLinesNames:function(a){var c=[];d(this.pointArrayMap,function(e){e!==a&&c.push("plot"+e.charAt(0).toUpperCase()+
e.slice(1))});return c},toYData:function(a){var c=[];d(this.pointArrayMap,function(e){c.push(a[e])});return c},translate:function(){var a=this,c=a.pointArrayMap,e=[],b,e=a.getTranslatedLinesNames();h.prototype.translate.apply(a,arguments);d(a.points,function(l){d(c,function(c,d){b=l[c];null!==b&&(l[e[d]]=a.yAxis.toPixels(b,!0))})})},drawGraph:function(){var a=this,c=a.linesApiNames,e=a.points,b=e.length,l=a.options,w=a.graph,m={options:{gapSize:l.gapSize}},n=[],g=a.getTranslatedLinesNames(a.pointValKey),
f;d(g,function(a,c){for(n[c]=[];b--;)f=e[b],n[c].push({x:f.x,plotX:f.plotX,plotY:f[a],isNull:!r(f[a])});b=e.length});d(c,function(c,b){n[b]?(a.points=n[b],l[c]?a.options=k(l[c].styles,m):q('Error: "There is no '+c+' in DOCS options declared. Check if linesApiNames are consistent with your DOCS line names." at mixin/multiple-line.js:34'),a.graph=a["graph"+c],h.prototype.drawGraph.call(a),a["graph"+c]=a.graph):q('Error: "'+c+" doesn't have equivalent in pointArrayMap. To many elements in linesApiNames relative to pointArrayMap.\"")});
a.points=e;a.options=l;a.graph=w;h.prototype.drawGraph.call(a)}}}(d);(function(b,d){var k=b.seriesTypes.sma,q=b.seriesTypes.ema,r=b.seriesTypes.atr,h=b.merge,a=b.correctFloat;b.seriesType("keltnerchannels","sma",{params:{period:20,periodATR:10,multiplierATR:2},bottomLine:{styles:{lineWidth:1,lineColor:void 0}},topLine:{styles:{lineWidth:1,lineColor:void 0}},tooltip:{pointFormat:'\x3cspan style\x3d"color:{point.color}"\x3e\u25cf\x3c/span\x3e\x3cb\x3e {series.name}\x3c/b\x3e\x3cbr/\x3eUpper Channel: {point.top}\x3cbr/\x3eEMA({series.options.params.period}): {point.middle}\x3cbr/\x3eLower Channel: {point.bottom}\x3cbr/\x3e'},
marker:{enabled:!1},dataGrouping:{approximation:"averages"},lineWidth:1},h(d,{pointArrayMap:["top","middle","bottom"],pointValKey:"middle",nameBase:"Keltner Channels",nameComponents:["period","periodATR","multiplierATR"],linesApiNames:["topLine","bottomLine"],requiredIndicators:["ema","atr"],init:function(){k.prototype.init.apply(this,arguments);this.options=h({topLine:{styles:{lineColor:this.color}},bottomLine:{styles:{lineColor:this.color}}},this.options)},getValues:function(c,b){var d=b.period,
e=b.periodATR,h=b.multiplierATR,m=c.yData,m=m?m.length:0,n=[],g,f,k;b=q.prototype.getValues(c,{period:d,index:b.index});var t=r.prototype.getValues(c,{period:e}),u=[],v=[],p;if(m<d)return!1;for(p=d;p<=m;p++)g=b.values[p-d],f=t.values[p-e],k=g[0],c=a(g[1]+h*f[1]),f=a(g[1]-h*f[1]),g=g[1],n.push([k,c,g,f]),u.push(k),v.push([c,g,f]);return{values:n,xData:u,yData:v}}}))})(d,t)});
//# sourceMappingURL=keltner-channels.js.map
|
export { default } from 'ember-ckeditor/components/ember-ckeditor';
|
/*
Highcharts JS v7.1.3 (2019-08-14)
(c) 2009-2019 Highsoft AS
License: www.highcharts.com/license
*/
(function(a){"object"===typeof module&&module.exports?(a["default"]=a,module.exports=a):"function"===typeof define&&define.amd?define("highcharts/themes/avocado",["highcharts"],function(b){a(b);a.Highcharts=b;return a}):a("undefined"!==typeof Highcharts?Highcharts:void 0)})(function(a){function b(a,b,c,d){a.hasOwnProperty(b)||(a[b]=d.apply(null,c))}a=a?a._modules:{};b(a,"themes/avocado.js",[a["parts/Globals.js"]],function(a){a.theme={colors:["#F3E796","#95C471","#35729E","#251735"],colorAxis:{maxColor:"#05426E",
minColor:"#F3E796"},plotOptions:{map:{nullColor:"#fcfefe"}},navigator:{maskFill:"rgba(170, 205, 170, 0.5)",series:{color:"#95C471",lineColor:"#35729E"}}};a.setOptions(a.theme)});b(a,"masters/themes/avocado.src.js",[],function(){})});
//# sourceMappingURL=avocado.js.map
|
export class ClickEvent {
constructor() {
this.enable = false;
this.mode = [];
}
load(data) {
if (data !== undefined) {
if (data.enable !== undefined) {
this.enable = data.enable;
}
if (data.mode !== undefined) {
this.mode = data.mode;
}
}
}
}
|
export{Angulartics2Mixpanel}from"./mixpanel";
|
import jQuery from "ember-views/system/jquery";
import run from "ember-metal/run_loop";
import EmberView from "ember-views/views/view";
var trim = jQuery.trim;
var originalLookup = Ember.lookup;
var lookup, App, view;
QUnit.module("test Ember.Handlebars.bootstrap", {
setup: function() {
Ember.lookup = lookup = { Ember: Ember };
},
teardown: function() {
Ember.TEMPLATES = {};
Ember.lookup = originalLookup;
if(App) { run(App, 'destroy'); }
if (view) { run(view, 'destroy'); }
}
});
function checkTemplate(templateName) {
run(function() {
Ember.Handlebars.bootstrap(jQuery('#qunit-fixture'));
});
var template = Ember.TEMPLATES[templateName];
ok(template, 'template is available on Ember.TEMPLATES');
equal(jQuery('#qunit-fixture script').length, 0, 'script removed');
var view = EmberView.create({
template: template,
context: {
firstName: 'Tobias',
drug: 'teamocil'
}
});
run(function() {
view.createElement();
});
equal(trim(view.$().text()), 'Tobias takes teamocil', 'template works');
run(function() {
view.destroy();
});
}
test('template with data-template-name should add a new template to Ember.TEMPLATES', function() {
jQuery('#qunit-fixture').html('<script type="text/x-handlebars" data-template-name="funkyTemplate">{{firstName}} takes {{drug}}</script>');
checkTemplate('funkyTemplate');
});
test('template with id instead of data-template-name should add a new template to Ember.TEMPLATES', function() {
jQuery('#qunit-fixture').html('<script type="text/x-handlebars" id="funkyTemplate" >{{firstName}} takes {{drug}}</script>');
checkTemplate('funkyTemplate');
});
test('template without data-template-name or id should default to application', function() {
jQuery('#qunit-fixture').html('<script type="text/x-handlebars">{{firstName}} takes {{drug}}</script>');
checkTemplate('application');
});
test('template with type text/x-raw-handlebars should be parsed', function() {
jQuery('#qunit-fixture').html('<script type="text/x-raw-handlebars" data-template-name="funkyTemplate">{{name}}</script>');
run(function() {
Ember.Handlebars.bootstrap(jQuery('#qunit-fixture'));
});
ok(Ember.TEMPLATES['funkyTemplate'], 'template with name funkyTemplate available');
// This won't even work with Ember templates
equal(trim(Ember.TEMPLATES['funkyTemplate']({ name: 'Tobias' })), "Tobias");
});
test('duplicated default application templates should throw exception', function() {
jQuery('#qunit-fixture').html('<script type="text/x-handlebars">first</script><script type="text/x-handlebars">second</script>');
throws(function () {
Ember.Handlebars.bootstrap(jQuery('#qunit-fixture'));
},
/Template named "[^"]+" already exists\./,
"duplicate templates should not be allowed");
});
test('default application template and id application template present should throw exception', function() {
jQuery('#qunit-fixture').html('<script type="text/x-handlebars">first</script><script type="text/x-handlebars" id="application">second</script>');
throws(function () {
Ember.Handlebars.bootstrap(jQuery('#qunit-fixture'));
},
/Template named "[^"]+" already exists\./,
"duplicate templates should not be allowed");
});
test('default application template and data-template-name application template present should throw exception', function() {
jQuery('#qunit-fixture').html('<script type="text/x-handlebars">first</script><script type="text/x-handlebars" data-template-name="application">second</script>');
throws(function () {
Ember.Handlebars.bootstrap(jQuery('#qunit-fixture'));
},
/Template named "[^"]+" already exists\./,
"duplicate templates should not be allowed");
});
test('duplicated template id should throw exception', function() {
jQuery('#qunit-fixture').html('<script type="text/x-handlebars" id="funkyTemplate">first</script><script type="text/x-handlebars" id="funkyTemplate">second</script>');
throws(function () {
Ember.Handlebars.bootstrap(jQuery('#qunit-fixture'));
},
/Template named "[^"]+" already exists\./,
"duplicate templates should not be allowed");
});
test('duplicated template data-template-name should throw exception', function() {
jQuery('#qunit-fixture').html('<script type="text/x-handlebars" data-template-name="funkyTemplate">first</script><script type="text/x-handlebars" data-template-name="funkyTemplate">second</script>');
throws(function () {
Ember.Handlebars.bootstrap(jQuery('#qunit-fixture'));
},
/Template named "[^"]+" already exists\./,
"duplicate templates should not be allowed");
});
if (Ember.component) {
test('registerComponents initializer', function(){
Ember.TEMPLATES['components/x-apple'] = 'asdf';
App = run(Ember.Application, 'create');
ok(Ember.Handlebars.helpers['x-apple'], 'x-apple helper is present');
ok(App.__container__.has('component:x-apple'), 'the container is aware of x-apple');
});
test('registerComponents and generated components', function(){
Ember.TEMPLATES['components/x-apple'] = 'asdf';
App = run(Ember.Application, 'create');
view = App.__container__.lookup('component:x-apple');
equal(view.get('layoutName'), 'components/x-apple', 'has correct layout name');
});
test('registerComponents and non-geneated components', function(){
Ember.TEMPLATES['components/x-apple'] = 'asdf';
run(function(){
App = Ember.Application.create();
// currently Component code must be loaded before initializers
// this is mostly due to how they are bootstrapped. We will hopefully
// sort this out soon.
App.XAppleComponent = Ember.Component.extend({
isCorrect: true
});
});
view = App.__container__.lookup('component:x-apple');
equal(view.get('layoutName'), 'components/x-apple', 'has correct layout name');
ok(view.get('isCorrect'), 'ensure a non-generated component');
});
}
|
/* global QUnit */
import { InterleavedBuffer } from '../../../../src/core/InterleavedBuffer.js';
import { DynamicDrawUsage } from '../../../../src/constants.js';
export default QUnit.module( 'Core', () => {
QUnit.module( 'InterleavedBuffer', () => {
function checkInstanceAgainstCopy( instance, copiedInstance, assert ) {
assert.ok( copiedInstance instanceof InterleavedBuffer, 'the clone has the correct type' );
for ( var i = 0; i < instance.array.length; i ++ ) {
assert.ok( copiedInstance.array[ i ] === instance.array[ i ], 'array was copied' );
}
assert.ok( copiedInstance.stride === instance.stride, 'stride was copied' );
assert.ok( copiedInstance.usage === DynamicDrawUsage, 'usage was copied' );
}
// INSTANCING
QUnit.todo( 'Instancing', ( assert ) => {
assert.ok( false, 'everything\'s gonna be alright' );
} );
// PROPERTIES
QUnit.test( 'needsUpdate', ( assert ) => {
var a = new InterleavedBuffer( new Float32Array( [ 1, 2, 3, 4 ] ), 2 );
a.needsUpdate = true;
assert.strictEqual( a.version, 1, 'Check version increased' );
} );
// PUBLIC STUFF
QUnit.todo( 'isInterleavedBuffer', ( assert ) => {
assert.ok( false, 'everything\'s gonna be alright' );
} );
QUnit.test( 'setUsage', ( assert ) => {
var instance = new InterleavedBuffer();
instance.setUsage( DynamicDrawUsage );
assert.strictEqual( instance.usage, DynamicDrawUsage, 'Usage was set' );
} );
QUnit.test( 'copy', ( assert ) => {
var array = new Float32Array( [ 1, 2, 3, 7, 8, 9 ] );
var instance = new InterleavedBuffer( array, 3 );
instance.setUsage( DynamicDrawUsage );
checkInstanceAgainstCopy( instance, instance.copy( instance ), assert );
} );
QUnit.test( 'copyAt', ( assert ) => {
var a = new InterleavedBuffer( new Float32Array( [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ] ), 3 );
var b = new InterleavedBuffer( new Float32Array( 9 ), 3 );
var expected = new Float32Array( [ 4, 5, 6, 7, 8, 9, 1, 2, 3 ] );
b.copyAt( 1, a, 2 );
b.copyAt( 0, a, 1 );
b.copyAt( 2, a, 0 );
assert.deepEqual( b.array, expected, 'Check the right values were replaced' );
} );
QUnit.test( 'set', ( assert ) => {
var instance = new InterleavedBuffer( new Float32Array( [ 1, 2, 3, 7, 8, 9 ] ), 3 );
instance.set( [ 0, - 1 ] );
assert.ok( instance.array[ 0 ] === 0 && instance.array[ 1 ] === - 1, 'replace at first by default' );
} );
QUnit.test( 'onUpload', ( assert ) => {
var a = new InterleavedBuffer();
var func = function () { };
a.onUpload( func );
assert.strictEqual( a.onUploadCallback, func, 'Check callback was set properly' );
} );
// OTHERS
QUnit.test( 'count', ( assert ) => {
var instance = new InterleavedBuffer( new Float32Array( [ 1, 2, 3, 7, 8, 9 ] ), 3 );
assert.equal( instance.count, 2, 'count is calculated via array length / stride' );
} );
} );
} );
|
/*!
* time-stamp <https://github.com/jonschlinkert/time-stamp>
*
* Copyright (c) 2015-2018, Jon Schlinkert.
* Released under the MIT License.
*/
'use strict';
var dateRegex = /(?=(YYYY|YY|MM|DD|HH|mm|ss|ms))\1([:\/]*)/g;
var timespan = {
YYYY: ['getFullYear', 4],
YY: ['getFullYear', 2],
MM: ['getMonth', 2, 1], // getMonth is zero-based, thus the extra increment field
DD: ['getDate', 2],
HH: ['getHours', 2],
mm: ['getMinutes', 2],
ss: ['getSeconds', 2],
ms: ['getMilliseconds', 3]
};
var timestamp = function(str, date, utc) {
if (typeof str !== 'string') {
date = str;
str = 'YYYY-MM-DD';
}
if (!date) date = new Date();
return str.replace(dateRegex, function(match, key, rest) {
var args = timespan[key];
var name = args[0];
var chars = args[1];
if (utc === true) name = 'getUTC' + name.slice(3);
var val = '00' + String(date[name]() + (args[2] || 0));
return val.slice(-chars) + (rest || '');
});
};
timestamp.utc = function(str, date) {
return timestamp(str, date, true);
};
module.exports = timestamp;
|
var searchData=
[
['type',['Type',['../enumcom_1_1thalmic_1_1myo_1_1_classifier_event_1_1_type.html',1,'com::thalmic::myo::ClassifierEvent']]]
];
|
/*
* Copyright (c) 2014 Adobe Systems Incorporated. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global define */
define({
/**
* Errors
*/
// General file io error strings
"GENERIC_ERROR" : "(fel {0})",
"NOT_FOUND_ERR" : "Filen kunde inte hittas.",
"NOT_READABLE_ERR" : "Filen kunde inte läsas.",
"NO_MODIFICATION_ALLOWED_ERR" : "Målmappen kunde inte ändras.",
"NO_MODIFICATION_ALLOWED_ERR_FILE" : "Du har inte behörighet att modifiera filen.",
"CONTENTS_MODIFIED_ERR" : "Filen har ändrats utanför {APP_NAME}.",
"UNSUPPORTED_ENCODING_ERR" : "{APP_NAME} stöder just nu bara textfiler kodade i UTF-8.",
"FILE_EXISTS_ERR" : "Filen eller mappen existerar redan.",
"FILE" : "fil",
"FILE_TITLE" : "Fil",
"DIRECTORY" : "mapp",
"DIRECTORY_TITLE" : "Mapp",
"DIRECTORY_NAMES_LEDE" : "Mappnamn",
"FILENAMES_LEDE" : "Filnamn",
"FILENAME" : "filnamn",
"DIRECTORY_NAME" : "mappnamn",
// Project error strings
"ERROR_LOADING_PROJECT" : "Projektet kunde inte öppnas",
"OPEN_DIALOG_ERROR" : "Ett fel inträffade när öppna-dialogen skulle visas. (fel {0})",
"REQUEST_NATIVE_FILE_SYSTEM_ERROR" : "Ett fel inträffade när mappen skulle öppnas <span class='dialog-filename'>{0}</span>. (fel {1})",
"READ_DIRECTORY_ENTRIES_ERROR" : "Ett fel inträffade när mappens innehåll skulle läsas <span class='dialog-filename'>{0}</span>. (fel {1})",
// File open/save error string
"ERROR_OPENING_FILE_TITLE" : "Filen kunde inte öppnas",
"ERROR_OPENING_FILE" : "Ett fel inträffade när filen <span class='dialog-filename'>{0}</span> skulle öppnas. {1}",
"ERROR_OPENING_FILES" : "Ett fel inträffade när följande filer skulle öppnas:",
"ERROR_RELOADING_FILE_TITLE" : "Filen kunde inte laddas om",
"ERROR_RELOADING_FILE" : "Ett fel inträffade när filen <span class='dialog-filename'>{0}</span> skulle läsas om. {1}",
"ERROR_SAVING_FILE_TITLE" : "Filen kunde inte sparas",
"ERROR_SAVING_FILE" : "Ett fel inträffade när filen <span class='dialog-filename'>{0}</span> skulle sparas. {1}",
"ERROR_RENAMING_FILE_TITLE" : "Filen kunde inte döpas om",
"ERROR_RENAMING_FILE" : "Ett fel uppstod när filen <span class='dialog-filename'>{0}</span> skulle döpas om. {1}",
"ERROR_DELETING_FILE_TITLE" : "Filen kunde inte raderas",
"ERROR_DELETING_FILE" : "Ett fel uppstod när filen <span class='dialog-filename'>{0}</span> skulle tas bort. {1}",
"INVALID_FILENAME_TITLE" : "Ogiltigt filnamn",
"INVALID_FILENAME_MESSAGE" : "Filnamn får inte innehålla följande tecken: {0} eller innehålla ord som reserverats av systemet.",
"ENTRY_WITH_SAME_NAME_EXISTS" : "En fil eller mapp med namnet <span class='dialog-filename'>{0}</span> existerar redan.",
"ERROR_CREATING_FILE_TITLE" : "Filen {0} kunde inte skapas",
"ERROR_CREATING_FILE" : "Ett fel uppstod när {0} <span class='dialog-filename'>{1}</span> skulle skapas. {2}",
// Application preferences corrupt error strings
"ERROR_PREFS_CORRUPT_TITLE" : "Kunde inte läsa inställningar",
"ERROR_PREFS_CORRUPT" : "Din inställningsfil är inte korrekt formaterad JSON. Filen kommer att öppnas så att du kan korrigera felet. Du kommer att behöva starta om {APP_NAME} för att ändringarna ska träda i kraft.",
// Application error strings
"ERROR_IN_BROWSER_TITLE" : "Ajdå! {APP_NAME} körs inte i webbläsaren ännu.",
"ERROR_IN_BROWSER" : "{APP_NAME} är byggd i HTML, men körs just nu som en skrivbordsapplikation så att du kan använda den för att redigera lokala filer. Vänligen använd skalapplikationen <b>github.com/adobe/brackets-shell</b> för att köra {APP_NAME}.",
// ProjectManager max files error string
"ERROR_MAX_FILES_TITLE" : "Fel vid indexering av filer",
"ERROR_MAX_FILES" : "Det maximala antalet filer har indexerats. Funktioner som använder sig av indexet kanske inte kommer att fungera som förväntat.",
// Live Preview error strings
"ERROR_LAUNCHING_BROWSER_TITLE" : "Webbläsaren kunde inte öppnas.",
"ERROR_CANT_FIND_CHROME" : "Google Chrome kunde inte hittas. Kontrollera att den är installerad.",
"ERROR_LAUNCHING_BROWSER" : "Ett fel inträffade då webbläsaren skulle startas. (fel {0})",
"LIVE_DEVELOPMENT_ERROR_TITLE" : "Förhandsvisning misslyckades",
"LIVE_DEVELOPMENT_RELAUNCH_TITLE" : "Ansluter till webbläsaren",
"LIVE_DEVELOPMENT_ERROR_MESSAGE" : "För att förhandsvisningen ska lyckas måste Chrome startas om med fjärrfelsökning aktiverad.<br /><br />Vill du starta om Chrome och aktivera fjärrfelsökning?",
"LIVE_DEV_LOADING_ERROR_MESSAGE" : "Lyckades inte ladda förhandsvisningssidan.",
"LIVE_DEV_NEED_HTML_MESSAGE" : "Öppna en HTML-fil eller kontrollera att det finns en fil med namnet index.html i din projektmapp för att kunna starta förhandsvisningen.",
"LIVE_DEV_NEED_BASEURL_MESSAGE" : "För att starta förhandsvisningen med en fil innehållande serverkod måste du ange en bas-URL för detta projekt.",
"LIVE_DEV_SERVER_NOT_READY_MESSAGE" : "Ett fel uppstod när webbsevern för förhandsvisningen skulle startas. Vänligen försök igen.",
"LIVE_DEVELOPMENT_INFO_TITLE" : "Välkommen till förhandsvisningen!",
"LIVE_DEVELOPMENT_INFO_MESSAGE" : "Förhandsvisningen ansluter {APP_NAME} till din webbläsare. Den öppnar en förhandsvisning av din HTML-fil i webbläsaren och uppdaterar förhandsvisningen så fort ändringar skett i koden.<br /><br />I denna tidiga version av {APP_NAME} fungerar förhandsvisningen endast för redigering av <strong>CSS- och HTML-filer</strong> och endast med <strong>Google Chrome</strong>. Vid ändringar i JavaScript-kod laddas webbläsaren om när du sparar filen.<br /><br />(Du kommer bara se detta meddelande en gång.)",
"LIVE_DEVELOPMENT_TROUBLESHOOTING" : "För mer information se <a href='{0}' title='{0}'>Troubleshooting Live Development connection errors</a>.",
"LIVE_DEV_STATUS_TIP_NOT_CONNECTED" : "Förhandsvisning",
"LIVE_DEV_STATUS_TIP_PROGRESS1" : "Förhandsvisning: Ansluter\u2026",
"LIVE_DEV_STATUS_TIP_PROGRESS2" : "Förhandsvisning: Initierar\u2026",
"LIVE_DEV_STATUS_TIP_CONNECTED" : "Koppla från förhandsvisningen",
"LIVE_DEV_STATUS_TIP_OUT_OF_SYNC" : "Förhandsvisning (spara filen för att uppdatera)",
"LIVE_DEV_STATUS_TIP_SYNC_ERROR" : "Förhandsvisning (uppdateras inte på grund av syntaxfel)",
"LIVE_DEV_DETACHED_REPLACED_WITH_DEVTOOLS" : "Förhandsvisningen avbröts eftersom webbläsarens utvecklarverktyg öppnades.",
"LIVE_DEV_DETACHED_TARGET_CLOSED" : "Förhandsvisningen avbröst eftersom sidan stängdes i webbläsaren.",
"LIVE_DEV_NAVIGATED_AWAY" : "Förhandsvisningen avbröts eftersom webbläsaren navigerades till en sida som inte är del av det nuvarande projektet.",
"LIVE_DEV_CLOSED_UNKNOWN_REASON" : "Förhandsvisningen avbröts på grund av ett okänt fel. ({0})",
"SAVE_CLOSE_TITLE" : "Spara ändringar?",
"SAVE_CLOSE_MESSAGE" : "Vill du spara de ändringar i dokumentet <span class='dialog-filename'>{0}</span>?",
"SAVE_CLOSE_MULTI_MESSAGE" : "Vill du spara ändringarna du gjort följande filer?",
"EXT_MODIFIED_TITLE" : "Externa ändringar",
"CONFIRM_FOLDER_DELETE_TITLE" : "Bekräfta borttagning",
"CONFIRM_FOLDER_DELETE" : "Är du säker att du vill radera mappen <span class='dialog-filename'>{0}</span>?",
"FILE_DELETED_TITLE" : "Filen raderades",
"EXT_MODIFIED_WARNING" : "<span class='dialog-filename'>{0}</span> har ändrats.<br /><br />Vill du spara filen och skriva över dessa ändringar?",
"EXT_MODIFIED_MESSAGE" : "<span class='dialog-filename'>{0}</span> har ändrats men har också osparade ändringar i {APP_NAME}.<br /><br />Vilken version vill du behålla?",
"EXT_DELETED_MESSAGE" : "<span class='dialog-filename'>{0}</span> har raderats man har också osparade ändringar i {APP_NAME}.<br /><br />Vill du behålla dina ändringar?",
// Generic dialog/button labels
"DONE" : "Klar",
"OK" : "OK",
"CANCEL" : "Avbryt",
"DONT_SAVE" : "Spara inte",
"SAVE" : "Spara",
"SAVE_AS" : "Spara som\u2026",
"SAVE_AND_OVERWRITE" : "Spara och skriv över",
"DELETE" : "Radera",
"BUTTON_YES" : "Ja",
"BUTTON_NO" : "Nej",
// Find, Replace, Find in Files
"FIND_RESULT_COUNT" : "{0} träffar",
"FIND_RESULT_COUNT_SINGLE" : "1 träff",
"FIND_NO_RESULTS" : "Inga träffar",
"FIND_QUERY_PLACEHOLDER" : "Sök\u2026",
"REPLACE_PLACEHOLDER" : "Ersätt med\u2026",
"BUTTON_REPLACE_ALL" : "Alla\u2026",
"BUTTON_REPLACE_ALL_IN_FILES" : "Ersätt\u2026",
"BUTTON_REPLACE" : "Ersätt",
"BUTTON_NEXT" : "\u25B6",
"BUTTON_PREV" : "\u25C0",
"BUTTON_NEXT_HINT" : "Nästa träff",
"BUTTON_PREV_HINT" : "Föregående träff",
"BUTTON_CASESENSITIVE_HINT" : "Skiftlägeskänslig",
"BUTTON_REGEXP_HINT" : "Regular Expression",
"REPLACE_WITHOUT_UNDO_WARNING_TITLE": "Ersätt utan att ångra",
"REPLACE_WITHOUT_UNDO_WARNING" : "Eftersom mer än {0} filer ändras kommer {APP_NAME} ändra dessa utan att de öppnas.<br />Du kommer inte att kunna ånga ändringarna i dessa filer.",
"BUTTON_REPLACE_WITHOUT_UNDO" : "Ersätt utan att ångra",
"OPEN_FILE" : "Öppna fil",
"SAVE_FILE_AS" : "Spara fil som",
"CHOOSE_FOLDER" : "Välj mapp",
"RELEASE_NOTES" : "Versionsinformation",
"NO_UPDATE_TITLE" : "Du är uppdaterad!",
"NO_UPDATE_MESSAGE" : "Du använder den senaste versionen av {APP_NAME}.",
// Find and Replace
"FIND_REPLACE_TITLE_LABEL" : "Ersätt",
"FIND_REPLACE_TITLE_WITH" : "med",
"FIND_TITLE_LABEL" : "Hittades",
"FIND_TITLE_SUMMARY" : "— {0} {1} {2} i {3}",
// Find in Files
"FIND_NUM_FILES" : "{0} {1}",
"FIND_IN_FILES_SCOPED" : "i <span class='dialog-filename'>{0}</span>",
"FIND_IN_FILES_NO_SCOPE" : "i projekt",
"FIND_IN_FILES_ZERO_FILES" : "Filter exkluderar alla filer {0}",
"FIND_IN_FILES_FILE" : "fil",
"FIND_IN_FILES_FILES" : "filer",
"FIND_IN_FILES_MATCH" : "träff",
"FIND_IN_FILES_MATCHES" : "träffar",
"FIND_IN_FILES_MORE_THAN" : "Mer än ",
"FIND_IN_FILES_PAGING" : "{0}—{1}",
"FIND_IN_FILES_FILE_PATH" : "<span class='dialog-filename'>{0}</span> {2} <span class='dialog-path'>{1}</span>", // We should use normal dashes on Windows instead of em dash eventually
"FIND_IN_FILES_EXPAND_COLLAPSE" : "Ctrl/Cmd-klicka för att expandera/minimera alla",
"REPLACE_IN_FILES_ERRORS_TITLE" : "Ersättningsfel",
"REPLACE_IN_FILES_ERRORS" : "Följande filer ändrades inte eftersom de förändrats efter sökningen eller inte kunde skrivas till.",
"ERROR_FETCHING_UPDATE_INFO_TITLE" : "Fel vid hämtning av versioninformation",
"ERROR_FETCHING_UPDATE_INFO_MSG" : "Det gick inte att hämta versionsinformation från servern. Kontrollera din internetuppkoppling och försök igen.",
// File exclusion filters
"NEW_FILE_FILTER" : "Nytt exkluderingsset\u2026",
"CLEAR_FILE_FILTER" : "Exkludera inte filer",
"NO_FILE_FILTER" : "Exkludera filer\u2026",
"EXCLUDE_FILE_FILTER" : "Exkludera {0}",
"EDIT_FILE_FILTER" : "Redigera\u2026",
"FILE_FILTER_DIALOG" : "Redigera filter",
"FILE_FILTER_INSTRUCTIONS" : "Exkludera filer och mappar som matchar någon av följande strängar, substrängar eller <a href='{0}' title='{0}'>wildcards</a>. Ange varje sträng på en ny rad.",
"FILTER_NAME_PLACEHOLDER" : "Namnge detta exkluderingsset (frivilligt)",
"FILE_FILTER_CLIPPED_SUFFIX" : "och {0} till",
"FILTER_COUNTING_FILES" : "Räknar filer\u2026",
"FILTER_FILE_COUNT" : "Tillåter {0} av {1} filer {2}",
"FILTER_FILE_COUNT_ALL" : "Tillåter alla {0} filer {1}",
// Quick Edit
"ERROR_QUICK_EDIT_PROVIDER_NOT_FOUND" : "Ingen Quick Edit är tillgänglig vid markörens nuvarande position",
"ERROR_CSSQUICKEDIT_BETWEENCLASSES" : "CSS Quick Edit: placera markören på ett klassnamn",
"ERROR_CSSQUICKEDIT_CLASSNOTFOUND" : "CSS Quick Edit: ofullständigt klassattribut",
"ERROR_CSSQUICKEDIT_IDNOTFOUND" : "CSS Quick Edit: ofullständigt ID-attribut",
"ERROR_CSSQUICKEDIT_UNSUPPORTEDATTR" : "CSS Quick Edit: placera markören inom en tagg, klass eller ID",
"ERROR_TIMINGQUICKEDIT_INVALIDSYNTAX" : "CSS tidsfunktion Quick Edit: felaktigt syntax",
"ERROR_JSQUICKEDIT_FUNCTIONNOTFOUND" : "JS Quick Edit: placera markören på ett funktionsnamn",
// Quick Docs
"ERROR_QUICK_DOCS_PROVIDER_NOT_FOUND" : "Inga Quick Docs är tillgängliga vid markörens nuvarande position",
/**
* ProjectManager
*/
"PROJECT_LOADING" : "Öppnar\u2026",
"UNTITLED" : "Namnlös",
"WORKING_FILES" : "Öppna filer",
/**
* Keyboard modifier names
*/
"KEYBOARD_CTRL" : "Ctrl",
"KEYBOARD_SHIFT" : "Shift",
"KEYBOARD_SPACE" : "Space",
/**
* StatusBar strings
*/
"STATUSBAR_CURSOR_POSITION" : "Rad {0}, kolumn {1}",
"STATUSBAR_SELECTION_CH_SINGULAR" : " \u2014 Markerade {0} kolumn",
"STATUSBAR_SELECTION_CH_PLURAL" : " \u2014 Markerade {0} kolumner",
"STATUSBAR_SELECTION_LINE_SINGULAR" : " \u2014 Markerade {0} rad",
"STATUSBAR_SELECTION_LINE_PLURAL" : " \u2014 Markerade {0} rader",
"STATUSBAR_SELECTION_MULTIPLE" : " \u2014 {0} markeringar",
"STATUSBAR_INDENT_TOOLTIP_SPACES" : "Klicka för att använda mellanslag för indrag",
"STATUSBAR_INDENT_TOOLTIP_TABS" : "Klicka för att använda tabbar för indrag",
"STATUSBAR_INDENT_SIZE_TOOLTIP_SPACES" : "Klicka för att ändra antalet mellanslag som används för indrag",
"STATUSBAR_INDENT_SIZE_TOOLTIP_TABS" : "Klicka för att ändra bredden på tabbtecken",
"STATUSBAR_SPACES" : "Mellanslag:",
"STATUSBAR_TAB_SIZE" : "Tabbstorlek:",
"STATUSBAR_LINE_COUNT_SINGULAR" : "\u2014 {0} rad",
"STATUSBAR_LINE_COUNT_PLURAL" : "\u2014 {0} rader",
"STATUSBAR_USER_EXTENSIONS_DISABLED" : "Tillägg har avaktiverats",
"STATUSBAR_INSERT" : "INS",
"STATUSBAR_OVERWRITE" : "ÖVR",
"STATUSBAR_DEFAULT_LANG" : "(standard)",
// CodeInspection: errors/warnings
"ERRORS_PANEL_TITLE_MULTIPLE" : "{0} fel",
"SINGLE_ERROR" : "1 {0} fel",
"MULTIPLE_ERRORS" : "{1} {0} fel",
"NO_ERRORS" : "Inga {0} fel funna - bra jobbat!",
"NO_ERRORS_MULTIPLE_PROVIDER" : "Inga fel funna - bra jobbat!",
"LINT_DISABLED" : "Linting är avaktiverat.",
"NO_LINT_AVAILABLE" : "Ingen linter är tillgänglig för {0}",
"NOTHING_TO_LINT" : "Ingenting att linta",
"LINTER_TIMED_OUT" : "{0} har avbrutits efter att ha väntat {1} ms",
"LINTER_FAILED" : "{0} avbröts efter ett fel: {1}",
/**
* Command Name Constants
*/
// File menu commands
"FILE_MENU" : "Arkiv",
"CMD_FILE_NEW_UNTITLED" : "Ny",
"CMD_FILE_NEW" : "Ny fil",
"CMD_FILE_NEW_FOLDER" : "Ny mapp",
"CMD_FILE_OPEN" : "Öppna\u2026",
"CMD_ADD_TO_WORKING_SET" : "Lägg till i arbetsyta",
"CMD_OPEN_DROPPED_FILES" : "Öppna släppta filer",
"CMD_OPEN_FOLDER" : "Öppna mapp\u2026",
"CMD_FILE_CLOSE" : "Stäng",
"CMD_FILE_CLOSE_ALL" : "Stäng alla",
"CMD_FILE_CLOSE_LIST" : "Stäng lista",
"CMD_FILE_CLOSE_OTHERS" : "Stäng andra",
"CMD_FILE_CLOSE_ABOVE" : "Stäng andra ovanför",
"CMD_FILE_CLOSE_BELOW" : "Stäng andra nedanför",
"CMD_FILE_SAVE" : "Spara",
"CMD_FILE_SAVE_ALL" : "Spara alla",
"CMD_FILE_SAVE_AS" : "Spara som\u2026",
"CMD_LIVE_FILE_PREVIEW" : "Förhandsvisning",
"CMD_RELOAD_LIVE_PREVIEW" : "Tvinga uppdatering av förhandsvisningen",
"CMD_PROJECT_SETTINGS" : "Projektinställningar\u2026",
"CMD_FILE_RENAME" : "Byt namn",
"CMD_FILE_DELETE" : "Radera",
"CMD_INSTALL_EXTENSION" : "Installera tillägg\u2026",
"CMD_EXTENSION_MANAGER" : "Tilläggshanteraren\u2026",
"CMD_FILE_REFRESH" : "Uppdatera filträd",
"CMD_QUIT" : "Avsluta",
// Used in native File menu on Windows
"CMD_EXIT" : "Avsluta",
// Edit menu commands
"EDIT_MENU" : "Redigera",
"CMD_UNDO" : "Ångra",
"CMD_REDO" : "Gör om",
"CMD_CUT" : "Klipp ut",
"CMD_COPY" : "Kopiera",
"CMD_PASTE" : "Klistra in",
"CMD_SELECT_ALL" : "Markera alla",
"CMD_SELECT_LINE" : "Markera rad",
"CMD_SPLIT_SEL_INTO_LINES" : "Dela markering i rader",
"CMD_ADD_CUR_TO_NEXT_LINE" : "Lägg till markör på nästa rad",
"CMD_ADD_CUR_TO_PREV_LINE" : "Lägg till markör på föregående rad",
"CMD_INDENT" : "Öka indrag",
"CMD_UNINDENT" : "Minska indrag",
"CMD_DUPLICATE" : "Duplicera",
"CMD_DELETE_LINES" : "Radera rad",
"CMD_COMMENT" : "Växla kommentarsrad",
"CMD_BLOCK_COMMENT" : "Växla blockkommentar",
"CMD_LINE_UP" : "Flytta rad uppåt",
"CMD_LINE_DOWN" : "Flytta rad nedåt",
"CMD_OPEN_LINE_ABOVE" : "Öppna rad ovanför",
"CMD_OPEN_LINE_BELOW" : "Öppna rad nedanför",
"CMD_TOGGLE_CLOSE_BRACKETS" : "Stäng paranteser automatiskt",
"CMD_SHOW_CODE_HINTS" : "Visa kodförslag",
// Search menu commands
"FIND_MENU" : "Sök",
"CMD_FIND" : "Sök",
"CMD_FIND_NEXT" : "Sök nästa",
"CMD_FIND_PREVIOUS" : "Sök föregående",
"CMD_FIND_ALL_AND_SELECT" : "Sök och markera alla",
"CMD_ADD_NEXT_MATCH" : "Lägg nästa träff till markering",
"CMD_SKIP_CURRENT_MATCH" : "Hoppa över och lägg till nästa träff",
"CMD_FIND_IN_FILES" : "Sök i filer",
"CMD_FIND_IN_SELECTED" : "Sök i markerad fil/mapp",
"CMD_FIND_IN_SUBTREE" : "Sök i\u2026",
"CMD_REPLACE" : "Ersätt",
"CMD_REPLACE_IN_FILES" : "Ersätt i filer",
"CMD_REPLACE_IN_SELECTED" : "Ersätt i markerad fil/mapp",
"CMD_REPLACE_IN_SUBTREE" : "Ersätt i\u2026",
// View menu commands
"VIEW_MENU" : "Visa",
"CMD_HIDE_SIDEBAR" : "Dölj sidomeny",
"CMD_SHOW_SIDEBAR" : "Visa sidomeny",
"CMD_INCREASE_FONT_SIZE" : "Öka textstorlek",
"CMD_DECREASE_FONT_SIZE" : "Minska teckenstorlek",
"CMD_RESTORE_FONT_SIZE" : "Återställ teckenstorlek",
"CMD_SCROLL_LINE_UP" : "Skrolla rad uppåt",
"CMD_SCROLL_LINE_DOWN" : "Skrolla rad nedåt",
"CMD_TOGGLE_LINE_NUMBERS" : "Radnummer",
"CMD_TOGGLE_ACTIVE_LINE" : "Markera aktiv rad",
"CMD_TOGGLE_WORD_WRAP" : "Automatisk radbrytning",
"CMD_LIVE_HIGHLIGHT" : "Markera förhandsvisning",
"CMD_VIEW_TOGGLE_INSPECTION" : "Linta filer vid spara",
"CMD_SORT_WORKINGSET_BY_ADDED" : "Sortera efter senast tillagd",
"CMD_SORT_WORKINGSET_BY_NAME" : "Sortera efter namn",
"CMD_SORT_WORKINGSET_BY_TYPE" : "Sortera efter typ",
"CMD_SORT_WORKINGSET_AUTO" : "Automatisk sortering",
"CMD_THEMES" : "Teman\u2026",
// Navigate menu Commands
"NAVIGATE_MENU" : "Navigera",
"CMD_QUICK_OPEN" : "Snabböppna",
"CMD_GOTO_LINE" : "Gå till rad",
"CMD_GOTO_DEFINITION" : "Gå till definition",
"CMD_GOTO_FIRST_PROBLEM" : "Gå till första fel/varning",
"CMD_TOGGLE_QUICK_EDIT" : "Snabbredigering",
"CMD_TOGGLE_QUICK_DOCS" : "Quick Docs",
"CMD_QUICK_EDIT_PREV_MATCH" : "Föregående träff",
"CMD_QUICK_EDIT_NEXT_MATCH" : "Nästa träff",
"CMD_CSS_QUICK_EDIT_NEW_RULE" : "Ny regel",
"CMD_NEXT_DOC" : "Nästa dokument",
"CMD_PREV_DOC" : "Föregående dokument",
"CMD_SHOW_IN_TREE" : "Visa i filträdet",
"CMD_SHOW_IN_EXPLORER" : "Visa i Utforskaren",
"CMD_SHOW_IN_FINDER" : "Visa i Finder",
"CMD_SHOW_IN_OS" : "Visa i operativsystemet",
// Help menu commands
"HELP_MENU" : "Hjälp",
"CMD_CHECK_FOR_UPDATE" : "Sök efter uppdateringar",
"CMD_HOW_TO_USE_BRACKETS" : "Hur du använder {APP_NAME}",
"CMD_SUPPORT" : "{APP_NAME}-forum",
"CMD_SUGGEST" : "Föreslå en funktion",
"CMD_RELEASE_NOTES" : "Versionsinformation",
"CMD_GET_INVOLVED" : "Engagera dig",
"CMD_SHOW_EXTENSIONS_FOLDER" : "Visa tilläggsmapp",
"CMD_HOMEPAGE" : "Webbplats för {APP_TITLE}",
"CMD_TWITTER" : "{TWITTER_NAME} på Twitter",
"CMD_ABOUT" : "Om {APP_TITLE}",
"CMD_OPEN_PREFERENCES" : "Öppna inställningsfil",
// Strings for main-view.html
"EXPERIMENTAL_BUILD" : "experimental build",
"DEVELOPMENT_BUILD" : "development build",
"RELOAD_FROM_DISK" : "Ladda om",
"KEEP_CHANGES_IN_EDITOR" : "Behåll ändringar i editorn",
"CLOSE_DONT_SAVE" : "Stäng (spara inte)",
"RELAUNCH_CHROME" : "Starta om Chrome",
"ABOUT" : "Om",
"CLOSE" : "Stäng",
"ABOUT_TEXT_LINE1" : "sprint {VERSION_MINOR} {BUILD_TYPE} {VERSION}",
"ABOUT_TEXT_BUILD_TIMESTAMP" : "tidsstämpel för build: ",
"ABOUT_TEXT_LINE3" : "Meddelanden och villkor gällande program från tredje part finns på <a href='{ADOBE_THIRD_PARTY}'>{ADOBE_THIRD_PARTY}</a> och inkluderas här som referens.",
"ABOUT_TEXT_LINE4" : "Dokumentation och källkod återfinns på <a href='https://github.com/adobe/brackets/'>https://github.com/adobe/brackets/</a>",
"ABOUT_TEXT_LINE5" : "Skapat med \u2764 och JavaScript av:",
"ABOUT_TEXT_LINE6" : "Massor av människor (men vi har lite problem att visa dessa data just nu).",
"ABOUT_TEXT_WEB_PLATFORM_DOCS" : "Web Platform Docs och dess logotyp är licenserad under en Creative Commons Attribution-licens, <a href='{WEB_PLATFORM_DOCS_LICENSE}'>CC-BY 3.0 Unported</a>.",
"UPDATE_NOTIFICATION_TOOLTIP" : "En ny version av {APP_NAME} är tillgänglig! Klicka här för fler detaljer.",
"UPDATE_AVAILABLE_TITLE" : "Uppdatering tillgänglig!",
"UPDATE_MESSAGE" : "Hallå! En ny version av {APP_NAME} är tillgänglig. Här är några av de nya funktionerna:",
"GET_IT_NOW" : "Installera nu!",
"PROJECT_SETTINGS_TITLE" : "Projektinställningar för: {0}",
"PROJECT_SETTING_BASE_URL" : "URL till förhandsvisning",
"PROJECT_SETTING_BASE_URL_HINT" : "För att använda en lokal server anger du en adress liknande: http://localhost:8000/",
"BASEURL_ERROR_INVALID_PROTOCOL" : "{0}-protokollet stöder inte förhandsvisning — vänligen använd http: eller https: .",
"BASEURL_ERROR_SEARCH_DISALLOWED" : "Adressen kan inte innehålla sökparametrar som \"{0}\".",
"BASEURL_ERROR_HASH_DISALLOWED" : "Adressen kan inte innehålla hashar som \"{0}\".",
"BASEURL_ERROR_INVALID_CHAR" : "Specialtecken som '{0}' måste vara %-kodade.",
"BASEURL_ERROR_UNKNOWN_ERROR" : "Okänt fel när adressen skulle läsas!",
// Strings for themes-settings.html and themes-general.html
"CURRENT_THEME" : "Nuvarande tema",
"USE_THEME_SCROLLBARS" : "Använd temats scrollbars",
"FONT_SIZE" : "Teckenstorlek",
"FONT_FAMILY" : "Typsnitt",
// CSS Quick Edit
"BUTTON_NEW_RULE" : "Ny regel",
// Extension Management strings
"INSTALL" : "Installera",
"UPDATE" : "Uppdatera",
"REMOVE" : "Radera",
"OVERWRITE" : "Skriv över",
"CANT_REMOVE_DEV" : "Tillägg i mappen \"dev\" måste raderas manuellt.",
"CANT_UPDATE" : "Uppdateringen är inte kompatibel med denna version av {APP_NAME}.",
"CANT_UPDATE_DEV" : "Tilläggen i mappen \"dev\" kan inte uppdateras automatiskt.",
"INSTALL_EXTENSION_TITLE" : "Installera tillägg",
"UPDATE_EXTENSION_TITLE" : "Uppdatera tillägg",
"INSTALL_EXTENSION_LABEL" : "Tilläggets URL",
"INSTALL_EXTENSION_HINT" : "URL till tilläggets zip-fil eller GitHub-repository",
"INSTALLING_FROM" : "Installerar tillägg från {0}\u2026",
"INSTALL_SUCCEEDED" : "Tillägget installerades!",
"INSTALL_FAILED" : "Installationen misslyckades.",
"CANCELING_INSTALL" : "Avbryter\u2026",
"CANCELING_HUNG" : "Installationen avbröts då den tog för lång tid. Ett internt fel kan ha inträffat.",
"INSTALL_CANCELED" : "Installationen avbröts.",
"VIEW_COMPLETE_DESCRIPTION" : "Visa hela beskrivningen",
"VIEW_TRUNCATED_DESCRIPTION" : "Visa förkortad beskrivning",
// These must match the error codes in ExtensionsDomain.Errors.* :
"INVALID_ZIP_FILE" : "Det nedladdade innehållet är inte en fungerande zip-fil.",
"INVALID_PACKAGE_JSON" : "Filen package.json är inte korrekt (felet var: {0}).",
"MISSING_PACKAGE_NAME" : "Filen package.json innehåller inte tilläggets namn.",
"BAD_PACKAGE_NAME" : "{0} är inte ett godkänt namn.",
"MISSING_PACKAGE_VERSION" : "Filen package.json innehåller inte tilläggets versionsnummer.",
"INVALID_VERSION_NUMBER" : "Tilläggets versionsnummer ({0}) är felaktigt.",
"INVALID_BRACKETS_VERSION" : "Kompabilitetssträngen ({0}) för {APP_NAME} är felaktig.",
"DISALLOWED_WORDS" : "Orden ({1}) är inte tillåtna i {0}-fältet.",
"API_NOT_COMPATIBLE" : "Tillägget är inte kompatibelt med denna version av {APP_NAME}. Det har installerats i din mapp med inaktiverade tillägg.",
"MISSING_MAIN" : "Tillägget har ingen fil med namnet main.js.",
"EXTENSION_ALREADY_INSTALLED" : "Installationen av detta tillägg kommer att skriva över ett tidigare installerat tillägg. Vill du skriva över det befintliga tillägget?",
"EXTENSION_SAME_VERSION" : "Tillägget har samma versionsnummer som ett redan installerat tillägg. Vill du skriva över den befintliga installationen?",
"EXTENSION_OLDER_VERSION" : "Detta tillägg har versionsnummer {0} och är äldre än den nuvarade versionen ({1}). Vill du skriva över den befintliga installationen?",
"DOWNLOAD_ID_IN_USE" : "Internt fel: nedladdnings-ID används redan.",
"NO_SERVER_RESPONSE" : "Kunde inte ansluta till servern.",
"BAD_HTTP_STATUS" : "Filen kunde inte hittas på servern (HTTP {0}).",
"CANNOT_WRITE_TEMP" : "Kunde inte spara filen temporärt.",
"ERROR_LOADING" : "Tillägget stötte på ett fel under uppstart.",
"MALFORMED_URL" : "Adressen är felaktig. Vänligen kontrollera att du angett den korrekt.",
"UNSUPPORTED_PROTOCOL" : "Adressen måste använda http eller https.",
"UNKNOWN_ERROR" : "Okänt internt fel.",
// For NOT_FOUND_ERR, see generic strings above
"EXTENSION_MANAGER_TITLE" : "Tilläggshanteraren",
"EXTENSION_MANAGER_ERROR_LOAD" : "Kunde inte nå tilläggsregistret. Vänligen försök igen senare.",
"INSTALL_EXTENSION_DRAG" : "Dra .zip hit eller",
"INSTALL_EXTENSION_DROP" : "Släpp .zip här för att installera",
"INSTALL_EXTENSION_DROP_ERROR" : "Installation/Uppdatering avbröts på grund av följande fel:",
"INSTALL_FROM_URL" : "Installera från URL\u2026",
"INSTALL_EXTENSION_VALIDATING" : "Validerar\u2026",
"EXTENSION_AUTHOR" : "Författare",
"EXTENSION_DATE" : "Datum",
"EXTENSION_INCOMPATIBLE_NEWER" : "Detta tillägg kräver en nyare version av {APP_NAME}.",
"EXTENSION_INCOMPATIBLE_OLDER" : "Detta tillägg fungerar för närvarande bara med äldre versioner av {APP_NAME}.",
"EXTENSION_LATEST_INCOMPATIBLE_NEWER" : "Version {0} av detta tillägg kräver en nyare version av {APP_NAME} men du kan installera den äldre versionen {1}.",
"EXTENSION_LATEST_INCOMPATIBLE_OLDER" : "Version {0} av detta tillägg fungerar endast med äldre versioner av {APP_NAME} men du kan installera den äldre versionen {1}.",
"EXTENSION_NO_DESCRIPTION" : "Ingen beskrivning",
"EXTENSION_MORE_INFO" : "Mer information...",
"EXTENSION_ERROR" : "Tilläggsfel",
"EXTENSION_KEYWORDS" : "Nyckelord",
"EXTENSION_TRANSLATED_USER_LANG" : "Översatt till {0} språk, inklusive ditt",
"EXTENSION_TRANSLATED_GENERAL" : "Översatt till {0} språk",
"EXTENSION_TRANSLATED_LANGS" : "Detta tillägg har översatts till dessa språk: {0}",
"EXTENSION_INSTALLED" : "Installerade",
"EXTENSION_UPDATE_INSTALLED" : "Uppdateringen av detta tillägg har laddats ner och kommer att installeras när {APP_NAME} startas om.",
"EXTENSION_SEARCH_PLACEHOLDER" : "Sök",
"EXTENSION_MORE_INFO_LINK" : "Mer",
"BROWSE_EXTENSIONS" : "Bläddra bland tillägg",
"EXTENSION_MANAGER_REMOVE" : "Ta bort tillägg",
"EXTENSION_MANAGER_REMOVE_ERROR" : "Kunde inte ta bort ett eller flera tillägg: {0}. {APP_NAME} kommer fortfarande att startas om.",
"EXTENSION_MANAGER_UPDATE" : "Uppdatera tillägg",
"EXTENSION_MANAGER_UPDATE_ERROR" : "Kunde inte uppdatera ett eller flera tillägg: {0}. {APP_NAME} kommer fortfarande att startas om.",
"MARKED_FOR_REMOVAL" : "Markerad för borttagning",
"UNDO_REMOVE" : "Ångra",
"MARKED_FOR_UPDATE" : "Markerad för uppdatering",
"UNDO_UPDATE" : "Ångra",
"CHANGE_AND_RELOAD_TITLE" : "Ändra tillägg",
"CHANGE_AND_RELOAD_MESSAGE" : "{APP_NAME} måste startas om för att uppdatera eller ta bort markerade tillägg. Du kommer att få en fråga om att spara eventuella osparade ändringar.",
"REMOVE_AND_RELOAD" : "Ta bort tillägg och starta om",
"CHANGE_AND_RELOAD" : "Ta bort tillägg och starta om",
"UPDATE_AND_RELOAD" : "Ändra tillägg och starta om",
"PROCESSING_EXTENSIONS" : "Genomför förändringar av tillägg\u2026",
"EXTENSION_NOT_INSTALLED" : "Kunde inte radera tillägget {0} då det inte är installerat.",
"NO_EXTENSIONS" : "Inga tillägg har installerats ännu.<br>Klicka på fliken Tillgängliga för att komma igång.",
"NO_EXTENSION_MATCHES" : "Inga tillägg matchade din sökning.",
"REGISTRY_SANITY_CHECK_WARNING" : "Var försiktig när du installerar tillägg från okända källor.",
"EXTENSIONS_INSTALLED_TITLE" : "Installerade",
"EXTENSIONS_AVAILABLE_TITLE" : "Tillgängliga",
"EXTENSIONS_UPDATES_TITLE" : "Uppdateringar",
"INLINE_EDITOR_NO_MATCHES" : "Inga träffar tillgängliga.",
"CSS_QUICK_EDIT_NO_MATCHES" : "Det finns inga CSS-regler som matchar din markering.<br> Klicka på \"Ny regel\" för att skapa en.",
"CSS_QUICK_EDIT_NO_STYLESHEETS" : "Det finns inga stilmallar i ditt projekt.<br>Skapa en flr att lägga till CSS-regler.",
// Custom Viewers
"IMAGE_VIEWER_LARGEST_ICON" : "största",
/**
* Unit names
*/
"UNIT_PIXELS" : "pixlar",
// extensions/default/DebugCommands
"DEBUG_MENU" : "Debug",
"ERRORS" : "Fel",
"CMD_SHOW_DEV_TOOLS" : "Visa utvecklarverktyg",
"CMD_REFRESH_WINDOW" : "Starta om med tillägg",
"CMD_RELOAD_WITHOUT_USER_EXTS" : "Starta om utan tillägg",
"CMD_NEW_BRACKETS_WINDOW" : "Nytt {APP_NAME}-fönster",
"CMD_SWITCH_LANGUAGE" : "Byt språk",
"CMD_RUN_UNIT_TESTS" : "Kör tester",
"CMD_SHOW_PERF_DATA" : "Visa prestandadata",
"CMD_ENABLE_NODE_DEBUGGER" : "Aktivera Node-debugger",
"CMD_LOG_NODE_STATE" : "Skriv ut Node-status till konsollen",
"CMD_RESTART_NODE" : "Starta om Node",
"CMD_SHOW_ERRORS_IN_STATUS_BAR" : "Visa fel i statusraden",
"LANGUAGE_TITLE" : "Byt språk",
"LANGUAGE_MESSAGE" : "Språk:",
"LANGUAGE_SUBMIT" : "Uppdatera {APP_NAME}",
"LANGUAGE_CANCEL" : "Avbryt",
"LANGUAGE_SYSTEM_DEFAULT" : "Systemstandard",
// extensions/default/InlineTimingFunctionEditor
"INLINE_TIMING_EDITOR_TIME" : "Tid",
"INLINE_TIMING_EDITOR_PROGRESSION" : "Progression",
"BEZIER_EDITOR_INFO" : "<kbd>↑</kbd><kbd>↓</kbd><kbd>←</kbd><kbd>→</kbd> Flytta markerad punkt<br><kbd class='text'>Shift</kbd> Flytta tio enheter",
"STEPS_EDITOR_INFO" : "<kbd>↑</kbd><kbd>↓</kbd> Öka eller minska antal steg<br><kbd>←</kbd><kbd>→</kbd> 'Start' eller 'Slut'",
"INLINE_TIMING_EDITOR_INVALID" : "Det tidigare värdet <code>{0}</code> är inte korrekt så den visade funktionen har ändrats till <code>{1}</code>. Dokumentet kommer att uppdateras med det första värdet.",
// extensions/default/InlineColorEditor
"COLOR_EDITOR_CURRENT_COLOR_SWATCH_TIP" : "Nuvarande färg",
"COLOR_EDITOR_ORIGINAL_COLOR_SWATCH_TIP" : "Originalfärg",
"COLOR_EDITOR_RGBA_BUTTON_TIP" : "RGBa-format",
"COLOR_EDITOR_HEX_BUTTON_TIP" : "Hex-format",
"COLOR_EDITOR_HSLA_BUTTON_TIP" : "HSLa-format",
"COLOR_EDITOR_USED_COLOR_TIP_SINGULAR" : "{0} (använd {1} gång)",
"COLOR_EDITOR_USED_COLOR_TIP_PLURAL" : "{0} (använd {1} gånger)",
// extensions/default/JavaScriptCodeHints
"CMD_JUMPTO_DEFINITION" : "Gå till definition",
"CMD_SHOW_PARAMETER_HINT" : "Visa parameterförslag",
"NO_ARGUMENTS" : "<inga parametrar>",
"DETECTED_EXCLUSION_TITLE" : "Problem att slutleda JavaScript-fil",
"DETECTED_EXCLUSION_INFO" : "Brackets stötte på processeringsfel:<br><br>{0}<br><br>Denna fil kommer inte längre genomsökas efter kodförslag eller definitioner. Öppna <code>.brackets.json</code> och ta bort filen från jscodehints.detectedExclusions för att återställa detta.",
// extensions/default/JSLint
"JSLINT_NAME" : "JSLint",
// extensions/default/QuickView
"CMD_ENABLE_QUICK_VIEW" : "Quick View vid hover",
// extensions/default/RecentProjects
"CMD_TOGGLE_RECENT_PROJECTS" : "Senaste projekt",
// extensions/default/WebPlatformDocs
"DOCS_MORE_LINK" : "Läs mer"
});
/* Last translated for 2f5acd9c6fb21330cad0dae16e26bf659859583e */
|
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'use strict';
/**
* The properties for a Media Services REST API endpoint.
*
*/
class ApiEndpoint {
/**
* Create a ApiEndpoint.
* @member {string} [endpoint] The Media Services REST endpoint.
* @member {string} [majorVersion] The version of Media Services REST API.
*/
constructor() {
}
/**
* Defines the metadata of ApiEndpoint
*
* @returns {object} metadata of ApiEndpoint
*
*/
mapper() {
return {
required: false,
serializedName: 'ApiEndpoint',
type: {
name: 'Composite',
className: 'ApiEndpoint',
modelProperties: {
endpoint: {
required: false,
serializedName: 'endpoint',
type: {
name: 'String'
}
},
majorVersion: {
required: false,
serializedName: 'majorVersion',
type: {
name: 'String'
}
}
}
}
};
}
}
module.exports = ApiEndpoint;
|
var parent = require('../../../actual/string/virtual/pad-start');
module.exports = parent;
|
Prism.languages.http={"request-line":{pattern:/^(POST|GET|PUT|DELETE|OPTIONS|PATCH|TRACE|CONNECT)\b\shttps?:\/\/\S+\sHTTP\/[0-9.]+/g,inside:{property:/^\b(POST|GET|PUT|DELETE|OPTIONS|PATCH|TRACE|CONNECT)\b/g,"attr-name":/:\w+/g}},"response-status":{pattern:/^HTTP\/1.[01] [0-9]+.*/g,inside:{property:/[0-9]+[A-Z\s-]+$/gi}},keyword:/^[\w-]+:(?=.+)/gm};var httpLanguages={"application/json":Prism.languages.javascript,"application/xml":Prism.languages.markup,"text/xml":Prism.languages.markup,"text/html":Prism.languages.markup};for(var contentType in httpLanguages)if(httpLanguages[contentType]){var options={};options[contentType]={pattern:new RegExp("(content-type:\\s*"+contentType+"[\\w\\W]*?)\\n\\n[\\w\\W]*","gi"),lookbehind:!0,inside:{rest:httpLanguages[contentType]}},Prism.languages.insertBefore("http","keyword",options)}
|
version https://git-lfs.github.com/spec/v1
oid sha256:607455e5cbf203081b2874ef87502dbaf05d027677da4c769b2e103983d0b1d9
size 1971
|
'use strict'
var helper = require("../../helper");
var GarmentInventoryDocumentManager = require("../../../src/managers/inventory-garment/garment-inventory-document-manager");
var productDataUtil = require('../master/garment-product-data-util');
var storageDataUtil = require('../master/storage-data-util');
var uomDataUtil = require('../master/uom-data-util');
var codeGenerator = require('../../../src/utils/code-generator');
var Models = require("dl-models");
var Map = Models.map;
var GarmentInventoryMovementModel = Models.garmentInventory.GarmentInventoryMovement;
class GarmentInventoryDocumentDataUtil {
getNewData() {
return Promise.all([ productDataUtil.getTestData(), storageDataUtil.getGarmentInventTestData(),uomDataUtil.getTestData()])
.then(result => {
var product = result[0];
var storage = result[1];
var uom = result [2];
var code = codeGenerator()
var data = {
code: code,
referenceNo: `RFNO-${code}`,
referenceType: 'unit-test-doc',
type: "IN",
date: new Date(),
storageId: storage._id,
items:[ {
productId: product._id,
quantity: 1000,
uomId: uom._id
}]
};
return data;
})
}
getNewTestData() {
return helper
.getManager(GarmentInventoryDocumentManager)
.then((manager) => {
return this.getNewData().then((data) => {
return manager.create(data)
.then((id) => {
return manager.getSingleById(id)
});
});
});
}
getPackingNewData() {
return Promise.all([productDataUtil.getTestData(), storageDataUtil.getPackingTestData(), uomDataUtil.getTestData()])
.then(result => {
var product = result[0];
var storage = result[1];
var uom = result[2];
var code = codeGenerator()
var data = {
code: code,
referenceNo: `RFNO-${code}`,
referenceType: 'unit-test-doc',
type: "IN",
date: new Date(),
storageId: storage._id,
items: [{
productId: product._id,
quantity: 1000,
uomId: uom._id
}]
};
return data;
});
}
getPackingNewTestData() {
return helper
.getManager(GarmentInventoryDocumentManager)
.then((manager) => {
return this.getPackingNewData().then((data) => {
return manager.create(data)
.then((id) => {
return manager.getSingleById(id)
});
});
});
}
}
module.exports = new GarmentInventoryDocumentDataUtil();
|
export default function() {
return {
'/admin': ['wechat']
};
}
|
'use strict';
var app = angular.module('myApp.brand_users.directives', []);
app.directive('listBrandUsers', ['Referral', '$location', '$routeParams', function(Referral, $location, $routeParams) {
var link = function(scope,element,attrs) {
};
return {
link: link,
scope: {}
};
}]);
|
// api/policies/AuditPolicy.js
module.exports = require('sails-permissions/api/policies/AuditPolicy');
|
/* Copyright (c) 2015-2017 The Open Source Geospatial Foundation
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* A {@link GeoExt.data.model.print.Capability Capability} of a mapfish print
* service has many layouts. You can create correct instances of this class by
* using the GeoExt.data.MapfishPrintProvider.
*
* @class GeoExt.data.model.print.Layout
*/
Ext.define('GeoExt.data.model.print.Layout', {
extend: 'GeoExt.data.model.Base',
requires: [
'GeoExt.data.model.print.LayoutAttribute'
],
/**
* @method getCapability
* Returns the layouts parent print capabilities. May be null if Layout is
* instantiated directly.
* @return {GeoExt.data.model.print.Capability} The print capabilities
*/
/**
* @method attributes
* Returns an Ext.data.Store of referenced
* {@link GeoExt.data.model.print.LayoutAttribute}s.
* @return {Ext.data.Store} The store
*/
fields: [
{name: 'name', type: 'string'},
{
name: 'capabilityId',
reference: {
type: 'print.Capability',
inverse: 'layouts'
}
}
]
});
|
steal('can/util', 'can/observe', 'can/observe/compute', function(can) {
can.extend(can.Observe.List.prototype, {
filter : function(callback) {
// The filtered list
var filtered = new can.Observe.List();
var self = this;
// Creates the binder for a single element at a given index
var generator = function(element, index) {
// The event handler that updates the filtered list
var binder = function(ev, val) {
var index = filtered.indexOf(element);
// Remove it from the list if it exists but the new value is false
if(!val && index !== -1) {
filtered.splice(index, 1);
}
// Add it to the list if it isn't in there and the new value is true
if(val && index === -1) {
filtered.push(element);
}
};
// a can.compute that executes the callback
var compute = can.compute(function() {
return callback(element, self.indexOf(element), self);
});
// Update the filtered list on any compute change
compute.bind('change', binder);
// Call binder explicitly for the initial list
binder(null, compute());
};
// We also want to know when something gets added to our original list
this.bind('add', function(ev, data, index) {
can.each(data, function(element, i) {
// Call the generator for each newly added element
// The index is the start index + the loop index
generator(element, index + i);
});
});
// Removed items should be removed from both lists
this.bind('remove', function(ev, data, index) {
can.each(data, function(element, i) {
var index = filtered.indexOf(element);
if(index !== -1) {
filtered.splice(index, 1);
}
});
});
// Run the generator for each list element
this.forEach(generator);
return filtered;
},
map : function(callback) {
var mapped = new can.Observe.List();
var self = this;
// Again, lets run a generator function
var generator = function(element, index) {
// The can.compute for the mapping
var compute = can.compute(function() {
return callback(element, index, self);
});
compute.bind('change', function(ev, val) {
// On change, replace the current value with the new one
mapped.splice(index, 1, val);
});
mapped.push(compute());
}
this.forEach(generator);
// We also want to know when something gets added to our original list
this.bind('add', function(ev, data, index) {
can.each(data, function(element, i) {
// Call the generator for each newly added element
// The index is the start index + the loop index
generator(element, index + i);
});
});
this.bind('remove', function(ev, data, index) {
// The indices in the mapped list are the same so lets just splice it out
mapped.splice(index, data.length);
})
return mapped;
}
/* TODO
,
every : function() {
},
some : function(callback) {
},
reduce : function() {
},
reduceRight : function() {
},
max : function() {
},
min : function() {
}
*/
});
return can.Observe.List;
})
|
// Adapted from https://github.com/jonschlinkert/is-plain-object
export function isObjectLike(val) {
return val != null && typeof val === 'object';
}
function isObject(val) {
return isObjectLike(val) && Array.isArray(val) === false;
}
function isObjectObject(o) {
return isObject(o) === true
&& Object.prototype.toString.call(o) === '[object Object]';
}
export default function isPlainObject(o) {
if (isObjectObject(o) === false) return false;
// If has modified constructor
const ctor = o.constructor;
if (typeof ctor !== 'function') return false;
// If has modified prototype
const prot = ctor.prototype;
if (isObjectObject(prot) === false) return false;
// If constructor does not have an Object-specific method
if (prot.hasOwnProperty('isPrototypeOf') === false) {
return false;
}
// Most likely a plain Object
return true;
}
|
var reporter = require('nodeunit').reporters.default;
process.chdir(__dirname);
var run_tests = new Array();
var tests_available = {
'signals' : 'tests/signals.js',
'store': 'tests/store.js',
'recorder': 'tests/recorder.js'
};
var test_name;
// Check if any arguments were provided to the script
if(process.argv.length > 2) {
var i;
// For each argument, treat it as the name of a test
for(i = 2; i < process.argv.length; i++) {
test_name = process.argv[i];
if(tests_available.hasOwnProperty(test_name)) {
// Add the test to the list of tests to run
run_tests.push(tests_available[test_name]);
} else {
console.log("Invalid test '" + test_name + "'");
}
}
} else {
// No arguments provided to the script, so we run all the tests
for(test_name in tests_available) {
if(tests_available.hasOwnProperty(test_name)) {
run_tests.push(tests_available[test_name]);
}
}
}
// Tell the reporter to run the tests
if(run_tests.length > 0) {
reporter.run(run_tests);
}
|
//
// Open Weather Map
// core script for OpenLayers library
// http://openweathermap.org/wiki/API/OWM.OpenLayers.js
//
//
// Version 1.3.5
// 2012.11.21
// NEW tile server
//
// Version 1.3.4
// 2012.09.17
// NEW json API
// text weather conditions
//
// Version 1.3.2
// 2012.08.13
//
// Version 1.3.0.3
// 2012.08.03
// bug fixed
//
// 2012.08.03 1.3.0.3
// Add Composite layers for clouds and etc
//
// 1.3.0.2
// Change interface getrect function to version 1.9
// add WMS layers
//
// 1.3.0.1
// new weather icons
//
// 2012.05.23 Version 1.2.1
// OpenLayers.Layer.Vector.OWMStations
//
// 2012.05.20 Version 1.2
// добавлена серверная кластеризация. Она включена по умолчанию для класса
// OpenLayers.Layer.Vector.OWMWeather
// для класса OpenLayers.Layer.Vector.OWMStations в настоящий момент серверная кластеризация не работает
//
// 2012.05.10 Version 1.1
// добавлена клиентская кластеризация
//if (typeof OpenLayers == 'undefined') {
// throw "Needs OpenLayers.";
// console.log("Needs OpenLayers.");
//}
// Композитный слой tiles
OpenLayers.Layer.OWMComposite = OpenLayers.Class(OpenLayers.Layer.WMS, {
initialize:function(layer,name, params)
{
this.l = layer;
if(params == undefined) {
params = {isBaseLayer: false, opacity: 0.6}
}
params.attribution = 'Forecast layers from <a href="http://openweathermap.org/wiki/Models/GDPRS">Environment Canada</a>';
var newArguments = [
name,
"http://tile.openweathermap.org/wms",
{
layers: 'GLBETA_'+this.l,
SERVICE: 'WMS',
VERSION: "1.1.1",
REQUEST: 'GetMap',
transparent: "true",
format: 'image/png'
},
params
];
OpenLayers.Layer.WMS.prototype.initialize.apply(this,newArguments);
},
getURL: function (bounds) {
var z=this.map.getZoom();
this.params.LAYERS = 'GLBETA_'+this.l;
if(z > 5) {
b= this.map.getExtent();
if ( isREGETA(b) ) {
this.params.LAYERS = 'REGETA_'+this.l;
if(z > 7) {
if( isLAMARCTICETA(b) ) this.params.LAYERS = 'LAMARCTICETA_'+this.l;
else if( isLAMWESTETA(b) ) this.params.LAYERS = 'LAMWESTETA_'+this.l;
else if( isLAMMARITIMEETA(b) ) this.params.LAYERS = 'LAMMARITIMEETA_'+this.l;
else if( isLAMEASTETA(b) ) this.params.LAYERS = 'LAMEASTETA_'+this.l;
}
//console.log(this.params.LAYERS);
}
}
bounds = this.adjustBounds(bounds);
var imageSize = this.getImageSize();
var newParams = {};
// WMS 1.3 introduced axis order
var reverseAxisOrder = this.reverseAxisOrder();
newParams.BBOX = this.encodeBBOX ?
bounds.toBBOX(null, reverseAxisOrder) :
bounds.toArray(reverseAxisOrder);
newParams.WIDTH = imageSize.w;
newParams.HEIGHT = imageSize.h;
var requestString = this.getFullRequestString(newParams);
return requestString;
}
});
// Radar compozite wms layer
OpenLayers.Layer.OWMRadar = OpenLayers.Class(OpenLayers.Layer.WMS, {
initialize:function(name, params)
{
if(params == undefined) {
params = {isBaseLayer: false, opacity: 0.4}
}
params.attribution = 'Radar layer from <a href="http://openweathermap.org/wiki/Layer/radar">Environment Canada</a>';
var newArguments = [
name,
"http://tile.openweathermap.org/wms",
{
layers: 'RADAR.12KM',
SERVICE: 'WMS',
VERSION: "1.1.1",
REQUEST: 'GetMap',
transparent: "true",
format: 'image/png'
},
params
];
OpenLayers.Layer.WMS.prototype.initialize.apply(this,newArguments);
},
getURL: function (bounds) {
var z=this.map.getZoom();
this.params.LAYERS = z > 8 ? 'RADAR.2KM' : 'RADAR.12KM';
bounds = this.adjustBounds(bounds);
var imageSize = this.getImageSize();
var newParams = {};
// WMS 1.3 introduced axis order
var reverseAxisOrder = this.reverseAxisOrder();
newParams.BBOX = this.encodeBBOX ?
bounds.toBBOX(null, reverseAxisOrder) :
bounds.toArray(reverseAxisOrder);
newParams.WIDTH = imageSize.w;
newParams.HEIGHT = imageSize.h;
var requestString = this.getFullRequestString(newParams);
return requestString;
}
});
//
// WMS
//
OpenLayers.Layer.OWMwms = OpenLayers.Class(OpenLayers.Layer.WMS, {
initialize:function(layer, name, params)
{
if(params == undefined) {
params = {isBaseLayer: false, opacity: 0.3}
}
if( ! layer ) layer = GLBETA_PR;
if( ! name ) name = layer;
var newArguments = [
name,
"http://tile.openweathermap.org/wms",
{
layers: layer,
SERVICE: 'WMS',
VERSION: "1.1.1",
REQUEST: 'GetMap',
transparent: "true",
format: 'image/png'
},
params
];
OpenLayers.Layer.WMS.prototype.initialize.apply(this,newArguments);
}
});
OpenLayers.Layer.OWMCanada = OpenLayers.Class(OpenLayers.Layer.WMS, {
initialize:function(layer, name, params)
{
if(params == undefined) {
params = {isBaseLayer: false, opacity: 0.3}
}
if( ! layer ) layer = GLBETA_PR;
if( ! name ) name = layer;
var newArguments = [
name,
"",
{
layers: layer,
SERVICE: 'WMS',
VERSION: "1.1.1",
REQUEST: 'GetMap',
transparent: "true",
format: 'image/png'
},
params
];
OpenLayers.Layer.WMS.prototype.initialize.apply(this,newArguments);
},
getURL: function (bounds) {
bounds = this.adjustBounds(bounds);
var imageSize = this.getImageSize();
var newParams = {};
// WMS 1.3 introduced axis order
var reverseAxisOrder = this.reverseAxisOrder();
newParams.BBOX = this.encodeBBOX ?
bounds.toBBOX(null, reverseAxisOrder) :
bounds.toArray(reverseAxisOrder);
newParams.WIDTH = imageSize.w;
newParams.HEIGHT = imageSize.h;
var requestString = this.getFullRequestString(newParams);
requestString = "http://openweathermap.org/t/t?url="+requestString.replace(/&/g,"%26");
return requestString;
}
});
//
// Weather
//
// A specific format for parsing OpenWeatherMap Weather API JSON responses.
OpenLayers.Format.OWMWeather = OpenLayers.Class(OpenLayers.Format, {
read: function(obj) {
if(obj.cod !== '200') {
throw new Error(
['OWM failure response (', obj.cod,'): ',obj.message].join('') );
}
if(!obj || !obj.list || !OpenLayers.Util.isArray(obj.list )) {
throw new Error('Unexpected OWM response');
}
var list = obj.list, x, y, point, feature, features = [];
//console.log('time='+obj.calctime+', cnt='+obj.cnt +', '+ obj.message);
for(var i=0,l=list.length; i<l; i++) {
feature = new OpenLayers.Feature.Vector(
new OpenLayers.Geometry.Point(list[i].coord.lon, list[i].coord.lat),
{
title: list[i].name,
station: list[i],
temp: Math.round(10*(list[i].main.temp-273.15))/10
});
features.push(feature);
}
return features;
}
});
// Vector
//cluster.geometry.getBounds().getCenterLonLat();
OpenLayers.Layer.Vector.OWMWeather = OpenLayers.Class( OpenLayers.Layer.Vector, {
projection: new OpenLayers.Projection("EPSG:4326"),
strategies: [new OpenLayers.Strategy.BBOX({resFactor: 1})],
/* protocol: new OpenLayers.Protocol.Script({
url: "http://openweathermap.org/data/2.1/find/city",
params: {
// type: 'city',
cluster: 'yes',
cnt: 200,
format: 'json',
layer: this // идиотское решение, но я не понял как иначе достать OpenLayers.Layer.Vector
},
filterToParams: function(filter, params) {
if (filter.type === OpenLayers.Filter.Spatial.BBOX) {
params.bbox = filter.value.toArray();
params.bbox.push(params.layer.map.getZoom()); //магия - добавляю zoom в параметры
if (filter.projection) {
params.bbox.push(filter.projection.getCode());
}
}
return params;
},
callbackKey: 'callback',
format: new OpenLayers.Format.OWMWeather()
}), */
styleMap: new OpenLayers.StyleMap(
new OpenLayers.Style({
fontColor: "black",
fontSize: "12px",
fontFamily: "Arial, Courier New",
graphicXOffset: -20,
graphicYOffset: -5,
labelAlign: "lt",
labelXOffset: "-5",
labelYOffset: "-35",
labelOutlineColor: "white",
labelOutlineWidth: 3,
externalGraphic: "${icon}",
graphicWidth: 50,
label : "${temp}"+ "°C"
},
{
context:
{
icon: function(feature) {
if (feature.layer) {
return feature.layer.options.getIcon(feature.attributes.station);
} else {
// @ToDo: 1 Feature/layer doesn't have the layer set for some reason
return S3.Ap.concat("/static/img/gis/openlayers/blank.gif")
}
}
}
}
)),
initialize:function(name,options)
{
if (options == undefined) options = {};
if (options.eventListeners == undefined)
options.eventListeners = {
featureselected: this.onSelect,
featureunselected: this.onUnselect
}
if (options.iconsets == undefined) options.iconsets='main';
options.attribution = 'Weather from <a href="http://openweathermap.org/" alt="World Map and worldwide Weather Forecast online">OpenWeatherMap</a>';
if (options.getIcon == undefined) options.getIcon = this.getIcon;
if (options.getPopupHtml == undefined) {
options.getPopupHtml = this.getPopupHtml;
if (options.popupX == undefined) options.popupX = 150;
if (options.popupY == undefined) options.popupY = 175;
}
var newArguments = [];
newArguments.push(name, options);
OpenLayers.Layer.Vector.prototype.initialize.apply(this,newArguments);
this.protocol = new OpenLayers.Protocol.Script({
url: "http://openweathermap.org/data/2.1/find/city",
params: {
cluster: 'yes',
cnt: 200,
format: 'json',
layer: this // идиотское решение, но я не понял как иначе достать OpenLayers.Layer.Vector
},
filterToParams: function(filter, params) {
if (filter.type === OpenLayers.Filter.Spatial.BBOX) {
params.bbox = filter.value.toArray();
params.bbox.push(params.layer.map.getZoom()); //магия - добавляю zoom в параметры
if (filter.projection) {
params.bbox.push(filter.projection.getCode());
}
}
return params;
},
callbackKey: 'callback',
format: new OpenLayers.Format.OWMWeather()
});
},
onPopupClose: function(evt) {
var feature = this.feature;
if (feature.pois) { // The feature is not destroyed
selectControl.unselect(feature);
} else { // After "moveend" or "refresh" events on POIs layer all
this.destroy();
}
},
onSelect: function(evt) {
feature = evt.feature;
var html = this.options.getPopupHtml(feature.attributes.station);
popup = new OpenLayers.Popup("FramedCloud", feature.geometry.getBounds().getCenterLonLat(),
new OpenLayers.Size(this.options.popupX, this.options.popupY), html, "City", false);
feature.popup = popup;
popup.feature = feature;
this.map.addPopup(popup, true);
},
onUnselect: function (evt) {
feature = evt.feature;
if (feature.popup) {
popup.feature = null;
this.map.removePopup(feature.popup);
feature.popup.destroy();
feature.popup = null;
}
},
getPopupHtml: function(station) {
return GetWeatherPopupHtml(station);
},
getIcon: function(station) {
if( station.weather.length > 0 ) {
return 'http://openweathermap.org/img/w/' + station.weather[0].icon + '.png';
}else{
var dt= new Date();
var times = SunCalc.getTimes(dt, station.coord.lat, station.coord.lon);
if( dt>times.sunrise && dt < times.sunset ) var day='day'; else var day='night';
var icon = GetWeatherIconDay(station, day);
return 'http://openweathermap.org/img/w/' + icon;
}
}
});
//
// Stations
// A specific format for parsing OpenWeatherMap Stations API JSON responses.
//
OpenLayers.Format.OWMStations = OpenLayers.Class(OpenLayers.Format, {
read: function(obj) {
if(obj.cod !== '200') {
throw new Error(
['OWM failure response (', obj.cod,'): ',obj.message].join('') );
}
if(!obj || !obj.list || !OpenLayers.Util.isArray(obj.list )) {
throw new Error(
'Unexpected OWM response');
}
//console.log('time='+obj.calctime+', cnt='+obj.cnt +', '+ obj.message);
var list = obj.list, x, y, point,
feature, features = [];
for(var i=0,l=list.length; i<l; i++) {
// list[i].type = list[i].type;
if(!list[i].main) continue;
feature = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(list[i].coord.lon, list[i].coord.lat),
{
title: list[i].name,
station: list[i],
stationType: list[i].type,
temp: Math.round(10*(list[i].main.temp-273.15))/10
});
features.push(feature);
}
return features;
}
});
// Vector Class
OpenLayers.Layer.Vector.OWMStations = OpenLayers.Class( OpenLayers.Layer.Vector, {
projection: new OpenLayers.Projection("EPSG:4326"),
strategies: [
new OpenLayers.Strategy.BBOX({resFactor: 1})],
/* protocol: new OpenLayers.Protocol.Script({
url: "http://openweathermap.org/data/2.1/find/station",
params: {
// type: 'station',
cluster_distance: 120,
cluster: 'yes',
format: 'json',
layer: this // идиотское решение, но я не понял как иначе достать OpenLayers.Layer.Vector
},
filterToParams: function(filter, params) {
if (filter.type === OpenLayers.Filter.Spatial.BBOX) {
params.bbox = filter.value.toArray();
params.bbox.push(params.layer.map.getZoom()); //магия - добавляю zoom в параметры
if (filter.projection) {
params.bbox.push(filter.projection.getCode());
}
}
return params;
},
callbackKey: 'callback',
format: new OpenLayers.Format.OWMStations()
}), */
styleMap: new OpenLayers.StyleMap(
new OpenLayers.Style({
fontColor: "black",
fontSize: "12px",
fontFamily: "Courier New, monospace",
labelAlign: "lt",
labelXOffset: "-15",
labelYOffset: "-17",
labelOutlineColor: "white",
labelOutlineWidth: 3,
externalGraphic: "${icon}",
graphicWidth: 25,
label : "${temp}°C"
},{
context:
{
icon: function(feature) {
if (feature.layer) {
return feature.layer.options.getIcon(feature.attributes.station);
} else {
// @ToDo: 1 Feature/layer doesn't have the layer set for some reason
return S3.Ap.concat("/static/img/gis/openlayers/blank.gif");
}
}
}
}
)),
initialize:function(name,options)
{
if (options == undefined) options = {};
if (options.eventListeners == undefined)
options.eventListeners = {
featureselected: this.onSelect,
featureunselected: this.onUnselect
}
options.attribution = 'Weather from <a href="http://openweathermap.org/" alt="World Map and worldwide Weather Forecast online">OpenWeatherMap</a>';
var newArguments = [];
if (options.getIcon == undefined) options.getIcon = this.getIcon;
if (options.getPopupHtml == undefined) {
options.getPopupHtml = this.getPopupHtml;
if (options.popupX == undefined) options.popupX = 150;
if (options.popupY == undefined) options.popupY = 200;
}
newArguments.push(name, options);
OpenLayers.Layer.Vector.prototype.initialize.apply(this,newArguments);
this.StationPopupHtml = GetStationPopupHtml;
this.protocol = new OpenLayers.Protocol.Script({
url: "http://openweathermap.org/data/2.1/find/station",
params: {
cluster_distance: 120,
cluster: 'yes',
format: 'json',
layer: this // идиотское решение, но я не понял как иначе достать OpenLayers.Layer.Vector
},
filterToParams: function(filter, params) {
if (filter.type === OpenLayers.Filter.Spatial.BBOX) {
params.bbox = filter.value.toArray();
params.bbox.push(params.layer.map.getZoom()); //магия - добавляю zoom в параметры
if (filter.projection) {
params.bbox.push(filter.projection.getCode());
}
}
return params;
},
callbackKey: 'callback',
format: new OpenLayers.Format.OWMStations()
});
},
onPopupClose: function(evt) {
var feature = this.feature;
if (feature.pois) {
selectControl.unselect(feature);
} else {
this.destroy();
}
},
onSelect: function(evt) {
feature = evt.feature;
var html = this.options.getPopupHtml(feature.attributes.station);
popup = new OpenLayers.Popup("Popup",
feature.geometry.getBounds().getCenterLonLat(),
new OpenLayers.Size(this.options.popupX, this.options.popupY), html, "Station", false);
feature.popup = popup;
popup.feature = feature;
this.map.addPopup(popup, true);
},
onUnselect: function (evt) {
feature = evt.feature;
if (feature.popup) {
popup.feature = null;
this.map.removePopup(feature.popup);
feature.popup.destroy();
feature.popup = null;
}
},
getPopupHtml: function(station) {
return GetStationPopupHtml(station);
},
getIcon: function(station) {
// console.log(feature.layer.options.iconsets);
var stationTypeLookup = {
1: {externalGraphic: "http://openweathermap.org/img/s/iplane.png"},
2: {externalGraphic: "http://openweathermap.org/img/s/istation.png"},
5: {externalGraphic: "http://openweathermap.org/img/s/istation.png"}
};
return stationTypeLookup[station.type].externalGraphic;
}
});
function GetWeatherIconDay(st, hr)
{
if(hr == undefined || hr == 'day' )
var day='d';
else
var day='n';
var cl =0
if(st.clouds && st.clouds.all ) cl = st.clouds.all;
var img = 'transparent';
if(cl < 1 && cl >= 0 ) img = '01';
if(cl < 5 && cl >= 1 ) img = '01';
if(cl < 25 && cl >= 5 ) img = '01';
if(cl < 50 && cl >= 25 ) img = '02';
if(cl < 75 && cl >= 50 ) img = '03';
if(cl >= 75 ) img = '04';
if(st.rain && st.rain['3h']) {
img = '09';
if(cl < 30 ) img = '10';
}
return img+day+'.png';
}
/* Geometry functions */
function isboundsinrect(bounds, r)
{
var position = new OpenLayers.LonLat(bounds.left, bounds.bottom);
position.transform(
new OpenLayers.Projection("EPSG:900913"),
new OpenLayers.Projection("EPSG:4326")
);
var position2 = new OpenLayers.LonLat(bounds.right, bounds.top);
position2.transform(
new OpenLayers.Projection("EPSG:900913"),
new OpenLayers.Projection("EPSG:4326")
);
p1 = {x: position.lat, y:position.lon};
p2 = {x: position2.lat, y:position2.lon};
return inRectangle(p1, r[0], r[1], r[2], r[3]) && inRectangle(p2, r[0], r[1], r[2], r[3]);
}
function isLAMEASTETA(bounds)
{
var r = [{x:37.990, y:-92.055}, {x:38.718, y:-70.551}, {x:51.323, y:-68.764}, {x:50.421, y:-95.476}];
if ( isboundsinrect(bounds, r) )
return true;
return false;
}
function isLAMWESTETA(bounds)
{
var r = [{x:44.167, y:-130.909}, {x:45.990, y:-108.855}, {x:57.208, y:-108.123}, {x:54.903, y:-136.010}];
if ( isboundsinrect(bounds, r) )
return true;
return false;
}
function isLAMMARITIMEETA(bounds)
{
var r = [{x:40.210, y:-66.554}, {x:44.907, y:-50.824}, {x:54.596, y:-54.152}, {x:49.002, y:-73.506}];
if ( isboundsinrect(bounds, r) )
return true;
return false;
}
function isLAMARCTICETA(bounds)
{
var r = [{x:58.252, y:-77.123}, {x:59.478, y:-56.694}, {x:70.236, y:-55.179}, {x:68.439, y:-85.106}];
if ( isboundsinrect(bounds, r) )
return true;
return false;
}
function isREGETA(bounds)
{
var r = [{x:20, y:-163.696}, {x:15, y:-71.801}, {x:66, y:-17}, {x:80, y:-179.9}]
if ( isboundsinrect(bounds, r) )
return true;
return false;
}
function areaOfTriangle(p1, p2, p3)
{
var p1s = {x: (p1.x-p3.x), y: (p1.y-p3.y)};
var p2s = {x: (p2.x-p3.x), y: (p2.y-p3.y)};
var s = ( p1s.x*p2s.y - p2s.x*p1s.y )/2.0
return Math.abs(s);
}
function inTriangle(p0, p1, p2, p3)
{
var s = areaOfTriangle(p1, p2, p3);
var sall = areaOfTriangle(p0, p1, p2) + areaOfTriangle(p0, p1, p3) + areaOfTriangle(p0, p2, p3);
if( Math.abs(s - sall) < 0.001 ) return true;
return false;
}
function inRectangle(p, p1, p2, p3, p4)
{
return inTriangle(p, p1, p2, p4) || inTriangle(p, p3, p2, p4);
}
//
// HTML bubles
//
var WeekDayText = {
months: ["января", "февраля", "марта", "апреля", "мая", "июня", "июля", "августа", "сентября", "октября", "ноября", "декабря"],
days: ["воскресенье", "понедельник", "вторник", "среда", "четверг", "пятница", "суббота"],
//days_small: ["вс", "пн", "вт", "ср", "чт", "пт", "сб"]
days_small: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
}
function GetWeatherText2(st)
{
var txt='';
if( st.snow && st.snow['3h'] )
txt = 'Snow ' + '( ' + st.snow['3h'] +'мм )';
if( st.rain && st.rain['3h'] )
txt = 'Rain:' + '(' + st.rain['3h'] +'мм)';
return txt;
}
function GetWeatherIcon2(st, we)
{
var dt= new Date();
var times = SunCalc.getTimes(dt, st.lat, st.lng);
if( dt>times.sunrise && dt < times.sunset ) var day='d'; else var day='n';
var cl = we.clouds.all;
var img = 'transparent';
if(cl < 1 && cl >= 0 ) img = '01';
if(cl < 5 && cl >= 1 ) img = '01';
if(cl < 25 && cl >= 5 ) img = '01';
if(cl < 50 && cl >= 25 ) img = '02';
if(cl < 75 && cl >= 50 ) img = '03';
if(cl >= 75 ) img = '04';
if(we.rain && we.rain['3h'])
img = '09';
// if(we.snow['3h'])img = '09';
return img+day+'.png';
}
function GetWeatherForecastBubleHtml( st, forecast, cnt )
{
var curdate = new Date( (new Date()).getTime()- 280 * 60 * 1000 );
var temp = Math.round((st.main.temp -273)*10)/10;
var temp_min = Math.round((st.main.temp_min -273)*100)/100;
var temp_max = Math.round((st.main.temp_max -273)*100)/100;
var dtat = new Date(st.dt * 1000 );
//var dt = dtat.toTimeString();
//var dt = st.dt;
var times = SunCalc.getTimes(dtat, st.coord.lat, st.coord.lon);
if( st.dt>times.sunrise && st.dt< times.sunset ) var day='d'; else var day='n';
//http://openweathermap.org/img/w/ + GetWeatherIconDay(st,day)
var wtext = GetWeatherText2(st);
var h_header =
'<p class="weather_title"><a style="weather_title_link" href="http://openweathermap.org/city/'+st.id+'">'+st.name+'</a></p> \
<div style="float: left;" >\
\
<div class="weather_block">\
<div class="cur_weather_block" title="'+wtext+'">\
<img class="weather_image" alt="'+wtext+'" src="http://openweathermap.org/img/w/'+GetWeatherIconDay(st,day)+'"/>\
<div class="temp_block" >\
<div class="big_temp" title="Current Temperature '+dt+'">'+temp+'°</div>\
<div class="small_temp_block" >\
<div class="small_temp">'+wtext+'</div>\
</div>\
</div>\
</div>\
<div class="small_val_grey" title="Min and max temperature">Min t: '+temp_min+' / Max t: '+temp_max+' °C</div>\
<div class="small_val_grey">Humidity: ' + st.main.humidity +'%</div>\
<div class="small_val_grey">Wind: '+st.wind.speed+' m/s</div>\
</div>';
h_footer = '</div>';
h_body = '';
for(var j = 0; j < cnt ; j++)
if( curdate < new Date(forecast[j].dt * 1000 ) ) break;
for(var i = j; i < cnt+j ; i++){
var dt= new Date();
var times = SunCalc.getTimes(dtat, st.coord.lat, st.coord.lon);
if( dt>times.sunrise && dt < times.sunset ) var day='d'; else var day='n';
temp = Math.round(forecast[i].main.temp -273);
temp_min = Math.round((forecast[i].main.temp_min -273)*100)/100;
temp_max = Math.round((forecast[i].main.temp_max -273)*100)/100;
dtat = new Date(forecast[i].dt * 1000 );
if( curdate > dtat ) continue;
hr = dtat.getHours();
dt = hr + ':00';
if(hr<10) dt = '0' + dt;
h_o =
'<div style="font-size: small; float: left; text-align: center;" >\
<div title="' + WeekDayText.days[dtat.getDay()] + '">'+WeekDayText.days_small[dtat.getDay()]+'</div>\
<div title="' + dtat.toString() + '">'+dt+'</div>\
<img alt="'+GetWeatherText2(forecast[i])+'" src="http://openweathermap.org/img/w/'+GetWeatherIcon2(st, forecast[i])+'"/>\
<div class="small_val" title="Temperature">'+temp+'°C</div>\
<div class="small_val" title="Ветер">'+forecast[i].wind.speed+' m/s</div>\
<div class="small_val_grey" title="Давление">'+forecast[i].main.pressure+'</div>\
</div>'
//<div style="font-size: small; padding: 0pt 3pt;" title="High Temperature">'+temp_max+'°C</div>\
//<div style="color: gray; font-size: small; padding: 0pt 3pt;" title="Low Temperature">'+temp_min+'°C</div>\
h_body = h_body + h_o;
}
return h_header + h_body + h_footer;
}
//
// generate html for Weather Popoup window
//
function GetWeatherPopupHtml(st)
{
var temp = Math.round((st.main.temp -273.15)*10)/10;
var temp_min = Math.round((st.main.temp_min -273.15)*10)/10;
var temp_max = Math.round((st.main.temp_max -273.15)*10)/10;
if( st.weather.length > 0 ) {
var icon_url = 'http://openweathermap.org/img/w/' + st.weather[0].icon + '.png';
var wtext = st.weather[0].main;
var wdescription = st.weather[0].description;
}else{
var dtat = new Date(st.dt * 1000 );
var times = SunCalc.getTimes(dtat, st.coord.lat, st.coord.lon);
if( st.dt>times.sunrise && st.dt< times.sunset ) var day='d'; else var day='n';
var icon_url = GetWeatherIconDay(st,day)
var wtext = GetWeatherText2(st);
}
var html =
'<p class="weather_title"><a class="weather_title_link" href="http://openweathermap.org/city/'+st.id+'">'+st.name+'</a></p> \
<div class="weather_block">\
<div class="cur_weather_block" title="'+wdescription+'">\
<img class="weather_image" alt="'+wdescription+'" src="'+icon_url+'"/>\
<div class="temp_block" >\
<div class="big_temp" title="Current Temperature">'+temp+'°</div>\
<div class="small_temp_block" >\
<div class="small_temp">'+wtext+'</div>\
</div>\
</div>\
</div>\
<div class="small_val_grey" title="Min and max temperature">Min t: '+temp_min+' / Max t: '+temp_max+' °C</div>\
<div class="small_val_grey">Humidity: ' + st.main.humidity +'%</div>\
<div class="small_val_grey">Wind: '+st.wind.speed+' m/s</div>\
<div class="small_val_grey">Clouds: '+st.clouds.all+' %</div>\
</div>';
return html;
}
function GetStationPopupHtml(st)
{
var temp = Math.round((st.main.temp -273.15)*10)/10;
var dt = new Date(st.dt * 1000 );
var html_h=
'<p class="weather_title"><a href="http://openweathermap.org/station/'+st.id+'">'+st.name+'</a></p> \
<div class="weather_block">\
<div class="cur_weather_block" >\
<img class="station_image" alt="'+GetWeatherText2(st)+'" src="'+GetStationIcon(st)+'"/>\
<div class="temp_block">\
<div class="big_temp" title="Current Temperature">'+temp+'°</div>\
</div>\
</div>';
if(st.main.humidity)
html_h += '<div class="small_val_grey">Humidity: ' + st.main.humidity +'%</div>';
if(st.wind)
html_h += '<div class="small_val_grey">Wind: '+st.wind.speed+' m/s</div>';
if(st.main.pressure)
html_h += '<div class="small_val_grey">Pressure: '+st.main.pressure+' hpa</div>';
if(st.rain && st.rain['1h'])
html_h += '<div class="small_val_grey">Rain: '+st.rain['1h']+' mm</div>';
html_h += '<div class="small_val_grey" title="'+dt.toString()+'" >Recived at '+dt.toTimeString()+'</div></div>';
html_h += '</div>';
return html_h;
}
function GetStationIcon(st)
{
if(st.type == 1)
return 'http://openweathermap.org/img/s/iplane.png';
return 'http://openweathermap.org/img/s/istation.png';
}
/*
Copyright (c) 2011, Vladimir Agafonkin
SunCalc is a JavaScript library for calculating sun position and sunlight phases.
https://github.com/mourner/suncalc
*/
(function(c){function n(a){return new Date((a+0.5-o)*p)}var c="undefined"!==typeof exports?exports:c.SunCalc={},b=Math,f=b.PI/180,a=b.sin,i=b.cos,p=864E5,o=2440588,t=357.5291*f,u=0.98560028*f,v=1.9148*f,w=0.02*f,x=3.0E-4*f,y=102.9372*f,q=23.45*f,D=280.16*f,E=360.9856235*f,r=[[-0.83,"sunrise","sunset"],[-0.3,"sunriseEnd","sunsetStart"],[-6,"dawn","dusk"],[-12,"nauticalDawn","nauticalDusk"],[-18,"nightEnd","night"],[6,"goldenHourEnd","goldenHour"]];c.addTime=function(a,b,d){r.push([a,b,d])};c.getTimes=
function(m,h,d){var d=f*-d,h=f*h,m=b.round(m.valueOf()/p-0.5+o-2451545-9.0E-4-d/(2*b.PI)),e=2451545.0009+(0+d)/(2*b.PI)+m,g=t+u*(e-2451545),c=v*a(g)+w*a(2*g)+x*a(3*g),c=g+y+c+b.PI,z=b.asin(a(c)*a(q)),e=e+0.0053*a(g)+-0.0069*a(2*c),s={solarNoon:n(e)},k,A,j,l,B,C;for(k=0,A=r.length;k<A;k+=1)j=r[k],l=j[0],B=j[1],j=j[2],l=2451545.0009+(b.acos((a(l*f)-a(h)*a(z))/(i(h)*i(z)))+d)/(2*b.PI)+m+0.0053*a(g)+-0.0069*a(2*c),C=e-(l-e),s[B]=n(C),s[j]=n(l);return s};c.getPosition=function(c,h,d){var d=f*-d,h=f*h,
c=c.valueOf()/p-0.5+o,e=t+u*(c-2451545),g=v*a(e)+w*a(2*e)+x*a(3*e),g=e+y+g+b.PI,e=b.asin(a(g)*a(q)),g=b.atan2(a(g)*i(q),i(g)),d=D+E*(c-2451545)-d-g;return{azimuth:b.atan2(a(d),i(d)*a(h)-b.tan(e)*i(h)),altitude:b.asin(a(h)*a(e)+i(h)*i(e)*i(d))}}})(this);
|
/**
* @license
* v1.2.4
* MIT (https://github.com/pnp/pnpjs/blob/master/LICENSE)
* Copyright (c) 2018 Microsoft
* docs: https://pnp.github.io/pnpjs/
* source: https://github.com/pnp/pnpjs
* bugs: https://github.com/pnp/pnpjs/issues
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@pnp/common'), require('@pnp/logging'), require('@pnp/odata')) :
typeof define === 'function' && define.amd ? define(['exports', '@pnp/common', '@pnp/logging', '@pnp/odata'], factory) :
(factory((global.pnp = global.pnp || {}, global.pnp.sp = {}),global.pnp.common,global.pnp.logging,global.pnp.odata));
}(this, (function (exports,common,logging,odata) { 'use strict';
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. 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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/* global Reflect, Promise */
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);
};
function __extends(d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
function __decorate(decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
}
function __awaiter(thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function __generator(thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
}
function extractWebUrl(candidateUrl) {
if (common.stringIsNullOrEmpty(candidateUrl)) {
return "";
}
var index = candidateUrl.indexOf("_api/");
if (index < 0) {
index = candidateUrl.indexOf("_vti_bin/");
}
if (index > -1) {
return candidateUrl.substr(0, index);
}
// if all else fails just give them what they gave us back
return candidateUrl;
}
function odataUrlFrom(candidate) {
var parts = [];
var s = ["odata.type", "odata.editLink", "__metadata", "odata.metadata"];
if (common.hOP(candidate, s[0]) && candidate[s[0]] === "SP.Web") {
// webs return an absolute url in the editLink
if (common.hOP(candidate, s[1])) {
parts.push(candidate[s[1]]);
}
else if (common.hOP(candidate, s[2])) {
// we are dealing with verbose, which has an absolute uri
parts.push(candidate.__metadata.uri);
}
}
else {
if (common.hOP(candidate, s[3]) && common.hOP(candidate, s[1])) {
// we are dealign with minimal metadata (default)
parts.push(extractWebUrl(candidate[s[3]]), "_api", candidate[s[1]]);
}
else if (common.hOP(candidate, s[1])) {
parts.push("_api", candidate[s[1]]);
}
else if (common.hOP(candidate, s[2])) {
// we are dealing with verbose, which has an absolute uri
parts.push(candidate.__metadata.uri);
}
}
if (parts.length < 1) {
logging.Logger.write("No uri information found in ODataEntity parsing, chaining will fail for this object.", 2 /* Warning */);
return "";
}
return common.combine.apply(void 0, parts);
}
var SPODataEntityParserImpl = /** @class */ (function (_super) {
__extends(SPODataEntityParserImpl, _super);
function SPODataEntityParserImpl(factory) {
var _this = _super.call(this) || this;
_this.factory = factory;
_this.hydrate = function (d) {
var o = new _this.factory(odataUrlFrom(d), null);
return common.extend(o, d);
};
return _this;
}
SPODataEntityParserImpl.prototype.parse = function (r) {
var _this = this;
return _super.prototype.parse.call(this, r).then(function (d) {
var o = new _this.factory(odataUrlFrom(d), null);
return common.extend(o, d);
});
};
return SPODataEntityParserImpl;
}(odata.ODataParserBase));
var SPODataEntityArrayParserImpl = /** @class */ (function (_super) {
__extends(SPODataEntityArrayParserImpl, _super);
function SPODataEntityArrayParserImpl(factory) {
var _this = _super.call(this) || this;
_this.factory = factory;
_this.hydrate = function (d) {
return d.map(function (v) {
var o = new _this.factory(odataUrlFrom(v), null);
return common.extend(o, v);
});
};
return _this;
}
SPODataEntityArrayParserImpl.prototype.parse = function (r) {
var _this = this;
return _super.prototype.parse.call(this, r).then(function (d) {
return d.map(function (v) {
var o = new _this.factory(odataUrlFrom(v), null);
return common.extend(o, v);
});
});
};
return SPODataEntityArrayParserImpl;
}(odata.ODataParserBase));
function spODataEntity(factory) {
return new SPODataEntityParserImpl(factory);
}
function spODataEntityArray(factory) {
return new SPODataEntityArrayParserImpl(factory);
}
function setup(config) {
common.RuntimeConfig.extend(config);
}
var SPRuntimeConfigImpl = /** @class */ (function () {
function SPRuntimeConfigImpl() {
}
Object.defineProperty(SPRuntimeConfigImpl.prototype, "headers", {
get: function () {
var spPart = common.RuntimeConfig.get("sp");
if (spPart !== undefined && spPart.headers !== undefined) {
return spPart.headers;
}
return {};
},
enumerable: true,
configurable: true
});
Object.defineProperty(SPRuntimeConfigImpl.prototype, "baseUrl", {
get: function () {
var spPart = common.RuntimeConfig.get("sp");
if (spPart !== undefined && spPart.baseUrl !== undefined) {
return spPart.baseUrl;
}
if (common.RuntimeConfig.spfxContext !== undefined && common.RuntimeConfig.spfxContext !== null) {
return common.RuntimeConfig.spfxContext.pageContext.web.absoluteUrl;
}
return null;
},
enumerable: true,
configurable: true
});
Object.defineProperty(SPRuntimeConfigImpl.prototype, "fetchClientFactory", {
get: function () {
var spPart = common.RuntimeConfig.get("sp");
if (spPart !== undefined && spPart.fetchClientFactory !== undefined) {
return spPart.fetchClientFactory;
}
else {
return function () { return new common.FetchClient(); };
}
},
enumerable: true,
configurable: true
});
return SPRuntimeConfigImpl;
}());
var SPRuntimeConfig = new SPRuntimeConfigImpl();
var CachedDigest = /** @class */ (function () {
function CachedDigest() {
}
return CachedDigest;
}());
// allows for the caching of digests across all HttpClient's which each have their own DigestCache wrapper.
var digests = new Map();
var DigestCache = /** @class */ (function () {
function DigestCache(_httpClient, _digests) {
if (_digests === void 0) { _digests = digests; }
this._httpClient = _httpClient;
this._digests = _digests;
}
DigestCache.prototype.getDigest = function (webUrl) {
var _this = this;
var cachedDigest = this._digests.get(webUrl);
if (cachedDigest !== undefined) {
var now = new Date();
if (now < cachedDigest.expiration) {
return Promise.resolve(cachedDigest.value);
}
}
var url = common.combine(webUrl, "/_api/contextinfo");
var headers = {
"Accept": "application/json;odata=verbose",
"Content-Type": "application/json;odata=verbose;charset=utf-8",
};
return this._httpClient.fetchRaw(url, {
cache: "no-cache",
credentials: "same-origin",
headers: common.extend(headers, SPRuntimeConfig.headers, true),
method: "POST",
}).then(function (response) {
var parser = new odata.ODataDefaultParser();
return parser.parse(response).then(function (d) { return d.GetContextWebInformation; });
}).then(function (data) {
var newCachedDigest = new CachedDigest();
newCachedDigest.value = data.FormDigestValue;
var seconds = data.FormDigestTimeoutSeconds;
var expiration = new Date();
expiration.setTime(expiration.getTime() + 1000 * seconds);
newCachedDigest.expiration = expiration;
_this._digests.set(webUrl, newCachedDigest);
return newCachedDigest.value;
});
};
DigestCache.prototype.clear = function () {
this._digests.clear();
};
return DigestCache;
}());
var SPHttpClient = /** @class */ (function () {
function SPHttpClient(_impl) {
if (_impl === void 0) { _impl = SPRuntimeConfig.fetchClientFactory(); }
this._impl = _impl;
this._digestCache = new DigestCache(this);
}
SPHttpClient.prototype.fetch = function (url, options) {
var _this = this;
if (options === void 0) { options = {}; }
var opts = common.extend(options, { cache: "no-cache", credentials: "same-origin" }, true);
var headers = new Headers();
// first we add the global headers so they can be overwritten by any passed in locally to this call
common.mergeHeaders(headers, SPRuntimeConfig.headers);
// second we add the local options so we can overwrite the globals
common.mergeHeaders(headers, options.headers);
// lastly we apply any default headers we need that may not exist
if (!headers.has("Accept")) {
headers.append("Accept", "application/json");
}
if (!headers.has("Content-Type")) {
headers.append("Content-Type", "application/json;odata=verbose;charset=utf-8");
}
if (!headers.has("X-ClientService-ClientTag")) {
headers.append("X-ClientService-ClientTag", "PnPCoreJS:@pnp-1.2.4");
}
if (!headers.has("User-Agent")) {
// this marks the requests for understanding by the service
headers.append("User-Agent", "NONISV|SharePointPnP|PnPCoreJS/1.2.4");
}
opts = common.extend(opts, { headers: headers });
if (opts.method && opts.method.toUpperCase() !== "GET") {
// if we have either a request digest or an authorization header we don't need a digest
if (!headers.has("X-RequestDigest") && !headers.has("Authorization")) {
return this._digestCache.getDigest(extractWebUrl(url))
.then(function (digest) {
headers.append("X-RequestDigest", digest);
return _this.fetchRaw(url, opts);
});
}
}
return this.fetchRaw(url, opts);
};
SPHttpClient.prototype.fetchRaw = function (url, options) {
var _this = this;
if (options === void 0) { options = {}; }
// here we need to normalize the headers
var rawHeaders = new Headers();
common.mergeHeaders(rawHeaders, options.headers);
options = common.extend(options, { headers: rawHeaders });
var retry = function (ctx) {
// handles setting the proper timeout for a retry
var setRetry = function (response) {
var delay;
if (response.headers.has("Retry-After")) {
// if we have gotten a header, use that value as the delay value
delay = parseInt(response.headers.get("Retry-After"), 10);
}
else {
// grab our current delay
delay = ctx.delay;
// Increment our counters.
ctx.delay *= 2;
}
ctx.attempts++;
// If we have exceeded the retry count, reject.
if (ctx.retryCount <= ctx.attempts) {
ctx.reject(Error("Retry count exceeded (" + ctx.retryCount + ") for request. Response status: [" + response.status + "] " + response.statusText));
}
else {
// Set our retry timeout for {delay} milliseconds.
setTimeout(common.getCtxCallback(_this, retry, ctx), delay);
}
};
// send the actual request
_this._impl.fetch(url, options).then(function (response) {
if (response.status === 429) {
// we have been throttled
setRetry(response);
}
else {
ctx.resolve(response);
}
}).catch(function (response) {
if (response.status === 503) {
// http status code 503, we can retry this
setRetry(response);
}
else {
ctx.reject(response);
}
});
};
return new Promise(function (resolve, reject) {
var retryContext = {
attempts: 0,
delay: 100,
reject: reject,
resolve: resolve,
retryCount: 7,
};
retry.call(_this, retryContext);
});
};
SPHttpClient.prototype.get = function (url, options) {
if (options === void 0) { options = {}; }
var opts = common.extend(options, { method: "GET" });
return this.fetch(url, opts);
};
SPHttpClient.prototype.post = function (url, options) {
if (options === void 0) { options = {}; }
var opts = common.extend(options, { method: "POST" });
return this.fetch(url, opts);
};
SPHttpClient.prototype.patch = function (url, options) {
if (options === void 0) { options = {}; }
var opts = common.extend(options, { method: "PATCH" });
return this.fetch(url, opts);
};
SPHttpClient.prototype.delete = function (url, options) {
if (options === void 0) { options = {}; }
var opts = common.extend(options, { method: "DELETE" });
return this.fetch(url, opts);
};
return SPHttpClient;
}());
var global$1 = (typeof global !== "undefined" ? global :
typeof self !== "undefined" ? self :
typeof window !== "undefined" ? window : {});
/**
* Ensures that a given url is absolute for the current web based on context
*
* @param candidateUrl The url to make absolute
*
*/
function toAbsoluteUrl(candidateUrl) {
return new Promise(function (resolve) {
if (common.isUrlAbsolute(candidateUrl)) {
// if we are already absolute, then just return the url
return resolve(candidateUrl);
}
if (SPRuntimeConfig.baseUrl !== null) {
// base url specified either with baseUrl of spfxContext config property
return resolve(common.combine(SPRuntimeConfig.baseUrl, candidateUrl));
}
if (global$1._spPageContextInfo !== undefined) {
// operating in classic pages
if (common.hOP(global$1._spPageContextInfo, "webAbsoluteUrl")) {
return resolve(common.combine(global$1._spPageContextInfo.webAbsoluteUrl, candidateUrl));
}
else if (common.hOP(global$1._spPageContextInfo, "webServerRelativeUrl")) {
return resolve(common.combine(global$1._spPageContextInfo.webServerRelativeUrl, candidateUrl));
}
}
// does window.location exist and have a certain path part in it?
if (global$1.location !== undefined) {
var baseUrl_1 = global$1.location.toString().toLowerCase();
["/_layouts/", "/siteassets/"].forEach(function (s) {
var index = baseUrl_1.indexOf(s);
if (index > 0) {
return resolve(common.combine(baseUrl_1.substr(0, index), candidateUrl));
}
});
}
return resolve(candidateUrl);
});
}
function metadata(type) {
return {
"__metadata": { "type": type },
};
}
/**
* SharePointQueryable Base Class
*
*/
var SharePointQueryable = /** @class */ (function (_super) {
__extends(SharePointQueryable, _super);
/**
* Creates a new instance of the SharePointQueryable class
*
* @constructor
* @param baseUrl A string or SharePointQueryable that should form the base part of the url
*
*/
function SharePointQueryable(baseUrl, path) {
var _this = _super.call(this) || this;
_this._forceCaching = false;
if (typeof baseUrl === "string") {
// we need to do some extra parsing to get the parent url correct if we are
// being created from just a string.
if (common.isUrlAbsolute(baseUrl) || baseUrl.lastIndexOf("/") < 0) {
_this._parentUrl = baseUrl;
_this._url = common.combine(baseUrl, path);
}
else if (baseUrl.lastIndexOf("/") > baseUrl.lastIndexOf("(")) {
// .../items(19)/fields
var index = baseUrl.lastIndexOf("/");
_this._parentUrl = baseUrl.slice(0, index);
path = common.combine(baseUrl.slice(index), path);
_this._url = common.combine(_this._parentUrl, path);
}
else {
// .../items(19)
var index = baseUrl.lastIndexOf("(");
_this._parentUrl = baseUrl.slice(0, index);
_this._url = common.combine(baseUrl, path);
}
}
else {
_this.extend(baseUrl, path);
var target = baseUrl.query.get("@target");
if (target !== undefined) {
_this.query.set("@target", target);
}
}
return _this;
}
/**
* Creates a new instance of the supplied factory and extends this into that new instance
*
* @param factory constructor for the new SharePointQueryable
*/
SharePointQueryable.prototype.as = function (factory) {
var o = new factory(this._url, null);
return common.extend(o, this, true);
};
/**
* Gets the full url with query information
*
*/
SharePointQueryable.prototype.toUrlAndQuery = function () {
var aliasedParams = new Map(this.query);
var url = this.toUrl().replace(/'!(@.*?)::(.*?)'/ig, function (match, labelName, value) {
logging.Logger.write("Rewriting aliased parameter from match " + match + " to label: " + labelName + " value: " + value, 0 /* Verbose */);
aliasedParams.set(labelName, "'" + value + "'");
return labelName;
});
if (aliasedParams.size > 0) {
var char = url.indexOf("?") > -1 ? "&" : "?";
url += "" + char + Array.from(aliasedParams).map(function (v) { return v[0] + "=" + v[1]; }).join("&");
}
return url;
};
/**
* Choose which fields to return
*
* @param selects One or more fields to return
*/
SharePointQueryable.prototype.select = function () {
var selects = [];
for (var _i = 0; _i < arguments.length; _i++) {
selects[_i] = arguments[_i];
}
if (selects.length > 0) {
this.query.set("$select", selects.join(","));
}
return this;
};
/**
* Expands fields such as lookups to get additional data
*
* @param expands The Fields for which to expand the values
*/
SharePointQueryable.prototype.expand = function () {
var expands = [];
for (var _i = 0; _i < arguments.length; _i++) {
expands[_i] = arguments[_i];
}
if (expands.length > 0) {
this.query.set("$expand", expands.join(","));
}
return this;
};
/**
* Gets a parent for this instance as specified
*
* @param factory The contructor for the class to create
*/
SharePointQueryable.prototype.getParent = function (factory, baseUrl, path, batch) {
if (baseUrl === void 0) { baseUrl = this.parentUrl; }
var parent = new factory(baseUrl, path).configureFrom(this);
var t = "@target";
if (this.query.has(t)) {
parent.query.set(t, this.query.get(t));
}
if (batch !== undefined) {
parent = parent.inBatch(batch);
}
return parent;
};
/**
* Clones this SharePointQueryable into a new SharePointQueryable instance of T
* @param factory Constructor used to create the new instance
* @param additionalPath Any additional path to include in the clone
* @param includeBatch If true this instance's batch will be added to the cloned instance
*/
SharePointQueryable.prototype.clone = function (factory, additionalPath, includeBatch) {
if (includeBatch === void 0) { includeBatch = true; }
var clone = _super.prototype._clone.call(this, new factory(this, additionalPath), { includeBatch: includeBatch });
// handle sp specific clone actions
var t = "@target";
if (this.query.has(t)) {
clone.query.set(t, this.query.get(t));
}
return clone;
};
/**
* Converts the current instance to a request context
*
* @param verb The request verb
* @param options The set of supplied request options
* @param parser The supplied ODataParser instance
* @param pipeline Optional request processing pipeline
*/
SharePointQueryable.prototype.toRequestContext = function (verb, options, parser, pipeline) {
var _this = this;
if (options === void 0) { options = {}; }
var dependencyDispose = this.hasBatch ? this.addBatchDependency() : function () { return; };
return toAbsoluteUrl(this.toUrlAndQuery()).then(function (url) {
common.mergeOptions(options, _this._options);
// build our request context
var context = {
batch: _this.batch,
batchDependency: dependencyDispose,
cachingOptions: _this._cachingOptions,
clientFactory: function () { return new SPHttpClient(); },
isBatched: _this.hasBatch,
isCached: _this._forceCaching || (_this._useCaching && /^get$/i.test(verb)),
options: options,
parser: parser,
pipeline: pipeline,
requestAbsoluteUrl: url,
requestId: common.getGUID(),
verb: verb,
};
return context;
});
};
return SharePointQueryable;
}(odata.ODataQueryable));
/**
* Represents a REST collection which can be filtered, paged, and selected
*
*/
var SharePointQueryableCollection = /** @class */ (function (_super) {
__extends(SharePointQueryableCollection, _super);
function SharePointQueryableCollection() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Filters the returned collection (https://msdn.microsoft.com/en-us/library/office/fp142385.aspx#bk_supported)
*
* @param filter The string representing the filter query
*/
SharePointQueryableCollection.prototype.filter = function (filter) {
this.query.set("$filter", filter);
return this;
};
/**
* Orders based on the supplied fields
*
* @param orderby The name of the field on which to sort
* @param ascending If false DESC is appended, otherwise ASC (default)
*/
SharePointQueryableCollection.prototype.orderBy = function (orderBy, ascending) {
if (ascending === void 0) { ascending = true; }
var o = "$orderby";
var query = this.query.has(o) ? this.query.get(o).split(",") : [];
query.push(orderBy + " " + (ascending ? "asc" : "desc"));
this.query.set(o, query.join(","));
return this;
};
/**
* Skips the specified number of items
*
* @param skip The number of items to skip
*/
SharePointQueryableCollection.prototype.skip = function (skip) {
this.query.set("$skip", skip.toString());
return this;
};
/**
* Limits the query to only return the specified number of items
*
* @param top The query row limit
*/
SharePointQueryableCollection.prototype.top = function (top) {
this.query.set("$top", top.toString());
return this;
};
return SharePointQueryableCollection;
}(SharePointQueryable));
/**
* Represents an instance that can be selected
*
*/
var SharePointQueryableInstance = /** @class */ (function (_super) {
__extends(SharePointQueryableInstance, _super);
function SharePointQueryableInstance() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Curries the update function into the common pieces
*
* @param type
* @param mapper
*/
SharePointQueryableInstance.prototype._update = function (type, mapper) {
var _this = this;
return function (props) { return _this.postCore({
body: common.jsS(common.extend(metadata(type), props)),
headers: {
"X-HTTP-Method": "MERGE",
},
}).then(function (d) { return mapper(d, props); }); };
};
/**
* Deletes this instance
*
*/
SharePointQueryableInstance.prototype._delete = function () {
return this.postCore({
headers: {
"X-HTTP-Method": "DELETE",
},
});
};
/**
* Deletes this instance with an etag value in the headers
*
* @param eTag eTag to delete
*/
SharePointQueryableInstance.prototype._deleteWithETag = function (eTag) {
if (eTag === void 0) { eTag = "*"; }
return this.postCore({
headers: {
"IF-Match": eTag,
"X-HTTP-Method": "DELETE",
},
});
};
return SharePointQueryableInstance;
}(SharePointQueryable));
/**
* Decorator used to specify the default path for SharePointQueryable objects
*
* @param path
*/
function defaultPath(path) {
return function (target) {
return /** @class */ (function (_super) {
__extends(class_1, _super);
function class_1() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return _super.call(this, args[0], args.length > 1 && args[1] !== undefined ? args[1] : path) || this;
}
return class_1;
}(target));
};
}
/**
* Describes a collection of all site collection users
*
*/
var SiteUsers = /** @class */ (function (_super) {
__extends(SiteUsers, _super);
function SiteUsers() {
return _super !== null && _super.apply(this, arguments) || this;
}
SiteUsers_1 = SiteUsers;
/**
* Gets a user from the collection by id
*
* @param id The id of the user to retrieve
*/
SiteUsers.prototype.getById = function (id) {
return new SiteUser(this, "getById(" + id + ")");
};
/**
* Gets a user from the collection by email
*
* @param email The email address of the user to retrieve
*/
SiteUsers.prototype.getByEmail = function (email) {
return new SiteUser(this, "getByEmail('" + email + "')");
};
/**
* Gets a user from the collection by login name
*
* @param loginName The login name of the user to retrieve
*/
SiteUsers.prototype.getByLoginName = function (loginName) {
var su = new SiteUser(this);
su.concat("('!@v::" + encodeURIComponent(loginName) + "')");
return su;
};
/**
* Removes a user from the collection by id
*
* @param id The id of the user to remove
*/
SiteUsers.prototype.removeById = function (id) {
return this.clone(SiteUsers_1, "removeById(" + id + ")").postCore();
};
/**
* Removes a user from the collection by login name
*
* @param loginName The login name of the user to remove
*/
SiteUsers.prototype.removeByLoginName = function (loginName) {
var o = this.clone(SiteUsers_1, "removeByLoginName(@v)");
o.query.set("@v", "'" + encodeURIComponent(loginName) + "'");
return o.postCore();
};
/**
* Adds a user to a group
*
* @param loginName The login name of the user to add to the group
*
*/
SiteUsers.prototype.add = function (loginName) {
var _this = this;
return this.clone(SiteUsers_1, null).postCore({
body: common.jsS(common.extend(metadata("SP.User"), { LoginName: loginName })),
}).then(function () { return _this.getByLoginName(loginName); });
};
var SiteUsers_1;
SiteUsers = SiteUsers_1 = __decorate([
defaultPath("siteusers")
], SiteUsers);
return SiteUsers;
}(SharePointQueryableCollection));
/**
* Base class for a user
*
*/
var UserBase = /** @class */ (function (_super) {
__extends(UserBase, _super);
function UserBase() {
return _super !== null && _super.apply(this, arguments) || this;
}
Object.defineProperty(UserBase.prototype, "groups", {
/**
* Gets the groups for this user
*
*/
get: function () {
return new SiteGroups(this, "groups");
},
enumerable: true,
configurable: true
});
return UserBase;
}(SharePointQueryableInstance));
/**
* Describes a single user
*
*/
var SiteUser = /** @class */ (function (_super) {
__extends(SiteUser, _super);
function SiteUser() {
var _this = _super !== null && _super.apply(this, arguments) || this;
/**
* Updates this user instance with the supplied properties
*
* @param properties A plain object of property names and values to update for the user
*/
_this.update = _this._update("SP.User", function (data) { return ({ data: data, user: _this }); });
/**
* Delete this user
*
*/
_this.delete = _this._delete;
return _this;
}
return SiteUser;
}(UserBase));
/**
* Represents the current user
*/
var CurrentUser = /** @class */ (function (_super) {
__extends(CurrentUser, _super);
function CurrentUser() {
return _super !== null && _super.apply(this, arguments) || this;
}
CurrentUser = __decorate([
defaultPath("currentuser")
], CurrentUser);
return CurrentUser;
}(UserBase));
/**
* Principal Type enum
*
*/
var PrincipalType;
(function (PrincipalType) {
PrincipalType[PrincipalType["None"] = 0] = "None";
PrincipalType[PrincipalType["User"] = 1] = "User";
PrincipalType[PrincipalType["DistributionList"] = 2] = "DistributionList";
PrincipalType[PrincipalType["SecurityGroup"] = 4] = "SecurityGroup";
PrincipalType[PrincipalType["SharePointGroup"] = 8] = "SharePointGroup";
PrincipalType[PrincipalType["All"] = 15] = "All";
})(PrincipalType || (PrincipalType = {}));
/**
* Describes a collection of site groups
*
*/
var SiteGroups = /** @class */ (function (_super) {
__extends(SiteGroups, _super);
function SiteGroups() {
return _super !== null && _super.apply(this, arguments) || this;
}
SiteGroups_1 = SiteGroups;
/**
* Gets a group from the collection by id
*
* @param id The id of the group to retrieve
*/
SiteGroups.prototype.getById = function (id) {
var sg = new SiteGroup(this);
sg.concat("(" + id + ")");
return sg;
};
/**
* Adds a new group to the site collection
*
* @param props The group properties object of property names and values to be set for the group
*/
SiteGroups.prototype.add = function (properties) {
var _this = this;
var postBody = common.jsS(common.extend(metadata("SP.Group"), properties));
return this.postCore({ body: postBody }).then(function (data) {
return {
data: data,
group: _this.getById(data.Id),
};
});
};
/**
* Gets a group from the collection by name
*
* @param groupName The name of the group to retrieve
*/
SiteGroups.prototype.getByName = function (groupName) {
return new SiteGroup(this, "getByName('" + groupName + "')");
};
/**
* Removes the group with the specified member id from the collection
*
* @param id The id of the group to remove
*/
SiteGroups.prototype.removeById = function (id) {
return this.clone(SiteGroups_1, "removeById('" + id + "')").postCore();
};
/**
* Removes the cross-site group with the specified name from the collection
*
* @param loginName The name of the group to remove
*/
SiteGroups.prototype.removeByLoginName = function (loginName) {
return this.clone(SiteGroups_1, "removeByLoginName('" + loginName + "')").postCore();
};
var SiteGroups_1;
SiteGroups = SiteGroups_1 = __decorate([
defaultPath("sitegroups")
], SiteGroups);
return SiteGroups;
}(SharePointQueryableCollection));
/**
* Describes a single group
*
*/
var SiteGroup = /** @class */ (function (_super) {
__extends(SiteGroup, _super);
function SiteGroup() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.update = _this._update("SP.Group", function (d, p) {
var retGroup = _this;
if (common.hOP(p, "Title")) {
/* tslint:disable-next-line no-string-literal */
retGroup = _this.getParent(SiteGroup, _this.parentUrl, "getByName('" + p["Title"] + "')");
}
return {
data: d,
group: retGroup,
};
});
return _this;
}
Object.defineProperty(SiteGroup.prototype, "users", {
/**
* Gets the users for this group
*
*/
get: function () {
return new SiteUsers(this, "users");
},
enumerable: true,
configurable: true
});
return SiteGroup;
}(SharePointQueryableInstance));
/**
* Describes a set of role assignments for the current scope
*
*/
var RoleAssignments = /** @class */ (function (_super) {
__extends(RoleAssignments, _super);
function RoleAssignments() {
return _super !== null && _super.apply(this, arguments) || this;
}
RoleAssignments_1 = RoleAssignments;
/**
* Gets the role assignment associated with the specified principal id from the collection.
*
* @param id The id of the role assignment
*/
RoleAssignments.prototype.getById = function (id) {
var ra = new RoleAssignment(this);
ra.concat("(" + id + ")");
return ra;
};
/**
* Adds a new role assignment with the specified principal and role definitions to the collection
*
* @param principalId The id of the user or group to assign permissions to
* @param roleDefId The id of the role definition that defines the permissions to assign
*
*/
RoleAssignments.prototype.add = function (principalId, roleDefId) {
return this.clone(RoleAssignments_1, "addroleassignment(principalid=" + principalId + ", roledefid=" + roleDefId + ")").postCore();
};
/**
* Removes the role assignment with the specified principal and role definition from the collection
*
* @param principalId The id of the user or group in the role assignment
* @param roleDefId The id of the role definition in the role assignment
*
*/
RoleAssignments.prototype.remove = function (principalId, roleDefId) {
return this.clone(RoleAssignments_1, "removeroleassignment(principalid=" + principalId + ", roledefid=" + roleDefId + ")").postCore();
};
var RoleAssignments_1;
RoleAssignments = RoleAssignments_1 = __decorate([
defaultPath("roleassignments")
], RoleAssignments);
return RoleAssignments;
}(SharePointQueryableCollection));
/**
* Describes a role assignment
*
*/
var RoleAssignment = /** @class */ (function (_super) {
__extends(RoleAssignment, _super);
function RoleAssignment() {
var _this = _super !== null && _super.apply(this, arguments) || this;
/**
* Deletes this role assignment
*
*/
_this.delete = _this._delete;
return _this;
}
Object.defineProperty(RoleAssignment.prototype, "groups", {
/**
* Gets the groups that directly belong to the access control list (ACL) for this securable object
*
*/
get: function () {
return new SiteGroups(this, "groups");
},
enumerable: true,
configurable: true
});
Object.defineProperty(RoleAssignment.prototype, "bindings", {
/**
* Gets the role definition bindings for this role assignment
*
*/
get: function () {
return new RoleDefinitionBindings(this);
},
enumerable: true,
configurable: true
});
return RoleAssignment;
}(SharePointQueryableInstance));
/**
* Describes a collection of role definitions
*
*/
var RoleDefinitions = /** @class */ (function (_super) {
__extends(RoleDefinitions, _super);
function RoleDefinitions() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Gets the role definition with the specified id from the collection
*
* @param id The id of the role definition
*
*/
RoleDefinitions.prototype.getById = function (id) {
return new RoleDefinition(this, "getById(" + id + ")");
};
/**
* Gets the role definition with the specified name
*
* @param name The name of the role definition
*
*/
RoleDefinitions.prototype.getByName = function (name) {
return new RoleDefinition(this, "getbyname('" + name + "')");
};
/**
* Gets the role definition with the specified role type
*
* @param roleTypeKind The roletypekind of the role definition (None=0, Guest=1, Reader=2, Contributor=3, WebDesigner=4, Administrator=5, Editor=6, System=7)
*
*/
RoleDefinitions.prototype.getByType = function (roleTypeKind) {
return new RoleDefinition(this, "getbytype(" + roleTypeKind + ")");
};
/**
* Creates a role definition
*
* @param name The new role definition's name
* @param description The new role definition's description
* @param order The order in which the role definition appears
* @param basePermissions The permissions mask for this role definition
*
*/
RoleDefinitions.prototype.add = function (name, description, order, basePermissions) {
var _this = this;
var postBody = common.jsS({
BasePermissions: common.extend({ __metadata: { type: "SP.BasePermissions" } }, basePermissions),
Description: description,
Name: name,
Order: order,
__metadata: { "type": "SP.RoleDefinition" },
});
return this.postCore({ body: postBody }).then(function (data) {
return {
data: data,
definition: _this.getById(data.Id),
};
});
};
RoleDefinitions = __decorate([
defaultPath("roledefinitions")
], RoleDefinitions);
return RoleDefinitions;
}(SharePointQueryableCollection));
/**
* Describes a role definition
*
*/
var RoleDefinition = /** @class */ (function (_super) {
__extends(RoleDefinition, _super);
function RoleDefinition() {
var _this = _super !== null && _super.apply(this, arguments) || this;
/**
* Deletes this role definition
*
*/
_this.delete = _this._delete;
return _this;
/* tslint:enable */
}
/**
* Updates this role definition with the supplied properties
*
* @param properties A plain object hash of values to update for the role definition
*/
/* tslint:disable no-string-literal */
RoleDefinition.prototype.update = function (properties) {
var _this = this;
var s = ["BasePermissions"];
if (common.hOP(properties, s[0]) !== undefined) {
properties[s[0]] = common.extend({ __metadata: { type: "SP." + s[0] } }, properties[s[0]]);
}
var postBody = common.jsS(common.extend(metadata("SP.RoleDefinition"), properties));
return this.postCore({
body: postBody,
headers: {
"X-HTTP-Method": "MERGE",
},
}).then(function (data) {
var retDef = _this;
if (common.hOP(properties, "Name")) {
var parent_1 = _this.getParent(RoleDefinitions, _this.parentUrl, "");
retDef = parent_1.getByName(properties["Name"]);
}
return {
data: data,
definition: retDef,
};
});
};
return RoleDefinition;
}(SharePointQueryableInstance));
/**
* Describes the role definitons bound to a role assignment object
*
*/
var RoleDefinitionBindings = /** @class */ (function (_super) {
__extends(RoleDefinitionBindings, _super);
function RoleDefinitionBindings() {
return _super !== null && _super.apply(this, arguments) || this;
}
RoleDefinitionBindings = __decorate([
defaultPath("roledefinitionbindings")
], RoleDefinitionBindings);
return RoleDefinitionBindings;
}(SharePointQueryableCollection));
/**
* Determines the display mode of the given control or view
*/
(function (ControlMode) {
ControlMode[ControlMode["Display"] = 1] = "Display";
ControlMode[ControlMode["Edit"] = 2] = "Edit";
ControlMode[ControlMode["New"] = 3] = "New";
})(exports.ControlMode || (exports.ControlMode = {}));
(function (FieldTypes) {
FieldTypes[FieldTypes["Invalid"] = 0] = "Invalid";
FieldTypes[FieldTypes["Integer"] = 1] = "Integer";
FieldTypes[FieldTypes["Text"] = 2] = "Text";
FieldTypes[FieldTypes["Note"] = 3] = "Note";
FieldTypes[FieldTypes["DateTime"] = 4] = "DateTime";
FieldTypes[FieldTypes["Counter"] = 5] = "Counter";
FieldTypes[FieldTypes["Choice"] = 6] = "Choice";
FieldTypes[FieldTypes["Lookup"] = 7] = "Lookup";
FieldTypes[FieldTypes["Boolean"] = 8] = "Boolean";
FieldTypes[FieldTypes["Number"] = 9] = "Number";
FieldTypes[FieldTypes["Currency"] = 10] = "Currency";
FieldTypes[FieldTypes["URL"] = 11] = "URL";
FieldTypes[FieldTypes["Computed"] = 12] = "Computed";
FieldTypes[FieldTypes["Threading"] = 13] = "Threading";
FieldTypes[FieldTypes["Guid"] = 14] = "Guid";
FieldTypes[FieldTypes["MultiChoice"] = 15] = "MultiChoice";
FieldTypes[FieldTypes["GridChoice"] = 16] = "GridChoice";
FieldTypes[FieldTypes["Calculated"] = 17] = "Calculated";
FieldTypes[FieldTypes["File"] = 18] = "File";
FieldTypes[FieldTypes["Attachments"] = 19] = "Attachments";
FieldTypes[FieldTypes["User"] = 20] = "User";
FieldTypes[FieldTypes["Recurrence"] = 21] = "Recurrence";
FieldTypes[FieldTypes["CrossProjectLink"] = 22] = "CrossProjectLink";
FieldTypes[FieldTypes["ModStat"] = 23] = "ModStat";
FieldTypes[FieldTypes["Error"] = 24] = "Error";
FieldTypes[FieldTypes["ContentTypeId"] = 25] = "ContentTypeId";
FieldTypes[FieldTypes["PageSeparator"] = 26] = "PageSeparator";
FieldTypes[FieldTypes["ThreadIndex"] = 27] = "ThreadIndex";
FieldTypes[FieldTypes["WorkflowStatus"] = 28] = "WorkflowStatus";
FieldTypes[FieldTypes["AllDayEvent"] = 29] = "AllDayEvent";
FieldTypes[FieldTypes["WorkflowEventType"] = 30] = "WorkflowEventType";
})(exports.FieldTypes || (exports.FieldTypes = {}));
(function (DateTimeFieldFormatType) {
DateTimeFieldFormatType[DateTimeFieldFormatType["DateOnly"] = 0] = "DateOnly";
DateTimeFieldFormatType[DateTimeFieldFormatType["DateTime"] = 1] = "DateTime";
})(exports.DateTimeFieldFormatType || (exports.DateTimeFieldFormatType = {}));
(function (AddFieldOptions) {
/**
* Specify that a new field added to the list must also be added to the default content type in the site collection
*/
AddFieldOptions[AddFieldOptions["DefaultValue"] = 0] = "DefaultValue";
/**
* Specify that a new field added to the list must also be added to the default content type in the site collection.
*/
AddFieldOptions[AddFieldOptions["AddToDefaultContentType"] = 1] = "AddToDefaultContentType";
/**
* Specify that a new field must not be added to any other content type
*/
AddFieldOptions[AddFieldOptions["AddToNoContentType"] = 2] = "AddToNoContentType";
/**
* Specify that a new field that is added to the specified list must also be added to all content types in the site collection
*/
AddFieldOptions[AddFieldOptions["AddToAllContentTypes"] = 4] = "AddToAllContentTypes";
/**
* Specify adding an internal field name hint for the purpose of avoiding possible database locking or field renaming operations
*/
AddFieldOptions[AddFieldOptions["AddFieldInternalNameHint"] = 8] = "AddFieldInternalNameHint";
/**
* Specify that a new field that is added to the specified list must also be added to the default list view
*/
AddFieldOptions[AddFieldOptions["AddFieldToDefaultView"] = 16] = "AddFieldToDefaultView";
/**
* Specify to confirm that no other field has the same display name
*/
AddFieldOptions[AddFieldOptions["AddFieldCheckDisplayName"] = 32] = "AddFieldCheckDisplayName";
})(exports.AddFieldOptions || (exports.AddFieldOptions = {}));
(function (CalendarType) {
CalendarType[CalendarType["Gregorian"] = 1] = "Gregorian";
CalendarType[CalendarType["Japan"] = 3] = "Japan";
CalendarType[CalendarType["Taiwan"] = 4] = "Taiwan";
CalendarType[CalendarType["Korea"] = 5] = "Korea";
CalendarType[CalendarType["Hijri"] = 6] = "Hijri";
CalendarType[CalendarType["Thai"] = 7] = "Thai";
CalendarType[CalendarType["Hebrew"] = 8] = "Hebrew";
CalendarType[CalendarType["GregorianMEFrench"] = 9] = "GregorianMEFrench";
CalendarType[CalendarType["GregorianArabic"] = 10] = "GregorianArabic";
CalendarType[CalendarType["GregorianXLITEnglish"] = 11] = "GregorianXLITEnglish";
CalendarType[CalendarType["GregorianXLITFrench"] = 12] = "GregorianXLITFrench";
CalendarType[CalendarType["KoreaJapanLunar"] = 14] = "KoreaJapanLunar";
CalendarType[CalendarType["ChineseLunar"] = 15] = "ChineseLunar";
CalendarType[CalendarType["SakaEra"] = 16] = "SakaEra";
CalendarType[CalendarType["UmAlQura"] = 23] = "UmAlQura";
})(exports.CalendarType || (exports.CalendarType = {}));
(function (UrlFieldFormatType) {
UrlFieldFormatType[UrlFieldFormatType["Hyperlink"] = 0] = "Hyperlink";
UrlFieldFormatType[UrlFieldFormatType["Image"] = 1] = "Image";
})(exports.UrlFieldFormatType || (exports.UrlFieldFormatType = {}));
(function (PermissionKind) {
/**
* Has no permissions on the Site. Not available through the user interface.
*/
PermissionKind[PermissionKind["EmptyMask"] = 0] = "EmptyMask";
/**
* View items in lists, documents in document libraries, and Web discussion comments.
*/
PermissionKind[PermissionKind["ViewListItems"] = 1] = "ViewListItems";
/**
* Add items to lists, documents to document libraries, and Web discussion comments.
*/
PermissionKind[PermissionKind["AddListItems"] = 2] = "AddListItems";
/**
* Edit items in lists, edit documents in document libraries, edit Web discussion comments
* in documents, and customize Web Part Pages in document libraries.
*/
PermissionKind[PermissionKind["EditListItems"] = 3] = "EditListItems";
/**
* Delete items from a list, documents from a document library, and Web discussion
* comments in documents.
*/
PermissionKind[PermissionKind["DeleteListItems"] = 4] = "DeleteListItems";
/**
* Approve a minor version of a list item or document.
*/
PermissionKind[PermissionKind["ApproveItems"] = 5] = "ApproveItems";
/**
* View the source of documents with server-side file handlers.
*/
PermissionKind[PermissionKind["OpenItems"] = 6] = "OpenItems";
/**
* View past versions of a list item or document.
*/
PermissionKind[PermissionKind["ViewVersions"] = 7] = "ViewVersions";
/**
* Delete past versions of a list item or document.
*/
PermissionKind[PermissionKind["DeleteVersions"] = 8] = "DeleteVersions";
/**
* Discard or check in a document which is checked out to another user.
*/
PermissionKind[PermissionKind["CancelCheckout"] = 9] = "CancelCheckout";
/**
* Create, change, and delete personal views of lists.
*/
PermissionKind[PermissionKind["ManagePersonalViews"] = 10] = "ManagePersonalViews";
/**
* Create and delete lists, add or remove columns in a list, and add or remove public views of a list.
*/
PermissionKind[PermissionKind["ManageLists"] = 12] = "ManageLists";
/**
* View forms, views, and application pages, and enumerate lists.
*/
PermissionKind[PermissionKind["ViewFormPages"] = 13] = "ViewFormPages";
/**
* Make content of a list or document library retrieveable for anonymous users through SharePoint search.
* The list permissions in the site do not change.
*/
PermissionKind[PermissionKind["AnonymousSearchAccessList"] = 14] = "AnonymousSearchAccessList";
/**
* Allow users to open a Site, list, or folder to access items inside that container.
*/
PermissionKind[PermissionKind["Open"] = 17] = "Open";
/**
* View pages in a Site.
*/
PermissionKind[PermissionKind["ViewPages"] = 18] = "ViewPages";
/**
* Add, change, or delete HTML pages or Web Part Pages, and edit the Site using
* a Windows SharePoint Services compatible editor.
*/
PermissionKind[PermissionKind["AddAndCustomizePages"] = 19] = "AddAndCustomizePages";
/**
* Apply a theme or borders to the entire Site.
*/
PermissionKind[PermissionKind["ApplyThemeAndBorder"] = 20] = "ApplyThemeAndBorder";
/**
* Apply a style sheet (.css file) to the Site.
*/
PermissionKind[PermissionKind["ApplyStyleSheets"] = 21] = "ApplyStyleSheets";
/**
* View reports on Site usage.
*/
PermissionKind[PermissionKind["ViewUsageData"] = 22] = "ViewUsageData";
/**
* Create a Site using Self-Service Site Creation.
*/
PermissionKind[PermissionKind["CreateSSCSite"] = 23] = "CreateSSCSite";
/**
* Create subsites such as team sites, Meeting Workspace sites, and Document Workspace sites.
*/
PermissionKind[PermissionKind["ManageSubwebs"] = 24] = "ManageSubwebs";
/**
* Create a group of users that can be used anywhere within the site collection.
*/
PermissionKind[PermissionKind["CreateGroups"] = 25] = "CreateGroups";
/**
* Create and change permission levels on the Site and assign permissions to users
* and groups.
*/
PermissionKind[PermissionKind["ManagePermissions"] = 26] = "ManagePermissions";
/**
* Enumerate files and folders in a Site using Microsoft Office SharePoint Designer
* and WebDAV interfaces.
*/
PermissionKind[PermissionKind["BrowseDirectories"] = 27] = "BrowseDirectories";
/**
* View information about users of the Site.
*/
PermissionKind[PermissionKind["BrowseUserInfo"] = 28] = "BrowseUserInfo";
/**
* Add or remove personal Web Parts on a Web Part Page.
*/
PermissionKind[PermissionKind["AddDelPrivateWebParts"] = 29] = "AddDelPrivateWebParts";
/**
* Update Web Parts to display personalized information.
*/
PermissionKind[PermissionKind["UpdatePersonalWebParts"] = 30] = "UpdatePersonalWebParts";
/**
* Grant the ability to perform all administration tasks for the Site as well as
* manage content, activate, deactivate, or edit properties of Site scoped Features
* through the object model or through the user interface (UI). When granted on the
* root Site of a Site Collection, activate, deactivate, or edit properties of
* site collection scoped Features through the object model. To browse to the Site
* Collection Features page and activate or deactivate Site Collection scoped Features
* through the UI, you must be a Site Collection administrator.
*/
PermissionKind[PermissionKind["ManageWeb"] = 31] = "ManageWeb";
/**
* Content of lists and document libraries in the Web site will be retrieveable for anonymous users through
* SharePoint search if the list or document library has AnonymousSearchAccessList set.
*/
PermissionKind[PermissionKind["AnonymousSearchAccessWebLists"] = 32] = "AnonymousSearchAccessWebLists";
/**
* Use features that launch client applications. Otherwise, users must work on documents
* locally and upload changes.
*/
PermissionKind[PermissionKind["UseClientIntegration"] = 37] = "UseClientIntegration";
/**
* Use SOAP, WebDAV, or Microsoft Office SharePoint Designer interfaces to access the Site.
*/
PermissionKind[PermissionKind["UseRemoteAPIs"] = 38] = "UseRemoteAPIs";
/**
* Manage alerts for all users of the Site.
*/
PermissionKind[PermissionKind["ManageAlerts"] = 39] = "ManageAlerts";
/**
* Create e-mail alerts.
*/
PermissionKind[PermissionKind["CreateAlerts"] = 40] = "CreateAlerts";
/**
* Allows a user to change his or her user information, such as adding a picture.
*/
PermissionKind[PermissionKind["EditMyUserInfo"] = 41] = "EditMyUserInfo";
/**
* Enumerate permissions on Site, list, folder, document, or list item.
*/
PermissionKind[PermissionKind["EnumeratePermissions"] = 63] = "EnumeratePermissions";
/**
* Has all permissions on the Site. Not available through the user interface.
*/
PermissionKind[PermissionKind["FullMask"] = 65] = "FullMask";
})(exports.PermissionKind || (exports.PermissionKind = {}));
(function (PrincipalType) {
/**
* Enumeration whose value specifies no principal type.
*/
PrincipalType[PrincipalType["None"] = 0] = "None";
/**
* Enumeration whose value specifies a user as the principal type.
*/
PrincipalType[PrincipalType["User"] = 1] = "User";
/**
* Enumeration whose value specifies a distribution list as the principal type.
*/
PrincipalType[PrincipalType["DistributionList"] = 2] = "DistributionList";
/**
* Enumeration whose value specifies a security group as the principal type.
*/
PrincipalType[PrincipalType["SecurityGroup"] = 4] = "SecurityGroup";
/**
* Enumeration whose value specifies a group as the principal type.
*/
PrincipalType[PrincipalType["SharePointGroup"] = 8] = "SharePointGroup";
/**
* Enumeration whose value specifies all principal types.
*/
PrincipalType[PrincipalType["All"] = 15] = "All";
})(exports.PrincipalType || (exports.PrincipalType = {}));
(function (PrincipalSource) {
/**
* Enumeration whose value specifies no principal source.
*/
PrincipalSource[PrincipalSource["None"] = 0] = "None";
/**
* Enumeration whose value specifies user information list as the principal source.
*/
PrincipalSource[PrincipalSource["UserInfoList"] = 1] = "UserInfoList";
/**
* Enumeration whose value specifies Active Directory as the principal source.
*/
PrincipalSource[PrincipalSource["Windows"] = 2] = "Windows";
/**
* Enumeration whose value specifies the current membership provider as the principal source.
*/
PrincipalSource[PrincipalSource["MembershipProvider"] = 4] = "MembershipProvider";
/**
* Enumeration whose value specifies the current role provider as the principal source.
*/
PrincipalSource[PrincipalSource["RoleProvider"] = 8] = "RoleProvider";
/**
* Enumeration whose value specifies all principal sources.
*/
PrincipalSource[PrincipalSource["All"] = 15] = "All";
})(exports.PrincipalSource || (exports.PrincipalSource = {}));
(function (RoleType) {
RoleType[RoleType["None"] = 0] = "None";
RoleType[RoleType["Guest"] = 1] = "Guest";
RoleType[RoleType["Reader"] = 2] = "Reader";
RoleType[RoleType["Contributor"] = 3] = "Contributor";
RoleType[RoleType["WebDesigner"] = 4] = "WebDesigner";
RoleType[RoleType["Administrator"] = 5] = "Administrator";
})(exports.RoleType || (exports.RoleType = {}));
(function (PageType) {
PageType[PageType["Invalid"] = -1] = "Invalid";
PageType[PageType["DefaultView"] = 0] = "DefaultView";
PageType[PageType["NormalView"] = 1] = "NormalView";
PageType[PageType["DialogView"] = 2] = "DialogView";
PageType[PageType["View"] = 3] = "View";
PageType[PageType["DisplayForm"] = 4] = "DisplayForm";
PageType[PageType["DisplayFormDialog"] = 5] = "DisplayFormDialog";
PageType[PageType["EditForm"] = 6] = "EditForm";
PageType[PageType["EditFormDialog"] = 7] = "EditFormDialog";
PageType[PageType["NewForm"] = 8] = "NewForm";
PageType[PageType["NewFormDialog"] = 9] = "NewFormDialog";
PageType[PageType["SolutionForm"] = 10] = "SolutionForm";
PageType[PageType["PAGE_MAXITEMS"] = 11] = "PAGE_MAXITEMS";
})(exports.PageType || (exports.PageType = {}));
(function (SharingLinkKind) {
/**
* Uninitialized link
*/
SharingLinkKind[SharingLinkKind["Uninitialized"] = 0] = "Uninitialized";
/**
* Direct link to the object being shared
*/
SharingLinkKind[SharingLinkKind["Direct"] = 1] = "Direct";
/**
* Organization-shareable link to the object being shared with view permissions
*/
SharingLinkKind[SharingLinkKind["OrganizationView"] = 2] = "OrganizationView";
/**
* Organization-shareable link to the object being shared with edit permissions
*/
SharingLinkKind[SharingLinkKind["OrganizationEdit"] = 3] = "OrganizationEdit";
/**
* View only anonymous link
*/
SharingLinkKind[SharingLinkKind["AnonymousView"] = 4] = "AnonymousView";
/**
* Read/Write anonymous link
*/
SharingLinkKind[SharingLinkKind["AnonymousEdit"] = 5] = "AnonymousEdit";
/**
* Flexible sharing Link where properties can change without affecting link URL
*/
SharingLinkKind[SharingLinkKind["Flexible"] = 6] = "Flexible";
})(exports.SharingLinkKind || (exports.SharingLinkKind = {}));
(function (SharingRole) {
SharingRole[SharingRole["None"] = 0] = "None";
SharingRole[SharingRole["View"] = 1] = "View";
SharingRole[SharingRole["Edit"] = 2] = "Edit";
SharingRole[SharingRole["Owner"] = 3] = "Owner";
})(exports.SharingRole || (exports.SharingRole = {}));
(function (SharingOperationStatusCode) {
/**
* The share operation completed without errors.
*/
SharingOperationStatusCode[SharingOperationStatusCode["CompletedSuccessfully"] = 0] = "CompletedSuccessfully";
/**
* The share operation completed and generated requests for access.
*/
SharingOperationStatusCode[SharingOperationStatusCode["AccessRequestsQueued"] = 1] = "AccessRequestsQueued";
/**
* The share operation failed as there were no resolved users.
*/
SharingOperationStatusCode[SharingOperationStatusCode["NoResolvedUsers"] = -1] = "NoResolvedUsers";
/**
* The share operation failed due to insufficient permissions.
*/
SharingOperationStatusCode[SharingOperationStatusCode["AccessDenied"] = -2] = "AccessDenied";
/**
* The share operation failed when attempting a cross site share, which is not supported.
*/
SharingOperationStatusCode[SharingOperationStatusCode["CrossSiteRequestNotSupported"] = -3] = "CrossSiteRequestNotSupported";
/**
* The sharing operation failed due to an unknown error.
*/
SharingOperationStatusCode[SharingOperationStatusCode["UnknowError"] = -4] = "UnknowError";
/**
* The text you typed is too long. Please shorten it.
*/
SharingOperationStatusCode[SharingOperationStatusCode["EmailBodyTooLong"] = -5] = "EmailBodyTooLong";
/**
* The maximum number of unique scopes in the list has been exceeded.
*/
SharingOperationStatusCode[SharingOperationStatusCode["ListUniqueScopesExceeded"] = -6] = "ListUniqueScopesExceeded";
/**
* The share operation failed because a sharing capability is disabled in the site.
*/
SharingOperationStatusCode[SharingOperationStatusCode["CapabilityDisabled"] = -7] = "CapabilityDisabled";
/**
* The specified object for the share operation is not supported.
*/
SharingOperationStatusCode[SharingOperationStatusCode["ObjectNotSupported"] = -8] = "ObjectNotSupported";
/**
* A SharePoint group cannot contain another SharePoint group.
*/
SharingOperationStatusCode[SharingOperationStatusCode["NestedGroupsNotSupported"] = -9] = "NestedGroupsNotSupported";
})(exports.SharingOperationStatusCode || (exports.SharingOperationStatusCode = {}));
(function (SPSharedObjectType) {
SPSharedObjectType[SPSharedObjectType["Unknown"] = 0] = "Unknown";
SPSharedObjectType[SPSharedObjectType["File"] = 1] = "File";
SPSharedObjectType[SPSharedObjectType["Folder"] = 2] = "Folder";
SPSharedObjectType[SPSharedObjectType["Item"] = 3] = "Item";
SPSharedObjectType[SPSharedObjectType["List"] = 4] = "List";
SPSharedObjectType[SPSharedObjectType["Web"] = 5] = "Web";
SPSharedObjectType[SPSharedObjectType["Max"] = 6] = "Max";
})(exports.SPSharedObjectType || (exports.SPSharedObjectType = {}));
(function (SharingDomainRestrictionMode) {
SharingDomainRestrictionMode[SharingDomainRestrictionMode["None"] = 0] = "None";
SharingDomainRestrictionMode[SharingDomainRestrictionMode["AllowList"] = 1] = "AllowList";
SharingDomainRestrictionMode[SharingDomainRestrictionMode["BlockList"] = 2] = "BlockList";
})(exports.SharingDomainRestrictionMode || (exports.SharingDomainRestrictionMode = {}));
(function (RenderListDataOptions) {
RenderListDataOptions[RenderListDataOptions["None"] = 0] = "None";
RenderListDataOptions[RenderListDataOptions["ContextInfo"] = 1] = "ContextInfo";
RenderListDataOptions[RenderListDataOptions["ListData"] = 2] = "ListData";
RenderListDataOptions[RenderListDataOptions["ListSchema"] = 4] = "ListSchema";
RenderListDataOptions[RenderListDataOptions["MenuView"] = 8] = "MenuView";
RenderListDataOptions[RenderListDataOptions["ListContentType"] = 16] = "ListContentType";
RenderListDataOptions[RenderListDataOptions["FileSystemItemId"] = 32] = "FileSystemItemId";
RenderListDataOptions[RenderListDataOptions["ClientFormSchema"] = 64] = "ClientFormSchema";
RenderListDataOptions[RenderListDataOptions["QuickLaunch"] = 128] = "QuickLaunch";
RenderListDataOptions[RenderListDataOptions["Spotlight"] = 256] = "Spotlight";
RenderListDataOptions[RenderListDataOptions["Visualization"] = 512] = "Visualization";
RenderListDataOptions[RenderListDataOptions["ViewMetadata"] = 1024] = "ViewMetadata";
RenderListDataOptions[RenderListDataOptions["DisableAutoHyperlink"] = 2048] = "DisableAutoHyperlink";
RenderListDataOptions[RenderListDataOptions["EnableMediaTAUrls"] = 4096] = "EnableMediaTAUrls";
RenderListDataOptions[RenderListDataOptions["ParentInfo"] = 8192] = "ParentInfo";
RenderListDataOptions[RenderListDataOptions["PageContextInfo"] = 16384] = "PageContextInfo";
RenderListDataOptions[RenderListDataOptions["ClientSideComponentManifest"] = 32768] = "ClientSideComponentManifest";
})(exports.RenderListDataOptions || (exports.RenderListDataOptions = {}));
(function (FieldUserSelectionMode) {
FieldUserSelectionMode[FieldUserSelectionMode["PeopleAndGroups"] = 1] = "PeopleAndGroups";
FieldUserSelectionMode[FieldUserSelectionMode["PeopleOnly"] = 0] = "PeopleOnly";
})(exports.FieldUserSelectionMode || (exports.FieldUserSelectionMode = {}));
(function (ChoiceFieldFormatType) {
ChoiceFieldFormatType[ChoiceFieldFormatType["Dropdown"] = 0] = "Dropdown";
ChoiceFieldFormatType[ChoiceFieldFormatType["RadioButtons"] = 1] = "RadioButtons";
})(exports.ChoiceFieldFormatType || (exports.ChoiceFieldFormatType = {}));
(function (UrlZone) {
/**
* Specifies the default zone used for requests unless another zone is specified.
*/
UrlZone[UrlZone["DefaultZone"] = 0] = "DefaultZone";
/**
* Specifies an intranet zone.
*/
UrlZone[UrlZone["Intranet"] = 1] = "Intranet";
/**
* Specifies an Internet zone.
*/
UrlZone[UrlZone["Internet"] = 2] = "Internet";
/**
* Specifies a custom zone.
*/
UrlZone[UrlZone["Custom"] = 3] = "Custom";
/**
* Specifies an extranet zone.
*/
UrlZone[UrlZone["Extranet"] = 4] = "Extranet";
})(exports.UrlZone || (exports.UrlZone = {}));
var SharePointQueryableSecurable = /** @class */ (function (_super) {
__extends(SharePointQueryableSecurable, _super);
function SharePointQueryableSecurable() {
return _super !== null && _super.apply(this, arguments) || this;
}
Object.defineProperty(SharePointQueryableSecurable.prototype, "roleAssignments", {
/**
* Gets the set of role assignments for this item
*
*/
get: function () {
return new RoleAssignments(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(SharePointQueryableSecurable.prototype, "firstUniqueAncestorSecurableObject", {
/**
* Gets the closest securable up the security hierarchy whose permissions are applied to this list item
*
*/
get: function () {
return new SharePointQueryableInstance(this, "FirstUniqueAncestorSecurableObject");
},
enumerable: true,
configurable: true
});
/**
* Gets the effective permissions for the user supplied
*
* @param loginName The claims username for the user (ex: i:0#.f|membership|user@domain.com)
*/
SharePointQueryableSecurable.prototype.getUserEffectivePermissions = function (loginName) {
var q = this.clone(SharePointQueryable, "getUserEffectivePermissions(@user)");
q.query.set("@user", "'" + encodeURIComponent(loginName) + "'");
return q.get().then(function (r) {
// handle verbose mode
return common.hOP(r, "GetUserEffectivePermissions") ? r.GetUserEffectivePermissions : r;
});
};
/**
* Gets the effective permissions for the current user
*/
SharePointQueryableSecurable.prototype.getCurrentUserEffectivePermissions = function () {
var _this = this;
// remove need to reference Web here, which created a circular build issue
var w = new SharePointQueryableInstance("_api/web", "currentuser");
return w.configureFrom(this).select("LoginName").get().then(function (user) {
return _this.getUserEffectivePermissions(user.LoginName);
});
};
/**
* Breaks the security inheritance at this level optinally copying permissions and clearing subscopes
*
* @param copyRoleAssignments If true the permissions are copied from the current parent scope
* @param clearSubscopes Optional. true to make all child securable objects inherit role assignments from the current object
*/
SharePointQueryableSecurable.prototype.breakRoleInheritance = function (copyRoleAssignments, clearSubscopes) {
if (copyRoleAssignments === void 0) { copyRoleAssignments = false; }
if (clearSubscopes === void 0) { clearSubscopes = false; }
return this.clone(SharePointQueryableSecurable, "breakroleinheritance(copyroleassignments=" + copyRoleAssignments + ", clearsubscopes=" + clearSubscopes + ")").postCore();
};
/**
* Removes the local role assignments so that it re-inherit role assignments from the parent object.
*
*/
SharePointQueryableSecurable.prototype.resetRoleInheritance = function () {
return this.clone(SharePointQueryableSecurable, "resetroleinheritance").postCore();
};
/**
* Determines if a given user has the appropriate permissions
*
* @param loginName The user to check
* @param permission The permission being checked
*/
SharePointQueryableSecurable.prototype.userHasPermissions = function (loginName, permission) {
var _this = this;
return this.getUserEffectivePermissions(loginName).then(function (perms) {
return _this.hasPermissions(perms, permission);
});
};
/**
* Determines if the current user has the requested permissions
*
* @param permission The permission we wish to check
*/
SharePointQueryableSecurable.prototype.currentUserHasPermissions = function (permission) {
var _this = this;
return this.getCurrentUserEffectivePermissions().then(function (perms) {
return _this.hasPermissions(perms, permission);
});
};
/**
* Taken from sp.js, checks the supplied permissions against the mask
*
* @param value The security principal's permissions on the given object
* @param perm The permission checked against the value
*/
/* tslint:disable:no-bitwise */
SharePointQueryableSecurable.prototype.hasPermissions = function (value, perm) {
if (!perm) {
return true;
}
if (perm === exports.PermissionKind.FullMask) {
return (value.High & 32767) === 32767 && value.Low === 65535;
}
perm = perm - 1;
var num = 1;
if (perm >= 0 && perm < 32) {
num = num << perm;
return 0 !== (value.Low & num);
}
else if (perm >= 32 && perm < 64) {
num = num << perm - 32;
return 0 !== (value.High & num);
}
return false;
};
return SharePointQueryableSecurable;
}(SharePointQueryableInstance));
/**
* Internal helper class used to augment classes to include sharing functionality
*/
var SharePointQueryableShareable = /** @class */ (function (_super) {
__extends(SharePointQueryableShareable, _super);
function SharePointQueryableShareable() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Gets a sharing link for the supplied
*
* @param kind The kind of link to share
* @param expiration The optional expiration for this link
*/
SharePointQueryableShareable.prototype.getShareLink = function (kind, expiration) {
if (expiration === void 0) { expiration = null; }
// date needs to be an ISO string or null
var expString = expiration !== null ? expiration.toISOString() : null;
// clone using the factory and send the request
return this.clone(SharePointQueryableShareable, "shareLink").postCore({
body: common.jsS({
request: {
createLink: true,
emailData: null,
settings: {
expiration: expString,
linkKind: kind,
},
},
}),
});
};
/**
* Shares this instance with the supplied users
*
* @param loginNames Resolved login names to share
* @param role The role
* @param requireSignin True to require the user is authenticated, otherwise false
* @param propagateAcl True to apply this share to all children
* @param emailData If supplied an email will be sent with the indicated properties
*/
SharePointQueryableShareable.prototype.shareWith = function (loginNames, role, requireSignin, propagateAcl, emailData) {
var _this = this;
if (requireSignin === void 0) { requireSignin = false; }
if (propagateAcl === void 0) { propagateAcl = false; }
// handle the multiple input types
if (!Array.isArray(loginNames)) {
loginNames = [loginNames];
}
var userStr = common.jsS(loginNames.map(function (login) { return { Key: login }; }));
var roleFilter = role === exports.SharingRole.Edit ? exports.RoleType.Contributor : exports.RoleType.Reader;
// start by looking up the role definition id we need to set the roleValue
// remove need to reference Web here, which created a circular build issue
var w = new SharePointQueryableCollection("_api/web", "roledefinitions");
return w.select("Id").filter("RoleTypeKind eq " + roleFilter).get().then(function (def) {
if (!Array.isArray(def) || def.length < 1) {
throw Error("Could not locate a role defintion with RoleTypeKind " + roleFilter);
}
var postBody = {
includeAnonymousLinkInEmail: requireSignin,
peoplePickerInput: userStr,
propagateAcl: propagateAcl,
roleValue: "role:" + def[0].Id,
useSimplifiedRoles: true,
};
if (emailData !== undefined) {
postBody = common.extend(postBody, {
emailBody: emailData.body,
emailSubject: emailData.subject !== undefined ? emailData.subject : "",
sendEmail: true,
});
}
return _this.clone(SharePointQueryableShareable, "shareObject").postCore({
body: common.jsS(postBody),
});
});
};
/**
* Shares an object based on the supplied options
*
* @param options The set of options to send to the ShareObject method
* @param bypass If true any processing is skipped and the options are sent directly to the ShareObject method
*/
SharePointQueryableShareable.prototype.shareObject = function (options, bypass) {
var _this = this;
if (bypass === void 0) { bypass = false; }
if (bypass) {
// if the bypass flag is set send the supplied parameters directly to the service
return this.sendShareObjectRequest(options);
}
// extend our options with some defaults
options = common.extend(options, {
group: null,
includeAnonymousLinkInEmail: false,
propagateAcl: false,
useSimplifiedRoles: true,
}, true);
return this.getRoleValue(options.role, options.group).then(function (roleValue) {
// handle the multiple input types
if (!Array.isArray(options.loginNames)) {
options.loginNames = [options.loginNames];
}
var userStr = common.jsS(options.loginNames.map(function (login) { return { Key: login }; }));
var postBody = {
peoplePickerInput: userStr,
roleValue: roleValue,
url: options.url,
};
if (options.emailData !== undefined && options.emailData !== null) {
postBody = common.extend(postBody, {
emailBody: options.emailData.body,
emailSubject: options.emailData.subject !== undefined ? options.emailData.subject : "Shared with you.",
sendEmail: true,
});
}
return _this.sendShareObjectRequest(postBody);
});
};
/**
* Calls the web's UnshareObject method
*
* @param url The url of the object to unshare
*/
SharePointQueryableShareable.prototype.unshareObjectWeb = function (url) {
return this.clone(SharePointQueryableShareable, "unshareObject").postCore({
body: common.jsS({
url: url,
}),
});
};
/**
* Checks Permissions on the list of Users and returns back role the users have on the Item.
*
* @param recipients The array of Entities for which Permissions need to be checked.
*/
SharePointQueryableShareable.prototype.checkPermissions = function (recipients) {
return this.clone(SharePointQueryableShareable, "checkPermissions").postCore({
body: common.jsS({
recipients: recipients,
}),
});
};
/**
* Get Sharing Information.
*
* @param request The SharingInformationRequest Object.
* @param expands Expand more fields.
*
*/
SharePointQueryableShareable.prototype.getSharingInformation = function (request, expands) {
if (request === void 0) { request = null; }
var q = this.clone(SharePointQueryableShareable, "getSharingInformation");
return q.expand.apply(q, expands).postCore({
body: common.jsS({
request: request,
}),
});
};
/**
* Gets the sharing settings of an item.
*
* @param useSimplifiedRoles Determines whether to use simplified roles.
*/
SharePointQueryableShareable.prototype.getObjectSharingSettings = function (useSimplifiedRoles) {
if (useSimplifiedRoles === void 0) { useSimplifiedRoles = true; }
return this.clone(SharePointQueryableShareable, "getObjectSharingSettings").postCore({
body: common.jsS({
useSimplifiedRoles: useSimplifiedRoles,
}),
});
};
/**
* Unshares this object
*/
SharePointQueryableShareable.prototype.unshareObject = function () {
return this.clone(SharePointQueryableShareable, "unshareObject").postCore();
};
/**
* Deletes a link by type
*
* @param kind Deletes a sharing link by the kind of link
*/
SharePointQueryableShareable.prototype.deleteLinkByKind = function (kind) {
return this.clone(SharePointQueryableShareable, "deleteLinkByKind").postCore({
body: common.jsS({ linkKind: kind }),
});
};
/**
* Removes the specified link to the item.
*
* @param kind The kind of link to be deleted.
* @param shareId
*/
SharePointQueryableShareable.prototype.unshareLink = function (kind, shareId) {
if (shareId === void 0) { shareId = "00000000-0000-0000-0000-000000000000"; }
return this.clone(SharePointQueryableShareable, "unshareLink").postCore({
body: common.jsS({ linkKind: kind, shareId: shareId }),
});
};
/**
* Calculates the roleValue string used in the sharing query
*
* @param role The Sharing Role
* @param group The Group type
*/
SharePointQueryableShareable.prototype.getRoleValue = function (role, group) {
// we will give group precedence, because we had to make a choice
if (group !== undefined && group !== null) {
switch (group) {
case exports.RoleType.Contributor:
// remove need to reference Web here, which created a circular build issue
var memberGroup = new SharePointQueryableInstance("_api/web", "associatedmembergroup");
return memberGroup.select("Id").get().then(function (g) { return "group: " + g.Id; });
case exports.RoleType.Reader:
case exports.RoleType.Guest:
// remove need to reference Web here, which created a circular build issue
var visitorGroup = new SharePointQueryableInstance("_api/web", "associatedvisitorgroup");
return visitorGroup.select("Id").get().then(function (g) { return "group: " + g.Id; });
default:
throw Error("Could not determine role value for supplied value. Contributor, Reader, and Guest are supported");
}
}
else {
var roleFilter = role === exports.SharingRole.Edit ? exports.RoleType.Contributor : exports.RoleType.Reader;
// remove need to reference Web here, which created a circular build issue
var roleDefs = new SharePointQueryableCollection("_api/web", "roledefinitions");
return roleDefs.select("Id").top(1).filter("RoleTypeKind eq " + roleFilter).get().then(function (def) {
if (def.length < 1) {
throw Error("Could not locate associated role definition for supplied role. Edit and View are supported");
}
return "role: " + def[0].Id;
});
}
};
SharePointQueryableShareable.prototype.getShareObjectWeb = function (candidate) {
return Promise.resolve(new SharePointQueryableInstance(extractWebUrl(candidate), "/_api/SP.Web.ShareObject"));
};
SharePointQueryableShareable.prototype.sendShareObjectRequest = function (options) {
return this.getShareObjectWeb(this.toUrl()).then(function (web) {
return web.expand("UsersWithAccessRequests", "GroupsSharedWith").as(SharePointQueryableShareable).postCore({
body: common.jsS(options),
});
});
};
return SharePointQueryableShareable;
}(SharePointQueryable));
var SharePointQueryableShareableWeb = /** @class */ (function (_super) {
__extends(SharePointQueryableShareableWeb, _super);
function SharePointQueryableShareableWeb() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Shares this web with the supplied users
* @param loginNames The resolved login names to share
* @param role The role to share this web
* @param emailData Optional email data
*/
SharePointQueryableShareableWeb.prototype.shareWith = function (loginNames, role, emailData) {
var _this = this;
if (role === void 0) { role = exports.SharingRole.View; }
var dependency = this.addBatchDependency();
// remove need to reference Web here, which created a circular build issue
var web = new SharePointQueryableInstance(extractWebUrl(this.toUrl()), "/_api/web/url");
return web.get().then(function (url) {
dependency();
return _this.shareObject(common.combine(url, "/_layouts/15/aclinv.aspx?forSharing=1&mbypass=1"), loginNames, role, emailData);
});
};
/**
* Provides direct access to the static web.ShareObject method
*
* @param url The url to share
* @param loginNames Resolved loginnames string[] of a single login name string
* @param roleValue Role value
* @param emailData Optional email data
* @param groupId Optional group id
* @param propagateAcl
* @param includeAnonymousLinkInEmail
* @param useSimplifiedRoles
*/
SharePointQueryableShareableWeb.prototype.shareObject = function (url, loginNames, role, emailData, group, propagateAcl, includeAnonymousLinkInEmail, useSimplifiedRoles) {
if (propagateAcl === void 0) { propagateAcl = false; }
if (includeAnonymousLinkInEmail === void 0) { includeAnonymousLinkInEmail = false; }
if (useSimplifiedRoles === void 0) { useSimplifiedRoles = true; }
return this.clone(SharePointQueryableShareable, null).shareObject({
emailData: emailData,
group: group,
includeAnonymousLinkInEmail: includeAnonymousLinkInEmail,
loginNames: loginNames,
propagateAcl: propagateAcl,
role: role,
url: url,
useSimplifiedRoles: useSimplifiedRoles,
});
};
/**
* Supplies a method to pass any set of arguments to ShareObject
*
* @param options The set of options to send to ShareObject
*/
SharePointQueryableShareableWeb.prototype.shareObjectRaw = function (options) {
return this.clone(SharePointQueryableShareable, null).shareObject(options, true);
};
/**
* Unshares the object
*
* @param url The url of the object to stop sharing
*/
SharePointQueryableShareableWeb.prototype.unshareObject = function (url) {
return this.clone(SharePointQueryableShareable, null).unshareObjectWeb(url);
};
return SharePointQueryableShareableWeb;
}(SharePointQueryableSecurable));
var SharePointQueryableShareableItem = /** @class */ (function (_super) {
__extends(SharePointQueryableShareableItem, _super);
function SharePointQueryableShareableItem() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Gets a link suitable for sharing for this item
*
* @param kind The type of link to share
* @param expiration The optional expiration date
*/
SharePointQueryableShareableItem.prototype.getShareLink = function (kind, expiration) {
if (kind === void 0) { kind = exports.SharingLinkKind.OrganizationView; }
if (expiration === void 0) { expiration = null; }
return this.clone(SharePointQueryableShareable, null).getShareLink(kind, expiration);
};
/**
* Shares this item with one or more users
*
* @param loginNames string or string[] of resolved login names to which this item will be shared
* @param role The role (View | Edit) applied to the share
* @param emailData Optional, if inlucded an email will be sent. Note subject currently has no effect.
*/
SharePointQueryableShareableItem.prototype.shareWith = function (loginNames, role, requireSignin, emailData) {
if (role === void 0) { role = exports.SharingRole.View; }
if (requireSignin === void 0) { requireSignin = false; }
return this.clone(SharePointQueryableShareable, null).shareWith(loginNames, role, requireSignin, false, emailData);
};
/**
* Checks Permissions on the list of Users and returns back role the users have on the Item.
*
* @param recipients The array of Entities for which Permissions need to be checked.
*/
SharePointQueryableShareableItem.prototype.checkSharingPermissions = function (recipients) {
return this.clone(SharePointQueryableShareable, null).checkPermissions(recipients);
};
/**
* Get Sharing Information.
*
* @param request The SharingInformationRequest Object.
* @param expands Expand more fields.
*
*/
SharePointQueryableShareableItem.prototype.getSharingInformation = function (request, expands) {
if (request === void 0) { request = null; }
return this.clone(SharePointQueryableShareable, null).getSharingInformation(request, expands);
};
/**
* Gets the sharing settings of an item.
*
* @param useSimplifiedRoles Determines whether to use simplified roles.
*/
SharePointQueryableShareableItem.prototype.getObjectSharingSettings = function (useSimplifiedRoles) {
if (useSimplifiedRoles === void 0) { useSimplifiedRoles = true; }
return this.clone(SharePointQueryableShareable, null).getObjectSharingSettings(useSimplifiedRoles);
};
/**
* Unshare this item
*/
SharePointQueryableShareableItem.prototype.unshare = function () {
return this.clone(SharePointQueryableShareable, null).unshareObject();
};
/**
* Deletes a sharing link by kind
*
* @param kind Deletes a sharing link by the kind of link
*/
SharePointQueryableShareableItem.prototype.deleteSharingLinkByKind = function (kind) {
return this.clone(SharePointQueryableShareable, null).deleteLinkByKind(kind);
};
/**
* Removes the specified link to the item.
*
* @param kind The kind of link to be deleted.
* @param shareId
*/
SharePointQueryableShareableItem.prototype.unshareLink = function (kind, shareId) {
return this.clone(SharePointQueryableShareable, null).unshareLink(kind, shareId);
};
return SharePointQueryableShareableItem;
}(SharePointQueryableSecurable));
var FileFolderShared = /** @class */ (function (_super) {
__extends(FileFolderShared, _super);
function FileFolderShared() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Gets a link suitable for sharing
*
* @param kind The kind of link to get
* @param expiration Optional, an expiration for this link
*/
FileFolderShared.prototype.getShareLink = function (kind, expiration) {
if (kind === void 0) { kind = exports.SharingLinkKind.OrganizationView; }
if (expiration === void 0) { expiration = null; }
var dependency = this.addBatchDependency();
return this.getShareable().then(function (shareable) {
dependency();
return shareable.getShareLink(kind, expiration);
});
};
/**
* Checks Permissions on the list of Users and returns back role the users have on the Item.
*
* @param recipients The array of Entities for which Permissions need to be checked.
*/
FileFolderShared.prototype.checkSharingPermissions = function (recipients) {
var dependency = this.addBatchDependency();
return this.getShareable().then(function (shareable) {
dependency();
return shareable.checkPermissions(recipients);
});
};
/**
* Get Sharing Information.
*
* @param request The SharingInformationRequest Object.
* @param expands Expand more fields.
*
*/
FileFolderShared.prototype.getSharingInformation = function (request, expands) {
if (request === void 0) { request = null; }
var dependency = this.addBatchDependency();
return this.getShareable().then(function (shareable) {
dependency();
return shareable.getSharingInformation(request, expands);
});
};
/**
* Gets the sharing settings of an item.
*
* @param useSimplifiedRoles Determines whether to use simplified roles.
*/
FileFolderShared.prototype.getObjectSharingSettings = function (useSimplifiedRoles) {
if (useSimplifiedRoles === void 0) { useSimplifiedRoles = true; }
var dependency = this.addBatchDependency();
return this.getShareable().then(function (shareable) {
dependency();
return shareable.getObjectSharingSettings(useSimplifiedRoles);
});
};
/**
* Unshare this item
*/
FileFolderShared.prototype.unshare = function () {
var dependency = this.addBatchDependency();
return this.getShareable().then(function (shareable) {
dependency();
return shareable.unshareObject();
});
};
/**
* Deletes a sharing link by the kind of link
*
* @param kind The kind of link to be deleted.
*/
FileFolderShared.prototype.deleteSharingLinkByKind = function (kind) {
var dependency = this.addBatchDependency();
return this.getShareable().then(function (shareable) {
dependency();
return shareable.deleteLinkByKind(kind);
});
};
/**
* Removes the specified link to the item.
*
* @param kind The kind of link to be deleted.
* @param shareId The share id to delete
*/
FileFolderShared.prototype.unshareLink = function (kind, shareId) {
var dependency = this.addBatchDependency();
return this.getShareable().then(function (shareable) {
dependency();
return shareable.unshareLink(kind, shareId);
});
};
/**
* For files and folders we need to use the associated item end point
*/
FileFolderShared.prototype.getShareable = function () {
var _this = this;
// sharing only works on the item end point, not the file one - so we create a folder instance with the item url internally
return this.clone(SharePointQueryableShareableFile, "listItemAllFields", false).select("odata.id").get().then(function (d) {
var shareable = new SharePointQueryableShareable(odataUrlFrom(d));
// we need to handle batching
if (_this.hasBatch) {
shareable = shareable.inBatch(_this.batch);
}
return shareable;
});
};
return FileFolderShared;
}(SharePointQueryableInstance));
var SharePointQueryableShareableFile = /** @class */ (function (_super) {
__extends(SharePointQueryableShareableFile, _super);
function SharePointQueryableShareableFile() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Shares this item with one or more users
*
* @param loginNames string or string[] of resolved login names to which this item will be shared
* @param role The role (View | Edit) applied to the share
* @param shareEverything Share everything in this folder, even items with unique permissions.
* @param requireSignin If true the user must signin to view link, otherwise anyone with the link can access the resource
* @param emailData Optional, if inlucded an email will be sent. Note subject currently has no effect.
*/
SharePointQueryableShareableFile.prototype.shareWith = function (loginNames, role, requireSignin, emailData) {
if (role === void 0) { role = exports.SharingRole.View; }
if (requireSignin === void 0) { requireSignin = false; }
var dependency = this.addBatchDependency();
return this.getShareable().then(function (shareable) {
dependency();
return shareable.shareWith(loginNames, role, requireSignin, false, emailData);
});
};
return SharePointQueryableShareableFile;
}(FileFolderShared));
var SharePointQueryableShareableFolder = /** @class */ (function (_super) {
__extends(SharePointQueryableShareableFolder, _super);
function SharePointQueryableShareableFolder() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Shares this item with one or more users
*
* @param loginNames string or string[] of resolved login names to which this item will be shared
* @param role The role (View | Edit) applied to the share
* @param shareEverything Share everything in this folder, even items with unique permissions.
* @param requireSignin If true the user must signin to view link, otherwise anyone with the link can access the resource
* @param emailData Optional, if inlucded an email will be sent. Note subject currently has no effect.
*/
SharePointQueryableShareableFolder.prototype.shareWith = function (loginNames, role, requireSignin, shareEverything, emailData) {
if (role === void 0) { role = exports.SharingRole.View; }
if (requireSignin === void 0) { requireSignin = false; }
if (shareEverything === void 0) { shareEverything = false; }
var dependency = this.addBatchDependency();
return this.getShareable().then(function (shareable) {
dependency();
return shareable.shareWith(loginNames, role, requireSignin, shareEverything, emailData);
});
};
return SharePointQueryableShareableFolder;
}(FileFolderShared));
var LimitedWebPartManager = /** @class */ (function (_super) {
__extends(LimitedWebPartManager, _super);
function LimitedWebPartManager() {
return _super !== null && _super.apply(this, arguments) || this;
}
Object.defineProperty(LimitedWebPartManager.prototype, "webparts", {
/**
* Gets the set of web part definitions contained by this web part manager
*
*/
get: function () {
return new WebPartDefinitions(this, "webparts");
},
enumerable: true,
configurable: true
});
/**
* Exports a webpart definition
*
* @param id the GUID id of the definition to export
*/
LimitedWebPartManager.prototype.export = function (id) {
return this.clone(LimitedWebPartManager, "ExportWebPart").postCore({
body: common.jsS({ webPartId: id }),
});
};
/**
* Imports a webpart
*
* @param xml webpart definition which must be valid XML in the .dwp or .webpart format
*/
LimitedWebPartManager.prototype.import = function (xml) {
return this.clone(LimitedWebPartManager, "ImportWebPart").postCore({
body: common.jsS({ webPartXml: xml }),
});
};
return LimitedWebPartManager;
}(SharePointQueryable));
var WebPartDefinitions = /** @class */ (function (_super) {
__extends(WebPartDefinitions, _super);
function WebPartDefinitions() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Gets a web part definition from the collection by id
*
* @param id The storage ID of the SPWebPartDefinition to retrieve
*/
WebPartDefinitions.prototype.getById = function (id) {
return new WebPartDefinition(this, "getbyid('" + id + "')");
};
/**
* Gets a web part definition from the collection by storage id
*
* @param id The WebPart.ID of the SPWebPartDefinition to retrieve
*/
WebPartDefinitions.prototype.getByControlId = function (id) {
return new WebPartDefinition(this, "getByControlId('" + id + "')");
};
return WebPartDefinitions;
}(SharePointQueryableCollection));
var WebPartDefinition = /** @class */ (function (_super) {
__extends(WebPartDefinition, _super);
function WebPartDefinition() {
return _super !== null && _super.apply(this, arguments) || this;
}
Object.defineProperty(WebPartDefinition.prototype, "webpart", {
/**
* Gets the webpart information associated with this definition
*/
get: function () {
return new WebPart(this);
},
enumerable: true,
configurable: true
});
/**
* Saves changes to the Web Part made using other properties and methods on the SPWebPartDefinition object
*/
WebPartDefinition.prototype.saveChanges = function () {
return this.clone(WebPartDefinition, "SaveWebPartChanges").postCore();
};
/**
* Moves the Web Part to a different location on a Web Part Page
*
* @param zoneId The ID of the Web Part Zone to which to move the Web Part
* @param zoneIndex A Web Part zone index that specifies the position at which the Web Part is to be moved within the destination Web Part zone
*/
WebPartDefinition.prototype.moveTo = function (zoneId, zoneIndex) {
return this.clone(WebPartDefinition, "MoveWebPartTo(zoneID='" + zoneId + "', zoneIndex=" + zoneIndex + ")").postCore();
};
/**
* Closes the Web Part. If the Web Part is already closed, this method does nothing
*/
WebPartDefinition.prototype.close = function () {
return this.clone(WebPartDefinition, "CloseWebPart").postCore();
};
/**
* Opens the Web Part. If the Web Part is already closed, this method does nothing
*/
WebPartDefinition.prototype.open = function () {
return this.clone(WebPartDefinition, "OpenWebPart").postCore();
};
/**
* Removes a webpart from a page, all settings will be lost
*/
WebPartDefinition.prototype.delete = function () {
return this.clone(WebPartDefinition, "DeleteWebPart").postCore();
};
return WebPartDefinition;
}(SharePointQueryableInstance));
var WebPart = /** @class */ (function (_super) {
__extends(WebPart, _super);
function WebPart() {
return _super !== null && _super.apply(this, arguments) || this;
}
WebPart = __decorate([
defaultPath("webpart")
], WebPart);
return WebPart;
}(SharePointQueryableInstance));
/**
* Describes a collection of Folder objects
*
*/
var Folders = /** @class */ (function (_super) {
__extends(Folders, _super);
function Folders() {
return _super !== null && _super.apply(this, arguments) || this;
}
Folders_1 = Folders;
/**
* Gets a folder by folder name
*
*/
Folders.prototype.getByName = function (name) {
var f = new Folder(this);
f.concat("('" + name + "')");
return f;
};
/**
* Adds a new folder to the current folder (relative) or any folder (absolute)
*
* @param url The relative or absolute url where the new folder will be created. Urls starting with a forward slash are absolute.
* @returns The new Folder and the raw response.
*/
Folders.prototype.add = function (url) {
var _this = this;
return this.clone(Folders_1, "add('" + url + "')").postCore().then(function (response) {
return {
data: response,
folder: _this.getByName(url),
};
});
};
var Folders_1;
Folders = Folders_1 = __decorate([
defaultPath("folders")
], Folders);
return Folders;
}(SharePointQueryableCollection));
/**
* Describes a single Folder instance
*
*/
var Folder = /** @class */ (function (_super) {
__extends(Folder, _super);
function Folder() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.update = _this._update("SP.Folder", function (data) { return ({ data: data, folder: _this }); });
return _this;
}
Object.defineProperty(Folder.prototype, "contentTypeOrder", {
/**
* Specifies the sequence in which content types are displayed.
*
*/
get: function () {
return new SharePointQueryableCollection(this, "contentTypeOrder");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Folder.prototype, "files", {
/**
* Gets this folder's files
*
*/
get: function () {
return new Files(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Folder.prototype, "folders", {
/**
* Gets this folder's sub folders
*
*/
get: function () {
return new Folders(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Folder.prototype, "listItemAllFields", {
/**
* Gets this folder's list item field values
*
*/
get: function () {
return new SharePointQueryableInstance(this, "listItemAllFields");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Folder.prototype, "parentFolder", {
/**
* Gets the parent folder, if available
*
*/
get: function () {
return new Folder(this, "parentFolder");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Folder.prototype, "properties", {
/**
* Gets this folder's properties
*
*/
get: function () {
return new SharePointQueryableInstance(this, "properties");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Folder.prototype, "serverRelativeUrl", {
/**
* Gets this folder's server relative url
*
*/
get: function () {
return new SharePointQueryable(this, "serverRelativeUrl");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Folder.prototype, "uniqueContentTypeOrder", {
/**
* Gets a value that specifies the content type order.
*
*/
get: function () {
return new SharePointQueryableCollection(this, "uniqueContentTypeOrder");
},
enumerable: true,
configurable: true
});
/**
* Delete this folder
*
* @param eTag Value used in the IF-Match header, by default "*"
*/
Folder.prototype.delete = function (eTag) {
if (eTag === void 0) { eTag = "*"; }
return this.clone(Folder, null).postCore({
headers: {
"IF-Match": eTag,
"X-HTTP-Method": "DELETE",
},
});
};
/**
* Moves the folder to the Recycle Bin and returns the identifier of the new Recycle Bin item.
*/
Folder.prototype.recycle = function () {
return this.clone(Folder, "recycle").postCore();
};
/**
* Gets the associated list item for this folder, loading the default properties
*/
Folder.prototype.getItem = function () {
var selects = [];
for (var _i = 0; _i < arguments.length; _i++) {
selects[_i] = arguments[_i];
}
var q = this.listItemAllFields;
return q.select.apply(q, selects).get().then(function (d) {
return common.extend(new Item(odataUrlFrom(d)), d);
});
};
/**
* Moves a folder to destination path
*
* @param destUrl Absolute or relative URL of the destination path
*/
Folder.prototype.moveTo = function (destUrl) {
var _this = this;
return this.select("ServerRelativeUrl").get().then(function (_a) {
var srcUrl = _a.ServerRelativeUrl;
var client = new SPHttpClient();
var webBaseUrl = _this.toUrl().split("/_api")[0];
var hostUrl = webBaseUrl.replace("://", "___").split("/")[0].replace("___", "://");
var methodUrl = webBaseUrl + "/_api/SP.MoveCopyUtil.MoveFolder()";
return client.post(methodUrl, {
body: common.jsS({
destUrl: destUrl.indexOf("http") === 0 ? destUrl : "" + hostUrl + destUrl,
srcUrl: "" + hostUrl + srcUrl,
}),
}).then(function (r) { return r.json(); });
});
};
return Folder;
}(SharePointQueryableShareableFolder));
/**
* Describes a collection of content types
*
*/
var ContentTypes = /** @class */ (function (_super) {
__extends(ContentTypes, _super);
function ContentTypes() {
return _super !== null && _super.apply(this, arguments) || this;
}
ContentTypes_1 = ContentTypes;
/**
* Adds an existing contenttype to a content type collection
*
* @param contentTypeId in the following format, for example: 0x010102
*/
ContentTypes.prototype.addAvailableContentType = function (contentTypeId) {
var _this = this;
var postBody = common.jsS({
"contentTypeId": contentTypeId,
});
return this.clone(ContentTypes_1, "addAvailableContentType").postCore({ body: postBody }).then(function (data) {
return {
contentType: _this.getById(data.id),
data: data,
};
});
};
/**
* Gets a ContentType by content type id
*/
ContentTypes.prototype.getById = function (id) {
var ct = new ContentType(this);
ct.concat("('" + id + "')");
return ct;
};
/**
* Adds a new content type to the collection
*
* @param id The desired content type id for the new content type (also determines the parent content type)
* @param name The name of the content type
* @param description The description of the content type
* @param group The group in which to add the content type
* @param additionalSettings Any additional settings to provide when creating the content type
*
*/
ContentTypes.prototype.add = function (id, name, description, group, additionalSettings) {
var _this = this;
if (description === void 0) { description = ""; }
if (group === void 0) { group = "Custom Content Types"; }
if (additionalSettings === void 0) { additionalSettings = {}; }
var postBody = common.jsS(Object.assign(metadata("SP.ContentType"), {
"Description": description,
"Group": group,
"Id": { "StringValue": id },
"Name": name,
}, additionalSettings));
return this.postCore({ body: postBody }).then(function (data) {
return { contentType: _this.getById(data.id), data: data };
});
};
var ContentTypes_1;
ContentTypes = ContentTypes_1 = __decorate([
defaultPath("contenttypes")
], ContentTypes);
return ContentTypes;
}(SharePointQueryableCollection));
/**
* Describes a single ContentType instance
*
*/
var ContentType = /** @class */ (function (_super) {
__extends(ContentType, _super);
function ContentType() {
var _this = _super !== null && _super.apply(this, arguments) || this;
/**
* Delete this content type
*/
_this.delete = _this._delete;
return _this;
}
Object.defineProperty(ContentType.prototype, "fieldLinks", {
/**
* Gets the column (also known as field) references in the content type.
*/
get: function () {
return new FieldLinks(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(ContentType.prototype, "fields", {
/**
* Gets a value that specifies the collection of fields for the content type.
*/
get: function () {
return new SharePointQueryableCollection(this, "fields");
},
enumerable: true,
configurable: true
});
Object.defineProperty(ContentType.prototype, "parent", {
/**
* Gets the parent content type of the content type.
*/
get: function () {
return new ContentType(this, "parent");
},
enumerable: true,
configurable: true
});
Object.defineProperty(ContentType.prototype, "workflowAssociations", {
/**
* Gets a value that specifies the collection of workflow associations for the content type.
*/
get: function () {
return new SharePointQueryableCollection(this, "workflowAssociations");
},
enumerable: true,
configurable: true
});
return ContentType;
}(SharePointQueryableInstance));
/**
* Represents a collection of field link instances
*/
var FieldLinks = /** @class */ (function (_super) {
__extends(FieldLinks, _super);
function FieldLinks() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Gets a FieldLink by GUID id
*
* @param id The GUID id of the field link
*/
FieldLinks.prototype.getById = function (id) {
var fl = new FieldLink(this);
fl.concat("(guid'" + id + "')");
return fl;
};
FieldLinks = __decorate([
defaultPath("fieldlinks")
], FieldLinks);
return FieldLinks;
}(SharePointQueryableCollection));
/**
* Represents a field link instance
*/
var FieldLink = /** @class */ (function (_super) {
__extends(FieldLink, _super);
function FieldLink() {
return _super !== null && _super.apply(this, arguments) || this;
}
return FieldLink;
}(SharePointQueryableInstance));
/**
* Describes a collection of Item objects
*
*/
var AttachmentFiles = /** @class */ (function (_super) {
__extends(AttachmentFiles, _super);
function AttachmentFiles() {
return _super !== null && _super.apply(this, arguments) || this;
}
AttachmentFiles_1 = AttachmentFiles;
/**
* Gets a Attachment File by filename
*
* @param name The name of the file, including extension.
*/
AttachmentFiles.prototype.getByName = function (name) {
var f = new AttachmentFile(this);
f.concat("('" + name + "')");
return f;
};
/**
* Adds a new attachment to the collection. Not supported for batching.
*
* @param name The name of the file, including extension.
* @param content The Base64 file content.
*/
AttachmentFiles.prototype.add = function (name, content) {
var _this = this;
return this.clone(AttachmentFiles_1, "add(FileName='" + name + "')", false).postCore({
body: content,
}).then(function (response) {
return {
data: response,
file: _this.getByName(name),
};
});
};
/**
* Adds multiple new attachment to the collection. Not supported for batching.
*
* @param files The collection of files to add
*/
AttachmentFiles.prototype.addMultiple = function (files) {
var _this = this;
// add the files in series so we don't get update conflicts
return files.reduce(function (chain, file) { return chain.then(function () { return _this.clone(AttachmentFiles_1, "add(FileName='" + file.name + "')", false).postCore({
body: file.content,
}); }); }, Promise.resolve());
};
/**
* Delete multiple attachments from the collection. Not supported for batching.
*
* @param files The collection of files to delete
*/
AttachmentFiles.prototype.deleteMultiple = function () {
var _this = this;
var files = [];
for (var _i = 0; _i < arguments.length; _i++) {
files[_i] = arguments[_i];
}
return files.reduce(function (chain, file) { return chain.then(function () { return _this.getByName(file).delete(); }); }, Promise.resolve());
};
/**
* Delete multiple attachments from the collection and send to recycle bin. Not supported for batching.
*
* @param files The collection of files to be deleted and sent to recycle bin
*/
AttachmentFiles.prototype.recycleMultiple = function () {
var _this = this;
var files = [];
for (var _i = 0; _i < arguments.length; _i++) {
files[_i] = arguments[_i];
}
return files.reduce(function (chain, file) { return chain.then(function () { return _this.getByName(file).recycle(); }); }, Promise.resolve());
};
var AttachmentFiles_1;
AttachmentFiles = AttachmentFiles_1 = __decorate([
defaultPath("AttachmentFiles")
], AttachmentFiles);
return AttachmentFiles;
}(SharePointQueryableCollection));
/**
* Describes a single attachment file instance
*
*/
var AttachmentFile = /** @class */ (function (_super) {
__extends(AttachmentFile, _super);
function AttachmentFile() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.delete = _this._deleteWithETag;
return _this;
}
/**
* Gets the contents of the file as text
*
*/
AttachmentFile.prototype.getText = function () {
return this.getParsed(new odata.TextParser());
};
/**
* Gets the contents of the file as a blob, does not work in Node.js
*
*/
AttachmentFile.prototype.getBlob = function () {
return this.getParsed(new odata.BlobParser());
};
/**
* Gets the contents of a file as an ArrayBuffer, works in Node.js
*/
AttachmentFile.prototype.getBuffer = function () {
return this.getParsed(new odata.BufferParser());
};
/**
* Gets the contents of a file as an ArrayBuffer, works in Node.js
*/
AttachmentFile.prototype.getJSON = function () {
return this.getParsed(new odata.JSONParser());
};
/**
* Sets the content of a file. Not supported for batching
*
* @param content The value to set for the file contents
*/
AttachmentFile.prototype.setContent = function (content) {
var _this = this;
return this.clone(AttachmentFile, "$value", false).postCore({
body: content,
headers: {
"X-HTTP-Method": "PUT",
},
}).then(function (_) { return new AttachmentFile(_this); });
};
/**
* Delete this attachment file and send it to recycle bin
*
* @param eTag Value used in the IF-Match header, by default "*"
*/
AttachmentFile.prototype.recycle = function (eTag) {
if (eTag === void 0) { eTag = "*"; }
return this.clone(AttachmentFile, "recycleObject").postCore({
headers: {
"IF-Match": eTag,
"X-HTTP-Method": "DELETE",
},
});
};
// /**
// * Delete this attachment file
// *
// * @param eTag Value used in the IF-Match header, by default "*"
// */
// public delete(eTag = "*"): Promise<void> {
// return this.postCore({
// headers: {
// "IF-Match": eTag,
// "X-HTTP-Method": "DELETE",
// },
// });
// }
AttachmentFile.prototype.getParsed = function (parser) {
return this.clone(AttachmentFile, "$value", false).get(parser);
};
return AttachmentFile;
}(SharePointQueryableInstance));
/**
* Describes the views available in the current context
*
*/
var Views = /** @class */ (function (_super) {
__extends(Views, _super);
function Views() {
return _super !== null && _super.apply(this, arguments) || this;
}
Views_1 = Views;
/**
* Gets a view by guid id
*
* @param id The GUID id of the view
*/
Views.prototype.getById = function (id) {
var v = new View(this);
v.concat("('" + id + "')");
return v;
};
/**
* Gets a view by title (case-sensitive)
*
* @param title The case-sensitive title of the view
*/
Views.prototype.getByTitle = function (title) {
return new View(this, "getByTitle('" + title + "')");
};
/**
* Adds a new view to the collection
*
* @param title The new views's title
* @param personalView True if this is a personal view, otherwise false, default = false
* @param additionalSettings Will be passed as part of the view creation body
*/
Views.prototype.add = function (title, personalView, additionalSettings) {
var _this = this;
if (personalView === void 0) { personalView = false; }
if (additionalSettings === void 0) { additionalSettings = {}; }
var postBody = common.jsS(Object.assign(metadata("SP.View"), {
"PersonalView": personalView,
"Title": title,
}, additionalSettings));
return this.clone(Views_1, null).postCore({ body: postBody }).then(function (data) {
return {
data: data,
view: _this.getById(data.Id),
};
});
};
var Views_1;
Views = Views_1 = __decorate([
defaultPath("views")
], Views);
return Views;
}(SharePointQueryableCollection));
/**
* Describes a single View instance
*
*/
var View = /** @class */ (function (_super) {
__extends(View, _super);
function View() {
var _this = _super !== null && _super.apply(this, arguments) || this;
/**
* Updates this view intance with the supplied properties
*
* @param properties A plain object hash of values to update for the view
*/
_this.update = _this._update("SP.View", function (data) { return ({ data: data, view: _this }); });
/**
* Delete this view
*
*/
_this.delete = _this._delete;
return _this;
}
Object.defineProperty(View.prototype, "fields", {
get: function () {
return new ViewFields(this);
},
enumerable: true,
configurable: true
});
/**
* Returns the list view as HTML.
*
*/
View.prototype.renderAsHtml = function () {
return this.clone(SharePointQueryable, "renderashtml").get();
};
return View;
}(SharePointQueryableInstance));
var ViewFields = /** @class */ (function (_super) {
__extends(ViewFields, _super);
function ViewFields() {
return _super !== null && _super.apply(this, arguments) || this;
}
ViewFields_1 = ViewFields;
/**
* Gets a value that specifies the XML schema that represents the collection.
*/
ViewFields.prototype.getSchemaXml = function () {
return this.clone(SharePointQueryable, "schemaxml").get();
};
/**
* Adds the field with the specified field internal name or display name to the collection.
*
* @param fieldTitleOrInternalName The case-sensitive internal name or display name of the field to add.
*/
ViewFields.prototype.add = function (fieldTitleOrInternalName) {
return this.clone(ViewFields_1, "addviewfield('" + fieldTitleOrInternalName + "')").postCore();
};
/**
* Moves the field with the specified field internal name to the specified position in the collection.
*
* @param fieldInternalName The case-sensitive internal name of the field to move.
* @param index The zero-based index of the new position for the field.
*/
ViewFields.prototype.move = function (fieldInternalName, index) {
return this.clone(ViewFields_1, "moveviewfieldto").postCore({
body: common.jsS({ "field": fieldInternalName, "index": index }),
});
};
/**
* Removes all the fields from the collection.
*/
ViewFields.prototype.removeAll = function () {
return this.clone(ViewFields_1, "removeallviewfields").postCore();
};
/**
* Removes the field with the specified field internal name from the collection.
*
* @param fieldInternalName The case-sensitive internal name of the field to remove from the view.
*/
ViewFields.prototype.remove = function (fieldInternalName) {
return this.clone(ViewFields_1, "removeviewfield('" + fieldInternalName + "')").postCore();
};
var ViewFields_1;
ViewFields = ViewFields_1 = __decorate([
defaultPath("viewfields")
], ViewFields);
return ViewFields;
}(SharePointQueryableCollection));
/**
* Describes a collection of Field objects
*
*/
var Fields = /** @class */ (function (_super) {
__extends(Fields, _super);
function Fields() {
return _super !== null && _super.apply(this, arguments) || this;
}
Fields_1 = Fields;
/**
* Gets a field from the collection by id
*
* @param id The Id of the list
*/
Fields.prototype.getById = function (id) {
var f = new Field(this);
f.concat("('" + id + "')");
return f;
};
/**
* Gets a field from the collection by title
*
* @param title The case-sensitive title of the field
*/
Fields.prototype.getByTitle = function (title) {
return new Field(this, "getByTitle('" + title + "')");
};
/**
* Gets a field from the collection by using internal name or title
*
* @param name The case-sensitive internal name or title of the field
*/
Fields.prototype.getByInternalNameOrTitle = function (name) {
return new Field(this, "getByInternalNameOrTitle('" + name + "')");
};
/**
* Creates a field based on the specified schema
*/
Fields.prototype.createFieldAsXml = function (xml) {
var _this = this;
var info;
if (typeof xml === "string") {
info = { SchemaXml: xml };
}
else {
info = xml;
}
var postBody = common.jsS({
"parameters": common.extend(metadata("SP.XmlSchemaFieldCreationInformation"), info),
});
return this.clone(Fields_1, "createfieldasxml").postCore({ body: postBody }).then(function (data) {
return {
data: data,
field: _this.getById(data.Id),
};
});
};
/**
* Adds a new field to the collection
*
* @param title The new field's title
* @param fieldType The new field's type (ex: SP.FieldText)
* @param properties Differ by type of field being created (see: https://msdn.microsoft.com/en-us/library/office/dn600182.aspx)
*/
Fields.prototype.add = function (title, fieldType, properties) {
var _this = this;
var postBody = common.jsS(Object.assign(metadata(fieldType), {
"Title": title,
}, properties));
return this.clone(Fields_1, null).postCore({ body: postBody }).then(function (data) {
return {
data: data,
field: _this.getById(data.Id),
};
});
};
/**
* Adds a new SP.FieldText to the collection
*
* @param title The field title
* @param maxLength The maximum number of characters allowed in the value of the field.
* @param properties Differ by type of field being created (see: https://msdn.microsoft.com/en-us/library/office/dn600182.aspx)
*/
Fields.prototype.addText = function (title, maxLength, properties) {
if (maxLength === void 0) { maxLength = 255; }
var props = {
FieldTypeKind: 2,
MaxLength: maxLength,
};
return this.add(title, "SP.FieldText", common.extend(props, properties));
};
/**
* Adds a new SP.FieldCalculated to the collection
*
* @param title The field title.
* @param formula The formula for the field.
* @param dateFormat The date and time format that is displayed in the field.
* @param outputType Specifies the output format for the field. Represents a FieldType value.
* @param properties Differ by type of field being created (see: https://msdn.microsoft.com/en-us/library/office/dn600182.aspx)
*/
Fields.prototype.addCalculated = function (title, formula, dateFormat, outputType, properties) {
if (outputType === void 0) { outputType = exports.FieldTypes.Text; }
var props = {
DateFormat: dateFormat,
FieldTypeKind: 17,
Formula: formula,
OutputType: outputType,
};
return this.add(title, "SP.FieldCalculated", common.extend(props, properties));
};
/**
* Adds a new SP.FieldDateTime to the collection
*
* @param title The field title
* @param displayFormat The format of the date and time that is displayed in the field.
* @param calendarType Specifies the calendar type of the field.
* @param properties Differ by type of field being created (see: https://msdn.microsoft.com/en-us/library/office/dn600182.aspx)
*/
Fields.prototype.addDateTime = function (title, displayFormat, calendarType, friendlyDisplayFormat, properties) {
if (displayFormat === void 0) { displayFormat = exports.DateTimeFieldFormatType.DateOnly; }
if (calendarType === void 0) { calendarType = exports.CalendarType.Gregorian; }
if (friendlyDisplayFormat === void 0) { friendlyDisplayFormat = 0; }
var props = {
DateTimeCalendarType: calendarType,
DisplayFormat: displayFormat,
FieldTypeKind: 4,
FriendlyDisplayFormat: friendlyDisplayFormat,
};
return this.add(title, "SP.FieldDateTime", common.extend(props, properties));
};
/**
* Adds a new SP.FieldNumber to the collection
*
* @param title The field title
* @param minValue The field's minimum value
* @param maxValue The field's maximum value
* @param properties Differ by type of field being created (see: https://msdn.microsoft.com/en-us/library/office/dn600182.aspx)
*/
Fields.prototype.addNumber = function (title, minValue, maxValue, properties) {
var props = { FieldTypeKind: 9 };
if (minValue !== undefined) {
props = common.extend({ MinimumValue: minValue }, props);
}
if (maxValue !== undefined) {
props = common.extend({ MaximumValue: maxValue }, props);
}
return this.add(title, "SP.FieldNumber", common.extend(props, properties));
};
/**
* Adds a new SP.FieldCurrency to the collection
*
* @param title The field title
* @param minValue The field's minimum value
* @param maxValue The field's maximum value
* @param currencyLocalId Specifies the language code identifier (LCID) used to format the value of the field
* @param properties Differ by type of field being created (see: https://msdn.microsoft.com/en-us/library/office/dn600182.aspx)
*/
Fields.prototype.addCurrency = function (title, minValue, maxValue, currencyLocalId, properties) {
if (currencyLocalId === void 0) { currencyLocalId = 1033; }
var props = {
CurrencyLocaleId: currencyLocalId,
FieldTypeKind: 10,
};
if (minValue !== undefined) {
props = common.extend({ MinimumValue: minValue }, props);
}
if (maxValue !== undefined) {
props = common.extend({ MaximumValue: maxValue }, props);
}
return this.add(title, "SP.FieldCurrency", common.extend(props, properties));
};
/**
* Adds a new SP.FieldMultiLineText to the collection
*
* @param title The field title
* @param numberOfLines Specifies the number of lines of text to display for the field.
* @param richText Specifies whether the field supports rich formatting.
* @param restrictedMode Specifies whether the field supports a subset of rich formatting.
* @param appendOnly Specifies whether all changes to the value of the field are displayed in list forms.
* @param allowHyperlink Specifies whether a hyperlink is allowed as a value of the field.
* @param properties Differ by type of field being created (see: https://msdn.microsoft.com/en-us/library/office/dn600182.aspx)
*
*/
Fields.prototype.addMultilineText = function (title, numberOfLines, richText, restrictedMode, appendOnly, allowHyperlink, properties) {
if (numberOfLines === void 0) { numberOfLines = 6; }
if (richText === void 0) { richText = true; }
if (restrictedMode === void 0) { restrictedMode = false; }
if (appendOnly === void 0) { appendOnly = false; }
if (allowHyperlink === void 0) { allowHyperlink = true; }
var props = {
AllowHyperlink: allowHyperlink,
AppendOnly: appendOnly,
FieldTypeKind: 3,
NumberOfLines: numberOfLines,
RestrictedMode: restrictedMode,
RichText: richText,
};
return this.add(title, "SP.FieldMultiLineText", common.extend(props, properties));
};
/**
* Adds a new SP.FieldUrl to the collection
*
* @param title The field title
*/
Fields.prototype.addUrl = function (title, displayFormat, properties) {
if (displayFormat === void 0) { displayFormat = exports.UrlFieldFormatType.Hyperlink; }
var props = {
DisplayFormat: displayFormat,
FieldTypeKind: 11,
};
return this.add(title, "SP.FieldUrl", common.extend(props, properties));
};
/** Adds a user field to the colleciton
*
* @param title The new field's title
* @param selectionMode The selection mode of the field
* @param selectionGroup Value that specifies the identifier of the SharePoint group whose members can be selected as values of the field
* @param properties
*/
Fields.prototype.addUser = function (title, selectionMode, properties) {
var props = {
FieldTypeKind: 20,
SelectionMode: selectionMode,
};
return this.add(title, "SP.FieldUser", common.extend(props, properties));
};
/**
* Adds a SP.FieldLookup to the collection
*
* @param title The new field's title
* @param lookupListId The guid id of the list where the source of the lookup is found
* @param lookupFieldName The internal name of the field in the source list
* @param properties Set of additional properties to set on the new field
*/
Fields.prototype.addLookup = function (title, lookupListId, lookupFieldName, properties) {
var _this = this;
var props = common.extend({
FieldTypeKind: 7,
LookupFieldName: lookupFieldName,
LookupListId: lookupListId,
Title: title,
}, properties);
var postBody = common.jsS({
"parameters": common.extend(metadata("SP.FieldCreationInformation"), props),
});
return this.clone(Fields_1, "addfield").postCore({ body: postBody }).then(function (data) {
return {
data: data,
field: _this.getById(data.Id),
};
});
};
/**
* Adds a new SP.FieldChoice to the collection
*
* @param title The field title.
* @param choices The choices for the field.
* @param format The display format of the available options for the field.
* @param fillIn Specifies whether the field allows fill-in values.
* @param properties Differ by type of field being created (see: https://msdn.microsoft.com/en-us/library/office/dn600182.aspx)
*/
Fields.prototype.addChoice = function (title, choices, format, fillIn, properties) {
if (format === void 0) { format = exports.ChoiceFieldFormatType.Dropdown; }
var props = {
Choices: {
results: choices,
},
EditFormat: format,
FieldTypeKind: 6,
FillInChoice: fillIn,
};
return this.add(title, "SP.FieldChoice", common.extend(props, properties));
};
/**
* Adds a new SP.FieldMultiChoice to the collection
*
* @param title The field title.
* @param choices The choices for the field.
* @param fillIn Specifies whether the field allows fill-in values.
* @param properties Differ by type of field being created (see: https://msdn.microsoft.com/en-us/library/office/dn600182.aspx)
*/
Fields.prototype.addMultiChoice = function (title, choices, fillIn, properties) {
var props = {
Choices: {
results: choices,
},
FieldTypeKind: 15,
FillInChoice: fillIn,
};
return this.add(title, "SP.FieldMultiChoice", common.extend(props, properties));
};
/**
* Adds a new SP.FieldBoolean to the collection
*
* @param title The field title.
* @param properties Differ by type of field being created (see: https://msdn.microsoft.com/en-us/library/office/dn600182.aspx)
*/
Fields.prototype.addBoolean = function (title, properties) {
var props = {
FieldTypeKind: 8,
};
return this.add(title, "SP.Field", common.extend(props, properties));
};
/**
* Creates a secondary (dependent) lookup field, based on the Id of the primary lookup field.
*
* @param displayName The display name of the new field.
* @param primaryLookupFieldId The guid of the primary Lookup Field.
* @param showField Which field to show from the lookup list.
*/
Fields.prototype.addDependentLookupField = function (displayName, primaryLookupFieldId, showField) {
var _this = this;
return this.clone(Fields_1, "adddependentlookupfield(displayName='" + displayName + "', primarylookupfieldid='" + primaryLookupFieldId + "', showfield='" + showField + "')")
.postCore()
.then(function (data) {
return {
data: data,
field: _this.getById(data.Id),
};
});
};
var Fields_1;
Fields = Fields_1 = __decorate([
defaultPath("fields")
], Fields);
return Fields;
}(SharePointQueryableCollection));
/**
* Describes a single of Field instance
*
*/
var Field = /** @class */ (function (_super) {
__extends(Field, _super);
function Field() {
var _this = _super !== null && _super.apply(this, arguments) || this;
/**
* Delete this fields
*
*/
_this.delete = _this._delete;
return _this;
}
/**
* Updates this field intance with the supplied properties
*
* @param properties A plain object hash of values to update for the list
* @param fieldType The type value, required to update child field type properties
*/
Field.prototype.update = function (properties, fieldType) {
var _this = this;
if (fieldType === void 0) { fieldType = "SP.Field"; }
var postBody = common.jsS(common.extend(metadata(fieldType), properties));
return this.postCore({
body: postBody,
headers: {
"X-HTTP-Method": "MERGE",
},
}).then(function (data) {
return {
data: data,
field: _this,
};
});
};
/**
* Sets the value of the ShowInDisplayForm property for this field.
*/
Field.prototype.setShowInDisplayForm = function (show) {
return this.clone(Field, "setshowindisplayform(" + show + ")").postCore();
};
/**
* Sets the value of the ShowInEditForm property for this field.
*/
Field.prototype.setShowInEditForm = function (show) {
return this.clone(Field, "setshowineditform(" + show + ")").postCore();
};
/**
* Sets the value of the ShowInNewForm property for this field.
*/
Field.prototype.setShowInNewForm = function (show) {
return this.clone(Field, "setshowinnewform(" + show + ")").postCore();
};
return Field;
}(SharePointQueryableInstance));
/**
* Describes a collection of Field objects
*
*/
var Forms = /** @class */ (function (_super) {
__extends(Forms, _super);
function Forms() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Gets a form by id
*
* @param id The guid id of the item to retrieve
*/
Forms.prototype.getById = function (id) {
var i = new Form(this);
i.concat("('" + id + "')");
return i;
};
Forms = __decorate([
defaultPath("forms")
], Forms);
return Forms;
}(SharePointQueryableCollection));
/**
* Describes a single of Form instance
*
*/
var Form = /** @class */ (function (_super) {
__extends(Form, _super);
function Form() {
return _super !== null && _super.apply(this, arguments) || this;
}
return Form;
}(SharePointQueryableInstance));
/**
* Describes a collection of webhook subscriptions
*
*/
var Subscriptions = /** @class */ (function (_super) {
__extends(Subscriptions, _super);
function Subscriptions() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Returns all the webhook subscriptions or the specified webhook subscription
*
* @param subscriptionId The id of a specific webhook subscription to retrieve, omit to retrieve all the webhook subscriptions
*/
Subscriptions.prototype.getById = function (subscriptionId) {
var s = new Subscription(this);
s.concat("('" + subscriptionId + "')");
return s;
};
/**
* Creates a new webhook subscription
*
* @param notificationUrl The url to receive the notifications
* @param expirationDate The date and time to expire the subscription in the form YYYY-MM-ddTHH:mm:ss+00:00 (maximum of 6 months)
* @param clientState A client specific string (defaults to pnp-js-core-subscription when omitted)
*/
Subscriptions.prototype.add = function (notificationUrl, expirationDate, clientState) {
var _this = this;
var postBody = common.jsS({
"clientState": clientState || "pnp-js-core-subscription",
"expirationDateTime": expirationDate,
"notificationUrl": notificationUrl,
"resource": this.toUrl(),
});
return this.postCore({ body: postBody, headers: { "Content-Type": "application/json" } }).then(function (result) {
return { data: result, subscription: _this.getById(result.id) };
});
};
Subscriptions = __decorate([
defaultPath("subscriptions")
], Subscriptions);
return Subscriptions;
}(SharePointQueryableCollection));
/**
* Describes a single webhook subscription instance
*
*/
var Subscription = /** @class */ (function (_super) {
__extends(Subscription, _super);
function Subscription() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Renews this webhook subscription
*
* @param expirationDate The date and time to expire the subscription in the form YYYY-MM-ddTHH:mm:ss+00:00 (maximum of 6 months)
*/
Subscription.prototype.update = function (expirationDate) {
var _this = this;
var postBody = common.jsS({
"expirationDateTime": expirationDate,
});
return this.patchCore({ body: postBody, headers: { "Content-Type": "application/json" } }).then(function (data) {
return { data: data, subscription: _this };
});
};
/**
* Removes this webhook subscription
*
*/
Subscription.prototype.delete = function () {
return _super.prototype.deleteCore.call(this);
};
return Subscription;
}(SharePointQueryableInstance));
/**
* Describes a collection of user custom actions
*
*/
var UserCustomActions = /** @class */ (function (_super) {
__extends(UserCustomActions, _super);
function UserCustomActions() {
return _super !== null && _super.apply(this, arguments) || this;
}
UserCustomActions_1 = UserCustomActions;
/**
* Returns the user custom action with the specified id
*
* @param id The GUID id of the user custom action to retrieve
*/
UserCustomActions.prototype.getById = function (id) {
var uca = new UserCustomAction(this);
uca.concat("('" + id + "')");
return uca;
};
/**
* Creates a user custom action
*
* @param properties The information object of property names and values which define the new user custom action
*
*/
UserCustomActions.prototype.add = function (properties) {
var _this = this;
var postBody = common.jsS(common.extend({ __metadata: { "type": "SP.UserCustomAction" } }, properties));
return this.postCore({ body: postBody }).then(function (data) {
return {
action: _this.getById(data.Id),
data: data,
};
});
};
/**
* Deletes all user custom actions in the collection
*
*/
UserCustomActions.prototype.clear = function () {
return this.clone(UserCustomActions_1, "clear").postCore();
};
var UserCustomActions_1;
UserCustomActions = UserCustomActions_1 = __decorate([
defaultPath("usercustomactions")
], UserCustomActions);
return UserCustomActions;
}(SharePointQueryableCollection));
/**
* Describes a single user custom action
*
*/
var UserCustomAction = /** @class */ (function (_super) {
__extends(UserCustomAction, _super);
function UserCustomAction() {
var _this = _super !== null && _super.apply(this, arguments) || this;
/**
* Updates this user custom action with the supplied properties
*
* @param properties An information object of property names and values to update for this user custom action
*/
_this.update = _this._update("SP.UserCustomAction", function (data) { return ({ data: data, action: _this }); });
return _this;
}
/**
* Removes this user custom action
*
*/
UserCustomAction.prototype.delete = function () {
return _super.prototype.deleteCore.call(this);
};
return UserCustomAction;
}(SharePointQueryableInstance));
/**
* Describes a collection of List objects
*
*/
var Lists = /** @class */ (function (_super) {
__extends(Lists, _super);
function Lists() {
return _super !== null && _super.apply(this, arguments) || this;
}
Lists_1 = Lists;
/**
* Gets a list from the collection by guid id
*
* @param id The Id of the list (GUID)
*/
Lists.prototype.getById = function (id) {
var list = new List(this);
list.concat("('" + id + "')");
return list;
};
/**
* Gets a list from the collection by title
*
* @param title The title of the list
*/
Lists.prototype.getByTitle = function (title) {
return new List(this, "getByTitle('" + title + "')");
};
/**
* Adds a new list to the collection
*
* @param title The new list's title
* @param description The new list's description
* @param template The list template value
* @param enableContentTypes If true content types will be allowed and enabled, otherwise they will be disallowed and not enabled
* @param additionalSettings Will be passed as part of the list creation body
*/
Lists.prototype.add = function (title, description, template, enableContentTypes, additionalSettings) {
var _this = this;
if (description === void 0) { description = ""; }
if (template === void 0) { template = 100; }
if (enableContentTypes === void 0) { enableContentTypes = false; }
if (additionalSettings === void 0) { additionalSettings = {}; }
var addSettings = common.extend({
"AllowContentTypes": enableContentTypes,
"BaseTemplate": template,
"ContentTypesEnabled": enableContentTypes,
"Description": description,
"Title": title,
"__metadata": { "type": "SP.List" },
}, additionalSettings);
return this.postCore({ body: common.jsS(addSettings) }).then(function (data) {
return { data: data, list: _this.getByTitle(addSettings.Title) };
});
};
/**
* Ensures that the specified list exists in the collection (note: this method not supported for batching)
*
* @param title The new list's title
* @param description The new list's description
* @param template The list template value
* @param enableContentTypes If true content types will be allowed and enabled, otherwise they will be disallowed and not enabled
* @param additionalSettings Will be passed as part of the list creation body or used to update an existing list
*/
Lists.prototype.ensure = function (title, description, template, enableContentTypes, additionalSettings) {
var _this = this;
if (description === void 0) { description = ""; }
if (template === void 0) { template = 100; }
if (enableContentTypes === void 0) { enableContentTypes = false; }
if (additionalSettings === void 0) { additionalSettings = {}; }
if (this.hasBatch) {
throw Error("The ensure list method is not supported for use in a batch.");
}
return new Promise(function (resolve, reject) {
var addOrUpdateSettings = common.extend(additionalSettings, { Title: title, Description: description, ContentTypesEnabled: enableContentTypes }, true);
var list = _this.getByTitle(addOrUpdateSettings.Title);
list.get().then(function (_) {
list.update(addOrUpdateSettings).then(function (d) {
resolve({ created: false, data: d, list: _this.getByTitle(addOrUpdateSettings.Title) });
}).catch(function (e) { return reject(e); });
}).catch(function (_) {
_this.add(title, description, template, enableContentTypes, addOrUpdateSettings).then(function (r) {
resolve({ created: true, data: r.data, list: _this.getByTitle(addOrUpdateSettings.Title) });
}).catch(function (e) { return reject(e); });
});
});
};
/**
* Gets a list that is the default asset location for images or other files, which the users upload to their wiki pages.
*/
Lists.prototype.ensureSiteAssetsLibrary = function () {
return this.clone(Lists_1, "ensuresiteassetslibrary").postCore().then(function (json) {
return new List(odataUrlFrom(json));
});
};
/**
* Gets a list that is the default location for wiki pages.
*/
Lists.prototype.ensureSitePagesLibrary = function () {
return this.clone(Lists_1, "ensuresitepageslibrary").postCore().then(function (json) {
return new List(odataUrlFrom(json));
});
};
var Lists_1;
Lists = Lists_1 = __decorate([
defaultPath("lists")
], Lists);
return Lists;
}(SharePointQueryableCollection));
/**
* Describes a single List instance
*
*/
var List = /** @class */ (function (_super) {
__extends(List, _super);
function List() {
return _super !== null && _super.apply(this, arguments) || this;
}
Object.defineProperty(List.prototype, "contentTypes", {
/**
* Gets the content types in this list
*
*/
get: function () {
return new ContentTypes(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(List.prototype, "items", {
/**
* Gets the items in this list
*
*/
get: function () {
return new Items(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(List.prototype, "views", {
/**
* Gets the views in this list
*
*/
get: function () {
return new Views(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(List.prototype, "fields", {
/**
* Gets the fields in this list
*
*/
get: function () {
return new Fields(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(List.prototype, "forms", {
/**
* Gets the forms in this list
*
*/
get: function () {
return new Forms(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(List.prototype, "defaultView", {
/**
* Gets the default view of this list
*
*/
get: function () {
return new View(this, "DefaultView");
},
enumerable: true,
configurable: true
});
Object.defineProperty(List.prototype, "userCustomActions", {
/**
* Get all custom actions on a site collection
*
*/
get: function () {
return new UserCustomActions(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(List.prototype, "effectiveBasePermissions", {
/**
* Gets the effective base permissions of this list
*
*/
get: function () {
return new SharePointQueryable(this, "EffectiveBasePermissions");
},
enumerable: true,
configurable: true
});
Object.defineProperty(List.prototype, "eventReceivers", {
/**
* Gets the event receivers attached to this list
*
*/
get: function () {
return new SharePointQueryableCollection(this, "EventReceivers");
},
enumerable: true,
configurable: true
});
Object.defineProperty(List.prototype, "relatedFields", {
/**
* Gets the related fields of this list
*
*/
get: function () {
return new SharePointQueryable(this, "getRelatedFields");
},
enumerable: true,
configurable: true
});
Object.defineProperty(List.prototype, "informationRightsManagementSettings", {
/**
* Gets the IRM settings for this list
*
*/
get: function () {
return new SharePointQueryable(this, "InformationRightsManagementSettings");
},
enumerable: true,
configurable: true
});
Object.defineProperty(List.prototype, "subscriptions", {
/**
* Gets the webhook subscriptions of this list
*
*/
get: function () {
return new Subscriptions(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(List.prototype, "rootFolder", {
/**
* The root folder of the list
*/
get: function () {
return new Folder(this, "rootFolder");
},
enumerable: true,
configurable: true
});
/**
* Gets a view by view guid id
*
*/
List.prototype.getView = function (viewId) {
return new View(this, "getView('" + viewId + "')");
};
/**
* Updates this list intance with the supplied properties
*
* @param properties A plain object hash of values to update for the list
* @param eTag Value used in the IF-Match header, by default "*"
*/
/* tslint:disable no-string-literal */
List.prototype.update = function (properties, eTag) {
var _this = this;
if (eTag === void 0) { eTag = "*"; }
var postBody = common.jsS(common.extend({
"__metadata": { "type": "SP.List" },
}, properties));
return this.postCore({
body: postBody,
headers: {
"IF-Match": eTag,
"X-HTTP-Method": "MERGE",
},
}).then(function (data) {
var retList = _this;
if (common.hOP(properties, "Title")) {
retList = _this.getParent(List, _this.parentUrl, "getByTitle('" + properties["Title"] + "')");
}
return {
data: data,
list: retList,
};
});
};
/* tslint:enable */
/**
* Delete this list
*
* @param eTag Value used in the IF-Match header, by default "*"
*/
List.prototype.delete = function (eTag) {
if (eTag === void 0) { eTag = "*"; }
return this.postCore({
headers: {
"IF-Match": eTag,
"X-HTTP-Method": "DELETE",
},
});
};
/**
* Returns the collection of changes from the change log that have occurred within the list, based on the specified query.
*/
List.prototype.getChanges = function (query) {
return this.clone(List, "getchanges").postCore({
body: common.jsS({ "query": common.extend({ "__metadata": { "type": "SP.ChangeQuery" } }, query) }),
});
};
/**
* Returns a collection of items from the list based on the specified query.
*
* @param CamlQuery The Query schema of Collaborative Application Markup
* Language (CAML) is used in various ways within the context of Microsoft SharePoint Foundation
* to define queries against list data.
* see:
*
* https://msdn.microsoft.com/en-us/library/office/ms467521.aspx
*
* @param expands A URI with a $expand System Query Option indicates that Entries associated with
* the Entry or Collection of Entries identified by the Resource Path
* section of the URI must be represented inline (i.e. eagerly loaded).
* see:
*
* https://msdn.microsoft.com/en-us/library/office/fp142385.aspx
*
* http://www.odata.org/documentation/odata-version-2-0/uri-conventions/#ExpandSystemQueryOption
*/
List.prototype.getItemsByCAMLQuery = function (query) {
var expands = [];
for (var _i = 1; _i < arguments.length; _i++) {
expands[_i - 1] = arguments[_i];
}
var q = this.clone(List, "getitems");
return q.expand.apply(q, expands).postCore({
body: common.jsS({ "query": common.extend({ "__metadata": { "type": "SP.CamlQuery" } }, query) }),
});
};
/**
* See: https://msdn.microsoft.com/en-us/library/office/dn292554.aspx
*/
List.prototype.getListItemChangesSinceToken = function (query) {
return this.clone(List, "getlistitemchangessincetoken").postCore({
body: common.jsS({ "query": common.extend({ "__metadata": { "type": "SP.ChangeLogItemQuery" } }, query) }),
}, { parse: function (r) { return r.text(); } });
};
/**
* Moves the list to the Recycle Bin and returns the identifier of the new Recycle Bin item.
*/
List.prototype.recycle = function () {
return this.clone(List, "recycle").postCore().then(function (data) {
if (common.hOP(data, "Recycle")) {
return data.Recycle;
}
else {
return data;
}
});
};
/**
* Renders list data based on the view xml provided
*/
List.prototype.renderListData = function (viewXml) {
var q = this.clone(List, "renderlistdata(@viewXml)");
q.query.set("@viewXml", "'" + viewXml + "'");
return q.postCore().then(function (data) {
// data will be a string, so we parse it again
return JSON.parse(common.hOP(data, "RenderListData") ? data.RenderListData : data);
});
};
/**
* Returns the data for the specified query view
*
* @param parameters The parameters to be used to render list data as JSON string.
* @param overrideParameters The parameters that are used to override and extend the regular SPRenderListDataParameters.
*/
List.prototype.renderListDataAsStream = function (parameters, overrideParameters) {
if (overrideParameters === void 0) { overrideParameters = null; }
var postBody = {
overrideParameters: common.extend(metadata("SP.RenderListDataOverrideParameters"), overrideParameters),
parameters: common.extend(metadata("SP.RenderListDataParameters"), parameters),
};
return this.clone(List, "RenderListDataAsStream", true).postCore({
body: common.jsS(postBody),
});
};
/**
* Gets the field values and field schema attributes for a list item.
*/
List.prototype.renderListFormData = function (itemId, formId, mode) {
return this.clone(List, "renderlistformdata(itemid=" + itemId + ", formid='" + formId + "', mode='" + mode + "')").postCore().then(function (data) {
// data will be a string, so we parse it again
return JSON.parse(common.hOP(data, "RenderListFormData") ? data.RenderListFormData : data);
});
};
/**
* Reserves a list item ID for idempotent list item creation.
*/
List.prototype.reserveListItemId = function () {
return this.clone(List, "reservelistitemid").postCore().then(function (data) {
if (common.hOP(data, "ReserveListItemId")) {
return data.ReserveListItemId;
}
else {
return data;
}
});
};
/**
* Returns the ListItemEntityTypeFullName for this list, used when adding/updating list items. Does not support batching.
*
*/
List.prototype.getListItemEntityTypeFullName = function () {
return this.clone(List, null, false).select("ListItemEntityTypeFullName").get().then(function (o) { return o.ListItemEntityTypeFullName; });
};
/**
* Creates an item using path (in a folder), validates and sets its field values.
*
* @param formValues The fields to change and their new values.
* @param decodedUrl Path decoded url; folder's server relative path.
* @param bNewDocumentUpdate true if the list item is a document being updated after upload; otherwise false.
* @param checkInComment Optional check in comment.
*/
List.prototype.addValidateUpdateItemUsingPath = function (formValues, decodedUrl, bNewDocumentUpdate, checkInComment) {
if (bNewDocumentUpdate === void 0) { bNewDocumentUpdate = false; }
return this.clone(List, "AddValidateUpdateItemUsingPath()").postCore({
body: common.jsS({
bNewDocumentUpdate: bNewDocumentUpdate,
checkInComment: checkInComment,
formValues: formValues,
listItemCreateInfo: {
FolderPath: {
DecodedUrl: decodedUrl,
__metadata: { type: "SP.ResourcePath" },
},
__metadata: { type: "SP.ListItemCreationInformationUsingPath" },
},
}),
}).then(function (res) {
if (typeof res.AddValidateUpdateItemUsingPath !== "undefined") {
return res.AddValidateUpdateItemUsingPath.results;
}
return res;
});
};
return List;
}(SharePointQueryableSecurable));
/**
* Represents a Collection of comments
*/
var Comments = /** @class */ (function (_super) {
__extends(Comments, _super);
function Comments() {
return _super !== null && _super.apply(this, arguments) || this;
}
Comments_1 = Comments;
/**
* Adds a new comment to this collection
*
* @param info Comment information to add
*/
Comments.prototype.add = function (info) {
var _this = this;
if (typeof info === "string") {
info = { text: info };
}
var postBody = common.jsS(common.extend(metadata("Microsoft.SharePoint.Comments.comment"), info));
return this.clone(Comments_1, null).postCore({ body: postBody }).then(function (d) {
return common.extend(_this.getById(d.id), d);
});
};
/**
* Gets a comment by id
*
* @param id Id of the comment to load
*/
Comments.prototype.getById = function (id) {
var c = new Comment(this);
c.concat("(" + id + ")");
return c;
};
/**
* Deletes all the comments in this collection
*/
Comments.prototype.clear = function () {
return this.clone(Comments_1, "DeleteAll").postCore();
};
var Comments_1;
Comments = Comments_1 = __decorate([
defaultPath("comments")
], Comments);
return Comments;
}(SharePointQueryableCollection));
/**
* Represents a comment
*/
var Comment = /** @class */ (function (_super) {
__extends(Comment, _super);
function Comment() {
return _super !== null && _super.apply(this, arguments) || this;
}
Object.defineProperty(Comment.prototype, "replies", {
get: function () {
return new Replies(this);
},
enumerable: true,
configurable: true
});
/**
* Likes the comment as the current user
*/
Comment.prototype.like = function () {
return this.clone(Comment, "Like").postCore();
};
/**
* Unlikes the comment as the current user
*/
Comment.prototype.unlike = function () {
return this.clone(Comment, "Unlike").postCore();
};
/**
* Deletes this comment
*/
Comment.prototype.delete = function () {
return this.clone(Comment, "DeleteComment").postCore();
};
return Comment;
}(SharePointQueryableInstance));
/**
* Represents a Collection of comments
*/
var Replies = /** @class */ (function (_super) {
__extends(Replies, _super);
function Replies() {
return _super !== null && _super.apply(this, arguments) || this;
}
Replies_1 = Replies;
/**
* Adds a new reply to this collection
*
* @param info Comment information to add
*/
Replies.prototype.add = function (info) {
if (typeof info === "string") {
info = { text: info };
}
var postBody = common.jsS(common.extend(metadata("Microsoft.SharePoint.Comments.comment"), info));
return this.clone(Replies_1, null).postCore({ body: postBody }).then(function (d) {
return common.extend(new Comment(odataUrlFrom(d)), d);
});
};
var Replies_1;
Replies = Replies_1 = __decorate([
defaultPath("replies")
], Replies);
return Replies;
}(SharePointQueryableCollection));
/**
* Describes a collection of Item objects
*
*/
var Items = /** @class */ (function (_super) {
__extends(Items, _super);
function Items() {
return _super !== null && _super.apply(this, arguments) || this;
}
Items_1 = Items;
/**
* Gets an Item by id
*
* @param id The integer id of the item to retrieve
*/
Items.prototype.getById = function (id) {
var i = new Item(this);
i.concat("(" + id + ")");
return i;
};
/**
* Gets BCS Item by string id
*
* @param stringId The string id of the BCS item to retrieve
*/
Items.prototype.getItemByStringId = function (stringId) {
// creates an item with the parent list path and append out method call
return new Item(this.parentUrl, "getItemByStringId('" + stringId + "')");
};
/**
* Skips the specified number of items (https://msdn.microsoft.com/en-us/library/office/fp142385.aspx#sectionSection6)
*
* @param skip The starting id where the page should start, use with top to specify pages
* @param reverse It true the PagedPrev=true parameter is added allowing backwards navigation in the collection
*/
Items.prototype.skip = function (skip, reverse) {
if (reverse === void 0) { reverse = false; }
if (reverse) {
this.query.set("$skiptoken", encodeURIComponent("Paged=TRUE&PagedPrev=TRUE&p_ID=" + skip));
}
else {
this.query.set("$skiptoken", encodeURIComponent("Paged=TRUE&p_ID=" + skip));
}
return this;
};
/**
* Gets a collection designed to aid in paging through data
*
*/
Items.prototype.getPaged = function () {
return this.get(new PagedItemCollectionParser(this));
};
/**
* Gets all the items in a list, regardless of count. Does not support batching or caching
*
* @param requestSize Number of items to return in each request (Default: 2000)
* @param acceptHeader Allows for setting the value of the Accept header for SP 2013 support
*/
Items.prototype.getAll = function (requestSize, acceptHeader) {
if (requestSize === void 0) { requestSize = 2000; }
if (acceptHeader === void 0) { acceptHeader = "application/json;odata=nometadata"; }
logging.Logger.write("Calling items.getAll should be done sparingly. Ensure this is the correct choice. If you are unsure, it is not.", 2 /* Warning */);
// this will be used for the actual query
// and we set no metadata here to try and reduce traffic
var items = new Items_1(this, "").top(requestSize).configure({
headers: {
"Accept": acceptHeader,
},
});
// let's copy over the odata query params that can be applied
// $top - allow setting the page size this way (override what we did above)
// $select - allow picking the return fields (good behavior)
// $filter - allow setting a filter, though this may fail due for large lists
this.query.forEach(function (v, k) {
if (/^\$select|filter|top|expand$/i.test(k)) {
items.query.set(k, v);
}
});
// give back the promise
return new Promise(function (resolve, reject) {
// this will eventually hold the items we return
var itemsCollector = [];
// action that will gather up our results recursively
var gatherer = function (last) {
// collect that set of results
[].push.apply(itemsCollector, last.results);
// if we have more, repeat - otherwise resolve with the collected items
if (last.hasNext) {
last.getNext().then(gatherer).catch(reject);
}
else {
resolve(itemsCollector);
}
};
// start the cycle
items.getPaged().then(gatherer).catch(reject);
});
};
/**
* Adds a new item to the collection
*
* @param properties The new items's properties
* @param listItemEntityTypeFullName The type name of the list's entities
*/
Items.prototype.add = function (properties, listItemEntityTypeFullName) {
var _this = this;
if (properties === void 0) { properties = {}; }
if (listItemEntityTypeFullName === void 0) { listItemEntityTypeFullName = null; }
var removeDependency = this.addBatchDependency();
return this.ensureListItemEntityTypeName(listItemEntityTypeFullName).then(function (listItemEntityType) {
var postBody = common.jsS(common.extend(metadata(listItemEntityType), properties));
var promise = _this.clone(Items_1, "").postCore({ body: postBody }).then(function (data) {
return {
data: data,
item: _this.getById(data.Id),
};
});
removeDependency();
return promise;
});
};
/**
* Ensures we have the proper list item entity type name, either from the value provided or from the list
*
* @param candidatelistItemEntityTypeFullName The potential type name
*/
Items.prototype.ensureListItemEntityTypeName = function (candidatelistItemEntityTypeFullName) {
return candidatelistItemEntityTypeFullName ?
Promise.resolve(candidatelistItemEntityTypeFullName) :
this.getParent(List).getListItemEntityTypeFullName();
};
var Items_1;
Items = Items_1 = __decorate([
defaultPath("items")
], Items);
return Items;
}(SharePointQueryableCollection));
/**
* Descrines a single Item instance
*
*/
var Item = /** @class */ (function (_super) {
__extends(Item, _super);
function Item() {
var _this = _super !== null && _super.apply(this, arguments) || this;
/**
* Delete this item
*
* @param eTag Value used in the IF-Match header, by default "*"
*/
_this.delete = _this._deleteWithETag;
return _this;
}
Object.defineProperty(Item.prototype, "attachmentFiles", {
/**
* Gets the set of attachments for this item
*
*/
get: function () {
return new AttachmentFiles(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Item.prototype, "contentType", {
/**
* Gets the content type for this item
*
*/
get: function () {
return new ContentType(this, "ContentType");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Item.prototype, "comments", {
/**
* Gets the collection of comments associated with this list item
*/
get: function () {
return new Comments(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Item.prototype, "effectiveBasePermissions", {
/**
* Gets the effective base permissions for the item
*
*/
get: function () {
return new SharePointQueryable(this, "EffectiveBasePermissions");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Item.prototype, "effectiveBasePermissionsForUI", {
/**
* Gets the effective base permissions for the item in a UI context
*
*/
get: function () {
return new SharePointQueryable(this, "EffectiveBasePermissionsForUI");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Item.prototype, "fieldValuesAsHTML", {
/**
* Gets the field values for this list item in their HTML representation
*
*/
get: function () {
return new SharePointQueryableInstance(this, "FieldValuesAsHTML");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Item.prototype, "fieldValuesAsText", {
/**
* Gets the field values for this list item in their text representation
*
*/
get: function () {
return new SharePointQueryableInstance(this, "FieldValuesAsText");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Item.prototype, "fieldValuesForEdit", {
/**
* Gets the field values for this list item for use in editing controls
*
*/
get: function () {
return new SharePointQueryableInstance(this, "FieldValuesForEdit");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Item.prototype, "folder", {
/**
* Gets the folder associated with this list item (if this item represents a folder)
*
*/
get: function () {
return new Folder(this, "folder");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Item.prototype, "file", {
/**
* Gets the folder associated with this list item (if this item represents a folder)
*
*/
get: function () {
return new File(this, "file");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Item.prototype, "versions", {
/**
* Gets the collection of versions associated with this item
*/
get: function () {
return new ItemVersions(this);
},
enumerable: true,
configurable: true
});
/**
* Updates this list intance with the supplied properties
*
* @param properties A plain object hash of values to update for the list
* @param eTag Value used in the IF-Match header, by default "*"
* @param listItemEntityTypeFullName The type name of the list's entities
*/
Item.prototype.update = function (properties, eTag, listItemEntityTypeFullName) {
var _this = this;
if (eTag === void 0) { eTag = "*"; }
if (listItemEntityTypeFullName === void 0) { listItemEntityTypeFullName = null; }
return new Promise(function (resolve, reject) {
var removeDependency = _this.addBatchDependency();
return _this.ensureListItemEntityTypeName(listItemEntityTypeFullName).then(function (listItemEntityType) {
var postBody = common.jsS(common.extend(metadata(listItemEntityType), properties));
removeDependency();
return _this.postCore({
body: postBody,
headers: {
"IF-Match": eTag,
"X-HTTP-Method": "MERGE",
},
}, new ItemUpdatedParser()).then(function (data) {
resolve({
data: data,
item: _this,
});
});
}).catch(function (e) { return reject(e); });
});
};
/**
* Gets the collection of people who have liked this item
*/
Item.prototype.getLikedBy = function () {
return this.clone(Item, "likedBy").postCore();
};
/**
* Likes this item as the current user
*/
Item.prototype.like = function () {
return this.clone(Item, "like").postCore();
};
/**
* Unlikes this item as the current user
*/
Item.prototype.unlike = function () {
return this.clone(Item, "unlike").postCore();
};
/**
* Moves the list item to the Recycle Bin and returns the identifier of the new Recycle Bin item.
*/
Item.prototype.recycle = function () {
return this.clone(Item, "recycle").postCore();
};
/**
* Gets a string representation of the full URL to the WOPI frame.
* If there is no associated WOPI application, or no associated action, an empty string is returned.
*
* @param action Display mode: 0: view, 1: edit, 2: mobileView, 3: interactivePreview
*/
Item.prototype.getWopiFrameUrl = function (action) {
if (action === void 0) { action = 0; }
var i = this.clone(Item, "getWOPIFrameUrl(@action)");
i.query.set("@action", action);
return i.postCore().then(function (data) {
// handle verbose mode
if (common.hOP(data, "GetWOPIFrameUrl")) {
return data.GetWOPIFrameUrl;
}
return data;
});
};
/**
* Validates and sets the values of the specified collection of fields for the list item.
*
* @param formValues The fields to change and their new values.
* @param newDocumentUpdate true if the list item is a document being updated after upload; otherwise false.
*/
Item.prototype.validateUpdateListItem = function (formValues, newDocumentUpdate) {
if (newDocumentUpdate === void 0) { newDocumentUpdate = false; }
return this.clone(Item, "validateupdatelistitem").postCore({
body: common.jsS({ "formValues": formValues, bNewDocumentUpdate: newDocumentUpdate }),
});
};
/**
* Get the like by information for a modern site page
*/
Item.prototype.getLikedByInformation = function () {
return this.clone(Item, "likedByInformation").expand("likedby").getCore();
};
/**
* Ensures we have the proper list item entity type name, either from the value provided or from the list
*
* @param candidatelistItemEntityTypeFullName The potential type name
*/
Item.prototype.ensureListItemEntityTypeName = function (candidatelistItemEntityTypeFullName) {
return candidatelistItemEntityTypeFullName ?
Promise.resolve(candidatelistItemEntityTypeFullName) :
this.getParent(List, this.parentUrl.substr(0, this.parentUrl.lastIndexOf("/"))).getListItemEntityTypeFullName();
};
return Item;
}(SharePointQueryableShareableItem));
/**
* Describes a collection of Version objects
*
*/
var ItemVersions = /** @class */ (function (_super) {
__extends(ItemVersions, _super);
function ItemVersions() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Gets a version by id
*
* @param versionId The id of the version to retrieve
*/
ItemVersions.prototype.getById = function (versionId) {
var v = new ItemVersion(this);
v.concat("(" + versionId + ")");
return v;
};
ItemVersions = __decorate([
defaultPath("versions")
], ItemVersions);
return ItemVersions;
}(SharePointQueryableCollection));
/**
* Describes a single Version instance
*
*/
var ItemVersion = /** @class */ (function (_super) {
__extends(ItemVersion, _super);
function ItemVersion() {
var _this = _super !== null && _super.apply(this, arguments) || this;
/**
* Delete a specific version of a file.
*
* @param eTag Value used in the IF-Match header, by default "*"
*/
_this.delete = _this._deleteWithETag;
return _this;
}
return ItemVersion;
}(SharePointQueryableInstance));
/**
* Provides paging functionality for list items
*/
var PagedItemCollection = /** @class */ (function () {
function PagedItemCollection(parent, nextUrl, results) {
this.parent = parent;
this.nextUrl = nextUrl;
this.results = results;
}
Object.defineProperty(PagedItemCollection.prototype, "hasNext", {
/**
* If true there are more results available in the set, otherwise there are not
*/
get: function () {
return typeof this.nextUrl === "string" && this.nextUrl.length > 0;
},
enumerable: true,
configurable: true
});
/**
* Gets the next set of results, or resolves to null if no results are available
*/
PagedItemCollection.prototype.getNext = function () {
if (this.hasNext) {
var items = new Items(this.nextUrl, null).configureFrom(this.parent);
return items.getPaged();
}
return new Promise(function (r) { return r(null); });
};
return PagedItemCollection;
}());
var PagedItemCollectionParser = /** @class */ (function (_super) {
__extends(PagedItemCollectionParser, _super);
function PagedItemCollectionParser(_parent) {
var _this = _super.call(this) || this;
_this._parent = _parent;
return _this;
}
PagedItemCollectionParser.prototype.parse = function (r) {
var _this = this;
return new Promise(function (resolve, reject) {
if (_this.handleError(r, reject)) {
r.json().then(function (json) {
var nextUrl = common.hOP(json, "d") && common.hOP(json.d, "__next") ? json.d.__next : json["odata.nextLink"];
resolve(new PagedItemCollection(_this._parent, nextUrl, _this.parseODataJSON(json)));
});
}
});
};
return PagedItemCollectionParser;
}(odata.ODataParserBase));
var ItemUpdatedParser = /** @class */ (function (_super) {
__extends(ItemUpdatedParser, _super);
function ItemUpdatedParser() {
return _super !== null && _super.apply(this, arguments) || this;
}
ItemUpdatedParser.prototype.parse = function (r) {
var _this = this;
return new Promise(function (resolve, reject) {
if (_this.handleError(r, reject)) {
resolve({
"odata.etag": r.headers.get("etag"),
});
}
});
};
return ItemUpdatedParser;
}(odata.ODataParserBase));
/**
* Describes a collection of File objects
*
*/
var Files = /** @class */ (function (_super) {
__extends(Files, _super);
function Files() {
return _super !== null && _super.apply(this, arguments) || this;
}
Files_1 = Files;
/**
* Gets a File by filename
*
* @param name The name of the file, including extension.
*/
Files.prototype.getByName = function (name) {
var f = new File(this);
f.concat("('" + name + "')");
return f;
};
/**
* Uploads a file. Not supported for batching
*
* @param url The folder-relative url of the file.
* @param content The file contents blob.
* @param shouldOverWrite Should a file with the same name in the same location be overwritten? (default: true)
* @returns The new File and the raw response.
*/
Files.prototype.add = function (url, content, shouldOverWrite) {
var _this = this;
if (shouldOverWrite === void 0) { shouldOverWrite = true; }
return new Files_1(this, "add(overwrite=" + shouldOverWrite + ",url='" + url + "')")
.postCore({
body: content,
}).then(function (response) {
return {
data: response,
file: _this.getByName(url),
};
});
};
/**
* Uploads a file. Not supported for batching
*
* @param url The folder-relative url of the file.
* @param content The Blob file content to add
* @param progress A callback function which can be used to track the progress of the upload
* @param shouldOverWrite Should a file with the same name in the same location be overwritten? (default: true)
* @param chunkSize The size of each file slice, in bytes (default: 10485760)
* @returns The new File and the raw response.
*/
Files.prototype.addChunked = function (url, content, progress, shouldOverWrite, chunkSize) {
var _this = this;
if (shouldOverWrite === void 0) { shouldOverWrite = true; }
if (chunkSize === void 0) { chunkSize = 10485760; }
var adder = this.clone(Files_1, "add(overwrite=" + shouldOverWrite + ",url='" + url + "')", false);
return adder.postCore()
.then(function () { return _this.getByName(url); })
.then(function (file) { return file.setContentChunked(content, progress, chunkSize); });
};
/**
* Adds a ghosted file to an existing list or document library. Not supported for batching.
*
* @param fileUrl The server-relative url where you want to save the file.
* @param templateFileType The type of use to create the file.
* @returns The template file that was added and the raw response.
*/
Files.prototype.addTemplateFile = function (fileUrl, templateFileType) {
var _this = this;
return this.clone(Files_1, "addTemplateFile(urloffile='" + fileUrl + "',templatefiletype=" + templateFileType + ")", false)
.postCore().then(function (response) {
return {
data: response,
file: _this.getByName(fileUrl),
};
});
};
var Files_1;
Files = Files_1 = __decorate([
defaultPath("files")
], Files);
return Files;
}(SharePointQueryableCollection));
/**
* Describes a single File instance
*
*/
var File = /** @class */ (function (_super) {
__extends(File, _super);
function File() {
return _super !== null && _super.apply(this, arguments) || this;
}
Object.defineProperty(File.prototype, "listItemAllFields", {
/**
* Gets a value that specifies the list item field values for the list item corresponding to the file.
*
*/
get: function () {
return new SharePointQueryableInstance(this, "listItemAllFields");
},
enumerable: true,
configurable: true
});
Object.defineProperty(File.prototype, "versions", {
/**
* Gets a collection of versions
*
*/
get: function () {
return new Versions(this);
},
enumerable: true,
configurable: true
});
/**
* Approves the file submitted for content approval with the specified comment.
* Only documents in lists that are enabled for content approval can be approved.
*
* @param comment The comment for the approval.
*/
File.prototype.approve = function (comment) {
if (comment === void 0) { comment = ""; }
return this.clone(File, "approve(comment='" + comment + "')").postCore();
};
/**
* Stops the chunk upload session without saving the uploaded data. Does not support batching.
* If the file doesn’t already exist in the library, the partially uploaded file will be deleted.
* Use this in response to user action (as in a request to cancel an upload) or an error or exception.
* Use the uploadId value that was passed to the StartUpload method that started the upload session.
* This method is currently available only on Office 365.
*
* @param uploadId The unique identifier of the upload session.
*/
File.prototype.cancelUpload = function (uploadId) {
return this.clone(File, "cancelUpload(uploadId=guid'" + uploadId + "')", false).postCore();
};
/**
* Checks the file in to a document library based on the check-in type.
*
* @param comment A comment for the check-in. Its length must be <= 1023.
* @param checkinType The check-in type for the file.
*/
File.prototype.checkin = function (comment, checkinType) {
if (comment === void 0) { comment = ""; }
if (checkinType === void 0) { checkinType = exports.CheckinType.Major; }
if (comment.length > 1023) {
throw Error("The maximum comment length is 1023 characters.");
}
return this.clone(File, "checkin(comment='" + comment + "',checkintype=" + checkinType + ")").postCore();
};
/**
* Checks out the file from a document library.
*/
File.prototype.checkout = function () {
return this.clone(File, "checkout").postCore();
};
/**
* Copies the file to the destination url.
*
* @param url The absolute url or server relative url of the destination file path to copy to.
* @param shouldOverWrite Should a file with the same name in the same location be overwritten?
*/
File.prototype.copyTo = function (url, shouldOverWrite) {
if (shouldOverWrite === void 0) { shouldOverWrite = true; }
return this.clone(File, "copyTo(strnewurl='" + url + "',boverwrite=" + shouldOverWrite + ")").postCore();
};
/**
* Delete this file.
*
* @param eTag Value used in the IF-Match header, by default "*"
*/
File.prototype.delete = function (eTag) {
if (eTag === void 0) { eTag = "*"; }
return this.clone(File, null).postCore({
headers: {
"IF-Match": eTag,
"X-HTTP-Method": "DELETE",
},
});
};
/**
* Denies approval for a file that was submitted for content approval.
* Only documents in lists that are enabled for content approval can be denied.
*
* @param comment The comment for the denial.
*/
File.prototype.deny = function (comment) {
if (comment === void 0) { comment = ""; }
if (comment.length > 1023) {
throw Error("The maximum comment length is 1023 characters.");
}
return this.clone(File, "deny(comment='" + comment + "')").postCore();
};
/**
* Specifies the control set used to access, modify, or add Web Parts associated with this Web Part Page and view.
* An exception is thrown if the file is not an ASPX page.
*
* @param scope The WebPartsPersonalizationScope view on the Web Parts page.
*/
File.prototype.getLimitedWebPartManager = function (scope) {
if (scope === void 0) { scope = exports.WebPartsPersonalizationScope.Shared; }
return new LimitedWebPartManager(this, "getLimitedWebPartManager(scope=" + scope + ")");
};
/**
* Moves the file to the specified destination url.
*
* @param url The absolute url or server relative url of the destination file path to move to.
* @param moveOperations The bitwise MoveOperations value for how to move the file.
*/
File.prototype.moveTo = function (url, moveOperations) {
if (moveOperations === void 0) { moveOperations = exports.MoveOperations.Overwrite; }
return this.clone(File, "moveTo(newurl='" + url + "',flags=" + moveOperations + ")").postCore();
};
/**
* Submits the file for content approval with the specified comment.
*
* @param comment The comment for the published file. Its length must be <= 1023.
*/
File.prototype.publish = function (comment) {
if (comment === void 0) { comment = ""; }
if (comment.length > 1023) {
throw Error("The maximum comment length is 1023 characters.");
}
return this.clone(File, "publish(comment='" + comment + "')").postCore();
};
/**
* Moves the file to the Recycle Bin and returns the identifier of the new Recycle Bin item.
*
* @returns The GUID of the recycled file.
*/
File.prototype.recycle = function () {
return this.clone(File, "recycle").postCore();
};
/**
* Reverts an existing checkout for the file.
*
*/
File.prototype.undoCheckout = function () {
return this.clone(File, "undoCheckout").postCore();
};
/**
* Removes the file from content approval or unpublish a major version.
*
* @param comment The comment for the unpublish operation. Its length must be <= 1023.
*/
File.prototype.unpublish = function (comment) {
if (comment === void 0) { comment = ""; }
if (comment.length > 1023) {
throw Error("The maximum comment length is 1023 characters.");
}
return this.clone(File, "unpublish(comment='" + comment + "')").postCore();
};
/**
* Gets the contents of the file as text. Not supported in batching.
*
*/
File.prototype.getText = function () {
return this.clone(File, "$value", false).get(new odata.TextParser(), { headers: { "binaryStringResponseBody": "true" } });
};
/**
* Gets the contents of the file as a blob, does not work in Node.js. Not supported in batching.
*
*/
File.prototype.getBlob = function () {
return this.clone(File, "$value", false).get(new odata.BlobParser(), { headers: { "binaryStringResponseBody": "true" } });
};
/**
* Gets the contents of a file as an ArrayBuffer, works in Node.js. Not supported in batching.
*/
File.prototype.getBuffer = function () {
return this.clone(File, "$value", false).get(new odata.BufferParser(), { headers: { "binaryStringResponseBody": "true" } });
};
/**
* Gets the contents of a file as an ArrayBuffer, works in Node.js. Not supported in batching.
*/
File.prototype.getJSON = function () {
return this.clone(File, "$value", false).get(new odata.JSONParser(), { headers: { "binaryStringResponseBody": "true" } });
};
/**
* Sets the content of a file, for large files use setContentChunked. Not supported in batching.
*
* @param content The file content
*
*/
File.prototype.setContent = function (content) {
var _this = this;
return this.clone(File, "$value", false).postCore({
body: content,
headers: {
"X-HTTP-Method": "PUT",
},
}).then(function (_) { return new File(_this); });
};
/**
* Gets the associated list item for this folder, loading the default properties
*/
File.prototype.getItem = function () {
var selects = [];
for (var _i = 0; _i < arguments.length; _i++) {
selects[_i] = arguments[_i];
}
var q = this.listItemAllFields;
return q.select.apply(q, selects).get().then(function (d) {
return common.extend(new Item(odataUrlFrom(d)), d);
});
};
/**
* Sets the contents of a file using a chunked upload approach. Not supported in batching.
*
* @param file The file to upload
* @param progress A callback function which can be used to track the progress of the upload
* @param chunkSize The size of each file slice, in bytes (default: 10485760)
*/
File.prototype.setContentChunked = function (file, progress, chunkSize) {
var _this = this;
if (chunkSize === void 0) { chunkSize = 10485760; }
if (progress === undefined) {
progress = function () { return null; };
}
var fileSize = file.size;
var blockCount = parseInt((file.size / chunkSize).toString(), 10) + ((file.size % chunkSize === 0) ? 1 : 0);
var uploadId = common.getGUID();
// start the chain with the first fragment
progress({ uploadId: uploadId, blockNumber: 1, chunkSize: chunkSize, currentPointer: 0, fileSize: fileSize, stage: "starting", totalBlocks: blockCount });
var chain = this.startUpload(uploadId, file.slice(0, chunkSize));
var _loop_1 = function (i) {
chain = chain.then(function (pointer) {
progress({ uploadId: uploadId, blockNumber: i, chunkSize: chunkSize, currentPointer: pointer, fileSize: fileSize, stage: "continue", totalBlocks: blockCount });
return _this.continueUpload(uploadId, pointer, file.slice(pointer, pointer + chunkSize));
});
};
// skip the first and last blocks
for (var i = 2; i < blockCount; i++) {
_loop_1(i);
}
return chain.then(function (pointer) {
progress({ uploadId: uploadId, blockNumber: blockCount, chunkSize: chunkSize, currentPointer: pointer, fileSize: fileSize, stage: "finishing", totalBlocks: blockCount });
return _this.finishUpload(uploadId, pointer, file.slice(pointer));
});
};
/**
* Starts a new chunk upload session and uploads the first fragment.
* The current file content is not changed when this method completes.
* The method is idempotent (and therefore does not change the result) as long as you use the same values for uploadId and stream.
* The upload session ends either when you use the CancelUpload method or when you successfully
* complete the upload session by passing the rest of the file contents through the ContinueUpload and FinishUpload methods.
* The StartUpload and ContinueUpload methods return the size of the running total of uploaded data in bytes,
* so you can pass those return values to subsequent uses of ContinueUpload and FinishUpload.
* This method is currently available only on Office 365.
*
* @param uploadId The unique identifier of the upload session.
* @param fragment The file contents.
* @returns The size of the total uploaded data in bytes.
*/
File.prototype.startUpload = function (uploadId, fragment) {
return this.clone(File, "startUpload(uploadId=guid'" + uploadId + "')", false)
.postCore({ body: fragment })
.then(function (n) {
// When OData=verbose the payload has the following shape:
// { StartUpload: "10485760" }
if (typeof n === "object") {
n = n.StartUpload;
}
return parseFloat(n);
});
};
/**
* Continues the chunk upload session with an additional fragment.
* The current file content is not changed.
* Use the uploadId value that was passed to the StartUpload method that started the upload session.
* This method is currently available only on Office 365.
*
* @param uploadId The unique identifier of the upload session.
* @param fileOffset The size of the offset into the file where the fragment starts.
* @param fragment The file contents.
* @returns The size of the total uploaded data in bytes.
*/
File.prototype.continueUpload = function (uploadId, fileOffset, fragment) {
return this.clone(File, "continueUpload(uploadId=guid'" + uploadId + "',fileOffset=" + fileOffset + ")", false)
.postCore({ body: fragment })
.then(function (n) {
// When OData=verbose the payload has the following shape:
// { ContinueUpload: "20971520" }
if (typeof n === "object") {
n = n.ContinueUpload;
}
return parseFloat(n);
});
};
/**
* Uploads the last file fragment and commits the file. The current file content is changed when this method completes.
* Use the uploadId value that was passed to the StartUpload method that started the upload session.
* This method is currently available only on Office 365.
*
* @param uploadId The unique identifier of the upload session.
* @param fileOffset The size of the offset into the file where the fragment starts.
* @param fragment The file contents.
* @returns The newly uploaded file.
*/
File.prototype.finishUpload = function (uploadId, fileOffset, fragment) {
return this.clone(File, "finishUpload(uploadId=guid'" + uploadId + "',fileOffset=" + fileOffset + ")", false)
.postCore({ body: fragment })
.then(function (response) {
return {
data: response,
file: new File(odataUrlFrom(response)),
};
});
};
return File;
}(SharePointQueryableShareableFile));
/**
* Describes a collection of Version objects
*
*/
var Versions = /** @class */ (function (_super) {
__extends(Versions, _super);
function Versions() {
return _super !== null && _super.apply(this, arguments) || this;
}
Versions_1 = Versions;
/**
* Gets a version by id
*
* @param versionId The id of the version to retrieve
*/
Versions.prototype.getById = function (versionId) {
var v = new Version(this);
v.concat("(" + versionId + ")");
return v;
};
/**
* Deletes all the file version objects in the collection.
*
*/
Versions.prototype.deleteAll = function () {
return new Versions_1(this, "deleteAll").postCore();
};
/**
* Deletes the specified version of the file.
*
* @param versionId The ID of the file version to delete.
*/
Versions.prototype.deleteById = function (versionId) {
return this.clone(Versions_1, "deleteById(vid=" + versionId + ")").postCore();
};
/**
* Recycles the specified version of the file.
*
* @param versionId The ID of the file version to delete.
*/
Versions.prototype.recycleByID = function (versionId) {
return this.clone(Versions_1, "recycleByID(vid=" + versionId + ")").postCore();
};
/**
* Deletes the file version object with the specified version label.
*
* @param label The version label of the file version to delete, for example: 1.2
*/
Versions.prototype.deleteByLabel = function (label) {
return this.clone(Versions_1, "deleteByLabel(versionlabel='" + label + "')").postCore();
};
/**
* Recycles the file version object with the specified version label.
*
* @param label The version label of the file version to delete, for example: 1.2
*/
Versions.prototype.recycleByLabel = function (label) {
return this.clone(Versions_1, "recycleByLabel(versionlabel='" + label + "')").postCore();
};
/**
* Creates a new file version from the file specified by the version label.
*
* @param label The version label of the file version to restore, for example: 1.2
*/
Versions.prototype.restoreByLabel = function (label) {
return this.clone(Versions_1, "restoreByLabel(versionlabel='" + label + "')").postCore();
};
var Versions_1;
Versions = Versions_1 = __decorate([
defaultPath("versions")
], Versions);
return Versions;
}(SharePointQueryableCollection));
/**
* Describes a single Version instance
*
*/
var Version = /** @class */ (function (_super) {
__extends(Version, _super);
function Version() {
var _this = _super !== null && _super.apply(this, arguments) || this;
/**
* Delete a specific version of a file.
*
* @param eTag Value used in the IF-Match header, by default "*"
*/
_this.delete = _this._deleteWithETag;
return _this;
// /**
// * Delete a specific version of a file.
// *
// * @param eTag Value used in the IF-Match header, by default "*"
// */
// public delete(eTag = "*"): Promise<void> {
// return this.postCore({
// headers: {
// "IF-Match": eTag,
// "X-HTTP-Method": "DELETE",
// },
// });
// }
}
return Version;
}(SharePointQueryableInstance));
(function (CheckinType) {
CheckinType[CheckinType["Minor"] = 0] = "Minor";
CheckinType[CheckinType["Major"] = 1] = "Major";
CheckinType[CheckinType["Overwrite"] = 2] = "Overwrite";
})(exports.CheckinType || (exports.CheckinType = {}));
(function (WebPartsPersonalizationScope) {
WebPartsPersonalizationScope[WebPartsPersonalizationScope["User"] = 0] = "User";
WebPartsPersonalizationScope[WebPartsPersonalizationScope["Shared"] = 1] = "Shared";
})(exports.WebPartsPersonalizationScope || (exports.WebPartsPersonalizationScope = {}));
(function (MoveOperations) {
MoveOperations[MoveOperations["Overwrite"] = 1] = "Overwrite";
MoveOperations[MoveOperations["AllowBrokenThickets"] = 8] = "AllowBrokenThickets";
})(exports.MoveOperations || (exports.MoveOperations = {}));
(function (TemplateFileType) {
TemplateFileType[TemplateFileType["StandardPage"] = 0] = "StandardPage";
TemplateFileType[TemplateFileType["WikiPage"] = 1] = "WikiPage";
TemplateFileType[TemplateFileType["FormPage"] = 2] = "FormPage";
TemplateFileType[TemplateFileType["ClientSidePage"] = 3] = "ClientSidePage";
})(exports.TemplateFileType || (exports.TemplateFileType = {}));
/**
* Represents an app catalog
*/
var AppCatalog = /** @class */ (function (_super) {
__extends(AppCatalog, _super);
function AppCatalog(baseUrl, path) {
if (path === void 0) { path = "_api/web/tenantappcatalog/AvailableApps"; }
return _super.call(this, extractWebUrl(typeof baseUrl === "string" ? baseUrl : baseUrl.toUrl()), path) || this;
}
/**
* Get details of specific app from the app catalog
* @param id - Specify the guid of the app
*/
AppCatalog.prototype.getAppById = function (id) {
return new App(this, "getById('" + id + "')");
};
/**
* Uploads an app package. Not supported for batching
*
* @param filename Filename to create.
* @param content app package data (eg: the .app or .sppkg file).
* @param shouldOverWrite Should an app with the same name in the same location be overwritten? (default: true)
* @returns Promise<AppAddResult>
*/
AppCatalog.prototype.add = function (filename, content, shouldOverWrite) {
if (shouldOverWrite === void 0) { shouldOverWrite = true; }
// you don't add to the availableapps collection
var adder = new AppCatalog(extractWebUrl(this.toUrl()), "_api/web/tenantappcatalog/add(overwrite=" + shouldOverWrite + ",url='" + filename + "')");
return adder.postCore({
body: content,
}).then(function (r) {
return {
data: r,
file: new File(odataUrlFrom(r)),
};
});
};
return AppCatalog;
}(SharePointQueryableCollection));
/**
* Represents the actions you can preform on a given app within the catalog
*/
var App = /** @class */ (function (_super) {
__extends(App, _super);
function App() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* This method deploys an app on the app catalog. It must be called in the context
* of the tenant app catalog web or it will fail.
*
* @param skipFeatureDeployment Deploy the app to the entire tenant
*/
App.prototype.deploy = function (skipFeatureDeployment) {
if (skipFeatureDeployment === void 0) { skipFeatureDeployment = false; }
return this.clone(App, "Deploy(" + skipFeatureDeployment + ")").postCore();
};
/**
* This method retracts a deployed app on the app catalog. It must be called in the context
* of the tenant app catalog web or it will fail.
*/
App.prototype.retract = function () {
return this.clone(App, "Retract").postCore();
};
/**
* This method allows an app which is already deployed to be installed on a web
*/
App.prototype.install = function () {
return this.clone(App, "Install").postCore();
};
/**
* This method allows an app which is already insatlled to be uninstalled on a web
*/
App.prototype.uninstall = function () {
return this.clone(App, "Uninstall").postCore();
};
/**
* This method allows an app which is already insatlled to be upgraded on a web
*/
App.prototype.upgrade = function () {
return this.clone(App, "Upgrade").postCore();
};
/**
* This method removes an app from the app catalog. It must be called in the context
* of the tenant app catalog web or it will fail.
*/
App.prototype.remove = function () {
return this.clone(App, "Remove").postCore();
};
return App;
}(SharePointQueryableInstance));
/**
* Manages a batch of OData operations
*/
var SPBatch = /** @class */ (function (_super) {
__extends(SPBatch, _super);
function SPBatch(baseUrl) {
var _this = _super.call(this) || this;
_this.baseUrl = baseUrl;
return _this;
}
/**
* Parses the response from a batch request into an array of Response instances
*
* @param body Text body of the response from the batch request
*/
SPBatch.ParseResponse = function (body) {
return new Promise(function (resolve, reject) {
var responses = [];
var header = "--batchresponse_";
// Ex. "HTTP/1.1 500 Internal Server Error"
var statusRegExp = new RegExp("^HTTP/[0-9.]+ +([0-9]+) +(.*)", "i");
var lines = body.split("\n");
var state = "batch";
var status;
var statusText;
for (var i = 0; i < lines.length; ++i) {
var line = lines[i];
switch (state) {
case "batch":
if (line.substr(0, header.length) === header) {
state = "batchHeaders";
}
else {
if (line.trim() !== "") {
throw Error("Invalid response, line " + i);
}
}
break;
case "batchHeaders":
if (line.trim() === "") {
state = "status";
}
break;
case "status":
var parts = statusRegExp.exec(line);
if (parts.length !== 3) {
throw Error("Invalid status, line " + i);
}
status = parseInt(parts[1], 10);
statusText = parts[2];
state = "statusHeaders";
break;
case "statusHeaders":
if (line.trim() === "") {
state = "body";
}
break;
case "body":
responses.push((status === 204) ? new Response() : new Response(line, { status: status, statusText: statusText }));
state = "batch";
break;
}
}
if (state !== "status") {
reject(Error("Unexpected end of input"));
}
resolve(responses);
});
};
SPBatch.prototype.executeImpl = function () {
var _this = this;
logging.Logger.write("[" + this.batchId + "] (" + (new Date()).getTime() + ") Executing batch with " + this.requests.length + " requests.", 1 /* Info */);
// if we don't have any requests, don't bother sending anything
// this could be due to caching further upstream, or just an empty batch
if (this.requests.length < 1) {
logging.Logger.write("Resolving empty batch.", 1 /* Info */);
return Promise.resolve();
}
// creating the client here allows the url to be populated for nodejs client as well as potentially
// any other hacks needed for other types of clients. Essentially allows the absoluteRequestUrl
// below to be correct
var client = new SPHttpClient();
// due to timing we need to get the absolute url here so we can use it for all the individual requests
// and for sending the entire batch
return toAbsoluteUrl(this.baseUrl).then(function (absoluteRequestUrl) {
// build all the requests, send them, pipe results in order to parsers
var batchBody = [];
var currentChangeSetId = "";
for (var i = 0; i < _this.requests.length; i++) {
var reqInfo = _this.requests[i];
if (reqInfo.method === "GET") {
if (currentChangeSetId.length > 0) {
// end an existing change set
batchBody.push("--changeset_" + currentChangeSetId + "--\n\n");
currentChangeSetId = "";
}
batchBody.push("--batch_" + _this.batchId + "\n");
}
else {
if (currentChangeSetId.length < 1) {
// start new change set
currentChangeSetId = common.getGUID();
batchBody.push("--batch_" + _this.batchId + "\n");
batchBody.push("Content-Type: multipart/mixed; boundary=\"changeset_" + currentChangeSetId + "\"\n\n");
}
batchBody.push("--changeset_" + currentChangeSetId + "\n");
}
// common batch part prefix
batchBody.push("Content-Type: application/http\n");
batchBody.push("Content-Transfer-Encoding: binary\n\n");
var headers = new Headers();
// this is the url of the individual request within the batch
var url = common.isUrlAbsolute(reqInfo.url) ? reqInfo.url : common.combine(absoluteRequestUrl, reqInfo.url);
logging.Logger.write("[" + _this.batchId + "] (" + (new Date()).getTime() + ") Adding request " + reqInfo.method + " " + url + " to batch.", 0 /* Verbose */);
if (reqInfo.method !== "GET") {
var method = reqInfo.method;
var castHeaders = reqInfo.options.headers;
if (common.hOP(reqInfo, "options") && common.hOP(reqInfo.options, "headers") && castHeaders["X-HTTP-Method"] !== undefined) {
method = castHeaders["X-HTTP-Method"];
delete castHeaders["X-HTTP-Method"];
}
batchBody.push(method + " " + url + " HTTP/1.1\n");
headers.set("Content-Type", "application/json;odata=verbose;charset=utf-8");
}
else {
batchBody.push(reqInfo.method + " " + url + " HTTP/1.1\n");
}
// merge global config headers
common.mergeHeaders(headers, SPRuntimeConfig.headers);
// merge per-request headers
if (reqInfo.options) {
common.mergeHeaders(headers, reqInfo.options.headers);
}
// lastly we apply any default headers we need that may not exist
if (!headers.has("Accept")) {
headers.append("Accept", "application/json");
}
if (!headers.has("Content-Type")) {
headers.append("Content-Type", "application/json;odata=verbose;charset=utf-8");
}
if (!headers.has("X-ClientService-ClientTag")) {
headers.append("X-ClientService-ClientTag", "PnPCoreJS:@pnp-1.2.4");
}
// write headers into batch body
headers.forEach(function (value, name) {
batchBody.push(name + ": " + value + "\n");
});
batchBody.push("\n");
if (reqInfo.options.body) {
batchBody.push(reqInfo.options.body + "\n\n");
}
}
if (currentChangeSetId.length > 0) {
// Close the changeset
batchBody.push("--changeset_" + currentChangeSetId + "--\n\n");
currentChangeSetId = "";
}
batchBody.push("--batch_" + _this.batchId + "--\n");
var batchOptions = {
"body": batchBody.join(""),
"headers": {
"Content-Type": "multipart/mixed; boundary=batch_" + _this.batchId,
},
"method": "POST",
};
logging.Logger.write("[" + _this.batchId + "] (" + (new Date()).getTime() + ") Sending batch request.", 1 /* Info */);
return client.fetch(common.combine(absoluteRequestUrl, "/_api/$batch"), batchOptions)
.then(function (r) { return r.text(); })
.then(SPBatch.ParseResponse)
.then(function (responses) {
if (responses.length !== _this.requests.length) {
throw Error("Could not properly parse responses to match requests in batch.");
}
logging.Logger.write("[" + _this.batchId + "] (" + (new Date()).getTime() + ") Resolving batched requests.", 1 /* Info */);
return responses.reduce(function (chain, response, index) {
var request = _this.requests[index];
logging.Logger.write("[" + request.id + "] (" + (new Date()).getTime() + ") Resolving request in batch " + _this.batchId + ".", 1 /* Info */);
return chain.then(function (_) { return request.parser.parse(response).then(request.resolve).catch(request.reject); });
}, Promise.resolve());
});
});
};
return SPBatch;
}(odata.ODataBatch));
(function (PromotedState) {
/**
* Regular client side page
*/
PromotedState[PromotedState["NotPromoted"] = 0] = "NotPromoted";
/**
* Page that will be promoted as news article after publishing
*/
PromotedState[PromotedState["PromoteOnPublish"] = 1] = "PromoteOnPublish";
/**
* Page that is promoted as news article
*/
PromotedState[PromotedState["Promoted"] = 2] = "Promoted";
})(exports.PromotedState || (exports.PromotedState = {}));
/**
* Gets the next order value 1 based for the provided collection
*
* @param collection Collection of orderable things
*/
function getNextOrder(collection) {
if (collection.length < 1) {
return 1;
}
return Math.max.apply(null, collection.map(function (i) { return i.order; })) + 1;
}
/**
* After https://stackoverflow.com/questions/273789/is-there-a-version-of-javascripts-string-indexof-that-allows-for-regular-expr/274094#274094
*
* @param this Types the called context this to a string in which the search will be conducted
* @param regex A regex or string to match
* @param startpos A starting position from which the search will begin
*/
function regexIndexOf(regex, startpos) {
if (startpos === void 0) { startpos = 0; }
var indexOf = this.substring(startpos).search(regex);
return (indexOf >= 0) ? (indexOf + (startpos)) : indexOf;
}
/**
* Finds bounded blocks of markup bounded by divs, ensuring to match the ending div even with nested divs in the interstitial markup
*
* @param html HTML to search
* @param boundaryStartPattern The starting pattern to find, typically a div with attribute
* @param collector A func to take the found block and provide a way to form it into a useful return that is added into the return array
*/
function getBoundedDivMarkup(html, boundaryStartPattern, collector) {
var blocks = [];
if (html === undefined || html === null) {
return blocks;
}
// remove some extra whitespace if present
var cleanedHtml = html.replace(/[\t\r\n]/g, "");
// find the first div
var startIndex = regexIndexOf.call(cleanedHtml, boundaryStartPattern);
if (startIndex < 0) {
// we found no blocks in the supplied html
return blocks;
}
// this loop finds each of the blocks
while (startIndex > -1) {
// we have one open div counting from the one found above using boundaryStartPattern so we need to ensure we find it's close
var openCounter = 1;
var searchIndex = startIndex + 1;
var nextDivOpen = -1;
var nextCloseDiv = -1;
// this loop finds the </div> tag that matches the opening of the control
while (true) {
// find both the next opening and closing div tags from our current searching index
nextDivOpen = regexIndexOf.call(cleanedHtml, /<div[^>]*>/i, searchIndex);
nextCloseDiv = regexIndexOf.call(cleanedHtml, /<\/div>/i, searchIndex);
if (nextDivOpen < 0) {
// we have no more opening divs, just set this to simplify checks below
nextDivOpen = cleanedHtml.length + 1;
}
// determine which we found first, then increment or decrement our counter
// and set the location to begin searching again
if (nextDivOpen < nextCloseDiv) {
openCounter++;
searchIndex = nextDivOpen + 1;
}
else if (nextCloseDiv < nextDivOpen) {
openCounter--;
searchIndex = nextCloseDiv + 1;
}
// once we have no open divs back to the level of the opening control div
// meaning we have all of the markup we intended to find
if (openCounter === 0) {
// get the bounded markup, +6 is the size of the ending </div> tag
var markup = cleanedHtml.substring(startIndex, nextCloseDiv + 6).trim();
// save the control data we found to the array
blocks.push(collector(markup));
// get out of our while loop
break;
}
if (openCounter > 1000 || openCounter < 0) {
// this is an arbitrary cut-off but likely we will not have 1000 nested divs
// something has gone wrong above and we are probably stuck in our while loop
// let's get out of our while loop and not hang everything
throw Error("getBoundedDivMarkup exceeded depth parameters.");
}
}
// get the start of the next control
startIndex = regexIndexOf.call(cleanedHtml, boundaryStartPattern, nextCloseDiv);
}
return blocks;
}
/**
* Normalizes the order value for all the sections, columns, and controls to be 1 based and stepped (1, 2, 3...)
*
* @param collection The collection to normalize
*/
function reindex(collection) {
for (var i = 0; i < collection.length; i++) {
collection[i].order = i + 1;
if (common.hOP(collection[i], "columns")) {
reindex(collection[i].columns);
}
else if (common.hOP(collection[i], "controls")) {
reindex(collection[i].controls);
}
}
}
/**
* Represents the data and methods associated with client side "modern" pages
*/
var ClientSidePage = /** @class */ (function (_super) {
__extends(ClientSidePage, _super);
/**
* Creates a new instance of the ClientSidePage class
*
* @param baseUrl The url or SharePointQueryable which forms the parent of this web collection
* @param commentsDisabled Indicates if comments are disabled, not valid until load is called
*/
function ClientSidePage(file, sections, commentsDisabled) {
if (sections === void 0) { sections = []; }
if (commentsDisabled === void 0) { commentsDisabled = false; }
var _this = _super.call(this, file) || this;
_this.sections = sections;
_this.commentsDisabled = commentsDisabled;
return _this;
}
/**
* Creates a new blank page within the supplied library
*
* @param library The library in which to create the page
* @param pageName Filename of the page, such as "page.aspx"
* @param title The display title of the page
* @param pageLayoutType Layout type of the page to use
*/
ClientSidePage.create = function (library, pageName, title, pageLayoutType) {
if (pageLayoutType === void 0) { pageLayoutType = "Article"; }
// see if file exists, if not create it
return library.rootFolder.files.select("Name").filter("Name eq '" + pageName + "'").get().then(function (fs) {
if (fs.length > 0) {
throw Error("A file with the name '" + pageName + "' already exists in the library '" + library.toUrl() + "'.");
}
// get our server relative path
return library.rootFolder.select("ServerRelativePath").get().then(function (path) {
var pageServerRelPath = common.combine("/", path.ServerRelativePath.DecodedUrl, pageName);
// add the template file
return library.rootFolder.files.addTemplateFile(pageServerRelPath, exports.TemplateFileType.ClientSidePage).then(function (far) {
// get the item associated with the file
return far.file.getItem().then(function (i) {
// update the item to have the correct values to create the client side page
return i.update({
BannerImageUrl: {
Url: "/_layouts/15/images/sitepagethumbnail.png",
},
CanvasContent1: "",
ClientSideApplicationId: "b6917cb1-93a0-4b97-a84d-7cf49975d4ec",
ContentTypeId: "0x0101009D1CB255DA76424F860D91F20E6C4118",
PageLayoutType: pageLayoutType,
PromotedState: 0 /* NotPromoted */,
Title: title,
}).then(function (iar) { return new ClientSidePage(iar.item.file, iar.item.CommentsDisabled); });
});
});
});
});
};
/**
* Creates a new ClientSidePage instance from the provided html content string
*
* @param html HTML markup representing the page
*/
ClientSidePage.fromFile = function (file) {
var page = new ClientSidePage(file);
return page.load().then(function (_) { return page; });
};
/**
* Converts a json object to an escaped string appropriate for use in attributes when storing client-side controls
*
* @param json The json object to encode into a string
*/
ClientSidePage.jsonToEscapedString = function (json) {
return common.jsS(json)
.replace(/"/g, """)
.replace(/:/g, ":")
.replace(/{/g, "{")
.replace(/}/g, "}")
.replace(/\[/g, "\[")
.replace(/\]/g, "\]")
.replace(/\./g, "\.");
};
/**
* Converts an escaped string from a client-side control attribute to a json object
*
* @param escapedString
*/
ClientSidePage.escapedStringToJson = function (escapedString) {
var unespace = function (escaped) {
var mapDict = [
[/"/g, "\""], [/:/g, ":"], [/{/g, "{"], [/}/g, "}"],
[/\\\\/g, "\\"], [/\\\?/g, "?"], [/\\\./g, "."], [/\\\[/g, "["], [/\\\]/g, "]"],
[/\\\(/g, "("], [/\\\)/g, ")"], [/\\\|/g, "|"], [/\\\+/g, "+"],
];
return mapDict.reduce(function (r, m) { return r.replace(m[0], m[1]); }, escaped);
};
return JSON.parse(unespace(escapedString));
};
/**
* Add a section to this page
*/
ClientSidePage.prototype.addSection = function () {
var section = new CanvasSection(this, getNextOrder(this.sections));
this.sections.push(section);
return section;
};
/**
* Converts this page's content to html markup
*/
ClientSidePage.prototype.toHtml = function () {
// trigger reindex of the entire tree
reindex(this.sections);
var html = [];
html.push("<div>");
for (var i = 0; i < this.sections.length; i++) {
html.push(this.sections[i].toHtml());
}
html.push("</div>");
return html.join("");
};
/**
* Loads this page instance's content from the supplied html
*
* @param html html string representing the page's content
*/
ClientSidePage.prototype.fromHtml = function (html) {
var _this = this;
// reset sections
this.sections = [];
// gather our controls from the supplied html
getBoundedDivMarkup(html, /<div\b[^>]*data-sp-canvascontrol[^>]*?>/i, function (markup) {
// get the control type
var ct = /controlType":(\d*?),/i.exec(markup);
// if no control type is present this is a column which we give type 0 to let us process it
var controlType = ct == null || ct.length < 2 ? 0 : parseInt(ct[1], 10);
var control = null;
switch (controlType) {
case 0:
// empty canvas column
control = new CanvasColumn(null, 0);
control.fromHtml(markup);
_this.mergeColumnToTree(control);
break;
case 3:
// client side webpart
control = new ClientSideWebpart("");
control.fromHtml(markup);
_this.mergePartToTree(control);
break;
case 4:
// client side text
control = new ClientSideText();
control.fromHtml(markup);
_this.mergePartToTree(control);
break;
}
});
// refresh all the orders within the tree
reindex(this.sections);
return this;
};
/**
* Loads this page's content from the server
*/
ClientSidePage.prototype.load = function () {
var _this = this;
return this.getItem("CanvasContent1", "CommentsDisabled").then(function (item) {
_this.fromHtml(item.CanvasContent1);
_this.commentsDisabled = item.CommentsDisabled;
});
};
/**
* Persists the content changes (sections, columns, and controls)
*/
ClientSidePage.prototype.save = function () {
return this.updateProperties({ CanvasContent1: this.toHtml() });
};
/**
* Enables comments on this page
*/
ClientSidePage.prototype.enableComments = function () {
var _this = this;
return this.setCommentsOn(true).then(function (r) {
_this.commentsDisabled = false;
return r;
});
};
/**
* Disables comments on this page
*/
ClientSidePage.prototype.disableComments = function () {
var _this = this;
return this.setCommentsOn(false).then(function (r) {
_this.commentsDisabled = true;
return r;
});
};
/**
* Finds a control by the specified instance id
*
* @param id Instance id of the control to find
*/
ClientSidePage.prototype.findControlById = function (id) {
return this.findControl(function (c) { return c.id === id; });
};
/**
* Finds a control within this page's control tree using the supplied predicate
*
* @param predicate Takes a control and returns true or false, if true that control is returned by findControl
*/
ClientSidePage.prototype.findControl = function (predicate) {
// check all sections
for (var i = 0; i < this.sections.length; i++) {
// check all columns
for (var j = 0; j < this.sections[i].columns.length; j++) {
// check all controls
for (var k = 0; k < this.sections[i].columns[j].controls.length; k++) {
// check to see if the predicate likes this control
if (predicate(this.sections[i].columns[j].controls[k])) {
return this.sections[i].columns[j].controls[k];
}
}
}
}
// we found nothing so give nothing back
return null;
};
/**
* Like the modern site page
*/
ClientSidePage.prototype.like = function () {
return this.getItem().then(function (i) {
return i.like();
});
};
/**
* Unlike the modern site page
*/
ClientSidePage.prototype.unlike = function () {
return this.getItem().then(function (i) {
return i.unlike();
});
};
/**
* Get the liked by information for a modern site page
*/
ClientSidePage.prototype.getLikedByInformation = function () {
return this.getItem().then(function (i) {
return i.getLikedByInformation();
});
};
/**
* Sets the comments flag for a page
*
* @param on If true comments are enabled, false they are disabled
*/
ClientSidePage.prototype.setCommentsOn = function (on) {
return this.getItem().then(function (i) {
var updater = new Item(i, "SetCommentsDisabled(" + !on + ")");
return updater.update({});
});
};
/**
* Merges the control into the tree of sections and columns for this page
*
* @param control The control to merge
*/
ClientSidePage.prototype.mergePartToTree = function (control) {
var section = null;
var column = null;
var sections = this.sections.filter(function (s) { return s.order === control.controlData.position.zoneIndex; });
if (sections.length < 1) {
section = new CanvasSection(this, control.controlData.position.zoneIndex);
this.sections.push(section);
}
else {
section = sections[0];
}
var columns = section.columns.filter(function (c) { return c.order === control.controlData.position.sectionIndex; });
if (columns.length < 1) {
column = new CanvasColumn(section, control.controlData.position.sectionIndex, control.controlData.position.sectionFactor);
section.columns.push(column);
}
else {
column = columns[0];
}
control.column = column;
column.addControl(control);
};
/**
* Merges the supplied column into the tree
*
* @param column Column to merge
* @param position The position data for the column
*/
ClientSidePage.prototype.mergeColumnToTree = function (column) {
var section = null;
var sections = this.sections.filter(function (s) { return s.order === column.controlData.position.zoneIndex; });
if (sections.length < 1) {
section = new CanvasSection(this, column.controlData.position.zoneIndex);
this.sections.push(section);
}
else {
section = sections[0];
}
column.section = section;
section.columns.push(column);
};
/**
* Updates the properties of the underlying ListItem associated with this ClientSidePage
*
* @param properties Set of properties to update
* @param eTag Value used in the IF-Match header, by default "*"
*/
ClientSidePage.prototype.updateProperties = function (properties, eTag) {
if (eTag === void 0) { eTag = "*"; }
return this.getItem().then(function (i) { return i.update(properties, eTag); });
};
return ClientSidePage;
}(File));
var CanvasSection = /** @class */ (function () {
function CanvasSection(page, order, columns) {
if (columns === void 0) { columns = []; }
this.page = page;
this.order = order;
this.columns = columns;
this._memId = common.getGUID();
}
Object.defineProperty(CanvasSection.prototype, "defaultColumn", {
/**
* Default column (this.columns[0]) for this section
*/
get: function () {
if (this.columns.length < 1) {
this.addColumn(12);
}
return this.columns[0];
},
enumerable: true,
configurable: true
});
/**
* Adds a new column to this section
*/
CanvasSection.prototype.addColumn = function (factor) {
var column = new CanvasColumn(this, getNextOrder(this.columns), factor);
this.columns.push(column);
return column;
};
/**
* Adds a control to the default column for this section
*
* @param control Control to add to the default column
*/
CanvasSection.prototype.addControl = function (control) {
this.defaultColumn.addControl(control);
return this;
};
CanvasSection.prototype.toHtml = function () {
var html = [];
for (var i = 0; i < this.columns.length; i++) {
html.push(this.columns[i].toHtml());
}
return html.join("");
};
/**
* Removes this section and all contained columns and controls from the collection
*/
CanvasSection.prototype.remove = function () {
var _this = this;
this.page.sections = this.page.sections.filter(function (section) { return section._memId !== _this._memId; });
reindex(this.page.sections);
};
return CanvasSection;
}());
var CanvasControl = /** @class */ (function () {
function CanvasControl(controlType, dataVersion, column, order, id, controlData) {
if (column === void 0) { column = null; }
if (order === void 0) { order = 1; }
if (id === void 0) { id = common.getGUID(); }
if (controlData === void 0) { controlData = null; }
this.controlType = controlType;
this.dataVersion = dataVersion;
this.column = column;
this.order = order;
this.id = id;
this.controlData = controlData;
}
Object.defineProperty(CanvasControl.prototype, "jsonData", {
/**
* Value of the control's "data-sp-controldata" attribute
*/
get: function () {
return ClientSidePage.jsonToEscapedString(this.getControlData());
},
enumerable: true,
configurable: true
});
CanvasControl.prototype.fromHtml = function (html) {
this.controlData = ClientSidePage.escapedStringToJson(common.getAttrValueFromString(html, "data-sp-controldata"));
this.dataVersion = common.getAttrValueFromString(html, "data-sp-canvasdataversion");
this.controlType = this.controlData.controlType;
this.id = this.controlData.id;
};
return CanvasControl;
}());
var CanvasColumn = /** @class */ (function (_super) {
__extends(CanvasColumn, _super);
function CanvasColumn(section, order, factor, controls, dataVersion) {
if (factor === void 0) { factor = 12; }
if (controls === void 0) { controls = []; }
if (dataVersion === void 0) { dataVersion = "1.0"; }
var _this = _super.call(this, 0, dataVersion) || this;
_this.section = section;
_this.order = order;
_this.factor = factor;
_this.controls = controls;
return _this;
}
CanvasColumn.prototype.addControl = function (control) {
control.column = this;
this.controls.push(control);
return this;
};
CanvasColumn.prototype.getControl = function (index) {
return this.controls[index];
};
CanvasColumn.prototype.toHtml = function () {
var html = [];
if (this.controls.length < 1) {
html.push("<div data-sp-canvascontrol=\"\" data-sp-canvasdataversion=\"" + this.dataVersion + "\" data-sp-controldata=\"" + this.jsonData + "\"></div>");
}
else {
for (var i = 0; i < this.controls.length; i++) {
html.push(this.controls[i].toHtml(i + 1));
}
}
return html.join("");
};
CanvasColumn.prototype.fromHtml = function (html) {
_super.prototype.fromHtml.call(this, html);
this.controlData = ClientSidePage.escapedStringToJson(common.getAttrValueFromString(html, "data-sp-controldata"));
this.factor = this.controlData.position.sectionFactor;
this.order = this.controlData.position.sectionIndex;
};
CanvasColumn.prototype.getControlData = function () {
return {
displayMode: 2,
position: {
sectionFactor: this.factor,
sectionIndex: this.order,
zoneIndex: this.section.order,
},
};
};
/**
* Removes this column and all contained controls from the collection
*/
CanvasColumn.prototype.remove = function () {
var _this = this;
this.section.columns = this.section.columns.filter(function (column) { return column.id !== _this.id; });
reindex(this.column.controls);
};
return CanvasColumn;
}(CanvasControl));
/**
* Abstract class with shared functionality for parts
*/
var ClientSidePart = /** @class */ (function (_super) {
__extends(ClientSidePart, _super);
function ClientSidePart() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Removes this column and all contained controls from the collection
*/
ClientSidePart.prototype.remove = function () {
var _this = this;
this.column.controls = this.column.controls.filter(function (control) { return control.id !== _this.id; });
reindex(this.column.controls);
};
return ClientSidePart;
}(CanvasControl));
var ClientSideText = /** @class */ (function (_super) {
__extends(ClientSideText, _super);
function ClientSideText(text) {
if (text === void 0) { text = ""; }
var _this = _super.call(this, 4, "1.0") || this;
_this.text = text;
return _this;
}
Object.defineProperty(ClientSideText.prototype, "text", {
/**
* The text markup of this control
*/
get: function () {
return this._text;
},
set: function (text) {
if (!text.startsWith("<p>")) {
text = "<p>" + text + "</p>";
}
this._text = text;
},
enumerable: true,
configurable: true
});
ClientSideText.prototype.getControlData = function () {
return {
controlType: this.controlType,
editorType: "CKEditor",
id: this.id,
position: {
controlIndex: this.order,
sectionFactor: this.column.factor,
sectionIndex: this.column.order,
zoneIndex: this.column.section.order,
},
};
};
ClientSideText.prototype.toHtml = function (index) {
// set our order to the value passed in
this.order = index;
var html = [];
html.push("<div data-sp-canvascontrol=\"\" data-sp-canvasdataversion=\"" + this.dataVersion + "\" data-sp-controldata=\"" + this.jsonData + "\">");
html.push("<div data-sp-rte=\"\">");
html.push("" + this.text);
html.push("</div>");
html.push("</div>");
return html.join("");
};
ClientSideText.prototype.fromHtml = function (html) {
var _this = this;
_super.prototype.fromHtml.call(this, html);
this.text = "";
getBoundedDivMarkup(html, /<div[^>]*data-sp-rte[^>]*>/i, function (s) {
// now we need to grab the inner text between the divs
var match = /<div[^>]*data-sp-rte[^>]*>(.*?)<\/div>$/i.exec(s);
_this.text = match.length > 1 ? match[1] : "";
});
};
return ClientSideText;
}(ClientSidePart));
var ClientSideWebpart = /** @class */ (function (_super) {
__extends(ClientSideWebpart, _super);
function ClientSideWebpart(title, description, propertieJson, webPartId, htmlProperties, serverProcessedContent, canvasDataVersion) {
if (description === void 0) { description = ""; }
if (propertieJson === void 0) { propertieJson = {}; }
if (webPartId === void 0) { webPartId = ""; }
if (htmlProperties === void 0) { htmlProperties = ""; }
if (serverProcessedContent === void 0) { serverProcessedContent = null; }
if (canvasDataVersion === void 0) { canvasDataVersion = "1.0"; }
var _this = _super.call(this, 3, "1.0") || this;
_this.title = title;
_this.description = description;
_this.propertieJson = propertieJson;
_this.webPartId = webPartId;
_this.htmlProperties = htmlProperties;
_this.serverProcessedContent = serverProcessedContent;
_this.canvasDataVersion = canvasDataVersion;
return _this;
}
ClientSideWebpart.fromComponentDef = function (definition) {
var part = new ClientSideWebpart("");
part.import(definition);
return part;
};
ClientSideWebpart.prototype.import = function (component) {
this.webPartId = component.Id.replace(/^\{|\}$/g, "").toLowerCase();
var manifest = JSON.parse(component.Manifest);
this.title = manifest.preconfiguredEntries[0].title.default;
this.description = manifest.preconfiguredEntries[0].description.default;
this.dataVersion = "1.0";
this.propertieJson = this.parseJsonProperties(manifest.preconfiguredEntries[0].properties);
};
ClientSideWebpart.prototype.setProperties = function (properties) {
this.propertieJson = common.extend(this.propertieJson, properties);
return this;
};
ClientSideWebpart.prototype.getProperties = function () {
return this.propertieJson;
};
ClientSideWebpart.prototype.toHtml = function (index) {
// set our order to the value passed in
this.order = index;
// will form the value of the data-sp-webpartdata attribute
var data = {
dataVersion: this.dataVersion,
description: this.description,
id: this.webPartId,
instanceId: this.id,
properties: this.propertieJson,
serverProcessedContent: this.serverProcessedContent,
title: this.title,
};
var html = [];
html.push("<div data-sp-canvascontrol=\"\" data-sp-canvasdataversion=\"" + this.canvasDataVersion + "\" data-sp-controldata=\"" + this.jsonData + "\">");
html.push("<div data-sp-webpart=\"\" data-sp-webpartdataversion=\"" + this.dataVersion + "\" data-sp-webpartdata=\"" + ClientSidePage.jsonToEscapedString(data) + "\">");
html.push("<div data-sp-componentid>");
html.push(this.webPartId);
html.push("</div>");
html.push("<div data-sp-htmlproperties=\"\">");
html.push(this.renderHtmlProperties());
html.push("</div>");
html.push("</div>");
html.push("</div>");
return html.join("");
};
ClientSideWebpart.prototype.fromHtml = function (html) {
_super.prototype.fromHtml.call(this, html);
var webPartData = ClientSidePage.escapedStringToJson(common.getAttrValueFromString(html, "data-sp-webpartdata"));
this.title = webPartData.title;
this.description = webPartData.description;
this.webPartId = webPartData.id;
this.canvasDataVersion = common.getAttrValueFromString(html, "data-sp-canvasdataversion").replace(/\\\./, ".");
this.dataVersion = common.getAttrValueFromString(html, "data-sp-webpartdataversion").replace(/\\\./, ".");
this.setProperties(webPartData.properties);
if (webPartData.serverProcessedContent !== undefined) {
this.serverProcessedContent = webPartData.serverProcessedContent;
}
// get our html properties
var htmlProps = getBoundedDivMarkup(html, /<div\b[^>]*data-sp-htmlproperties[^>]*?>/i, function (markup) {
return markup.replace(/^<div\b[^>]*data-sp-htmlproperties[^>]*?>/i, "").replace(/<\/div>$/i, "");
});
this.htmlProperties = htmlProps.length > 0 ? htmlProps[0] : "";
};
ClientSideWebpart.prototype.getControlData = function () {
return {
controlType: this.controlType,
id: this.id,
position: {
controlIndex: this.order,
sectionFactor: this.column.factor,
sectionIndex: this.column.order,
zoneIndex: this.column.section.order,
},
webPartId: this.webPartId,
};
};
ClientSideWebpart.prototype.renderHtmlProperties = function () {
var html = [];
if (this.serverProcessedContent === undefined || this.serverProcessedContent === null) {
html.push(this.htmlProperties);
}
else if (this.serverProcessedContent !== undefined) {
if (this.serverProcessedContent.searchablePlainTexts !== undefined) {
var keys = Object.keys(this.serverProcessedContent.searchablePlainTexts);
for (var i = 0; i < keys.length; i++) {
html.push("<div data-sp-prop-name=\"" + keys[i] + "\" data-sp-searchableplaintext=\"true\">");
html.push(this.serverProcessedContent.searchablePlainTexts[keys[i]]);
html.push("</div>");
}
}
if (this.serverProcessedContent.imageSources !== undefined) {
var keys = Object.keys(this.serverProcessedContent.imageSources);
for (var i = 0; i < keys.length; i++) {
html.push("<img data-sp-prop-name=\"" + keys[i] + "\" src=\"" + this.serverProcessedContent.imageSources[keys[i]] + "\" />");
}
}
if (this.serverProcessedContent.links !== undefined) {
var keys = Object.keys(this.serverProcessedContent.links);
for (var i = 0; i < keys.length; i++) {
html.push("<a data-sp-prop-name=\"" + keys[i] + "\" href=\"" + this.serverProcessedContent.links[keys[i]] + "\"></a>");
}
}
}
return html.join("");
};
ClientSideWebpart.prototype.parseJsonProperties = function (props) {
// If the web part has the serverProcessedContent property then keep this one as it might be needed as input to render the web part HTML later on
if (props.webPartData !== undefined && props.webPartData.serverProcessedContent !== undefined) {
this.serverProcessedContent = props.webPartData.serverProcessedContent;
}
else if (props.serverProcessedContent !== undefined) {
this.serverProcessedContent = props.serverProcessedContent;
}
else {
this.serverProcessedContent = null;
}
if (props.webPartData !== undefined && props.webPartData.properties !== undefined) {
return props.webPartData.properties;
}
else if (props.properties !== undefined) {
return props.properties;
}
else {
return props;
}
};
return ClientSideWebpart;
}(ClientSidePart));
/**
* Represents a collection of navigation nodes
*
*/
var NavigationNodes = /** @class */ (function (_super) {
__extends(NavigationNodes, _super);
function NavigationNodes() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Gets a navigation node by id
*
* @param id The id of the node
*/
NavigationNodes.prototype.getById = function (id) {
var node = new NavigationNode(this);
node.concat("(" + id + ")");
return node;
};
/**
* Adds a new node to the collection
*
* @param title Display name of the node
* @param url The url of the node
* @param visible If true the node is visible, otherwise it is hidden (default: true)
*/
NavigationNodes.prototype.add = function (title, url, visible) {
var _this = this;
if (visible === void 0) { visible = true; }
var postBody = common.jsS(common.extend(metadata("SP.NavigationNode"), {
IsVisible: visible,
Title: title,
Url: url,
}));
return this.clone(NavigationNodes, null).postCore({ body: postBody }).then(function (data) {
return {
data: data,
node: _this.getById(data.Id),
};
});
};
/**
* Moves a node to be after another node in the navigation
*
* @param nodeId Id of the node to move
* @param previousNodeId Id of the node after which we move the node specified by nodeId
*/
NavigationNodes.prototype.moveAfter = function (nodeId, previousNodeId) {
var postBody = common.jsS({
nodeId: nodeId,
previousNodeId: previousNodeId,
});
return this.clone(NavigationNodes, "MoveAfter").postCore({ body: postBody });
};
return NavigationNodes;
}(SharePointQueryableCollection));
/**
* Represents an instance of a navigation node
*
*/
var NavigationNode = /** @class */ (function (_super) {
__extends(NavigationNode, _super);
function NavigationNode() {
return _super !== null && _super.apply(this, arguments) || this;
}
Object.defineProperty(NavigationNode.prototype, "children", {
/**
* Represents the child nodes of this node
*/
get: function () {
return new NavigationNodes(this, "Children");
},
enumerable: true,
configurable: true
});
/**
* Deletes this node and any child nodes
*/
NavigationNode.prototype.delete = function () {
return _super.prototype.deleteCore.call(this);
};
return NavigationNode;
}(SharePointQueryableInstance));
/**
* Exposes the navigation components
*
*/
var Navigation = /** @class */ (function (_super) {
__extends(Navigation, _super);
function Navigation() {
return _super !== null && _super.apply(this, arguments) || this;
}
Object.defineProperty(Navigation.prototype, "quicklaunch", {
/**
* Gets the quicklaunch navigation nodes for the current context
*
*/
get: function () {
return new NavigationNodes(this, "quicklaunch");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Navigation.prototype, "topNavigationBar", {
/**
* Gets the top bar navigation nodes for the current context
*
*/
get: function () {
return new NavigationNodes(this, "topnavigationbar");
},
enumerable: true,
configurable: true
});
Navigation = __decorate([
defaultPath("navigation")
], Navigation);
return Navigation;
}(SharePointQueryable));
/**
* Represents the top level navigation service
*/
var NavigationService = /** @class */ (function (_super) {
__extends(NavigationService, _super);
function NavigationService(path) {
if (path === void 0) { path = null; }
return _super.call(this, "_api/navigation", path) || this;
}
/**
* The MenuState service operation returns a Menu-State (dump) of a SiteMapProvider on a site.
*
* @param menuNodeKey MenuNode.Key of the start node within the SiteMapProvider If no key is provided the SiteMapProvider.RootNode will be the root of the menu state.
* @param depth Depth of the dump. If no value is provided a dump with the depth of 10 is returned
* @param mapProviderName The name identifying the SiteMapProvider to be used
* @param customProperties comma seperated list of custom properties to be returned.
*/
NavigationService.prototype.getMenuState = function (menuNodeKey, depth, mapProviderName, customProperties) {
if (menuNodeKey === void 0) { menuNodeKey = null; }
if (depth === void 0) { depth = 10; }
if (mapProviderName === void 0) { mapProviderName = null; }
if (customProperties === void 0) { customProperties = null; }
return (new NavigationService("MenuState")).postCore({
body: common.jsS({
customProperties: customProperties,
depth: depth,
mapProviderName: mapProviderName,
menuNodeKey: menuNodeKey,
}),
});
};
/**
* Tries to get a SiteMapNode.Key for a given URL within a site collection.
*
* @param currentUrl A url representing the SiteMapNode
* @param mapProviderName The name identifying the SiteMapProvider to be used
*/
NavigationService.prototype.getMenuNodeKey = function (currentUrl, mapProviderName) {
if (mapProviderName === void 0) { mapProviderName = null; }
return (new NavigationService("MenuNodeKey")).postCore({
body: common.jsS({
currentUrl: currentUrl,
mapProviderName: mapProviderName,
}),
});
};
return NavigationService;
}(SharePointQueryable));
/**
* Describes regional settings ODada object
*/
var RegionalSettings = /** @class */ (function (_super) {
__extends(RegionalSettings, _super);
function RegionalSettings() {
return _super !== null && _super.apply(this, arguments) || this;
}
Object.defineProperty(RegionalSettings.prototype, "installedLanguages", {
/**
* Gets the collection of languages used in a server farm.
*/
get: function () {
return new InstalledLanguages(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(RegionalSettings.prototype, "globalInstalledLanguages", {
/**
* Gets the collection of language packs that are installed on the server.
*/
get: function () {
return new InstalledLanguages(this, "globalinstalledlanguages");
},
enumerable: true,
configurable: true
});
Object.defineProperty(RegionalSettings.prototype, "timeZone", {
/**
* Gets time zone
*/
get: function () {
return new TimeZone(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(RegionalSettings.prototype, "timeZones", {
/**
* Gets time zones
*/
get: function () {
return new TimeZones(this);
},
enumerable: true,
configurable: true
});
RegionalSettings = __decorate([
defaultPath("regionalsettings")
], RegionalSettings);
return RegionalSettings;
}(SharePointQueryableInstance));
/**
* Describes installed languages ODada queriable collection
*/
var InstalledLanguages = /** @class */ (function (_super) {
__extends(InstalledLanguages, _super);
function InstalledLanguages() {
return _super !== null && _super.apply(this, arguments) || this;
}
InstalledLanguages = __decorate([
defaultPath("installedlanguages")
], InstalledLanguages);
return InstalledLanguages;
}(SharePointQueryableCollection));
/**
* Describes TimeZone ODada object
*/
var TimeZone = /** @class */ (function (_super) {
__extends(TimeZone, _super);
function TimeZone() {
return _super !== null && _super.apply(this, arguments) || this;
}
TimeZone_1 = TimeZone;
/**
* Gets an Local Time by UTC Time
*
* @param utcTime UTC Time as Date or ISO String
*/
TimeZone.prototype.utcToLocalTime = function (utcTime) {
var dateIsoString;
if (typeof utcTime === "string") {
dateIsoString = utcTime;
}
else {
dateIsoString = utcTime.toISOString();
}
return this.clone(TimeZone_1, "utctolocaltime('" + dateIsoString + "')")
.postCore()
.then(function (res) { return common.hOP(res, "UTCToLocalTime") ? res.UTCToLocalTime : res; });
};
/**
* Gets an UTC Time by Local Time
*
* @param localTime Local Time as Date or ISO String
*/
TimeZone.prototype.localTimeToUTC = function (localTime) {
var dateIsoString;
if (typeof localTime === "string") {
dateIsoString = localTime;
}
else {
dateIsoString = common.dateAdd(localTime, "minute", localTime.getTimezoneOffset() * -1).toISOString();
}
return this.clone(TimeZone_1, "localtimetoutc('" + dateIsoString + "')")
.postCore()
.then(function (res) { return common.hOP(res, "LocalTimeToUTC") ? res.LocalTimeToUTC : res; });
};
var TimeZone_1;
TimeZone = TimeZone_1 = __decorate([
defaultPath("timezone")
], TimeZone);
return TimeZone;
}(SharePointQueryableInstance));
/**
* Describes time zones queriable collection
*/
var TimeZones = /** @class */ (function (_super) {
__extends(TimeZones, _super);
function TimeZones() {
return _super !== null && _super.apply(this, arguments) || this;
}
TimeZones_1 = TimeZones;
// https://msdn.microsoft.com/en-us/library/office/jj247008.aspx - timezones ids
/**
* Gets an TimeZone by id
*
* @param id The integer id of the timezone to retrieve
*/
TimeZones.prototype.getById = function (id) {
// do the post and merge the result into a TimeZone instance so the data and methods are available
return this.clone(TimeZones_1, "GetById(" + id + ")").postCore({}, spODataEntity(TimeZone));
};
var TimeZones_1;
TimeZones = TimeZones_1 = __decorate([
defaultPath("timezones")
], TimeZones);
return TimeZones;
}(SharePointQueryableCollection));
var funcs = new Map([
["text", "Querytext"],
["template", "QueryTemplate"],
["sourceId", "SourceId"],
["trimDuplicatesIncludeId", ""],
["startRow", ""],
["rowLimit", ""],
["rankingModelId", ""],
["rowsPerPage", ""],
["selectProperties", ""],
["culture", ""],
["timeZoneId", ""],
["refinementFilters", ""],
["refiners", ""],
["hiddenConstraints", ""],
["sortList", ""],
["timeout", ""],
["hithighlightedProperties", ""],
["clientType", ""],
["personalizationData", ""],
["resultsURL", ""],
["queryTag", ""],
["properties", ""],
["queryTemplatePropertiesUrl", ""],
["reorderingRules", ""],
["hitHighlightedMultivaluePropertyLimit", ""],
["collapseSpecification", ""],
["uiLanguage", ""],
["desiredSnippetLength", ""],
["maxSnippetLength", ""],
["summaryLength", ""],
]);
var props = new Map([]);
function toPropCase(str) {
return str.replace(/^(.)/, function ($1) { return $1.toUpperCase(); });
}
/**
* Creates a new instance of the SearchQueryBuilder
*
* @param queryText Initial query text
* @param _query Any initial query configuration
*/
function SearchQueryBuilder(queryText, _query) {
if (queryText === void 0) { queryText = ""; }
if (_query === void 0) { _query = {}; }
return new Proxy({
query: Object.assign({
Querytext: queryText,
}, _query),
}, {
get: function (self, propertyKey, proxy) {
var pk = propertyKey.toString();
if (pk === "toSearchQuery") {
return function () { return self.query; };
}
if (funcs.has(pk)) {
return function () {
var value = [];
for (var _i = 0; _i < arguments.length; _i++) {
value[_i] = arguments[_i];
}
var mappedPk = funcs.get(pk);
self.query[mappedPk.length > 0 ? mappedPk : toPropCase(pk)] = value.length > 1 ? value : value[0];
return proxy;
};
}
var propKey = props.has(pk) ? props.get(pk) : toPropCase(pk);
self.query[propKey] = true;
return proxy;
},
});
}
/**
* Describes the search API
*
*/
var Search = /** @class */ (function (_super) {
__extends(Search, _super);
function Search() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* @returns Promise
*/
Search.prototype.execute = function (queryInit) {
var _this = this;
var query = this.parseQuery(queryInit);
var postBody = common.jsS({
request: common.extend(metadata("Microsoft.Office.Server.Search.REST.SearchRequest"), Object.assign({}, query, {
HitHighlightedProperties: this.fixArrProp(query.HitHighlightedProperties),
Properties: this.fixArrProp(query.Properties),
QueryTag: this.fixArrProp(query.QueryTag),
RefinementFilters: this.fixArrProp(query.RefinementFilters),
ReorderingRules: this.fixArrProp(query.ReorderingRules),
SelectProperties: this.fixArrProp(query.SelectProperties),
SortList: this.fixArrProp(query.SortList),
})),
});
// if we are using caching with this search request, then we need to handle some work upfront to enable that
if (this._useCaching) {
// force use of the cache for this request if .usingCaching was called
this._forceCaching = true;
// because all the requests use the same url they would collide in the cache we use a special key
var cacheKey = "PnPjs.SearchWithCaching(" + common.getHashCode(postBody) + ")";
if (common.objectDefinedNotNull(this._cachingOptions)) {
// if our key ends in the postquery url we overwrite it
if (/\/_api\/search\/postquery$/i.test(this._cachingOptions.key)) {
this._cachingOptions.key = cacheKey;
}
}
else {
this._cachingOptions = new odata.CachingOptions(cacheKey);
}
}
return this.postCore({ body: postBody }).then(function (data) { return new SearchResults(data, _this.toUrl(), query); });
};
/**
* Fix array property
*
* @param prop property to fix for container struct
*/
Search.prototype.fixArrProp = function (prop) {
if (typeof prop === "undefined") {
return ({ results: [] });
}
prop = common.isArray(prop) ? prop : [prop];
return common.hOP(prop, "results") ? prop : { results: prop };
};
/**
* Translates one of the query initializers into a SearchQuery instance
*
* @param query
*/
Search.prototype.parseQuery = function (query) {
var finalQuery;
if (typeof query === "string") {
finalQuery = { Querytext: query };
}
else if (query.toSearchQuery) {
finalQuery = query.toSearchQuery();
}
else {
finalQuery = query;
}
return finalQuery;
};
Search = __decorate([
defaultPath("_api/search/postquery")
], Search);
return Search;
}(SharePointQueryableInstance));
/**
* Describes the SearchResults class, which returns the formatted and raw version of the query response
*/
var SearchResults = /** @class */ (function () {
/**
* Creates a new instance of the SearchResult class
*
*/
function SearchResults(rawResponse, _url, _query, _raw, _primary) {
if (_raw === void 0) { _raw = null; }
if (_primary === void 0) { _primary = null; }
this._url = _url;
this._query = _query;
this._raw = _raw;
this._primary = _primary;
this._raw = rawResponse.postquery ? rawResponse.postquery : rawResponse;
}
Object.defineProperty(SearchResults.prototype, "ElapsedTime", {
get: function () {
return this.RawSearchResults.ElapsedTime;
},
enumerable: true,
configurable: true
});
Object.defineProperty(SearchResults.prototype, "RowCount", {
get: function () {
return this.RawSearchResults.PrimaryQueryResult.RelevantResults.RowCount;
},
enumerable: true,
configurable: true
});
Object.defineProperty(SearchResults.prototype, "TotalRows", {
get: function () {
return this.RawSearchResults.PrimaryQueryResult.RelevantResults.TotalRows;
},
enumerable: true,
configurable: true
});
Object.defineProperty(SearchResults.prototype, "TotalRowsIncludingDuplicates", {
get: function () {
return this.RawSearchResults.PrimaryQueryResult.RelevantResults.TotalRowsIncludingDuplicates;
},
enumerable: true,
configurable: true
});
Object.defineProperty(SearchResults.prototype, "RawSearchResults", {
get: function () {
return this._raw;
},
enumerable: true,
configurable: true
});
Object.defineProperty(SearchResults.prototype, "PrimarySearchResults", {
get: function () {
if (this._primary === null) {
this._primary = this.formatSearchResults(this._raw.PrimaryQueryResult.RelevantResults.Table.Rows);
}
return this._primary;
},
enumerable: true,
configurable: true
});
/**
* Gets a page of results
*
* @param pageNumber Index of the page to return. Used to determine StartRow
* @param pageSize Optional, items per page (default = 10)
*/
SearchResults.prototype.getPage = function (pageNumber, pageSize) {
// if we got all the available rows we don't have another page
if (this.TotalRows < this.RowCount) {
return Promise.resolve(null);
}
// if pageSize is supplied, then we use that regardless of any previous values
// otherwise get the previous RowLimit or default to 10
var rows = pageSize !== undefined ? pageSize : common.hOP(this._query, "RowLimit") ? this._query.RowLimit : 10;
var query = common.extend(this._query, {
RowLimit: rows,
StartRow: rows * (pageNumber - 1),
});
// we have reached the end
if (query.StartRow > this.TotalRows) {
return Promise.resolve(null);
}
var search = new Search(this._url, null);
return search.execute(query);
};
/**
* Formats a search results array
*
* @param rawResults The array to process
*/
SearchResults.prototype.formatSearchResults = function (rawResults) {
var results = new Array();
var tempResults = rawResults.results ? rawResults.results : rawResults;
for (var _i = 0, tempResults_1 = tempResults; _i < tempResults_1.length; _i++) {
var tempResult = tempResults_1[_i];
var cells = tempResult.Cells.results ? tempResult.Cells.results : tempResult.Cells;
results.push(cells.reduce(function (res, cell) {
Object.defineProperty(res, cell.Key, {
configurable: false,
enumerable: true,
value: cell.Value,
writable: false,
});
return res;
}, {}));
}
return results;
};
return SearchResults;
}());
(function (SortDirection) {
SortDirection[SortDirection["Ascending"] = 0] = "Ascending";
SortDirection[SortDirection["Descending"] = 1] = "Descending";
SortDirection[SortDirection["FQLFormula"] = 2] = "FQLFormula";
})(exports.SortDirection || (exports.SortDirection = {}));
(function (ReorderingRuleMatchType) {
ReorderingRuleMatchType[ReorderingRuleMatchType["ResultContainsKeyword"] = 0] = "ResultContainsKeyword";
ReorderingRuleMatchType[ReorderingRuleMatchType["TitleContainsKeyword"] = 1] = "TitleContainsKeyword";
ReorderingRuleMatchType[ReorderingRuleMatchType["TitleMatchesKeyword"] = 2] = "TitleMatchesKeyword";
ReorderingRuleMatchType[ReorderingRuleMatchType["UrlStartsWith"] = 3] = "UrlStartsWith";
ReorderingRuleMatchType[ReorderingRuleMatchType["UrlExactlyMatches"] = 4] = "UrlExactlyMatches";
ReorderingRuleMatchType[ReorderingRuleMatchType["ContentTypeIs"] = 5] = "ContentTypeIs";
ReorderingRuleMatchType[ReorderingRuleMatchType["FileExtensionMatches"] = 6] = "FileExtensionMatches";
ReorderingRuleMatchType[ReorderingRuleMatchType["ResultHasTag"] = 7] = "ResultHasTag";
ReorderingRuleMatchType[ReorderingRuleMatchType["ManualCondition"] = 8] = "ManualCondition";
})(exports.ReorderingRuleMatchType || (exports.ReorderingRuleMatchType = {}));
(function (QueryPropertyValueType) {
QueryPropertyValueType[QueryPropertyValueType["None"] = 0] = "None";
QueryPropertyValueType[QueryPropertyValueType["StringType"] = 1] = "StringType";
QueryPropertyValueType[QueryPropertyValueType["Int32Type"] = 2] = "Int32Type";
QueryPropertyValueType[QueryPropertyValueType["BooleanType"] = 3] = "BooleanType";
QueryPropertyValueType[QueryPropertyValueType["StringArrayType"] = 4] = "StringArrayType";
QueryPropertyValueType[QueryPropertyValueType["UnSupportedType"] = 5] = "UnSupportedType";
})(exports.QueryPropertyValueType || (exports.QueryPropertyValueType = {}));
var SearchBuiltInSourceId = /** @class */ (function () {
function SearchBuiltInSourceId() {
}
SearchBuiltInSourceId.Documents = "e7ec8cee-ded8-43c9-beb5-436b54b31e84";
SearchBuiltInSourceId.ItemsMatchingContentType = "5dc9f503-801e-4ced-8a2c-5d1237132419";
SearchBuiltInSourceId.ItemsMatchingTag = "e1327b9c-2b8c-4b23-99c9-3730cb29c3f7";
SearchBuiltInSourceId.ItemsRelatedToCurrentUser = "48fec42e-4a92-48ce-8363-c2703a40e67d";
SearchBuiltInSourceId.ItemsWithSameKeywordAsThisItem = "5c069288-1d17-454a-8ac6-9c642a065f48";
SearchBuiltInSourceId.LocalPeopleResults = "b09a7990-05ea-4af9-81ef-edfab16c4e31";
SearchBuiltInSourceId.LocalReportsAndDataResults = "203fba36-2763-4060-9931-911ac8c0583b";
SearchBuiltInSourceId.LocalSharePointResults = "8413cd39-2156-4e00-b54d-11efd9abdb89";
SearchBuiltInSourceId.LocalVideoResults = "78b793ce-7956-4669-aa3b-451fc5defebf";
SearchBuiltInSourceId.Pages = "5e34578e-4d08-4edc-8bf3-002acf3cdbcc";
SearchBuiltInSourceId.Pictures = "38403c8c-3975-41a8-826e-717f2d41568a";
SearchBuiltInSourceId.Popular = "97c71db1-58ce-4891-8b64-585bc2326c12";
SearchBuiltInSourceId.RecentlyChangedItems = "ba63bbae-fa9c-42c0-b027-9a878f16557c";
SearchBuiltInSourceId.RecommendedItems = "ec675252-14fa-4fbe-84dd-8d098ed74181";
SearchBuiltInSourceId.Wiki = "9479bf85-e257-4318-b5a8-81a180f5faa1";
return SearchBuiltInSourceId;
}());
var SearchSuggest = /** @class */ (function (_super) {
__extends(SearchSuggest, _super);
function SearchSuggest() {
return _super !== null && _super.apply(this, arguments) || this;
}
SearchSuggest.prototype.execute = function (query) {
this.mapQueryToQueryString(query);
return this.get().then(function (response) {
var mapper = common.hOP(response, "suggest") ? function (s) { return response.suggest[s].results; } : function (s) { return response[s]; };
return {
PeopleNames: mapper("PeopleNames"),
PersonalResults: mapper("PersonalResults"),
Queries: mapper("Queries"),
};
});
};
SearchSuggest.prototype.mapQueryToQueryString = function (query) {
var _this = this;
var setProp = function (q) { return function (checkProp) { return function (sp) {
if (common.hOP(q, checkProp)) {
_this.query.set(sp, q[checkProp].toString());
}
}; }; };
this.query.set("querytext", "'" + query.querytext + "'");
var querySetter = setProp(query);
querySetter("count")("inumberofquerysuggestions");
querySetter("personalCount")("inumberofresultsuggestions");
querySetter("preQuery")("fprequerysuggestions");
querySetter("hitHighlighting")("fhithighlighting");
querySetter("capitalize")("fcapitalizefirstletters");
querySetter("culture")("culture");
querySetter("stemming")("enablestemming");
querySetter("includePeople")("showpeoplenamesuggestions");
querySetter("queryRules")("enablequeryrules");
querySetter("prefixMatch")("fprefixmatchallterms");
};
SearchSuggest = __decorate([
defaultPath("_api/search/suggest")
], SearchSuggest);
return SearchSuggest;
}(SharePointQueryableInstance));
/**
* Describes a collection of List objects
*
*/
var Features = /** @class */ (function (_super) {
__extends(Features, _super);
function Features() {
return _super !== null && _super.apply(this, arguments) || this;
}
Features_1 = Features;
/**
* Adds a new list to the collection
*
* @param id The Id of the feature (GUID)
* @param force If true the feature activation will be forced
*/
Features.prototype.add = function (id, force) {
var _this = this;
if (force === void 0) { force = false; }
return this.clone(Features_1, "add").postCore({
body: common.jsS({
featdefScope: 0,
featureId: id,
force: force,
}),
}).then(function (data) {
return {
data: data,
feature: _this.getById(id),
};
});
};
/**
* Gets a list from the collection by guid id
*
* @param id The Id of the feature (GUID)
*/
Features.prototype.getById = function (id) {
var feature = new Feature(this);
feature.concat("('" + id + "')");
return feature;
};
/**
* Removes (deactivates) a feature from the collection
*
* @param id The Id of the feature (GUID)
* @param force If true the feature deactivation will be forced
*/
Features.prototype.remove = function (id, force) {
if (force === void 0) { force = false; }
return this.clone(Features_1, "remove").postCore({
body: common.jsS({
featureId: id,
force: force,
}),
});
};
var Features_1;
Features = Features_1 = __decorate([
defaultPath("features")
], Features);
return Features;
}(SharePointQueryableCollection));
var Feature = /** @class */ (function (_super) {
__extends(Feature, _super);
function Feature() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Removes (deactivates) a feature from the collection
*
* @param force If true the feature deactivation will be forced
*/
Feature.prototype.deactivate = function (force) {
var _this = this;
if (force === void 0) { force = false; }
var removeDependency = this.addBatchDependency();
var idGet = new Feature(this).select("DefinitionId");
return idGet.get().then(function (feature) {
var promise = _this.getParent(Features, _this.parentUrl, "", _this.batch).remove(feature.DefinitionId, force);
removeDependency();
return promise;
});
};
return Feature;
}(SharePointQueryableInstance));
var RelatedItemManagerImpl = /** @class */ (function (_super) {
__extends(RelatedItemManagerImpl, _super);
function RelatedItemManagerImpl() {
return _super !== null && _super.apply(this, arguments) || this;
}
RelatedItemManagerImpl_1 = RelatedItemManagerImpl;
RelatedItemManagerImpl.FromUrl = function (url) {
if (url === null) {
return new RelatedItemManagerImpl_1("");
}
var index = url.indexOf("_api/");
if (index > -1) {
return new RelatedItemManagerImpl_1(url.substr(0, index));
}
return new RelatedItemManagerImpl_1(url);
};
RelatedItemManagerImpl.prototype.getRelatedItems = function (sourceListName, sourceItemId) {
var query = this.clone(RelatedItemManagerImpl_1, null);
query.concat(".GetRelatedItems");
return query.postCore({
body: common.jsS({
SourceItemID: sourceItemId,
SourceListName: sourceListName,
}),
});
};
RelatedItemManagerImpl.prototype.getPageOneRelatedItems = function (sourceListName, sourceItemId) {
var query = this.clone(RelatedItemManagerImpl_1, null);
query.concat(".GetPageOneRelatedItems");
return query.postCore({
body: common.jsS({
SourceItemID: sourceItemId,
SourceListName: sourceListName,
}),
});
};
RelatedItemManagerImpl.prototype.addSingleLink = function (sourceListName, sourceItemId, sourceWebUrl, targetListName, targetItemID, targetWebUrl, tryAddReverseLink) {
if (tryAddReverseLink === void 0) { tryAddReverseLink = false; }
var query = this.clone(RelatedItemManagerImpl_1, null);
query.concat(".AddSingleLink");
return query.postCore({
body: common.jsS({
SourceItemID: sourceItemId,
SourceListName: sourceListName,
SourceWebUrl: sourceWebUrl,
TargetItemID: targetItemID,
TargetListName: targetListName,
TargetWebUrl: targetWebUrl,
TryAddReverseLink: tryAddReverseLink,
}),
});
};
/**
* Adds a related item link from an item specified by list name and item id, to an item specified by url
*
* @param sourceListName The source list name or list id
* @param sourceItemId The source item id
* @param targetItemUrl The target item url
* @param tryAddReverseLink If set to true try to add the reverse link (will not return error if it fails)
*/
RelatedItemManagerImpl.prototype.addSingleLinkToUrl = function (sourceListName, sourceItemId, targetItemUrl, tryAddReverseLink) {
if (tryAddReverseLink === void 0) { tryAddReverseLink = false; }
var query = this.clone(RelatedItemManagerImpl_1, null);
query.concat(".AddSingleLinkToUrl");
return query.postCore({
body: common.jsS({
SourceItemID: sourceItemId,
SourceListName: sourceListName,
TargetItemUrl: targetItemUrl,
TryAddReverseLink: tryAddReverseLink,
}),
});
};
/**
* Adds a related item link from an item specified by url, to an item specified by list name and item id
*
* @param sourceItemUrl The source item url
* @param targetListName The target list name or list id
* @param targetItemId The target item id
* @param tryAddReverseLink If set to true try to add the reverse link (will not return error if it fails)
*/
RelatedItemManagerImpl.prototype.addSingleLinkFromUrl = function (sourceItemUrl, targetListName, targetItemId, tryAddReverseLink) {
if (tryAddReverseLink === void 0) { tryAddReverseLink = false; }
var query = this.clone(RelatedItemManagerImpl_1, null);
query.concat(".AddSingleLinkFromUrl");
return query.postCore({
body: common.jsS({
SourceItemUrl: sourceItemUrl,
TargetItemID: targetItemId,
TargetListName: targetListName,
TryAddReverseLink: tryAddReverseLink,
}),
});
};
RelatedItemManagerImpl.prototype.deleteSingleLink = function (sourceListName, sourceItemId, sourceWebUrl, targetListName, targetItemId, targetWebUrl, tryDeleteReverseLink) {
if (tryDeleteReverseLink === void 0) { tryDeleteReverseLink = false; }
var query = this.clone(RelatedItemManagerImpl_1, null);
query.concat(".DeleteSingleLink");
return query.postCore({
body: common.jsS({
SourceItemID: sourceItemId,
SourceListName: sourceListName,
SourceWebUrl: sourceWebUrl,
TargetItemID: targetItemId,
TargetListName: targetListName,
TargetWebUrl: targetWebUrl,
TryDeleteReverseLink: tryDeleteReverseLink,
}),
});
};
var RelatedItemManagerImpl_1;
RelatedItemManagerImpl = RelatedItemManagerImpl_1 = __decorate([
defaultPath("_api/SP.RelatedItemManager")
], RelatedItemManagerImpl);
return RelatedItemManagerImpl;
}(SharePointQueryable));
/**
* Describes a collection of webs
*
*/
var Webs = /** @class */ (function (_super) {
__extends(Webs, _super);
function Webs() {
return _super !== null && _super.apply(this, arguments) || this;
}
Webs_1 = Webs;
/**
* Adds a new web to the collection
*
* @param title The new web's title
* @param url The new web's relative url
* @param description The new web's description
* @param template The new web's template internal name (default = STS)
* @param language The locale id that specifies the new web's language (default = 1033 [English, US])
* @param inheritPermissions When true, permissions will be inherited from the new web's parent (default = true)
*/
Webs.prototype.add = function (title, url, description, template, language, inheritPermissions) {
if (description === void 0) { description = ""; }
if (template === void 0) { template = "STS"; }
if (language === void 0) { language = 1033; }
if (inheritPermissions === void 0) { inheritPermissions = true; }
var props = {
Description: description,
Language: language,
Title: title,
Url: url,
UseSamePermissionsAsParentSite: inheritPermissions,
WebTemplate: template,
};
var postBody = common.jsS({
"parameters": common.extend({
"__metadata": { "type": "SP.WebCreationInformation" },
}, props),
});
return this.clone(Webs_1, "add").postCore({ body: postBody }).then(function (data) {
return {
data: data,
web: new Web(odataUrlFrom(data).replace(/_api\/web\/?/i, "")),
};
});
};
var Webs_1;
Webs = Webs_1 = __decorate([
defaultPath("webs")
], Webs);
return Webs;
}(SharePointQueryableCollection));
/**
* Describes a collection of web infos
*
*/
var WebInfos = /** @class */ (function (_super) {
__extends(WebInfos, _super);
function WebInfos() {
return _super !== null && _super.apply(this, arguments) || this;
}
WebInfos = __decorate([
defaultPath("webinfos")
], WebInfos);
return WebInfos;
}(SharePointQueryableCollection));
/**
* Describes a web
*
*/
var Web = /** @class */ (function (_super) {
__extends(Web, _super);
function Web() {
return _super !== null && _super.apply(this, arguments) || this;
}
Web_1 = Web;
/**
* Creates a new web instance from the given url by indexing the location of the /_api/
* segment. If this is not found the method creates a new web with the entire string as
* supplied.
*
* @param url
*/
Web.fromUrl = function (url, path) {
return new Web_1(extractWebUrl(url), path);
};
Object.defineProperty(Web.prototype, "webs", {
/**
* Gets this web's subwebs
*
*/
get: function () {
return new Webs(this);
},
enumerable: true,
configurable: true
});
/**
* Gets this web's parent web and data
*
*/
Web.prototype.getParentWeb = function () {
var _this = this;
return this.select("ParentWeb/Id").expand("ParentWeb").get()
.then(function (_a) {
var ParentWeb = _a.ParentWeb;
return new Site(_this.toUrlAndQuery().split("/_api")[0]).openWebById(ParentWeb.Id);
});
};
/**
* Returns a collection of objects that contain metadata about subsites of the current site in which the current user is a member.
*
* @param nWebTemplateFilter Specifies the site definition (default = -1)
* @param nConfigurationFilter A 16-bit integer that specifies the identifier of a configuration (default = -1)
*/
Web.prototype.getSubwebsFilteredForCurrentUser = function (nWebTemplateFilter, nConfigurationFilter) {
if (nWebTemplateFilter === void 0) { nWebTemplateFilter = -1; }
if (nConfigurationFilter === void 0) { nConfigurationFilter = -1; }
return this.clone(Webs, "getSubwebsFilteredForCurrentUser(nWebTemplateFilter=" + nWebTemplateFilter + ",nConfigurationFilter=" + nConfigurationFilter + ")");
};
Object.defineProperty(Web.prototype, "allProperties", {
/**
* Allows access to the web's all properties collection
*/
get: function () {
return this.clone(SharePointQueryableCollection, "allproperties");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Web.prototype, "webinfos", {
/**
* Gets a collection of WebInfos for this web's subwebs
*
*/
get: function () {
return new WebInfos(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Web.prototype, "contentTypes", {
/**
* Gets the content types available in this web
*
*/
get: function () {
return new ContentTypes(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Web.prototype, "lists", {
/**
* Gets the lists in this web
*
*/
get: function () {
return new Lists(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Web.prototype, "fields", {
/**
* Gets the fields in this web
*
*/
get: function () {
return new Fields(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Web.prototype, "features", {
/**
* Gets the active features for this web
*
*/
get: function () {
return new Features(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Web.prototype, "availablefields", {
/**
* Gets the available fields in this web
*
*/
get: function () {
return new Fields(this, "availablefields");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Web.prototype, "navigation", {
/**
* Gets the navigation options in this web
*
*/
get: function () {
return new Navigation(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Web.prototype, "siteUsers", {
/**
* Gets the site users
*
*/
get: function () {
return new SiteUsers(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Web.prototype, "siteGroups", {
/**
* Gets the site groups
*
*/
get: function () {
return new SiteGroups(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Web.prototype, "siteUserInfoList", {
/**
* Gets site user info list
*
*/
get: function () {
return new List(this, "siteuserinfolist");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Web.prototype, "regionalSettings", {
/**
* Gets regional settings
*
*/
get: function () {
return new RegionalSettings(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Web.prototype, "currentUser", {
/**
* Gets the current user
*/
get: function () {
return new CurrentUser(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Web.prototype, "folders", {
/**
* Gets the top-level folders in this web
*
*/
get: function () {
return new Folders(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Web.prototype, "userCustomActions", {
/**
* Gets all user custom actions for this web
*
*/
get: function () {
return new UserCustomActions(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Web.prototype, "roleDefinitions", {
/**
* Gets the collection of RoleDefinition resources
*
*/
get: function () {
return new RoleDefinitions(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Web.prototype, "relatedItems", {
/**
* Provides an interface to manage related items
*
*/
get: function () {
return RelatedItemManagerImpl.FromUrl(this.toUrl());
},
enumerable: true,
configurable: true
});
/**
* Creates a new batch for requests within the context of this web
*
*/
Web.prototype.createBatch = function () {
return new SPBatch(this.parentUrl);
};
Object.defineProperty(Web.prototype, "rootFolder", {
/**
* Gets the root folder of this web
*
*/
get: function () {
return new Folder(this, "rootFolder");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Web.prototype, "associatedOwnerGroup", {
/**
* Gets the associated owner group for this web
*
*/
get: function () {
return new SiteGroup(this, "associatedownergroup");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Web.prototype, "associatedMemberGroup", {
/**
* Gets the associated member group for this web
*
*/
get: function () {
return new SiteGroup(this, "associatedmembergroup");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Web.prototype, "associatedVisitorGroup", {
/**
* Gets the associated visitor group for this web
*
*/
get: function () {
return new SiteGroup(this, "associatedvisitorgroup");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Web.prototype, "defaultDocumentLibrary", {
/**
* Gets the default document library for this web
*
*/
get: function () {
return new List(this, "DefaultDocumentLibrary");
},
enumerable: true,
configurable: true
});
/**
* Gets a folder by server relative url
*
* @param folderRelativeUrl The server relative path to the folder (including /sites/ if applicable)
*/
Web.prototype.getFolderByServerRelativeUrl = function (folderRelativeUrl) {
return new Folder(this, "getFolderByServerRelativeUrl('" + folderRelativeUrl + "')");
};
/**
* Gets a folder by server relative relative path if your folder name contains # and % characters
* you need to first encode the file name using encodeURIComponent() and then pass the url
* let url = "/sites/test/Shared Documents/" + encodeURIComponent("%123");
* This works only in SharePoint online.
*
* @param folderRelativeUrl The server relative path to the folder (including /sites/ if applicable)
*/
Web.prototype.getFolderByServerRelativePath = function (folderRelativeUrl) {
return new Folder(this, "getFolderByServerRelativePath(decodedUrl='" + folderRelativeUrl + "')");
};
/**
* Gets a file by server relative url
*
* @param fileRelativeUrl The server relative path to the file (including /sites/ if applicable)
*/
Web.prototype.getFileByServerRelativeUrl = function (fileRelativeUrl) {
return new File(this, "getFileByServerRelativeUrl('" + fileRelativeUrl + "')");
};
/**
* Gets a file by server relative url if your file name contains # and % characters
* you need to first encode the file name using encodeURIComponent() and then pass the url
* let url = "/sites/test/Shared Documents/" + encodeURIComponent("%123.docx");
*
* @param fileRelativeUrl The server relative path to the file (including /sites/ if applicable)
*/
Web.prototype.getFileByServerRelativePath = function (fileRelativeUrl) {
return new File(this, "getFileByServerRelativePath(decodedUrl='" + fileRelativeUrl + "')");
};
/**
* Gets a list by server relative url (list's root folder)
*
* @param listRelativeUrl The server relative path to the list's root folder (including /sites/ if applicable)
*/
Web.prototype.getList = function (listRelativeUrl) {
return new List(this, "getList('" + listRelativeUrl + "')");
};
/**
* Updates this web instance with the supplied properties
*
* @param properties A plain object hash of values to update for the web
*/
Web.prototype.update = function (properties) {
var _this = this;
var postBody = common.jsS(common.extend({
"__metadata": { "type": "SP.Web" },
}, properties));
return this.postCore({
body: postBody,
headers: {
"X-HTTP-Method": "MERGE",
},
}).then(function (data) {
return {
data: data,
web: _this,
};
});
};
/**
* Deletes this web
*
*/
Web.prototype.delete = function () {
return _super.prototype.deleteCore.call(this);
};
/**
* Applies the theme specified by the contents of each of the files specified in the arguments to the site
*
* @param colorPaletteUrl The server-relative URL of the color palette file
* @param fontSchemeUrl The server-relative URL of the font scheme
* @param backgroundImageUrl The server-relative URL of the background image
* @param shareGenerated When true, the generated theme files are stored in the root site. When false, they are stored in this web
*/
Web.prototype.applyTheme = function (colorPaletteUrl, fontSchemeUrl, backgroundImageUrl, shareGenerated) {
var postBody = common.jsS({
backgroundImageUrl: backgroundImageUrl,
colorPaletteUrl: colorPaletteUrl,
fontSchemeUrl: fontSchemeUrl,
shareGenerated: shareGenerated,
});
return this.clone(Web_1, "applytheme").postCore({ body: postBody });
};
/**
* Applies the specified site definition or site template to the Web site that has no template applied to it
*
* @param template Name of the site definition or the name of the site template
*/
Web.prototype.applyWebTemplate = function (template) {
var q = this.clone(Web_1, "applywebtemplate");
q.concat("(@t)");
q.query.set("@t", template);
return q.postCore();
};
/**
* Checks whether the specified login name belongs to a valid user in the web. If the user doesn't exist, adds the user to the web.
*
* @param loginName The login name of the user (ex: i:0#.f|membership|user@domain.onmicrosoft.com)
*/
Web.prototype.ensureUser = function (loginName) {
var postBody = common.jsS({
logonName: loginName,
});
return this.clone(Web_1, "ensureuser").postCore({ body: postBody }).then(function (data) {
return {
data: data,
user: new SiteUser(odataUrlFrom(data)),
};
});
};
/**
* Returns a collection of site templates available for the site
*
* @param language The locale id of the site templates to retrieve (default = 1033 [English, US])
* @param includeCrossLanguage When true, includes language-neutral site templates; otherwise false (default = true)
*/
Web.prototype.availableWebTemplates = function (language, includeCrossLanugage) {
if (language === void 0) { language = 1033; }
if (includeCrossLanugage === void 0) { includeCrossLanugage = true; }
return new SharePointQueryableCollection(this, "getavailablewebtemplates(lcid=" + language + ", doincludecrosslanguage=" + includeCrossLanugage + ")");
};
/**
* Returns the list gallery on the site
*
* @param type The gallery type - WebTemplateCatalog = 111, WebPartCatalog = 113 ListTemplateCatalog = 114,
* MasterPageCatalog = 116, SolutionCatalog = 121, ThemeCatalog = 123, DesignCatalog = 124, AppDataCatalog = 125
*/
Web.prototype.getCatalog = function (type) {
return this.clone(Web_1, "getcatalog(" + type + ")").select("Id").get().then(function (data) {
return new List(odataUrlFrom(data));
});
};
/**
* Returns the collection of changes from the change log that have occurred within the list, based on the specified query
*
* @param query The change query
*/
Web.prototype.getChanges = function (query) {
var postBody = common.jsS({ "query": common.extend({ "__metadata": { "type": "SP.ChangeQuery" } }, query) });
return this.clone(Web_1, "getchanges").postCore({ body: postBody });
};
Object.defineProperty(Web.prototype, "customListTemplate", {
/**
* Gets the custom list templates for the site
*
*/
get: function () {
return new SharePointQueryableCollection(this, "getcustomlisttemplates");
},
enumerable: true,
configurable: true
});
/**
* Returns the user corresponding to the specified member identifier for the current site
*
* @param id The id of the user
*/
Web.prototype.getUserById = function (id) {
return new SiteUser(this, "getUserById(" + id + ")");
};
/**
* Returns the name of the image file for the icon that is used to represent the specified file
*
* @param filename The file name. If this parameter is empty, the server returns an empty string
* @param size The size of the icon: 16x16 pixels = 0, 32x32 pixels = 1 (default = 0)
* @param progId The ProgID of the application that was used to create the file, in the form OLEServerName.ObjectName
*/
Web.prototype.mapToIcon = function (filename, size, progId) {
if (size === void 0) { size = 0; }
if (progId === void 0) { progId = ""; }
return this.clone(Web_1, "maptoicon(filename='" + filename + "', progid='" + progId + "', size=" + size + ")").get();
};
/**
* Returns the tenant property corresponding to the specified key in the app catalog site
*
* @param key Id of storage entity to be set
*/
Web.prototype.getStorageEntity = function (key) {
return this.clone(Web_1, "getStorageEntity('" + key + "')").get();
};
/**
* This will set the storage entity identified by the given key (MUST be called in the context of the app catalog)
*
* @param key Id of storage entity to be set
* @param value Value of storage entity to be set
* @param description Description of storage entity to be set
* @param comments Comments of storage entity to be set
*/
Web.prototype.setStorageEntity = function (key, value, description, comments) {
if (description === void 0) { description = ""; }
if (comments === void 0) { comments = ""; }
return this.clone(Web_1, "setStorageEntity").postCore({
body: common.jsS({
comments: comments,
description: description,
key: key,
value: value,
}),
});
};
/**
* This will remove the storage entity identified by the given key
*
* @param key Id of storage entity to be removed
*/
Web.prototype.removeStorageEntity = function (key) {
return this.clone(Web_1, "removeStorageEntity('" + key + "')").postCore();
};
/**
* Gets the app catalog for this web
*
* @param url Optional url or web containing the app catalog (default: current web)
*/
Web.prototype.getAppCatalog = function (url) {
return new AppCatalog(url || this);
};
/**
* Gets the collection of available client side web parts for this web instance
*/
Web.prototype.getClientSideWebParts = function () {
return this.clone(SharePointQueryableCollection, "GetClientSideWebParts").get();
};
/**
* Creates a new client side page
*
* @param pageName Name of the new page
* @param title Display title of the new page
* @param libraryTitle Title of the library in which to create the new page. Default: "Site Pages"
*/
Web.prototype.addClientSidePage = function (pageName, title, libraryTitle) {
if (title === void 0) { title = pageName.replace(/\.[^/.]+$/, ""); }
if (libraryTitle === void 0) { libraryTitle = "Site Pages"; }
return ClientSidePage.create(this.lists.getByTitle(libraryTitle), pageName, title);
};
/**
* Creates a new client side page using the library path
*
* @param pageName Name of the new page
* @param listRelativePath The server relative path to the list's root folder (including /sites/ if applicable)
* @param title Display title of the new page
*/
Web.prototype.addClientSidePageByPath = function (pageName, listRelativePath, title) {
if (title === void 0) { title = pageName.replace(/\.[^/.]+$/, ""); }
return ClientSidePage.create(this.getList(listRelativePath), pageName, title);
};
/**
* Creates the default associated groups (Members, Owners, Visitors) and gives them the default permissions on the site.
* The target site must have unique permissions and no associated members / owners / visitors groups
*
* @param siteOwner The user login name to be added to the site Owners group. Default is the current user
* @param siteOwner2 The second user login name to be added to the site Owners group. Default is empty
* @param groupNameSeed The base group name. E.g. 'TestSite' would produce 'TestSite Members' etc.
*/
Web.prototype.createDefaultAssociatedGroups = function (siteOwner, siteOwner2, groupNameSeed) {
var q = this.clone(Web_1, "createDefaultAssociatedGroups(userLogin=@u,userLogin2=@v,groupNameSeed=@s)");
q.query.set("@u", "'" + encodeURIComponent(siteOwner || "") + "'");
q.query.set("@v", "'" + encodeURIComponent(siteOwner2 || "") + "'");
q.query.set("@s", "'" + encodeURIComponent(groupNameSeed || "") + "'");
return q.postCore();
};
/**
* Gets hub site data for the current web.
*
* @param forceRefresh Default value is false. When false, the data is returned from the server's cache.
* When true, the cache is refreshed with the latest updates and then returned.
* Use this if you just made changes and need to see those changes right away.
*/
Web.prototype.hubSiteData = function (forceRefresh) {
if (forceRefresh === void 0) { forceRefresh = false; }
return this.clone(Web_1, "hubSiteData(" + forceRefresh + ")").get();
};
/**
* Applies theme updates from the parent hub site collection.
*/
Web.prototype.syncHubSiteTheme = function () {
return this.clone(Web_1, "syncHubSiteTheme").postCore();
};
var Web_1;
Web = Web_1 = __decorate([
defaultPath("_api/web")
], Web);
return Web;
}(SharePointQueryableShareableWeb));
/**
* Describes a site collection
*
*/
var Site = /** @class */ (function (_super) {
__extends(Site, _super);
function Site() {
return _super !== null && _super.apply(this, arguments) || this;
}
Site_1 = Site;
Object.defineProperty(Site.prototype, "rootWeb", {
/**
* Gets the root web of the site collection
*
*/
get: function () {
return new Web(this, "rootweb");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Site.prototype, "features", {
/**
* Gets the active features for this site collection
*
*/
get: function () {
return new Features(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Site.prototype, "userCustomActions", {
/**
* Gets all custom actions for this site collection
*
*/
get: function () {
return new UserCustomActions(this);
},
enumerable: true,
configurable: true
});
/**
* Gets a Web instance representing the root web of the site collection
* correctly setup for chaining within the library
*/
Site.prototype.getRootWeb = function () {
return this.rootWeb.select("Url").get().then(function (web) { return new Web(web.Url); });
};
/**
* Gets the context information for this site collection
*/
Site.prototype.getContextInfo = function () {
var q = new Site_1(this.parentUrl, "_api/contextinfo");
return q.postCore().then(function (data) {
if (common.hOP(data, "GetContextWebInformation")) {
var info = data.GetContextWebInformation;
info.SupportedSchemaVersions = info.SupportedSchemaVersions.results;
return info;
}
else {
return data;
}
});
};
/**
* Gets the document libraries on a site. Static method. (SharePoint Online only)
*
* @param absoluteWebUrl The absolute url of the web whose document libraries should be returned
*/
Site.prototype.getDocumentLibraries = function (absoluteWebUrl) {
var q = new SharePointQueryable("", "_api/sp.web.getdocumentlibraries(@v)");
q.query.set("@v", "'" + absoluteWebUrl + "'");
return q.get().then(function (data) {
if (common.hOP(data, "GetDocumentLibraries")) {
return data.GetDocumentLibraries;
}
else {
return data;
}
});
};
/**
* Gets the site url from a page url
*
* @param absolutePageUrl The absolute url of the page
*/
Site.prototype.getWebUrlFromPageUrl = function (absolutePageUrl) {
var q = new SharePointQueryable("", "_api/sp.web.getweburlfrompageurl(@v)");
q.query.set("@v", "'" + absolutePageUrl + "'");
return q.get().then(function (data) {
if (common.hOP(data, "GetWebUrlFromPageUrl")) {
return data.GetWebUrlFromPageUrl;
}
else {
return data;
}
});
};
/**
* Creates a new batch for requests within the context of this site collection
*
*/
Site.prototype.createBatch = function () {
return new SPBatch(this.parentUrl);
};
/**
* Opens a web by id (using POST)
*
* @param webId The GUID id of the web to open
*/
Site.prototype.openWebById = function (webId) {
return this.clone(Site_1, "openWebById('" + webId + "')").postCore().then(function (d) { return ({
data: d,
web: Web.fromUrl(d["odata.id"] || d.__metadata.uri),
}); });
};
/**
* Associates a site collection to a hub site.
*
* @param siteId Id of the hub site collection you want to join.
* If you want to disassociate the site collection from hub site, then
* pass the siteId as 00000000-0000-0000-0000-000000000000
*/
Site.prototype.joinHubSite = function (siteId) {
return this.clone(Site_1, "joinHubSite('" + siteId + "')").postCore();
};
/**
* Registers the current site collection as hub site collection
*/
Site.prototype.registerHubSite = function () {
return this.clone(Site_1, "registerHubSite").postCore();
};
/**
* Unregisters the current site collection as hub site collection.
*/
Site.prototype.unRegisterHubSite = function () {
return this.clone(Site_1, "unRegisterHubSite").postCore();
};
var Site_1;
Site = Site_1 = __decorate([
defaultPath("_api/site")
], Site);
return Site;
}(SharePointQueryableInstance));
var UserProfileQuery = /** @class */ (function (_super) {
__extends(UserProfileQuery, _super);
/**
* Creates a new instance of the UserProfileQuery class
*
* @param baseUrl The url or SharePointQueryable which forms the parent of this user profile query
*/
function UserProfileQuery(baseUrl, path) {
if (path === void 0) { path = "_api/sp.userprofiles.peoplemanager"; }
var _this = _super.call(this, baseUrl, path) || this;
_this.clientPeoplePickerQuery = (new ClientPeoplePickerQuery(baseUrl)).configureFrom(_this);
_this.profileLoader = (new ProfileLoader(baseUrl)).configureFrom(_this);
return _this;
}
Object.defineProperty(UserProfileQuery.prototype, "editProfileLink", {
/**
* The url of the edit profile page for the current user
*/
get: function () {
return this.clone(UserProfileQuery, "EditProfileLink").get();
},
enumerable: true,
configurable: true
});
Object.defineProperty(UserProfileQuery.prototype, "isMyPeopleListPublic", {
/**
* A boolean value that indicates whether the current user's "People I'm Following" list is public
*/
get: function () {
return this.clone(UserProfileQuery, "IsMyPeopleListPublic").get();
},
enumerable: true,
configurable: true
});
/**
* A boolean value that indicates whether the current user is being followed by the specified user
*
* @param loginName The account name of the user
*/
UserProfileQuery.prototype.amIFollowedBy = function (loginName) {
var q = this.clone(UserProfileQuery, "amifollowedby(@v)");
q.query.set("@v", "'" + encodeURIComponent(loginName) + "'");
return q.get();
};
/**
* A boolean value that indicates whether the current user is following the specified user
*
* @param loginName The account name of the user
*/
UserProfileQuery.prototype.amIFollowing = function (loginName) {
var q = this.clone(UserProfileQuery, "amifollowing(@v)");
q.query.set("@v", "'" + encodeURIComponent(loginName) + "'");
return q.get();
};
/**
* Gets tags that the current user is following
*
* @param maxCount The maximum number of tags to retrieve (default is 20)
*/
UserProfileQuery.prototype.getFollowedTags = function (maxCount) {
if (maxCount === void 0) { maxCount = 20; }
return this.clone(UserProfileQuery, "getfollowedtags(" + maxCount + ")").get();
};
/**
* Gets the people who are following the specified user
*
* @param loginName The account name of the user
*/
UserProfileQuery.prototype.getFollowersFor = function (loginName) {
var q = this.clone(UserProfileQuery, "getfollowersfor(@v)");
q.query.set("@v", "'" + encodeURIComponent(loginName) + "'");
return q.get();
};
Object.defineProperty(UserProfileQuery.prototype, "myFollowers", {
/**
* Gets the people who are following the current user
*
*/
get: function () {
return new SharePointQueryableCollection(this, "getmyfollowers");
},
enumerable: true,
configurable: true
});
Object.defineProperty(UserProfileQuery.prototype, "myProperties", {
/**
* Gets user properties for the current user
*
*/
get: function () {
return new UserProfileQuery(this, "getmyproperties");
},
enumerable: true,
configurable: true
});
/**
* Gets the people who the specified user is following
*
* @param loginName The account name of the user.
*/
UserProfileQuery.prototype.getPeopleFollowedBy = function (loginName) {
var q = this.clone(UserProfileQuery, "getpeoplefollowedby(@v)");
q.query.set("@v", "'" + encodeURIComponent(loginName) + "'");
return q.get();
};
/**
* Gets user properties for the specified user.
*
* @param loginName The account name of the user.
*/
UserProfileQuery.prototype.getPropertiesFor = function (loginName) {
var q = this.clone(UserProfileQuery, "getpropertiesfor(@v)");
q.query.set("@v", "'" + encodeURIComponent(loginName) + "'");
return q.get();
};
Object.defineProperty(UserProfileQuery.prototype, "trendingTags", {
/**
* Gets the 20 most popular hash tags over the past week, sorted so that the most popular tag appears first
*
*/
get: function () {
var q = this.clone(UserProfileQuery, null);
q.concat(".gettrendingtags");
return q.get();
},
enumerable: true,
configurable: true
});
/**
* Gets the specified user profile property for the specified user
*
* @param loginName The account name of the user
* @param propertyName The case-sensitive name of the property to get
*/
UserProfileQuery.prototype.getUserProfilePropertyFor = function (loginName, propertyName) {
var q = this.clone(UserProfileQuery, "getuserprofilepropertyfor(accountname=@v, propertyname='" + propertyName + "')");
q.query.set("@v", "'" + encodeURIComponent(loginName) + "'");
return q.get();
};
/**
* Removes the specified user from the user's list of suggested people to follow
*
* @param loginName The account name of the user
*/
UserProfileQuery.prototype.hideSuggestion = function (loginName) {
var q = this.clone(UserProfileQuery, "hidesuggestion(@v)");
q.query.set("@v", "'" + encodeURIComponent(loginName) + "'");
return q.postCore();
};
/**
* A boolean values that indicates whether the first user is following the second user
*
* @param follower The account name of the user who might be following the followee
* @param followee The account name of the user who might be followed by the follower
*/
UserProfileQuery.prototype.isFollowing = function (follower, followee) {
var q = this.clone(UserProfileQuery, null);
q.concat(".isfollowing(possiblefolloweraccountname=@v, possiblefolloweeaccountname=@y)");
q.query.set("@v", "'" + encodeURIComponent(follower) + "'");
q.query.set("@y", "'" + encodeURIComponent(followee) + "'");
return q.get();
};
/**
* Uploads and sets the user profile picture (Users can upload a picture to their own profile only). Not supported for batching.
*
* @param profilePicSource Blob data representing the user's picture in BMP, JPEG, or PNG format of up to 4.76MB
*/
UserProfileQuery.prototype.setMyProfilePic = function (profilePicSource) {
var _this = this;
return new Promise(function (resolve, reject) {
var buffer = null;
var reader = new FileReader();
reader.onload = function (e) { return buffer = e.target.result; };
reader.readAsArrayBuffer(profilePicSource);
var request = new UserProfileQuery(_this, "setmyprofilepicture");
request.postCore({
body: String.fromCharCode.apply(null, new Uint16Array(buffer)),
}).then(function (_) { return resolve(); }).catch(function (e) { return reject(e); });
});
};
/**
* Sets single value User Profile property
*
* @param accountName The account name of the user
* @param propertyName Property name
* @param propertyValue Property value
*/
UserProfileQuery.prototype.setSingleValueProfileProperty = function (accountName, propertyName, propertyValue) {
var postBody = common.jsS({
accountName: accountName,
propertyName: propertyName,
propertyValue: propertyValue,
});
return this.clone(UserProfileQuery, "SetSingleValueProfileProperty")
.postCore({ body: postBody });
};
/**
* Sets multi valued User Profile property
*
* @param accountName The account name of the user
* @param propertyName Property name
* @param propertyValues Property values
*/
UserProfileQuery.prototype.setMultiValuedProfileProperty = function (accountName, propertyName, propertyValues) {
var postBody = common.jsS({
accountName: accountName,
propertyName: propertyName,
propertyValues: propertyValues,
});
return this.clone(UserProfileQuery, "SetMultiValuedProfileProperty")
.postCore({ body: postBody });
};
/**
* Provisions one or more users' personal sites. (My Site administrator on SharePoint Online only)
*
* @param emails The email addresses of the users to provision sites for
*/
UserProfileQuery.prototype.createPersonalSiteEnqueueBulk = function () {
var emails = [];
for (var _i = 0; _i < arguments.length; _i++) {
emails[_i] = arguments[_i];
}
return this.profileLoader.createPersonalSiteEnqueueBulk(emails);
};
Object.defineProperty(UserProfileQuery.prototype, "ownerUserProfile", {
/**
* Gets the user profile of the site owner
*
*/
get: function () {
return this.profileLoader.ownerUserProfile;
},
enumerable: true,
configurable: true
});
Object.defineProperty(UserProfileQuery.prototype, "userProfile", {
/**
* Gets the user profile for the current user
*/
get: function () {
return this.profileLoader.userProfile;
},
enumerable: true,
configurable: true
});
/**
* Enqueues creating a personal site for this user, which can be used to share documents, web pages, and other files
*
* @param interactiveRequest true if interactively (web) initiated request, or false (default) if non-interactively (client) initiated request
*/
UserProfileQuery.prototype.createPersonalSite = function (interactiveRequest) {
if (interactiveRequest === void 0) { interactiveRequest = false; }
return this.profileLoader.createPersonalSite(interactiveRequest);
};
/**
* Sets the privacy settings for this profile
*
* @param share true to make all social data public; false to make all social data private
*/
UserProfileQuery.prototype.shareAllSocialData = function (share) {
return this.profileLoader.shareAllSocialData(share);
};
/**
* Resolves user or group using specified query parameters
*
* @param queryParams The query parameters used to perform resolve
*/
UserProfileQuery.prototype.clientPeoplePickerResolveUser = function (queryParams) {
return this.clientPeoplePickerQuery.clientPeoplePickerResolveUser(queryParams);
};
/**
* Searches for users or groups using specified query parameters
*
* @param queryParams The query parameters used to perform search
*/
UserProfileQuery.prototype.clientPeoplePickerSearchUser = function (queryParams) {
return this.clientPeoplePickerQuery.clientPeoplePickerSearchUser(queryParams);
};
return UserProfileQuery;
}(SharePointQueryableInstance));
var ProfileLoader = /** @class */ (function (_super) {
__extends(ProfileLoader, _super);
function ProfileLoader() {
return _super !== null && _super.apply(this, arguments) || this;
}
ProfileLoader_1 = ProfileLoader;
/**
* Provisions one or more users' personal sites. (My Site administrator on SharePoint Online only) Doesn't support batching
*
* @param emails The email addresses of the users to provision sites for
*/
ProfileLoader.prototype.createPersonalSiteEnqueueBulk = function (emails) {
return this.clone(ProfileLoader_1, "createpersonalsiteenqueuebulk", false).postCore({
body: common.jsS({ "emailIDs": emails }),
});
};
Object.defineProperty(ProfileLoader.prototype, "ownerUserProfile", {
/**
* Gets the user profile of the site owner.
*
*/
get: function () {
var q = this.getParent(ProfileLoader_1, this.parentUrl, "_api/sp.userprofiles.profileloader.getowneruserprofile");
if (this.hasBatch) {
q = q.inBatch(this.batch);
}
return q.postCore();
},
enumerable: true,
configurable: true
});
Object.defineProperty(ProfileLoader.prototype, "userProfile", {
/**
* Gets the user profile of the current user.
*
*/
get: function () {
return this.clone(ProfileLoader_1, "getuserprofile").postCore();
},
enumerable: true,
configurable: true
});
/**
* Enqueues creating a personal site for this user, which can be used to share documents, web pages, and other files.
*
* @param interactiveRequest true if interactively (web) initiated request, or false (default) if non-interactively (client) initiated request
*/
ProfileLoader.prototype.createPersonalSite = function (interactiveRequest) {
if (interactiveRequest === void 0) { interactiveRequest = false; }
return this.clone(ProfileLoader_1, "getuserprofile/createpersonalsiteenque(" + interactiveRequest + ")").postCore();
};
/**
* Sets the privacy settings for this profile
*
* @param share true to make all social data public; false to make all social data private.
*/
ProfileLoader.prototype.shareAllSocialData = function (share) {
return this.clone(ProfileLoader_1, "getuserprofile/shareallsocialdata(" + share + ")").postCore();
};
var ProfileLoader_1;
ProfileLoader = ProfileLoader_1 = __decorate([
defaultPath("_api/sp.userprofiles.profileloader.getprofileloader")
], ProfileLoader);
return ProfileLoader;
}(SharePointQueryable));
var ClientPeoplePickerQuery = /** @class */ (function (_super) {
__extends(ClientPeoplePickerQuery, _super);
function ClientPeoplePickerQuery() {
return _super !== null && _super.apply(this, arguments) || this;
}
ClientPeoplePickerQuery_1 = ClientPeoplePickerQuery;
/**
* Resolves user or group using specified query parameters
*
* @param queryParams The query parameters used to perform resolve
*/
ClientPeoplePickerQuery.prototype.clientPeoplePickerResolveUser = function (queryParams) {
var q = this.clone(ClientPeoplePickerQuery_1, null);
q.concat(".clientpeoplepickerresolveuser");
return q.postCore({
body: this.createClientPeoplePickerQueryParametersRequestBody(queryParams),
})
.then(function (res) {
if (typeof res === "object") {
return res.ClientPeoplePickerResolveUser;
}
return res;
})
.then(JSON.parse);
};
/**
* Searches for users or groups using specified query parameters
*
* @param queryParams The query parameters used to perform search
*/
ClientPeoplePickerQuery.prototype.clientPeoplePickerSearchUser = function (queryParams) {
var q = this.clone(ClientPeoplePickerQuery_1, null);
q.concat(".clientpeoplepickersearchuser");
return q.postCore({
body: this.createClientPeoplePickerQueryParametersRequestBody(queryParams),
})
.then(function (res) {
if (typeof res === "object") {
return res.ClientPeoplePickerSearchUser;
}
return res;
})
.then(JSON.parse);
};
/**
* Creates ClientPeoplePickerQueryParameters request body
*
* @param queryParams The query parameters to create request body
*/
ClientPeoplePickerQuery.prototype.createClientPeoplePickerQueryParametersRequestBody = function (queryParams) {
return common.jsS({
"queryParams": common.extend(metadata("SP.UI.ApplicationPages.ClientPeoplePickerQueryParameters"), queryParams),
});
};
var ClientPeoplePickerQuery_1;
ClientPeoplePickerQuery = ClientPeoplePickerQuery_1 = __decorate([
defaultPath("_api/sp.ui.applicationpages.clientpeoplepickerwebserviceinterface")
], ClientPeoplePickerQuery);
return ClientPeoplePickerQuery;
}(SharePointQueryable));
/**
* Exposes social following methods
*/
var SocialQuery = /** @class */ (function (_super) {
__extends(SocialQuery, _super);
function SocialQuery() {
return _super !== null && _super.apply(this, arguments) || this;
}
SocialQuery_1 = SocialQuery;
Object.defineProperty(SocialQuery.prototype, "my", {
get: function () {
return new MySocialQuery(this);
},
enumerable: true,
configurable: true
});
/**
* Gets a URI to a site that lists the current user's followed sites.
*/
SocialQuery.prototype.getFollowedSitesUri = function () {
return this.clone(SocialQuery_1, "FollowedSitesUri").get().then(function (r) {
return r.FollowedSitesUri || r;
});
};
/**
* Gets a URI to a site that lists the current user's followed documents.
*/
SocialQuery.prototype.getFollowedDocumentsUri = function () {
return this.clone(SocialQuery_1, "FollowedDocumentsUri").get().then(function (r) {
return r.FollowedDocumentsUri || r;
});
};
/**
* Makes the current user start following a user, document, site, or tag
*
* @param actorInfo The actor to start following
*/
SocialQuery.prototype.follow = function (actorInfo) {
return this.clone(SocialQuery_1, "follow").postCore({ body: this.createSocialActorInfoRequestBody(actorInfo) });
};
/**
* Indicates whether the current user is following a specified user, document, site, or tag
*
* @param actorInfo The actor to find the following status for
*/
SocialQuery.prototype.isFollowed = function (actorInfo) {
return this.clone(SocialQuery_1, "isfollowed").postCore({ body: this.createSocialActorInfoRequestBody(actorInfo) });
};
/**
* Makes the current user stop following a user, document, site, or tag
*
* @param actorInfo The actor to stop following
*/
SocialQuery.prototype.stopFollowing = function (actorInfo) {
return this.clone(SocialQuery_1, "stopfollowing").postCore({ body: this.createSocialActorInfoRequestBody(actorInfo) });
};
/**
* Creates SocialActorInfo request body
*
* @param actorInfo The actor to create request body
*/
SocialQuery.prototype.createSocialActorInfoRequestBody = function (actorInfo) {
return common.jsS({
"actor": Object.assign(metadata("SP.Social.SocialActorInfo"), {
Id: null,
}, actorInfo),
});
};
var SocialQuery_1;
SocialQuery = SocialQuery_1 = __decorate([
defaultPath("_api/social.following")
], SocialQuery);
return SocialQuery;
}(SharePointQueryableInstance));
var MySocialQuery = /** @class */ (function (_super) {
__extends(MySocialQuery, _super);
function MySocialQuery() {
return _super !== null && _super.apply(this, arguments) || this;
}
MySocialQuery_1 = MySocialQuery;
/**
* Gets users, documents, sites, and tags that the current user is following.
*
* @param types Bitwise set of SocialActorTypes to retrieve
*/
MySocialQuery.prototype.followed = function (types) {
return this.clone(MySocialQuery_1, "followed(types=" + types + ")").get().then(function (r) {
return common.hOP(r, "Followed") ? r.Followed.results : r;
});
};
/**
* Gets the count of users, documents, sites, and tags that the current user is following.
*
* @param types Bitwise set of SocialActorTypes to retrieve
*/
MySocialQuery.prototype.followedCount = function (types) {
return this.clone(MySocialQuery_1, "followedcount(types=" + types + ")").get().then(function (r) {
return r.FollowedCount || r;
});
};
/**
* Gets the users who are following the current user.
*/
MySocialQuery.prototype.followers = function () {
return this.clone(MySocialQuery_1, "followers").get().then(function (r) {
return common.hOP(r, "Followers") ? r.Followers.results : r;
});
};
/**
* Gets users who the current user might want to follow.
*/
MySocialQuery.prototype.suggestions = function () {
return this.clone(MySocialQuery_1, "suggestions").get().then(function (r) {
return common.hOP(r, "Suggestions") ? r.Suggestions.results : r;
});
};
var MySocialQuery_1;
MySocialQuery = MySocialQuery_1 = __decorate([
defaultPath("my")
], MySocialQuery);
return MySocialQuery;
}(SharePointQueryableInstance));
(function (SocialActorType) {
SocialActorType[SocialActorType["User"] = 0] = "User";
SocialActorType[SocialActorType["Document"] = 1] = "Document";
SocialActorType[SocialActorType["Site"] = 2] = "Site";
SocialActorType[SocialActorType["Tag"] = 3] = "Tag";
})(exports.SocialActorType || (exports.SocialActorType = {}));
(function (SocialActorTypes) {
SocialActorTypes[SocialActorTypes["None"] = 0] = "None";
SocialActorTypes[SocialActorTypes["User"] = 1] = "User";
SocialActorTypes[SocialActorTypes["Document"] = 2] = "Document";
SocialActorTypes[SocialActorTypes["Site"] = 4] = "Site";
SocialActorTypes[SocialActorTypes["Tag"] = 8] = "Tag";
/**
* The set excludes documents and sites that do not have feeds.
*/
SocialActorTypes[SocialActorTypes["ExcludeContentWithoutFeeds"] = 268435456] = "ExcludeContentWithoutFeeds";
/**
* The set includes group sites
*/
SocialActorTypes[SocialActorTypes["IncludeGroupsSites"] = 536870912] = "IncludeGroupsSites";
/**
* The set includes only items created within the last 24 hours
*/
SocialActorTypes[SocialActorTypes["WithinLast24Hours"] = 1073741824] = "WithinLast24Hours";
})(exports.SocialActorTypes || (exports.SocialActorTypes = {}));
(function (SocialFollowResult) {
SocialFollowResult[SocialFollowResult["Ok"] = 0] = "Ok";
SocialFollowResult[SocialFollowResult["AlreadyFollowing"] = 1] = "AlreadyFollowing";
SocialFollowResult[SocialFollowResult["LimitReached"] = 2] = "LimitReached";
SocialFollowResult[SocialFollowResult["InternalError"] = 3] = "InternalError";
})(exports.SocialFollowResult || (exports.SocialFollowResult = {}));
(function (SocialStatusCode) {
/**
* The operation completed successfully
*/
SocialStatusCode[SocialStatusCode["OK"] = 0] = "OK";
/**
* The request is invalid.
*/
SocialStatusCode[SocialStatusCode["InvalidRequest"] = 1] = "InvalidRequest";
/**
* The current user is not authorized to perform the operation.
*/
SocialStatusCode[SocialStatusCode["AccessDenied"] = 2] = "AccessDenied";
/**
* The target of the operation was not found.
*/
SocialStatusCode[SocialStatusCode["ItemNotFound"] = 3] = "ItemNotFound";
/**
* The operation is invalid for the target's current state.
*/
SocialStatusCode[SocialStatusCode["InvalidOperation"] = 4] = "InvalidOperation";
/**
* The operation completed without modifying the target.
*/
SocialStatusCode[SocialStatusCode["ItemNotModified"] = 5] = "ItemNotModified";
/**
* The operation failed because an internal error occurred.
*/
SocialStatusCode[SocialStatusCode["InternalError"] = 6] = "InternalError";
/**
* The operation failed because the server could not access the distributed cache.
*/
SocialStatusCode[SocialStatusCode["CacheReadError"] = 7] = "CacheReadError";
/**
* The operation succeeded but the server could not update the distributed cache.
*/
SocialStatusCode[SocialStatusCode["CacheUpdateError"] = 8] = "CacheUpdateError";
/**
* No personal site exists for the current user, and no further information is available.
*/
SocialStatusCode[SocialStatusCode["PersonalSiteNotFound"] = 9] = "PersonalSiteNotFound";
/**
* No personal site exists for the current user, and a previous attempt to create one failed.
*/
SocialStatusCode[SocialStatusCode["FailedToCreatePersonalSite"] = 10] = "FailedToCreatePersonalSite";
/**
* No personal site exists for the current user, and a previous attempt to create one was not authorized.
*/
SocialStatusCode[SocialStatusCode["NotAuthorizedToCreatePersonalSite"] = 11] = "NotAuthorizedToCreatePersonalSite";
/**
* No personal site exists for the current user, and no attempt should be made to create one.
*/
SocialStatusCode[SocialStatusCode["CannotCreatePersonalSite"] = 12] = "CannotCreatePersonalSite";
/**
* The operation was rejected because an internal limit had been reached.
*/
SocialStatusCode[SocialStatusCode["LimitReached"] = 13] = "LimitReached";
/**
* The operation failed because an error occurred during the processing of the specified attachment.
*/
SocialStatusCode[SocialStatusCode["AttachmentError"] = 14] = "AttachmentError";
/**
* The operation succeeded with recoverable errors; the returned data is incomplete.
*/
SocialStatusCode[SocialStatusCode["PartialData"] = 15] = "PartialData";
/**
* A required SharePoint feature is not enabled.
*/
SocialStatusCode[SocialStatusCode["FeatureDisabled"] = 16] = "FeatureDisabled";
/**
* The site's storage quota has been exceeded.
*/
SocialStatusCode[SocialStatusCode["StorageQuotaExceeded"] = 17] = "StorageQuotaExceeded";
/**
* The operation failed because the server could not access the database.
*/
SocialStatusCode[SocialStatusCode["DatabaseError"] = 18] = "DatabaseError";
})(exports.SocialStatusCode || (exports.SocialStatusCode = {}));
/**
* Implements the site script API REST methods
*
*/
var SiteScripts = /** @class */ (function (_super) {
__extends(SiteScripts, _super);
/**
* Creates a new instance of the SiteScripts method class
*
* @param baseUrl The parent url provider
* @param methodName The static method name to call on the utility class
*/
function SiteScripts(baseUrl, methodName) {
return _super.call(this, SiteScripts.getBaseUrl(baseUrl), "_api/Microsoft.Sharepoint.Utilities.WebTemplateExtensions.SiteScriptUtility." + methodName) || this;
}
SiteScripts.getBaseUrl = function (candidate) {
if (typeof candidate === "string") {
return candidate;
}
var c = candidate;
var url = c.toUrl();
var index = url.indexOf("_api/");
if (index < 0) {
return url;
}
return url.substr(0, index);
};
SiteScripts.prototype.execute = function (props) {
return this.postCore({
body: JSON.stringify(props),
});
};
/**
* Gets a list of information on all existing site scripts.
*/
SiteScripts.prototype.getSiteScripts = function () {
return this.clone(SiteScripts, "GetSiteScripts", true).execute({});
};
/**
* Creates a new site script.
*
* @param title The display name of the site design.
* @param content JSON value that describes the script. For more information, see JSON reference.
*/
SiteScripts.prototype.createSiteScript = function (title, description, content) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.clone(SiteScripts, "CreateSiteScript(Title=@title,Description=@desc)?@title='" + encodeURIComponent(title) + "'&@desc='" + encodeURIComponent(description) + "'")
.execute(content)];
case 1: return [2 /*return*/, _a.sent()];
}
});
});
};
/**
* Gets information about a specific site script. It also returns the JSON of the script.
*
* @param id The ID of the site script to get information about.
*/
SiteScripts.prototype.getSiteScriptMetadata = function (id) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.clone(SiteScripts, "GetSiteScriptMetadata").execute({ id: id })];
case 1: return [2 /*return*/, _a.sent()];
}
});
});
};
/**
* Deletes a site script.
*
* @param id The ID of the site script to delete.
*/
SiteScripts.prototype.deleteSiteScript = function (id) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.clone(SiteScripts, "DeleteSiteScript").execute({ id: id })];
case 1:
_a.sent();
return [2 /*return*/];
}
});
});
};
/**
* Updates a site script with new values. In the REST call, all parameters are optional except the site script Id.
*
* @param siteScriptUpdateInfo Object that contains the information to update a site script.
* Make sure you stringify the content object or pass it in the second 'content' parameter
* @param content (Optional) A new JSON script defining the script actions. For more information, see Site design JSON schema.
*/
SiteScripts.prototype.updateSiteScript = function (siteScriptUpdateInfo, content) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (content) {
siteScriptUpdateInfo.Content = JSON.stringify(content);
}
return [4 /*yield*/, this.clone(SiteScripts, "UpdateSiteScript").execute({ updateInfo: siteScriptUpdateInfo })];
case 1: return [2 /*return*/, _a.sent()];
}
});
});
};
return SiteScripts;
}(SharePointQueryable));
/**
* Implements the site designs API REST methods
*
*/
var SiteDesigns = /** @class */ (function (_super) {
__extends(SiteDesigns, _super);
/**
* Creates a new instance of the SiteDesigns method class
*
* @param baseUrl The parent url provider
* @param methodName The static method name to call on the utility class
*/
function SiteDesigns(baseUrl, methodName) {
return _super.call(this, SiteDesigns.getBaseUrl(baseUrl), "_api/Microsoft.Sharepoint.Utilities.WebTemplateExtensions.SiteScriptUtility." + methodName) || this;
}
SiteDesigns.getBaseUrl = function (candidate) {
if (typeof candidate === "string") {
return candidate;
}
var c = candidate;
var url = c.toUrl();
var index = url.indexOf("_api/");
if (index < 0) {
return url;
}
return url.substr(0, index);
};
SiteDesigns.prototype.execute = function (props) {
return this.postCore({
body: JSON.stringify(props),
headers: {
"Content-Type": "application/json;charset=utf-8",
},
});
};
/**
* Creates a new site design available to users when they create a new site from the SharePoint home page.
*
* @param creationInfo A sitedesign creation information object
*/
SiteDesigns.prototype.createSiteDesign = function (creationInfo) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.clone(SiteDesigns, "CreateSiteDesign").execute({ info: creationInfo })];
case 1: return [2 /*return*/, _a.sent()];
}
});
});
};
/**
* Applies a site design to an existing site collection.
*
* @param siteDesignId The ID of the site design to apply.
* @param webUrl The URL of the site collection where you want to apply the site design.
*/
SiteDesigns.prototype.applySiteDesign = function (siteDesignId, webUrl) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.clone(SiteDesigns, "ApplySiteDesign").execute({ siteDesignId: siteDesignId, "webUrl": webUrl })];
case 1: return [2 /*return*/, _a.sent()];
}
});
});
};
/**
* Gets a list of information about existing site designs.
*/
SiteDesigns.prototype.getSiteDesigns = function () {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.clone(SiteDesigns, "GetSiteDesigns").execute({})];
case 1: return [2 /*return*/, _a.sent()];
}
});
});
};
/**
* Gets information about a specific site design.
* @param id The ID of the site design to get information about.
*/
SiteDesigns.prototype.getSiteDesignMetadata = function (id) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.clone(SiteDesigns, "GetSiteDesignMetadata").execute({ id: id })];
case 1: return [2 /*return*/, _a.sent()];
}
});
});
};
/**
* Updates a site design with new values. In the REST call, all parameters are optional except the site script Id.
* If you had previously set the IsDefault parameter to TRUE and wish it to remain true, you must pass in this parameter again (otherwise it will be reset to FALSE).
* @param updateInfo A sitedesign update information object
*/
SiteDesigns.prototype.updateSiteDesign = function (updateInfo) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.clone(SiteDesigns, "UpdateSiteDesign").execute({ updateInfo: updateInfo })];
case 1: return [2 /*return*/, _a.sent()];
}
});
});
};
/**
* Deletes a site design.
* @param id The ID of the site design to delete.
*/
SiteDesigns.prototype.deleteSiteDesign = function (id) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.clone(SiteDesigns, "DeleteSiteDesign").execute({ id: id })];
case 1: return [2 /*return*/, _a.sent()];
}
});
});
};
/**
* Gets a list of principals that have access to a site design.
* @param id The ID of the site design to get rights information from.
*/
SiteDesigns.prototype.getSiteDesignRights = function (id) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.clone(SiteDesigns, "GetSiteDesignRights").execute({ id: id })];
case 1: return [2 /*return*/, _a.sent()];
}
});
});
};
/**
* Grants access to a site design for one or more principals.
* @param id The ID of the site design to grant rights on.
* @param principalNames An array of one or more principals to grant view rights.
* Principals can be users or mail-enabled security groups in the form of "alias" or "alias@<domain name>.com"
* @param grantedRights Always set to 1. This represents the View right.
*/
SiteDesigns.prototype.grantSiteDesignRights = function (id, principalNames, grantedRights) {
if (grantedRights === void 0) { grantedRights = 1; }
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.clone(SiteDesigns, "GrantSiteDesignRights")
.execute({
"grantedRights": grantedRights.toString(),
"id": id,
"principalNames": principalNames,
})];
case 1: return [2 /*return*/, _a.sent()];
}
});
});
};
/**
* Revokes access from a site design for one or more principals.
* @param id The ID of the site design to revoke rights from.
* @param principalNames An array of one or more principals to revoke view rights from.
* If all principals have rights revoked on the site design, the site design becomes viewable to everyone.
*/
SiteDesigns.prototype.revokeSiteDesignRights = function (id, principalNames) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.clone(SiteDesigns, "RevokeSiteDesignRights")
.execute({
"id": id,
"principalNames": principalNames,
})];
case 1: return [2 /*return*/, _a.sent()];
}
});
});
};
return SiteDesigns;
}(SharePointQueryable));
/**
* Allows for calling of the static SP.Utilities.Utility methods by supplying the method name
*/
var UtilityMethod = /** @class */ (function (_super) {
__extends(UtilityMethod, _super);
/**
* Creates a new instance of the Utility method class
*
* @param baseUrl The parent url provider
* @param methodName The static method name to call on the utility class
*/
function UtilityMethod(baseUrl, methodName) {
return _super.call(this, UtilityMethod.getBaseUrl(baseUrl), "_api/SP.Utilities.Utility." + methodName) || this;
}
UtilityMethod.getBaseUrl = function (candidate) {
if (typeof candidate === "string") {
return candidate;
}
var c = candidate;
var url = c.toUrl();
var index = url.indexOf("_api/");
if (index < 0) {
return url;
}
return url.substr(0, index);
};
UtilityMethod.prototype.excute = function (props) {
return this.postCore({
body: common.jsS(props),
});
};
/**
* Sends an email based on the supplied properties
*
* @param props The properties of the email to send
*/
UtilityMethod.prototype.sendEmail = function (props) {
var params = {
properties: common.extend(metadata("SP.Utilities.EmailProperties"), {
Body: props.Body,
From: props.From,
Subject: props.Subject,
}),
};
if (props.To && props.To.length > 0) {
params.properties = common.extend(params.properties, {
To: { results: props.To },
});
}
if (props.CC && props.CC.length > 0) {
params.properties = common.extend(params.properties, {
CC: { results: props.CC },
});
}
if (props.BCC && props.BCC.length > 0) {
params.properties = common.extend(params.properties, {
BCC: { results: props.BCC },
});
}
if (props.AdditionalHeaders) {
params.properties = common.extend(params.properties, {
AdditionalHeaders: props.AdditionalHeaders,
});
}
return this.clone(UtilityMethod, "SendEmail", true).excute(params);
};
UtilityMethod.prototype.getCurrentUserEmailAddresses = function () {
return this.clone(UtilityMethod, "GetCurrentUserEmailAddresses", true).excute({});
};
UtilityMethod.prototype.resolvePrincipal = function (input, scopes, sources, inputIsEmailOnly, addToUserInfoList, matchUserInfoList) {
if (matchUserInfoList === void 0) { matchUserInfoList = false; }
var params = {
addToUserInfoList: addToUserInfoList,
input: input,
inputIsEmailOnly: inputIsEmailOnly,
matchUserInfoList: matchUserInfoList,
scopes: scopes,
sources: sources,
};
return this.clone(UtilityMethod, "ResolvePrincipalInCurrentContext", true).excute(params);
};
UtilityMethod.prototype.searchPrincipals = function (input, scopes, sources, groupName, maxCount) {
var params = {
groupName: groupName,
input: input,
maxCount: maxCount,
scopes: scopes,
sources: sources,
};
return this.clone(UtilityMethod, "SearchPrincipalsUsingContextWeb", true).excute(params);
};
UtilityMethod.prototype.createEmailBodyForInvitation = function (pageAddress) {
var params = {
pageAddress: pageAddress,
};
return this.clone(UtilityMethod, "CreateEmailBodyForInvitation", true).excute(params);
};
UtilityMethod.prototype.expandGroupsToPrincipals = function (inputs, maxCount) {
if (maxCount === void 0) { maxCount = 30; }
var params = {
inputs: inputs,
maxCount: maxCount,
};
return this.clone(UtilityMethod, "ExpandGroupsToPrincipals", true).excute(params);
};
UtilityMethod.prototype.createWikiPage = function (info) {
return this.clone(UtilityMethod, "CreateWikiPageInContextWeb", true).excute({
parameters: info,
}).then(function (r) {
return {
data: r,
file: new File(odataUrlFrom(r)),
};
});
};
/**
* Checks if file or folder name contains invalid characters
*
* @param input File or folder name to check
* @param onPremise Set to true for SharePoint On-Premise
* @returns True if contains invalid chars, false otherwise
*/
UtilityMethod.prototype.containsInvalidFileFolderChars = function (input, onPremise) {
if (onPremise === void 0) { onPremise = false; }
if (onPremise) {
return UtilityMethod.InvalidFileFolderNameCharsOnPremiseRegex.test(input);
}
else {
return UtilityMethod.InvalidFileFolderNameCharsOnlineRegex.test(input);
}
};
/**
* Removes invalid characters from file or folder name
*
* @param input File or folder name
* @param replacer Value that will replace invalid characters
* @param onPremise Set to true for SharePoint On-Premise
* @returns File or folder name with replaced invalid characters
*/
UtilityMethod.prototype.stripInvalidFileFolderChars = function (input, replacer, onPremise) {
if (replacer === void 0) { replacer = ""; }
if (onPremise === void 0) { onPremise = false; }
if (onPremise) {
return input.replace(UtilityMethod.InvalidFileFolderNameCharsOnPremiseRegex, replacer);
}
else {
return input.replace(UtilityMethod.InvalidFileFolderNameCharsOnlineRegex, replacer);
}
};
UtilityMethod.InvalidFileFolderNameCharsOnlineRegex = /["*:<>?/\\|\x00-\x1f\x7f-\x9f]/g;
UtilityMethod.InvalidFileFolderNameCharsOnPremiseRegex = /["#%*:<>?/\\|\x00-\x1f\x7f-\x9f]/g;
return UtilityMethod;
}(SharePointQueryable));
/**
* Root of the SharePoint REST module
*/
var SPRest = /** @class */ (function () {
/**
* Creates a new instance of the SPRest class
*
* @param options Additional options
* @param baseUrl A string that should form the base part of the url
*/
function SPRest(_options, _baseUrl) {
if (_options === void 0) { _options = {}; }
if (_baseUrl === void 0) { _baseUrl = ""; }
this._options = _options;
this._baseUrl = _baseUrl;
}
/**
* Configures instance with additional options and baseUrl.
* Provided configuration used by other objects in a chain
*
* @param options Additional options
* @param baseUrl A string that should form the base part of the url
*/
SPRest.prototype.configure = function (options, baseUrl) {
if (baseUrl === void 0) { baseUrl = ""; }
return new SPRest(options, baseUrl);
};
/**
* Global SharePoint configuration options
*
* @param config The SharePoint configuration to apply
*/
SPRest.prototype.setup = function (config) {
setup(config);
};
/**
* Executes a search against this web context
*
* @param query The SearchQuery definition
*/
SPRest.prototype.searchSuggest = function (query) {
var finalQuery;
if (typeof query === "string") {
finalQuery = { querytext: query };
}
else {
finalQuery = query;
}
return this.create(SearchSuggest).execute(finalQuery);
};
/**
* Executes a search against this web context
*
* @param query The SearchQuery definition
*/
SPRest.prototype.search = function (query) {
return this.create(Search).execute(query);
};
/**
* Executes the provided search query, caching the results
*
* @param query The SearchQuery definition
* @param options The set of caching options used to store the results
*/
SPRest.prototype.searchWithCaching = function (query, options) {
return this.create(Search).usingCaching(options).execute(query);
};
Object.defineProperty(SPRest.prototype, "site", {
/**
* Begins a site collection scoped REST request
*
*/
get: function () {
return this.create(Site);
},
enumerable: true,
configurable: true
});
Object.defineProperty(SPRest.prototype, "web", {
/**
* Begins a web scoped REST request
*
*/
get: function () {
return this.create(Web);
},
enumerable: true,
configurable: true
});
Object.defineProperty(SPRest.prototype, "profiles", {
/**
* Access to user profile methods
*
*/
get: function () {
return this.create(UserProfileQuery);
},
enumerable: true,
configurable: true
});
Object.defineProperty(SPRest.prototype, "social", {
/**
* Access to social methods
*/
get: function () {
return this.create(SocialQuery);
},
enumerable: true,
configurable: true
});
Object.defineProperty(SPRest.prototype, "navigation", {
/**
* Access to the site collection level navigation service
*/
get: function () {
return new NavigationService();
},
enumerable: true,
configurable: true
});
/**
* Creates a new batch object for use with the SharePointQueryable.addToBatch method
*
*/
SPRest.prototype.createBatch = function () {
return this.web.createBatch();
};
Object.defineProperty(SPRest.prototype, "utility", {
/**
* Static utilities methods from SP.Utilities.Utility
*/
get: function () {
return this.create(UtilityMethod, "");
},
enumerable: true,
configurable: true
});
Object.defineProperty(SPRest.prototype, "siteScripts", {
/**
* Access to sitescripts methods
*/
get: function () {
return this.create(SiteScripts, "");
},
enumerable: true,
configurable: true
});
Object.defineProperty(SPRest.prototype, "siteDesigns", {
/**
* Access to sitedesigns methods
*/
get: function () {
return this.create(SiteDesigns, "");
},
enumerable: true,
configurable: true
});
/**
* Handles creating and configuring the objects returned from this class
*
* @param fm The factory method used to create the instance
* @param path Optional additional path information to pass to the factory method
*/
SPRest.prototype.create = function (fm, path) {
return new fm(this._baseUrl, path).configure(this._options);
};
return SPRest;
}());
var sp = new SPRest();
exports.odataUrlFrom = odataUrlFrom;
exports.spODataEntity = spODataEntity;
exports.spODataEntityArray = spODataEntityArray;
exports.SharePointQueryable = SharePointQueryable;
exports.SharePointQueryableInstance = SharePointQueryableInstance;
exports.SharePointQueryableCollection = SharePointQueryableCollection;
exports.SharePointQueryableSecurable = SharePointQueryableSecurable;
exports.FileFolderShared = FileFolderShared;
exports.SharePointQueryableShareable = SharePointQueryableShareable;
exports.SharePointQueryableShareableFile = SharePointQueryableShareableFile;
exports.SharePointQueryableShareableFolder = SharePointQueryableShareableFolder;
exports.SharePointQueryableShareableItem = SharePointQueryableShareableItem;
exports.SharePointQueryableShareableWeb = SharePointQueryableShareableWeb;
exports.AppCatalog = AppCatalog;
exports.App = App;
exports.SPBatch = SPBatch;
exports.ContentType = ContentType;
exports.ContentTypes = ContentTypes;
exports.FieldLink = FieldLink;
exports.FieldLinks = FieldLinks;
exports.Field = Field;
exports.Fields = Fields;
exports.File = File;
exports.Files = Files;
exports.Folder = Folder;
exports.Folders = Folders;
exports.SPHttpClient = SPHttpClient;
exports.Item = Item;
exports.Items = Items;
exports.ItemVersion = ItemVersion;
exports.ItemVersions = ItemVersions;
exports.PagedItemCollection = PagedItemCollection;
exports.NavigationNodes = NavigationNodes;
exports.NavigationNode = NavigationNode;
exports.NavigationService = NavigationService;
exports.List = List;
exports.Lists = Lists;
exports.RegionalSettings = RegionalSettings;
exports.InstalledLanguages = InstalledLanguages;
exports.TimeZone = TimeZone;
exports.TimeZones = TimeZones;
exports.sp = sp;
exports.SPRest = SPRest;
exports.RoleDefinitionBindings = RoleDefinitionBindings;
exports.Search = Search;
exports.SearchQueryBuilder = SearchQueryBuilder;
exports.SearchResults = SearchResults;
exports.SearchBuiltInSourceId = SearchBuiltInSourceId;
exports.SearchSuggest = SearchSuggest;
exports.Site = Site;
exports.UserProfileQuery = UserProfileQuery;
exports.toAbsoluteUrl = toAbsoluteUrl;
exports.extractWebUrl = extractWebUrl;
exports.UtilityMethod = UtilityMethod;
exports.View = View;
exports.Views = Views;
exports.ViewFields = ViewFields;
exports.WebPartDefinitions = WebPartDefinitions;
exports.WebPartDefinition = WebPartDefinition;
exports.WebPart = WebPart;
exports.Web = Web;
exports.SiteScripts = SiteScripts;
exports.SiteDesigns = SiteDesigns;
exports.ClientSidePage = ClientSidePage;
exports.CanvasSection = CanvasSection;
exports.CanvasControl = CanvasControl;
exports.CanvasColumn = CanvasColumn;
exports.ClientSidePart = ClientSidePart;
exports.ClientSideText = ClientSideText;
exports.ClientSideWebpart = ClientSideWebpart;
exports.Comments = Comments;
exports.Comment = Comment;
exports.Replies = Replies;
exports.SocialQuery = SocialQuery;
exports.MySocialQuery = MySocialQuery;
Object.defineProperty(exports, '__esModule', { value: true });
})));
//# sourceMappingURL=sp.es5.umd.js.map
|
import _extends from "@babel/runtime/helpers/esm/extends";
import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
import * as React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import withStyles from '../styles/withStyles';
import capitalize from '../utils/capitalize';
export var styles = function styles(theme) {
return {
/* Styles applied to the root element. */
root: {
boxSizing: 'border-box',
lineHeight: '48px',
listStyle: 'none',
color: theme.palette.text.secondary,
fontFamily: theme.typography.fontFamily,
fontWeight: theme.typography.fontWeightMedium,
fontSize: theme.typography.pxToRem(14)
},
/* Styles applied to the root element if `color="primary"`. */
colorPrimary: {
color: theme.palette.primary.main
},
/* Styles applied to the root element if `color="inherit"`. */
colorInherit: {
color: 'inherit'
},
/* Styles applied to the inner `component` element if `disableGutters={false}`. */
gutters: {
paddingLeft: 16,
paddingRight: 16
},
/* Styles applied to the root element if `inset={true}`. */
inset: {
paddingLeft: 72
},
/* Styles applied to the root element if `disableSticky={false}`. */
sticky: {
position: 'sticky',
top: 0,
zIndex: 1,
backgroundColor: 'inherit'
}
};
};
var ListSubheader = React.forwardRef(function ListSubheader(props, ref) {
var classes = props.classes,
className = props.className,
_props$color = props.color,
color = _props$color === void 0 ? 'default' : _props$color,
_props$component = props.component,
Component = _props$component === void 0 ? 'li' : _props$component,
_props$disableGutters = props.disableGutters,
disableGutters = _props$disableGutters === void 0 ? false : _props$disableGutters,
_props$disableSticky = props.disableSticky,
disableSticky = _props$disableSticky === void 0 ? false : _props$disableSticky,
_props$inset = props.inset,
inset = _props$inset === void 0 ? false : _props$inset,
other = _objectWithoutProperties(props, ["classes", "className", "color", "component", "disableGutters", "disableSticky", "inset"]);
return /*#__PURE__*/React.createElement(Component, _extends({
className: clsx(classes.root, className, color !== 'default' && classes["color".concat(capitalize(color))], inset && classes.inset, !disableSticky && classes.sticky, !disableGutters && classes.gutters),
ref: ref
}, other));
});
process.env.NODE_ENV !== "production" ? ListSubheader.propTypes = {
/**
* The content of the component.
*/
children: PropTypes.node,
/**
* Override or extend the styles applied to the component.
* See [CSS API](#css) below for more details.
*/
classes: PropTypes.object.isRequired,
/**
* @ignore
*/
className: PropTypes.string,
/**
* The color of the component. It supports those theme colors that make sense for this component.
*/
color: PropTypes.oneOf(['default', 'primary', 'inherit']),
/**
* The component used for the root node.
* Either a string to use a HTML element or a component.
*/
component: PropTypes.elementType,
/**
* If `true`, the List Subheader will not have gutters.
*/
disableGutters: PropTypes.bool,
/**
* If `true`, the List Subheader will not stick to the top during scroll.
*/
disableSticky: PropTypes.bool,
/**
* If `true`, the List Subheader will be indented.
*/
inset: PropTypes.bool
} : void 0;
export default withStyles(styles, {
name: 'MuiListSubheader'
})(ListSubheader);
|
const NodeUtils = {
elements: [ 'x', 'y', 'z', 'w' ],
addShortcuts: function () {
function applyShortcut( proxy, property, subProperty ) {
if ( subProperty ) {
return {
get: function () {
return this[ proxy ][ property ][ subProperty ];
},
set: function ( val ) {
this[ proxy ][ property ][ subProperty ] = val;
}
};
} else {
return {
get: function () {
return this[ proxy ][ property ];
},
set: function ( val ) {
this[ proxy ][ property ] = val;
}
};
}
}
return function addShortcuts( proto, proxy, list ) {
const shortcuts = {};
for ( let i = 0; i < list.length; ++ i ) {
const data = list[ i ].split( '.' ),
property = data[ 0 ],
subProperty = data[ 1 ];
shortcuts[ property ] = applyShortcut( proxy, property, subProperty );
}
Object.defineProperties( proto, shortcuts );
};
}()
};
export { NodeUtils };
|
exports.BattleFormats = {
pokemon: {
effectType: 'Banlist',
validateSet: function (set, format) {
var template = this.getTemplate(set.species);
var problems = [];
if (set.species === set.name) delete set.name;
if (template.gen > this.gen) {
problems.push(set.species + ' does not exist in gen ' + this.gen + '.');
} else if (template.isNonstandard) {
problems.push(set.species + ' is not a real Pokemon.');
}
var hasHP = false;
var hasSD = false;
if (set.item) {
var item = this.getItem(set.item);
if (item.gen > this.gen) {
problems.push(item.name + ' does not exist in gen ' + this.gen + '.');
} else if (item.isNonstandard) {
problems.push(item.name + ' is not a real item.');
}
}
if (set.moves) {
for (var i = 0; i < set.moves.length; i++) {
var move = this.getMove(set.moves[i]);
if (move.gen > this.gen) {
problems.push(move.name + ' does not exist in gen ' + this.gen + '.');
} else if (move.isNonstandard) {
problems.push(move.name + ' is not a real move.');
}
if (move.id === 'hiddenpower') hasHP = true;
if (move.id === 'swordsdance') hasSD = true;
}
}
if (set.moves && set.moves.length > 4) {
problems.push((set.name || set.species) + ' has more than four moves.');
}
// Automatically set ability to None
set.ability = 'None';
// In gen 2, there's no advantage on having subpar EVs and you could max all of them
set.evs = {hp: 255, atk: 255, def: 255, spa: 255, spd: 255, spe: 255};
// Check if there's Hidden Power
if (hasHP) {
// All IVs to 31 forces correct Hidden Power from Typecharts in the engine
set.ivs = {hp: 31, atk: 31, def: 31, spa: 31, spd: 31, spe: 31};
// There's no good shiny Pokémon with good HPs
set.shiny = false;
} else {
// IVs still maxed at 30 on Gen 2
if (!set.ivs) {
set.ivs = {hp: 30, atk: 30, def: 30, spa: 30, spd: 30, spe: 30};
} else {
for (var iv in set.ivs) {
// Since Gen 2 has 0-15 DVs that increase 2 points, we only want pair numbers
if (set.ivs[iv] % 2 !== 0) set.ivs[iv]--;
// This shouldn't even be possible
if (set.ivs[iv] > 30) set.ivs[iv] = 30;
}
// Special is one IV, we use spa for spa and spd.
set.ivs.spd = set.ivs.spa;
}
// Calculate all the IV oddness on gen 2.
// If you use Marowak with Thick Club, we'll be gentle enough to deal with your Attack DVs.
// This is only done because the gen 6 Teambuilder is confusing, using IVs and all.
var marowakClub = false;
if (toId(set.item) === 'thickclub' && set.species === 'Marowak' && hasSD) {
set.ivs.atk = 26;
marowakClub = true;
}
// Don't run shinies, they fuck your IVs
if (set.shiny) {
set.ivs.def = 20;
set.ivs.spe = 20;
set.ivs.spa = 20;
set.ivs.spd = 20;
// Attack can vary, so let's check it
if (!(set.ivs.atk in {4:1, 6:1, 12:1, 14:1, 20:1, 22:1, 28:1, 30:1})) {
set.ivs.atk = marowakClub ? 22 : 30;
}
}
// Deal with female IVs.
if (!template.gender) {
set.gender = 'M';
// 0001 (1 DV = 2 IV) Gender value 1:7
if (template.genderRatio && template.genderRatio.F === 0.125 && set.ivs.atk < 3) {
set.gender = 'F';
}
// 0010 (2 DV = 4 IV) Gender value 1:3
if (template.genderRatio && template.genderRatio.F === 0.25 && set.ivs.atk < 5) {
set.gender = 'F';
}
// 0011 (3 DV = 6 IV) Gender value 1:1
if (!template.genderRatio && set.ivs.atk < 7) {
set.gender = 'F';
}
// 0100 (4 DV = 8 IV) Gender value 3:1
if (template.genderRatio && template.genderRatio.F === 0.75 && set.ivs.atk < 9) {
set.gender = 'F';
}
}
// The HP IV is calculated with the last bit of every value. Do this last.
set.ivs.hp = (((set.ivs.atk / 2) % 2 * 8) + ((set.ivs.def / 2) % 2 * 4) + ((set.ivs.spe / 2) % 2 * 2) + ((set.ivs.spa / 2) % 2 * 1)) * 2;
}
// They all also get a useless nature, since that didn't exist
set.nature = 'Serious';
return problems;
}
},
standard: {
effectType: 'Banlist',
ruleset: ['Sleep Clause Mod', 'Species Clause', 'OHKO Clause', 'Evasion Moves Clause', 'HP Percentage Mod'],
banlist: ['Unreleased', 'Illegal',
'Hypnosis + Perish Song + Mean Look',
'Hypnosis + Perish Song + Spider Web',
'Lovely Kiss + Perish Song + Mean Look',
'Lovely Kiss + Perish Song + Spider Web',
'Sing + Perish Song + Mean Look',
'Sing + Perish Song + Spider Web',
'Sleep Powder + Perish Song + Mean Look',
'Sleep Powder + Perish Song + Spider Web',
'Spore + Perish Song + Mean Look',
'Spore + Perish Song + Spider Web'
],
validateSet: function (set) {
// limit one of each move in Standard
var moves = [];
if (set.moves) {
var hasMove = {};
for (var i = 0; i < set.moves.length; i++) {
var move = this.getMove(set.moves[i]);
var moveid = move.id;
if (hasMove[moveid]) continue;
hasMove[moveid] = true;
moves.push(set.moves[i]);
}
}
set.moves = moves;
}
}
};
|
import page from 'page';
import User from '../models/user';
import Board from '../models/board';
import Ticket from '../models/ticket';
import request from '../utils/request';
/**
* NOTE We use a lot of Model.fromJS.toJS conversion here, this is so that we
* can be sure the data we resolve to is formatted properly. This is not
* necessarily the most clean way, but it will do for now.
*/
export default {
login: login,
loginGuest: loginGuest,
logout: logout,
register: register,
giveBoardAccess: giveBoardAccess,
getUser: getUser,
getBoard: getBoard,
getBoards: getBoards,
getTicket: getTicket,
getTickets: getTickets,
getComments: getComments,
updateUserPassword: updateUserPassword,
updateUser: updateUser,
createBoard: createBoard,
createTicket: createTicket,
createComment: createComment,
updateBoard: updateBoard,
updateTicket: updateTicket,
deleteBoard: deleteBoard,
deleteTicket: deleteTicket,
revokeAccessCode: revokeAccessCode,
generateAccessCode: generateAccessCode,
setUserBoardActivity: setUserBoardActivity,
queryApiVersion: queryApiVersion,
queryImgVersion: queryImgVersion
}
const API_URL = process.env.API_URL || 'http://localhost:9002/api';
function login(opts = {}) {
let provider = 'basic';
let auth = 'basic ' + new Buffer(opts.payload.email + ':' + opts.payload.password).toString('base64');
let options = {
url: `${API_URL}/auth/`+ provider + `/login`,
auth: auth
}
return request.get(options).then((res) => {
return {
user: User.fromJS(res.body).toJS(),
token: res.headers['x-access-token']
}
});
}
function logout(opts = {}) {
let options = {
url: `${API_URL}/auth/logout`,
token: opts.token
}
return request.post(options);
}
function register(opts = {}) {
let options = {
url: `${API_URL}/auth/register`,
payload: opts.payload
}
return request.post(options).then((res) => {
return {
user: User.fromJS(res.body).toJS()
}
});
}
function loginGuest(opts = {}) {
let options = {
url: `${API_URL}/boards/${opts.id.board}/access/${opts.id.code}`,
payload: opts.payload
}
return request.post(options).then((res) => {
return {
user: User.fromJS(res.body).toJS(),
token: res.headers['x-access-token']
}
});
}
function giveBoardAccess(opts = {}) {
let options = {
url: `${API_URL}/boards/${opts.id.board}/access/${opts.id.code}/grantaccess`,
token: opts.token
}
return request.put(options).then((res) => {
return Board.fromJS(res.body).toJS();
});
}
function getUser(opts = {}) {
let options = {
url: `${API_URL}/auth`,
token: opts.token
}
return request.get(options).then((res) => {
return User.fromJS(res.body).toJS();
});
}
function getBoard(opts = {}) {
let options = {
url: `${API_URL}/boards/${opts.id.board}`,
token: opts.token
}
return request.get(options).then((res) => {
let board = Board.fromJS(res.body).toJS();
// Remove the empty 'tickets' collection to prevent overwriting.
delete board.tickets;
return board;
});
}
function getBoards(opts = {}) {
let options = {
url: `${API_URL}/boards`,
token: opts.token
}
return request.get(options).then((res) => {
return res.body.map((board) => {
board = Board.fromJS(board).toJS();
// Remove the empty 'tickets' collection to prevent overwriting.
delete board.tickets;
return board;
});
});
}
function getTicket(opts = {}) {
let options = {
url: `${API_URL}/boards/${opts.id.board}/tickets/${opts.id.ticket}`,
token: opts.token
}
return request.get(options).then((res) => {
return Ticket.fromJS(res.body).toJS();
});
}
function getTickets(opts = {}) {
let options = {
url: `${API_URL}/boards/${opts.id.board}/tickets`,
token: opts.token
}
return request.get(options).then((res) => {
return res.body.map((ticket) => {
return Ticket.fromJS(ticket).toJS();
});
});
}
function parseCommentFromEvent(event) {
return {
id: event.id,
message: event.data.message,
createdBy: event.user,
createdAt: event.createdAt
}
}
function getComments(opts = {}) {
let options = {
url: `${API_URL}/boards/${opts.id.board}/tickets/${opts.id.ticket}/comments`,
token: opts.token
}
return request.get(options)
.then(res => res.body.map(parseCommentFromEvent));
}
function createComment(opts = {}) {
let options = {
url: `${API_URL}/boards/${opts.id.board}/tickets/${opts.id.ticket}/comments`,
token: opts.token,
payload: opts.payload
}
return request.post(options).then(res => parseCommentFromEvent(res.body));
}
function createBoard(opts = {}) {
let options = {
url: `${API_URL}/boards`,
token: opts.token,
payload: opts.payload
}
return request.post(options).then((res) => {
return Board.fromJS(res.body).toJS();
});
}
function createTicket(opts = {}) {
let options = {
url: `${API_URL}/boards/${opts.id.board}/tickets`,
token: opts.token,
payload: opts.payload
}
return request.post(options).then((res) => {
return Ticket.fromJS(res.body).toJS();
});
}
function updateUser(opts = {}) {
let options = {
url: `${API_URL}/user/edit`,
token: opts.token,
payload: opts.payload
}
return request.put(options).then((res) => {
return User.fromJS(res.body).toJS();
});
}
function updateUserPassword(opts = {}) {
let options = {
url: `${API_URL}/user/changepw`,
token: opts.token,
payload: opts.payload
}
return request.put(options).then((res) => {
return User.fromJS(res.body).toJS();
});
}
function updateBoard(opts = {}) {
let options = {
url: `${API_URL}/boards/${opts.id.board}`,
token: opts.token,
payload: opts.payload
}
return request.put(options).then((res) => {
let board = Board.fromJS(res.body).toJS();
// Remove the empty 'tickets' collection to prevent overwriting.
delete board.tickets;
return board;
});
}
function updateTicket(opts = {}) {
let options = {
url: `${API_URL}/boards/${opts.id.board}/tickets/${opts.id.ticket}`,
token: opts.token,
payload: opts.payload
}
return request.put(options).then((res) => {
return Ticket.fromJS(res.body).toJS();
});
}
function deleteBoard(opts = {}) {
let options = {
url: `${API_URL}/boards/${opts.id.board}`,
token: opts.token
}
return request.del(options).then((res) => {
let board = Board.fromJS(res.body).toJS();
// Remove the empty 'tickets' collection to prevent overwriting.
delete board.tickets;
return board;
});
}
function deleteTicket(opts = {}) {
let options = {
url: `${API_URL}/boards/${opts.id.board}/tickets/${opts.id.ticket}`,
token: opts.token
}
return request.del(options)
}
function setUserBoardActivity(opts = {}) {
let options = {
url: `${API_URL}/boards/${opts.id.board}/setactivity`,
token: opts.token,
payload: opts.payload
}
if(opts.isPoll) {
return request.put(options);
} else {
return request.post(options);
}
}
function generateAccessCode(opts = {}) {
let options = {
url: `${API_URL}/boards/${opts.id.board}/access`,
token: opts.token
}
return request.post(options).then((res) => {
let board = Board.fromJS(res.body).toJS();
// Remove the empty 'tickets' collection to prevent overwriting.
delete board.tickets;
return board;
});
}
function revokeAccessCode(opts = {}) {
let options = {
url: `${API_URL}/boards/${opts.id.board}/access`,
token: opts.token
}
return request.del(options);
}
function queryApiVersion(opts = {}) {
let options = {
url: `${API_URL}/version/api`,
token: opts.token
}
return request.get(options).then((res) => {
return res.body;
});
}
function queryImgVersion(opts = {}) {
let options = {
url: `${API_URL}/version/img`,
token: opts.token
}
return request.get(options).then((res) => {
return res.body;
});
}
|
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
function getDecimals(n) {
n = n + '';
var i = n.indexOf('.');
return (i == -1) ? 0 : n.length - i - 1;
}
function getVF(n, opt_precision) {
var v = opt_precision;
if (undefined === v) {
v = Math.min(getDecimals(n), 3);
}
var base = Math.pow(10, v);
var f = ((n * base) | 0) % base;
return {v: v, f: f};
}
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"k\u00edk\u00edr\u00edg",
"ng\u0259g\u00f3g\u0259le"
],
"DAY": [
"s\u0254\u0301nd\u0254",
"m\u0254\u0301ndi",
"s\u0254\u0301nd\u0254 m\u0259l\u00fa m\u0259\u0301b\u025b\u030c",
"s\u0254\u0301nd\u0254 m\u0259l\u00fa m\u0259\u0301l\u025b\u0301",
"s\u0254\u0301nd\u0254 m\u0259l\u00fa m\u0259\u0301nyi",
"f\u00falad\u00e9",
"s\u00e9rad\u00e9"
],
"MONTH": [
"ng\u0254n os\u00fa",
"ng\u0254n b\u025b\u030c",
"ng\u0254n l\u00e1la",
"ng\u0254n nyina",
"ng\u0254n t\u00e1na",
"ng\u0254n sam\u0259na",
"ng\u0254n zamgb\u00e1la",
"ng\u0254n mwom",
"ng\u0254n ebul\u00fa",
"ng\u0254n aw\u00f3m",
"ng\u0254n aw\u00f3m ai dzi\u00e1",
"ng\u0254n aw\u00f3m ai b\u025b\u030c"
],
"SHORTDAY": [
"s\u0254\u0301n",
"m\u0254\u0301n",
"smb",
"sml",
"smn",
"f\u00fal",
"s\u00e9r"
],
"SHORTMONTH": [
"ngo",
"ngb",
"ngl",
"ngn",
"ngt",
"ngs",
"ngz",
"ngm",
"nge",
"nga",
"ngad",
"ngab"
],
"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": "FCFA",
"DECIMAL_SEP": ",",
"GROUP_SEP": "\u00a0",
"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": "ewo",
"pluralCat": function(n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]);
|
/**
* @author alteredq / http://alteredqualia.com/
*
* parameters = {
* defines: { "label" : "value" },
* uniforms: { "parameter1": { type: "1f", value: 1.0 }, "parameter2": { type: "1i" value2: 2 } },
*
* fragmentShader: <string>,
* vertexShader: <string>,
*
* shading: THREE.SmoothShading,
*
* wireframe: <boolean>,
* wireframeLinewidth: <float>,
*
* lights: <bool>,
*
* vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
*
* skinning: <bool>,
* morphTargets: <bool>,
* morphNormals: <bool>,
*
* fog: <bool>
* }
*/
THREE.ShaderMaterial = function ( parameters ) {
THREE.Material.call( this );
this.type = 'ShaderMaterial';
this.defines = {};
this.uniforms = {};
this.vertexShader = 'void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}';
this.fragmentShader = 'void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}';
this.shading = THREE.SmoothShading;
this.linewidth = 1;
this.wireframe = false;
this.wireframeLinewidth = 1;
this.fog = false; // set to use scene fog
this.lights = false; // set to use scene lights
this.clipping = false; // set to use user-defined clipping planes
this.vertexColors = THREE.NoColors; // set to use "color" attribute stream
this.skinning = false; // set to use skinning attribute streams
this.morphTargets = false; // set to use morph targets
this.morphNormals = false; // set to use morph normals
this.extensions = {
derivatives: false, // set to use derivatives
fragDepth: false, // set to use fragment depth values
drawBuffers: false, // set to use draw buffers
shaderTextureLOD: false // set to use shader texture LOD
};
// When rendered geometry doesn't include these attributes but the material does,
// use these default values in WebGL. This avoids errors when buffer data is missing.
this.defaultAttributeValues = {
'color': [ 1, 1, 1 ],
'uv': [ 0, 0 ],
'uv2': [ 0, 0 ]
};
this.index0AttributeName = undefined;
if ( parameters !== undefined ) {
if ( parameters.attributes !== undefined ) {
console.error( 'THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.' );
}
this.setValues( parameters );
}
};
THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype );
THREE.ShaderMaterial.prototype.constructor = THREE.ShaderMaterial;
THREE.ShaderMaterial.prototype.copy = function ( source ) {
THREE.Material.prototype.copy.call( this, source );
this.fragmentShader = source.fragmentShader;
this.vertexShader = source.vertexShader;
this.uniforms = THREE.UniformsUtils.clone( source.uniforms );
this.defines = source.defines;
this.shading = source.shading;
this.wireframe = source.wireframe;
this.wireframeLinewidth = source.wireframeLinewidth;
this.fog = source.fog;
this.lights = source.lights;
this.clipping = source.clipping;
this.vertexColors = source.vertexColors;
this.skinning = source.skinning;
this.morphTargets = source.morphTargets;
this.morphNormals = source.morphNormals;
this.extensions = source.extensions;
return this;
};
THREE.ShaderMaterial.prototype.toJSON = function ( meta ) {
var data = THREE.Material.prototype.toJSON.call( this, meta );
data.uniforms = this.uniforms;
data.vertexShader = this.vertexShader;
data.fragmentShader = this.fragmentShader;
return data;
};
|
import { get } from 'ember-metal/property_get';
import { set } from 'ember-metal/property_set';
QUnit.module('set');
test('should set arbitrary properties on an object', function() {
var obj = {
string: 'string',
number: 23,
boolTrue: true,
boolFalse: false,
nullValue: null,
undefinedValue: undefined
};
var newObj = {
undefinedValue: 'emberjs'
};
for (var key in obj) {
if (!obj.hasOwnProperty(key)) {
continue;
}
equal(set(newObj, key, obj[key]), obj[key], 'should return value');
equal(get(newObj, key), obj[key], 'should set value');
}
});
test('should call setUnknownProperty if defined and value is undefined', function() {
var obj = {
count: 0,
unknownProperty: function(key, value) {
ok(false, 'should not invoke unknownProperty if setUnknownProperty is defined');
},
setUnknownProperty: function(key, value) {
equal(key, 'foo', 'should pass key');
equal(value, 'BAR', 'should pass key');
this.count++;
return 'FOO';
}
};
equal(set(obj, 'foo', "BAR"), 'BAR', 'should return set value');
equal(obj.count, 1, 'should have invoked');
});
|
import basicClassCreator from '../utils/basicClassCreator';
export default basicClassCreator('mdl-layout-spacer');
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Stack = function Stack() {
_classCallCheck(this, Stack);
};
exports.default = Stack;
|
/*!
* jQuery JavaScript Library v2.1.0 -ajax,-ajax/jsonp,-ajax/load,-ajax/parseJSON,-ajax/parseXML,-ajax/script,-ajax/var/nonce,-ajax/var/rquery,-ajax/xhr,-manipulation/_evalUrl,-css,-css/addGetHookIf,-css/curCSS,-css/defaultDisplay,-css/hiddenVisibleSelectors,-css/support,-css/swap,-css/var/cssExpand,-css/var/getStyles,-css/var/isHidden,-css/var/rmargin,-css/var/rnumnonpx,-effects,-effects/Tween,-effects/animatedSelector,-dimensions,-offset,-deprecated,-event-alias
* 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: 2014-09-28T03:56Z
*/
(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+
//
var arr = [];
var slice = arr.slice;
var concat = arr.concat;
var push = arr.push;
var indexOf = arr.indexOf;
var class2type = {};
var toString = class2type.toString;
var hasOwn = class2type.hasOwnProperty;
var trim = "".trim;
var support = {};
var
// Use the correct document accordingly with window argument (sandbox)
document = window.document,
version = "2.1.0 -ajax,-ajax/jsonp,-ajax/load,-ajax/parseJSON,-ajax/parseXML,-ajax/script,-ajax/var/nonce,-ajax/var/rquery,-ajax/xhr,-manipulation/_evalUrl,-css,-css/addGetHookIf,-css/curCSS,-css/defaultDisplay,-css/hiddenVisibleSelectors,-css/support,-css/swap,-css/var/cssExpand,-css/var/getStyles,-css/var/isHidden,-css/var/rmargin,-css/var/rnumnonpx,-effects,-effects/Tween,-effects/animatedSelector,-dimensions,-offset,-deprecated,-event-alias",
// Define a local copy of jQuery
jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
// Need init if jQuery is called (just allow error to be thrown if not included)
return new jQuery.fn.init( selector, context );
},
// Matches dashed string for camelizing
rmsPrefix = /^-ms-/,
rdashAlpha = /-([\da-z])/gi,
// Used by jQuery.camelCase as callback to replace()
fcamelCase = function( all, letter ) {
return letter.toUpperCase();
};
jQuery.fn = jQuery.prototype = {
// The current version of jQuery being used
jquery: version,
constructor: jQuery,
// Start with an empty selector
selector: "",
// The default length of a jQuery object is 0
length: 0,
toArray: function() {
return slice.call( this );
},
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function( num ) {
return num != null ?
// Return a 'clean' array
( num < 0 ? this[ num + this.length ] : this[ num ] ) :
// Return just the object
slice.call( this );
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems ) {
// Build a new jQuery matched element set
var ret = jQuery.merge( this.constructor(), elems );
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
ret.context = this.context;
// Return the newly-formed element set
return ret;
},
// Execute a callback for every element in the matched set.
// (You can seed the arguments with an array of args, but this is
// only used internally.)
each: function( callback, args ) {
return jQuery.each( this, callback, args );
},
map: function( callback ) {
return this.pushStack( jQuery.map(this, function( elem, i ) {
return callback.call( elem, i, elem );
}));
},
slice: function() {
return this.pushStack( slice.apply( this, arguments ) );
},
first: function() {
return this.eq( 0 );
},
last: function() {
return this.eq( -1 );
},
eq: function( i ) {
var len = this.length,
j = +i + ( i < 0 ? len : 0 );
return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] );
},
end: function() {
return this.prevObject || this.constructor(null);
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: push,
sort: arr.sort,
splice: arr.splice
};
jQuery.extend = jQuery.fn.extend = function() {
var options, name, src, copy, copyIsArray, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
// skip the boolean and the target
target = arguments[ i ] || {};
i++;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
target = {};
}
// extend jQuery itself if only one argument is passed
if ( i === length ) {
target = this;
i--;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( (options = arguments[ i ]) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && jQuery.isArray(src) ? src : [];
} else {
clone = src && jQuery.isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[ name ] = jQuery.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
jQuery.extend({
// Unique for each copy of jQuery on the page
expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ),
// Assume jQuery is ready without the ready module
isReady: true,
error: function( msg ) {
throw new Error( msg );
},
noop: function() {},
// See test/unit/core.js for details concerning isFunction.
// Since version 1.3, DOM methods and functions like alert
// aren't supported. They return false on IE (#2968).
isFunction: function( obj ) {
return jQuery.type(obj) === "function";
},
isArray: Array.isArray,
isWindow: function( obj ) {
return obj != null && obj === obj.window;
},
isNumeric: function( obj ) {
// parseFloat NaNs numeric-cast false positives (null|true|false|"")
// ...but misinterprets leading-number strings, particularly hex literals ("0x...")
// subtraction forces infinities to NaN
return obj - parseFloat( obj ) >= 0;
},
isPlainObject: function( obj ) {
// Not plain objects:
// - Any object or value whose internal [[Class]] property is not "[object Object]"
// - DOM nodes
// - window
if ( jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}
// Support: Firefox <20
// The try/catch suppresses exceptions thrown when attempting to access
// the "constructor" property of certain host objects, ie. |window.location|
// https://bugzilla.mozilla.org/show_bug.cgi?id=814622
try {
if ( obj.constructor &&
!hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) {
return false;
}
} catch ( e ) {
return false;
}
// If the function hasn't returned already, we're confident that
// |obj| is a plain object, created by {} or constructed with new Object
return true;
},
isEmptyObject: function( obj ) {
var name;
for ( name in obj ) {
return false;
}
return true;
},
type: function( obj ) {
if ( obj == null ) {
return obj + "";
}
// Support: Android < 4.0, iOS < 6 (functionish RegExp)
return typeof obj === "object" || typeof obj === "function" ?
class2type[ toString.call(obj) ] || "object" :
typeof obj;
},
// Evaluates a script in a global context
globalEval: function( code ) {
var script,
indirect = eval;
code = jQuery.trim( code );
if ( code ) {
// If the code includes a valid, prologue position
// strict mode pragma, execute code by injecting a
// script tag into the document.
if ( code.indexOf("use strict") === 1 ) {
script = document.createElement("script");
script.text = code;
document.head.appendChild( script ).parentNode.removeChild( script );
} else {
// Otherwise, avoid the DOM node creation, insertion
// and removal by using an indirect global eval
indirect( code );
}
}
},
// Convert dashed to camelCase; used by the css and data modules
// Microsoft forgot to hump their vendor prefix (#9572)
camelCase: function( string ) {
return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
},
nodeName: function( elem, name ) {
return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
},
// args is for internal usage only
each: function( obj, callback, args ) {
var value,
i = 0,
length = obj.length,
isArray = isArraylike( obj );
if ( args ) {
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback.apply( obj[ i ], args );
if ( value === false ) {
break;
}
}
} else {
for ( i in obj ) {
value = callback.apply( obj[ i ], args );
if ( value === false ) {
break;
}
}
}
// A special, fast, case for the most common use of each
} else {
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback.call( obj[ i ], i, obj[ i ] );
if ( value === false ) {
break;
}
}
} else {
for ( i in obj ) {
value = callback.call( obj[ i ], i, obj[ i ] );
if ( value === false ) {
break;
}
}
}
}
return obj;
},
trim: function( text ) {
return text == null ? "" : trim.call( text );
},
// results is for internal usage only
makeArray: function( arr, results ) {
var ret = results || [];
if ( arr != null ) {
if ( isArraylike( Object(arr) ) ) {
jQuery.merge( ret,
typeof arr === "string" ?
[ arr ] : arr
);
} else {
push.call( ret, arr );
}
}
return ret;
},
inArray: function( elem, arr, i ) {
return arr == null ? -1 : indexOf.call( arr, elem, i );
},
merge: function( first, second ) {
var len = +second.length,
j = 0,
i = first.length;
for ( ; j < len; j++ ) {
first[ i++ ] = second[ j ];
}
first.length = i;
return first;
},
grep: function( elems, callback, invert ) {
var callbackInverse,
matches = [],
i = 0,
length = elems.length,
callbackExpect = !invert;
// Go through the array, only saving the items
// that pass the validator function
for ( ; i < length; i++ ) {
callbackInverse = !callback( elems[ i ], i );
if ( callbackInverse !== callbackExpect ) {
matches.push( elems[ i ] );
}
}
return matches;
},
// arg is for internal usage only
map: function( elems, callback, arg ) {
var value,
i = 0,
length = elems.length,
isArray = isArraylike( elems ),
ret = [];
// Go through the array, translating each of the items to their new values
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret.push( value );
}
}
// Go through every key on the object,
} else {
for ( i in elems ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret.push( value );
}
}
}
// Flatten any nested arrays
return concat.apply( [], ret );
},
// A global GUID counter for objects
guid: 1,
// Bind a function to a context, optionally partially applying any
// arguments.
proxy: function( fn, context ) {
var tmp, args, proxy;
if ( typeof context === "string" ) {
tmp = fn[ context ];
context = fn;
fn = tmp;
}
// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
if ( !jQuery.isFunction( fn ) ) {
return undefined;
}
// Simulated bind
args = slice.call( arguments, 2 );
proxy = function() {
return fn.apply( context || this, args.concat( slice.call( arguments ) ) );
};
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || jQuery.guid++;
return proxy;
},
now: Date.now,
// jQuery.support is not used in Core but other projects attach their
// properties to it so it needs to exist.
support: support
});
// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
function isArraylike( obj ) {
var length = obj.length,
type = jQuery.type( obj );
if ( type === "function" || jQuery.isWindow( obj ) ) {
return false;
}
if ( obj.nodeType === 1 && length ) {
return true;
}
return type === "array" || length === 0 ||
typeof length === "number" && length > 0 && ( length - 1 ) in obj;
}
/*
* Optional (non-Sizzle) selector module for custom builds.
*
* Note that this DOES NOT SUPPORT many documented jQuery
* features in exchange for its smaller size:
*
* Attribute not equal selector
* Positional selectors (:first; :eq(n); :odd; etc.)
* Type selectors (:input; :checkbox; :button; etc.)
* State-based selectors (:animated; :visible; :hidden; etc.)
* :has(selector)
* :not(complex selector)
* custom selectors via Sizzle extensions
* Leading combinators (e.g., $collection.find("> *"))
* Reliable functionality on XML fragments
* Requiring all parts of a selector to match elements under context
* (e.g., $div.find("div > *") now matches children of $div)
* Matching against non-elements
* Reliable sorting of disconnected nodes
* querySelectorAll bug fixes (e.g., unreliable :focus on WebKit)
*
* If any of these are unacceptable tradeoffs, either use Sizzle or
* customize this stub for the project's specific needs.
*/
var docElem = window.document.documentElement,
selector_hasDuplicate,
matches = docElem.webkitMatchesSelector ||
docElem.mozMatchesSelector ||
docElem.oMatchesSelector ||
docElem.msMatchesSelector,
selector_sortOrder = function( a, b ) {
// Flag for duplicate removal
if ( a === b ) {
selector_hasDuplicate = true;
return 0;
}
var compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b );
if ( compare ) {
// Disconnected nodes
if ( compare & 1 ) {
// Choose the first element that is related to our document
if ( a === document || jQuery.contains(document, a) ) {
return -1;
}
if ( b === document || jQuery.contains(document, b) ) {
return 1;
}
// Maintain original order
return 0;
}
return compare & 4 ? -1 : 1;
}
// Not directly comparable, sort on existence of method
return a.compareDocumentPosition ? -1 : 1;
};
jQuery.extend({
find: function( selector, context, results, seed ) {
var elem, nodeType,
i = 0;
results = results || [];
context = context || document;
// Same basic safeguard as Sizzle
if ( !selector || typeof selector !== "string" ) {
return results;
}
// Early return if context is not an element or document
if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) {
return [];
}
if ( seed ) {
while ( (elem = seed[i++]) ) {
if ( jQuery.find.matchesSelector(elem, selector) ) {
results.push( elem );
}
}
} else {
jQuery.merge( results, context.querySelectorAll(selector) );
}
return results;
},
unique: function( results ) {
var elem,
duplicates = [],
i = 0,
j = 0;
selector_hasDuplicate = false;
results.sort( selector_sortOrder );
if ( selector_hasDuplicate ) {
while ( (elem = results[i++]) ) {
if ( elem === results[ i ] ) {
j = duplicates.push( i );
}
}
while ( j-- ) {
results.splice( duplicates[ j ], 1 );
}
}
return results;
},
text: function( elem ) {
var node,
ret = "",
i = 0,
nodeType = elem.nodeType;
if ( !nodeType ) {
// If no nodeType, this is expected to be an array
while ( (node = elem[i++]) ) {
// Do not traverse comment nodes
ret += jQuery.text( node );
}
} else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
// Use textContent for elements
return elem.textContent;
} else if ( nodeType === 3 || nodeType === 4 ) {
return elem.nodeValue;
}
// Do not include comment or processing instruction nodes
return ret;
},
contains: function( a, b ) {
var adown = a.nodeType === 9 ? a.documentElement : a,
bup = b && b.parentNode;
return a === bup || !!( bup && bup.nodeType === 1 && adown.contains(bup) );
},
isXMLDoc: function( elem ) {
return (elem.ownerDocument || elem).documentElement.nodeName !== "HTML";
},
expr: {
attrHandle: {},
match: {
bool: /^(?:checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped)$/i,
needsContext: /^[\x20\t\r\n\f]*[>+~]/
}
}
});
jQuery.extend( jQuery.find, {
matches: function( expr, elements ) {
return jQuery.find( expr, null, null, elements );
},
matchesSelector: function( elem, expr ) {
return matches.call( elem, expr );
},
attr: function( elem, name ) {
return elem.getAttribute( name );
}
});
var rneedsContext = jQuery.expr.match.needsContext;
var rsingleTag = (/^<(\w+)\s*\/?>(?:<\/\1>|)$/);
var risSimple = /^.[^:#\[\.,]*$/;
// Implement the identical functionality for filter and not
function winnow( elements, qualifier, not ) {
if ( jQuery.isFunction( qualifier ) ) {
return jQuery.grep( elements, function( elem, i ) {
/* jshint -W018 */
return !!qualifier.call( elem, i, elem ) !== not;
});
}
if ( qualifier.nodeType ) {
return jQuery.grep( elements, function( elem ) {
return ( elem === qualifier ) !== not;
});
}
if ( typeof qualifier === "string" ) {
if ( risSimple.test( qualifier ) ) {
return jQuery.filter( qualifier, elements, not );
}
qualifier = jQuery.filter( qualifier, elements );
}
return jQuery.grep( elements, function( elem ) {
return ( indexOf.call( qualifier, elem ) >= 0 ) !== not;
});
}
jQuery.filter = function( expr, elems, not ) {
var elem = elems[ 0 ];
if ( not ) {
expr = ":not(" + expr + ")";
}
return elems.length === 1 && elem.nodeType === 1 ?
jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] :
jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) {
return elem.nodeType === 1;
}));
};
jQuery.fn.extend({
find: function( selector ) {
var i,
len = this.length,
ret = [],
self = this;
if ( typeof selector !== "string" ) {
return this.pushStack( jQuery( selector ).filter(function() {
for ( i = 0; i < len; i++ ) {
if ( jQuery.contains( self[ i ], this ) ) {
return true;
}
}
}) );
}
for ( i = 0; i < len; i++ ) {
jQuery.find( selector, self[ i ], ret );
}
// Needed because $( selector, context ) becomes $( context ).find( selector )
ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret );
ret.selector = this.selector ? this.selector + " " + selector : selector;
return ret;
},
filter: function( selector ) {
return this.pushStack( winnow(this, selector || [], false) );
},
not: function( selector ) {
return this.pushStack( winnow(this, selector || [], true) );
},
is: function( selector ) {
return !!winnow(
this,
// If this is a positional/relative selector, check membership in the returned set
// so $("p:first").is("p:last") won't return true for a doc with two "p".
typeof selector === "string" && rneedsContext.test( selector ) ?
jQuery( selector ) :
selector || [],
false
).length;
}
});
// Initialize a jQuery object
// A central reference to the root jQuery(document)
var rootjQuery,
// A simple way to check for HTML strings
// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
// Strict HTML recognition (#11290: must start with <)
rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,
init = jQuery.fn.init = function( selector, context ) {
var match, elem;
// HANDLE: $(""), $(null), $(undefined), $(false)
if ( !selector ) {
return this;
}
// Handle HTML strings
if ( typeof selector === "string" ) {
if ( selector[0] === "<" && selector[ selector.length - 1 ] === ">" && selector.length >= 3 ) {
// Assume that strings that start and end with <> are HTML and skip the regex check
match = [ null, selector, null ];
} else {
match = rquickExpr.exec( selector );
}
// Match html or make sure no context is specified for #id
if ( match && (match[1] || !context) ) {
// HANDLE: $(html) -> $(array)
if ( match[1] ) {
context = context instanceof jQuery ? context[0] : context;
// scripts is true for back-compat
// Intentionally let the error be thrown if parseHTML is not present
jQuery.merge( this, jQuery.parseHTML(
match[1],
context && context.nodeType ? context.ownerDocument || context : document,
true
) );
// HANDLE: $(html, props)
if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) {
for ( match in context ) {
// Properties of context are called as methods if possible
if ( jQuery.isFunction( this[ match ] ) ) {
this[ match ]( context[ match ] );
// ...and otherwise set as attributes
} else {
this.attr( match, context[ match ] );
}
}
}
return this;
// HANDLE: $(#id)
} else {
elem = document.getElementById( match[2] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Inject the element directly into the jQuery object
this.length = 1;
this[0] = elem;
}
this.context = document;
this.selector = selector;
return this;
}
// HANDLE: $(expr, $(...))
} else if ( !context || context.jquery ) {
return ( context || rootjQuery ).find( selector );
// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
return this.constructor( context ).find( selector );
}
// HANDLE: $(DOMElement)
} else if ( selector.nodeType ) {
this.context = this[0] = selector;
this.length = 1;
return this;
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return typeof rootjQuery.ready !== "undefined" ?
rootjQuery.ready( selector ) :
// Execute immediately if ready is not present
selector( jQuery );
}
if ( selector.selector !== undefined ) {
this.selector = selector.selector;
this.context = selector.context;
}
return jQuery.makeArray( selector, this );
};
// Give the init function the jQuery prototype for later instantiation
init.prototype = jQuery.fn;
// Initialize central reference
rootjQuery = jQuery( document );
var rparentsprev = /^(?:parents|prev(?:Until|All))/,
// methods guaranteed to produce a unique set when starting from a unique set
guaranteedUnique = {
children: true,
contents: true,
next: true,
prev: true
};
jQuery.extend({
dir: function( elem, dir, until ) {
var matched = [],
truncate = until !== undefined;
while ( (elem = elem[ dir ]) && elem.nodeType !== 9 ) {
if ( elem.nodeType === 1 ) {
if ( truncate && jQuery( elem ).is( until ) ) {
break;
}
matched.push( elem );
}
}
return matched;
},
sibling: function( n, elem ) {
var matched = [];
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType === 1 && n !== elem ) {
matched.push( n );
}
}
return matched;
}
});
jQuery.fn.extend({
has: function( target ) {
var targets = jQuery( target, this ),
l = targets.length;
return this.filter(function() {
var i = 0;
for ( ; i < l; i++ ) {
if ( jQuery.contains( this, targets[i] ) ) {
return true;
}
}
});
},
closest: function( selectors, context ) {
var cur,
i = 0,
l = this.length,
matched = [],
pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ?
jQuery( selectors, context || this.context ) :
0;
for ( ; i < l; i++ ) {
for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) {
// Always skip document fragments
if ( cur.nodeType < 11 && (pos ?
pos.index(cur) > -1 :
// Don't pass non-elements to Sizzle
cur.nodeType === 1 &&
jQuery.find.matchesSelector(cur, selectors)) ) {
matched.push( cur );
break;
}
}
}
return this.pushStack( matched.length > 1 ? jQuery.unique( matched ) : matched );
},
// Determine the position of an element within
// the matched set of elements
index: function( elem ) {
// No argument, return index in parent
if ( !elem ) {
return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1;
}
// index in selector
if ( typeof elem === "string" ) {
return indexOf.call( jQuery( elem ), this[ 0 ] );
}
// Locate the position of the desired element
return indexOf.call( this,
// If it receives a jQuery object, the first element is used
elem.jquery ? elem[ 0 ] : elem
);
},
add: function( selector, context ) {
return this.pushStack(
jQuery.unique(
jQuery.merge( this.get(), jQuery( selector, context ) )
)
);
},
addBack: function( selector ) {
return this.add( selector == null ?
this.prevObject : this.prevObject.filter(selector)
);
}
});
function sibling( cur, dir ) {
while ( (cur = cur[dir]) && cur.nodeType !== 1 ) {}
return cur;
}
jQuery.each({
parent: function( elem ) {
var parent = elem.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
parents: function( elem ) {
return jQuery.dir( elem, "parentNode" );
},
parentsUntil: function( elem, i, until ) {
return jQuery.dir( elem, "parentNode", until );
},
next: function( elem ) {
return sibling( elem, "nextSibling" );
},
prev: function( elem ) {
return sibling( elem, "previousSibling" );
},
nextAll: function( elem ) {
return jQuery.dir( elem, "nextSibling" );
},
prevAll: function( elem ) {
return jQuery.dir( elem, "previousSibling" );
},
nextUntil: function( elem, i, until ) {
return jQuery.dir( elem, "nextSibling", until );
},
prevUntil: function( elem, i, until ) {
return jQuery.dir( elem, "previousSibling", until );
},
siblings: function( elem ) {
return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem );
},
children: function( elem ) {
return jQuery.sibling( elem.firstChild );
},
contents: function( elem ) {
return elem.contentDocument || jQuery.merge( [], elem.childNodes );
}
}, function( name, fn ) {
jQuery.fn[ name ] = function( until, selector ) {
var matched = jQuery.map( this, fn, until );
if ( name.slice( -5 ) !== "Until" ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
matched = jQuery.filter( selector, matched );
}
if ( this.length > 1 ) {
// Remove duplicates
if ( !guaranteedUnique[ name ] ) {
jQuery.unique( matched );
}
// Reverse order for parents* and prev-derivatives
if ( rparentsprev.test( name ) ) {
matched.reverse();
}
}
return this.pushStack( matched );
};
});
var rnotwhite = (/\S+/g);
// String to Object options format cache
var optionsCache = {};
// Convert String-formatted options into Object-formatted ones and store in cache
function createOptions( options ) {
var object = optionsCache[ options ] = {};
jQuery.each( options.match( rnotwhite ) || [], function( _, flag ) {
object[ flag ] = true;
});
return object;
}
/*
* Create a callback list using the following parameters:
*
* options: an optional list of space-separated options that will change how
* the callback list behaves or a more traditional option object
*
* By default a callback list will act like an event callback list and can be
* "fired" multiple times.
*
* Possible options:
*
* once: will ensure the callback list can only be fired once (like a Deferred)
*
* memory: will keep track of previous values and will call any callback added
* after the list has been fired right away with the latest "memorized"
* values (like a Deferred)
*
* unique: will ensure a callback can only be added once (no duplicate in the list)
*
* stopOnFalse: interrupt callings when a callback returns false
*
*/
jQuery.Callbacks = function( options ) {
// Convert options from String-formatted to Object-formatted if needed
// (we check in cache first)
options = typeof options === "string" ?
( optionsCache[ options ] || createOptions( options ) ) :
jQuery.extend( {}, options );
var // Last fire value (for non-forgettable lists)
memory,
// Flag to know if list was already fired
fired,
// Flag to know if list is currently firing
firing,
// First callback to fire (used internally by add and fireWith)
firingStart,
// End of the loop when firing
firingLength,
// Index of currently firing callback (modified by remove if needed)
firingIndex,
// Actual callback list
list = [],
// Stack of fire calls for repeatable lists
stack = !options.once && [],
// Fire callbacks
fire = function( data ) {
memory = options.memory && data;
fired = true;
firingIndex = firingStart || 0;
firingStart = 0;
firingLength = list.length;
firing = true;
for ( ; list && firingIndex < firingLength; firingIndex++ ) {
if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) {
memory = false; // To prevent further calls using add
break;
}
}
firing = false;
if ( list ) {
if ( stack ) {
if ( stack.length ) {
fire( stack.shift() );
}
} else if ( memory ) {
list = [];
} else {
self.disable();
}
}
},
// Actual Callbacks object
self = {
// Add a callback or a collection of callbacks to the list
add: function() {
if ( list ) {
// First, we save the current length
var start = list.length;
(function add( args ) {
jQuery.each( args, function( _, arg ) {
var type = jQuery.type( arg );
if ( type === "function" ) {
if ( !options.unique || !self.has( arg ) ) {
list.push( arg );
}
} else if ( arg && arg.length && type !== "string" ) {
// Inspect recursively
add( arg );
}
});
})( arguments );
// Do we need to add the callbacks to the
// current firing batch?
if ( firing ) {
firingLength = list.length;
// With memory, if we're not firing then
// we should call right away
} else if ( memory ) {
firingStart = start;
fire( memory );
}
}
return this;
},
// Remove a callback from the list
remove: function() {
if ( list ) {
jQuery.each( arguments, function( _, arg ) {
var index;
while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
list.splice( index, 1 );
// Handle firing indexes
if ( firing ) {
if ( index <= firingLength ) {
firingLength--;
}
if ( index <= firingIndex ) {
firingIndex--;
}
}
}
});
}
return this;
},
// Check if a given callback is in the list.
// If no argument is given, return whether or not list has callbacks attached.
has: function( fn ) {
return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length );
},
// Remove all callbacks from the list
empty: function() {
list = [];
firingLength = 0;
return this;
},
// Have the list do nothing anymore
disable: function() {
list = stack = memory = undefined;
return this;
},
// Is it disabled?
disabled: function() {
return !list;
},
// Lock the list in its current state
lock: function() {
stack = undefined;
if ( !memory ) {
self.disable();
}
return this;
},
// Is it locked?
locked: function() {
return !stack;
},
// Call all callbacks with the given context and arguments
fireWith: function( context, args ) {
if ( list && ( !fired || stack ) ) {
args = args || [];
args = [ context, args.slice ? args.slice() : args ];
if ( firing ) {
stack.push( args );
} else {
fire( args );
}
}
return this;
},
// Call all the callbacks with the given arguments
fire: function() {
self.fireWith( this, arguments );
return this;
},
// To know if the callbacks have already been called at least once
fired: function() {
return !!fired;
}
};
return self;
};
jQuery.extend({
Deferred: function( func ) {
var tuples = [
// action, add listener, listener list, final state
[ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ],
[ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ],
[ "notify", "progress", jQuery.Callbacks("memory") ]
],
state = "pending",
promise = {
state: function() {
return state;
},
always: function() {
deferred.done( arguments ).fail( arguments );
return this;
},
then: function( /* fnDone, fnFail, fnProgress */ ) {
var fns = arguments;
return jQuery.Deferred(function( newDefer ) {
jQuery.each( tuples, function( i, tuple ) {
var fn = jQuery.isFunction( fns[ i ] ) && fns[ i ];
// deferred[ done | fail | progress ] for forwarding actions to newDefer
deferred[ tuple[1] ](function() {
var returned = fn && fn.apply( this, arguments );
if ( returned && jQuery.isFunction( returned.promise ) ) {
returned.promise()
.done( newDefer.resolve )
.fail( newDefer.reject )
.progress( newDefer.notify );
} else {
newDefer[ tuple[ 0 ] + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments );
}
});
});
fns = null;
}).promise();
},
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function( obj ) {
return obj != null ? jQuery.extend( obj, promise ) : promise;
}
},
deferred = {};
// Keep pipe for back-compat
promise.pipe = promise.then;
// Add list-specific methods
jQuery.each( tuples, function( i, tuple ) {
var list = tuple[ 2 ],
stateString = tuple[ 3 ];
// promise[ done | fail | progress ] = list.add
promise[ tuple[1] ] = list.add;
// Handle state
if ( stateString ) {
list.add(function() {
// state = [ resolved | rejected ]
state = stateString;
// [ reject_list | resolve_list ].disable; progress_list.lock
}, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock );
}
// deferred[ resolve | reject | notify ]
deferred[ tuple[0] ] = function() {
deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments );
return this;
};
deferred[ tuple[0] + "With" ] = list.fireWith;
});
// Make the deferred a promise
promise.promise( deferred );
// Call given func if any
if ( func ) {
func.call( deferred, deferred );
}
// All done!
return deferred;
},
// Deferred helper
when: function( subordinate /* , ..., subordinateN */ ) {
var i = 0,
resolveValues = slice.call( arguments ),
length = resolveValues.length,
// the count of uncompleted subordinates
remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0,
// the master Deferred. If resolveValues consist of only a single Deferred, just use that.
deferred = remaining === 1 ? subordinate : jQuery.Deferred(),
// Update function for both resolve and progress values
updateFunc = function( i, contexts, values ) {
return function( value ) {
contexts[ i ] = this;
values[ i ] = arguments.length > 1 ? slice.call( arguments ) : value;
if ( values === progressValues ) {
deferred.notifyWith( contexts, values );
} else if ( !( --remaining ) ) {
deferred.resolveWith( contexts, values );
}
};
},
progressValues, progressContexts, resolveContexts;
// add listeners to Deferred subordinates; treat others as resolved
if ( length > 1 ) {
progressValues = new Array( length );
progressContexts = new Array( length );
resolveContexts = new Array( length );
for ( ; i < length; i++ ) {
if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) {
resolveValues[ i ].promise()
.done( updateFunc( i, resolveContexts, resolveValues ) )
.fail( deferred.reject )
.progress( updateFunc( i, progressContexts, progressValues ) );
} else {
--remaining;
}
}
}
// if we're not waiting on anything, resolve the master
if ( !remaining ) {
deferred.resolveWith( resolveContexts, resolveValues );
}
return deferred.promise();
}
});
// The deferred used on DOM ready
var readyList;
jQuery.fn.ready = function( fn ) {
// Add the callback
jQuery.ready.promise().done( fn );
return this;
};
jQuery.extend({
// Is the DOM ready to be used? Set to true once it occurs.
isReady: false,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait: 1,
// Hold (or release) the ready event
holdReady: function( hold ) {
if ( hold ) {
jQuery.readyWait++;
} else {
jQuery.ready( true );
}
},
// Handle when the DOM is ready
ready: function( wait ) {
// Abort if there are pending holds or we're already ready
if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
return;
}
// Remember that the DOM is ready
jQuery.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if ( wait !== true && --jQuery.readyWait > 0 ) {
return;
}
// If there are functions bound, to execute
readyList.resolveWith( document, [ jQuery ] );
// Trigger any bound ready events
if ( jQuery.fn.trigger ) {
jQuery( document ).trigger("ready").off("ready");
}
}
});
/**
* The ready event handler and self cleanup method
*/
function completed() {
document.removeEventListener( "DOMContentLoaded", completed, false );
window.removeEventListener( "load", completed, false );
jQuery.ready();
}
jQuery.ready.promise = function( obj ) {
if ( !readyList ) {
readyList = jQuery.Deferred();
// Catch cases where $(document).ready() is called after the browser event has already occurred.
// we once tried to use readyState "interactive" here, but it caused issues like the one
// discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
setTimeout( jQuery.ready );
} else {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", completed, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", completed, false );
}
}
return readyList.promise( obj );
};
// Kick off the DOM ready check even if the user does not
jQuery.ready.promise();
// Multifunctional method to get and set values of a collection
// The value/s can optionally be executed if it's a function
var access = jQuery.access = function( elems, fn, key, value, chainable, emptyGet, raw ) {
var i = 0,
len = elems.length,
bulk = key == null;
// Sets many values
if ( jQuery.type( key ) === "object" ) {
chainable = true;
for ( i in key ) {
jQuery.access( elems, fn, i, key[i], true, emptyGet, raw );
}
// Sets one value
} else if ( value !== undefined ) {
chainable = true;
if ( !jQuery.isFunction( value ) ) {
raw = true;
}
if ( bulk ) {
// Bulk operations run against the entire set
if ( raw ) {
fn.call( elems, value );
fn = null;
// ...except when executing function values
} else {
bulk = fn;
fn = function( elem, key, value ) {
return bulk.call( jQuery( elem ), value );
};
}
}
if ( fn ) {
for ( ; i < len; i++ ) {
fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) );
}
}
}
return chainable ?
elems :
// Gets
bulk ?
fn.call( elems ) :
len ? fn( elems[0], key ) : emptyGet;
};
/**
* Determines whether an object can have data
*/
jQuery.acceptData = function( owner ) {
// Accepts only:
// - Node
// - Node.ELEMENT_NODE
// - Node.DOCUMENT_NODE
// - Object
// - Any
/* jshint -W018 */
return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType );
};
function Data() {
// Support: Android < 4,
// Old WebKit does not have Object.preventExtensions/freeze method,
// return new empty object instead with no [[set]] accessor
Object.defineProperty( this.cache = {}, 0, {
get: function() {
return {};
}
});
this.expando = jQuery.expando + Math.random();
}
Data.uid = 1;
Data.accepts = jQuery.acceptData;
Data.prototype = {
key: function( owner ) {
// We can accept data for non-element nodes in modern browsers,
// but we should not, see #8335.
// Always return the key for a frozen object.
if ( !Data.accepts( owner ) ) {
return 0;
}
var descriptor = {},
// Check if the owner object already has a cache key
unlock = owner[ this.expando ];
// If not, create one
if ( !unlock ) {
unlock = Data.uid++;
// Secure it in a non-enumerable, non-writable property
try {
descriptor[ this.expando ] = { value: unlock };
Object.defineProperties( owner, descriptor );
// Support: Android < 4
// Fallback to a less secure definition
} catch ( e ) {
descriptor[ this.expando ] = unlock;
jQuery.extend( owner, descriptor );
}
}
// Ensure the cache object
if ( !this.cache[ unlock ] ) {
this.cache[ unlock ] = {};
}
return unlock;
},
set: function( owner, data, value ) {
var prop,
// There may be an unlock assigned to this node,
// if there is no entry for this "owner", create one inline
// and set the unlock as though an owner entry had always existed
unlock = this.key( owner ),
cache = this.cache[ unlock ];
// Handle: [ owner, key, value ] args
if ( typeof data === "string" ) {
cache[ data ] = value;
// Handle: [ owner, { properties } ] args
} else {
// Fresh assignments by object are shallow copied
if ( jQuery.isEmptyObject( cache ) ) {
jQuery.extend( this.cache[ unlock ], data );
// Otherwise, copy the properties one-by-one to the cache object
} else {
for ( prop in data ) {
cache[ prop ] = data[ prop ];
}
}
}
return cache;
},
get: function( owner, key ) {
// Either a valid cache is found, or will be created.
// New caches will be created and the unlock returned,
// allowing direct access to the newly created
// empty data object. A valid owner object must be provided.
var cache = this.cache[ this.key( owner ) ];
return key === undefined ?
cache : cache[ key ];
},
access: function( owner, key, value ) {
var stored;
// In cases where either:
//
// 1. No key was specified
// 2. A string key was specified, but no value provided
//
// Take the "read" path and allow the get method to determine
// which value to return, respectively either:
//
// 1. The entire cache object
// 2. The data stored at the key
//
if ( key === undefined ||
((key && typeof key === "string") && value === undefined) ) {
stored = this.get( owner, key );
return stored !== undefined ?
stored : this.get( owner, jQuery.camelCase(key) );
}
// [*]When the key is not a string, or both a key and value
// are specified, set or extend (existing objects) with either:
//
// 1. An object of properties
// 2. A key and value
//
this.set( owner, key, value );
// Since the "set" path can have two possible entry points
// return the expected data based on which path was taken[*]
return value !== undefined ? value : key;
},
remove: function( owner, key ) {
var i, name, camel,
unlock = this.key( owner ),
cache = this.cache[ unlock ];
if ( key === undefined ) {
this.cache[ unlock ] = {};
} else {
// Support array or space separated string of keys
if ( jQuery.isArray( key ) ) {
// If "name" is an array of keys...
// When data is initially created, via ("key", "val") signature,
// keys will be converted to camelCase.
// Since there is no way to tell _how_ a key was added, remove
// both plain key and camelCase key. #12786
// This will only penalize the array argument path.
name = key.concat( key.map( jQuery.camelCase ) );
} else {
camel = jQuery.camelCase( key );
// Try the string as a key before any manipulation
if ( key in cache ) {
name = [ key, camel ];
} else {
// If a key with the spaces exists, use it.
// Otherwise, create an array by matching non-whitespace
name = camel;
name = name in cache ?
[ name ] : ( name.match( rnotwhite ) || [] );
}
}
i = name.length;
while ( i-- ) {
delete cache[ name[ i ] ];
}
}
},
hasData: function( owner ) {
return !jQuery.isEmptyObject(
this.cache[ owner[ this.expando ] ] || {}
);
},
discard: function( owner ) {
if ( owner[ this.expando ] ) {
delete this.cache[ owner[ this.expando ] ];
}
}
};
var data_priv = new Data();
var data_user = new Data();
/*
Implementation Summary
1. Enforce API surface and semantic compatibility with 1.9.x branch
2. Improve the module's maintainability by reducing the storage
paths to a single mechanism.
3. Use the same single mechanism to support "private" and "user" data.
4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData)
5. Avoid exposing implementation details on user objects (eg. expando properties)
6. Provide a clear path for implementation upgrade to WeakMap in 2014
*/
var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,
rmultiDash = /([A-Z])/g;
function dataAttr( elem, key, data ) {
var name;
// If nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute
if ( data === undefined && elem.nodeType === 1 ) {
name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();
data = elem.getAttribute( name );
if ( typeof data === "string" ) {
try {
data = data === "true" ? true :
data === "false" ? false :
data === "null" ? null :
// Only convert to a number if it doesn't change the string
+data + "" === data ? +data :
rbrace.test( data ) ? jQuery.parseJSON( data ) :
data;
} catch( e ) {}
// Make sure we set the data so it isn't changed later
data_user.set( elem, key, data );
} else {
data = undefined;
}
}
return data;
}
jQuery.extend({
hasData: function( elem ) {
return data_user.hasData( elem ) || data_priv.hasData( elem );
},
data: function( elem, name, data ) {
return data_user.access( elem, name, data );
},
removeData: function( elem, name ) {
data_user.remove( elem, name );
},
// TODO: Now that all calls to _data and _removeData have been replaced
// with direct calls to data_priv methods, these can be deprecated.
_data: function( elem, name, data ) {
return data_priv.access( elem, name, data );
},
_removeData: function( elem, name ) {
data_priv.remove( elem, name );
}
});
jQuery.fn.extend({
data: function( key, value ) {
var i, name, data,
elem = this[ 0 ],
attrs = elem && elem.attributes;
// Gets all values
if ( key === undefined ) {
if ( this.length ) {
data = data_user.get( elem );
if ( elem.nodeType === 1 && !data_priv.get( elem, "hasDataAttrs" ) ) {
i = attrs.length;
while ( i-- ) {
name = attrs[ i ].name;
if ( name.indexOf( "data-" ) === 0 ) {
name = jQuery.camelCase( name.slice(5) );
dataAttr( elem, name, data[ name ] );
}
}
data_priv.set( elem, "hasDataAttrs", true );
}
}
return data;
}
// Sets multiple values
if ( typeof key === "object" ) {
return this.each(function() {
data_user.set( this, key );
});
}
return access( this, function( value ) {
var data,
camelKey = jQuery.camelCase( key );
// The calling jQuery object (element matches) is not empty
// (and therefore has an element appears at this[ 0 ]) and the
// `value` parameter was not undefined. An empty jQuery object
// will result in `undefined` for elem = this[ 0 ] which will
// throw an exception if an attempt to read a data cache is made.
if ( elem && value === undefined ) {
// Attempt to get data from the cache
// with the key as-is
data = data_user.get( elem, key );
if ( data !== undefined ) {
return data;
}
// Attempt to get data from the cache
// with the key camelized
data = data_user.get( elem, camelKey );
if ( data !== undefined ) {
return data;
}
// Attempt to "discover" the data in
// HTML5 custom data-* attrs
data = dataAttr( elem, camelKey, undefined );
if ( data !== undefined ) {
return data;
}
// We tried really hard, but the data doesn't exist.
return;
}
// Set the data...
this.each(function() {
// First, attempt to store a copy or reference of any
// data that might've been store with a camelCased key.
var data = data_user.get( this, camelKey );
// For HTML5 data-* attribute interop, we have to
// store property names with dashes in a camelCase form.
// This might not apply to all properties...*
data_user.set( this, camelKey, value );
// *... In the case of properties that might _actually_
// have dashes, we need to also store a copy of that
// unchanged property.
if ( key.indexOf("-") !== -1 && data !== undefined ) {
data_user.set( this, key, value );
}
});
}, null, value, arguments.length > 1, null, true );
},
removeData: function( key ) {
return this.each(function() {
data_user.remove( this, key );
});
}
});
jQuery.extend({
queue: function( elem, type, data ) {
var queue;
if ( elem ) {
type = ( type || "fx" ) + "queue";
queue = data_priv.get( elem, type );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( data ) {
if ( !queue || jQuery.isArray( data ) ) {
queue = data_priv.access( elem, type, jQuery.makeArray(data) );
} else {
queue.push( data );
}
}
return queue || [];
}
},
dequeue: function( elem, type ) {
type = type || "fx";
var queue = jQuery.queue( elem, type ),
startLength = queue.length,
fn = queue.shift(),
hooks = jQuery._queueHooks( elem, type ),
next = function() {
jQuery.dequeue( elem, type );
};
// If the fx queue is dequeued, always remove the progress sentinel
if ( fn === "inprogress" ) {
fn = queue.shift();
startLength--;
}
if ( fn ) {
// Add a progress sentinel to prevent the fx queue from being
// automatically dequeued
if ( type === "fx" ) {
queue.unshift( "inprogress" );
}
// clear up the last queue stop function
delete hooks.stop;
fn.call( elem, next, hooks );
}
if ( !startLength && hooks ) {
hooks.empty.fire();
}
},
// not intended for public consumption - generates a queueHooks object, or returns the current one
_queueHooks: function( elem, type ) {
var key = type + "queueHooks";
return data_priv.get( elem, key ) || data_priv.access( elem, key, {
empty: jQuery.Callbacks("once memory").add(function() {
data_priv.remove( elem, [ type + "queue", key ] );
})
});
}
});
jQuery.fn.extend({
queue: function( type, data ) {
var setter = 2;
if ( typeof type !== "string" ) {
data = type;
type = "fx";
setter--;
}
if ( arguments.length < setter ) {
return jQuery.queue( this[0], type );
}
return data === undefined ?
this :
this.each(function() {
var queue = jQuery.queue( this, type, data );
// ensure a hooks for this queue
jQuery._queueHooks( this, type );
if ( type === "fx" && queue[0] !== "inprogress" ) {
jQuery.dequeue( this, type );
}
});
},
dequeue: function( type ) {
return this.each(function() {
jQuery.dequeue( this, type );
});
},
clearQueue: function( type ) {
return this.queue( type || "fx", [] );
},
// Get a promise resolved when queues of a certain type
// are emptied (fx is the type by default)
promise: function( type, obj ) {
var tmp,
count = 1,
defer = jQuery.Deferred(),
elements = this,
i = this.length,
resolve = function() {
if ( !( --count ) ) {
defer.resolveWith( elements, [ elements ] );
}
};
if ( typeof type !== "string" ) {
obj = type;
type = undefined;
}
type = type || "fx";
while ( i-- ) {
tmp = data_priv.get( elements[ i ], type + "queueHooks" );
if ( tmp && tmp.empty ) {
count++;
tmp.empty.add( resolve );
}
}
resolve();
return defer.promise( obj );
}
});
var pnum = (/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/).source;
var rcheckableType = (/^(?:checkbox|radio)$/i);
(function() {
var fragment = document.createDocumentFragment(),
div = fragment.appendChild( document.createElement( "div" ) );
// #11217 - WebKit loses check when the name is after the checked attribute
div.innerHTML = "<input type='radio' checked='checked' name='t'/>";
// Support: Safari 5.1, iOS 5.1, Android 4.x, Android 2.3
// old WebKit doesn't clone checked state correctly in fragments
support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked;
// Make sure textarea (and checkbox) defaultValue is properly cloned
// Support: IE9-IE11+
div.innerHTML = "<textarea>x</textarea>";
support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue;
})();
var strundefined = typeof undefined;
support.focusinBubbles = "onfocusin" in window;
var
rkeyEvent = /^key/,
rmouseEvent = /^(?:mouse|contextmenu)|click/,
rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
rtypenamespace = /^([^.]*)(?:\.(.+)|)$/;
function returnTrue() {
return true;
}
function returnFalse() {
return false;
}
function safeActiveElement() {
try {
return document.activeElement;
} catch ( err ) { }
}
/*
* Helper functions for managing events -- not part of the public interface.
* Props to Dean Edwards' addEvent library for many of the ideas.
*/
jQuery.event = {
global: {},
add: function( elem, types, handler, data, selector ) {
var handleObjIn, eventHandle, tmp,
events, t, handleObj,
special, handlers, type, namespaces, origType,
elemData = data_priv.get( elem );
// Don't attach events to noData or text/comment nodes (but allow plain objects)
if ( !elemData ) {
return;
}
// Caller can pass in an object of custom data in lieu of the handler
if ( handler.handler ) {
handleObjIn = handler;
handler = handleObjIn.handler;
selector = handleObjIn.selector;
}
// Make sure that the handler has a unique ID, used to find/remove it later
if ( !handler.guid ) {
handler.guid = jQuery.guid++;
}
// Init the element's event structure and main handler, if this is the first
if ( !(events = elemData.events) ) {
events = elemData.events = {};
}
if ( !(eventHandle = elemData.handle) ) {
eventHandle = elemData.handle = function( e ) {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery !== strundefined && jQuery.event.triggered !== e.type ?
jQuery.event.dispatch.apply( elem, arguments ) : undefined;
};
}
// Handle multiple events separated by a space
types = ( types || "" ).match( rnotwhite ) || [ "" ];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[t] ) || [];
type = origType = tmp[1];
namespaces = ( tmp[2] || "" ).split( "." ).sort();
// There *must* be a type, no attaching namespace-only handlers
if ( !type ) {
continue;
}
// If event changes its type, use the special event handlers for the changed type
special = jQuery.event.special[ type ] || {};
// If selector defined, determine special event api type, otherwise given type
type = ( selector ? special.delegateType : special.bindType ) || type;
// Update special based on newly reset type
special = jQuery.event.special[ type ] || {};
// handleObj is passed to all event handlers
handleObj = jQuery.extend({
type: type,
origType: origType,
data: data,
handler: handler,
guid: handler.guid,
selector: selector,
needsContext: selector && jQuery.expr.match.needsContext.test( selector ),
namespace: namespaces.join(".")
}, handleObjIn );
// Init the event handler queue if we're the first
if ( !(handlers = events[ type ]) ) {
handlers = events[ type ] = [];
handlers.delegateCount = 0;
// Only use addEventListener if the special events handler returns false
if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
if ( elem.addEventListener ) {
elem.addEventListener( type, eventHandle, false );
}
}
}
if ( special.add ) {
special.add.call( elem, handleObj );
if ( !handleObj.handler.guid ) {
handleObj.handler.guid = handler.guid;
}
}
// Add to the element's handler list, delegates in front
if ( selector ) {
handlers.splice( handlers.delegateCount++, 0, handleObj );
} else {
handlers.push( handleObj );
}
// Keep track of which events have ever been used, for event optimization
jQuery.event.global[ type ] = true;
}
},
// Detach an event or set of events from an element
remove: function( elem, types, handler, selector, mappedTypes ) {
var j, origCount, tmp,
events, t, handleObj,
special, handlers, type, namespaces, origType,
elemData = data_priv.hasData( elem ) && data_priv.get( elem );
if ( !elemData || !(events = elemData.events) ) {
return;
}
// Once for each type.namespace in types; type may be omitted
types = ( types || "" ).match( rnotwhite ) || [ "" ];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[t] ) || [];
type = origType = tmp[1];
namespaces = ( tmp[2] || "" ).split( "." ).sort();
// Unbind all events (on this namespace, if provided) for the element
if ( !type ) {
for ( type in events ) {
jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
}
continue;
}
special = jQuery.event.special[ type ] || {};
type = ( selector ? special.delegateType : special.bindType ) || type;
handlers = events[ type ] || [];
tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" );
// Remove matching events
origCount = j = handlers.length;
while ( j-- ) {
handleObj = handlers[ j ];
if ( ( mappedTypes || origType === handleObj.origType ) &&
( !handler || handler.guid === handleObj.guid ) &&
( !tmp || tmp.test( handleObj.namespace ) ) &&
( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) {
handlers.splice( j, 1 );
if ( handleObj.selector ) {
handlers.delegateCount--;
}
if ( special.remove ) {
special.remove.call( elem, handleObj );
}
}
}
// Remove generic event handler if we removed something and no more handlers exist
// (avoids potential for endless recursion during removal of special event handlers)
if ( origCount && !handlers.length ) {
if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) {
jQuery.removeEvent( elem, type, elemData.handle );
}
delete events[ type ];
}
}
// Remove the expando if it's no longer used
if ( jQuery.isEmptyObject( events ) ) {
delete elemData.handle;
data_priv.remove( elem, "events" );
}
},
trigger: function( event, data, elem, onlyHandlers ) {
var i, cur, tmp, bubbleType, ontype, handle, special,
eventPath = [ elem || document ],
type = hasOwn.call( event, "type" ) ? event.type : event,
namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : [];
cur = tmp = elem = elem || document;
// Don't do events on text and comment nodes
if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
return;
}
// focus/blur morphs to focusin/out; ensure we're not firing them right now
if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
return;
}
if ( type.indexOf(".") >= 0 ) {
// Namespaced trigger; create a regexp to match event type in handle()
namespaces = type.split(".");
type = namespaces.shift();
namespaces.sort();
}
ontype = type.indexOf(":") < 0 && "on" + type;
// Caller can pass in a jQuery.Event object, Object, or just an event type string
event = event[ jQuery.expando ] ?
event :
new jQuery.Event( type, typeof event === "object" && event );
// Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true)
event.isTrigger = onlyHandlers ? 2 : 3;
event.namespace = namespaces.join(".");
event.namespace_re = event.namespace ?
new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) :
null;
// Clean up the event in case it is being reused
event.result = undefined;
if ( !event.target ) {
event.target = elem;
}
// Clone any incoming data and prepend the event, creating the handler arg list
data = data == null ?
[ event ] :
jQuery.makeArray( data, [ event ] );
// Allow special events to draw outside the lines
special = jQuery.event.special[ type ] || {};
if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) {
return;
}
// Determine event propagation path in advance, per W3C events spec (#9951)
// Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) {
bubbleType = special.delegateType || type;
if ( !rfocusMorph.test( bubbleType + type ) ) {
cur = cur.parentNode;
}
for ( ; cur; cur = cur.parentNode ) {
eventPath.push( cur );
tmp = cur;
}
// Only add window if we got to document (e.g., not plain obj or detached DOM)
if ( tmp === (elem.ownerDocument || document) ) {
eventPath.push( tmp.defaultView || tmp.parentWindow || window );
}
}
// Fire handlers on the event path
i = 0;
while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) {
event.type = i > 1 ?
bubbleType :
special.bindType || type;
// jQuery handler
handle = ( data_priv.get( cur, "events" ) || {} )[ event.type ] && data_priv.get( cur, "handle" );
if ( handle ) {
handle.apply( cur, data );
}
// Native handler
handle = ontype && cur[ ontype ];
if ( handle && handle.apply && jQuery.acceptData( cur ) ) {
event.result = handle.apply( cur, data );
if ( event.result === false ) {
event.preventDefault();
}
}
}
event.type = type;
// If nobody prevented the default action, do it now
if ( !onlyHandlers && !event.isDefaultPrevented() ) {
if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) &&
jQuery.acceptData( elem ) ) {
// Call a native DOM method on the target with the same name name as the event.
// Don't do default actions on window, that's where global variables be (#6170)
if ( ontype && jQuery.isFunction( elem[ type ] ) && !jQuery.isWindow( elem ) ) {
// Don't re-trigger an onFOO event when we call its FOO() method
tmp = elem[ ontype ];
if ( tmp ) {
elem[ ontype ] = null;
}
// Prevent re-triggering of the same event, since we already bubbled it above
jQuery.event.triggered = type;
elem[ type ]();
jQuery.event.triggered = undefined;
if ( tmp ) {
elem[ ontype ] = tmp;
}
}
}
}
return event.result;
},
dispatch: function( event ) {
// Make a writable jQuery.Event from the native event object
event = jQuery.event.fix( event );
var i, j, ret, matched, handleObj,
handlerQueue = [],
args = slice.call( arguments ),
handlers = ( data_priv.get( this, "events" ) || {} )[ event.type ] || [],
special = jQuery.event.special[ event.type ] || {};
// Use the fix-ed jQuery.Event rather than the (read-only) native event
args[0] = event;
event.delegateTarget = this;
// Call the preDispatch hook for the mapped type, and let it bail if desired
if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) {
return;
}
// Determine handlers
handlerQueue = jQuery.event.handlers.call( this, event, handlers );
// Run delegates first; they may want to stop propagation beneath us
i = 0;
while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) {
event.currentTarget = matched.elem;
j = 0;
while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) {
// Triggered event must either 1) have no namespace, or
// 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace).
if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) {
event.handleObj = handleObj;
event.data = handleObj.data;
ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler )
.apply( matched.elem, args );
if ( ret !== undefined ) {
if ( (event.result = ret) === false ) {
event.preventDefault();
event.stopPropagation();
}
}
}
}
}
// Call the postDispatch hook for the mapped type
if ( special.postDispatch ) {
special.postDispatch.call( this, event );
}
return event.result;
},
handlers: function( event, handlers ) {
var i, matches, sel, handleObj,
handlerQueue = [],
delegateCount = handlers.delegateCount,
cur = event.target;
// Find delegate handlers
// Black-hole SVG <use> instance trees (#13180)
// Avoid non-left-click bubbling in Firefox (#3861)
if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) {
for ( ; cur !== this; cur = cur.parentNode || this ) {
// Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)
if ( cur.disabled !== true || event.type !== "click" ) {
matches = [];
for ( i = 0; i < delegateCount; i++ ) {
handleObj = handlers[ i ];
// Don't conflict with Object.prototype properties (#13203)
sel = handleObj.selector + " ";
if ( matches[ sel ] === undefined ) {
matches[ sel ] = handleObj.needsContext ?
jQuery( sel, this ).index( cur ) >= 0 :
jQuery.find( sel, this, null, [ cur ] ).length;
}
if ( matches[ sel ] ) {
matches.push( handleObj );
}
}
if ( matches.length ) {
handlerQueue.push({ elem: cur, handlers: matches });
}
}
}
}
// Add the remaining (directly-bound) handlers
if ( delegateCount < handlers.length ) {
handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) });
}
return handlerQueue;
},
// Includes some event props shared by KeyEvent and MouseEvent
props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),
fixHooks: {},
keyHooks: {
props: "char charCode key keyCode".split(" "),
filter: function( event, original ) {
// Add which for key events
if ( event.which == null ) {
event.which = original.charCode != null ? original.charCode : original.keyCode;
}
return event;
}
},
mouseHooks: {
props: "button buttons clientX clientY offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
filter: function( event, original ) {
var eventDoc, doc, body,
button = original.button;
// Calculate pageX/Y if missing and clientX/Y available
if ( event.pageX == null && original.clientX != null ) {
eventDoc = event.target.ownerDocument || document;
doc = eventDoc.documentElement;
body = eventDoc.body;
event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 );
event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 );
}
// Add which for click: 1 === left; 2 === middle; 3 === right
// Note: button is not normalized, so don't use it
if ( !event.which && button !== undefined ) {
event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );
}
return event;
}
},
fix: function( event ) {
if ( event[ jQuery.expando ] ) {
return event;
}
// Create a writable copy of the event object and normalize some properties
var i, prop, copy,
type = event.type,
originalEvent = event,
fixHook = this.fixHooks[ type ];
if ( !fixHook ) {
this.fixHooks[ type ] = fixHook =
rmouseEvent.test( type ) ? this.mouseHooks :
rkeyEvent.test( type ) ? this.keyHooks :
{};
}
copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props;
event = new jQuery.Event( originalEvent );
i = copy.length;
while ( i-- ) {
prop = copy[ i ];
event[ prop ] = originalEvent[ prop ];
}
// Support: Cordova 2.5 (WebKit) (#13255)
// All events should have a target; Cordova deviceready doesn't
if ( !event.target ) {
event.target = document;
}
// Support: Safari 6.0+, Chrome < 28
// Target should not be a text node (#504, #13143)
if ( event.target.nodeType === 3 ) {
event.target = event.target.parentNode;
}
return fixHook.filter ? fixHook.filter( event, originalEvent ) : event;
},
special: {
load: {
// Prevent triggered image.load events from bubbling to window.load
noBubble: true
},
focus: {
// Fire native event if possible so blur/focus sequence is correct
trigger: function() {
if ( this !== safeActiveElement() && this.focus ) {
this.focus();
return false;
}
},
delegateType: "focusin"
},
blur: {
trigger: function() {
if ( this === safeActiveElement() && this.blur ) {
this.blur();
return false;
}
},
delegateType: "focusout"
},
click: {
// For checkbox, fire native event so checked state will be right
trigger: function() {
if ( this.type === "checkbox" && this.click && jQuery.nodeName( this, "input" ) ) {
this.click();
return false;
}
},
// For cross-browser consistency, don't fire native .click() on links
_default: function( event ) {
return jQuery.nodeName( event.target, "a" );
}
},
beforeunload: {
postDispatch: function( event ) {
// Support: Firefox 20+
// Firefox doesn't alert if the returnValue field is not set.
if ( event.result !== undefined ) {
event.originalEvent.returnValue = event.result;
}
}
}
},
simulate: function( type, elem, event, bubble ) {
// Piggyback on a donor event to simulate a different one.
// Fake originalEvent to avoid donor's stopPropagation, but if the
// simulated event prevents default then we do the same on the donor.
var e = jQuery.extend(
new jQuery.Event(),
event,
{
type: type,
isSimulated: true,
originalEvent: {}
}
);
if ( bubble ) {
jQuery.event.trigger( e, null, elem );
} else {
jQuery.event.dispatch.call( elem, e );
}
if ( e.isDefaultPrevented() ) {
event.preventDefault();
}
}
};
jQuery.removeEvent = function( elem, type, handle ) {
if ( elem.removeEventListener ) {
elem.removeEventListener( type, handle, false );
}
};
jQuery.Event = function( src, props ) {
// Allow instantiation without the 'new' keyword
if ( !(this instanceof jQuery.Event) ) {
return new jQuery.Event( src, props );
}
// Event object
if ( src && src.type ) {
this.originalEvent = src;
this.type = src.type;
// Events bubbling up the document may have been marked as prevented
// by a handler lower down the tree; reflect the correct value.
this.isDefaultPrevented = src.defaultPrevented ||
// Support: Android < 4.0
src.defaultPrevented === undefined &&
src.getPreventDefault && src.getPreventDefault() ?
returnTrue :
returnFalse;
// Event type
} else {
this.type = src;
}
// Put explicitly provided properties onto the event object
if ( props ) {
jQuery.extend( this, props );
}
// Create a timestamp if incoming event doesn't have one
this.timeStamp = src && src.timeStamp || jQuery.now();
// Mark it as fixed
this[ jQuery.expando ] = true;
};
// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse,
preventDefault: function() {
var e = this.originalEvent;
this.isDefaultPrevented = returnTrue;
if ( e && e.preventDefault ) {
e.preventDefault();
}
},
stopPropagation: function() {
var e = this.originalEvent;
this.isPropagationStopped = returnTrue;
if ( e && e.stopPropagation ) {
e.stopPropagation();
}
},
stopImmediatePropagation: function() {
this.isImmediatePropagationStopped = returnTrue;
this.stopPropagation();
}
};
// Create mouseenter/leave events using mouseover/out and event-time checks
// Support: Chrome 15+
jQuery.each({
mouseenter: "mouseover",
mouseleave: "mouseout"
}, function( orig, fix ) {
jQuery.event.special[ orig ] = {
delegateType: fix,
bindType: fix,
handle: function( event ) {
var ret,
target = this,
related = event.relatedTarget,
handleObj = event.handleObj;
// For mousenter/leave call the handler if related is outside the target.
// NB: No relatedTarget if the mouse left/entered the browser window
if ( !related || (related !== target && !jQuery.contains( target, related )) ) {
event.type = handleObj.origType;
ret = handleObj.handler.apply( this, arguments );
event.type = fix;
}
return ret;
}
};
});
// Create "bubbling" focus and blur events
// Support: Firefox, Chrome, Safari
if ( !support.focusinBubbles ) {
jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
// Attach a single capturing handler on the document while someone wants focusin/focusout
var handler = function( event ) {
jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true );
};
jQuery.event.special[ fix ] = {
setup: function() {
var doc = this.ownerDocument || this,
attaches = data_priv.access( doc, fix );
if ( !attaches ) {
doc.addEventListener( orig, handler, true );
}
data_priv.access( doc, fix, ( attaches || 0 ) + 1 );
},
teardown: function() {
var doc = this.ownerDocument || this,
attaches = data_priv.access( doc, fix ) - 1;
if ( !attaches ) {
doc.removeEventListener( orig, handler, true );
data_priv.remove( doc, fix );
} else {
data_priv.access( doc, fix, attaches );
}
}
};
});
}
jQuery.fn.extend({
on: function( types, selector, data, fn, /*INTERNAL*/ one ) {
var origFn, type;
// Types can be a map of types/handlers
if ( typeof types === "object" ) {
// ( types-Object, selector, data )
if ( typeof selector !== "string" ) {
// ( types-Object, data )
data = data || selector;
selector = undefined;
}
for ( type in types ) {
this.on( type, selector, data, types[ type ], one );
}
return this;
}
if ( data == null && fn == null ) {
// ( types, fn )
fn = selector;
data = selector = undefined;
} else if ( fn == null ) {
if ( typeof selector === "string" ) {
// ( types, selector, fn )
fn = data;
data = undefined;
} else {
// ( types, data, fn )
fn = data;
data = selector;
selector = undefined;
}
}
if ( fn === false ) {
fn = returnFalse;
} else if ( !fn ) {
return this;
}
if ( one === 1 ) {
origFn = fn;
fn = function( event ) {
// Can use an empty set, since event contains the info
jQuery().off( event );
return origFn.apply( this, arguments );
};
// Use same guid so caller can remove using origFn
fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
}
return this.each( function() {
jQuery.event.add( this, types, fn, data, selector );
});
},
one: function( types, selector, data, fn ) {
return this.on( types, selector, data, fn, 1 );
},
off: function( types, selector, fn ) {
var handleObj, type;
if ( types && types.preventDefault && types.handleObj ) {
// ( event ) dispatched jQuery.Event
handleObj = types.handleObj;
jQuery( types.delegateTarget ).off(
handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType,
handleObj.selector,
handleObj.handler
);
return this;
}
if ( typeof types === "object" ) {
// ( types-object [, selector] )
for ( type in types ) {
this.off( type, selector, types[ type ] );
}
return this;
}
if ( selector === false || typeof selector === "function" ) {
// ( types [, fn] )
fn = selector;
selector = undefined;
}
if ( fn === false ) {
fn = returnFalse;
}
return this.each(function() {
jQuery.event.remove( this, types, fn, selector );
});
},
trigger: function( type, data ) {
return this.each(function() {
jQuery.event.trigger( type, data, this );
});
},
triggerHandler: function( type, data ) {
var elem = this[0];
if ( elem ) {
return jQuery.event.trigger( type, data, elem, true );
}
}
});
var
rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,
rtagName = /<([\w:]+)/,
rhtml = /<|&#?\w+;/,
rnoInnerhtml = /<(?:script|style|link)/i,
// checked="checked" or checked
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
rscriptType = /^$|\/(?:java|ecma)script/i,
rscriptTypeMasked = /^true\/(.*)/,
rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,
// We have to close these tags to support XHTML (#13200)
wrapMap = {
// Support: IE 9
option: [ 1, "<select multiple='multiple'>", "</select>" ],
thead: [ 1, "<table>", "</table>" ],
col: [ 2, "<table><colgroup>", "</colgroup></table>" ],
tr: [ 2, "<table><tbody>", "</tbody></table>" ],
td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
_default: [ 0, "", "" ]
};
// Support: IE 9
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
// Support: 1.x compatibility
// Manipulating tables requires a tbody
function manipulationTarget( elem, content ) {
return jQuery.nodeName( elem, "table" ) &&
jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ?
elem.getElementsByTagName("tbody")[0] ||
elem.appendChild( elem.ownerDocument.createElement("tbody") ) :
elem;
}
// Replace/restore the type attribute of script elements for safe DOM manipulation
function disableScript( elem ) {
elem.type = (elem.getAttribute("type") !== null) + "/" + elem.type;
return elem;
}
function restoreScript( elem ) {
var match = rscriptTypeMasked.exec( elem.type );
if ( match ) {
elem.type = match[ 1 ];
} else {
elem.removeAttribute("type");
}
return elem;
}
// Mark scripts as having already been evaluated
function setGlobalEval( elems, refElements ) {
var i = 0,
l = elems.length;
for ( ; i < l; i++ ) {
data_priv.set(
elems[ i ], "globalEval", !refElements || data_priv.get( refElements[ i ], "globalEval" )
);
}
}
function cloneCopyEvent( src, dest ) {
var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events;
if ( dest.nodeType !== 1 ) {
return;
}
// 1. Copy private data: events, handlers, etc.
if ( data_priv.hasData( src ) ) {
pdataOld = data_priv.access( src );
pdataCur = data_priv.set( dest, pdataOld );
events = pdataOld.events;
if ( events ) {
delete pdataCur.handle;
pdataCur.events = {};
for ( type in events ) {
for ( i = 0, l = events[ type ].length; i < l; i++ ) {
jQuery.event.add( dest, type, events[ type ][ i ] );
}
}
}
}
// 2. Copy user data
if ( data_user.hasData( src ) ) {
udataOld = data_user.access( src );
udataCur = jQuery.extend( {}, udataOld );
data_user.set( dest, udataCur );
}
}
function getAll( context, tag ) {
var ret = context.getElementsByTagName ? context.getElementsByTagName( tag || "*" ) :
context.querySelectorAll ? context.querySelectorAll( tag || "*" ) :
[];
return tag === undefined || tag && jQuery.nodeName( context, tag ) ?
jQuery.merge( [ context ], ret ) :
ret;
}
// Support: IE >= 9
function fixInput( src, dest ) {
var nodeName = dest.nodeName.toLowerCase();
// Fails to persist the checked state of a cloned checkbox or radio button.
if ( nodeName === "input" && rcheckableType.test( src.type ) ) {
dest.checked = src.checked;
// Fails to return the selected option to the default selected state when cloning options
} else if ( nodeName === "input" || nodeName === "textarea" ) {
dest.defaultValue = src.defaultValue;
}
}
jQuery.extend({
clone: function( elem, dataAndEvents, deepDataAndEvents ) {
var i, l, srcElements, destElements,
clone = elem.cloneNode( true ),
inPage = jQuery.contains( elem.ownerDocument, elem );
// Support: IE >= 9
// Fix Cloning issues
if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) &&
!jQuery.isXMLDoc( elem ) ) {
// We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2
destElements = getAll( clone );
srcElements = getAll( elem );
for ( i = 0, l = srcElements.length; i < l; i++ ) {
fixInput( srcElements[ i ], destElements[ i ] );
}
}
// Copy the events from the original to the clone
if ( dataAndEvents ) {
if ( deepDataAndEvents ) {
srcElements = srcElements || getAll( elem );
destElements = destElements || getAll( clone );
for ( i = 0, l = srcElements.length; i < l; i++ ) {
cloneCopyEvent( srcElements[ i ], destElements[ i ] );
}
} else {
cloneCopyEvent( elem, clone );
}
}
// Preserve script evaluation history
destElements = getAll( clone, "script" );
if ( destElements.length > 0 ) {
setGlobalEval( destElements, !inPage && getAll( elem, "script" ) );
}
// Return the cloned set
return clone;
},
buildFragment: function( elems, context, scripts, selection ) {
var elem, tmp, tag, wrap, contains, j,
fragment = context.createDocumentFragment(),
nodes = [],
i = 0,
l = elems.length;
for ( ; i < l; i++ ) {
elem = elems[ i ];
if ( elem || elem === 0 ) {
// Add nodes directly
if ( jQuery.type( elem ) === "object" ) {
// Support: QtWebKit
// jQuery.merge because push.apply(_, arraylike) throws
jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem );
// Convert non-html into a text node
} else if ( !rhtml.test( elem ) ) {
nodes.push( context.createTextNode( elem ) );
// Convert html into DOM nodes
} else {
tmp = tmp || fragment.appendChild( context.createElement("div") );
// Deserialize a standard representation
tag = ( rtagName.exec( elem ) || [ "", "" ] )[ 1 ].toLowerCase();
wrap = wrapMap[ tag ] || wrapMap._default;
tmp.innerHTML = wrap[ 1 ] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[ 2 ];
// Descend through wrappers to the right content
j = wrap[ 0 ];
while ( j-- ) {
tmp = tmp.lastChild;
}
// Support: QtWebKit
// jQuery.merge because push.apply(_, arraylike) throws
jQuery.merge( nodes, tmp.childNodes );
// Remember the top-level container
tmp = fragment.firstChild;
// Fixes #12346
// Support: Webkit, IE
tmp.textContent = "";
}
}
}
// Remove wrapper from fragment
fragment.textContent = "";
i = 0;
while ( (elem = nodes[ i++ ]) ) {
// #4087 - If origin and destination elements are the same, and this is
// that element, do not do anything
if ( selection && jQuery.inArray( elem, selection ) !== -1 ) {
continue;
}
contains = jQuery.contains( elem.ownerDocument, elem );
// Append to fragment
tmp = getAll( fragment.appendChild( elem ), "script" );
// Preserve script evaluation history
if ( contains ) {
setGlobalEval( tmp );
}
// Capture executables
if ( scripts ) {
j = 0;
while ( (elem = tmp[ j++ ]) ) {
if ( rscriptType.test( elem.type || "" ) ) {
scripts.push( elem );
}
}
}
}
return fragment;
},
cleanData: function( elems ) {
var data, elem, events, type, key, j,
special = jQuery.event.special,
i = 0;
for ( ; (elem = elems[ i ]) !== undefined; i++ ) {
if ( jQuery.acceptData( elem ) ) {
key = elem[ data_priv.expando ];
if ( key && (data = data_priv.cache[ key ]) ) {
events = Object.keys( data.events || {} );
if ( events.length ) {
for ( j = 0; (type = events[j]) !== undefined; j++ ) {
if ( special[ type ] ) {
jQuery.event.remove( elem, type );
// This is a shortcut to avoid jQuery.event.remove's overhead
} else {
jQuery.removeEvent( elem, type, data.handle );
}
}
}
if ( data_priv.cache[ key ] ) {
// Discard any remaining `private` data
delete data_priv.cache[ key ];
}
}
}
// Discard any remaining `user` data
delete data_user.cache[ elem[ data_user.expando ] ];
}
}
});
jQuery.fn.extend({
text: function( value ) {
return access( this, function( value ) {
return value === undefined ?
jQuery.text( this ) :
this.empty().each(function() {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
this.textContent = value;
}
});
}, null, value, arguments.length );
},
append: function() {
return this.domManip( arguments, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
var target = manipulationTarget( this, elem );
target.appendChild( elem );
}
});
},
prepend: function() {
return this.domManip( arguments, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
var target = manipulationTarget( this, elem );
target.insertBefore( elem, target.firstChild );
}
});
},
before: function() {
return this.domManip( arguments, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this );
}
});
},
after: function() {
return this.domManip( arguments, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this.nextSibling );
}
});
},
remove: function( selector, keepData /* Internal Use Only */ ) {
var elem,
elems = selector ? jQuery.filter( selector, this ) : this,
i = 0;
for ( ; (elem = elems[i]) != null; i++ ) {
if ( !keepData && elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem ) );
}
if ( elem.parentNode ) {
if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) {
setGlobalEval( getAll( elem, "script" ) );
}
elem.parentNode.removeChild( elem );
}
}
return this;
},
empty: function() {
var elem,
i = 0;
for ( ; (elem = this[i]) != null; i++ ) {
if ( elem.nodeType === 1 ) {
// Prevent memory leaks
jQuery.cleanData( getAll( elem, false ) );
// Remove any remaining nodes
elem.textContent = "";
}
}
return this;
},
clone: function( dataAndEvents, deepDataAndEvents ) {
dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
return this.map(function() {
return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
});
},
html: function( value ) {
return access( this, function( value ) {
var elem = this[ 0 ] || {},
i = 0,
l = this.length;
if ( value === undefined && elem.nodeType === 1 ) {
return elem.innerHTML;
}
// See if we can take a shortcut and just use innerHTML
if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
!wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) {
value = value.replace( rxhtmlTag, "<$1></$2>" );
try {
for ( ; i < l; i++ ) {
elem = this[ i ] || {};
// Remove element nodes and prevent memory leaks
if ( elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem, false ) );
elem.innerHTML = value;
}
}
elem = 0;
// If using innerHTML throws an exception, use the fallback method
} catch( e ) {}
}
if ( elem ) {
this.empty().append( value );
}
}, null, value, arguments.length );
},
replaceWith: function() {
var arg = arguments[ 0 ];
// Make the changes, replacing each context element with the new content
this.domManip( arguments, function( elem ) {
arg = this.parentNode;
jQuery.cleanData( getAll( this ) );
if ( arg ) {
arg.replaceChild( elem, this );
}
});
// Force removal if there was no new content (e.g., from empty arguments)
return arg && (arg.length || arg.nodeType) ? this : this.remove();
},
detach: function( selector ) {
return this.remove( selector, true );
},
domManip: function( args, callback ) {
// Flatten any nested arrays
args = concat.apply( [], args );
var fragment, first, scripts, hasScripts, node, doc,
i = 0,
l = this.length,
set = this,
iNoClone = l - 1,
value = args[ 0 ],
isFunction = jQuery.isFunction( value );
// We can't cloneNode fragments that contain checked, in WebKit
if ( isFunction ||
( l > 1 && typeof value === "string" &&
!support.checkClone && rchecked.test( value ) ) ) {
return this.each(function( index ) {
var self = set.eq( index );
if ( isFunction ) {
args[ 0 ] = value.call( this, index, self.html() );
}
self.domManip( args, callback );
});
}
if ( l ) {
fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this );
first = fragment.firstChild;
if ( fragment.childNodes.length === 1 ) {
fragment = first;
}
if ( first ) {
scripts = jQuery.map( getAll( fragment, "script" ), disableScript );
hasScripts = scripts.length;
// Use the original fragment for the last item instead of the first because it can end up
// being emptied incorrectly in certain situations (#8070).
for ( ; i < l; i++ ) {
node = fragment;
if ( i !== iNoClone ) {
node = jQuery.clone( node, true, true );
// Keep references to cloned scripts for later restoration
if ( hasScripts ) {
// Support: QtWebKit
// jQuery.merge because push.apply(_, arraylike) throws
jQuery.merge( scripts, getAll( node, "script" ) );
}
}
callback.call( this[ i ], node, i );
}
if ( hasScripts ) {
doc = scripts[ scripts.length - 1 ].ownerDocument;
// Reenable scripts
jQuery.map( scripts, restoreScript );
// Evaluate executable scripts on first document insertion
for ( i = 0; i < hasScripts; i++ ) {
node = scripts[ i ];
if ( rscriptType.test( node.type || "" ) &&
!data_priv.access( node, "globalEval" ) && jQuery.contains( doc, node ) ) {
if ( node.src ) {
// Optional AJAX dependency, but won't run scripts if not present
if ( jQuery._evalUrl ) {
jQuery._evalUrl( node.src );
}
} else {
jQuery.globalEval( node.textContent.replace( rcleanScript, "" ) );
}
}
}
}
}
}
return this;
}
});
jQuery.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function( name, original ) {
jQuery.fn[ name ] = function( selector ) {
var elems,
ret = [],
insert = jQuery( selector ),
last = insert.length - 1,
i = 0;
for ( ; i <= last; i++ ) {
elems = i === last ? this : this.clone( true );
jQuery( insert[ i ] )[ original ]( elems );
// Support: QtWebKit
// .get() because push.apply(_, arraylike) throws
push.apply( ret, elems.get() );
}
return this.pushStack( ret );
};
});
// Based off of the plugin by Clint Helfers, with permission.
// http://blindsignals.com/index.php/2009/07/jquery-delay/
jQuery.fn.delay = function( time, type ) {
time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
type = type || "fx";
return this.queue( type, function( next, hooks ) {
var timeout = setTimeout( next, time );
hooks.stop = function() {
clearTimeout( timeout );
};
});
};
(function() {
var input = document.createElement( "input" ),
select = document.createElement( "select" ),
opt = select.appendChild( document.createElement( "option" ) );
input.type = "checkbox";
// Support: iOS 5.1, Android 4.x, Android 2.3
// Check the default checkbox/radio value ("" on old WebKit; "on" elsewhere)
support.checkOn = input.value !== "";
// Must access the parent to make an option select properly
// Support: IE9, IE10
support.optSelected = opt.selected;
// Make sure that the options inside disabled selects aren't marked as disabled
// (WebKit marks them as disabled)
select.disabled = true;
support.optDisabled = !opt.disabled;
// Check if an input maintains its value after becoming a radio
// Support: IE9, IE10
input = document.createElement( "input" );
input.value = "t";
input.type = "radio";
support.radioValue = input.value === "t";
})();
var nodeHook, boolHook,
attrHandle = jQuery.expr.attrHandle;
jQuery.fn.extend({
attr: function( name, value ) {
return access( this, jQuery.attr, name, value, arguments.length > 1 );
},
removeAttr: function( name ) {
return this.each(function() {
jQuery.removeAttr( this, name );
});
}
});
jQuery.extend({
attr: function( elem, name, value ) {
var hooks, ret,
nType = elem.nodeType;
// don't get/set attributes on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
// Fallback to prop when attributes are not supported
if ( typeof elem.getAttribute === strundefined ) {
return jQuery.prop( elem, name, value );
}
// All attributes are lowercase
// Grab necessary hook if one is defined
if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {
name = name.toLowerCase();
hooks = jQuery.attrHooks[ name ] ||
( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook );
}
if ( value !== undefined ) {
if ( value === null ) {
jQuery.removeAttr( elem, name );
} else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
elem.setAttribute( name, value + "" );
return value;
}
} else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
ret = jQuery.find.attr( elem, name );
// Non-existent attributes return null, we normalize to undefined
return ret == null ?
undefined :
ret;
}
},
removeAttr: function( elem, value ) {
var name, propName,
i = 0,
attrNames = value && value.match( rnotwhite );
if ( attrNames && elem.nodeType === 1 ) {
while ( (name = attrNames[i++]) ) {
propName = jQuery.propFix[ name ] || name;
// Boolean attributes get special treatment (#10870)
if ( jQuery.expr.match.bool.test( name ) ) {
// Set corresponding property to false
elem[ propName ] = false;
}
elem.removeAttribute( name );
}
}
},
attrHooks: {
type: {
set: function( elem, value ) {
if ( !support.radioValue && value === "radio" &&
jQuery.nodeName( elem, "input" ) ) {
// Setting the type on a radio button after the value resets the value in IE6-9
// Reset value to default in case type is set after value during creation
var val = elem.value;
elem.setAttribute( "type", value );
if ( val ) {
elem.value = val;
}
return value;
}
}
}
}
});
// Hooks for boolean attributes
boolHook = {
set: function( elem, value, name ) {
if ( value === false ) {
// Remove boolean attributes when set to false
jQuery.removeAttr( elem, name );
} else {
elem.setAttribute( name, name );
}
return name;
}
};
jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) {
var getter = attrHandle[ name ] || jQuery.find.attr;
attrHandle[ name ] = function( elem, name, isXML ) {
var ret, handle;
if ( !isXML ) {
// Avoid an infinite loop by temporarily removing this function from the getter
handle = attrHandle[ name ];
attrHandle[ name ] = ret;
ret = getter( elem, name, isXML ) != null ?
name.toLowerCase() :
null;
attrHandle[ name ] = handle;
}
return ret;
};
});
var rfocusable = /^(?:input|select|textarea|button)$/i;
jQuery.fn.extend({
prop: function( name, value ) {
return access( this, jQuery.prop, name, value, arguments.length > 1 );
},
removeProp: function( name ) {
return this.each(function() {
delete this[ jQuery.propFix[ name ] || name ];
});
}
});
jQuery.extend({
propFix: {
"for": "htmlFor",
"class": "className"
},
prop: function( elem, name, value ) {
var ret, hooks, notxml,
nType = elem.nodeType;
// don't get/set properties on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
if ( notxml ) {
// Fix name and attach hooks
name = jQuery.propFix[ name ] || name;
hooks = jQuery.propHooks[ name ];
}
if ( value !== undefined ) {
return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ?
ret :
( elem[ name ] = value );
} else {
return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ?
ret :
elem[ name ];
}
},
propHooks: {
tabIndex: {
get: function( elem ) {
return elem.hasAttribute( "tabindex" ) || rfocusable.test( elem.nodeName ) || elem.href ?
elem.tabIndex :
-1;
}
}
}
});
// Support: IE9+
// Selectedness for an option in an optgroup can be inaccurate
if ( !support.optSelected ) {
jQuery.propHooks.selected = {
get: function( elem ) {
var parent = elem.parentNode;
if ( parent && parent.parentNode ) {
parent.parentNode.selectedIndex;
}
return null;
}
};
}
jQuery.each([
"tabIndex",
"readOnly",
"maxLength",
"cellSpacing",
"cellPadding",
"rowSpan",
"colSpan",
"useMap",
"frameBorder",
"contentEditable"
], function() {
jQuery.propFix[ this.toLowerCase() ] = this;
});
var rclass = /[\t\r\n\f]/g;
jQuery.fn.extend({
addClass: function( value ) {
var classes, elem, cur, clazz, j, finalValue,
proceed = typeof value === "string" && value,
i = 0,
len = this.length;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).addClass( value.call( this, j, this.className ) );
});
}
if ( proceed ) {
// The disjunction here is for better compressibility (see removeClass)
classes = ( value || "" ).match( rnotwhite ) || [];
for ( ; i < len; i++ ) {
elem = this[ i ];
cur = elem.nodeType === 1 && ( elem.className ?
( " " + elem.className + " " ).replace( rclass, " " ) :
" "
);
if ( cur ) {
j = 0;
while ( (clazz = classes[j++]) ) {
if ( cur.indexOf( " " + clazz + " " ) < 0 ) {
cur += clazz + " ";
}
}
// only assign if different to avoid unneeded rendering.
finalValue = jQuery.trim( cur );
if ( elem.className !== finalValue ) {
elem.className = finalValue;
}
}
}
}
return this;
},
removeClass: function( value ) {
var classes, elem, cur, clazz, j, finalValue,
proceed = arguments.length === 0 || typeof value === "string" && value,
i = 0,
len = this.length;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).removeClass( value.call( this, j, this.className ) );
});
}
if ( proceed ) {
classes = ( value || "" ).match( rnotwhite ) || [];
for ( ; i < len; i++ ) {
elem = this[ i ];
// This expression is here for better compressibility (see addClass)
cur = elem.nodeType === 1 && ( elem.className ?
( " " + elem.className + " " ).replace( rclass, " " ) :
""
);
if ( cur ) {
j = 0;
while ( (clazz = classes[j++]) ) {
// Remove *all* instances
while ( cur.indexOf( " " + clazz + " " ) >= 0 ) {
cur = cur.replace( " " + clazz + " ", " " );
}
}
// only assign if different to avoid unneeded rendering.
finalValue = value ? jQuery.trim( cur ) : "";
if ( elem.className !== finalValue ) {
elem.className = finalValue;
}
}
}
}
return this;
},
toggleClass: function( value, stateVal ) {
var type = typeof value;
if ( typeof stateVal === "boolean" && type === "string" ) {
return stateVal ? this.addClass( value ) : this.removeClass( value );
}
if ( jQuery.isFunction( value ) ) {
return this.each(function( i ) {
jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal );
});
}
return this.each(function() {
if ( type === "string" ) {
// toggle individual class names
var className,
i = 0,
self = jQuery( this ),
classNames = value.match( rnotwhite ) || [];
while ( (className = classNames[ i++ ]) ) {
// check each className given, space separated list
if ( self.hasClass( className ) ) {
self.removeClass( className );
} else {
self.addClass( className );
}
}
// Toggle whole class name
} else if ( type === strundefined || type === "boolean" ) {
if ( this.className ) {
// store className if set
data_priv.set( this, "__className__", this.className );
}
// If the element has a class name or if we're passed "false",
// then remove the whole classname (if there was one, the above saved it).
// Otherwise bring back whatever was previously saved (if anything),
// falling back to the empty string if nothing was stored.
this.className = this.className || value === false ? "" : data_priv.get( this, "__className__" ) || "";
}
});
},
hasClass: function( selector ) {
var className = " " + selector + " ",
i = 0,
l = this.length;
for ( ; i < l; i++ ) {
if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) {
return true;
}
}
return false;
}
});
var rreturn = /\r/g;
jQuery.fn.extend({
val: function( value ) {
var hooks, ret, isFunction,
elem = this[0];
if ( !arguments.length ) {
if ( elem ) {
hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];
if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
return ret;
}
ret = elem.value;
return typeof ret === "string" ?
// handle most common string cases
ret.replace(rreturn, "") :
// handle cases where value is null/undef or number
ret == null ? "" : ret;
}
return;
}
isFunction = jQuery.isFunction( value );
return this.each(function( i ) {
var val;
if ( this.nodeType !== 1 ) {
return;
}
if ( isFunction ) {
val = value.call( this, i, jQuery( this ).val() );
} else {
val = value;
}
// Treat null/undefined as ""; convert numbers to string
if ( val == null ) {
val = "";
} else if ( typeof val === "number" ) {
val += "";
} else if ( jQuery.isArray( val ) ) {
val = jQuery.map( val, function( value ) {
return value == null ? "" : value + "";
});
}
hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];
// If set returns undefined, fall back to normal setting
if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) {
this.value = val;
}
});
}
});
jQuery.extend({
valHooks: {
select: {
get: function( elem ) {
var value, option,
options = elem.options,
index = elem.selectedIndex,
one = elem.type === "select-one" || index < 0,
values = one ? null : [],
max = one ? index + 1 : options.length,
i = index < 0 ?
max :
one ? index : 0;
// Loop through all the selected options
for ( ; i < max; i++ ) {
option = options[ i ];
// IE6-9 doesn't update selected after form reset (#2551)
if ( ( option.selected || i === index ) &&
// Don't return options that are disabled or in a disabled optgroup
( support.optDisabled ? !option.disabled : option.getAttribute( "disabled" ) === null ) &&
( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) {
// Get the specific value for the option
value = jQuery( option ).val();
// We don't need an array for one selects
if ( one ) {
return value;
}
// Multi-Selects return an array
values.push( value );
}
}
return values;
},
set: function( elem, value ) {
var optionSet, option,
options = elem.options,
values = jQuery.makeArray( value ),
i = options.length;
while ( i-- ) {
option = options[ i ];
if ( (option.selected = jQuery.inArray( jQuery(option).val(), values ) >= 0) ) {
optionSet = true;
}
}
// force browsers to behave consistently when non-matching value is set
if ( !optionSet ) {
elem.selectedIndex = -1;
}
return values;
}
}
}
});
// Radios and checkboxes getter/setter
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = {
set: function( elem, value ) {
if ( jQuery.isArray( value ) ) {
return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 );
}
}
};
if ( !support.checkOn ) {
jQuery.valHooks[ this ].get = function( elem ) {
// Support: Webkit
// "" is returned instead of "on" if a value isn't specified
return elem.getAttribute("value") === null ? "on" : elem.value;
};
}
});
// Return jQuery for attributes-only inclusion
jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
"change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) {
// Handle event binding
jQuery.fn[ name ] = function( data, fn ) {
return arguments.length > 0 ?
this.on( name, null, data, fn ) :
this.trigger( name );
};
});
jQuery.fn.extend({
hover: function( fnOver, fnOut ) {
return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
},
bind: function( types, data, fn ) {
return this.on( types, null, data, fn );
},
unbind: function( types, fn ) {
return this.off( types, null, fn );
},
delegate: function( selector, types, data, fn ) {
return this.on( types, selector, data, fn );
},
undelegate: function( selector, types, fn ) {
// ( namespace ) or ( selector, types [, fn] )
return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn );
}
});
jQuery.fn.extend({
wrapAll: function( html ) {
var wrap;
if ( jQuery.isFunction( html ) ) {
return this.each(function( i ) {
jQuery( this ).wrapAll( html.call(this, i) );
});
}
if ( this[ 0 ] ) {
// The elements to wrap the target around
wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true );
if ( this[ 0 ].parentNode ) {
wrap.insertBefore( this[ 0 ] );
}
wrap.map(function() {
var elem = this;
while ( elem.firstElementChild ) {
elem = elem.firstElementChild;
}
return elem;
}).append( this );
}
return this;
},
wrapInner: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function( i ) {
jQuery( this ).wrapInner( html.call(this, i) );
});
}
return this.each(function() {
var self = jQuery( this ),
contents = self.contents();
if ( contents.length ) {
contents.wrapAll( html );
} else {
self.append( html );
}
});
},
wrap: function( html ) {
var isFunction = jQuery.isFunction( html );
return this.each(function( i ) {
jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html );
});
},
unwrap: function() {
return this.parent().each(function() {
if ( !jQuery.nodeName( this, "body" ) ) {
jQuery( this ).replaceWith( this.childNodes );
}
}).end();
}
});
var r20 = /%20/g,
rbracket = /\[\]$/,
rCRLF = /\r?\n/g,
rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i,
rsubmittable = /^(?:input|select|textarea|keygen)/i;
function buildParams( prefix, obj, traditional, add ) {
var name;
if ( jQuery.isArray( obj ) ) {
// Serialize array item.
jQuery.each( obj, function( i, v ) {
if ( traditional || rbracket.test( prefix ) ) {
// Treat each array item as a scalar.
add( prefix, v );
} else {
// Item is non-scalar (array or object), encode its numeric index.
buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add );
}
});
} else if ( !traditional && jQuery.type( obj ) === "object" ) {
// Serialize object item.
for ( name in obj ) {
buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
}
} else {
// Serialize scalar item.
add( prefix, obj );
}
}
// Serialize an array of form elements or a set of
// key/values into a query string
jQuery.param = function( a, traditional ) {
var prefix,
s = [],
add = function( key, value ) {
// If value is a function, invoke it and return its value
value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value );
s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
};
// Set traditional to true for jQuery <= 1.3.2 behavior.
if ( traditional === undefined ) {
traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional;
}
// If an array was passed in, assume that it is an array of form elements.
if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
// Serialize the form elements
jQuery.each( a, function() {
add( this.name, this.value );
});
} else {
// If traditional, encode the "old" way (the way 1.3.2 or older
// did it), otherwise encode params recursively.
for ( prefix in a ) {
buildParams( prefix, a[ prefix ], traditional, add );
}
}
// Return the resulting serialization
return s.join( "&" ).replace( r20, "+" );
};
jQuery.fn.extend({
serialize: function() {
return jQuery.param( this.serializeArray() );
},
serializeArray: function() {
return this.map(function() {
// Can add propHook for "elements" to filter or add form elements
var elements = jQuery.prop( this, "elements" );
return elements ? jQuery.makeArray( elements ) : this;
})
.filter(function() {
var type = this.type;
// Use .is( ":disabled" ) so that fieldset[disabled] works
return this.name && !jQuery( this ).is( ":disabled" ) &&
rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) &&
( this.checked || !rcheckableType.test( type ) );
})
.map(function( i, elem ) {
var val = jQuery( this ).val();
return val == null ?
null :
jQuery.isArray( val ) ?
jQuery.map( val, function( val ) {
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}) :
{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}).get();
}
});
// data: string of html
// context (optional): If specified, the fragment will be created in this context, defaults to document
// keepScripts (optional): If true, will include scripts passed in the html string
jQuery.parseHTML = function( data, context, keepScripts ) {
if ( !data || typeof data !== "string" ) {
return null;
}
if ( typeof context === "boolean" ) {
keepScripts = context;
context = false;
}
context = context || document;
var parsed = rsingleTag.exec( data ),
scripts = !keepScripts && [];
// Single tag
if ( parsed ) {
return [ context.createElement( parsed[1] ) ];
}
parsed = jQuery.buildFragment( [ data ], context, scripts );
if ( scripts && scripts.length ) {
jQuery( scripts ).remove();
}
return jQuery.merge( [], parsed.childNodes );
};
// Register as a named AMD module, since jQuery can be concatenated with other
// files that may use define, but not via a proper concatenation script that
// understands anonymous AMD modules. A named AMD is safest and most robust
// way to register. Lowercase jquery is used because AMD module names are
// derived from file names, and jQuery is normally delivered in a lowercase
// file name. Do this after creating the global so that if an AMD module wants
// to call noConflict to hide this version of jQuery, it will work.
if ( typeof define === "function" && define.amd ) {
define( "jquery", [], function() {
return jQuery;
});
}
var
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$;
jQuery.noConflict = function( deep ) {
if ( window.$ === jQuery ) {
window.$ = _$;
}
if ( deep && window.jQuery === jQuery ) {
window.jQuery = _jQuery;
}
return jQuery;
};
// Expose jQuery and $ identifiers, even in
// AMD (#7102#comment:10, https://github.com/jquery/jquery/pull/557)
// and CommonJS for browser emulators (#13566)
if ( typeof noGlobal === strundefined ) {
window.jQuery = window.$ = jQuery;
}
return jQuery;
}));
|
var _curry3 = require('./internal/_curry3');
var _isTransformer = require('./internal/_isTransformer');
var _reduce = require('./internal/_reduce');
var _stepCat = require('./internal/_stepCat');
/**
* Transforms the items of the list with the transducer and appends the
* transformed items to the accumulator using an appropriate iterator function
* based on the accumulator type.
*
* The accumulator can be an array, string, object or a transformer. Iterated
* items will be appended to arrays and concatenated to strings. Objects will
* be merged directly or 2-item arrays will be merged as key, value pairs.
*
* The accumulator can also be a transformer object that provides a 2-arity
* reducing iterator function, step, 0-arity initial value function, init, and
* 1-arity result extraction function result. The step function is used as the
* iterator function in reduce. The result function is used to convert the
* final accumulator into the return type and in most cases is R.identity. The
* init function is used to provide the initial accumulator.
*
* The iteration is performed with R.reduce after initializing the transducer.
*
* @func
* @memberOf R
* @since v0.12.0
* @category List
* @sig a -> (b -> b) -> [c] -> a
* @param {*} acc The initial accumulator value.
* @param {Function} xf The transducer function. Receives a transformer and returns a transformer.
* @param {Array} list The list to iterate over.
* @return {*} The final, accumulated value.
* @example
*
* var numbers = [1, 2, 3, 4];
* var transducer = R.compose(R.map(R.add(1)), R.take(2));
*
* R.into([], transducer, numbers); //=> [2, 3]
*
* var intoArray = R.into([]);
* intoArray(transducer, numbers); //=> [2, 3]
*/
module.exports = _curry3(function into(acc, xf, list) {
return _isTransformer(acc) ? _reduce(xf(acc), acc['@@transducer/init'](), list)
: _reduce(xf(_stepCat(acc)), acc, list);
});
|
CKEDITOR.plugins.setLang("colorbutton","vi",{auto:"Tự động",bgColorTitle:"Màu nền",colors:{"000":"Đen",8E5:"Maroon","8B4513":"Saddle Brown","2F4F4F":"Dark Slate Gray","008080":"Teal","000080":"Navy","4B0082":"Indigo",696969:"Dark Gray",B22222:"Fire Brick",A52A2A:"Nâu",DAA520:"Golden Rod","006400":"Dark Green","40E0D0":"Turquoise","0000CD":"Medium Blue",800080:"Purple",808080:"Xám",F00:"Đỏ",FF8C00:"Dark Orange",FFD700:"Vàng","008000":"Xanh lá cây","0FF":"Cyan","00F":"Xanh da trời",EE82EE:"Tím",A9A9A9:"Xám tối",
FFA07A:"Light Salmon",FFA500:"Màu cam",FFFF00:"Vàng","00FF00":"Lime",AFEEEE:"Pale Turquoise",ADD8E6:"Light Blue",DDA0DD:"Plum",D3D3D3:"Light Grey",FFF0F5:"Lavender Blush",FAEBD7:"Antique White",FFFFE0:"Light Yellow",F0FFF0:"Honeydew",F0FFFF:"Azure",F0F8FF:"Alice Blue",E6E6FA:"Lavender",FFF:"Trắng"},more:"Màu khác...",panelTitle:"Màu sắc",textColorTitle:"Màu chữ"});
|
/*
Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'clipboard', 'ja', {
copy: 'コピー',
copyError: 'ブラウザーのセキュリティ設定によりエディタのコピー操作を自動で実行することができません。実行するには手動でキーボードの(Ctrl/Cmd+C)を使用してください。',
cut: '切り取り',
cutError: 'ブラウザーのセキュリティ設定によりエディタの切り取り操作を自動で実行することができません。実行するには手動でキーボードの(Ctrl/Cmd+X)を使用してください。',
paste: '貼り付け',
pasteArea: '貼り付け場所',
pasteMsg: 'キーボード(<STRONG>Ctrl/Cmd+V</STRONG>)を使用して、次の入力エリア内で貼り付けて、<STRONG>OK</STRONG>を押してください。',
securityMsg: 'ブラウザのセキュリティ設定により、エディタはクリップボードデータに直接アクセスすることができません。このウィンドウは貼り付け操作を行う度に表示されます。',
title: '貼り付け'
} );
|
var requirejs = require( 'requirejs' ),
path = require( 'path' ),
fs = require( 'fs' );
module.exports = function( grunt ) {
var min = {}, config = grunt.config.get( 'global' ),
helpers = config.helpers;
grunt.registerTask( 'js:compile', function() {
var require = grunt.config.get( 'js' ).require,
global_config = grunt.config.get( 'global' );
// pull the includes together using require js
requirejs.optimize( require );
// replace the version with the value in version.text
grunt.file.copy( require.out, require.out, { process: function( fileContents ) {
return fileContents.replace( /__version__/, '"' + global_config.ver.official + '"' );
}});
});
grunt.registerTask( 'js:cleanup', 'compile and minify the js', function() {
var require = grunt.config.get( 'js' ).require;
// remove the requirejs compile output
fs.unlink( require.out );
});
// NOTE custom dasks don't accept dependencies so we alias
grunt.registerTask( 'js', 'custom_init config:async js:compile concat:js min js:cleanup' );
};
|
// Copyright (c) 2005-2007 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
// (c) 2005-2007 Sammi Williams (http://www.oriontransfer.co.nz, sammi@oriontransfer.co.nz)
//
// script.aculo.us is freely distributable under the terms of an MIT-style license.
// For details, see the script.aculo.us web site: http://script.aculo.us/
if(typeof Effect == 'undefined')
throw("dragdrop.js requires including script.aculo.us' effects.js library");
var Droppables = {
drops: [],
remove: function(element) {
this.drops = this.drops.reject(function(d) { return d.element==$(element) });
},
add: function(element) {
element = $(element);
var options = Object.extend({
greedy: true,
hoverclass: null,
tree: false
}, arguments[1] || {});
// cache containers
if(options.containment) {
options._containers = [];
var containment = options.containment;
if((typeof containment == 'object') &&
(containment.constructor == Array)) {
containment.each( function(c) { options._containers.push($(c)) });
} else {
options._containers.push($(containment));
}
}
if(options.accept) options.accept = [options.accept].flatten();
Element.makePositioned(element); // fix IE
options.element = element;
this.drops.push(options);
},
findDeepestChild: function(drops) {
deepest = drops[0];
for (i = 1; i < drops.length; ++i)
if (Element.isParent(drops[i].element, deepest.element))
deepest = drops[i];
return deepest;
},
isContained: function(element, drop) {
var containmentNode;
if(drop.tree) {
containmentNode = element.treeNode;
} else {
containmentNode = element.parentNode;
}
return drop._containers.detect(function(c) { return containmentNode == c });
},
isAffected: function(point, element, drop) {
return (
(drop.element!=element) &&
((!drop._containers) ||
this.isContained(element, drop)) &&
((!drop.accept) ||
(Element.classNames(element).detect(
function(v) { return drop.accept.include(v) } ) )) &&
Position.within(drop.element, point[0], point[1]) );
},
deactivate: function(drop) {
if(drop.hoverclass)
Element.removeClassName(drop.element, drop.hoverclass);
this.last_active = null;
},
activate: function(drop) {
if(drop.hoverclass)
Element.addClassName(drop.element, drop.hoverclass);
this.last_active = drop;
},
show: function(point, element) {
if(!this.drops.length) return;
var affected = [];
if(this.last_active) this.deactivate(this.last_active);
this.drops.each( function(drop) {
if(Droppables.isAffected(point, element, drop))
affected.push(drop);
});
if(affected.length>0) {
drop = Droppables.findDeepestChild(affected);
Position.within(drop.element, point[0], point[1]);
if(drop.onHover)
drop.onHover(element, drop.element, Position.overlap(drop.overlap, drop.element));
Droppables.activate(drop);
}
},
fire: function(event, element) {
if(!this.last_active) return;
Position.prepare();
if (this.isAffected([Event.pointerX(event), Event.pointerY(event)], element, this.last_active))
if (this.last_active.onDrop) {
this.last_active.onDrop(element, this.last_active.element, event);
return true;
}
},
reset: function() {
if(this.last_active)
this.deactivate(this.last_active);
}
}
var Draggables = {
drags: [],
observers: [],
register: function(draggable) {
if(this.drags.length == 0) {
this.eventMouseUp = this.endDrag.bindAsEventListener(this);
this.eventMouseMove = this.updateDrag.bindAsEventListener(this);
this.eventKeypress = this.keyPress.bindAsEventListener(this);
Event.observe(document, "mouseup", this.eventMouseUp);
Event.observe(document, "mousemove", this.eventMouseMove);
Event.observe(document, "keypress", this.eventKeypress);
}
this.drags.push(draggable);
},
unregister: function(draggable) {
this.drags = this.drags.reject(function(d) { return d==draggable });
if(this.drags.length == 0) {
Event.stopObserving(document, "mouseup", this.eventMouseUp);
Event.stopObserving(document, "mousemove", this.eventMouseMove);
Event.stopObserving(document, "keypress", this.eventKeypress);
}
},
activate: function(draggable) {
if(draggable.options.delay) {
this._timeout = setTimeout(function() {
Draggables._timeout = null;
window.focus();
Draggables.activeDraggable = draggable;
}.bind(this), draggable.options.delay);
} else {
window.focus(); // allows keypress events if window isn't currently focused, fails for Safari
this.activeDraggable = draggable;
}
},
deactivate: function() {
this.activeDraggable = null;
},
updateDrag: function(event) {
if(!this.activeDraggable) return;
var pointer = [Event.pointerX(event), Event.pointerY(event)];
// Mozilla-based browsers fire successive mousemove events with
// the same coordinates, prevent needless redrawing (moz bug?)
if(this._lastPointer && (this._lastPointer.inspect() == pointer.inspect())) return;
this._lastPointer = pointer;
this.activeDraggable.updateDrag(event, pointer);
},
endDrag: function(event) {
if(this._timeout) {
clearTimeout(this._timeout);
this._timeout = null;
}
if(!this.activeDraggable) return;
this._lastPointer = null;
this.activeDraggable.endDrag(event);
this.activeDraggable = null;
},
keyPress: function(event) {
if(this.activeDraggable)
this.activeDraggable.keyPress(event);
},
addObserver: function(observer) {
this.observers.push(observer);
this._cacheObserverCallbacks();
},
removeObserver: function(element) { // element instead of observer fixes mem leaks
this.observers = this.observers.reject( function(o) { return o.element==element });
this._cacheObserverCallbacks();
},
notify: function(eventName, draggable, event) { // 'onStart', 'onEnd', 'onDrag'
if(this[eventName+'Count'] > 0)
this.observers.each( function(o) {
if(o[eventName]) o[eventName](eventName, draggable, event);
});
if(draggable.options[eventName]) draggable.options[eventName](draggable, event);
},
_cacheObserverCallbacks: function() {
['onStart','onEnd','onDrag'].each( function(eventName) {
Draggables[eventName+'Count'] = Draggables.observers.select(
function(o) { return o[eventName]; }
).length;
});
}
}
/*--------------------------------------------------------------------------*/
var Draggable = Class.create();
Draggable._dragging = {};
Draggable.prototype = {
initialize: function(element) {
var defaults = {
handle: false,
reverteffect: function(element, top_offset, left_offset) {
var dur = Math.sqrt(Math.abs(top_offset^2)+Math.abs(left_offset^2))*0.02;
new Effect.Move(element, { x: -left_offset, y: -top_offset, duration: dur,
queue: {scope:'_draggable', position:'end'}
});
},
endeffect: function(element) {
var toOpacity = typeof element._opacity == 'number' ? element._opacity : 1.0;
new Effect.Opacity(element, {duration:0.2, from:0.7, to:toOpacity,
queue: {scope:'_draggable', position:'end'},
afterFinish: function(){
Draggable._dragging[element] = false
}
});
},
zindex: 1000,
revert: false,
quiet: false,
scroll: false,
scrollSensitivity: 20,
scrollSpeed: 15,
snap: false, // false, or xy or [x,y] or function(x,y){ return [x,y] }
delay: 0
};
if(!arguments[1] || typeof arguments[1].endeffect == 'undefined')
Object.extend(defaults, {
starteffect: function(element) {
element._opacity = Element.getOpacity(element);
Draggable._dragging[element] = true;
new Effect.Opacity(element, {duration:0.2, from:element._opacity, to:0.7});
}
});
var options = Object.extend(defaults, arguments[1] || {});
this.element = $(element);
if(options.handle && (typeof options.handle == 'string'))
this.handle = this.element.down('.'+options.handle, 0);
if(!this.handle) this.handle = $(options.handle);
if(!this.handle) this.handle = this.element;
if(options.scroll && !options.scroll.scrollTo && !options.scroll.outerHTML) {
options.scroll = $(options.scroll);
this._isScrollChild = Element.childOf(this.element, options.scroll);
}
Element.makePositioned(this.element); // fix IE
this.delta = this.currentDelta();
this.options = options;
this.dragging = false;
this.eventMouseDown = this.initDrag.bindAsEventListener(this);
Event.observe(this.handle, "mousedown", this.eventMouseDown);
Draggables.register(this);
},
destroy: function() {
Event.stopObserving(this.handle, "mousedown", this.eventMouseDown);
Draggables.unregister(this);
},
currentDelta: function() {
return([
parseInt(Element.getStyle(this.element,'left') || '0'),
parseInt(Element.getStyle(this.element,'top') || '0')]);
},
initDrag: function(event) {
if(typeof Draggable._dragging[this.element] != 'undefined' &&
Draggable._dragging[this.element]) return;
if(Event.isLeftClick(event)) {
// abort on form elements, fixes a Firefox issue
var src = Event.element(event);
if((tag_name = src.tagName.toUpperCase()) && (
tag_name=='INPUT' ||
tag_name=='SELECT' ||
tag_name=='OPTION' ||
tag_name=='BUTTON' ||
tag_name=='TEXTAREA')) return;
var pointer = [Event.pointerX(event), Event.pointerY(event)];
var pos = Position.cumulativeOffset(this.element);
this.offset = [0,1].map( function(i) { return (pointer[i] - pos[i]) });
Draggables.activate(this);
Event.stop(event);
}
},
startDrag: function(event) {
this.dragging = true;
if(this.options.zindex) {
this.originalZ = parseInt(Element.getStyle(this.element,'z-index') || 0);
this.element.style.zIndex = this.options.zindex;
}
if(this.options.ghosting) {
this._clone = this.element.cloneNode(true);
Position.absolutize(this.element);
this.element.parentNode.insertBefore(this._clone, this.element);
}
if(this.options.scroll) {
if (this.options.scroll == window) {
var where = this._getWindowScroll(this.options.scroll);
this.originalScrollLeft = where.left;
this.originalScrollTop = where.top;
} else {
this.originalScrollLeft = this.options.scroll.scrollLeft;
this.originalScrollTop = this.options.scroll.scrollTop;
}
}
Draggables.notify('onStart', this, event);
if(this.options.starteffect) this.options.starteffect(this.element);
},
updateDrag: function(event, pointer) {
if(!this.dragging) this.startDrag(event);
if(!this.options.quiet){
Position.prepare();
Droppables.show(pointer, this.element);
}
Draggables.notify('onDrag', this, event);
this.draw(pointer);
if(this.options.change) this.options.change(this);
if(this.options.scroll) {
this.stopScrolling();
var p;
if (this.options.scroll == window) {
with(this._getWindowScroll(this.options.scroll)) { p = [ left, top, left+width, top+height ]; }
} else {
p = Position.page(this.options.scroll);
p[0] += this.options.scroll.scrollLeft + Position.deltaX;
p[1] += this.options.scroll.scrollTop + Position.deltaY;
p.push(p[0]+this.options.scroll.offsetWidth);
p.push(p[1]+this.options.scroll.offsetHeight);
}
var speed = [0,0];
if(pointer[0] < (p[0]+this.options.scrollSensitivity)) speed[0] = pointer[0]-(p[0]+this.options.scrollSensitivity);
if(pointer[1] < (p[1]+this.options.scrollSensitivity)) speed[1] = pointer[1]-(p[1]+this.options.scrollSensitivity);
if(pointer[0] > (p[2]-this.options.scrollSensitivity)) speed[0] = pointer[0]-(p[2]-this.options.scrollSensitivity);
if(pointer[1] > (p[3]-this.options.scrollSensitivity)) speed[1] = pointer[1]-(p[3]-this.options.scrollSensitivity);
this.startScrolling(speed);
}
// fix AppleWebKit rendering
if(Prototype.Browser.WebKit) window.scrollBy(0,0);
Event.stop(event);
},
finishDrag: function(event, success) {
this.dragging = false;
if(this.options.quiet){
Position.prepare();
var pointer = [Event.pointerX(event), Event.pointerY(event)];
Droppables.show(pointer, this.element);
}
if(this.options.ghosting) {
Position.relativize(this.element);
Element.remove(this._clone);
this._clone = null;
}
var dropped = false;
if(success) {
dropped = Droppables.fire(event, this.element);
if (!dropped) dropped = false;
}
if(dropped && this.options.onDropped) this.options.onDropped(this.element);
Draggables.notify('onEnd', this, event);
var revert = this.options.revert;
if(revert && typeof revert == 'function') revert = revert(this.element);
var d = this.currentDelta();
if(revert && this.options.reverteffect) {
if (dropped == 0 || revert != 'failure')
this.options.reverteffect(this.element,
d[1]-this.delta[1], d[0]-this.delta[0]);
} else {
this.delta = d;
}
if(this.options.zindex)
this.element.style.zIndex = this.originalZ;
if(this.options.endeffect)
this.options.endeffect(this.element);
Draggables.deactivate(this);
Droppables.reset();
},
keyPress: function(event) {
if(event.keyCode!=Event.KEY_ESC) return;
this.finishDrag(event, false);
Event.stop(event);
},
endDrag: function(event) {
if(!this.dragging) return;
this.stopScrolling();
this.finishDrag(event, true);
Event.stop(event);
},
draw: function(point) {
var pos = Position.cumulativeOffset(this.element);
if(this.options.ghosting) {
var r = Position.realOffset(this.element);
pos[0] += r[0] - Position.deltaX; pos[1] += r[1] - Position.deltaY;
}
var d = this.currentDelta();
pos[0] -= d[0]; pos[1] -= d[1];
if(this.options.scroll && (this.options.scroll != window && this._isScrollChild)) {
pos[0] -= this.options.scroll.scrollLeft-this.originalScrollLeft;
pos[1] -= this.options.scroll.scrollTop-this.originalScrollTop;
}
var p = [0,1].map(function(i){
return (point[i]-pos[i]-this.offset[i])
}.bind(this));
if(this.options.snap) {
if(typeof this.options.snap == 'function') {
p = this.options.snap(p[0],p[1],this);
} else {
if(this.options.snap instanceof Array) {
p = p.map( function(v, i) {
return Math.round(v/this.options.snap[i])*this.options.snap[i] }.bind(this))
} else {
p = p.map( function(v) {
return Math.round(v/this.options.snap)*this.options.snap }.bind(this))
}
}}
var style = this.element.style;
if((!this.options.constraint) || (this.options.constraint=='horizontal'))
style.left = p[0] + "px";
if((!this.options.constraint) || (this.options.constraint=='vertical'))
style.top = p[1] + "px";
if(style.visibility=="hidden") style.visibility = ""; // fix gecko rendering
},
stopScrolling: function() {
if(this.scrollInterval) {
clearInterval(this.scrollInterval);
this.scrollInterval = null;
Draggables._lastScrollPointer = null;
}
},
startScrolling: function(speed) {
if(!(speed[0] || speed[1])) return;
this.scrollSpeed = [speed[0]*this.options.scrollSpeed,speed[1]*this.options.scrollSpeed];
this.lastScrolled = new Date();
this.scrollInterval = setInterval(this.scroll.bind(this), 10);
},
scroll: function() {
var current = new Date();
var delta = current - this.lastScrolled;
this.lastScrolled = current;
if(this.options.scroll == window) {
with (this._getWindowScroll(this.options.scroll)) {
if (this.scrollSpeed[0] || this.scrollSpeed[1]) {
var d = delta / 1000;
this.options.scroll.scrollTo( left + d*this.scrollSpeed[0], top + d*this.scrollSpeed[1] );
}
}
} else {
this.options.scroll.scrollLeft += this.scrollSpeed[0] * delta / 1000;
this.options.scroll.scrollTop += this.scrollSpeed[1] * delta / 1000;
}
Position.prepare();
Droppables.show(Draggables._lastPointer, this.element);
Draggables.notify('onDrag', this);
if (this._isScrollChild) {
Draggables._lastScrollPointer = Draggables._lastScrollPointer || $A(Draggables._lastPointer);
Draggables._lastScrollPointer[0] += this.scrollSpeed[0] * delta / 1000;
Draggables._lastScrollPointer[1] += this.scrollSpeed[1] * delta / 1000;
if (Draggables._lastScrollPointer[0] < 0)
Draggables._lastScrollPointer[0] = 0;
if (Draggables._lastScrollPointer[1] < 0)
Draggables._lastScrollPointer[1] = 0;
this.draw(Draggables._lastScrollPointer);
}
if(this.options.change) this.options.change(this);
},
_getWindowScroll: function(w) {
var T, L, W, H;
with (w.document) {
if (w.document.documentElement && documentElement.scrollTop) {
T = documentElement.scrollTop;
L = documentElement.scrollLeft;
} else if (w.document.body) {
T = body.scrollTop;
L = body.scrollLeft;
}
if (w.innerWidth) {
W = w.innerWidth;
H = w.innerHeight;
} else if (w.document.documentElement && documentElement.clientWidth) {
W = documentElement.clientWidth;
H = documentElement.clientHeight;
} else {
W = body.offsetWidth;
H = body.offsetHeight
}
}
return { top: T, left: L, width: W, height: H };
}
}
/*--------------------------------------------------------------------------*/
var SortableObserver = Class.create();
SortableObserver.prototype = {
initialize: function(element, observer) {
this.element = $(element);
this.observer = observer;
this.lastValue = Sortable.serialize(this.element);
},
onStart: function() {
this.lastValue = Sortable.serialize(this.element);
},
onEnd: function() {
Sortable.unmark();
if(this.lastValue != Sortable.serialize(this.element))
this.observer(this.element)
}
}
var Sortable = {
SERIALIZE_RULE: /^[^_\-](?:[A-Za-z0-9\-\_]*)[_](.*)$/,
sortables: {},
_findRootElement: function(element) {
while (element.tagName.toUpperCase() != "BODY") {
if(element.id && Sortable.sortables[element.id]) return element;
element = element.parentNode;
}
},
options: function(element) {
element = Sortable._findRootElement($(element));
if(!element) return;
return Sortable.sortables[element.id];
},
destroy: function(element){
var s = Sortable.options(element);
if(s) {
Draggables.removeObserver(s.element);
s.droppables.each(function(d){ Droppables.remove(d) });
s.draggables.invoke('destroy');
delete Sortable.sortables[s.element.id];
}
},
create: function(element) {
element = $(element);
var options = Object.extend({
element: element,
tag: 'li', // assumes li children, override with tag: 'tagname'
dropOnEmpty: false,
tree: false,
treeTag: 'ul',
overlap: 'vertical', // one of 'vertical', 'horizontal'
constraint: 'vertical', // one of 'vertical', 'horizontal', false
containment: element, // also takes array of elements (or id's); or false
handle: false, // or a CSS class
only: false,
delay: 0,
hoverclass: null,
ghosting: false,
quiet: false,
scroll: false,
scrollSensitivity: 20,
scrollSpeed: 15,
format: this.SERIALIZE_RULE,
// these take arrays of elements or ids and can be
// used for better initialization performance
elements: false,
handles: false,
onChange: Prototype.emptyFunction,
onUpdate: Prototype.emptyFunction
}, arguments[1] || {});
// clear any old sortable with same element
this.destroy(element);
// build options for the draggables
var options_for_draggable = {
revert: true,
quiet: options.quiet,
scroll: options.scroll,
scrollSpeed: options.scrollSpeed,
scrollSensitivity: options.scrollSensitivity,
delay: options.delay,
ghosting: options.ghosting,
constraint: options.constraint,
handle: options.handle };
if(options.starteffect)
options_for_draggable.starteffect = options.starteffect;
if(options.reverteffect)
options_for_draggable.reverteffect = options.reverteffect;
else
if(options.ghosting) options_for_draggable.reverteffect = function(element) {
element.style.top = 0;
element.style.left = 0;
};
if(options.endeffect)
options_for_draggable.endeffect = options.endeffect;
if(options.zindex)
options_for_draggable.zindex = options.zindex;
// build options for the droppables
var options_for_droppable = {
overlap: options.overlap,
containment: options.containment,
tree: options.tree,
hoverclass: options.hoverclass,
onHover: Sortable.onHover
}
var options_for_tree = {
onHover: Sortable.onEmptyHover,
overlap: options.overlap,
containment: options.containment,
hoverclass: options.hoverclass
}
// fix for gecko engine
Element.cleanWhitespace(element);
options.draggables = [];
options.droppables = [];
// drop on empty handling
if(options.dropOnEmpty || options.tree) {
Droppables.add(element, options_for_tree);
options.droppables.push(element);
}
(options.elements || this.findElements(element, options) || []).each( function(e,i) {
var handle = options.handles ? $(options.handles[i]) :
(options.handle ? $(e).getElementsByClassName(options.handle)[0] : e);
options.draggables.push(
new Draggable(e, Object.extend(options_for_draggable, { handle: handle })));
Droppables.add(e, options_for_droppable);
if(options.tree) e.treeNode = element;
options.droppables.push(e);
});
if(options.tree) {
(Sortable.findTreeElements(element, options) || []).each( function(e) {
Droppables.add(e, options_for_tree);
e.treeNode = element;
options.droppables.push(e);
});
}
// keep reference
this.sortables[element.id] = options;
// for onupdate
Draggables.addObserver(new SortableObserver(element, options.onUpdate));
},
// return all suitable-for-sortable elements in a guaranteed order
findElements: function(element, options) {
return Element.findChildren(
element, options.only, options.tree ? true : false, options.tag);
},
findTreeElements: function(element, options) {
return Element.findChildren(
element, options.only, options.tree ? true : false, options.treeTag);
},
onHover: function(element, dropon, overlap) {
if(Element.isParent(dropon, element)) return;
if(overlap > .33 && overlap < .66 && Sortable.options(dropon).tree) {
return;
} else if(overlap>0.5) {
Sortable.mark(dropon, 'before');
if(dropon.previousSibling != element) {
var oldParentNode = element.parentNode;
element.style.visibility = "hidden"; // fix gecko rendering
dropon.parentNode.insertBefore(element, dropon);
if(dropon.parentNode!=oldParentNode)
Sortable.options(oldParentNode).onChange(element);
Sortable.options(dropon.parentNode).onChange(element);
}
} else {
Sortable.mark(dropon, 'after');
var nextElement = dropon.nextSibling || null;
if(nextElement != element) {
var oldParentNode = element.parentNode;
element.style.visibility = "hidden"; // fix gecko rendering
dropon.parentNode.insertBefore(element, nextElement);
if(dropon.parentNode!=oldParentNode)
Sortable.options(oldParentNode).onChange(element);
Sortable.options(dropon.parentNode).onChange(element);
}
}
},
onEmptyHover: function(element, dropon, overlap) {
var oldParentNode = element.parentNode;
var droponOptions = Sortable.options(dropon);
if(!Element.isParent(dropon, element)) {
var index;
var children = Sortable.findElements(dropon, {tag: droponOptions.tag, only: droponOptions.only});
var child = null;
if(children) {
var offset = Element.offsetSize(dropon, droponOptions.overlap) * (1.0 - overlap);
for (index = 0; index < children.length; index += 1) {
if (offset - Element.offsetSize (children[index], droponOptions.overlap) >= 0) {
offset -= Element.offsetSize (children[index], droponOptions.overlap);
} else if (offset - (Element.offsetSize (children[index], droponOptions.overlap) / 2) >= 0) {
child = index + 1 < children.length ? children[index + 1] : null;
break;
} else {
child = children[index];
break;
}
}
}
dropon.insertBefore(element, child);
Sortable.options(oldParentNode).onChange(element);
droponOptions.onChange(element);
}
},
unmark: function() {
if(Sortable._marker) Sortable._marker.hide();
},
mark: function(dropon, position) {
// mark on ghosting only
var sortable = Sortable.options(dropon.parentNode);
if(sortable && !sortable.ghosting) return;
if(!Sortable._marker) {
Sortable._marker =
($('dropmarker') || Element.extend(document.createElement('DIV'))).
hide().addClassName('dropmarker').setStyle({position:'absolute'});
document.getElementsByTagName("body").item(0).appendChild(Sortable._marker);
}
var offsets = Position.cumulativeOffset(dropon);
Sortable._marker.setStyle({left: offsets[0]+'px', top: offsets[1] + 'px'});
if(position=='after')
if(sortable.overlap == 'horizontal')
Sortable._marker.setStyle({left: (offsets[0]+dropon.clientWidth) + 'px'});
else
Sortable._marker.setStyle({top: (offsets[1]+dropon.clientHeight) + 'px'});
Sortable._marker.show();
},
_tree: function(element, options, parent) {
var children = Sortable.findElements(element, options) || [];
for (var i = 0; i < children.length; ++i) {
var match = children[i].id.match(options.format);
if (!match) continue;
var child = {
id: encodeURIComponent(match ? match[1] : null),
element: element,
parent: parent,
children: [],
position: parent.children.length,
container: $(children[i]).down(options.treeTag)
}
/* Get the element containing the children and recurse over it */
if (child.container)
this._tree(child.container, options, child)
parent.children.push (child);
}
return parent;
},
tree: function(element) {
element = $(element);
var sortableOptions = this.options(element);
var options = Object.extend({
tag: sortableOptions.tag,
treeTag: sortableOptions.treeTag,
only: sortableOptions.only,
name: element.id,
format: sortableOptions.format
}, arguments[1] || {});
var root = {
id: null,
parent: null,
children: [],
container: element,
position: 0
}
return Sortable._tree(element, options, root);
},
/* Construct a [i] index for a particular node */
_constructIndex: function(node) {
var index = '';
do {
if (node.id) index = '[' + node.position + ']' + index;
} while ((node = node.parent) != null);
return index;
},
sequence: function(element) {
element = $(element);
var options = Object.extend(this.options(element), arguments[1] || {});
return $(this.findElements(element, options) || []).map( function(item) {
return item.id.match(options.format) ? item.id.match(options.format)[1] : '';
});
},
setSequence: function(element, new_sequence) {
element = $(element);
var options = Object.extend(this.options(element), arguments[2] || {});
var nodeMap = {};
this.findElements(element, options).each( function(n) {
if (n.id.match(options.format))
nodeMap[n.id.match(options.format)[1]] = [n, n.parentNode];
n.parentNode.removeChild(n);
});
new_sequence.each(function(ident) {
var n = nodeMap[ident];
if (n) {
n[1].appendChild(n[0]);
delete nodeMap[ident];
}
});
},
serialize: function(element) {
element = $(element);
var options = Object.extend(Sortable.options(element), arguments[1] || {});
var name = encodeURIComponent(
(arguments[1] && arguments[1].name) ? arguments[1].name : element.id);
if (options.tree) {
return Sortable.tree(element, arguments[1]).children.map( function (item) {
return [name + Sortable._constructIndex(item) + "[id]=" +
encodeURIComponent(item.id)].concat(item.children.map(arguments.callee));
}).flatten().join('&');
} else {
return Sortable.sequence(element, arguments[1]).map( function(item) {
return name + "[]=" + encodeURIComponent(item);
}).join('&');
}
}
}
// Returns true if child is contained within element
Element.isParent = function(child, element) {
if (!child.parentNode || child == element) return false;
if (child.parentNode == element) return true;
return Element.isParent(child.parentNode, element);
}
Element.findChildren = function(element, only, recursive, tagName) {
if(!element.hasChildNodes()) return null;
tagName = tagName.toUpperCase();
if(only) only = [only].flatten();
var elements = [];
$A(element.childNodes).each( function(e) {
if(e.tagName && e.tagName.toUpperCase()==tagName &&
(!only || (Element.classNames(e).detect(function(v) { return only.include(v) }))))
elements.push(e);
if(recursive) {
var grandchildren = Element.findChildren(e, only, recursive, tagName);
if(grandchildren) elements.push(grandchildren);
}
});
return (elements.length>0 ? elements.flatten() : []);
}
Element.offsetSize = function (element, type) {
return element['offset' + ((type=='vertical' || type=='height') ? 'Height' : 'Width')];
}
|
"use strict";
var exec = require( "child_process" ).exec;
module.exports = function( grunt ) {
grunt.registerTask( "version", "Commit a new version", function( version ) {
if ( !/\d\.\d+\.\d+(?:-pre)?/.test( version ) ) {
grunt.fatal( "Version must follow semver release format: " + version );
return;
}
var done = this.async(),
files = grunt.config( "version.files" ),
rversion = /("version":\s*")[^"]+/;
// Update version in specified files
files.forEach(function( filename ) {
var text = grunt.file.read( filename );
text = text.replace( rversion, "$1" + version );
grunt.file.write( filename, text );
});
// Add files to git index
exec( "git add -A", function( err ) {
if ( err ) {
grunt.fatal( err );
return;
}
// Commit next pre version
grunt.config( "pkg.version", version );
grunt.task.run([
"build",
"tests",
"commit:'Release\\: Update version to " + version + "'"
]);
done();
});
});
};
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
(function(global) {
global.ng = global.ng || {};
global.ng.common = global.ng.common || {};
global.ng.common.locales = global.ng.common.locales || {};
const u = undefined;
function plural(n) {
let i = Math.floor(Math.abs(n)), v = n.toString().replace(/^[^.]*\.?/, '').length;
if (v === 0 && i % 100 === 1) return 1;
if (v === 0 && i % 100 === 2) return 2;
if (v === 0 && i % 100 === Math.floor(i % 100) && i % 100 >= 3 && i % 100 <= 4 || !(v === 0))
return 3;
return 5;
}
global.ng.common.locales['sl'] = [
'sl',
[['d', 'p'], ['dop.', 'pop.'], u],
[['d', 'p'], ['dop.', 'pop.'], ['dopoldne', 'popoldne']],
[
['n', 'p', 't', 's', 'č', 'p', 's'], ['ned.', 'pon.', 'tor.', 'sre.', 'čet.', 'pet.', 'sob.'],
['nedelja', 'ponedeljek', 'torek', 'sreda', 'četrtek', 'petek', 'sobota'],
['ned.', 'pon.', 'tor.', 'sre.', 'čet.', 'pet.', 'sob.']
],
u,
[
['j', 'f', 'm', 'a', 'm', 'j', 'j', 'a', 's', 'o', 'n', 'd'],
['jan.', 'feb.', 'mar.', 'apr.', 'maj', 'jun.', 'jul.', 'avg.', 'sep.', 'okt.', 'nov.', 'dec.'],
[
'januar', 'februar', 'marec', 'april', 'maj', 'junij', 'julij', 'avgust', 'september',
'oktober', 'november', 'december'
]
],
u,
[['pr. Kr.', 'po Kr.'], u, ['pred Kristusom', 'po Kristusu']],
1,
[6, 0],
['d. MM. yy', 'd. MMM y', 'dd. MMMM y', 'EEEE, dd. MMMM y'],
['HH:mm', 'HH:mm:ss', 'HH:mm:ss z', 'HH:mm:ss zzzz'],
['{1} {0}', u, u, u],
[',', '.', ';', '%', '+', '−', 'e', '×', '‰', '∞', 'NaN', ':'],
['#,##0.###', '#,##0 %', '#,##0.00 ¤', '#E0'],
'EUR',
'€',
'evro',
{
'AUD': [u, '$'],
'BRL': [u, 'R$'],
'CAD': [u, '$'],
'GBP': [u, '£'],
'MXN': [u, '$'],
'NZD': [u, '$'],
'TWD': [u, 'NT$'],
'XCD': [u, '$']
},
'ltr',
plural,
[
[
['24.00', '12.00', 'zj', 'd', 'p', 'zv', 'po'],
['opoln.', 'opold.', 'zjut.', 'dop.', 'pop.', 'zveč.', 'ponoči'],
['opolnoči', 'opoldne', 'zjutraj', 'dopoldan', 'popoldan', 'zvečer', 'ponoči']
],
[
['24.00', '12.00', 'j', 'd', 'p', 'v', 'n'],
['poln.', 'pold.', 'jut.', 'dop.', 'pop.', 'zveč.', 'noč'],
['polnoč', 'poldne', 'jutro', 'dopoldne', 'popoldne', 'večer', 'noč']
],
[
'00:00', '12:00', ['06:00', '10:00'], ['10:00', '12:00'], ['12:00', '18:00'],
['18:00', '22:00'], ['22:00', '06:00']
]
]
];
})(typeof globalThis !== 'undefined' && globalThis || typeof global !== 'undefined' && global ||
typeof window !== 'undefined' && window);
|
// Copyright 2014 the V8 project authors. All rights reserved.
// AUTO-GENERATED BY tools/generate-runtime-tests.py, DO NOT MODIFY
// Flags: --allow-natives-syntax --harmony --harmony-proxies
var _x = 1.5;
var _y = 1.5;
%MathAtan2(_x, _y);
|
module.exports = {
description: 'single module, no imports or exports'
};
|
"use strict";
/**
* @license
* Copyright 2013 Palantir Technologies, Inc.
*
* 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.
*/
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var tsutils_1 = require("tsutils");
var ts = require("typescript");
var completedDocsRule_1 = require("../completedDocsRule");
var exclusion_1 = require("./exclusion");
var ClassExclusion = /** @class */ (function (_super) {
tslib_1.__extends(ClassExclusion, _super);
function ClassExclusion() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.locations = _this.createSet(_this.descriptor.locations);
_this.privacies = _this.createSet(_this.descriptor.privacies);
return _this;
}
ClassExclusion.prototype.excludes = function (node) {
return !(this.shouldLocationBeDocumented(node)
&& this.shouldPrivacyBeDocumented(node));
};
ClassExclusion.prototype.shouldLocationBeDocumented = function (node) {
if (this.locations.has(completedDocsRule_1.ALL)) {
return true;
}
if (tsutils_1.hasModifier(node.modifiers, ts.SyntaxKind.StaticKeyword)) {
return this.locations.has(completedDocsRule_1.LOCATION_STATIC);
}
return this.locations.has(completedDocsRule_1.LOCATION_INSTANCE);
};
ClassExclusion.prototype.shouldPrivacyBeDocumented = function (node) {
if (this.privacies.has(completedDocsRule_1.ALL)) {
return true;
}
if (tsutils_1.hasModifier(node.modifiers, ts.SyntaxKind.PrivateKeyword)) {
return this.privacies.has(completedDocsRule_1.PRIVACY_PRIVATE);
}
if (tsutils_1.hasModifier(node.modifiers, ts.SyntaxKind.ProtectedKeyword)) {
return this.privacies.has(completedDocsRule_1.PRIVACY_PROTECTED);
}
return this.privacies.has(completedDocsRule_1.PRIVACY_PUBLIC);
};
return ClassExclusion;
}(exclusion_1.Exclusion));
exports.ClassExclusion = ClassExclusion;
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.render = render;
var _reactDom = require('react-dom');
var _reactDom2 = _interopRequireDefault(_reactDom);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Helper method for testing components that may use Portal and thus require cleanup.
* This helper method renders components to a transient node that is destroyed after the test completes.
* Note that rendering twice within the same test method will update the same element (rather than recreate it).
*/
function render(markup) {
if (!render._mountNode) {
render._mountNode = document.createElement('div');
// Unless we attach the mount-node to body, getBoundingClientRect() won't work
document.body.appendChild(render._mountNode);
afterEach(render.unmount);
}
return _reactDom2.default.render(markup, render._mountNode);
}
/**
* The render() method auto-unmounts components after each test has completed.
* Use this method manually to test the componentWillUnmount() lifecycle method.
*/
render.unmount = function () {
if (render._mountNode) {
_reactDom2.default.unmountComponentAtNode(render._mountNode);
document.body.removeChild(render._mountNode);
render._mountNode = null;
}
};
|
'use strict';
const assert = require('./../../assert');
const common = require('./../../common');
let battle;
describe('Unburden', function () {
afterEach(function () {
battle.destroy();
});
it('should trigger when an item is consumed', function () {
battle = common.createBattle();
battle.setPlayer('p1', {team: [{species: 'Hitmonlee', ability: 'unburden', item: 'whiteherb', moves: ['closecombat']}]});
battle.setPlayer('p2', {team: [{species: 'Scizor', ability: 'swarm', item: 'focussash', moves: ['swordsdance']}]});
const target = battle.p1.active[0];
assert.sets(() => target.getStat('spe'), 2 * target.getStat('spe'), () => battle.makeChoices('move closecombat', 'move swordsdance'));
});
it('should trigger when an item is destroyed', function () {
battle = common.createBattle();
battle.setPlayer('p1', {team: [{species: 'Drifblim', ability: 'unburden', item: 'airballoon', moves: ['endure']}]});
battle.setPlayer('p2', {team: [{species: 'Machamp', ability: 'noguard', moves: ['stoneedge']}]});
const target = battle.p1.active[0];
assert.sets(() => target.getStat('spe'), 2 * target.getStat('spe'), () => battle.makeChoices('move endure', 'move stoneedge'));
});
it('should trigger when Natural Gift consumes a berry', function () {
battle = common.createBattle();
battle.setPlayer('p1', {team: [{species: 'Sceptile', ability: 'unburden', item: 'oranberry', moves: ['naturalgift']}]});
battle.setPlayer('p2', {team: [{species: 'Scizor', ability: 'swarm', item: 'focussash', moves: ['swordsdance']}]});
const target = battle.p1.active[0];
assert.sets(() => target.getStat('spe'), 2 * target.getStat('spe'), () => battle.makeChoices('move naturalgift', 'move swordsdance'));
});
it('should trigger when an item is flung', function () {
battle = common.createBattle();
battle.setPlayer('p1', {team: [{species: 'Sceptile', ability: 'unburden', item: 'whiteherb', moves: ['fling']}]});
battle.setPlayer('p2', {team: [{species: 'Scizor', ability: 'swarm', item: 'focussash', moves: ['swordsdance']}]});
const target = battle.p1.active[0];
assert.sets(() => target.getStat('spe'), 2 * target.getStat('spe'), () => battle.makeChoices('move fling', 'move swordsdance'));
});
it('should trigger when an item is forcefully removed', function () {
battle = common.createBattle();
battle.setPlayer('p1', {team: [{species: 'Sceptile', ability: 'unburden', item: 'whiteherb', moves: ['leechseed']}]});
battle.setPlayer('p2', {team: [{species: 'Scizor', ability: 'swarm', moves: ['knockoff']}]});
const target = battle.p1.active[0];
assert.sets(() => target.getStat('spe'), 2 * target.getStat('spe'), () => battle.makeChoices('move leechseed', 'move knockoff'));
});
it('should not be suppressed by Mold Breaker', function () {
battle = common.createBattle();
battle.setPlayer('p1', {team: [{species: 'Sceptile', ability: 'unburden', item: 'whiteherb', moves: ['leechseed']}]});
battle.setPlayer('p2', {team: [{species: 'Scizor', ability: 'moldbreaker', moves: ['knockoff']}]});
const target = battle.p1.active[0];
assert.sets(() => target.getStat('spe'), 2 * target.getStat('spe'), () => battle.makeChoices('move leechseed', 'move knockoff'));
});
it('should lose the boost when it gains a new item', function () {
battle = common.createBattle();
battle.setPlayer('p1', {team: [{species: 'Hitmonlee', ability: 'unburden', item: 'fightinggem', moves: ['machpunch']}]});
battle.setPlayer('p2', {team: [{species: 'Togekiss', ability: 'serenegrace', item: 'laggingtail', moves: ['bestow', 'followme']}]});
const originalSpeed = battle.p1.active[0].getStat('spe');
battle.makeChoices('move machpunch', 'move followme');
assert.equal(battle.p1.active[0].getStat('spe'), 2 * originalSpeed);
battle.makeChoices('move machpunch', 'move bestow');
assert.equal(battle.p1.active[0].getStat('spe'), originalSpeed);
});
});
|
/*
*****************************************************************************
Copyright (c) Microsoft Corporation. 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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
*****************************************************************************/
var $jscomp={scope:{}};$jscomp.defineProperty="function"==typeof Object.defineProperties?Object.defineProperty:function(e,d,k){if(k.get||k.set)throw new TypeError("ES3 does not support getters and setters.");e!=Array.prototype&&e!=Object.prototype&&(e[d]=k.value)};$jscomp.getGlobal=function(e){return"undefined"!=typeof window&&window===e?e:"undefined"!=typeof global&&null!=global?global:e};$jscomp.global=$jscomp.getGlobal(this);
$jscomp.polyfill=function(e,d,k,h){if(d){k=$jscomp.global;e=e.split(".");for(h=0;h<e.length-1;h++){var y=e[h];y in k||(k[y]={});k=k[y]}e=e[e.length-1];h=k[e];d=d(h);d!=h&&null!=d&&$jscomp.defineProperty(k,e,{configurable:!0,writable:!0,value:d})}};$jscomp.polyfill("Object.setPrototypeOf",function(e){return e?e:"object"!=typeof"".__proto__?null:function(d,e){d.__proto__=e;if(d.__proto__!==e)throw new TypeError(d+" is not extensible");return d}},"es6","es5");
$jscomp.owns=function(e,d){return Object.prototype.hasOwnProperty.call(e,d)};$jscomp.polyfill("Object.assign",function(e){return e?e:function(d,e){for(var h=1;h<arguments.length;h++){var k=arguments[h];if(k)for(var n in k)$jscomp.owns(k,n)&&(d[n]=k[n])}return d}},"es6-impl","es3");$jscomp.SYMBOL_PREFIX="jscomp_symbol_";$jscomp.initSymbol=function(){$jscomp.initSymbol=function(){};$jscomp.global.Symbol||($jscomp.global.Symbol=$jscomp.Symbol)};$jscomp.symbolCounter_=0;
$jscomp.Symbol=function(e){return $jscomp.SYMBOL_PREFIX+(e||"")+$jscomp.symbolCounter_++};$jscomp.initSymbolIterator=function(){$jscomp.initSymbol();var e=$jscomp.global.Symbol.iterator;e||(e=$jscomp.global.Symbol.iterator=$jscomp.global.Symbol("iterator"));"function"!=typeof Array.prototype[e]&&$jscomp.defineProperty(Array.prototype,e,{configurable:!0,writable:!0,value:function(){return $jscomp.arrayIterator(this)}});$jscomp.initSymbolIterator=function(){}};
$jscomp.arrayIterator=function(e){var d=0;return $jscomp.iteratorPrototype(function(){return d<e.length?{done:!1,value:e[d++]}:{done:!0}})};$jscomp.iteratorPrototype=function(e){$jscomp.initSymbolIterator();e={next:e};e[$jscomp.global.Symbol.iterator]=function(){return this};return e};$jscomp.makeIterator=function(e){$jscomp.initSymbolIterator();var d=e[Symbol.iterator];return d?d.call(e):$jscomp.arrayIterator(e)};$jscomp.EXPOSE_ASYNC_EXECUTOR=!0;$jscomp.FORCE_POLYFILL_PROMISE=!1;
$jscomp.polyfill("Promise",function(e){function d(){this.batch_=null}if(e&&!$jscomp.FORCE_POLYFILL_PROMISE)return e;d.prototype.asyncExecute=function(d){null==this.batch_&&(this.batch_=[],this.asyncExecuteBatch_());this.batch_.push(d);return this};d.prototype.asyncExecuteBatch_=function(){var d=this;this.asyncExecuteFunction(function(){d.executeBatch_()})};var k=$jscomp.global.setTimeout;d.prototype.asyncExecuteFunction=function(d){k(d,0)};d.prototype.executeBatch_=function(){for(;this.batch_&&this.batch_.length;){var d=
this.batch_;this.batch_=[];for(var e=0;e<d.length;++e){var m=d[e];delete d[e];try{m()}catch(G){this.asyncThrow_(G)}}}this.batch_=null};d.prototype.asyncThrow_=function(d){this.asyncExecuteFunction(function(){throw d;})};var h=function(d){this.state_=0;this.result_=void 0;this.onSettledCallbacks_=[];var e=this.createResolveAndReject_();try{d(e.resolve,e.reject)}catch(m){e.reject(m)}};h.prototype.createResolveAndReject_=function(){function d(d){return function(n){m||(m=!0,d.call(e,n))}}var e=this,m=
!1;return{resolve:d(this.resolveTo_),reject:d(this.reject_)}};h.prototype.resolveTo_=function(d){if(d===this)this.reject_(new TypeError("A Promise cannot resolve to itself"));else if(d instanceof h)this.settleSameAsPromise_(d);else{var e;a:switch(typeof d){case "object":e=null!=d;break a;case "function":e=!0;break a;default:e=!1}e?this.resolveToNonPromiseObj_(d):this.fulfill_(d)}};h.prototype.resolveToNonPromiseObj_=function(d){var e=void 0;try{e=d.then}catch(m){this.reject_(m);return}"function"==
typeof e?this.settleSameAsThenable_(e,d):this.fulfill_(d)};h.prototype.reject_=function(d){this.settle_(2,d)};h.prototype.fulfill_=function(d){this.settle_(1,d)};h.prototype.settle_=function(d,e){if(0!=this.state_)throw Error("Cannot settle("+d+", "+e|"): Promise already settled in state"+this.state_);this.state_=d;this.result_=e;this.executeOnSettledCallbacks_()};h.prototype.executeOnSettledCallbacks_=function(){if(null!=this.onSettledCallbacks_){for(var d=this.onSettledCallbacks_,e=0;e<d.length;++e)d[e].call(),
d[e]=null;this.onSettledCallbacks_=null}};var y=new d;h.prototype.settleSameAsPromise_=function(d){var e=this.createResolveAndReject_();d.callWhenSettled_(e.resolve,e.reject)};h.prototype.settleSameAsThenable_=function(d,e){var m=this.createResolveAndReject_();try{d.call(e,m.resolve,m.reject)}catch(G){m.reject(G)}};h.prototype.then=function(d,e){function m(d,e){return"function"==typeof d?function(e){try{k(d(e))}catch(B){n(B)}}:e}var k,n,O=new h(function(d,e){k=d;n=e});this.callWhenSettled_(m(d,k),
m(e,n));return O};h.prototype.catch=function(d){return this.then(void 0,d)};h.prototype.callWhenSettled_=function(d,e){function m(){switch(h.state_){case 1:d(h.result_);break;case 2:e(h.result_);break;default:throw Error("Unexpected state: "+h.state_);}}var h=this;null==this.onSettledCallbacks_?y.asyncExecute(m):this.onSettledCallbacks_.push(function(){y.asyncExecute(m)})};h.resolve=function(d){return d instanceof h?d:new h(function(e,m){e(d)})};h.reject=function(d){return new h(function(e,m){m(d)})};
h.race=function(d){return new h(function(e,m){for(var k=$jscomp.makeIterator(d),n=k.next();!n.done;n=k.next())h.resolve(n.value).callWhenSettled_(e,m)})};h.all=function(d){var e=$jscomp.makeIterator(d),m=e.next();return m.done?h.resolve([]):new h(function(d,k){function n(e){return function(m){G[e]=m;P--;0==P&&d(G)}}var G=[],P=0;do G.push(void 0),P++,h.resolve(m.value).callWhenSettled_(n(G.length-1),k),m=e.next();while(!m.done)})};$jscomp.EXPOSE_ASYNC_EXECUTOR&&(h.$jscomp$new$AsyncExecutor=function(){return new d});
return h},"es6-impl","es3");
$jscomp.polyfill("WeakMap",function(e){function d(d){$jscomp.owns(d,h)||$jscomp.defineProperty(d,h,{value:{}})}function k(e){var m=Object[e];m&&(Object[e]=function(e){d(e);return m(e)})}if(function(){if(!e||!Object.seal)return!1;try{var d=Object.seal({}),m=Object.seal({}),h=new e([[d,2],[m,3]]);if(2!=h.get(d)||3!=h.get(m))return!1;h.delete(d);h.set(m,4);return!h.has(d)&&4==h.get(m)}catch(P){return!1}}())return e;var h="$jscomp_hidden_"+Math.random().toString().substring(2);k("freeze");k("preventExtensions");
k("seal");var y=0,n=function(d){this.id_=(y+=Math.random()+1).toString();if(d){$jscomp.initSymbol();$jscomp.initSymbolIterator();d=$jscomp.makeIterator(d);for(var e;!(e=d.next()).done;)e=e.value,this.set(e[0],e[1])}};n.prototype.set=function(e,m){d(e);if(!$jscomp.owns(e,h))throw Error("WeakMap key fail: "+e);e[h][this.id_]=m;return this};n.prototype.get=function(d){return $jscomp.owns(d,h)?d[h][this.id_]:void 0};n.prototype.has=function(d){return $jscomp.owns(d,h)&&$jscomp.owns(d[h],this.id_)};n.prototype.delete=
function(d){return $jscomp.owns(d,h)&&$jscomp.owns(d[h],this.id_)?delete d[h][this.id_]:!1};return n},"es6-impl","es3");$jscomp.ASSUME_NO_NATIVE_MAP=!1;
$jscomp.polyfill("Map",function(e){if(!$jscomp.ASSUME_NO_NATIVE_MAP&&function(){if(!e||!e.prototype.entries||"function"!=typeof Object.seal)return!1;try{var d=Object.seal({x:4}),h=new e($jscomp.makeIterator([[d,"s"]]));if("s"!=h.get(d)||1!=h.size||h.get({x:4})||h.set({x:4},"t")!=h||2!=h.size)return!1;var k=h.entries(),n=k.next();if(n.done||n.value[0]!=d||"s"!=n.value[1])return!1;n=k.next();return n.done||4!=n.value[0].x||"t"!=n.value[1]||!k.next().done?!1:!0}catch(la){return!1}}())return e;$jscomp.initSymbol();
$jscomp.initSymbolIterator();var d=new WeakMap,k=function(d){this.data_={};this.head_=n();this.size=0;if(d){d=$jscomp.makeIterator(d);for(var e;!(e=d.next()).done;)e=e.value,this.set(e[0],e[1])}};k.prototype.set=function(d,e){var m=h(this,d);m.list||(m.list=this.data_[m.id]=[]);m.entry?m.entry.value=e:(m.entry={next:this.head_,previous:this.head_.previous,head:this.head_,key:d,value:e},m.list.push(m.entry),this.head_.previous.next=m.entry,this.head_.previous=m.entry,this.size++);return this};k.prototype.delete=
function(d){d=h(this,d);return d.entry&&d.list?(d.list.splice(d.index,1),d.list.length||delete this.data_[d.id],d.entry.previous.next=d.entry.next,d.entry.next.previous=d.entry.previous,d.entry.head=null,this.size--,!0):!1};k.prototype.clear=function(){this.data_={};this.head_=this.head_.previous=n();this.size=0};k.prototype.has=function(d){return!!h(this,d).entry};k.prototype.get=function(d){return(d=h(this,d).entry)&&d.value};k.prototype.entries=function(){return y(this,function(d){return[d.key,
d.value]})};k.prototype.keys=function(){return y(this,function(d){return d.key})};k.prototype.values=function(){return y(this,function(d){return d.value})};k.prototype.forEach=function(d,e){for(var h=this.entries(),k;!(k=h.next()).done;)k=k.value,d.call(e,k[1],k[0],this)};k.prototype[Symbol.iterator]=k.prototype.entries;var h=function(e,h){var k;k=h&&typeof h;"object"==k||"function"==k?d.has(h)?k=d.get(h):(k=""+ ++O,d.set(h,k)):k="p_"+h;var m=e.data_[k];if(m&&$jscomp.owns(e.data_,k))for(e=0;e<m.length;e++){var n=
m[e];if(h!==h&&n.key!==n.key||h===n.key)return{id:k,list:m,index:e,entry:n}}return{id:k,list:m,index:-1,entry:void 0}},y=function(d,e){var h=d.head_;return $jscomp.iteratorPrototype(function(){if(h){for(;h.head!=d.head_;)h=h.previous;for(;h.next!=h.head;)return h=h.next,{done:!1,value:e(h)};h=null}return{done:!0,value:void 0}})},n=function(){var d={};return d.previous=d.next=d.head=d},O=0;return k},"es6-impl","es3");$jscomp.array=$jscomp.array||{};
$jscomp.iteratorFromArray=function(e,d){$jscomp.initSymbolIterator();e instanceof String&&(e+="");var k=0,h={next:function(){if(k<e.length){var y=k++;return{value:d(y,e[y]),done:!1}}h.next=function(){return{done:!0,value:void 0}};return h.next()}};h[Symbol.iterator]=function(){return h};return h};$jscomp.polyfill("Array.prototype.values",function(e){return e?e:function(){return $jscomp.iteratorFromArray(this,function(d,e){return e})}},"es6","es3");
$jscomp.polyfill("Array.prototype.keys",function(e){return e?e:function(){return $jscomp.iteratorFromArray(this,function(d){return d})}},"es6-impl","es3");$jscomp.ASSUME_NO_NATIVE_SET=!1;
$jscomp.polyfill("Set",function(e){if(!$jscomp.ASSUME_NO_NATIVE_SET&&function(){if(!e||!e.prototype.entries||"function"!=typeof Object.seal)return!1;try{var d=Object.seal({x:4}),h=new e($jscomp.makeIterator([d]));if(!h.has(d)||1!=h.size||h.add(d)!=h||1!=h.size||h.add({x:4})!=h||2!=h.size)return!1;var y=h.entries(),n=y.next();if(n.done||n.value[0]!=d||n.value[1]!=d)return!1;n=y.next();return n.done||n.value[0]==d||4!=n.value[0].x||n.value[1]!=n.value[0]?!1:y.next().done}catch(O){return!1}}())return e;
$jscomp.initSymbol();$jscomp.initSymbolIterator();var d=function(d){this.map_=new Map;if(d){d=$jscomp.makeIterator(d);for(var e;!(e=d.next()).done;)this.add(e.value)}this.size=this.map_.size};d.prototype.add=function(d){this.map_.set(d,d);this.size=this.map_.size;return this};d.prototype.delete=function(d){d=this.map_.delete(d);this.size=this.map_.size;return d};d.prototype.clear=function(){this.map_.clear();this.size=0};d.prototype.has=function(d){return this.map_.has(d)};d.prototype.entries=function(){return this.map_.entries()};
d.prototype.values=function(){return this.map_.values()};d.prototype.keys=d.prototype.values;d.prototype[Symbol.iterator]=d.prototype.values;d.prototype.forEach=function(d,e){var h=this;this.map_.forEach(function(k){return d.call(e,k,k,h)})};return d},"es6-impl","es3");
(function(e,d){"object"===typeof exports&&"undefined"!==typeof module?d(exports):"function"===typeof define&&define.amd?define(["exports"],d):d(e.rxjs=e.rxjs||{})})(this,function(e){function d(c,a){function b(){this.constructor=c}Mb(c,a);c.prototype=null===a?Object.create(a):(b.prototype=a.prototype,new b)}function k(c){return"function"===typeof c}function h(c){setTimeout(function(){throw c;})}function y(){try{return La.apply(this,arguments)}catch(c){return q.e=c,q}}function n(c){La=c;return y}function O(c){return c.reduce(function(a,
b){return a.concat(b instanceof ea?b.errors:b)},[])}function m(){}function G(){for(var c=[],a=0;a<arguments.length;a++)c[a]=arguments[a];return P(c)}function P(c){return c?1===c.length?c[0]:function(a){return c.reduce(function(b,a){return a(b)},a)}:m}function Ka(c){c||(c=H.Promise||Promise);if(!c)throw Error("no Promise impl found");return c}function la(){return function(c){return c.lift(new Nb(c))}}function I(c){return c?Lb(c):Q}function Lb(c){return new r(function(a){return c.schedule(function(){return a.complete()})})}
function B(c){return c&&"function"===typeof c.schedule}function J(c,a){return a?new r(function(b){var f=new w,g=0;f.add(a.schedule(function(){g===c.length?b.complete():(b.next(c[g++]),b.closed||f.add(this.schedule()))}));return f}):new r(Ma(c))}function ta(c){var a=new r(function(b){b.next(c);b.complete()});a._isScalar=!0;a.value=c;return a}function ua(){for(var c=[],a=0;a<arguments.length;a++)c[a]=arguments[a];a=c[c.length-1];B(a)?c.pop():a=void 0;switch(c.length){case 0:return I(a);case 1:return a?
J(c,a):ta(c[0]);default:return J(c,a)}}function va(c,a){return a?new r(function(b){return a.schedule(Ob,0,{error:c,subscriber:b})}):new r(function(b){return b.error(c)})}function Ob(c){c.subscriber.error(c.error)}function R(c){return c}function F(c,a){return function(b){if("function"!==typeof c)throw new TypeError("argument is not a function. Are you looking for `mapTo()`?");return b.lift(new Pb(c,a))}}function Na(c,a,b){if(a)if(B(a))b=a;else return function(){for(var f=[],g=0;g<arguments.length;g++)f[g]=
arguments[g];return Na(c,b).apply(void 0,f).pipe(F(function(b){return D(b)?a.apply(void 0,b):a(b)}))};return function(){for(var a=[],g=0;g<arguments.length;g++)a[g]=arguments[g];var l=this,d,e={context:l,subject:d,callbackFunc:c,scheduler:b};return new r(function(f){if(b)return b.schedule(Qb,0,{args:a,subscriber:f,params:e});if(!d){d=new Y;try{c.apply(l,a.concat([function(){for(var b=[],a=0;a<arguments.length;a++)b[a]=arguments[a];d.next(1>=b.length?b[0]:b);d.complete()}]))}catch(xa){d.error(xa)}}return d.subscribe(f)})}}
function Qb(c){var a=this,b=c.args,f=c.subscriber;c=c.params;var g=c.callbackFunc,l=c.context,d=c.scheduler,e=c.subject;if(!e){e=c.subject=new Y;try{g.apply(l,b.concat([function(){for(var b=[],c=0;c<arguments.length;c++)b[c]=arguments[c];a.add(d.schedule(Rb,0,{value:1>=b.length?b[0]:b,subject:e}))}]))}catch(S){e.error(S)}}this.add(e.subscribe(f))}function Rb(c){var a=c.subject;a.next(c.value);a.complete()}function Oa(c,a,b){if(a)if(B(a))b=a;else return function(){for(var f=[],g=0;g<arguments.length;g++)f[g]=
arguments[g];return Oa(c,b).apply(void 0,f).pipe(F(function(b){return D(b)?a.apply(void 0,b):a(b)}))};return function(){for(var a=[],g=0;g<arguments.length;g++)a[g]=arguments[g];var l={subject:void 0,args:a,callbackFunc:c,scheduler:b,context:this};return new r(function(f){var g=l.context,d=l.subject;if(b)return b.schedule(Sb,0,{params:l,subscriber:f,context:g});if(!d){d=l.subject=new Y;try{c.apply(g,a.concat([function(){for(var b=[],a=0;a<arguments.length;a++)b[a]=arguments[a];(a=b.shift())?d.error(a):
(d.next(1>=b.length?b[0]:b),d.complete())}]))}catch(xa){d.error(xa)}}return d.subscribe(f)})}}function Sb(c){var a=this,b=c.params,f=c.subscriber;c=c.context;var g=b.callbackFunc,l=b.args,d=b.scheduler,e=b.subject;if(!e){e=b.subject=new Y;try{g.apply(c,l.concat([function(){for(var b=[],c=0;c<arguments.length;c++)b[c]=arguments[c];(c=b.shift())?a.add(d.schedule(Pa,0,{err:c,subject:e})):a.add(d.schedule(Tb,0,{value:1>=b.length?b[0]:b,subject:e}))}]))}catch(S){this.add(d.schedule(Pa,0,{err:S,subject:e}))}}this.add(e.subscribe(f))}
function Tb(c){var a=c.subject;a.next(c.value);a.complete()}function Pa(c){c.subject.error(c.err)}function Qa(c){return c&&"function"!==typeof c.subscribe&&"function"===typeof c.then}function u(c,a,b,f){c=new Ub(c,b,f);return Ra(a)(c)}function Vb(c,a){return a?new r(function(b){var f=new w;f.add(a.schedule(function(){return c.then(function(c){f.add(a.schedule(function(){b.next(c);f.add(a.schedule(function(){return b.complete()}))}))},function(c){f.add(a.schedule(function(){return b.error(c)}))})}));
return f}):new r(Sa(c))}function Wb(c,a){if(!c)throw Error("Iterable cannot be null");return a?new r(function(b){var f=new w,g;f.add(function(){g&&"function"===typeof g.return&&g.return()});f.add(a.schedule(function(){g=c[K]();f.add(a.schedule(function(){if(!b.closed){var a,c;try{var f=g.next();a=f.value;c=f.done}catch(S){b.error(S);return}c?b.complete():(b.next(a),this.schedule())}}))}));return f}):new r(Ta(c))}function Xb(c,a){return a?new r(function(b){var f=new w;f.add(a.schedule(function(){var g=
c[Z]();f.add(g.subscribe({next:function(c){f.add(a.schedule(function(){return b.next(c)}))},error:function(c){f.add(a.schedule(function(){return b.error(c)}))},complete:function(){f.add(a.schedule(function(){return b.complete()}))}}))}));return f}):new r(Ua(c))}function L(c,a){if(!a)return c instanceof r?c:new r(Ra(c));if(null!=c){if(c&&"function"===typeof c[Z])return Xb(c,a);if(Qa(c))return Vb(c,a);if(Va(c))return J(c,a);if(c&&"function"===typeof c[K]||"string"===typeof c)return Wb(c,a)}throw new TypeError((null!==
c&&typeof c||c)+" is not observable");}function T(c,a,b){void 0===b&&(b=Number.POSITIVE_INFINITY);if("function"===typeof a)return function(f){return f.pipe(T(function(b,f){return L(c(b,f)).pipe(F(function(c,g){return a(b,c,f,g)}))},b))};"number"===typeof a&&(b=a);return function(a){return a.lift(new Yb(c,b))}}function ya(c){void 0===c&&(c=Number.POSITIVE_INFINITY);return T(R,c)}function Wa(){return ya(1)}function M(){for(var c=[],a=0;a<arguments.length;a++)c[a]=arguments[a];return 1===c.length||2===
c.length&&B(c[1])?L(c[0]):Wa()(ua.apply(void 0,c))}function za(c){return new r(function(a){var b;try{b=c()}catch(f){a.error(f);return}return(b?L(b):I()).subscribe(a)})}function Xa(){for(var c=[],a=0;a<arguments.length;a++)c[a]=arguments[a];var b;"function"===typeof c[c.length-1]&&(b=c.pop());1===c.length&&D(c[0])&&(c=c[0]);return 0===c.length?Q:b?Xa(c).pipe(F(function(a){return b.apply(void 0,a)})):new r(function(b){return new Zb(b,c)})}function Ya(c,a,b,f){k(b)&&(f=b,b=void 0);return f?Ya(c,a,b).pipe(F(function(b){return D(b)?
f.apply(void 0,b):f(b)})):new r(function(f){Za(c,a,function(b){1<arguments.length?f.next(Array.prototype.slice.call(arguments)):f.next(b)},f,b)})}function Za(c,a,b,f,g){var l;if(c&&"function"===typeof c.addEventListener&&"function"===typeof c.removeEventListener)c.addEventListener(a,b,g),l=function(){return c.removeEventListener(a,b,g)};else if(c&&"function"===typeof c.on&&"function"===typeof c.off)c.on(a,b),l=function(){return c.off(a,b)};else if(c&&"function"===typeof c.addListener&&"function"===
typeof c.removeListener)c.addListener(a,b),l=function(){return c.removeListener(a,b)};else if(c&&c.length)for(var d=0,e=c.length;d<e;d++)Za(c[d],a,b,f,g);else throw new TypeError("Invalid event target");f.add(l)}function $a(c,a,b){return b?$a(c,a).pipe(F(function(a){return D(a)?b.apply(void 0,a):b(a)})):new r(function(b){var f=function(){for(var a=[],c=0;c<arguments.length;c++)a[c]=arguments[c];return b.next(1===a.length?a[0]:a)},l;try{l=c(f)}catch(x){b.error(x);return}if(k(a))return function(){return a(f,
l)}})}function $b(c){var a=c.subscriber,b=c.condition;if(!a.closed){if(c.needIterate)try{c.state=c.iterate(c.state)}catch(l){a.error(l);return}else c.needIterate=!0;if(b){var f=void 0;try{f=b(c.state)}catch(l){a.error(l);return}if(!f){a.complete();return}if(a.closed)return}var g;try{g=c.resultSelector(c.state)}catch(l){a.error(l);return}if(!a.closed&&(a.next(g),!a.closed))return this.schedule(c)}}function aa(c){return!D(c)&&0<=c-parseFloat(c)+1}function ac(c){var a=c.subscriber,b=c.counter;c=c.period;
a.next(b);this.schedule({subscriber:a,counter:b+1,period:c},c)}function ab(){for(var c=[],a=0;a<arguments.length;a++)c[a]=arguments[a];var a=Number.POSITIVE_INFINITY,b=null,f=c[c.length-1];B(f)?(b=c.pop(),1<c.length&&"number"===typeof c[c.length-1]&&(a=c.pop())):"number"===typeof f&&(a=c.pop());return null===b&&1===c.length&&c[0]instanceof r?c[0]:ya(a)(J(c,b))}function Aa(){for(var c=[],a=0;a<arguments.length;a++)c[a]=arguments[a];if(0===c.length)return Q;var b=c[0],f=c.slice(1);return 1===c.length&&
D(b)?Aa.apply(void 0,b):new r(function(a){var c=function(){return a.add(Aa.apply(void 0,f).subscribe(a))};return L(b).subscribe({next:function(b){a.next(b)},error:c,complete:c})})}function bc(c){var a=c.keys,b=c.index,f=c.subscriber,g=c.subscription;c=c.obj;if(!f.closed)if(b<a.length){var l=a[b];f.next([l,c[l]]);g.add(this.schedule({keys:a,index:b+1,subscriber:f,subscription:g,obj:c}))}else f.complete()}function bb(){for(var c=[],a=0;a<arguments.length;a++)c[a]=arguments[a];if(1===c.length)if(D(c[0]))c=
c[0];else return c[0];return J(c,void 0).lift(new cc)}function dc(c){var a=c.start,b=c.index,f=c.subscriber;b>=c.count?f.complete():(f.next(a),f.closed||(c.index=b+1,c.start=a+1,this.schedule(c)))}function cb(c,a,b){void 0===c&&(c=0);var f=-1;aa(a)?f=1>Number(a)&&1||Number(a):B(a)&&(b=a);B(b)||(b=C);return new r(function(a){var g=aa(c)?c:+c-b.now();return b.schedule(ec,g,{index:0,period:f,subscriber:a})})}function ec(c){var a=c.index,b=c.period,f=c.subscriber;f.next(a);if(!f.closed){if(-1===b)return f.complete();
c.index=a+1;this.schedule(c,b)}}function db(){for(var c=[],a=0;a<arguments.length;a++)c[a]=arguments[a];a=c[c.length-1];"function"===typeof a&&c.pop();return J(c,void 0).lift(new eb(a))}function fb(c){return function(a){return a.lift(new fc(c))}}function gb(c){var a=c.subscriber,b=c.context;b&&a.closeContext(b);a.closed||(c.context=a.openContext(),c.context.closeAction=this.schedule(c,c.bufferTimeSpan))}function gc(c){var a=c.bufferCreationInterval,b=c.bufferTimeSpan,f=c.subscriber,g=c.scheduler,
l=f.openContext();f.closed||(f.add(l.closeAction=g.schedule(hb,b,{subscriber:f,context:l})),this.schedule(c,a))}function hb(c){c.subscriber.closeContext(c.context)}function ib(c,a){return T(c,a,1)}function hc(c){c.debouncedNext()}function fa(c){void 0===c&&(c=null);return function(a){return a.lift(new ic(c))}}function jb(c,a){return function(b){return b.lift(new jc(c,a))}}function ba(c,a){return function(b){return b.lift(new kc(c,a))}}function kb(c,a,b){return function(f){return f.lift(new lc(c,a,
b))}}function mc(){return new ga}function Ba(c){return function(a){return 0===c?I():a.lift(new nc(c))}}function lb(c,a){return a?function(b){return b.pipe(lb(function(b,g){return L(c(b,g)).pipe(F(function(c,f){return a(b,c,g,f)}))}))}:function(b){return b.lift(new oc(c))}}function ma(c){return function(a){return 0===c?I():a.lift(new pc(c))}}function na(c,a){var b=!1;2<=arguments.length&&(b=!0);return function(f){return f.lift(new qc(c,a,b))}}function oa(c,a){return 2<=arguments.length?function(b){return G(na(c,
a),ma(1),fa(a))(b)}:function(b){return G(na(function(b,a,l){return c(b,a,l+1)}),ma(1))(b)}}function U(c,a){return function(b){var f;f="function"===typeof c?c:function(){return c};if("function"===typeof a)return b.lift(new rc(f,a));var g=Object.create(b,sc);g.source=b;g.subjectFactory=f;return g}}function tc(c,a){function b(){return!b.pred.apply(b.thisArg,arguments)}b.pred=c;b.thisArg=a;return b}function uc(c,a){return function(b){var f=b;for(b=0;b<a;b++)if(f=f[c[b]],"undefined"===typeof f)return;
return f}}function vc(c){var a=c.period;c.subscriber.notifyNext();this.schedule(c,a)}function wc(){return new z}function xc(c,a,b){var f,g=0,l,d=!1,e=!1;return function(x){g++;if(!f||d)d=!1,f=new V(c,a,b),l=x.subscribe({next:function(b){f.next(b)},error:function(b){d=!0;f.error(b)},complete:function(){e=!0;f.complete()}});var h=f.subscribe(this);return function(){g--;h.unsubscribe();l&&0===g&&e&&l.unsubscribe()}}}function ha(c,a){return"function"===typeof a?function(b){return b.pipe(ha(function(b,
g){return L(c(b,g)).pipe(F(function(c,f){return a(b,c,g,f)}))}))}:function(b){return b.lift(new yc(c))}}function zc(c){c.subscriber.clearThrottle()}function mb(c,a,b){void 0===b&&(b=C);return function(f){var g=c instanceof Date&&!isNaN(+c),l=g?+c-b.now():Math.abs(c);return f.lift(new Ac(l,g,a,b))}}function Bc(c,a,b){if(0===b)return[a];c.push(a);return c}function Cc(c){var a=c.subscriber,b=c.windowTimeSpan,f=c.window;f&&a.closeWindow(f);c.window=a.openWindow();this.schedule(c,b)}function Dc(c){var a=
c.windowTimeSpan,b=c.subscriber,f=c.scheduler,g=c.windowCreationInterval,l=b.openWindow(),d={action:this,subscription:null};d.subscription=f.schedule(nb,a,{subscriber:b,window:l,context:d});this.add(d.subscription);this.schedule(c,g)}function nb(c){var a=c.subscriber,b=c.window;(c=c.context)&&c.action&&c.subscription&&c.action.remove(c.subscription);a.closeWindow(b)}function ob(c,a){for(var b=0,f=a.length;b<f;b++)for(var g=a[b],l=Object.getOwnPropertyNames(g.prototype),d=0,e=l.length;d<e;d++){var h=
l[d];c.prototype[h]=g.prototype[h]}}function Ec(c,a){void 0===a&&(a=null);return new W({method:"GET",url:c,headers:a})}function Fc(c,a,b){return new W({method:"POST",url:c,body:a,headers:b})}function Gc(c,a){return new W({method:"DELETE",url:c,headers:a})}function Hc(c,a,b){return new W({method:"PUT",url:c,body:a,headers:b})}function Ic(c,a,b){return new W({method:"PATCH",url:c,body:a,headers:b})}function Jc(c,a){return Kc(new W({method:"GET",url:c,responseType:"json",headers:a}))}function pb(c,a){switch(c){case "json":return"response"in
a?a.responseType?a.response:JSON.parse(a.response||a.responseText||"null"):JSON.parse(a.responseText||"null");case "xml":return a.responseXML;default:return"response"in a?a.response:a.responseText}}var Mb=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(c,a){c.__proto__=a}||function(c,a){for(var b in a)a.hasOwnProperty(b)&&(c[b]=a[b])},Lc=Object.assign||function(c){for(var a,b=1,f=arguments.length;b<f;b++){a=arguments[b];for(var g in a)Object.prototype.hasOwnProperty.call(a,g)&&(c[g]=
a[g])}return c},Ca=!1,H={Promise:void 0,set useDeprecatedSynchronousErrorHandling(c){c?console.warn("DEPRECATED! RxJS was set to use deprecated synchronous error handling behavior by code at: \n"+Error().stack):Ca&&console.log("RxJS: Back to a better error behavior. Thank you. \x3c3");Ca=c},get useDeprecatedSynchronousErrorHandling(){return Ca}},pa={closed:!0,next:function(c){},error:function(c){if(H.useDeprecatedSynchronousErrorHandling)throw c;h(c)},complete:function(){}},D=Array.isArray||function(c){return c&&
"number"===typeof c.length},q={e:{}},La,ea=function(c){function a(b){var f=c.call(this,b?b.length+" errors occurred during unsubscription:\n "+b.map(function(b,a){return a+1+") "+b.toString()}).join("\n "):"")||this;f.errors=b;f.name="UnsubscriptionError";Object.setPrototypeOf(f,a.prototype);return f}d(a,c);return a}(Error),w=function(){function c(a){this.closed=!1;this._subscriptions=this._parents=this._parent=null;a&&(this._unsubscribe=a)}c.prototype.unsubscribe=function(){var a=!1,b;if(!this.closed){var c=
this._parent,g=this._parents,l=this._unsubscribe,d=this._subscriptions;this.closed=!0;this._subscriptions=this._parents=this._parent=null;for(var e=-1,h=g?g.length:0;c;)c.remove(this),c=++e<h&&g[e]||null;k(l)&&(c=n(l).call(this),c===q&&(a=!0,b=b||(q.e instanceof ea?O(q.e.errors):[q.e])));if(D(d))for(e=-1,h=d.length;++e<h;)c=d[e],null!=c&&"object"===typeof c&&(c=n(c.unsubscribe).call(c),c===q&&(a=!0,b=b||[],c=q.e,c instanceof ea?b=b.concat(O(c.errors)):b.push(c)));if(a)throw new ea(b);}};c.prototype.add=
function(a){if(!a||a===c.EMPTY)return c.EMPTY;if(a===this)return this;var b=a;switch(typeof a){case "function":b=new c(a);case "object":if(b.closed||"function"!==typeof b.unsubscribe)return b;if(this.closed)return b.unsubscribe(),b;"function"!==typeof b._addParent&&(a=b,b=new c,b._subscriptions=[a]);break;default:throw Error("unrecognized teardown "+a+" added to Subscription.");}(this._subscriptions||(this._subscriptions=[])).push(b);b._addParent(this);return b};c.prototype.remove=function(a){var b=
this._subscriptions;b&&(a=b.indexOf(a),-1!==a&&b.splice(a,1))};c.prototype._addParent=function(a){var b=this._parent,c=this._parents;b&&b!==a?c?-1===c.indexOf(a)&&c.push(a):this._parents=[a]:this._parent=a};c.EMPTY=function(a){a.closed=!0;return a}(new c);return c}(),ca="function"===typeof Symbol&&"function"===typeof Symbol.for?Symbol.for("rxSubscriber"):"@@rxSubscriber",p=function(c){function a(b,a,g){var f=c.call(this)||this;f.syncErrorValue=null;f.syncErrorThrown=!1;f.syncErrorThrowable=!1;f.isStopped=
!1;switch(arguments.length){case 0:f.destination=pa;break;case 1:if(!b){f.destination=pa;break}if("object"===typeof b){if(b instanceof p||"syncErrorThrowable"in b&&b[ca]){var d=b[ca]();f.syncErrorThrowable=d.syncErrorThrowable;f.destination=d;d.add(f)}else f.syncErrorThrowable=!0,f.destination=new qb(f,b);break}default:f.syncErrorThrowable=!0,f.destination=new qb(f,b,a,g)}return f}d(a,c);a.prototype[ca]=function(){return this};a.create=function(b,c,g){b=new a(b,c,g);b.syncErrorThrowable=!1;return b};
a.prototype.next=function(b){this.isStopped||this._next(b)};a.prototype.error=function(b){this.isStopped||(this.isStopped=!0,this._error(b))};a.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())};a.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,c.prototype.unsubscribe.call(this))};a.prototype._next=function(b){this.destination.next(b)};a.prototype._error=function(b){this.destination.error(b);this.unsubscribe()};a.prototype._complete=function(){this.destination.complete();
this.unsubscribe()};a.prototype._unsubscribeAndRecycle=function(){var b=this._parent,a=this._parents;this._parents=this._parent=null;this.unsubscribe();this.isStopped=this.closed=!1;this._parent=b;this._parents=a;return this};return a}(w),qb=function(c){function a(b,a,g,l){var f=c.call(this)||this;f._parentSubscriber=b;var d;b=f;k(a)?d=a:a&&(d=a.next,g=a.error,l=a.complete,a!==pa&&(b=Object.create(a),k(b.unsubscribe)&&f.add(b.unsubscribe.bind(b)),b.unsubscribe=f.unsubscribe.bind(f)));f._context=b;
f._next=d;f._error=g;f._complete=l;return f}d(a,c);a.prototype.next=function(b){if(!this.isStopped&&this._next){var a=this._parentSubscriber;H.useDeprecatedSynchronousErrorHandling&&a.syncErrorThrowable?this.__tryOrSetError(a,this._next,b)&&this.unsubscribe():this.__tryOrUnsub(this._next,b)}};a.prototype.error=function(b){if(!this.isStopped){var a=this._parentSubscriber,c=H.useDeprecatedSynchronousErrorHandling;if(this._error)c&&a.syncErrorThrowable?this.__tryOrSetError(a,this._error,b):this.__tryOrUnsub(this._error,
b),this.unsubscribe();else if(a.syncErrorThrowable)c?(a.syncErrorValue=b,a.syncErrorThrown=!0):h(b),this.unsubscribe();else{this.unsubscribe();if(c)throw b;h(b)}}};a.prototype.complete=function(){var b=this;if(!this.isStopped){var a=this._parentSubscriber;if(this._complete){var c=function(){return b._complete.call(b._context)};H.useDeprecatedSynchronousErrorHandling&&a.syncErrorThrowable?this.__tryOrSetError(a,c):this.__tryOrUnsub(c)}this.unsubscribe()}};a.prototype.__tryOrUnsub=function(b,a){try{b.call(this._context,
a)}catch(g){this.unsubscribe();if(H.useDeprecatedSynchronousErrorHandling)throw g;h(g)}};a.prototype.__tryOrSetError=function(b,a,c){if(!H.useDeprecatedSynchronousErrorHandling)throw Error("bad call");try{a.call(this._context,c)}catch(l){return H.useDeprecatedSynchronousErrorHandling?(b.syncErrorValue=l,b.syncErrorThrown=!0):h(l),!0}return!1};a.prototype._unsubscribe=function(){var b=this._parentSubscriber;this._parentSubscriber=this._context=null;b.unsubscribe()};return a}(p),Z="function"===typeof Symbol&&
Symbol.observable||"@@observable",r=function(){function c(a){this._isScalar=!1;a&&(this._subscribe=a)}c.prototype.lift=function(a){var b=new c;b.source=this;b.operator=a;return b};c.prototype.subscribe=function(a,b,c){var f=this.operator;a:{if(a){if(a instanceof p)break a;if(a[ca]){a=a[ca]();break a}}a=a||b||c?new p(a,b,c):new p(pa)}f?f.call(a,this.source):a.add(this.source||H.useDeprecatedSynchronousErrorHandling&&!a.syncErrorThrowable?this._subscribe(a):this._trySubscribe(a));if(H.useDeprecatedSynchronousErrorHandling&&
a.syncErrorThrowable&&(a.syncErrorThrowable=!1,a.syncErrorThrown))throw a.syncErrorValue;return a};c.prototype._trySubscribe=function(a){try{return this._subscribe(a)}catch(b){H.useDeprecatedSynchronousErrorHandling&&(a.syncErrorThrown=!0,a.syncErrorValue=b),a.error(b)}};c.prototype.forEach=function(a,b){var c=this;b=Ka(b);return new b(function(b,f){var g;g=c.subscribe(function(b){try{a(b)}catch(S){f(S),g&&g.unsubscribe()}},f,b)})};c.prototype._subscribe=function(a){var b=this.source;return b&&b.subscribe(a)};
c.prototype[Z]=function(){return this};c.prototype.pipe=function(){for(var a=[],b=0;b<arguments.length;b++)a[b]=arguments[b];return 0===a.length?this:P(a)(this)};c.prototype.toPromise=function(a){var b=this;a=Ka(a);return new a(function(a,c){var f;b.subscribe(function(b){return f=b},function(b){return c(b)},function(){return a(f)})})};c.create=function(a){return new c(a)};return c}(),N=function(c){function a(){var b=c.call(this,"object unsubscribed")||this;b.name="ObjectUnsubscribedError";Object.setPrototypeOf(b,
a.prototype);return b}d(a,c);return a}(Error),rb=function(c){function a(b,a){var f=c.call(this)||this;f.subject=b;f.subscriber=a;f.closed=!1;return f}d(a,c);a.prototype.unsubscribe=function(){if(!this.closed){this.closed=!0;var b=this.subject,a=b.observers;this.subject=null;!a||0===a.length||b.isStopped||b.closed||(b=a.indexOf(this.subscriber),-1!==b&&a.splice(b,1))}};return a}(w),sb=function(c){function a(b){var a=c.call(this,b)||this;a.destination=b;return a}d(a,c);return a}(p),z=function(c){function a(){var b=
c.call(this)||this;b.observers=[];b.closed=!1;b.isStopped=!1;b.hasError=!1;b.thrownError=null;return b}d(a,c);a.prototype[ca]=function(){return new sb(this)};a.prototype.lift=function(b){var a=new Da(this,this);a.operator=b;return a};a.prototype.next=function(b){if(this.closed)throw new N;if(!this.isStopped)for(var a=this.observers,c=a.length,a=a.slice(),l=0;l<c;l++)a[l].next(b)};a.prototype.error=function(b){if(this.closed)throw new N;this.hasError=!0;this.thrownError=b;this.isStopped=!0;for(var a=
this.observers,c=a.length,a=a.slice(),l=0;l<c;l++)a[l].error(b);this.observers.length=0};a.prototype.complete=function(){if(this.closed)throw new N;this.isStopped=!0;for(var b=this.observers,a=b.length,b=b.slice(),c=0;c<a;c++)b[c].complete();this.observers.length=0};a.prototype.unsubscribe=function(){this.closed=this.isStopped=!0;this.observers=null};a.prototype._trySubscribe=function(b){if(this.closed)throw new N;return c.prototype._trySubscribe.call(this,b)};a.prototype._subscribe=function(b){if(this.closed)throw new N;
if(this.hasError)return b.error(this.thrownError),w.EMPTY;if(this.isStopped)return b.complete(),w.EMPTY;this.observers.push(b);return new rb(this,b)};a.prototype.asObservable=function(){var b=new r;b.source=this;return b};a.create=function(b,a){return new Da(b,a)};return a}(r),Da=function(c){function a(b,a){var f=c.call(this)||this;f.destination=b;f.source=a;return f}d(a,c);a.prototype.next=function(b){var a=this.destination;a&&a.next&&a.next(b)};a.prototype.error=function(b){var a=this.destination;
a&&a.error&&this.destination.error(b)};a.prototype.complete=function(){var b=this.destination;b&&b.complete&&this.destination.complete()};a.prototype._subscribe=function(b){return this.source?this.source.subscribe(b):w.EMPTY};return a}(z),Nb=function(){function c(a){this.connectable=a}c.prototype.call=function(a,b){var c=this.connectable;c._refCount++;a=new Mc(a,c);b=b.subscribe(a);a.closed||(a.connection=c.connect());return b};return c}(),Mc=function(c){function a(b,a){b=c.call(this,b)||this;b.connectable=
a;return b}d(a,c);a.prototype._unsubscribe=function(){var b=this.connectable;if(b){this.connectable=null;var a=b._refCount;0>=a?this.connection=null:(b._refCount=a-1,1<a?this.connection=null:(a=this.connection,b=b._connection,this.connection=null,!b||a&&b!==a||b.unsubscribe()))}else this.connection=null};return a}(p),tb=function(c){function a(b,a){var f=c.call(this)||this;f.source=b;f.subjectFactory=a;f._refCount=0;f._isComplete=!1;return f}d(a,c);a.prototype._subscribe=function(b){return this.getSubject().subscribe(b)};
a.prototype.getSubject=function(){var b=this._subject;if(!b||b.isStopped)this._subject=this.subjectFactory();return this._subject};a.prototype.connect=function(){var b=this._connection;b||(this._isComplete=!1,b=this._connection=new w,b.add(this.source.subscribe(new Nc(this.getSubject(),this))),b.closed?(this._connection=null,b=w.EMPTY):this._connection=b);return b};a.prototype.refCount=function(){return la()(this)};return a}(r),ia=tb.prototype,sc={operator:{value:null},_refCount:{value:0,writable:!0},
_subject:{value:null,writable:!0},_connection:{value:null,writable:!0},_subscribe:{value:ia._subscribe},_isComplete:{value:ia._isComplete,writable:!0},getSubject:{value:ia.getSubject},connect:{value:ia.connect},refCount:{value:ia.refCount}},Nc=function(c){function a(b,a){b=c.call(this,b)||this;b.connectable=a;return b}d(a,c);a.prototype._error=function(b){this._unsubscribe();c.prototype._error.call(this,b)};a.prototype._complete=function(){this.connectable._isComplete=!0;this._unsubscribe();c.prototype._complete.call(this)};
a.prototype._unsubscribe=function(){var b=this.connectable;if(b){this.connectable=null;var a=b._connection;b._refCount=0;b._subject=null;b._connection=null;a&&a.unsubscribe()}};return a}(sb);(function(c){function a(b,a){b=c.call(this,b)||this;b.connectable=a;return b}d(a,c);a.prototype._unsubscribe=function(){var b=this.connectable;if(b){this.connectable=null;var a=b._refCount;0>=a?this.connection=null:(b._refCount=a-1,1<a?this.connection=null:(a=this.connection,b=b._connection,this.connection=null,
!b||a&&b!==a||b.unsubscribe()))}else this.connection=null};return a})(p);var Pc=function(){function c(a,b,c,g){this.keySelector=a;this.elementSelector=b;this.durationSelector=c;this.subjectSelector=g}c.prototype.call=function(a,b){return b.subscribe(new Oc(a,this.keySelector,this.elementSelector,this.durationSelector,this.subjectSelector))};return c}(),Oc=function(c){function a(b,a,g,l,d){b=c.call(this,b)||this;b.keySelector=a;b.elementSelector=g;b.durationSelector=l;b.subjectSelector=d;b.groups=
null;b.attemptedToUnsubscribe=!1;b.count=0;return b}d(a,c);a.prototype._next=function(b){var a;try{a=this.keySelector(b)}catch(g){this.error(g);return}this._group(b,a)};a.prototype._group=function(b,a){var c=this.groups;c||(c=this.groups=new Map);var f=c.get(a),d;if(this.elementSelector)try{d=this.elementSelector(b)}catch(wa){this.error(wa)}else d=b;if(!f&&(f=this.subjectSelector?this.subjectSelector():new z,c.set(a,f),b=new Ea(a,f,this),this.destination.next(b),this.durationSelector)){b=void 0;try{b=
this.durationSelector(new Ea(a,f))}catch(wa){this.error(wa);return}this.add(b.subscribe(new Qc(a,f,this)))}f.closed||f.next(d)};a.prototype._error=function(b){var a=this.groups;a&&(a.forEach(function(a,c){a.error(b)}),a.clear());this.destination.error(b)};a.prototype._complete=function(){var b=this.groups;b&&(b.forEach(function(b,a){b.complete()}),b.clear());this.destination.complete()};a.prototype.removeGroup=function(b){this.groups.delete(b)};a.prototype.unsubscribe=function(){this.closed||(this.attemptedToUnsubscribe=
!0,0===this.count&&c.prototype.unsubscribe.call(this))};return a}(p),Qc=function(c){function a(b,a,g){var f=c.call(this,a)||this;f.key=b;f.group=a;f.parent=g;return f}d(a,c);a.prototype._next=function(b){this.complete()};a.prototype._unsubscribe=function(){var b=this.parent,a=this.key;this.key=this.parent=null;b&&b.removeGroup(a)};return a}(p),Ea=function(c){function a(b,a,g){var f=c.call(this)||this;f.key=b;f.groupSubject=a;f.refCountSubscription=g;return f}d(a,c);a.prototype._subscribe=function(b){var a=
new w,c=this.refCountSubscription,l=this.groupSubject;c&&!c.closed&&a.add(new Rc(c));a.add(l.subscribe(b));return a};return a}(r),Rc=function(c){function a(b){var a=c.call(this)||this;a.parent=b;b.count++;return a}d(a,c);a.prototype.unsubscribe=function(){var b=this.parent;b.closed||this.closed||(c.prototype.unsubscribe.call(this),--b.count,0===b.count&&b.attemptedToUnsubscribe&&b.unsubscribe())};return a}(w),ub=function(c){function a(b){var a=c.call(this)||this;a._value=b;return a}d(a,c);Object.defineProperty(a.prototype,
"value",{get:function(){return this.getValue()},enumerable:!0,configurable:!0});a.prototype._subscribe=function(b){var a=c.prototype._subscribe.call(this,b);a&&!a.closed&&b.next(this._value);return a};a.prototype.getValue=function(){if(this.hasError)throw this.thrownError;if(this.closed)throw new N;return this._value};a.prototype.next=function(b){c.prototype.next.call(this,this._value=b)};return a}(z),ja=function(c){function a(b,a){var f=c.call(this,b,a)||this;f.scheduler=b;f.work=a;f.pending=!1;
return f}d(a,c);a.prototype.schedule=function(b,a){void 0===a&&(a=0);if(this.closed)return this;this.state=b;b=this.id;var c=this.scheduler;null!=b&&(this.id=this.recycleAsyncId(c,b,a));this.pending=!0;this.delay=a;this.id=this.id||this.requestAsyncId(c,this.id,a);return this};a.prototype.requestAsyncId=function(b,a,c){void 0===c&&(c=0);return setInterval(b.flush.bind(b,this),c)};a.prototype.recycleAsyncId=function(b,a,c){void 0===c&&(c=0);return null!==c&&this.delay===c&&!1===this.pending?a:(clearInterval(a),
void 0)};a.prototype.execute=function(b,a){if(this.closed)return Error("executing a cancelled action");this.pending=!1;if(b=this._execute(b,a))return b;!1===this.pending&&null!=this.id&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))};a.prototype._execute=function(b,a){a=!1;var c=void 0;try{this.work(b)}catch(l){a=!0,c=!!l&&l||Error(l)}if(a)return this.unsubscribe(),c};a.prototype._unsubscribe=function(){var b=this.id,a=this.scheduler,c=a.actions,l=c.indexOf(this);this.state=this.work=
null;this.pending=!1;this.scheduler=null;-1!==l&&c.splice(l,1);null!=b&&(this.id=this.recycleAsyncId(a,b,null));this.delay=null};return a}(function(c){function a(b,a){return c.call(this)||this}d(a,c);a.prototype.schedule=function(b,a){return this};return a}(w)),Sc=function(c){function a(b,a){var f=c.call(this,b,a)||this;f.scheduler=b;f.work=a;return f}d(a,c);a.prototype.schedule=function(b,a){void 0===a&&(a=0);if(0<a)return c.prototype.schedule.call(this,b,a);this.delay=a;this.state=b;this.scheduler.flush(this);
return this};a.prototype.execute=function(b,a){return 0<a||this.closed?c.prototype.execute.call(this,b,a):this._execute(b,a)};a.prototype.requestAsyncId=function(b,a,g){void 0===g&&(g=0);return null!==g&&0<g||null===g&&0<this.delay?c.prototype.requestAsyncId.call(this,b,a,g):b.flush(this)};return a}(ja),Fa=function(){function c(a,b){void 0===b&&(b=c.now);this.SchedulerAction=a;this.now=b}c.prototype.schedule=function(a,b,c){void 0===b&&(b=0);return(new this.SchedulerAction(this,a)).schedule(c,b)};
c.now=function(){return Date.now()};return c}(),X=function(c){function a(b,f){void 0===f&&(f=Fa.now);var g=c.call(this,b,function(){return a.delegate&&a.delegate!==g?a.delegate.now():f()})||this;g.actions=[];g.active=!1;g.scheduled=void 0;return g}d(a,c);a.prototype.schedule=function(b,f,g){void 0===f&&(f=0);return a.delegate&&a.delegate!==this?a.delegate.schedule(b,f,g):c.prototype.schedule.call(this,b,f,g)};a.prototype.flush=function(b){var a=this.actions;if(this.active)a.push(b);else{var c;this.active=
!0;do if(c=b.execute(b.state,b.delay))break;while(b=a.shift());this.active=!1;if(c){for(;b=a.shift();)b.unsubscribe();throw c;}}};return a}(Fa),vb=new (function(c){function a(){return null!==c&&c.apply(this,arguments)||this}d(a,c);return a}(X))(Sc),Q=new r(function(c){return c.complete()}),Ma=function(c){return function(a){for(var b=0,f=c.length;b<f&&!a.closed;b++)a.next(c[b]);a.closed||a.complete()}},A=function(){function c(a,b,c){this.kind=a;this.value=b;this.error=c;this.hasValue="N"===a}c.prototype.observe=
function(a){switch(this.kind){case "N":return a.next&&a.next(this.value);case "E":return a.error&&a.error(this.error);case "C":return a.complete&&a.complete()}};c.prototype.do=function(a,b,c){switch(this.kind){case "N":return a&&a(this.value);case "E":return b&&b(this.error);case "C":return c&&c()}};c.prototype.accept=function(a,b,c){return a&&"function"===typeof a.next?this.observe(a):this.do(a,b,c)};c.prototype.toObservable=function(){switch(this.kind){case "N":return ua(this.value);case "E":return va(this.error);
case "C":return I()}throw Error("unexpected notification kind value");};c.createNext=function(a){return"undefined"!==typeof a?new c("N",a):c.undefinedValueNotification};c.createError=function(a){return new c("E",void 0,a)};c.createComplete=function(){return c.completeNotification};c.completeNotification=new c("C");c.undefinedValueNotification=new c("N",void 0);return c}(),Tc=function(){function c(a,b){void 0===b&&(b=0);this.scheduler=a;this.delay=b}c.prototype.call=function(a,b){return b.subscribe(new wb(a,
this.scheduler,this.delay))};return c}(),wb=function(c){function a(b,a,g){void 0===g&&(g=0);b=c.call(this,b)||this;b.scheduler=a;b.delay=g;return b}d(a,c);a.dispatch=function(b){b.notification.observe(b.destination);this.unsubscribe()};a.prototype.scheduleMessage=function(b){this.add(this.scheduler.schedule(a.dispatch,this.delay,new Uc(b,this.destination)))};a.prototype._next=function(b){this.scheduleMessage(A.createNext(b))};a.prototype._error=function(b){this.scheduleMessage(A.createError(b))};
a.prototype._complete=function(){this.scheduleMessage(A.createComplete())};return a}(p),Uc=function(){return function(c,a){this.notification=c;this.destination=a}}(),V=function(c){function a(b,a,g){void 0===b&&(b=Number.POSITIVE_INFINITY);void 0===a&&(a=Number.POSITIVE_INFINITY);var f=c.call(this)||this;f.scheduler=g;f._events=[];f._infiniteTimeWindow=!1;f._bufferSize=1>b?1:b;f._windowTime=1>a?1:a;a===Number.POSITIVE_INFINITY?(f._infiniteTimeWindow=!0,f.next=f.nextInfiniteTimeWindow):f.next=f.nextTimeWindow;
return f}d(a,c);a.prototype.nextInfiniteTimeWindow=function(b){var a=this._events;a.push(b);a.length>this._bufferSize&&a.shift();c.prototype.next.call(this,b)};a.prototype.nextTimeWindow=function(b){this._events.push(new Vc(this._getNow(),b));this._trimBufferThenGetEvents();c.prototype.next.call(this,b)};a.prototype._subscribe=function(b){var a=this._infiniteTimeWindow,c=a?this._events:this._trimBufferThenGetEvents(),l=this.scheduler,d=c.length,e;if(this.closed)throw new N;this.isStopped||this.hasError?
e=w.EMPTY:(this.observers.push(b),e=new rb(this,b));l&&b.add(b=new wb(b,l));if(a)for(a=0;a<d&&!b.closed;a++)b.next(c[a]);else for(a=0;a<d&&!b.closed;a++)b.next(c[a].value);this.hasError?b.error(this.thrownError):this.isStopped&&b.complete();return e};a.prototype._getNow=function(){return(this.scheduler||vb).now()};a.prototype._trimBufferThenGetEvents=function(){for(var b=this._getNow(),a=this._bufferSize,c=this._windowTime,l=this._events,d=l.length,e=0;e<d&&!(b-l[e].time<c);)e++;d>a&&(e=Math.max(e,
d-a));0<e&&l.splice(0,e);return l};return a}(z),Vc=function(){return function(c,a){this.time=c;this.value=a}}(),Y=function(c){function a(){var b=null!==c&&c.apply(this,arguments)||this;b.value=null;b.hasNext=!1;b.hasCompleted=!1;return b}d(a,c);a.prototype._subscribe=function(b){return this.hasError?(b.error(this.thrownError),w.EMPTY):this.hasCompleted&&this.hasNext?(b.next(this.value),b.complete(),w.EMPTY):c.prototype._subscribe.call(this,b)};a.prototype.next=function(b){this.hasCompleted||(this.value=
b,this.hasNext=!0)};a.prototype.error=function(b){this.hasCompleted||c.prototype.error.call(this,b)};a.prototype.complete=function(){this.hasCompleted=!0;this.hasNext&&c.prototype.next.call(this,this.value);c.prototype.complete.call(this)};return a}(z),Wc=1,Ga={},xb={setImmediate:function(c){var a=Wc++;Ga[a]=c;Promise.resolve().then(function(){var b=Ga[a];b&&b()});return a},clearImmediate:function(c){delete Ga[c]}},Xc=function(c){function a(b,a){var f=c.call(this,b,a)||this;f.scheduler=b;f.work=a;
return f}d(a,c);a.prototype.requestAsyncId=function(b,a,g){void 0===g&&(g=0);if(null!==g&&0<g)return c.prototype.requestAsyncId.call(this,b,a,g);b.actions.push(this);return b.scheduled||(b.scheduled=xb.setImmediate(b.flush.bind(b,null)))};a.prototype.recycleAsyncId=function(b,a,g){void 0===g&&(g=0);if(null!==g&&0<g||null===g&&0<this.delay)return c.prototype.recycleAsyncId.call(this,b,a,g);0===b.actions.length&&(xb.clearImmediate(a),b.scheduled=void 0)};return a}(ja),qa=new (function(c){function a(){return null!==
c&&c.apply(this,arguments)||this}d(a,c);a.prototype.flush=function(b){this.active=!0;this.scheduled=void 0;var a=this.actions,c,l=-1,d=a.length;b=b||a.shift();do if(c=b.execute(b.state,b.delay))break;while(++l<d&&(b=a.shift()));this.active=!1;if(c){for(;++l<d&&(b=a.shift());)b.unsubscribe();throw c;}};return a}(X))(Xc),C=new X(ja),Yc=function(c){function a(b,a){var f=c.call(this,b,a)||this;f.scheduler=b;f.work=a;return f}d(a,c);a.prototype.requestAsyncId=function(b,a,g){void 0===g&&(g=0);if(null!==
g&&0<g)return c.prototype.requestAsyncId.call(this,b,a,g);b.actions.push(this);return b.scheduled||(b.scheduled=requestAnimationFrame(function(){return b.flush(null)}))};a.prototype.recycleAsyncId=function(b,a,g){void 0===g&&(g=0);if(null!==g&&0<g||null===g&&0<this.delay)return c.prototype.recycleAsyncId.call(this,b,a,g);0===b.actions.length&&(cancelAnimationFrame(a),b.scheduled=void 0)};return a}(ja),Zc=new (function(c){function a(){return null!==c&&c.apply(this,arguments)||this}d(a,c);a.prototype.flush=
function(b){this.active=!0;this.scheduled=void 0;var a=this.actions,c,l=-1,d=a.length;b=b||a.shift();do if(c=b.execute(b.state,b.delay))break;while(++l<d&&(b=a.shift()));this.active=!1;if(c){for(;++l<d&&(b=a.shift());)b.unsubscribe();throw c;}};return a}(X))(Yc),yb=function(c){function a(b,a){void 0===b&&(b=Ha);void 0===a&&(a=Number.POSITIVE_INFINITY);var f=c.call(this,b,function(){return f.frame})||this;f.maxFrames=a;f.frame=0;f.index=-1;return f}d(a,c);a.prototype.flush=function(){for(var b=this.actions,
a=this.maxFrames,c,l;(l=b.shift())&&(this.frame=l.delay)<=a&&!(c=l.execute(l.state,l.delay)););if(c){for(;l=b.shift();)l.unsubscribe();throw c;}};a.frameTimeFactor=10;return a}(X),Ha=function(c){function a(b,a,g){void 0===g&&(g=b.index+=1);var f=c.call(this,b,a)||this;f.scheduler=b;f.work=a;f.index=g;f.active=!0;f.index=b.index=g;return f}d(a,c);a.prototype.schedule=function(b,f){void 0===f&&(f=0);if(!this.id)return c.prototype.schedule.call(this,b,f);this.active=!1;var g=new a(this.scheduler,this.work);
this.add(g);return g.schedule(b,f)};a.prototype.requestAsyncId=function(b,c,g){void 0===g&&(g=0);this.delay=b.frame+g;b=b.actions;b.push(this);b.sort(a.sortActions);return!0};a.prototype.recycleAsyncId=function(b,a,c){};a.prototype._execute=function(b,a){if(!0===this.active)return c.prototype._execute.call(this,b,a)};a.sortActions=function(b,a){return b.delay===a.delay?b.index===a.index?0:b.index>a.index?1:-1:b.delay>a.delay?1:-1};return a}(ja),da=function(c){function a(){var b=c.call(this,"argument out of range")||
this;b.name="ArgumentOutOfRangeError";Object.setPrototypeOf(b,a.prototype);return b}d(a,c);return a}(Error),ga=function(c){function a(){var b=c.call(this,"no elements in sequence")||this;b.name="EmptyError";Object.setPrototypeOf(b,a.prototype);return b}d(a,c);return a}(Error),zb=function(c){function a(){var b=c.call(this,"Timeout has occurred")||this;b.name="TimeoutError";Object.setPrototypeOf(b,a.prototype);return b}d(a,c);return a}(Error),Pb=function(){function c(a,b){this.project=a;this.thisArg=
b}c.prototype.call=function(a,b){return b.subscribe(new $c(a,this.project,this.thisArg))};return c}(),$c=function(c){function a(b,a,g){b=c.call(this,b)||this;b.project=a;b.count=0;b.thisArg=g||b;return b}d(a,c);a.prototype._next=function(b){var a;try{a=this.project.call(this.thisArg,b,this.count++)}catch(g){this.destination.error(g);return}this.destination.next(a)};return a}(p),v=function(c){function a(){return null!==c&&c.apply(this,arguments)||this}d(a,c);a.prototype.notifyNext=function(b,a,c,l,
d){this.destination.next(a)};a.prototype.notifyError=function(b,a){this.destination.error(b)};a.prototype.notifyComplete=function(b){this.destination.complete()};return a}(p),Ub=function(c){function a(b,a,g){var f=c.call(this)||this;f.parent=b;f.outerValue=a;f.outerIndex=g;f.index=0;return f}d(a,c);a.prototype._next=function(b){this.parent.notifyNext(this.outerValue,b,this.outerIndex,this.index++,this)};a.prototype._error=function(b){this.parent.notifyError(b,this);this.unsubscribe()};a.prototype._complete=
function(){this.parent.notifyComplete(this);this.unsubscribe()};return a}(p),Sa=function(c){return function(a){c.then(function(b){a.closed||(a.next(b),a.complete())},function(b){return a.error(b)}).then(null,h);return a}},K;K="function"===typeof Symbol&&Symbol.iterator?Symbol.iterator:"@@iterator";var Ta=function(c){return function(a){var b=c[K]();do{var f=b.next();if(f.done){a.complete();break}a.next(f.value);if(a.closed)break}while(1);"function"===typeof b.return&&a.add(function(){b.return&&b.return()});
return a}},Ua=function(c){return function(a){var b=c[Z]();if("function"!==typeof b.subscribe)throw new TypeError("Provided object does not correctly implement Symbol.observable");return b.subscribe(a)}},Va=function(c){return c&&"number"===typeof c.length&&"function"!==typeof c},Ra=function(c){if(c instanceof r)return function(a){if(c._isScalar)a.next(c.value),a.complete();else return c.subscribe(a)};if(c&&"function"===typeof c[Z])return Ua(c);if(Va(c))return Ma(c);if(Qa(c))return Sa(c);if(c&&"function"===
typeof c[K])return Ta(c);throw new TypeError("You provided "+(null!=c&&"object"===typeof c?"an invalid object":"'"+c+"'")+" where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.");},Ab={},Ia=function(){function c(a){this.resultSelector=a}c.prototype.call=function(a,b){return b.subscribe(new ad(a,this.resultSelector))};return c}(),ad=function(c){function a(b,a){b=c.call(this,b)||this;b.resultSelector=a;b.active=0;b.values=[];b.observables=[];return b}d(a,c);a.prototype._next=
function(b){this.values.push(Ab);this.observables.push(b)};a.prototype._complete=function(){var b=this.observables,a=b.length;if(0===a)this.destination.complete();else{this.toRespond=this.active=a;for(var c=0;c<a;c++){var d=b[c];this.add(u(this,d,d,c))}}};a.prototype.notifyComplete=function(b){0===--this.active&&this.destination.complete()};a.prototype.notifyNext=function(b,a,c,d,e){b=this.values;d=b[c];d=this.toRespond?d===Ab?--this.toRespond:this.toRespond:0;b[c]=a;0===d&&(this.resultSelector?this._tryResultSelector(b):
this.destination.next(b.slice()))};a.prototype._tryResultSelector=function(b){var a;try{a=this.resultSelector.apply(this,b)}catch(g){this.destination.error(g);return}this.destination.next(a)};return a}(v),Yb=function(){function c(a,b){void 0===b&&(b=Number.POSITIVE_INFINITY);this.project=a;this.concurrent=b}c.prototype.call=function(a,b){return b.subscribe(new bd(a,this.project,this.concurrent))};return c}(),bd=function(c){function a(b,a,g){void 0===g&&(g=Number.POSITIVE_INFINITY);b=c.call(this,b)||
this;b.project=a;b.concurrent=g;b.hasCompleted=!1;b.buffer=[];b.active=0;b.index=0;return b}d(a,c);a.prototype._next=function(b){this.active<this.concurrent?this._tryNext(b):this.buffer.push(b)};a.prototype._tryNext=function(b){var a,c=this.index++;try{a=this.project(b,c)}catch(l){this.destination.error(l);return}this.active++;this._innerSub(a,b,c)};a.prototype._innerSub=function(b,a,c){this.add(u(this,b,a,c))};a.prototype._complete=function(){this.hasCompleted=!0;0===this.active&&0===this.buffer.length&&
this.destination.complete()};a.prototype.notifyNext=function(b,a,c,d,e){this.destination.next(a)};a.prototype.notifyComplete=function(b){var a=this.buffer;this.remove(b);this.active--;0<a.length?this._next(a.shift()):0===this.active&&this.hasCompleted&&this.destination.complete()};return a}(v),Zb=function(c){function a(b,a){b=c.call(this,b)||this;b.sources=a;b.completed=0;b.haveValues=0;var f=a.length;b.values=Array(f);for(var d=0;d<f;d++){var e=u(b,a[d],null,d);e&&b.add(e)}return b}d(a,c);a.prototype.notifyNext=
function(b,a,c,d,e){this.values[c]=a;e._hasValue||(e._hasValue=!0,this.haveValues++)};a.prototype.notifyComplete=function(b){var a=this.destination,c=this.haveValues,d=this.values,e=d.length;b._hasValue?(this.completed++,this.completed===e&&(c===e&&a.next(d),a.complete())):a.complete()};return a}(v),Bb=new r(m),cc=function(){function c(){}c.prototype.call=function(a,b){return b.subscribe(new cd(a))};return c}(),cd=function(c){function a(b){b=c.call(this,b)||this;b.hasFirst=!1;b.observables=[];b.subscriptions=
[];return b}d(a,c);a.prototype._next=function(b){this.observables.push(b)};a.prototype._complete=function(){var b=this.observables,a=b.length;if(0===a)this.destination.complete();else{for(var c=0;c<a&&!this.hasFirst;c++){var d=b[c],d=u(this,d,d,c);this.subscriptions&&this.subscriptions.push(d);this.add(d)}this.observables=null}};a.prototype.notifyNext=function(b,a,c,d,e){if(!this.hasFirst){this.hasFirst=!0;for(b=0;b<this.subscriptions.length;b++)b!==c&&(d=this.subscriptions[b],d.unsubscribe(),this.remove(d));
this.subscriptions=null}this.destination.next(a)};return a}(v),eb=function(){function c(a){this.resultSelector=a}c.prototype.call=function(a,b){return b.subscribe(new dd(a,this.resultSelector))};return c}(),dd=function(c){function a(b,a,g){void 0===g&&(g=Object.create(null));b=c.call(this,b)||this;b.iterators=[];b.active=0;b.resultSelector="function"===typeof a?a:null;b.values=g;return b}d(a,c);a.prototype._next=function(b){var a=this.iterators;D(b)?a.push(new ed(b)):"function"===typeof b[K]?a.push(new fd(b[K]())):
a.push(new gd(this.destination,this,b))};a.prototype._complete=function(){var b=this.iterators,a=b.length;if(0===a)this.destination.complete();else{this.active=a;for(var c=0;c<a;c++){var d=b[c];d.stillUnsubscribed?this.add(d.subscribe(d,c)):this.active--}}};a.prototype.notifyInactive=function(){this.active--;0===this.active&&this.destination.complete()};a.prototype.checkIterators=function(){for(var b=this.iterators,a=b.length,c=this.destination,d=0;d<a;d++){var e=b[d];if("function"===typeof e.hasValue&&
!e.hasValue())return}for(var h=!1,k=[],d=0;d<a;d++){var e=b[d],n=e.next();e.hasCompleted()&&(h=!0);if(n.done){c.complete();return}k.push(n.value)}this.resultSelector?this._tryresultSelector(k):c.next(k);h&&c.complete()};a.prototype._tryresultSelector=function(b){var a;try{a=this.resultSelector.apply(this,b)}catch(g){this.destination.error(g);return}this.destination.next(a)};return a}(p),fd=function(){function c(a){this.iterator=a;this.nextResult=a.next()}c.prototype.hasValue=function(){return!0};
c.prototype.next=function(){var a=this.nextResult;this.nextResult=this.iterator.next();return a};c.prototype.hasCompleted=function(){var a=this.nextResult;return a&&a.done};return c}(),ed=function(){function c(a){this.array=a;this.length=this.index=0;this.length=a.length}c.prototype[K]=function(){return this};c.prototype.next=function(a){a=this.index++;var b=this.array;return a<this.length?{value:b[a],done:!1}:{value:null,done:!0}};c.prototype.hasValue=function(){return this.array.length>this.index};
c.prototype.hasCompleted=function(){return this.array.length===this.index};return c}(),gd=function(c){function a(b,a,g){b=c.call(this,b)||this;b.parent=a;b.observable=g;b.stillUnsubscribed=!0;b.buffer=[];b.isComplete=!1;return b}d(a,c);a.prototype[K]=function(){return this};a.prototype.next=function(){var b=this.buffer;return 0===b.length&&this.isComplete?{value:null,done:!0}:{value:b.shift(),done:!1}};a.prototype.hasValue=function(){return 0<this.buffer.length};a.prototype.hasCompleted=function(){return 0===
this.buffer.length&&this.isComplete};a.prototype.notifyComplete=function(){0<this.buffer.length?(this.isComplete=!0,this.parent.notifyInactive()):this.destination.complete()};a.prototype.notifyNext=function(b,a,c,d,e){this.buffer.push(a);this.parent.checkIterators()};a.prototype.subscribe=function(b,a){return u(this,this.observable,this,a)};return a}(v),fc=function(){function c(a){this.durationSelector=a}c.prototype.call=function(a,b){return b.subscribe(new hd(a,this.durationSelector))};return c}(),
hd=function(c){function a(b,a){b=c.call(this,b)||this;b.durationSelector=a;b.hasValue=!1;return b}d(a,c);a.prototype._next=function(b){this.value=b;this.hasValue=!0;this.throttled||(b=n(this.durationSelector)(b),b===q?this.destination.error(q.e):(b=u(this,b),!b||b.closed?this.clearThrottle():this.add(this.throttled=b)))};a.prototype.clearThrottle=function(){var b=this.value,a=this.hasValue,c=this.throttled;c&&(this.remove(c),this.throttled=null,c.unsubscribe());a&&(this.value=null,this.hasValue=!1,
this.destination.next(b))};a.prototype.notifyNext=function(b,a,c,d){this.clearThrottle()};a.prototype.notifyComplete=function(){this.clearThrottle()};return a}(v),jd=function(){function c(a){this.closingNotifier=a}c.prototype.call=function(a,b){return b.subscribe(new id(a,this.closingNotifier))};return c}(),id=function(c){function a(b,a){b=c.call(this,b)||this;b.buffer=[];b.add(u(b,a));return b}d(a,c);a.prototype._next=function(b){this.buffer.push(b)};a.prototype.notifyNext=function(b,a,c,d,e){b=
this.buffer;this.buffer=[];this.destination.next(b)};return a}(v),md=function(){function c(a,b){this.bufferSize=a;this.subscriberClass=(this.startBufferEvery=b)&&a!==b?kd:ld}c.prototype.call=function(a,b){return b.subscribe(new this.subscriberClass(a,this.bufferSize,this.startBufferEvery))};return c}(),ld=function(c){function a(b,a){b=c.call(this,b)||this;b.bufferSize=a;b.buffer=[];return b}d(a,c);a.prototype._next=function(b){var a=this.buffer;a.push(b);a.length==this.bufferSize&&(this.destination.next(a),
this.buffer=[])};a.prototype._complete=function(){var b=this.buffer;0<b.length&&this.destination.next(b);c.prototype._complete.call(this)};return a}(p),kd=function(c){function a(b,a,g){b=c.call(this,b)||this;b.bufferSize=a;b.startBufferEvery=g;b.buffers=[];b.count=0;return b}d(a,c);a.prototype._next=function(b){var a=this.bufferSize,c=this.startBufferEvery,d=this.buffers,e=this.count;this.count++;0===e%c&&d.push([]);for(c=d.length;c--;)e=d[c],e.push(b),e.length===a&&(d.splice(c,1),this.destination.next(e))};
a.prototype._complete=function(){for(var b=this.buffers,a=this.destination;0<b.length;){var g=b.shift();0<g.length&&a.next(g)}c.prototype._complete.call(this)};return a}(p),od=function(){function c(a,b,c,g){this.bufferTimeSpan=a;this.bufferCreationInterval=b;this.maxBufferSize=c;this.scheduler=g}c.prototype.call=function(a,b){return b.subscribe(new nd(a,this.bufferTimeSpan,this.bufferCreationInterval,this.maxBufferSize,this.scheduler))};return c}(),pd=function(){return function(){this.buffer=[]}}(),
nd=function(c){function a(b,a,g,d,e){b=c.call(this,b)||this;b.bufferTimeSpan=a;b.bufferCreationInterval=g;b.maxBufferSize=d;b.scheduler=e;b.contexts=[];d=b.openContext();b.timespanOnly=null==g||0>g;if(b.timespanOnly)b.add(d.closeAction=e.schedule(gb,a,{subscriber:b,context:d,bufferTimeSpan:a}));else{var f={bufferTimeSpan:a,bufferCreationInterval:g,subscriber:b,scheduler:e};b.add(d.closeAction=e.schedule(hb,a,{subscriber:b,context:d}));b.add(e.schedule(gc,g,f))}return b}d(a,c);a.prototype._next=function(b){for(var a=
this.contexts,c=a.length,d,e=0;e<c;e++){var h=a[e],k=h.buffer;k.push(b);k.length==this.maxBufferSize&&(d=h)}if(d)this.onBufferFull(d)};a.prototype._error=function(b){this.contexts.length=0;c.prototype._error.call(this,b)};a.prototype._complete=function(){for(var b=this.contexts,a=this.destination;0<b.length;){var g=b.shift();a.next(g.buffer)}c.prototype._complete.call(this)};a.prototype._unsubscribe=function(){this.contexts=null};a.prototype.onBufferFull=function(b){this.closeContext(b);b=b.closeAction;
b.unsubscribe();this.remove(b);if(!this.closed&&this.timespanOnly){b=this.openContext();var a=this.bufferTimeSpan;this.add(b.closeAction=this.scheduler.schedule(gb,a,{subscriber:this,context:b,bufferTimeSpan:a}))}};a.prototype.openContext=function(){var b=new pd;this.contexts.push(b);return b};a.prototype.closeContext=function(b){this.destination.next(b.buffer);var a=this.contexts;0<=(a?a.indexOf(b):-1)&&a.splice(a.indexOf(b),1)};return a}(p),rd=function(){function c(a,b){this.openings=a;this.closingSelector=
b}c.prototype.call=function(a,b){return b.subscribe(new qd(a,this.openings,this.closingSelector))};return c}(),qd=function(c){function a(b,a,g){b=c.call(this,b)||this;b.openings=a;b.closingSelector=g;b.contexts=[];b.add(u(b,a));return b}d(a,c);a.prototype._next=function(b){for(var a=this.contexts,c=a.length,d=0;d<c;d++)a[d].buffer.push(b)};a.prototype._error=function(b){for(var a=this.contexts;0<a.length;){var g=a.shift();g.subscription.unsubscribe();g.buffer=null;g.subscription=null}this.contexts=
null;c.prototype._error.call(this,b)};a.prototype._complete=function(){for(var b=this.contexts;0<b.length;){var a=b.shift();this.destination.next(a.buffer);a.subscription.unsubscribe();a.buffer=null;a.subscription=null}this.contexts=null;c.prototype._complete.call(this)};a.prototype.notifyNext=function(b,a,c,d,e){b?this.closeBuffer(b):this.openBuffer(a)};a.prototype.notifyComplete=function(b){this.closeBuffer(b.context)};a.prototype.openBuffer=function(b){try{var a=this.closingSelector.call(this,
b);a&&this.trySubscribe(a)}catch(g){this._error(g)}};a.prototype.closeBuffer=function(b){var a=this.contexts;if(a&&b){var c=b.subscription;this.destination.next(b.buffer);a.splice(a.indexOf(b),1);this.remove(c);c.unsubscribe()}};a.prototype.trySubscribe=function(b){var a=this.contexts,c=new w,d={buffer:[],subscription:c};a.push(d);b=u(this,b,d);!b||b.closed?this.closeBuffer(d):(b.context=d,this.add(b),c.add(b))};return a}(v),td=function(){function c(a){this.closingSelector=a}c.prototype.call=function(a,
b){return b.subscribe(new sd(a,this.closingSelector))};return c}(),sd=function(c){function a(b,a){b=c.call(this,b)||this;b.closingSelector=a;b.subscribing=!1;b.openBuffer();return b}d(a,c);a.prototype._next=function(b){this.buffer.push(b)};a.prototype._complete=function(){var b=this.buffer;b&&this.destination.next(b);c.prototype._complete.call(this)};a.prototype._unsubscribe=function(){this.buffer=null;this.subscribing=!1};a.prototype.notifyNext=function(b,a,c,d,e){this.openBuffer()};a.prototype.notifyComplete=
function(){this.subscribing?this.complete():this.openBuffer()};a.prototype.openBuffer=function(){var b=this.closingSubscription;b&&(this.remove(b),b.unsubscribe());(b=this.buffer)&&this.destination.next(b);this.buffer=[];var a=n(this.closingSelector)();a===q?this.error(q.e):(this.closingSubscription=b=new w,this.add(b),this.subscribing=!0,b.add(u(this,a)),this.subscribing=!1)};return a}(v),vd=function(){function c(a){this.selector=a}c.prototype.call=function(a,b){return b.subscribe(new ud(a,this.selector,
this.caught))};return c}(),ud=function(c){function a(b,a,g){b=c.call(this,b)||this;b.selector=a;b.caught=g;return b}d(a,c);a.prototype.error=function(b){if(!this.isStopped){var a=void 0;try{a=this.selector(b,this.caught)}catch(g){c.prototype.error.call(this,g);return}this._unsubscribeAndRecycle();this.add(u(this,a))}};return a}(v),xd=function(){function c(a,b){this.predicate=a;this.source=b}c.prototype.call=function(a,b){return b.subscribe(new wd(a,this.predicate,this.source))};return c}(),wd=function(c){function a(b,
a,g){b=c.call(this,b)||this;b.predicate=a;b.source=g;b.count=0;b.index=0;return b}d(a,c);a.prototype._next=function(b){this.predicate?this._tryPredicate(b):this.count++};a.prototype._tryPredicate=function(b){var a;try{a=this.predicate(b,this.index++,this.source)}catch(g){this.destination.error(g);return}a&&this.count++};a.prototype._complete=function(){this.destination.next(this.count);this.destination.complete()};return a}(p),zd=function(){function c(a){this.durationSelector=a}c.prototype.call=function(a,
b){return b.subscribe(new yd(a,this.durationSelector))};return c}(),yd=function(c){function a(b,a){b=c.call(this,b)||this;b.durationSelector=a;b.hasValue=!1;b.durationSubscription=null;return b}d(a,c);a.prototype._next=function(b){try{var a=this.durationSelector.call(this,b);a&&this._tryNext(b,a)}catch(g){this.destination.error(g)}};a.prototype._complete=function(){this.emitValue();this.destination.complete()};a.prototype._tryNext=function(b,a){var c=this.durationSubscription;this.value=b;this.hasValue=
!0;c&&(c.unsubscribe(),this.remove(c));(c=u(this,a))&&!c.closed&&this.add(this.durationSubscription=c)};a.prototype.notifyNext=function(b,a,c,d,e){this.emitValue()};a.prototype.notifyComplete=function(){this.emitValue()};a.prototype.emitValue=function(){if(this.hasValue){var b=this.value,a=this.durationSubscription;a&&(this.durationSubscription=null,a.unsubscribe(),this.remove(a));this.value=null;this.hasValue=!1;c.prototype._next.call(this,b)}};return a}(v),Bd=function(){function c(a,b){this.dueTime=
a;this.scheduler=b}c.prototype.call=function(a,b){return b.subscribe(new Ad(a,this.dueTime,this.scheduler))};return c}(),Ad=function(c){function a(b,a,g){b=c.call(this,b)||this;b.dueTime=a;b.scheduler=g;b.debouncedSubscription=null;b.lastValue=null;b.hasValue=!1;return b}d(a,c);a.prototype._next=function(b){this.clearDebounce();this.lastValue=b;this.hasValue=!0;this.add(this.debouncedSubscription=this.scheduler.schedule(hc,this.dueTime,this))};a.prototype._complete=function(){this.debouncedNext();
this.destination.complete()};a.prototype.debouncedNext=function(){this.clearDebounce();if(this.hasValue){var b=this.lastValue;this.lastValue=null;this.hasValue=!1;this.destination.next(b)}};a.prototype.clearDebounce=function(){var b=this.debouncedSubscription;null!==b&&(this.remove(b),b.unsubscribe(),this.debouncedSubscription=null)};return a}(p),ic=function(){function c(a){this.defaultValue=a}c.prototype.call=function(a,b){return b.subscribe(new Cd(a,this.defaultValue))};return c}(),Cd=function(c){function a(b,
a){b=c.call(this,b)||this;b.defaultValue=a;b.isEmpty=!0;return b}d(a,c);a.prototype._next=function(b){this.isEmpty=!1;this.destination.next(b)};a.prototype._complete=function(){this.isEmpty&&this.destination.next(this.defaultValue);this.destination.complete()};return a}(p),Ed=function(){function c(a,b){this.delay=a;this.scheduler=b}c.prototype.call=function(a,b){return b.subscribe(new Dd(a,this.delay,this.scheduler))};return c}(),Dd=function(c){function a(b,a,g){b=c.call(this,b)||this;b.delay=a;b.scheduler=
g;b.queue=[];b.active=!1;b.errored=!1;return b}d(a,c);a.dispatch=function(b){for(var a=b.source,c=a.queue,d=b.scheduler,e=b.destination;0<c.length&&0>=c[0].time-d.now();)c.shift().notification.observe(e);0<c.length?(a=Math.max(0,c[0].time-d.now()),this.schedule(b,a)):(this.unsubscribe(),a.active=!1)};a.prototype._schedule=function(b){this.active=!0;this.add(b.schedule(a.dispatch,this.delay,{source:this,destination:this.destination,scheduler:b}))};a.prototype.scheduleNotification=function(b){if(!0!==
this.errored){var a=this.scheduler;b=new Fd(a.now()+this.delay,b);this.queue.push(b);!1===this.active&&this._schedule(a)}};a.prototype._next=function(b){this.scheduleNotification(A.createNext(b))};a.prototype._error=function(b){this.errored=!0;this.queue=[];this.destination.error(b)};a.prototype._complete=function(){this.scheduleNotification(A.createComplete())};return a}(p),Fd=function(){return function(c,a){this.time=c;this.notification=a}}(),Cb=function(){function c(a){this.delayDurationSelector=
a}c.prototype.call=function(a,b){return b.subscribe(new Gd(a,this.delayDurationSelector))};return c}(),Gd=function(c){function a(b,a){b=c.call(this,b)||this;b.delayDurationSelector=a;b.completed=!1;b.delayNotifierSubscriptions=[];return b}d(a,c);a.prototype.notifyNext=function(b,a,c,d,e){this.destination.next(b);this.removeSubscription(e);this.tryComplete()};a.prototype.notifyError=function(b,a){this._error(b)};a.prototype.notifyComplete=function(b){(b=this.removeSubscription(b))&&this.destination.next(b);
this.tryComplete()};a.prototype._next=function(b){try{var a=this.delayDurationSelector(b);a&&this.tryDelay(a,b)}catch(g){this.destination.error(g)}};a.prototype._complete=function(){this.completed=!0;this.tryComplete()};a.prototype.removeSubscription=function(b){b.unsubscribe();var a=this.delayNotifierSubscriptions.indexOf(b);-1!==a&&this.delayNotifierSubscriptions.splice(a,1);return b.outerValue};a.prototype.tryDelay=function(b,a){(b=u(this,b,a))&&!b.closed&&(this.add(b),this.delayNotifierSubscriptions.push(b))};
a.prototype.tryComplete=function(){this.completed&&0===this.delayNotifierSubscriptions.length&&this.destination.complete()};return a}(v),Id=function(c){function a(b,a){var f=c.call(this)||this;f.source=b;f.subscriptionDelay=a;return f}d(a,c);a.prototype._subscribe=function(b){this.subscriptionDelay.subscribe(new Hd(b,this.source))};return a}(r),Hd=function(c){function a(b,a){var f=c.call(this)||this;f.parent=b;f.source=a;f.sourceSubscribed=!1;return f}d(a,c);a.prototype._next=function(b){this.subscribeToSource()};
a.prototype._error=function(b){this.unsubscribe();this.parent.error(b)};a.prototype._complete=function(){this.subscribeToSource()};a.prototype.subscribeToSource=function(){this.sourceSubscribed||(this.sourceSubscribed=!0,this.unsubscribe(),this.source.subscribe(this.parent))};return a}(p),Kd=function(){function c(){}c.prototype.call=function(a,b){return b.subscribe(new Jd(a))};return c}(),Jd=function(c){function a(b){return c.call(this,b)||this}d(a,c);a.prototype._next=function(b){b.observe(this.destination)};
return a}(p),Md=function(){function c(a,b){this.keySelector=a;this.flushes=b}c.prototype.call=function(a,b){return b.subscribe(new Ld(a,this.keySelector,this.flushes))};return c}(),Ld=function(c){function a(b,a,g){b=c.call(this,b)||this;b.keySelector=a;b.values=new Set;g&&b.add(u(b,g));return b}d(a,c);a.prototype.notifyNext=function(b,a,c,d,e){this.values.clear()};a.prototype.notifyError=function(b,a){this._error(b)};a.prototype._next=function(b){this.keySelector?this._useKeySelector(b):this._finalizeNext(b,
b)};a.prototype._useKeySelector=function(b){var a,c=this.destination;try{a=this.keySelector(b)}catch(l){c.error(l);return}this._finalizeNext(a,b)};a.prototype._finalizeNext=function(b,a){var c=this.values;c.has(b)||(c.add(b),this.destination.next(a))};return a}(v),jc=function(){function c(a,b){this.compare=a;this.keySelector=b}c.prototype.call=function(a,b){return b.subscribe(new Nd(a,this.compare,this.keySelector))};return c}(),Nd=function(c){function a(b,a,g){b=c.call(this,b)||this;b.keySelector=
g;b.hasKey=!1;"function"===typeof a&&(b.compare=a);return b}d(a,c);a.prototype.compare=function(b,a){return b===a};a.prototype._next=function(b){var a=b;if(this.keySelector&&(a=n(this.keySelector)(b),a===q))return this.destination.error(q.e);var c=!1;if(this.hasKey){if(c=n(this.compare)(this.key,a),c===q)return this.destination.error(q.e)}else this.hasKey=!0;!1===!!c&&(this.key=a,this.destination.next(b))};return a}(p),kc=function(){function c(a,b){this.predicate=a;this.thisArg=b}c.prototype.call=
function(a,b){return b.subscribe(new Od(a,this.predicate,this.thisArg))};return c}(),Od=function(c){function a(b,a,g){b=c.call(this,b)||this;b.predicate=a;b.thisArg=g;b.count=0;return b}d(a,c);a.prototype._next=function(b){var a;try{a=this.predicate.call(this.thisArg,b,this.count++)}catch(g){this.destination.error(g);return}a&&this.destination.next(b)};return a}(p),lc=function(){function c(a,b,c){this.nextOrObserver=a;this.error=b;this.complete=c}c.prototype.call=function(a,b){return b.subscribe(new Pd(a,
this.nextOrObserver,this.error,this.complete))};return c}(),Pd=function(c){function a(b,a,g,d){b=c.call(this,b)||this;b._tapNext=m;b._tapError=m;b._tapComplete=m;b._tapError=g||m;b._tapComplete=d||m;k(a)?(b._context=b,b._tapNext=a):a&&(b._context=a,b._tapNext=a.next||m,b._tapError=a.error||m,b._tapComplete=a.complete||m);return b}d(a,c);a.prototype._next=function(b){try{this._tapNext.call(this._context,b)}catch(f){this.destination.error(f);return}this.destination.next(b)};a.prototype._error=function(b){try{this._tapError.call(this._context,
b)}catch(f){this.destination.error(f);return}this.destination.error(b)};a.prototype._complete=function(){try{this._tapComplete.call(this._context)}catch(b){this.destination.error(b);return}return this.destination.complete()};return a}(p),ra=function(c){void 0===c&&(c=mc);return kb({hasValue:!1,next:function(){this.hasValue=!0},complete:function(){if(!this.hasValue)throw c();}})},nc=function(){function c(a){this.total=a;if(0>this.total)throw new da;}c.prototype.call=function(a,b){return b.subscribe(new Qd(a,
this.total))};return c}(),Qd=function(c){function a(b,a){b=c.call(this,b)||this;b.total=a;b.count=0;return b}d(a,c);a.prototype._next=function(b){var a=this.total,c=++this.count;c<=a&&(this.destination.next(b),c===a&&(this.destination.complete(),this.unsubscribe()))};return a}(p),Sd=function(){function c(a,b,c){this.predicate=a;this.thisArg=b;this.source=c}c.prototype.call=function(a,b){return b.subscribe(new Rd(a,this.predicate,this.thisArg,this.source))};return c}(),Rd=function(c){function a(b,
a,g,d){b=c.call(this,b)||this;b.predicate=a;b.thisArg=g;b.source=d;b.index=0;b.thisArg=g||b;return b}d(a,c);a.prototype.notifyComplete=function(b){this.destination.next(b);this.destination.complete()};a.prototype._next=function(b){var a=!1;try{a=this.predicate.call(this.thisArg,b,this.index++,this.source)}catch(g){this.destination.error(g);return}a||this.notifyComplete(!1)};a.prototype._complete=function(){this.notifyComplete(!0)};return a}(p),Ud=function(){function c(){}c.prototype.call=function(a,
b){return b.subscribe(new Td(a))};return c}(),Td=function(c){function a(b){b=c.call(this,b)||this;b.hasCompleted=!1;b.hasSubscription=!1;return b}d(a,c);a.prototype._next=function(b){this.hasSubscription||(this.hasSubscription=!0,this.add(u(this,b)))};a.prototype._complete=function(){this.hasCompleted=!0;this.hasSubscription||this.destination.complete()};a.prototype.notifyComplete=function(b){this.remove(b);this.hasSubscription=!1;this.hasCompleted&&this.destination.complete()};return a}(v),oc=function(){function c(a){this.project=
a}c.prototype.call=function(a,b){return b.subscribe(new Vd(a,this.project))};return c}(),Vd=function(c){function a(b,a){b=c.call(this,b)||this;b.project=a;b.hasSubscription=!1;b.hasCompleted=!1;b.index=0;return b}d(a,c);a.prototype._next=function(b){this.hasSubscription||this.tryNext(b)};a.prototype.tryNext=function(b){var a=this.index++,c=this.destination;try{var d=this.project(b,a);this.hasSubscription=!0;this.add(u(this,d,b,a))}catch(x){c.error(x)}};a.prototype._complete=function(){this.hasCompleted=
!0;this.hasSubscription||this.destination.complete()};a.prototype.notifyNext=function(b,a,c,d,e){this.destination.next(a)};a.prototype.notifyError=function(b){this.destination.error(b)};a.prototype.notifyComplete=function(b){this.remove(b);this.hasSubscription=!1;this.hasCompleted&&this.destination.complete()};return a}(v),Xd=function(){function c(a,b,c){this.project=a;this.concurrent=b;this.scheduler=c}c.prototype.call=function(a,b){return b.subscribe(new Wd(a,this.project,this.concurrent,this.scheduler))};
return c}(),Wd=function(c){function a(b,a,g,d){b=c.call(this,b)||this;b.project=a;b.concurrent=g;b.scheduler=d;b.index=0;b.active=0;b.hasCompleted=!1;g<Number.POSITIVE_INFINITY&&(b.buffer=[]);return b}d(a,c);a.dispatch=function(b){b.subscriber.subscribeToProjection(b.result,b.value,b.index)};a.prototype._next=function(b){var c=this.destination;if(c.closed)this._complete();else{var g=this.index++;if(this.active<this.concurrent){c.next(b);var d=n(this.project)(b,g);d===q?c.error(q.e):this.scheduler?
this.add(this.scheduler.schedule(a.dispatch,0,{subscriber:this,result:d,value:b,index:g})):this.subscribeToProjection(d,b,g)}else this.buffer.push(b)}};a.prototype.subscribeToProjection=function(b,a,c){this.active++;this.add(u(this,b,a,c))};a.prototype._complete=function(){(this.hasCompleted=!0,0===this.active)&&this.destination.complete()};a.prototype.notifyNext=function(b,a,c,d,e){this._next(a)};a.prototype.notifyComplete=function(b){var a=this.buffer;this.remove(b);this.active--;a&&0<a.length&&
this._next(a.shift());this.hasCompleted&&0===this.active&&this.destination.complete()};return a}(v),Zd=function(){function c(a){this.callback=a}c.prototype.call=function(a,b){return b.subscribe(new Yd(a,this.callback))};return c}(),Yd=function(c){function a(b,a){b=c.call(this,b)||this;b.add(new w(a));return b}d(a,c);return a}(p),Db=function(){function c(a,b,c,g){this.predicate=a;this.source=b;this.yieldIndex=c;this.thisArg=g}c.prototype.call=function(a,b){return b.subscribe(new $d(a,this.predicate,
this.source,this.yieldIndex,this.thisArg))};return c}(),$d=function(c){function a(b,a,g,d,e){b=c.call(this,b)||this;b.predicate=a;b.source=g;b.yieldIndex=d;b.thisArg=e;b.index=0;return b}d(a,c);a.prototype.notifyComplete=function(b){var a=this.destination;a.next(b);a.complete()};a.prototype._next=function(b){var a=this.predicate,c=this.thisArg,d=this.index++;try{a.call(c||this,b,d,this.source)&&this.notifyComplete(this.yieldIndex?d:b)}catch(x){this.destination.error(x)}};a.prototype._complete=function(){this.notifyComplete(this.yieldIndex?
-1:void 0)};return a}(p),be=function(){function c(){}c.prototype.call=function(a,b){return b.subscribe(new ae(a))};return c}(),ae=function(c){function a(){return null!==c&&c.apply(this,arguments)||this}d(a,c);a.prototype._next=function(b){};return a}(p),de=function(){function c(){}c.prototype.call=function(a,b){return b.subscribe(new ce(a))};return c}(),ce=function(c){function a(b){return c.call(this,b)||this}d(a,c);a.prototype.notifyComplete=function(b){var a=this.destination;a.next(b);a.complete()};
a.prototype._next=function(b){this.notifyComplete(!1)};a.prototype._complete=function(){this.notifyComplete(!0)};return a}(p),pc=function(){function c(a){this.total=a;if(0>this.total)throw new da;}c.prototype.call=function(a,b){return b.subscribe(new ee(a,this.total))};return c}(),ee=function(c){function a(b,a){b=c.call(this,b)||this;b.total=a;b.ring=[];b.count=0;return b}d(a,c);a.prototype._next=function(b){var a=this.ring,c=this.total,d=this.count++;a.length<c?a.push(b):a[d%c]=b};a.prototype._complete=
function(){var b=this.destination,a=this.count;if(0<a)for(var c=this.count>=this.total?this.total:this.count,d=this.ring,e=0;e<c;e++){var h=a++%c;b.next(d[h])}b.complete()};return a}(p),ge=function(){function c(a){this.value=a}c.prototype.call=function(a,b){return b.subscribe(new fe(a,this.value))};return c}(),fe=function(c){function a(b,a){b=c.call(this,b)||this;b.value=a;return b}d(a,c);a.prototype._next=function(b){this.destination.next(this.value)};return a}(p),ie=function(){function c(){}c.prototype.call=
function(a,b){return b.subscribe(new he(a))};return c}(),he=function(c){function a(b){return c.call(this,b)||this}d(a,c);a.prototype._next=function(b){this.destination.next(A.createNext(b))};a.prototype._error=function(b){var a=this.destination;a.next(A.createError(b));a.complete()};a.prototype._complete=function(){var b=this.destination;b.next(A.createComplete());b.complete()};return a}(p),qc=function(){function c(a,b,c){void 0===c&&(c=!1);this.accumulator=a;this.seed=b;this.hasSeed=c}c.prototype.call=
function(a,b){return b.subscribe(new je(a,this.accumulator,this.seed,this.hasSeed))};return c}(),je=function(c){function a(b,a,g,d){b=c.call(this,b)||this;b.accumulator=a;b._seed=g;b.hasSeed=d;b.index=0;return b}d(a,c);Object.defineProperty(a.prototype,"seed",{get:function(){return this._seed},set:function(b){this.hasSeed=!0;this._seed=b},enumerable:!0,configurable:!0});a.prototype._next=function(b){if(this.hasSeed)return this._tryNext(b);this.seed=b;this.destination.next(b)};a.prototype._tryNext=
function(b){var a=this.index++,c;try{c=this.accumulator(this.seed,b,a)}catch(l){this.destination.error(l)}this.seed=c;this.destination.next(c)};return a}(p),le=function(){function c(a,b,c){this.accumulator=a;this.seed=b;this.concurrent=c}c.prototype.call=function(a,b){return b.subscribe(new ke(a,this.accumulator,this.seed,this.concurrent))};return c}(),ke=function(c){function a(b,a,g,d){b=c.call(this,b)||this;b.accumulator=a;b.acc=g;b.concurrent=d;b.hasValue=!1;b.hasCompleted=!1;b.buffer=[];b.active=
0;b.index=0;return b}d(a,c);a.prototype._next=function(b){if(this.active<this.concurrent){var a=this.index++,c=n(this.accumulator)(this.acc,b),d=this.destination;c===q?d.error(q.e):(this.active++,this._innerSub(c,b,a))}else this.buffer.push(b)};a.prototype._innerSub=function(b,a,c){this.add(u(this,b,a,c))};a.prototype._complete=function(){this.hasCompleted=!0;0===this.active&&0===this.buffer.length&&(!1===this.hasValue&&this.destination.next(this.acc),this.destination.complete())};a.prototype.notifyNext=
function(b,a,c,d,e){b=this.destination;this.acc=a;this.hasValue=!0;b.next(a)};a.prototype.notifyComplete=function(b){var a=this.buffer;this.remove(b);this.active--;0<a.length?this._next(a.shift()):0===this.active&&this.hasCompleted&&(!1===this.hasValue&&this.destination.next(this.acc),this.destination.complete())};return a}(v),rc=function(){function c(a,b){this.subjectFactory=a;this.selector=b}c.prototype.call=function(a,b){var c=this.selector,g=this.subjectFactory();a=c(g).subscribe(a);a.add(b.subscribe(g));
return a};return c}(),ne=function(){function c(a){this.nextSources=a}c.prototype.call=function(a,b){return b.subscribe(new me(a,this.nextSources))};return c}(),me=function(c){function a(b,a){var f=c.call(this,b)||this;f.destination=b;f.nextSources=a;return f}d(a,c);a.prototype.notifyError=function(b,a){this.subscribeToNextSource()};a.prototype.notifyComplete=function(b){this.subscribeToNextSource()};a.prototype._error=function(b){this.subscribeToNextSource()};a.prototype._complete=function(){this.subscribeToNextSource()};
a.prototype.subscribeToNextSource=function(){var b=this.nextSources.shift();b?this.add(u(this,b)):this.destination.complete()};return a}(v),pe=function(){function c(){}c.prototype.call=function(a,b){return b.subscribe(new oe(a))};return c}(),oe=function(c){function a(b){b=c.call(this,b)||this;b.hasPrev=!1;return b}d(a,c);a.prototype._next=function(b){this.hasPrev?this.destination.next([this.prev,b]):this.hasPrev=!0;this.prev=b};return a}(p),Eb=function(){function c(a,b){this.count=a;this.source=b}
c.prototype.call=function(a,b){return b.subscribe(new qe(a,this.count,this.source))};return c}(),qe=function(c){function a(b,a,g){b=c.call(this,b)||this;b.count=a;b.source=g;return b}d(a,c);a.prototype.complete=function(){if(!this.isStopped){var b=this.source,a=this.count;if(0===a)return c.prototype.complete.call(this);-1<a&&(this.count=a-1);b.subscribe(this._unsubscribeAndRecycle())}};return a}(p),se=function(){function c(a){this.notifier=a}c.prototype.call=function(a,b){return b.subscribe(new re(a,
this.notifier,b))};return c}(),re=function(c){function a(b,a,g){b=c.call(this,b)||this;b.notifier=a;b.source=g;b.sourceIsBeingSubscribedTo=!0;return b}d(a,c);a.prototype.notifyNext=function(b,a,c,d,e){this.sourceIsBeingSubscribedTo=!0;this.source.subscribe(this)};a.prototype.notifyComplete=function(b){if(!1===this.sourceIsBeingSubscribedTo)return c.prototype.complete.call(this)};a.prototype.complete=function(){this.sourceIsBeingSubscribedTo=!1;if(!this.isStopped){this.retries||this.subscribeToRetries();
if(!this.retriesSubscription||this.retriesSubscription.closed)return c.prototype.complete.call(this);this._unsubscribeAndRecycle();this.notifications.next()}};a.prototype._unsubscribe=function(){var b=this.notifications,a=this.retriesSubscription;b&&(b.unsubscribe(),this.notifications=null);a&&(a.unsubscribe(),this.retriesSubscription=null);this.retries=null};a.prototype._unsubscribeAndRecycle=function(){var b=this._unsubscribe;this._unsubscribe=null;c.prototype._unsubscribeAndRecycle.call(this);
this._unsubscribe=b;return this};a.prototype.subscribeToRetries=function(){this.notifications=new z;var b=n(this.notifier)(this.notifications);if(b===q)return c.prototype.complete.call(this);this.retries=b;this.retriesSubscription=u(this,b)};return a}(v),ue=function(){function c(a,b){this.count=a;this.source=b}c.prototype.call=function(a,b){return b.subscribe(new te(a,this.count,this.source))};return c}(),te=function(c){function a(b,a,g){b=c.call(this,b)||this;b.count=a;b.source=g;return b}d(a,c);
a.prototype.error=function(b){if(!this.isStopped){var a=this.source,g=this.count;if(0===g)return c.prototype.error.call(this,b);-1<g&&(this.count=g-1);a.subscribe(this._unsubscribeAndRecycle())}};return a}(p),we=function(){function c(a,b){this.notifier=a;this.source=b}c.prototype.call=function(a,b){return b.subscribe(new ve(a,this.notifier,this.source))};return c}(),ve=function(c){function a(b,a,g){b=c.call(this,b)||this;b.notifier=a;b.source=g;return b}d(a,c);a.prototype.error=function(b){if(!this.isStopped){var a=
this.errors,g=this.retries,d=this.retriesSubscription;if(g)this.retriesSubscription=this.errors=null;else{a=new z;g=n(this.notifier)(a);if(g===q)return c.prototype.error.call(this,q.e);d=u(this,g)}this._unsubscribeAndRecycle();this.errors=a;this.retries=g;this.retriesSubscription=d;a.next(b)}};a.prototype._unsubscribe=function(){var b=this.errors,a=this.retriesSubscription;b&&(b.unsubscribe(),this.errors=null);a&&(a.unsubscribe(),this.retriesSubscription=null);this.retries=null};a.prototype.notifyNext=
function(b,a,c,d,e){b=this._unsubscribe;this._unsubscribe=null;this._unsubscribeAndRecycle();this._unsubscribe=b;this.source.subscribe(this)};return a}(v),ye=function(){function c(a){this.notifier=a}c.prototype.call=function(a,b){a=new xe(a);b=b.subscribe(a);b.add(u(a,this.notifier));return b};return c}(),xe=function(c){function a(){var b=null!==c&&c.apply(this,arguments)||this;b.hasValue=!1;return b}d(a,c);a.prototype._next=function(b){this.value=b;this.hasValue=!0};a.prototype.notifyNext=function(b,
a,c,d,e){this.emitValue()};a.prototype.notifyComplete=function(){this.emitValue()};a.prototype.emitValue=function(){this.hasValue&&(this.hasValue=!1,this.destination.next(this.value))};return a}(v),Ae=function(){function c(a,b){this.period=a;this.scheduler=b}c.prototype.call=function(a,b){return b.subscribe(new ze(a,this.period,this.scheduler))};return c}(),ze=function(c){function a(b,a,g){b=c.call(this,b)||this;b.period=a;b.scheduler=g;b.hasValue=!1;b.add(g.schedule(vc,a,{subscriber:b,period:a}));
return b}d(a,c);a.prototype._next=function(b){this.lastValue=b;this.hasValue=!0};a.prototype.notifyNext=function(){this.hasValue&&(this.hasValue=!1,this.destination.next(this.lastValue))};return a}(p),Ce=function(){function c(a,b){this.compareTo=a;this.comparor=b}c.prototype.call=function(a,b){return b.subscribe(new Be(a,this.compareTo,this.comparor))};return c}(),Be=function(c){function a(b,a,g){var f=c.call(this,b)||this;f.compareTo=a;f.comparor=g;f._a=[];f._b=[];f._oneComplete=!1;f.add(a.subscribe(new De(b,
f)));return f}d(a,c);a.prototype._next=function(b){this._oneComplete&&0===this._b.length?this.emit(!1):(this._a.push(b),this.checkValues())};a.prototype._complete=function(){this._oneComplete?this.emit(0===this._a.length&&0===this._b.length):this._oneComplete=!0};a.prototype.checkValues=function(){for(var b=this._a,a=this._b,c=this.comparor;0<b.length&&0<a.length;){var d=b.shift(),e=a.shift();c?(d=n(c)(d,e),d===q&&this.destination.error(q.e)):d=d===e;d||this.emit(!1)}};a.prototype.emit=function(b){var a=
this.destination;a.next(b);a.complete()};a.prototype.nextB=function(b){this._oneComplete&&0===this._a.length?this.emit(!1):(this._b.push(b),this.checkValues())};return a}(p),De=function(c){function a(b,a){b=c.call(this,b)||this;b.parent=a;return b}d(a,c);a.prototype._next=function(b){this.parent.nextB(b)};a.prototype._error=function(b){this.parent.error(b)};a.prototype._complete=function(){this.parent._complete()};return a}(p),Fe=function(){function c(a,b){this.predicate=a;this.source=b}c.prototype.call=
function(a,b){return b.subscribe(new Ee(a,this.predicate,this.source))};return c}(),Ee=function(c){function a(b,a,d){b=c.call(this,b)||this;b.predicate=a;b.source=d;b.seenValue=!1;b.index=0;return b}d(a,c);a.prototype.applySingleValue=function(b){this.seenValue?this.destination.error("Sequence contains more than one element"):(this.seenValue=!0,this.singleValue=b)};a.prototype._next=function(b){var a=this.index++;this.predicate?this.tryNext(b,a):this.applySingleValue(b)};a.prototype.tryNext=function(b,
a){try{this.predicate(b,a,this.source)&&this.applySingleValue(b)}catch(g){this.destination.error(g)}};a.prototype._complete=function(){var b=this.destination;0<this.index?(b.next(this.seenValue?this.singleValue:void 0),b.complete()):b.error(new ga)};return a}(p),He=function(){function c(a){this.total=a}c.prototype.call=function(a,b){return b.subscribe(new Ge(a,this.total))};return c}(),Ge=function(c){function a(b,a){b=c.call(this,b)||this;b.total=a;b.count=0;return b}d(a,c);a.prototype._next=function(b){++this.count>
this.total&&this.destination.next(b)};return a}(p),Je=function(){function c(a){this._skipCount=a;if(0>this._skipCount)throw new da;}c.prototype.call=function(a,b){return 0===this._skipCount?b.subscribe(new p(a)):b.subscribe(new Ie(a,this._skipCount))};return c}(),Ie=function(c){function a(b,a){b=c.call(this,b)||this;b._skipCount=a;b._count=0;b._ring=Array(a);return b}d(a,c);a.prototype._next=function(b){var a=this._skipCount,c=this._count++;if(c<a)this._ring[c]=b;else{var a=c%a,c=this._ring,d=c[a];
c[a]=b;this.destination.next(d)}};return a}(p),Le=function(){function c(a){this.notifier=a}c.prototype.call=function(a,b){return b.subscribe(new Ke(a,this.notifier))};return c}(),Ke=function(c){function a(a,f){a=c.call(this,a)||this;a.hasValue=!1;a.add(a.innerSubscription=u(a,f));return a}d(a,c);a.prototype._next=function(a){this.hasValue&&c.prototype._next.call(this,a)};a.prototype.notifyNext=function(a,c,d,e,h){this.hasValue=!0;this.innerSubscription&&this.innerSubscription.unsubscribe()};a.prototype.notifyComplete=
function(){};return a}(v),Ne=function(){function c(a){this.predicate=a}c.prototype.call=function(a,b){return b.subscribe(new Me(a,this.predicate))};return c}(),Me=function(c){function a(a,f){a=c.call(this,a)||this;a.predicate=f;a.skipping=!0;a.index=0;return a}d(a,c);a.prototype._next=function(a){var b=this.destination;this.skipping&&this.tryCallPredicate(a);this.skipping||b.next(a)};a.prototype.tryCallPredicate=function(a){try{this.skipping=!!this.predicate(a,this.index++)}catch(f){this.destination.error(f)}};
return a}(p),Oe=function(c){function a(a,f,d){void 0===f&&(f=0);void 0===d&&(d=qa);var b=c.call(this)||this;b.source=a;b.delayTime=f;b.scheduler=d;if(!aa(f)||0>f)b.delayTime=0;d&&"function"===typeof d.schedule||(b.scheduler=qa);return b}d(a,c);a.create=function(b,c,d){void 0===c&&(c=0);void 0===d&&(d=qa);return new a(b,c,d)};a.dispatch=function(a){return this.add(a.source.subscribe(a.subscriber))};a.prototype._subscribe=function(b){return this.scheduler.schedule(a.dispatch,this.delayTime,{source:this.source,
subscriber:b})};return a}(r),Pe=function(){function c(a,b){this.scheduler=a;this.delay=b}c.prototype.call=function(a,b){return(new Oe(b,this.delay,this.scheduler)).subscribe(a)};return c}(),yc=function(){function c(a){this.project=a}c.prototype.call=function(a,b){return b.subscribe(new Qe(a,this.project))};return c}(),Qe=function(c){function a(a,f){a=c.call(this,a)||this;a.project=f;a.index=0;return a}d(a,c);a.prototype._next=function(a){var b,c=this.index++;try{b=this.project(a,c)}catch(l){this.destination.error(l);
return}this._innerSub(b,a,c)};a.prototype._innerSub=function(a,c,d){var b=this.innerSubscription;b&&b.unsubscribe();this.add(this.innerSubscription=u(this,a,c,d))};a.prototype._complete=function(){var a=this.innerSubscription;a&&!a.closed||c.prototype._complete.call(this)};a.prototype._unsubscribe=function(){this.innerSubscription=null};a.prototype.notifyComplete=function(a){this.remove(a);this.innerSubscription=null;this.isStopped&&c.prototype._complete.call(this)};a.prototype.notifyNext=function(a,
c,d,e,h){this.destination.next(c)};return a}(v),Se=function(){function c(a){this.notifier=a}c.prototype.call=function(a,b){a=new Re(a);var c=u(a,this.notifier);return c&&!c.closed?(a.add(c),b.subscribe(a)):a};return c}(),Re=function(c){function a(a){return c.call(this,a)||this}d(a,c);a.prototype.notifyNext=function(a,c,d,e,h){this.complete()};a.prototype.notifyComplete=function(){};return a}(v),Ue=function(){function c(a){this.predicate=a}c.prototype.call=function(a,b){return b.subscribe(new Te(a,
this.predicate))};return c}(),Te=function(c){function a(a,f){a=c.call(this,a)||this;a.predicate=f;a.index=0;return a}d(a,c);a.prototype._next=function(a){var b=this.destination,c;try{c=this.predicate(a,this.index++)}catch(l){b.error(l);return}this.nextOrComplete(a,c)};a.prototype.nextOrComplete=function(a,c){var b=this.destination;c?b.next(a):b.complete()};return a}(p),Fb={leading:!0,trailing:!1},We=function(){function c(a,b,c){this.durationSelector=a;this.leading=b;this.trailing=c}c.prototype.call=
function(a,b){return b.subscribe(new Ve(a,this.durationSelector,this.leading,this.trailing))};return c}(),Ve=function(c){function a(a,f,d,e){var b=c.call(this,a)||this;b.destination=a;b.durationSelector=f;b._leading=d;b._trailing=e;b._hasValue=!1;return b}d(a,c);a.prototype._next=function(a){this._hasValue=!0;this._sendValue=a;this._throttled||(this._leading?this.send():this.throttle(a))};a.prototype.send=function(){var a=this._sendValue;this._hasValue&&(this.destination.next(a),this.throttle(a));
this._hasValue=!1;this._sendValue=null};a.prototype.throttle=function(a){(a=this.tryDurationSelector(a))&&this.add(this._throttled=u(this,a))};a.prototype.tryDurationSelector=function(a){try{return this.durationSelector(a)}catch(f){return this.destination.error(f),null}};a.prototype.throttlingDone=function(){var a=this._throttled,c=this._trailing;a&&a.unsubscribe();this._throttled=null;c&&this.send()};a.prototype.notifyNext=function(a,c,d,e,h){this.throttlingDone()};a.prototype.notifyComplete=function(){this.throttlingDone()};
return a}(v),Ye=function(){function c(a,b,c,d){this.duration=a;this.scheduler=b;this.leading=c;this.trailing=d}c.prototype.call=function(a,b){return b.subscribe(new Xe(a,this.duration,this.scheduler,this.leading,this.trailing))};return c}(),Xe=function(c){function a(a,f,d,e,h){a=c.call(this,a)||this;a.duration=f;a.scheduler=d;a.leading=e;a.trailing=h;a._hasTrailingValue=!1;a._trailingValue=null;return a}d(a,c);a.prototype._next=function(a){this.throttled?this.trailing&&(this._trailingValue=a,this._hasTrailingValue=
!0):(this.add(this.throttled=this.scheduler.schedule(zc,this.duration,{subscriber:this})),this.leading&&this.destination.next(a))};a.prototype._complete=function(){this._hasTrailingValue&&this.destination.next(this._trailingValue);this.destination.complete()};a.prototype.clearThrottle=function(){var a=this.throttled;a&&(this.trailing&&this._hasTrailingValue&&(this.destination.next(this._trailingValue),this._trailingValue=null,this._hasTrailingValue=!1),a.unsubscribe(),this.remove(a),this.throttled=
null)};return a}(p),Ze=function(){return function(c,a){this.value=c;this.interval=a}}(),Ac=function(){function c(a,b,c,d){this.waitFor=a;this.absoluteTimeout=b;this.withObservable=c;this.scheduler=d}c.prototype.call=function(a,b){return b.subscribe(new $e(a,this.absoluteTimeout,this.waitFor,this.withObservable,this.scheduler))};return c}(),$e=function(c){function a(a,f,d,e,h){a=c.call(this,a)||this;a.absoluteTimeout=f;a.waitFor=d;a.withObservable=e;a.scheduler=h;a.action=null;a.scheduleTimeout();
return a}d(a,c);a.dispatchTimeout=function(a){var b=a.withObservable;a._unsubscribeAndRecycle();a.add(u(a,b))};a.prototype.scheduleTimeout=function(){var b=this.action;b?this.action=b.schedule(this,this.waitFor):this.add(this.action=this.scheduler.schedule(a.dispatchTimeout,this.waitFor,this))};a.prototype._next=function(a){this.absoluteTimeout||this.scheduleTimeout();c.prototype._next.call(this,a)};a.prototype._unsubscribe=function(){this.withObservable=this.scheduler=this.action=null};return a}(v),
af=function(){return function(c,a){this.value=c;this.timestamp=a}}(),cf=function(){function c(a){this.windowBoundaries=a}c.prototype.call=function(a,b){a=new bf(a);b=b.subscribe(a);b.closed||a.add(u(a,this.windowBoundaries));return b};return c}(),bf=function(c){function a(a){var b=c.call(this,a)||this;b.window=new z;a.next(b.window);return b}d(a,c);a.prototype.notifyNext=function(a,c,d,e,h){this.openWindow()};a.prototype.notifyError=function(a,c){this._error(a)};a.prototype.notifyComplete=function(a){this._complete()};
a.prototype._next=function(a){this.window.next(a)};a.prototype._error=function(a){this.window.error(a);this.destination.error(a)};a.prototype._complete=function(){this.window.complete();this.destination.complete()};a.prototype._unsubscribe=function(){this.window=null};a.prototype.openWindow=function(){var a=this.window;a&&a.complete();var a=this.destination,c=this.window=new z;a.next(c)};return a}(v),ef=function(){function c(a,b){this.windowSize=a;this.startWindowEvery=b}c.prototype.call=function(a,
b){return b.subscribe(new df(a,this.windowSize,this.startWindowEvery))};return c}(),df=function(c){function a(a,f,d){var b=c.call(this,a)||this;b.destination=a;b.windowSize=f;b.startWindowEvery=d;b.windows=[new z];b.count=0;a.next(b.windows[0]);return b}d(a,c);a.prototype._next=function(a){for(var b=0<this.startWindowEvery?this.startWindowEvery:this.windowSize,c=this.destination,d=this.windowSize,e=this.windows,h=e.length,k=0;k<h&&!this.closed;k++)e[k].next(a);a=this.count-d+1;0<=a&&0===a%b&&!this.closed&&
e.shift().complete();0!==++this.count%b||this.closed||(b=new z,e.push(b),c.next(b))};a.prototype._error=function(a){var b=this.windows;if(b)for(;0<b.length&&!this.closed;)b.shift().error(a);this.destination.error(a)};a.prototype._complete=function(){var a=this.windows;if(a)for(;0<a.length&&!this.closed;)a.shift().complete();this.destination.complete()};a.prototype._unsubscribe=function(){this.count=0;this.windows=null};return a}(p),gf=function(){function c(a,b,c,d){this.windowTimeSpan=a;this.windowCreationInterval=
b;this.maxWindowSize=c;this.scheduler=d}c.prototype.call=function(a,b){return b.subscribe(new ff(a,this.windowTimeSpan,this.windowCreationInterval,this.maxWindowSize,this.scheduler))};return c}(),hf=function(c){function a(){var a=null!==c&&c.apply(this,arguments)||this;a._numberOfNextedValues=0;return a}d(a,c);a.prototype.next=function(a){this._numberOfNextedValues++;c.prototype.next.call(this,a)};Object.defineProperty(a.prototype,"numberOfNextedValues",{get:function(){return this._numberOfNextedValues},
enumerable:!0,configurable:!0});return a}(z),ff=function(c){function a(a,f,d,e,h){var b=c.call(this,a)||this;b.destination=a;b.windowTimeSpan=f;b.windowCreationInterval=d;b.maxWindowSize=e;b.scheduler=h;b.windows=[];a=b.openWindow();null!==d&&0<=d?(e={windowTimeSpan:f,windowCreationInterval:d,subscriber:b,scheduler:h},b.add(h.schedule(nb,f,{subscriber:b,window:a,context:null})),b.add(h.schedule(Dc,d,e))):b.add(h.schedule(Cc,f,{subscriber:b,window:a,windowTimeSpan:f}));return b}d(a,c);a.prototype._next=
function(a){for(var b=this.windows,c=b.length,d=0;d<c;d++){var e=b[d];e.closed||(e.next(a),e.numberOfNextedValues>=this.maxWindowSize&&this.closeWindow(e))}};a.prototype._error=function(a){for(var b=this.windows;0<b.length;)b.shift().error(a);this.destination.error(a)};a.prototype._complete=function(){for(var a=this.windows;0<a.length;){var c=a.shift();c.closed||c.complete()}this.destination.complete()};a.prototype.openWindow=function(){var a=new hf;this.windows.push(a);this.destination.next(a);return a};
a.prototype.closeWindow=function(a){a.complete();var b=this.windows;b.splice(b.indexOf(a),1)};return a}(p),kf=function(){function c(a,b){this.openings=a;this.closingSelector=b}c.prototype.call=function(a,b){return b.subscribe(new jf(a,this.openings,this.closingSelector))};return c}(),jf=function(c){function a(a,f,d){a=c.call(this,a)||this;a.openings=f;a.closingSelector=d;a.contexts=[];a.add(a.openSubscription=u(a,f,f));return a}d(a,c);a.prototype._next=function(a){var b=this.contexts;if(b)for(var c=
b.length,d=0;d<c;d++)b[d].window.next(a)};a.prototype._error=function(a){var b=this.contexts;this.contexts=null;if(b)for(var d=b.length,e=-1;++e<d;){var h=b[e];h.window.error(a);h.subscription.unsubscribe()}c.prototype._error.call(this,a)};a.prototype._complete=function(){var a=this.contexts;this.contexts=null;if(a)for(var d=a.length,g=-1;++g<d;){var e=a[g];e.window.complete();e.subscription.unsubscribe()}c.prototype._complete.call(this)};a.prototype._unsubscribe=function(){var a=this.contexts;this.contexts=
null;if(a)for(var c=a.length,d=-1;++d<c;){var e=a[d];e.window.unsubscribe();e.subscription.unsubscribe()}};a.prototype.notifyNext=function(a,c,d,e,h){if(a===this.openings){e=n(this.closingSelector)(c);if(e===q)return this.error(q.e);a=new z;c=new w;d={window:a,subscription:c};this.contexts.push(d);e=u(this,e,d);e.closed?this.closeWindow(this.contexts.length-1):(e.context=d,c.add(e));this.destination.next(a)}else this.closeWindow(this.contexts.indexOf(a))};a.prototype.notifyError=function(a){this.error(a)};
a.prototype.notifyComplete=function(a){a!==this.openSubscription&&this.closeWindow(this.contexts.indexOf(a.context))};a.prototype.closeWindow=function(a){if(-1!==a){var b=this.contexts,c=b[a],d=c.window,c=c.subscription;b.splice(a,1);d.complete();c.unsubscribe()}};return a}(v),mf=function(){function c(a){this.closingSelector=a}c.prototype.call=function(a,b){return b.subscribe(new lf(a,this.closingSelector))};return c}(),lf=function(c){function a(a,d){var b=c.call(this,a)||this;b.destination=a;b.closingSelector=
d;b.openWindow();return b}d(a,c);a.prototype.notifyNext=function(a,c,d,e,h){this.openWindow(h)};a.prototype.notifyError=function(a,c){this._error(a)};a.prototype.notifyComplete=function(a){this.openWindow(a)};a.prototype._next=function(a){this.window.next(a)};a.prototype._error=function(a){this.window.error(a);this.destination.error(a);this.unsubscribeClosingNotification()};a.prototype._complete=function(){this.window.complete();this.destination.complete();this.unsubscribeClosingNotification()};a.prototype.unsubscribeClosingNotification=
function(){this.closingNotification&&this.closingNotification.unsubscribe()};a.prototype.openWindow=function(a){void 0===a&&(a=null);a&&(this.remove(a),a.unsubscribe());(a=this.window)&&a.complete();a=this.window=new z;this.destination.next(a);a=n(this.closingSelector)();a===q?(a=q.e,this.destination.error(a),this.window.error(a)):this.add(this.closingNotification=u(this,a))};return a}(v),of=function(){function c(a,b){this.observables=a;this.project=b}c.prototype.call=function(a,b){return b.subscribe(new nf(a,
this.observables,this.project))};return c}(),nf=function(c){function a(a,d,g){a=c.call(this,a)||this;a.observables=d;a.project=g;a.toRespond=[];g=d.length;a.values=Array(g);for(var b=0;b<g;b++)a.toRespond.push(b);for(b=0;b<g;b++){var f=d[b];a.add(u(a,f,f,b))}return a}d(a,c);a.prototype.notifyNext=function(a,c,d,e,h){this.values[d]=c;a=this.toRespond;0<a.length&&(d=a.indexOf(d),-1!==d&&a.splice(d,1))};a.prototype.notifyComplete=function(){};a.prototype._next=function(a){0===this.toRespond.length&&
(a=[a].concat(this.values),this.project?this._tryProject(a):this.destination.next(a))};a.prototype._tryProject=function(a){var b;try{b=this.project.apply(this,a)}catch(g){this.destination.error(g);return}this.destination.next(b)};return a}(v),pf=Object.freeze({audit:fb,auditTime:function(c,a){void 0===a&&(a=C);return fb(function(){return cb(c,a)})},buffer:function(c){return function(a){return a.lift(new jd(c))}},bufferCount:function(c,a){void 0===a&&(a=null);return function(b){return b.lift(new md(c,
a))}},bufferTime:function(c){var a=arguments.length,b=C;B(arguments[arguments.length-1])&&(b=arguments[arguments.length-1],a--);var d=null;2<=a&&(d=arguments[1]);var g=Number.POSITIVE_INFINITY;3<=a&&(g=arguments[2]);return function(a){return a.lift(new od(c,d,g,b))}},bufferToggle:function(c,a){return function(b){return b.lift(new rd(c,a))}},bufferWhen:function(c){return function(a){return a.lift(new td(c))}},catchError:function(c){return function(a){var b=new vd(c);a=a.lift(b);return b.caught=a}},
combineAll:function(c){return function(a){return a.lift(new Ia(c))}},combineLatest:function(){for(var c=[],a=0;a<arguments.length;a++)c[a]=arguments[a];var b=null;"function"===typeof c[c.length-1]&&(b=c.pop());1===c.length&&D(c[0])&&(c=c[0].slice());return function(a){return a.lift.call(L([a].concat(c)),new Ia(b))}},concat:function(){for(var c=[],a=0;a<arguments.length;a++)c[a]=arguments[a];return function(a){return a.lift.call(M.apply(void 0,[a].concat(c)))}},concatAll:Wa,concatMap:ib,concatMapTo:function(c,
a){return ib(function(){return c},a)},count:function(c){return function(a){return a.lift(new xd(c,a))}},debounce:function(c){return function(a){return a.lift(new zd(c))}},debounceTime:function(c,a){void 0===a&&(a=C);return function(b){return b.lift(new Bd(c,a))}},defaultIfEmpty:fa,delay:function(c,a){void 0===a&&(a=C);var b=c instanceof Date&&!isNaN(+c)?+c-a.now():Math.abs(c);return function(c){return c.lift(new Ed(b,a))}},delayWhen:function(c,a){return a?function(b){return(new Id(b,a)).lift(new Cb(c))}:
function(a){return a.lift(new Cb(c))}},dematerialize:function(){return function(c){return c.lift(new Kd)}},distinct:function(c,a){return function(b){return b.lift(new Md(c,a))}},distinctUntilChanged:jb,distinctUntilKeyChanged:function(c,a){return jb(function(b,d){return a?a(b[c],d[c]):b[c]===d[c]})},elementAt:function(c,a){if(0>c)throw new da;var b=2<=arguments.length;return function(d){return d.pipe(ba(function(a,b){return b===c}),Ba(1),b?fa(a):ra(function(){return new da}))}},endWith:function(){for(var c=
[],a=0;a<arguments.length;a++)c[a]=arguments[a];return function(a){var b=c[c.length-1];B(b)?c.pop():b=null;var d=c.length;return 1!==d||b?0<d?M(a,J(c,b)):M(a,I(b)):M(a,ta(c[0]))}},every:function(c,a){return function(b){return b.lift(new Sd(c,a,b))}},exhaust:function(){return function(c){return c.lift(new Ud)}},exhaustMap:lb,expand:function(c,a,b){void 0===a&&(a=Number.POSITIVE_INFINITY);void 0===b&&(b=void 0);a=1>(a||0)?Number.POSITIVE_INFINITY:a;return function(d){return d.lift(new Xd(c,a,b))}},
filter:ba,finalize:function(c){return function(a){return a.lift(new Zd(c))}},find:function(c,a){if("function"!==typeof c)throw new TypeError("predicate is not a function");return function(b){return b.lift(new Db(c,b,!1,a))}},findIndex:function(c,a){return function(b){return b.lift(new Db(c,b,!0,a))}},first:function(c,a){var b=2<=arguments.length;return function(d){return d.pipe(c?ba(function(a,b){return c(a,b,d)}):R,Ba(1),b?fa(a):ra(function(){return new ga}))}},groupBy:function(c,a,b,d){return function(f){return f.lift(new Pc(c,
a,b,d))}},ignoreElements:function(){return function(c){return c.lift(new be)}},isEmpty:function(){return function(c){return c.lift(new de)}},last:function(c,a){var b=2<=arguments.length;return function(d){return d.pipe(c?ba(function(a,b){return c(a,b,d)}):R,ma(1),b?fa(a):ra(function(){return new ga}))}},map:F,mapTo:function(c){return function(a){return a.lift(new ge(c))}},materialize:function(){return function(c){return c.lift(new ie)}},max:function(c){return oa("function"===typeof c?function(a,b){return 0<
c(a,b)?a:b}:function(a,b){return a>b?a:b})},merge:function(){for(var c=[],a=0;a<arguments.length;a++)c[a]=arguments[a];return function(a){return a.lift.call(ab.apply(void 0,[a].concat(c)))}},mergeAll:ya,mergeMap:T,flatMap:T,mergeMapTo:function(c,a,b){void 0===b&&(b=Number.POSITIVE_INFINITY);if("function"===typeof a)return T(function(){return c},a,b);"number"===typeof a&&(b=a);return T(function(){return c},b)},mergeScan:function(c,a,b){void 0===b&&(b=Number.POSITIVE_INFINITY);return function(d){return d.lift(new le(c,
a,b))}},min:function(c){return oa("function"===typeof c?function(a,b){return 0>c(a,b)?a:b}:function(a,b){return a<b?a:b})},multicast:U,observeOn:function(c,a){void 0===a&&(a=0);return function(b){return b.lift(new Tc(c,a))}},onErrorResumeNext:function(){for(var c=[],a=0;a<arguments.length;a++)c[a]=arguments[a];1===c.length&&D(c[0])&&(c=c[0]);return function(a){return a.lift(new ne(c))}},pairwise:function(){return function(c){return c.lift(new pe)}},partition:function(c,a){return function(b){return[ba(c,
a)(b),ba(tc(c,a))(b)]}},pluck:function(){for(var c=[],a=0;a<arguments.length;a++)c[a]=arguments[a];var b=c.length;if(0===b)throw Error("list of properties cannot be empty.");return function(a){return F(uc(c,b))(a)}},publish:function(c){return c?U(function(){return new z},c):U(new z)},publishBehavior:function(c){return function(a){return U(new ub(c))(a)}},publishLast:function(){return function(c){return U(new Y)(c)}},publishReplay:function(c,a,b,d){b&&"function"!==typeof b&&(d=b);var f="function"===
typeof b?b:void 0,e=new V(c,a,d);return function(a){return U(function(){return e},f)(a)}},race:function(){for(var c=[],a=0;a<arguments.length;a++)c[a]=arguments[a];return function(a){1===c.length&&D(c[0])&&(c=c[0]);return a.lift.call(bb.apply(void 0,[a].concat(c)))}},reduce:oa,repeat:function(c){void 0===c&&(c=-1);return function(a){return 0===c?I():0>c?a.lift(new Eb(-1,a)):a.lift(new Eb(c-1,a))}},repeatWhen:function(c){return function(a){return a.lift(new se(c))}},retry:function(c){void 0===c&&(c=
-1);return function(a){return a.lift(new ue(c,a))}},retryWhen:function(c){return function(a){return a.lift(new we(c,a))}},refCount:la,sample:function(c){return function(a){return a.lift(new ye(c))}},sampleTime:function(c,a){void 0===a&&(a=C);return function(b){return b.lift(new Ae(c,a))}},scan:na,sequenceEqual:function(c,a){return function(b){return b.lift(new Ce(c,a))}},share:function(){return function(c){return la()(U(wc)(c))}},shareReplay:function(c,a,b){return function(d){return d.lift(xc(c,a,
b))}},single:function(c){return function(a){return a.lift(new Fe(c,a))}},skip:function(c){return function(a){return a.lift(new He(c))}},skipLast:function(c){return function(a){return a.lift(new Je(c))}},skipUntil:function(c){return function(a){return a.lift(new Le(c))}},skipWhile:function(c){return function(a){return a.lift(new Ne(c))}},startWith:function(){for(var c=[],a=0;a<arguments.length;a++)c[a]=arguments[a];return function(a){var b=c[c.length-1];B(b)?c.pop():b=null;var d=c.length;return 1!==
d||b?0<d?M(J(c,b),a):M(I(b),a):M(ta(c[0]),a)}},subscribeOn:function(c,a){void 0===a&&(a=0);return function(b){return b.lift(new Pe(c,a))}},switchAll:function(){return ha(R)},switchMap:ha,switchMapTo:function(c,a){return a?ha(function(){return c},a):ha(function(){return c})},take:Ba,takeLast:ma,takeUntil:function(c){return function(a){return a.lift(new Se(c))}},takeWhile:function(c){return function(a){return a.lift(new Ue(c))}},tap:kb,throttle:function(c,a){void 0===a&&(a=Fb);return function(b){return b.lift(new We(c,
a.leading,a.trailing))}},throttleTime:function(c,a,b){void 0===a&&(a=C);void 0===b&&(b=Fb);return function(d){return d.lift(new Ye(c,a,b.leading,b.trailing))}},throwIfEmpty:ra,timeInterval:function(c){void 0===c&&(c=C);return function(a){return za(function(){return a.pipe(na(function(a,d){a=a.current;return{value:d,current:c.now(),last:a}},{current:c.now(),value:void 0,last:void 0}),F(function(a){return new Ze(a.value,a.current-a.last)}))})}},timeout:function(c,a){void 0===a&&(a=C);return mb(c,va(new zb),
a)},timeoutWith:mb,timestamp:function(c){void 0===c&&(c=C);return F(function(a){return new af(a,c.now())})},toArray:function(){return oa(Bc,[])},window:function(c){return function(a){return a.lift(new cf(c))}},windowCount:function(c,a){void 0===a&&(a=0);return function(b){return b.lift(new ef(c,a))}},windowTime:function(c,a,b,d){var f=C,e=null,h=Number.POSITIVE_INFINITY;B(d)&&(f=d);B(b)?f=b:aa(b)&&(h=b);B(a)?f=a:aa(a)&&(e=a);return function(a){return a.lift(new gf(c,e,h,f))}},windowToggle:function(c,
a){return function(b){return b.lift(new kf(c,a))}},windowWhen:function(c){return function(a){return a.lift(new mf(c))}},withLatestFrom:function(){for(var c=[],a=0;a<arguments.length;a++)c[a]=arguments[a];return function(a){var b;"function"===typeof c[c.length-1]&&(b=c.pop());return a.lift(new of(c,b))}},zip:function(){for(var c=[],a=0;a<arguments.length;a++)c[a]=arguments[a];return function(a){return a.lift.call(db.apply(void 0,[a].concat(c)))}},zipAll:function(c){return function(a){return a.lift(new eb(c))}}}),
ka=function(){return function(c,a){void 0===a&&(a=Number.POSITIVE_INFINITY);this.subscribedFrame=c;this.unsubscribedFrame=a}}(),Gb=function(){function c(){this.subscriptions=[]}c.prototype.logSubscribedFrame=function(){this.subscriptions.push(new ka(this.scheduler.now()));return this.subscriptions.length-1};c.prototype.logUnsubscribedFrame=function(a){var b=this.subscriptions;b[a]=new ka(b[a].subscribedFrame,this.scheduler.now())};return c}(),Ja=function(c){function a(a,d){var b=c.call(this,function(a){var b=
this,c=b.logSubscribedFrame();a.add(new w(function(){b.logUnsubscribedFrame(c)}));b.scheduleMessages(a);return a})||this;b.messages=a;b.subscriptions=[];b.scheduler=d;return b}d(a,c);a.prototype.scheduleMessages=function(a){for(var b=this.messages.length,c=0;c<b;c++){var d=this.messages[c];a.add(this.scheduler.schedule(function(a){a.message.notification.observe(a.subscriber)},d.frame,{message:d,subscriber:a}))}};return a}(r);ob(Ja,[Gb]);var Hb=function(c){function a(a,d){var b=c.call(this)||this;
b.messages=a;b.subscriptions=[];b.scheduler=d;return b}d(a,c);a.prototype._subscribe=function(a){var b=this,d=b.logSubscribedFrame();a.add(new w(function(){b.logUnsubscribedFrame(d)}));return c.prototype._subscribe.call(this,a)};a.prototype.setup=function(){for(var a=this,c=a.messages.length,d=0;d<c;d++)(function(){var b=a.messages[d];a.scheduler.schedule(function(){b.notification.observe(a)},b.frame)})()};return a}(z);ob(Hb,[Gb]);var qf=function(c){function a(a){var b=c.call(this,Ha,750)||this;b.assertDeepEqual=
a;b.hotObservables=[];b.coldObservables=[];b.flushTests=[];b.runMode=!1;return b}d(a,c);a.prototype.createTime=function(b){b=b.indexOf("|");if(-1===b)throw Error('marble diagram for time should have a completion marker "|"');return b*a.frameTimeFactor};a.prototype.createColdObservable=function(b,c,d){if(-1!==b.indexOf("^"))throw Error('cold observable cannot have subscription offset "^"');if(-1!==b.indexOf("!"))throw Error('cold observable cannot have unsubscription marker "!"');b=a.parseMarbles(b,
c,d,void 0,this.runMode);b=new Ja(b,this);this.coldObservables.push(b);return b};a.prototype.createHotObservable=function(b,c,d){if(-1!==b.indexOf("!"))throw Error('hot observable cannot have unsubscription marker "!"');b=a.parseMarbles(b,c,d,void 0,this.runMode);b=new Hb(b,this);this.hotObservables.push(b);return b};a.prototype.materializeInnerObservable=function(a,c){var b=this,d=[];a.subscribe(function(a){d.push({frame:b.frame-c,notification:A.createNext(a)})},function(a){d.push({frame:b.frame-
c,notification:A.createError(a)})},function(){d.push({frame:b.frame-c,notification:A.createComplete()})});return d};a.prototype.expectObservable=function(b,c){var d=this;void 0===c&&(c=null);var f=[],e={actual:f,ready:!1};c=a.parseMarblesAsSubscriptions(c,this.runMode).unsubscribedFrame;var h;this.schedule(function(){h=b.subscribe(function(a){var b=a;a instanceof r&&(b=d.materializeInnerObservable(b,d.frame));f.push({frame:d.frame,notification:A.createNext(b)})},function(a){f.push({frame:d.frame,
notification:A.createError(a)})},function(){f.push({frame:d.frame,notification:A.createComplete()})})},0);c!==Number.POSITIVE_INFINITY&&this.schedule(function(){return h.unsubscribe()},c);this.flushTests.push(e);var k=this.runMode;return{toBe:function(b,c,d){e.ready=!0;e.expected=a.parseMarbles(b,c,d,!0,k)}}};a.prototype.expectSubscriptions=function(b){var c={actual:b,ready:!1};this.flushTests.push(c);var d=this.runMode;return{toBe:function(b){b="string"===typeof b?[b]:b;c.ready=!0;c.expected=b.map(function(b){return a.parseMarblesAsSubscriptions(b,
d)})}}};a.prototype.flush=function(){for(var a=this,d=this.hotObservables;0<d.length;)d.shift().setup();c.prototype.flush.call(this);this.flushTests=this.flushTests.filter(function(b){return b.ready?(a.assertDeepEqual(b.actual,b.expected),!1):!0})};a.parseMarblesAsSubscriptions=function(a,c){var b=this;void 0===c&&(c=!1);if("string"!==typeof a)return new ka(Number.POSITIVE_INFINITY);for(var d=a.length,f=-1,e=Number.POSITIVE_INFINITY,h=Number.POSITIVE_INFINITY,k=0,n=function(d){var g=k,l=function(a){g+=
a*b.frameTimeFactor},n=a[d];switch(n){case " ":c||l(1);break;case "-":l(1);break;case "(":f=k;l(1);break;case ")":f=-1;l(1);break;case "^":if(e!==Number.POSITIVE_INFINITY)throw Error("found a second subscription point '^' in a subscription marble diagram. There can only be one.");e=-1<f?f:k;l(1);break;case "!":if(h!==Number.POSITIVE_INFINITY)throw Error("found a second subscription point '^' in a subscription marble diagram. There can only be one.");h=-1<f?f:k;break;default:if(c&&n.match(/^[0-9]$/)&&
(0===d||" "===a[d-1])){var t=a.slice(d).match(/^([0-9]+(?:\.[0-9]+)?)(ms|s|m) /);if(t){d+=t[0].length-1;var n=parseFloat(t[1]),x=void 0;switch(t[2]){case "ms":x=n;break;case "s":x=1E3*n;break;case "m":x=6E4*n}l(x/m.frameTimeFactor);break}}throw Error("there can only be '^' and '!' markers in a subscription marble diagram. Found instead '"+n+"'.");}k=g;p=d},m=this,p,q=0;q<d;q++)n(q),q=p;return 0>h?new ka(e):new ka(e,h)};a.parseMarbles=function(a,c,d,e,h){var b=this;void 0===e&&(e=!1);void 0===h&&(h=
!1);if(-1!==a.indexOf("!"))throw Error('conventional marble diagrams cannot have the unsubscription marker "!"');for(var f=a.length,g=[],l=h?a.replace(/^[ ]+/,"").indexOf("^"):a.indexOf("^"),k=-1===l?0:l*-this.frameTimeFactor,n="object"!==typeof c?function(a){return a}:function(a){return e&&c[a]instanceof Ja?c[a].messages:c[a]},m=-1,l=function(c){var f=k,e=function(a){f+=a*b.frameTimeFactor},l=void 0,t=a[c];switch(t){case " ":h||e(1);break;case "-":e(1);break;case "(":m=k;e(1);break;case ")":m=-1;
e(1);break;case "|":l=A.createComplete();e(1);break;case "^":e(1);break;case "#":l=A.createError(d||"error");e(1);break;default:if(h&&t.match(/^[0-9]$/)&&(0===c||" "===a[c-1])){var x=a.slice(c).match(/^([0-9]+(?:\.[0-9]+)?)(ms|s|m) /);if(x){c+=x[0].length-1;var t=parseFloat(x[1]),r=void 0;switch(x[2]){case "ms":r=t;break;case "s":r=1E3*t;break;case "m":r=6E4*t}e(r/p.frameTimeFactor);break}}l=A.createNext(n(t));e(1)}l&&g.push({frame:-1<m?m:k,notification:l});k=f;q=c},p=this,q,x=0;x<f;x++)l(x),x=q;
return g};a.prototype.run=function(b){var c=a.frameTimeFactor,d=this.maxFrames;a.frameTimeFactor=1;this.maxFrames=Number.POSITIVE_INFINITY;this.runMode=!0;X.delegate=this;var e={cold:this.createColdObservable.bind(this),hot:this.createHotObservable.bind(this),flush:this.flush.bind(this),expectObservable:this.expectObservable.bind(this),expectSubscriptions:this.expectSubscriptions.bind(this)};try{var h=b(e);this.flush();return h}finally{a.frameTimeFactor=c,this.maxFrames=d,this.runMode=!1,X.delegate=
void 0}};return a}(yb),rf=Object.freeze({TestScheduler:qf}),sf="undefined"!==typeof self&&"undefined"!==typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&self,tf="undefined"!==typeof global&&global,E="undefined"!==typeof window&&window||tf||sf;if(!E)throw Error("RxJS could not find any global context (window, self, global)");var Kc=F(function(c,a){return c.response}),W=function(c){function a(a){var b=c.call(this)||this,d={async:!0,createXHR:function(){var a;if(this.crossDomain)if(E.XMLHttpRequest)a=
new E.XMLHttpRequest;else if(E.XDomainRequest)a=new E.XDomainRequest;else throw Error("CORS is not supported by your browser");else if(E.XMLHttpRequest)a=new E.XMLHttpRequest;else{var b=void 0;try{for(var c=["Msxml2.XMLHTTP","Microsoft.XMLHTTP","Msxml2.XMLHTTP.4.0"],d=0;3>d;d++)try{b=c[d];new E.ActiveXObject(b);break}catch(t){}a=new E.ActiveXObject(b)}catch(t){throw Error("XMLHttpRequest is not supported by your browser");}}return a},crossDomain:!0,withCredentials:!1,headers:{},method:"GET",responseType:"json",
timeout:0};if("string"===typeof a)d.url=a;else for(var e in a)a.hasOwnProperty(e)&&(d[e]=a[e]);b.request=d;return b}d(a,c);a.prototype._subscribe=function(a){return new uf(a,this.request)};a.create=function(){var b=function(b){return new a(b)};b.get=Ec;b.post=Fc;b.delete=Gc;b.put=Hc;b.patch=Ic;b.getJSON=Jc;return b}();return a}(r),uf=function(c){function a(a,d){a=c.call(this,a)||this;a.request=d;a.done=!1;var b=d.headers=d.headers||{};d.crossDomain||b["X-Requested-With"]||(b["X-Requested-With"]="XMLHttpRequest");
"Content-Type"in b||E.FormData&&d.body instanceof E.FormData||"undefined"===typeof d.body||(b["Content-Type"]="application/x-www-form-urlencoded; charset\x3dUTF-8");d.body=a.serializeBody(d.body,d.headers["Content-Type"]);a.send();return a}d(a,c);a.prototype.next=function(a){this.done=!0;var b=this.destination;a=new Ib(a,this.xhr,this.request);b.next(a)};a.prototype.send=function(){var a=this.request,c=this.request,d=c.user,e=c.method,h=c.url,k=c.async,m=c.password,p=c.headers,c=c.body,t=n(a.createXHR).call(a);
if(t===q)this.error(q.e);else{this.xhr=t;this.setupEvents(t,a);d=d?n(t.open).call(t,e,h,k,d,m):n(t.open).call(t,e,h,k);if(d===q)return this.error(q.e),null;k&&(t.timeout=a.timeout,t.responseType=a.responseType);"withCredentials"in t&&(t.withCredentials=!!a.withCredentials);this.setHeaders(t,p);d=c?n(t.send).call(t,c):n(t.send).call(t);if(d===q)return this.error(q.e),null}return t};a.prototype.serializeBody=function(a,c){if(!a||"string"===typeof a||E.FormData&&a instanceof E.FormData)return a;if(c){var b=
c.indexOf(";");-1!==b&&(c=c.substring(0,b))}switch(c){case "application/x-www-form-urlencoded":return Object.keys(a).map(function(b){return encodeURIComponent(b)+"\x3d"+encodeURIComponent(a[b])}).join("\x26");case "application/json":return JSON.stringify(a);default:return a}};a.prototype.setHeaders=function(a,c){for(var b in c)c.hasOwnProperty(b)&&a.setRequestHeader(b,c[b])};a.prototype.setupEvents=function(a,c){function b(a){var c=b.subscriber,d=b.progressSubscriber,f=b.request;d&&d.error(a);c.error(new Jb(this,
f))}function d(a){}function f(a){var b=f.subscriber,c=f.progressSubscriber,d=f.request;if(4===this.readyState){var e=1223===this.status?204:this.status,g="text"===this.responseType?this.response||this.responseText:this.response;0===e&&(e=g?200:0);400>e?(c&&c.complete(),b.next(a),b.complete()):(c&&c.error(a),b.error(new sa("ajax error "+e,this,d)))}}var e=c.progressSubscriber;a.ontimeout=b;b.request=c;b.subscriber=this;b.progressSubscriber=e;if(a.upload&&"withCredentials"in a){if(e){var h;h=function(a){h.progressSubscriber.next(a)};
E.XDomainRequest?a.onprogress=h:a.upload.onprogress=h;h.progressSubscriber=e}var k;k=function(a){var b=k.progressSubscriber,c=k.subscriber,d=k.request;b&&b.error(a);c.error(new sa("ajax error",this,d))};a.onerror=k;k.request=c;k.subscriber=this;k.progressSubscriber=e}a.onreadystatechange=d;d.subscriber=this;d.progressSubscriber=e;d.request=c;a.onload=f;f.subscriber=this;f.progressSubscriber=e;f.request=c};a.prototype.unsubscribe=function(){var a=this.xhr;!this.done&&a&&4!==a.readyState&&"function"===
typeof a.abort&&a.abort();c.prototype.unsubscribe.call(this)};return a}(p),Ib=function(){return function(c,a,b){this.originalEvent=c;this.xhr=a;this.request=b;this.status=a.status;this.responseType=a.responseType||b.responseType;this.response=pb(this.responseType,a)}}(),sa=function(c){function a(b,d,e){var f=c.call(this,b)||this;f.name="AjaxError";f.message=b;f.xhr=d;f.request=e;f.status=d.status;f.responseType=d.responseType||e.responseType;f.response=pb(f.responseType,d);Object.setPrototypeOf(f,
a.prototype);return f}d(a,c);return a}(Error),Jb=function(c){function a(b,d){b=c.call(this,"ajax timeout",b,d)||this;b.name="AjaxTimeoutError";Object.setPrototypeOf(b,a.prototype);return b}d(a,c);return a}(sa),vf=Object.freeze({ajax:W.create,AjaxResponse:Ib,AjaxError:sa,AjaxTimeoutError:Jb}),wf={url:"",deserializer:function(c){return JSON.parse(c.data)},serializer:function(c){return JSON.stringify(c)}},Kb=function(c){function a(a,d){var b=c.call(this)||this;if(a instanceof r)b.destination=d,b.source=
a;else{d=b._config=Lc({},wf);b._output=new z;if("string"===typeof a)d.url=a;else for(var e in a)a.hasOwnProperty(e)&&(d[e]=a[e]);if(!d.WebSocketCtor&&WebSocket)d.WebSocketCtor=WebSocket;else if(!d.WebSocketCtor)throw Error("no WebSocket constructor can be found");b.destination=new V}return b}d(a,c);a.prototype.lift=function(b){var c=new a(this._config,this.destination);c.operator=b;c.source=this;return c};a.prototype._resetState=function(){this._socket=null;this.source||(this.destination=new V);this._output=
new z};a.prototype.multiplex=function(a,c,d){var b=this;return new r(function(e){var f=n(a)();f===q?e.error(q.e):b.next(f);var g=b.subscribe(function(a){var b=n(d)(a);b===q?e.error(q.e):b&&e.next(a)},function(a){return e.error(a)},function(){return e.complete()});return function(){var a=n(c)();a===q?e.error(q.e):b.next(a);g.unsubscribe()}})};a.prototype._connectSocket=function(){var a=this,c=this._config,d=c.WebSocketCtor,e=c.protocol,h=c.url,c=c.binaryType,k=this._output,m=null;try{this._socket=
m=e?new d(h,e):new d(h),c&&(this._socket.binaryType=c)}catch(t){k.error(t);return}var r=new w(function(){a._socket=null;m&&1===m.readyState&&m.close()});m.onopen=function(b){var c=a._config.openObserver;c&&c.next(b);b=a.destination;a.destination=p.create(function(b){1===m.readyState&&(b=n(a._config.serializer)(b),b===q?a.destination.error(q.e):m.send(b))},function(b){var c=a._config.closingObserver;c&&c.next(void 0);b&&b.code?m.close(b.code,b.reason):k.error(new TypeError("WebSocketSubject.error must be called with an object with an error code, and an optional reason: { code: number, reason: string }"));
a._resetState()},function(){var b=a._config.closingObserver;b&&b.next(void 0);m.close();a._resetState()});b&&b instanceof V&&r.add(b.subscribe(a.destination))};m.onerror=function(b){a._resetState();k.error(b)};m.onclose=function(b){a._resetState();var c=a._config.closeObserver;c&&c.next(b);b.wasClean?k.complete():k.error(b)};m.onmessage=function(b){b=n(a._config.deserializer)(b);b===q?k.error(q.e):k.next(b)}};a.prototype._subscribe=function(a){var b=this,c=this.source;if(c)return c.subscribe(a);this._socket||
this._connectSocket();c=new w;c.add(this._output.subscribe(a));c.add(function(){var a=b._socket;0===b._output.observers.length&&(a&&1===a.readyState&&a.close(),b._resetState())});return c};a.prototype.unsubscribe=function(){var a=this.source,d=this._socket;d&&1===d.readyState&&(d.close(),this._resetState());c.prototype.unsubscribe.call(this);a||(this.destination=new V)};return a}(Da),xf=Object.freeze({webSocket:function(c){return new Kb(c)},WebSocketSubject:Kb});e.operators=pf;e.testing=rf;e.ajax=
vf;e.webSocket=xf;e.Observable=r;e.ConnectableObservable=tb;e.GroupedObservable=Ea;e.observable=Z;e.Subject=z;e.BehaviorSubject=ub;e.ReplaySubject=V;e.AsyncSubject=Y;e.asapScheduler=qa;e.asyncScheduler=C;e.queueScheduler=vb;e.animationFrameScheduler=Zc;e.VirtualTimeScheduler=yb;e.VirtualAction=Ha;e.Scheduler=Fa;e.Subscription=w;e.Subscriber=p;e.Notification=A;e.pipe=G;e.noop=m;e.identity=R;e.isObservable=function(c){return!!c&&(c instanceof r||"function"===typeof c.lift&&"function"===typeof c.subscribe)};
e.ArgumentOutOfRangeError=da;e.EmptyError=ga;e.ObjectUnsubscribedError=N;e.UnsubscriptionError=ea;e.TimeoutError=zb;e.bindCallback=Na;e.bindNodeCallback=Oa;e.combineLatest=function(){for(var c=[],a=0;a<arguments.length;a++)c[a]=arguments[a];var b=a=null;B(c[c.length-1])&&(b=c.pop());"function"===typeof c[c.length-1]&&(a=c.pop());1===c.length&&D(c[0])&&(c=c[0]);return J(c,b).lift(new Ia(a))};e.concat=M;e.defer=za;e.empty=I;e.forkJoin=Xa;e.from=L;e.fromEvent=Ya;e.fromEventPattern=$a;e.generate=function(c,
a,b,d,e){var f,g;1==arguments.length?(g=c.initialState,a=c.condition,b=c.iterate,f=c.resultSelector||R,e=c.scheduler):void 0===d||B(d)?(g=c,f=R,e=d):(g=c,f=d);return new r(function(c){var d=g;if(e)return e.schedule($b,0,{subscriber:c,iterate:b,condition:a,resultSelector:f,state:d});do{if(a){var h=void 0;try{h=a(d)}catch(t){c.error(t);break}if(!h){c.complete();break}}h=void 0;try{h=f(d)}catch(t){c.error(t);break}c.next(h);if(c.closed)break;try{d=b(d)}catch(t){c.error(t);break}}while(1)})};e.iif=function(c,
a,b){void 0===a&&(a=Q);void 0===b&&(b=Q);return za(function(){return c()?a:b})};e.interval=function(c,a){void 0===c&&(c=0);void 0===a&&(a=C);if(!aa(c)||0>c)c=0;a&&"function"===typeof a.schedule||(a=C);return new r(function(b){b.add(a.schedule(ac,c,{subscriber:b,counter:0,period:c}));return b})};e.merge=ab;e.never=function(){return Bb};e.of=ua;e.onErrorResumeNext=Aa;e.pairs=function(c,a){return a?new r(function(b){var d=Object.keys(c),e=new w;e.add(a.schedule(bc,0,{keys:d,index:0,subscriber:b,subscription:e,
obj:c}));return e}):new r(function(a){for(var b=Object.keys(c),d=0;d<b.length&&!a.closed;d++){var e=b[d];c.hasOwnProperty(e)&&a.next([e,c[e]])}a.complete()})};e.race=bb;e.range=function(c,a,b){void 0===c&&(c=0);void 0===a&&(a=0);return new r(function(d){var e=0,f=c;if(b)return b.schedule(dc,0,{index:e,count:a,start:c,subscriber:d});do{if(e++>=a){d.complete();break}d.next(f++);if(d.closed)break}while(1)})};e.throwError=va;e.timer=cb;e.using=function(c,a){return new r(function(b){var d;try{d=c()}catch(x){b.error(x);
return}var e;try{e=a(d)}catch(x){b.error(x);return}var h=(e?L(e):Q).subscribe(b);return function(){h.unsubscribe();d&&d.unsubscribe()}})};e.zip=db;e.EMPTY=Q;e.NEVER=Bb;e.config=H;Object.defineProperty(e,"__esModule",{value:!0})});
|
if(SC.setupBodyClassNames){SC.setupBodyClassNames()};
|
'use strict';
var utils = require('./utils');
/**
* `Run` represents a single execution of a `Task`.
*
* @param {Number} `id` identifier of this run.
* @api public
*/
function Run(id) {
if (!(this instanceof Run)) {
return new Run(id);
}
this.runId = id;
this.date = {};
this.hr = {};
/**
* Calculate the difference between the `start` and `end` hr times in nanoseconds.
*
* @api public
* @name hr.diff
*/
Object.defineProperty(this.hr, 'diff', {
get: function() {
return utils.nano(this.end) - utils.nano(this.start);
}
});
/**
* Calculate the offset between the hr `duration` and hr `diff` properties in nanoseconds.
* This is needed because `duration` is called with `process.hrtime(hr.start)` after `hr.end`
* is calculated using `process.hrtime()`.
*
* @api public
* @name hr.offset
*/
Object.defineProperty(this.hr, 'offset', {
get: function() {
return utils.nano(this.duration) - this.diff;
}
});
}
/**
* Start recording the run times. This will save the start date on `run.date.start` and the start hr time on `run.hr.start`
*/
Run.prototype.start = function() {
this.date.start = new Date();
this.hr.start = process.hrtime();
};
/**
* Stop recording the run times. This will save the end hr time on `run.hr.end`,
* calculate the duration using `process.hrtime(run.hr.start)`,
* and save the end date on `run.date.end`
*
* `end` is calculated before `duration` causing `duration` to be approximately 10,000 nanoseconds off.
* See `offset` for actual `offset`
*/
Run.prototype.end = function() {
this.hr.end = process.hrtime();
this.hr.duration = process.hrtime(this.hr.start);
this.date.end = new Date();
};
/**
* Expose `Run`
*/
module.exports = Run;
|
/*
* FCKeditor - The text editor for internet
* Copyright (C) 2003-2006 Frederico Caldeira Knabben
*
* Licensed under the terms of the GNU Lesser General Public License:
* http://www.opensource.org/licenses/lgpl-license.php
*
* For further information visit:
* http://www.fckeditor.net/
*
* "Support Open Source software. What about a donation today?"
*
* File Name: fck_2_ie.js
* This is the second part of the "FCK" object creation. This is the main
* object that represents an editor instance.
* (IE specific implementations)
*
* File Authors:
* Frederico Caldeira Knabben (fredck@fckeditor.net)
*/
/*
if ( FCKConfig.UseBROnCarriageReturn )
{
// Named commands to be handled by this browsers specific implementation.
FCK.RedirectNamedCommands =
{
InsertOrderedList : true,
InsertUnorderedList : true
}
FCK.ExecuteRedirectedNamedCommand = function( commandName, commandParameter )
{
if ( commandName == 'InsertOrderedList' || commandName == 'InsertUnorderedList' )
{
if ( !(FCK.EditorDocument.queryCommandState( 'InsertOrderedList' ) || FCK.EditorDocument.queryCommandState( 'InsertUnorderedList' )) )
{
}
}
FCK.ExecuteNamedCommand( commandName, commandParameter ) ;
}
}
*/
FCK.Paste = function()
{
if ( FCKConfig.ForcePasteAsPlainText )
{
FCK.PasteAsPlainText() ;
return ;
}
var sHTML = FCK.GetClipboardHTML() ;
if ( FCKConfig.AutoDetectPasteFromWord )
{
var re = /<\w[^>]*(( class="?MsoNormal"?)|(="mso-))/gi ;
if ( re.test( sHTML ) )
{
if ( confirm( FCKLang["PasteWordConfirm"] ) )
{
FCK.PasteFromWord() ;
return ;
}
}
}
FCK.InsertHtml( sHTML ) ;
}
FCK.PasteAsPlainText = function()
{
// Get the data available in the clipboard and encodes it in HTML.
var sText = FCKTools.HTMLEncode( clipboardData.getData("Text") ) ;
// Replace the carriage returns with <BR>
sText = sText.replace( /\n/g, '<BR>' ) ;
// Insert the resulting data in the editor.
this.InsertHtml( sText ) ;
}
/*
FCK.PasteFromWord = function()
{
FCK.CleanAndPaste( FCK.GetClipboardHTML() ) ;
}
*/
FCK.InsertElement = function( element )
{
FCK.InsertHtml( element.outerHTML ) ;
}
FCK.GetClipboardHTML = function()
{
var oDiv = document.getElementById( '___FCKHiddenDiv' ) ;
if ( !oDiv )
{
var oDiv = document.createElement( 'DIV' ) ;
oDiv.id = '___FCKHiddenDiv' ;
oDiv.style.visibility = 'hidden' ;
oDiv.style.overflow = 'hidden' ;
oDiv.style.position = 'absolute' ;
oDiv.style.width = 1 ;
oDiv.style.height = 1 ;
document.body.appendChild( oDiv ) ;
}
oDiv.innerHTML = '' ;
var oTextRange = document.body.createTextRange() ;
oTextRange.moveToElementText( oDiv ) ;
oTextRange.execCommand( 'Paste' ) ;
var sData = oDiv.innerHTML ;
oDiv.innerHTML = '' ;
return sData ;
}
FCK.AttachToOnSelectionChange = function( functionPointer )
{
this.Events.AttachEvent( 'OnSelectionChange', functionPointer ) ;
}
/*
FCK.AttachToOnSelectionChange = function( functionPointer )
{
FCK.EditorDocument.attachEvent( 'onselectionchange', functionPointer ) ;
}
*/
FCK.CreateLink = function( url )
{
// Remove any existing link in the selection.
FCK.ExecuteNamedCommand( 'Unlink' ) ;
if ( url.length > 0 )
{
// Generate a temporary name for the link.
var sTempUrl = 'javascript:void(0);/*' + ( new Date().getTime() ) + '*/' ;
// Use the internal "CreateLink" command to create the link.
FCK.ExecuteNamedCommand( 'CreateLink', sTempUrl ) ;
// Look for the just create link.
var oLinks = this.EditorDocument.links ;
for ( i = 0 ; i < oLinks.length ; i++ )
{
var oLink = oLinks[i] ;
if ( oLink.href == sTempUrl )
{
var sInnerHtml = oLink.innerHTML ; // Save the innerHTML (IE changes it if it is like an URL).
oLink.href = url ;
oLink.innerHTML = sInnerHtml ; // Restore the innerHTML.
return oLink ;
}
}
}
}
|
//TODO: move arrow styles and button click code into configurable items, with defaults matching the existing code
/*!
* Timepicker Component for Twitter Bootstrap
*
* Copyright 2013 Joris de Wit
*
* Contributors https://github.com/jdewit/bootstrap-timepicker/graphs/contributors
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
(function($, window, document, undefined) {
'use strict';
// TIMEPICKER PUBLIC CLASS DEFINITION
var Timepicker = function(element, options) {
this.widget = '';
this.$element = $(element);
this.defaultTime = options.defaultTime;
this.disableFocus = options.disableFocus;
this.isOpen = options.isOpen;
this.minuteStep = options.minuteStep;
this.modalBackdrop = options.modalBackdrop;
this.secondStep = options.secondStep;
this.showInputs = options.showInputs;
this.showMeridian = options.showMeridian;
this.showSeconds = options.showSeconds;
this.template = options.template;
this.appendWidgetTo = options.appendWidgetTo;
this.upArrowStyle = options.upArrowStyle;
this.downArrowStyle = options.downArrowStyle;
this.containerClass = options.containerClass;
this._init();
};
Timepicker.prototype = {
constructor: Timepicker,
_init: function() {
var self = this;
if (this.$element.parent().hasClass('input-group')) {
if (this.$element.parent('.input-group').find('.input-group-addon').length) {
this.$element.parent('.input-group').find('.input-group-addon').on({
'click.timepicker': $.proxy(this.showWidget, this)
});
} else {
this.$element.closest(this.containerClass).find('.input-group-addon').on({
'click.timepicker': $.proxy(this.showWidget, this)
});
}
this.$element.on({
'focus.timepicker': $.proxy(this.highlightUnit, this),
'click.timepicker': $.proxy(this.highlightUnit, this),
'keydown.timepicker': $.proxy(this.elementKeydown, this),
'blur.timepicker': $.proxy(this.blurElement, this)
});
} else {
if (this.template) {
this.$element.on({
'focus.timepicker': $.proxy(this.showWidget, this),
'click.timepicker': $.proxy(this.showWidget, this),
'blur.timepicker': $.proxy(this.blurElement, this)
});
} else {
this.$element.on({
'focus.timepicker': $.proxy(this.highlightUnit, this),
'click.timepicker': $.proxy(this.highlightUnit, this),
'keydown.timepicker': $.proxy(this.elementKeydown, this),
'blur.timepicker': $.proxy(this.blurElement, this)
});
}
}
if (this.template !== false) {
this.$widget = $(this.getTemplate()).prependTo(this.$element.parents(this.appendWidgetTo)).on('click', $.proxy(this.widgetClick, this));
} else {
this.$widget = false;
}
if (this.showInputs && this.$widget !== false) {
this.$widget.find('input').each(function() {
$(this).on({
'click.timepicker': function() { $(this).select(); },
'keydown.timepicker': $.proxy(self.widgetKeydown, self)
});
});
}
this.setDefaultTime(this.defaultTime);
},
blurElement: function() {
this.highlightedUnit = undefined;
this.updateFromElementVal();
},
decrementHour: function() {
if (this.showMeridian) {
if (this.hour === 1) {
this.hour = 12;
} else if (this.hour === 12) {
this.hour--;
return this.toggleMeridian();
} else if (this.hour === 0) {
this.hour = 11;
return this.toggleMeridian();
} else {
this.hour--;
}
} else {
if (this.hour === 0) {
this.hour = 23;
} else {
this.hour--;
}
}
this.update();
},
decrementMinute: function(step) {
var newVal;
if (step) {
newVal = this.minute - step;
} else {
newVal = this.minute - this.minuteStep;
}
if (newVal < 0) {
this.decrementHour();
this.minute = newVal + 60;
} else {
this.minute = newVal;
}
this.update();
},
decrementSecond: function() {
var newVal = this.second - this.secondStep;
if (newVal < 0) {
this.decrementMinute(true);
this.second = newVal + 60;
} else {
this.second = newVal;
}
this.update();
},
elementKeydown: function(e) {
switch (e.keyCode) {
case 9: //tab
this.updateFromElementVal();
switch (this.highlightedUnit) {
case 'hour':
e.preventDefault();
this.highlightNextUnit();
break;
case 'minute':
if (this.showMeridian || this.showSeconds) {
e.preventDefault();
this.highlightNextUnit();
}
break;
case 'second':
if (this.showMeridian) {
e.preventDefault();
this.highlightNextUnit();
}
break;
}
break;
case 27: // escape
this.updateFromElementVal();
break;
case 37: // left arrow
e.preventDefault();
this.highlightPrevUnit();
this.updateFromElementVal();
break;
case 38: // up arrow
e.preventDefault();
switch (this.highlightedUnit) {
case 'hour':
this.incrementHour();
this.highlightHour();
break;
case 'minute':
this.incrementMinute();
this.highlightMinute();
break;
case 'second':
this.incrementSecond();
this.highlightSecond();
break;
case 'meridian':
this.toggleMeridian();
this.highlightMeridian();
break;
}
break;
case 39: // right arrow
e.preventDefault();
this.updateFromElementVal();
this.highlightNextUnit();
break;
case 40: // down arrow
e.preventDefault();
switch (this.highlightedUnit) {
case 'hour':
this.decrementHour();
this.highlightHour();
break;
case 'minute':
this.decrementMinute();
this.highlightMinute();
break;
case 'second':
this.decrementSecond();
this.highlightSecond();
break;
case 'meridian':
this.toggleMeridian();
this.highlightMeridian();
break;
}
break;
}
},
formatTime: function(hour, minute, second, meridian) {
hour = hour < 10 ? '0' + hour : hour;
minute = minute < 10 ? '0' + minute : minute;
second = second < 10 ? '0' + second : second;
return hour + ':' + minute + (this.showSeconds ? ':' + second : '') + (this.showMeridian ? ' ' + meridian : '');
},
getCursorPosition: function() {
var input = this.$element.get(0);
if ('selectionStart' in input) {// Standard-compliant browsers
return input.selectionStart;
} else if (document.selection) {// IE fix
input.focus();
var sel = document.selection.createRange(),
selLen = document.selection.createRange().text.length;
sel.moveStart('character', - input.value.length);
return sel.text.length - selLen;
}
},
getTemplate: function() {
var template,
hourTemplate,
minuteTemplate,
secondTemplate,
meridianTemplate,
templateContent;
if (this.showInputs) {
hourTemplate = '<input type="text" name="hour" class="bootstrap-timepicker-hour form-control" maxlength="2"/>';
minuteTemplate = '<input type="text" name="minute" class="bootstrap-timepicker-minute form-control" maxlength="2"/>';
secondTemplate = '<input type="text" name="second" class="bootstrap-timepicker-second form-control" maxlength="2"/>';
meridianTemplate = '<input type="text" name="meridian" class="bootstrap-timepicker-meridian form-control" maxlength="2"/>';
} else {
hourTemplate = '<span class="bootstrap-timepicker-hour"></span>';
minuteTemplate = '<span class="bootstrap-timepicker-minute"></span>';
secondTemplate = '<span class="bootstrap-timepicker-second"></span>';
meridianTemplate = '<span class="bootstrap-timepicker-meridian"></span>';
}
templateContent = '<table>'+
'<tr>'+
'<td><a href="#" data-action="incrementHour"><i class="' + this.upArrowStyle + '"></i></a></td>'+
'<td class="separator"> </td>'+
'<td><a href="#" data-action="incrementMinute"><i class="' + this.upArrowStyle + '"></i></a></td>'+
(this.showSeconds ?
'<td class="separator"> </td>'+
'<td><a href="#" data-action="incrementSecond"><i class="' + this.upArrowStyle + '"></i></a></td>'
: '') +
(this.showMeridian ?
'<td class="separator"> </td>'+
'<td class="meridian-column"><a href="#" data-action="toggleMeridian"><i class="' + this.upArrowStyle + '"></i></a></td>'
: '') +
'</tr>'+
'<tr>'+
'<td>'+ hourTemplate +'</td> '+
'<td class="separator">:</td>'+
'<td>'+ minuteTemplate +'</td> '+
(this.showSeconds ?
'<td class="separator">:</td>'+
'<td>'+ secondTemplate +'</td>'
: '') +
(this.showMeridian ?
'<td class="separator"> </td>'+
'<td>'+ meridianTemplate +'</td>'
: '') +
'</tr>'+
'<tr>'+
'<td><a href="#" data-action="decrementHour"><i class="' + this.downArrowStyle + '"></i></a></td>'+
'<td class="separator"></td>'+
'<td><a href="#" data-action="decrementMinute"><i class="' + this.downArrowStyle + '"></i></a></td>'+
(this.showSeconds ?
'<td class="separator"> </td>'+
'<td><a href="#" data-action="decrementSecond"><i class="' + this.downArrowStyle + '"></i></a></td>'
: '') +
(this.showMeridian ?
'<td class="separator"> </td>'+
'<td><a href="#" data-action="toggleMeridian"><i class="' + this.downArrowStyle + '"></i></a></td>'
: '') +
'</tr>'+
'</table>';
switch(this.template) {
case 'modal':
template = '<div class="bootstrap-timepicker-widget modal hide fade in" data-backdrop="'+ (this.modalBackdrop ? 'true' : 'false') +'">'+
'<div class="modal-header">'+
'<a href="#" class="close" data-dismiss="modal">×</a>'+
'<h3>Pick a Time</h3>'+
'</div>'+
'<div class="modal-content">'+
templateContent +
'</div>'+
'<div class="modal-footer">'+
'<a href="#" class="btn btn-primary" data-dismiss="modal">OK</a>'+
'</div>'+
'</div>';
break;
case 'dropdown':
template = '<div class="bootstrap-timepicker-widget dropdown-menu">'+ templateContent +'</div>';
break;
}
return template;
},
getTime: function() {
return this.formatTime(this.hour, this.minute, this.second, this.meridian);
},
hideWidget: function() {
if (this.isOpen === false) {
return;
}
if (this.showInputs) {
this.updateFromWidgetInputs();
}
this.$element.trigger({
'type': 'hide.timepicker',
'time': {
'value': this.getTime(),
'hours': this.hour,
'minutes': this.minute,
'seconds': this.second,
'meridian': this.meridian
}
});
if (this.template === 'modal' && this.$widget.modal) {
this.$widget.modal('hide');
} else {
this.$widget.removeClass('open');
}
$(document).off('mousedown.timepicker');
this.isOpen = false;
},
highlightUnit: function() {
this.position = this.getCursorPosition();
if (this.position >= 0 && this.position <= 2) {
this.highlightHour();
} else if (this.position >= 3 && this.position <= 5) {
this.highlightMinute();
} else if (this.position >= 6 && this.position <= 8) {
if (this.showSeconds) {
this.highlightSecond();
} else {
this.highlightMeridian();
}
} else if (this.position >= 9 && this.position <= 11) {
this.highlightMeridian();
}
},
highlightNextUnit: function() {
switch (this.highlightedUnit) {
case 'hour':
this.highlightMinute();
break;
case 'minute':
if (this.showSeconds) {
this.highlightSecond();
} else if (this.showMeridian){
this.highlightMeridian();
} else {
this.highlightHour();
}
break;
case 'second':
if (this.showMeridian) {
this.highlightMeridian();
} else {
this.highlightHour();
}
break;
case 'meridian':
this.highlightHour();
break;
}
},
highlightPrevUnit: function() {
switch (this.highlightedUnit) {
case 'hour':
this.highlightMeridian();
break;
case 'minute':
this.highlightHour();
break;
case 'second':
this.highlightMinute();
break;
case 'meridian':
if (this.showSeconds) {
this.highlightSecond();
} else {
this.highlightMinute();
}
break;
}
},
highlightHour: function() {
var $element = this.$element.get(0);
this.highlightedUnit = 'hour';
if ($element.setSelectionRange) {
setTimeout(function() {
$element.setSelectionRange(0,2);
}, 0);
}
},
highlightMinute: function() {
var $element = this.$element.get(0);
this.highlightedUnit = 'minute';
if ($element.setSelectionRange) {
setTimeout(function() {
$element.setSelectionRange(3,5);
}, 0);
}
},
highlightSecond: function() {
var $element = this.$element.get(0);
this.highlightedUnit = 'second';
if ($element.setSelectionRange) {
setTimeout(function() {
$element.setSelectionRange(6,8);
}, 0);
}
},
highlightMeridian: function() {
var $element = this.$element.get(0);
this.highlightedUnit = 'meridian';
if ($element.setSelectionRange) {
if (this.showSeconds) {
setTimeout(function() {
$element.setSelectionRange(9,11);
}, 0);
} else {
setTimeout(function() {
$element.setSelectionRange(6,8);
}, 0);
}
}
},
incrementHour: function() {
if (this.showMeridian) {
if (this.hour === 11) {
this.hour++;
return this.toggleMeridian();
} else if (this.hour === 12) {
this.hour = 0;
}
}
if (this.hour === 23) {
this.hour = 0;
return;
}
this.hour++;
this.update();
},
incrementMinute: function(step) {
var newVal;
if (step) {
newVal = this.minute + step;
} else {
newVal = this.minute + this.minuteStep - (this.minute % this.minuteStep);
}
if (newVal > 59) {
this.incrementHour();
this.minute = newVal - 60;
} else {
this.minute = newVal;
}
this.update();
},
incrementSecond: function() {
var newVal = this.second + this.secondStep - (this.second % this.secondStep);
if (newVal > 59) {
this.incrementMinute(true);
this.second = newVal - 60;
} else {
this.second = newVal;
}
this.update();
},
remove: function() {
$('document').off('.timepicker');
if (this.$widget) {
this.$widget.remove();
}
delete this.$element.data().timepicker;
},
setDefaultTime: function(defaultTime){
if (!this.$element.val()) {
if (defaultTime === 'current') {
var dTime = new Date(),
hours = dTime.getHours(),
minutes = Math.floor(dTime.getMinutes() / this.minuteStep) * this.minuteStep,
seconds = Math.floor(dTime.getSeconds() / this.secondStep) * this.secondStep,
meridian = 'AM';
if (this.showMeridian) {
if (hours === 0) {
hours = 12;
} else if (hours >= 12) {
if (hours > 12) {
hours = hours - 12;
}
meridian = 'PM';
} else {
meridian = 'AM';
}
}
this.hour = hours;
this.minute = minutes;
this.second = seconds;
this.meridian = meridian;
this.update();
} else if (defaultTime === false) {
this.hour = 0;
this.minute = 0;
this.second = 0;
this.meridian = 'AM';
} else {
this.setTime(defaultTime);
}
} else {
this.updateFromElementVal();
}
},
setTime: function(time) {
var arr,
timeArray;
if (this.showMeridian) {
arr = time.split(' ');
timeArray = arr[0].split(':');
this.meridian = arr[1];
} else {
timeArray = time.split(':');
}
this.hour = parseInt(timeArray[0], 10);
this.minute = parseInt(timeArray[1], 10);
this.second = parseInt(timeArray[2], 10);
if (isNaN(this.hour)) {
this.hour = 0;
}
if (isNaN(this.minute)) {
this.minute = 0;
}
if (this.showMeridian) {
if (this.hour > 12) {
this.hour = 12;
} else if (this.hour < 1) {
this.hour = 12;
}
if (this.meridian === 'am' || this.meridian === 'a') {
this.meridian = 'AM';
} else if (this.meridian === 'pm' || this.meridian === 'p') {
this.meridian = 'PM';
}
if (this.meridian !== 'AM' && this.meridian !== 'PM') {
this.meridian = 'AM';
}
} else {
if (this.hour >= 24) {
this.hour = 23;
} else if (this.hour < 0) {
this.hour = 0;
}
}
if (this.minute < 0) {
this.minute = 0;
} else if (this.minute >= 60) {
this.minute = 59;
}
if (this.showSeconds) {
if (isNaN(this.second)) {
this.second = 0;
} else if (this.second < 0) {
this.second = 0;
} else if (this.second >= 60) {
this.second = 59;
}
}
this.update();
},
showWidget: function() {
if (this.isOpen) {
return;
}
if (this.$element.is(':disabled')) {
return;
}
var self = this;
$(document).on('mousedown.timepicker', function (e) {
// Clicked outside the timepicker, hide it
if ($(e.target).closest('.bootstrap-timepicker-widget').length === 0) {
self.hideWidget();
}
});
this.$element.trigger({
'type': 'show.timepicker',
'time': {
'value': this.getTime(),
'hours': this.hour,
'minutes': this.minute,
'seconds': this.second,
'meridian': this.meridian
}
});
if (this.disableFocus) {
this.$element.blur();
}
this.updateFromElementVal();
if (this.template === 'modal' && this.$widget.modal) {
this.$widget.modal('show').on('hidden', $.proxy(this.hideWidget, this));
} else {
if (this.isOpen === false) {
this.$widget.addClass('open');
}
}
this.isOpen = true;
},
toggleMeridian: function() {
this.meridian = this.meridian === 'AM' ? 'PM' : 'AM';
this.update();
},
update: function() {
this.$element.trigger({
'type': 'changeTime.timepicker',
'time': {
'value': this.getTime(),
'hours': this.hour,
'minutes': this.minute,
'seconds': this.second,
'meridian': this.meridian
}
});
this.updateElement();
this.updateWidget();
},
updateElement: function() {
this.$element.val(this.getTime()).change();
},
updateFromElementVal: function() {
var val = this.$element.val();
if (val) {
this.setTime(val);
}
},
updateWidget: function() {
if (this.$widget === false) {
return;
}
var hour = this.hour < 10 ? '0' + this.hour : this.hour,
minute = this.minute < 10 ? '0' + this.minute : this.minute,
second = this.second < 10 ? '0' + this.second : this.second;
if (this.showInputs) {
this.$widget.find('input.bootstrap-timepicker-hour').val(hour);
this.$widget.find('input.bootstrap-timepicker-minute').val(minute);
if (this.showSeconds) {
this.$widget.find('input.bootstrap-timepicker-second').val(second);
}
if (this.showMeridian) {
this.$widget.find('input.bootstrap-timepicker-meridian').val(this.meridian);
}
} else {
this.$widget.find('span.bootstrap-timepicker-hour').text(hour);
this.$widget.find('span.bootstrap-timepicker-minute').text(minute);
if (this.showSeconds) {
this.$widget.find('span.bootstrap-timepicker-second').text(second);
}
if (this.showMeridian) {
this.$widget.find('span.bootstrap-timepicker-meridian').text(this.meridian);
}
}
},
updateFromWidgetInputs: function() {
if (this.$widget === false) {
return;
}
var time = $('input.bootstrap-timepicker-hour', this.$widget).val() + ':' +
$('input.bootstrap-timepicker-minute', this.$widget).val() +
(this.showSeconds ? ':' + $('input.bootstrap-timepicker-second', this.$widget).val() : '') +
(this.showMeridian ? ' ' + $('input.bootstrap-timepicker-meridian', this.$widget).val() : '');
this.setTime(time);
},
widgetClick: function(e) {
e.stopPropagation();
e.preventDefault();
var action = $(e.target).closest('a').data('action');
if (action) {
this[action]();
}
},
widgetKeydown: function(e) {
var $input = $(e.target).closest('input'),
name = $input.attr('name');
switch (e.keyCode) {
case 9: //tab
if (this.showMeridian) {
if (name === 'meridian') {
return this.hideWidget();
}
} else {
if (this.showSeconds) {
if (name === 'second') {
return this.hideWidget();
}
} else {
if (name === 'minute') {
return this.hideWidget();
}
}
}
this.updateFromWidgetInputs();
break;
case 27: // escape
this.hideWidget();
break;
case 38: // up arrow
e.preventDefault();
switch (name) {
case 'hour':
this.incrementHour();
break;
case 'minute':
this.incrementMinute();
break;
case 'second':
this.incrementSecond();
break;
case 'meridian':
this.toggleMeridian();
break;
}
break;
case 40: // down arrow
e.preventDefault();
switch (name) {
case 'hour':
this.decrementHour();
break;
case 'minute':
this.decrementMinute();
break;
case 'second':
this.decrementSecond();
break;
case 'meridian':
this.toggleMeridian();
break;
}
break;
}
}
};
//TIMEPICKER PLUGIN DEFINITION
$.fn.timepicker = function(option) {
var args = Array.apply(null, arguments);
args.shift();
return this.each(function() {
var $this = $(this),
data = $this.data('timepicker'),
options = typeof option === 'object' && option;
if (!data) {
$this.data('timepicker', (data = new Timepicker(this, $.extend({}, $.fn.timepicker.defaults, options, $(this).data()))));
}
if (typeof option === 'string') {
data[option].apply(data, args);
}
});
};
$.fn.timepicker.defaults = {
defaultTime: 'current',
disableFocus: false,
isOpen: false,
minuteStep: 15,
modalBackdrop: false,
secondStep: 15,
showSeconds: false,
showInputs: true,
showMeridian: true,
template: 'dropdown',
appendWidgetTo: '.bootstrap-timepicker',
upArrowStyle: 'glyphicon glyphicon-chevron-up',
downArrowStyle: 'glyphicon glyphicon-chevron-down',
containerClass: 'bootstrap-timepicker'
};
$.fn.timepicker.Constructor = Timepicker;
})(jQuery, window, document);
|
function ip2long(IP) {
// discuss at: http://phpjs.org/functions/ip2long/
// original by: Waldo Malqui Silva
// improved by: Victor
// revised by: fearphage (http://http/my.opera.com/fearphage/)
// revised by: Theriault
// example 1: ip2long('192.0.34.166');
// returns 1: 3221234342
// example 2: ip2long('0.0xABCDEF');
// returns 2: 11259375
// example 3: ip2long('255.255.255.256');
// returns 3: false
var i = 0;
// PHP allows decimal, octal, and hexadecimal IP components.
// PHP allows between 1 (e.g. 127) to 4 (e.g 127.0.0.1) components.
IP = IP.match(
/^([1-9]\d*|0[0-7]*|0x[\da-f]+)(?:\.([1-9]\d*|0[0-7]*|0x[\da-f]+))?(?:\.([1-9]\d*|0[0-7]*|0x[\da-f]+))?(?:\.([1-9]\d*|0[0-7]*|0x[\da-f]+))?$/i
); // Verify IP format.
if (!IP) {
return false; // Invalid format.
}
// Reuse IP variable for component counter.
IP[0] = 0;
for (i = 1; i < 5; i += 1) {
IP[0] += !! ((IP[i] || '')
.length);
IP[i] = parseInt(IP[i]) || 0;
}
// Continue to use IP for overflow values.
// PHP does not allow any component to overflow.
IP.push(256, 256, 256, 256);
// Recalculate overflow of last component supplied to make up for missing components.
IP[4 + IP[0]] *= Math.pow(256, 4 - IP[0]);
if (IP[1] >= IP[5] || IP[2] >= IP[6] || IP[3] >= IP[7] || IP[4] >= IP[8]) {
return false;
}
return IP[1] * (IP[0] === 1 || 16777216) + IP[2] * (IP[0] <= 2 || 65536) + IP[3] * (IP[0] <= 3 || 256) + IP[4] * 1;
}
|
/*!
* Angular Material Design
* https://github.com/angular/material
* @license MIT
* v1.1.0-rc4-master-c81f9f1
*/
goog.provide('ng.material.components.slider');
goog.require('ng.material.core');
/**
* @ngdoc module
* @name material.components.slider
*/
angular.module('material.components.slider', [
'material.core'
])
.directive('mdSlider', SliderDirective)
.directive('mdSliderContainer', SliderContainerDirective);
/**
* @ngdoc directive
* @name mdSliderContainer
* @module material.components.slider
* @restrict E
* @description
* The `<md-slider-container>` contains slider with two other elements.
*
*
* @usage
* <h4>Normal Mode</h4>
* <hljs lang="html">
* </hljs>
*/
function SliderContainerDirective() {
return {
controller: function () {},
compile: function (elem) {
var slider = elem.find('md-slider');
if (!slider) {
return;
}
var vertical = slider.attr('md-vertical');
if (vertical !== undefined) {
elem.attr('md-vertical', '');
}
if(!slider.attr('flex')) {
slider.attr('flex', '');
}
return function postLink(scope, element, attr, ctrl) {
element.addClass('_md'); // private md component indicator for styling
// We have to manually stop the $watch on ngDisabled because it exists
// on the parent scope, and won't be automatically destroyed when
// the component is destroyed.
function setDisable(value) {
element.children().attr('disabled', value);
element.find('input').attr('disabled', value);
}
var stopDisabledWatch = angular.noop;
if (attr.disabled) {
setDisable(true);
}
else if (attr.ngDisabled) {
stopDisabledWatch = scope.$watch(attr.ngDisabled, function (value) {
setDisable(value);
});
}
scope.$on('$destroy', function () {
stopDisabledWatch();
});
var initialMaxWidth;
ctrl.fitInputWidthToTextLength = function (length) {
var input = element.find('md-input-container');
var computedStyle = getComputedStyle(input[0]);
var minWidth = parseInt(computedStyle['min-width']);
var padding = parseInt(computedStyle['padding']) * 2;
initialMaxWidth = initialMaxWidth || parseInt(computedStyle['max-width']);
var newMaxWidth = Math.max(initialMaxWidth, minWidth + padding + (minWidth / 2 * length));
input.css('max-width', newMaxWidth + 'px');
};
}
}
}
}
/**
* @ngdoc directive
* @name mdSlider
* @module material.components.slider
* @restrict E
* @description
* The `<md-slider>` component allows the user to choose from a range of
* values.
*
* As per the [material design spec](http://www.google.com/design/spec/style/color.html#color-ui-color-application)
* the slider is in the accent color by default. The primary color palette may be used with
* the `md-primary` class.
*
* It has two modes: 'normal' mode, where the user slides between a wide range
* of values, and 'discrete' mode, where the user slides between only a few
* select values.
*
* To enable discrete mode, add the `md-discrete` attribute to a slider,
* and use the `step` attribute to change the distance between
* values the user is allowed to pick.
*
* @usage
* <h4>Normal Mode</h4>
* <hljs lang="html">
* <md-slider ng-model="myValue" min="5" max="500">
* </md-slider>
* </hljs>
* <h4>Discrete Mode</h4>
* <hljs lang="html">
* <md-slider md-discrete ng-model="myDiscreteValue" step="10" min="10" max="130">
* </md-slider>
* </hljs>
*
* @param {boolean=} md-discrete Whether to enable discrete mode.
* @param {number=} step The distance between values the user is allowed to pick. Default 1.
* @param {number=} min The minimum value the user is allowed to pick. Default 0.
* @param {number=} max The maximum value the user is allowed to pick. Default 100.
* @param {number=} round The amount of numbers after the decimal point, maximum is 6 to prevent scientific notation. Default 3.
*/
function SliderDirective($$rAF, $window, $mdAria, $mdUtil, $mdConstant, $mdTheming, $mdGesture, $parse, $log, $timeout) {
return {
scope: {},
require: ['?ngModel', '?^mdSliderContainer'],
template:
'<div class="_md-slider-wrapper">' +
'<div class="_md-slider-content">' +
'<div class="_md-track-container">' +
'<div class="_md-track"></div>' +
'<div class="_md-track _md-track-fill"></div>' +
'<div class="_md-track-ticks"></div>' +
'</div>' +
'<div class="_md-thumb-container">' +
'<div class="_md-thumb"></div>' +
'<div class="_md-focus-thumb"></div>' +
'<div class="_md-focus-ring"></div>' +
'<div class="_md-sign">' +
'<span class="_md-thumb-text"></span>' +
'</div>' +
'<div class="_md-disabled-thumb"></div>' +
'</div>' +
'</div>' +
'</div>',
compile: compile
};
// **********************************************************
// Private Methods
// **********************************************************
function compile (tElement, tAttrs) {
var wrapper = angular.element(tElement[0].getElementsByClassName('_md-slider-wrapper'));
var tabIndex = tAttrs.tabindex || 0;
wrapper.attr('tabindex', tabIndex);
if (tAttrs.disabled || tAttrs.ngDisabled) wrapper.attr('tabindex', -1);
wrapper.attr('role', 'slider');
$mdAria.expect(tElement, 'aria-label');
return postLink;
}
function postLink(scope, element, attr, ctrls) {
$mdTheming(element);
var ngModelCtrl = ctrls[0] || {
// Mock ngModelController if it doesn't exist to give us
// the minimum functionality needed
$setViewValue: function(val) {
this.$viewValue = val;
this.$viewChangeListeners.forEach(function(cb) { cb(); });
},
$parsers: [],
$formatters: [],
$viewChangeListeners: []
};
var containerCtrl = ctrls[1];
var container = angular.element($mdUtil.getClosest(element, '_md-slider-container', true));
var isDisabled = attr.ngDisabled ? angular.bind(null, $parse(attr.ngDisabled), scope.$parent) : function () {
return element[0].hasAttribute('disabled');
};
var thumb = angular.element(element[0].querySelector('._md-thumb'));
var thumbText = angular.element(element[0].querySelector('._md-thumb-text'));
var thumbContainer = thumb.parent();
var trackContainer = angular.element(element[0].querySelector('._md-track-container'));
var activeTrack = angular.element(element[0].querySelector('._md-track-fill'));
var tickContainer = angular.element(element[0].querySelector('._md-track-ticks'));
var wrapper = angular.element(element[0].getElementsByClassName('_md-slider-wrapper'));
var content = angular.element(element[0].getElementsByClassName('_md-slider-content'));
var throttledRefreshDimensions = $mdUtil.throttle(refreshSliderDimensions, 5000);
// Default values, overridable by attrs
var DEFAULT_ROUND = 3;
var vertical = angular.isDefined(attr.mdVertical);
var discrete = angular.isDefined(attr.mdDiscrete);
angular.isDefined(attr.min) ? attr.$observe('min', updateMin) : updateMin(0);
angular.isDefined(attr.max) ? attr.$observe('max', updateMax) : updateMax(100);
angular.isDefined(attr.step)? attr.$observe('step', updateStep) : updateStep(1);
angular.isDefined(attr.round)? attr.$observe('round', updateRound) : updateRound(DEFAULT_ROUND);
// We have to manually stop the $watch on ngDisabled because it exists
// on the parent scope, and won't be automatically destroyed when
// the component is destroyed.
var stopDisabledWatch = angular.noop;
if (attr.ngDisabled) {
stopDisabledWatch = scope.$parent.$watch(attr.ngDisabled, updateAriaDisabled);
}
$mdGesture.register(wrapper, 'drag', { horizontal: !vertical });
scope.mouseActive = false;
wrapper
.on('keydown', keydownListener)
.on('mousedown', mouseDownListener)
.on('focus', focusListener)
.on('blur', blurListener)
.on('$md.pressdown', onPressDown)
.on('$md.pressup', onPressUp)
.on('$md.dragstart', onDragStart)
.on('$md.drag', onDrag)
.on('$md.dragend', onDragEnd);
// On resize, recalculate the slider's dimensions and re-render
function updateAll() {
refreshSliderDimensions();
ngModelRender();
}
setTimeout(updateAll, 0);
var debouncedUpdateAll = $$rAF.throttle(updateAll);
angular.element($window).on('resize', debouncedUpdateAll);
scope.$on('$destroy', function() {
angular.element($window).off('resize', debouncedUpdateAll);
});
ngModelCtrl.$render = ngModelRender;
ngModelCtrl.$viewChangeListeners.push(ngModelRender);
ngModelCtrl.$formatters.push(minMaxValidator);
ngModelCtrl.$formatters.push(stepValidator);
/**
* Attributes
*/
var min;
var max;
var step;
var round;
function updateMin(value) {
min = parseFloat(value);
element.attr('aria-valuemin', value);
updateAll();
}
function updateMax(value) {
max = parseFloat(value);
element.attr('aria-valuemax', value);
updateAll();
}
function updateStep(value) {
step = parseFloat(value);
}
function updateRound(value) {
// Set max round digits to 6, after 6 the input uses scientific notation
round = minMaxValidator(parseInt(value), 0, 6);
}
function updateAriaDisabled() {
element.attr('aria-disabled', !!isDisabled());
}
// Draw the ticks with canvas.
// The alternative to drawing ticks with canvas is to draw one element for each tick,
// which could quickly become a performance bottleneck.
var tickCanvas, tickCtx;
function redrawTicks() {
if (!discrete || isDisabled()) return;
if ( angular.isUndefined(step) ) return;
if ( step <= 0 ) {
var msg = 'Slider step value must be greater than zero when in discrete mode';
$log.error(msg);
throw new Error(msg);
}
var numSteps = Math.floor( (max - min) / step );
if (!tickCanvas) {
tickCanvas = angular.element('<canvas>').css('position', 'absolute');
tickContainer.append(tickCanvas);
tickCtx = tickCanvas[0].getContext('2d');
}
var dimensions = getSliderDimensions();
// If `dimensions` doesn't have height and width it might be the first attempt so we will refresh dimensions
if (dimensions && !dimensions.height && !dimensions.width) {
refreshSliderDimensions();
dimensions = sliderDimensions;
}
tickCanvas[0].width = dimensions.width;
tickCanvas[0].height = dimensions.height;
var distance;
for (var i = 0; i <= numSteps; i++) {
var trackTicksStyle = $window.getComputedStyle(tickContainer[0]);
tickCtx.fillStyle = trackTicksStyle.color || 'black';
distance = Math.floor((vertical ? dimensions.height : dimensions.width) * (i / numSteps));
tickCtx.fillRect(vertical ? 0 : distance - 1,
vertical ? distance - 1 : 0,
vertical ? dimensions.width : 2,
vertical ? 2 : dimensions.height);
}
}
function clearTicks() {
if(tickCanvas && tickCtx) {
var dimensions = getSliderDimensions();
tickCtx.clearRect(0, 0, dimensions.width, dimensions.height);
}
}
/**
* Refreshing Dimensions
*/
var sliderDimensions = {};
refreshSliderDimensions();
function refreshSliderDimensions() {
sliderDimensions = trackContainer[0].getBoundingClientRect();
}
function getSliderDimensions() {
throttledRefreshDimensions();
return sliderDimensions;
}
/**
* left/right/up/down arrow listener
*/
function keydownListener(ev) {
if (isDisabled()) return;
var changeAmount;
if (vertical ? ev.keyCode === $mdConstant.KEY_CODE.DOWN_ARROW : ev.keyCode === $mdConstant.KEY_CODE.LEFT_ARROW) {
changeAmount = -step;
} else if (vertical ? ev.keyCode === $mdConstant.KEY_CODE.UP_ARROW : ev.keyCode === $mdConstant.KEY_CODE.RIGHT_ARROW) {
changeAmount = step;
}
if (changeAmount) {
if (ev.metaKey || ev.ctrlKey || ev.altKey) {
changeAmount *= 4;
}
ev.preventDefault();
ev.stopPropagation();
scope.$evalAsync(function() {
setModelValue(ngModelCtrl.$viewValue + changeAmount);
});
}
}
function mouseDownListener() {
redrawTicks();
scope.mouseActive = true;
wrapper.removeClass('md-focused');
$timeout(function() {
scope.mouseActive = false;
}, 100);
}
function focusListener() {
if (scope.mouseActive === false) {
wrapper.addClass('md-focused');
}
}
function blurListener() {
wrapper.removeClass('md-focused');
element.removeClass('_md-active');
clearTicks();
}
/**
* ngModel setters and validators
*/
function setModelValue(value) {
ngModelCtrl.$setViewValue( minMaxValidator(stepValidator(value)) );
}
function ngModelRender() {
if (isNaN(ngModelCtrl.$viewValue)) {
ngModelCtrl.$viewValue = ngModelCtrl.$modelValue;
}
ngModelCtrl.$viewValue = minMaxValidator(ngModelCtrl.$viewValue);
var percent = (ngModelCtrl.$viewValue - min) / (max - min);
scope.modelValue = ngModelCtrl.$viewValue;
element.attr('aria-valuenow', ngModelCtrl.$viewValue);
setSliderPercent(percent);
thumbText.text( ngModelCtrl.$viewValue );
}
function minMaxValidator(value, minValue, maxValue) {
if (angular.isNumber(value)) {
minValue = angular.isNumber(minValue) ? minValue : min;
maxValue = angular.isNumber(maxValue) ? maxValue : max;
return Math.max(minValue, Math.min(maxValue, value));
}
}
function stepValidator(value) {
if (angular.isNumber(value)) {
var formattedValue = (Math.round((value - min) / step) * step + min);
formattedValue = (Math.round(formattedValue * Math.pow(10, round)) / Math.pow(10, round));
if (containerCtrl && containerCtrl.fitInputWidthToTextLength){
$mdUtil.debounce(function () {
containerCtrl.fitInputWidthToTextLength(formattedValue.toString().length);
}, 100)();
}
return formattedValue;
}
}
/**
* @param percent 0-1
*/
function setSliderPercent(percent) {
percent = clamp(percent);
var thumbPosition = (percent * 100) + '%';
thumbContainer.css(vertical ? 'bottom' : 'left', thumbPosition);
activeTrack.css(vertical ? 'height' : 'width', thumbPosition);
element.toggleClass('_md-min', percent === 0);
element.toggleClass('_md-max', percent === 1);
}
/**
* Slide listeners
*/
var isDragging = false;
function onPressDown(ev) {
if (isDisabled()) return;
element.addClass('_md-active');
element[0].focus();
refreshSliderDimensions();
var exactVal = percentToValue( positionToPercent( vertical ? ev.pointer.y : ev.pointer.x ));
var closestVal = minMaxValidator( stepValidator(exactVal) );
scope.$apply(function() {
setModelValue( closestVal );
setSliderPercent( valueToPercent(closestVal));
});
}
function onPressUp(ev) {
if (isDisabled()) return;
element.removeClass('_md-dragging');
var exactVal = percentToValue( positionToPercent( vertical ? ev.pointer.y : ev.pointer.x ));
var closestVal = minMaxValidator( stepValidator(exactVal) );
scope.$apply(function() {
setModelValue(closestVal);
ngModelRender();
});
}
function onDragStart(ev) {
if (isDisabled()) return;
isDragging = true;
ev.stopPropagation();
element.addClass('_md-dragging');
setSliderFromEvent(ev);
}
function onDrag(ev) {
if (!isDragging) return;
ev.stopPropagation();
setSliderFromEvent(ev);
}
function onDragEnd(ev) {
if (!isDragging) return;
ev.stopPropagation();
isDragging = false;
}
function setSliderFromEvent(ev) {
// While panning discrete, update only the
// visual positioning but not the model value.
if ( discrete ) adjustThumbPosition( vertical ? ev.pointer.y : ev.pointer.x );
else doSlide( vertical ? ev.pointer.y : ev.pointer.x );
}
/**
* Slide the UI by changing the model value
* @param x
*/
function doSlide( x ) {
scope.$evalAsync( function() {
setModelValue( percentToValue( positionToPercent(x) ));
});
}
/**
* Slide the UI without changing the model (while dragging/panning)
* @param x
*/
function adjustThumbPosition( x ) {
var exactVal = percentToValue( positionToPercent( x ));
var closestVal = minMaxValidator( stepValidator(exactVal) );
setSliderPercent( positionToPercent(x) );
thumbText.text( closestVal );
}
/**
* Clamps the value to be between 0 and 1.
* @param {number} value The value to clamp.
* @returns {number}
*/
function clamp(value) {
return Math.max(0, Math.min(value || 0, 1));
}
/**
* Convert position on slider to percentage value of offset from beginning...
* @param position
* @returns {number}
*/
function positionToPercent( position ) {
var offset = vertical ? sliderDimensions.top : sliderDimensions.left;
var size = vertical ? sliderDimensions.height : sliderDimensions.width;
var calc = (position - offset) / size;
return Math.max(0, Math.min(1, vertical ? 1 - calc : calc));
}
/**
* Convert percentage offset on slide to equivalent model value
* @param percent
* @returns {*}
*/
function percentToValue( percent ) {
return (min + percent * (max - min));
}
function valueToPercent( val ) {
return (val - min)/(max - min);
}
}
}
SliderDirective.$inject = ["$$rAF", "$window", "$mdAria", "$mdUtil", "$mdConstant", "$mdTheming", "$mdGesture", "$parse", "$log", "$timeout"];
ng.material.components.slider = angular.module("material.components.slider");
|
/* jshint node: true */
'use strict';
module.exports = {
name: 'ember-parse-adapter'
};
|
'use strict';
var hide = require('./_hide')
, redefine = require('./_redefine')
, fails = require('./_fails')
, defined = require('./_defined')
, wks = require('./_wks');
module.exports = function(KEY, length, exec){
var SYMBOL = wks(KEY)
, fns = exec(defined, SYMBOL, ''[KEY])
, strfn = fns[0]
, rxfn = fns[1];
if(fails(function(){
var O = {};
O[SYMBOL] = function(){ return 7; };
return ''[KEY](O) != 7;
})){
redefine(String.prototype, KEY, strfn);
hide(RegExp.prototype, SYMBOL, length == 2
// 21.2.5.8 RegExp.prototype[@@replace](string, replaceValue)
// 21.2.5.11 RegExp.prototype[@@split](string, limit)
? function(string, arg){ return rxfn.call(string, this, arg); }
// 21.2.5.6 RegExp.prototype[@@match](string)
// 21.2.5.9 RegExp.prototype[@@search](string)
: function(string){ return rxfn.call(string, this); }
);
}
};
|
// <time> element
// http://www.whatwg.org/specs/web-apps/current-work/multipage/rendering.html#the-time-element-0
// by Addy Osmani
Modernizr.addTest('time', 'valueAsDate' in document.createElement('time'));
|
'use strict';
var deferred = require('../../../deferred')
, reject = deferred.reject;
module.exports = function (t) {
var x = {}, y = {}, z = {}, e = new Error("Error");
return {
"Empty": {
"": function (a, d) {
t.call([])(function (result) {
a.deep(result, []);
}, a.never).done(d, d);
},
"Callback": function (a, d) {
t.call([], a.never)(function (result) {
a.deep(result, []);
}, a.never).done(d, d);
}
},
"One": {
"Value": {
"": function (a, d) {
t.call([x])(function (result) {
a.deep(result, [x]);
}, a.never).done(d, d);
},
"Callback": function (a, d) {
var list = [x];
t.call(list, function (arg, index, target) {
a(arg, x, "Argument");
a(index, 0, "Index");
a(target, list, "Target");
a(this, x, "Context");
return y;
}, x)(function (result) {
a.deep(result, [y]);
}, a.never).done(d, d);
}
},
"Promise": {
"": function (a, d) {
t.call([deferred(x)])(function (result) {
a.deep(result, [x]);
}, a.never).done(d, d);
},
"Callback": function (a, d) {
t.call([deferred(x)], function (arg) {
a(arg, x, "Argument");
return y;
})(function (result) {
a.deep(result, [y]);
}, a.never).done(d, d);
}
}
},
"Many": {
"No callback": {
"Error": function (a, d) {
t.call([x, y, deferred(x), reject(e), z])(a.never, function (res) {
a(res, e);
d();
});
},
"Values & Promises": function (a, d) {
t.call([x, y, deferred(x), z, deferred(y)])(function (res) {
a.deep(res, [x, y, x, z, y]);
}, a.never).done(d, d);
},
"Error promise": function (a, d) {
t.call([x, y, deferred(e), z, deferred(y)])(a.never, function (res) {
a(res, e);
}, a.never).done(d, d);
}
},
"Callback": {
"Error": function (a, d) {
var count = 0;
t.call([x, y, deferred(x), z], function () {
if (count++) {
a.never();
}
throw e;
})(a.never, function (res) {
a(res, e);
}).done(d, d);
},
"Error via input": function (a, d) {
t.call([x, y, deferred(e), z], function () {
return x;
})(a.never, function (res) {
a(res, e);
}).done(d, d);
},
"Values & Promises": function (a, d) {
t.call([1, deferred(2), 3, deferred(4), 5], function (val) {
return val * val;
})(function (res) {
a.deep(res, [1, 4, 9, 16, 25]);
}, a.never).done(d, d);
},
"Values & Promises, through promise": function (a, d) {
t.call([1, deferred(2), 3, deferred(4), 5], function (val) {
return deferred(val * val);
})(function (res) {
a.deep(res, [1, 4, 9, 16, 25]);
}, a.never).done(d, d);
}
}
},
"Resolve not via then": function (a) {
// With v0.3.0 we introduced a bug - resolve of map in some cases was
// called within callback passed to then, therefore any following errors
// in given event loop were silent - this test makes sure it's not the
// case anymore
var d = deferred();
t.call([d.promise]).done(function () {
throw new Error("ERROR");
});
a.throws(d.resolve);
},
"Return rejected promise in callback": function (a) {
var e = new Error("Some error");
t.call([1, 2], function () {
return reject(e);
}).done(a.never, function (err) {
a(err, e);
});
}
};
};
|
var fs = require('fs');
var path = require('path');
var chalk = require('chalk');
var parse = require('react-docgen').parse;
var chokidar = require('chokidar');
var paths = {
examples: path.join(__dirname, '../src', 'docs', 'examples'),
components: path.join(__dirname, '../src', 'components'),
output: path.join(__dirname, '../config', 'componentData.js')
};
const enableWatchMode = process.argv.slice(2) == '--watch';
if (enableWatchMode) {
// Regenerate component metadata when components or examples change.
chokidar.watch([paths.examples, paths.components]).on('change', function(event, path) {
generate(paths);
});
} else {
// Generate component metadata
generate(paths);
}
function generate(paths) {
var errors = [];
var componentData = getDirectories(paths.components).map(function(componentName) {
try {
return getComponentData(paths, componentName)
} catch(error) {
errors.push('An error occurred while attempting to generate metadata for ' + componentName + '. ' + error);
}
});
writeFile(paths.output, "module.exports = " + JSON.stringify(errors.length ? errors : componentData));
}
function getComponentData(paths, componentName) {
var content = readFile(path.join(paths.components, componentName, componentName + '.js'));
var info = parse(content);
return {
name: componentName,
description: info.description,
props: info.props,
code: content,
examples: getExampleData(paths.examples, componentName)
}
}
function getExampleData(examplesPath, componentName) {
var examples = getExampleFiles(examplesPath, componentName);
return examples.map(function(file) {
var filePath = path.join(examplesPath, componentName, file)
var content = readFile(filePath)
var info = parse(content);
return {
// By convention, component name should match the filename.
// So remove the .js extension to get the component name.
name: file.slice(0, -3),
description: info.description,
code: content
};
});
}
function getExampleFiles(examplesPath, componentName) {
var exampleFiles = [];
try {
exampleFiles = getFiles(path.join(examplesPath, componentName));
} catch(error) {
console.log(chalk.red(`No examples found for ${componentName}.`));
}
return exampleFiles;
}
function getDirectories(filepath) {
return fs.readdirSync(filepath).filter(function(file) {
return fs.statSync(path.join(filepath, file)).isDirectory();
});
}
function getFiles(filepath) {
return fs.readdirSync(filepath).filter(function(file) {
return fs.statSync(path.join(filepath, file)).isFile();
});
}
function writeFile(filepath, content) {
fs.writeFile(filepath, content, function (err) {
err ? console.log(chalk.red(err)) : console.log(chalk.green("Component data saved."));
});
}
function readFile(filePath) {
return fs.readFileSync(filePath, 'utf-8');
}
|
(function (Flow, FustyFlow, window) {
'use strict';
var fustyFlowFactory = function (opts) {
var flow = new Flow(opts);
if (flow.support) {
return flow;
}
return new FustyFlow(opts);
}
window.fustyFlowFactory = fustyFlowFactory;
})(window.Flow, window.FustyFlow, window);
|
// 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 2009 Google Inc. All Rights Reserved.
/**
* @fileoverview Functions for formatting relative dates. Such as "3 days ago"
* "3 hours ago", "14 minutes ago", "12 days ago", "Today", "Yesterday".
*
*/
goog.provide('goog.date.relative');
goog.require('goog.i18n.DateTimeFormat');
/**
* Number of milliseconds in a minute.
* @type {number}
* @private
*/
goog.date.relative.MINUTE_MS_ = 60000;
/**
* Number of milliseconds in a day.
* @type {number}
* @private
*/
goog.date.relative.DAY_MS_ = 86400000;
/**
* Enumeration used to identify time units internally.
* @enum {number}
* @private
*/
goog.date.relative.Unit_ = {
MINUTES: 0,
HOURS: 1,
DAYS: 2
};
/**
* Full date formatter.
* @type {goog.i18n.DateTimeFormat}
* @private
*/
goog.date.relative.fullDateFormatter_;
/**
* Short time formatter.
* @type {goog.i18n.DateTimeFormat}
* @private
*/
goog.date.relative.shortTimeFormatter_;
/**
* Month-date formatter.
* @type {goog.i18n.DateTimeFormat}
* @private
*/
goog.date.relative.monthDateFormatter_;
/**
* Returns a date in month format, e.g. Mar 15.
* @param {Date} date The date object.
* @return {string} The formatted string.
* @private
*/
goog.date.relative.formatMonth_ = function(date) {
if (!goog.date.relative.monthDateFormatter_) {
goog.date.relative.monthDateFormatter_ =
new goog.i18n.DateTimeFormat('MMM dd');
}
return goog.date.relative.monthDateFormatter_.format(date);
};
/**
* Returns a date in short-time format, e.g. 2:50 PM.
* @param {Date} date The date object.
* @return {string} The formatted string.
* @private
*/
goog.date.relative.formatShortTime_ = function(date) {
if (!goog.date.relative.shortTimeFormatter_) {
goog.date.relative.shortTimeFormatter_ = new goog.i18n.DateTimeFormat(
goog.i18n.DateTimeFormat.Format.SHORT_TIME);
}
return goog.date.relative.shortTimeFormatter_.format(date);
};
/**
* Returns a date in full date format, e.g. Tuesday, March 24, 2009.
* @param {Date} date The date object.
* @return {string} The formatted string.
* @private
*/
goog.date.relative.formatFullDate_ = function(date) {
if (!goog.date.relative.fullDateFormatter_) {
goog.date.relative.fullDateFormatter_ = new goog.i18n.DateTimeFormat(
goog.i18n.DateTimeFormat.Format.FULL_DATE);
}
return goog.date.relative.fullDateFormatter_.format(date);
};
/**
* Accepts a timestamp in milliseconds and outputs a relative time in the form
* of "1 hour ago", "1 day ago", "in 1 hour", "in 2 days" etc. If the date
* delta is over 2 weeks, then the output string will be empty.
* @param {number} dateMs Date in milliseconds.
* @return {string} The formatted date.
*/
goog.date.relative.format = function(dateMs) {
var now = goog.now();
var delta = Math.floor((now - dateMs) / goog.date.relative.MINUTE_MS_);
var future = false;
if (delta < 0) {
future = true;
delta *= -1;
}
if (delta < 60) { // Minutes.
return goog.date.relative.getMessage_(
delta, future, goog.date.relative.Unit_.MINUTES);
} else {
delta = Math.floor(delta / 60);
if (delta < 24) { // Hours.
return goog.date.relative.getMessage_(
delta, future, goog.date.relative.Unit_.HOURS);
} else {
// Timezone offset is in minutes. We pass goog.now so that we can easily
// unit test this, the JSCompiler will optimize it away for us.
var offset = new Date(goog.now()).getTimezoneOffset() *
goog.date.relative.MINUTE_MS_;
// Convert to days ago.
delta = Math.floor((now + offset) / goog.date.relative.DAY_MS_) -
Math.floor((dateMs + offset) / goog.date.relative.DAY_MS_);
if (future) {
delta *= -1;
}
// Uses days for less than 2-weeks.
if (delta < 14) {
return goog.date.relative.getMessage_(
delta, future, goog.date.relative.Unit_.DAYS);
} else {
// For messages older than 2 weeks do not show anything. The client
// should decide the date format to show.
return '';
}
}
}
};
/**
* Accepts a timestamp in milliseconds and outputs a relative time in the form
* of "1 hour ago", "1 day ago". All future times will be returned as 0 minutes
* ago.
*
* This is provided for compatibility with users of the previous incarnation of
* the above {@see #format} method who relied on it protecting against
* future dates.
*
* @param {number} dateMs Date in milliseconds.
* @return {string} The formatted date.
*/
goog.date.relative.formatPast = function(dateMs) {
var now = goog.now();
if (now < dateMs) {
dateMs = now;
}
return goog.date.relative.format(dateMs);
};
/**
* Accepts a timestamp in milliseconds and outputs a relative day. i.e. "Today",
* "Yesterday" or "Sept 15".
*
* @param {number} dateMs Date in milliseconds.
* @return {string} The formatted date.
*/
goog.date.relative.formatDay = function(dateMs) {
var message;
var today = new Date(goog.now());
today.setHours(0);
today.setMinutes(0);
today.setSeconds(0);
today.setMilliseconds(0);
var yesterday = new Date(today.getTime() - goog.date.relative.DAY_MS_);
if (today.getTime() < dateMs) {
/** @desc Today. */
var MSG_TODAY = goog.getMsg('Today');
message = MSG_TODAY;
} else if (yesterday.getTime() < dateMs) {
/** @desc Yesterday. */
var MSG_YESTERDAY = goog.getMsg('Yesterday');
message = MSG_YESTERDAY;
} else {
message = goog.date.relative.formatMonth_(new Date(dateMs));
}
return message;
};
/**
* Formats a date, adding the relative date in parenthesis. If the date is less
* than 24 hours then the time will be printed, otherwise the full-date will be
* used. Examples:
* 2:20 PM (1 minute ago)
* Monday, February 27, 2009 (4 days ago)
* Tuesday, March 20, 2005 // Too long ago for a relative date.
*
* @param {Date} date A date object.
* @param {string} opt_shortTimeMsg An optional short time message can be
* provided if available, so that it's not recalculated in this function.
* @param {string} opt_fullDateMsg An optional date message can be
* provided if available, so that it's not recalculated in this function.
* @return {string} The date string in the above form.
*/
goog.date.relative.getDateString = function(
date, opt_shortTimeMsg, opt_fullDateMsg) {
return goog.date.relative.getDateString_(
date, goog.date.relative.format, opt_shortTimeMsg, opt_fullDateMsg)
};
/**
* Formats a date, adding the relative date in parenthesis. Functions the same
* as #getDateString but ensures that the date is always seen to be in the past.
* If the date is in the future, it will be shown as 0 minutes ago.
*
* This is provided for compatibility with users of the previous incarnation of
* the above {@see #getDateString} method who relied on it protecting against
* future dates.
*
* @param {Date} date A timestamp or date object.
* @param {string} opt_shortTimeMsg An optional short time message can be
* provided if available, so that it's not recalculated in this function.
* @param {string} opt_fullDateMsg An optional date message can be
* provided if available, so that it's not recalculated in this function.
* @return {string} The date string in the above form.
*/
goog.date.relative.getPastDateString = function(
date, opt_shortTimeMsg, opt_fullDateMsg) {
return goog.date.relative.getDateString_(
date, goog.date.relative.formatPast, opt_shortTimeMsg, opt_fullDateMsg)
};
/**
* Formats a date, adding the relative date in parenthesis. If the date is less
* than 24 hours then the time will be printed, otherwise the full-date will be
* used. Examples:
* 2:20 PM (1 minute ago)
* Monday, February 27, 2009 (4 days ago)
* Tuesday, March 20, 2005 // Too long ago for a relative date.
*
* @param {Date} date A timestamp or date object.
* @param {function(number) : string} relativeFormatter Function to use when
* formatting the relative date.
* @param {string} opt_shortTimeMsg An optional short time message can be
* provided if available, so that it's not recalculated in this function.
* @param {string} opt_fullDateMsg An optional date message can be
* provided if available, so that it's not recalculated in this function.
* @return {string} The date string in the above form.
* @private
*/
goog.date.relative.getDateString_ = function(
date, relativeFormatter, opt_shortTimeMsg, opt_fullDateMsg) {
var dateMs = date.getTime();
var relativeDate = relativeFormatter(dateMs);
if (relativeDate) {
relativeDate = ' (' + relativeDate + ')';
}
var delta = Math.floor((goog.now() - dateMs) / goog.date.relative.MINUTE_MS_);
if (delta < 60 * 24) {
return (opt_shortTimeMsg || goog.date.relative.formatShortTime_(date)) +
relativeDate;
} else {
return (opt_fullDateMsg || goog.date.relative.formatFullDate_(date)) +
relativeDate;
}
};
/**
* Gets a localized relative date string for a given delta and unit.
* @param {number} delta Number of minutes/hours/days.
* @param {boolean} future Whether the delta is in the future.
* @param {goog.date.relative.Unit_} unit The units the delta is in.
* @return {string} The message.
* @private
*/
goog.date.relative.getMessage_ = function(delta, future, unit) {
if (!future && unit == goog.date.relative.Unit_.MINUTES) {
/**
* @desc Relative date indicating how many minutes ago something happened
* (singular).
*/
var MSG_MINUTES_AGO_SINGULAR =
goog.getMsg('{$num} minute ago', {'num' : delta});
/**
* @desc Relative date indicating how many minutes ago something happened
* (plural).
*/
var MSG_MINUTES_AGO_PLURAL =
goog.getMsg('{$num} minutes ago', {'num' : delta});
return delta == 1 ? MSG_MINUTES_AGO_SINGULAR : MSG_MINUTES_AGO_PLURAL;
} else if (future && unit == goog.date.relative.Unit_.MINUTES) {
/**
* @desc Relative date indicating in how many minutes something happens
* (singular).
*/
var MSG_IN_MINUTES_SINGULAR =
goog.getMsg('in {$num} minute', {'num' : delta});
/**
* @desc Relative date indicating in how many minutes something happens
* (plural).
*/
var MSG_IN_MINUTES_PLURAL =
goog.getMsg('in {$num} minutes', {'num' : delta});
return delta == 1 ? MSG_IN_MINUTES_SINGULAR : MSG_IN_MINUTES_PLURAL;
} else if (!future && unit == goog.date.relative.Unit_.HOURS) {
/**
* @desc Relative date indicating how many hours ago something happened
* (singular).
*/
var MSG_HOURS_AGO_SINGULAR =
goog.getMsg('{$num} hour ago', {'num' : delta});
/**
* @desc Relative date indicating how many hours ago something happened
* (plural).
*/
var MSG_HOURS_AGO_PLURAL = goog.getMsg('{$num} hours ago', {'num' : delta});
return delta == 1 ? MSG_HOURS_AGO_SINGULAR : MSG_HOURS_AGO_PLURAL;
} else if (future && unit == goog.date.relative.Unit_.HOURS) {
/**
* @desc Relative date indicating in how many hours something happens
* (singular).
*/
var MSG_IN_HOURS_SINGULAR = goog.getMsg('in {$num} hour', {'num' : delta});
/**
* @desc Relative date indicating in how many hours something happens
* (plural).
*/
var MSG_IN_HOURS_PLURAL = goog.getMsg('in {$num} hours', {'num' : delta});
return delta == 1 ? MSG_IN_HOURS_SINGULAR : MSG_IN_HOURS_PLURAL;
} else if (!future && unit == goog.date.relative.Unit_.DAYS) {
/**
* @desc Relative date indicating how many days ago something happened
* (singular).
*/
var MSG_DAYS_AGO_SINGULAR = goog.getMsg('{$num} day ago', {'num' : delta});
/**
* @desc Relative date indicating how many days ago something happened
* (plural).
*/
var MSG_DAYS_AGO_PLURAL = goog.getMsg('{$num} days ago', {'num' : delta});
return delta == 1 ? MSG_DAYS_AGO_SINGULAR : MSG_DAYS_AGO_PLURAL;
} else if (future && unit == goog.date.relative.Unit_.DAYS) {
/**
* @desc Relative date indicating in how many days something happens
* (singular).
*/
var MSG_IN_DAYS_SINGULAR = goog.getMsg('in {$num} day', {'num' : delta});
/**
* @desc Relative date indicating in how many days something happens
* (plural).
*/
var MSG_IN_DAYS_PLURAL = goog.getMsg('in {$num} days', {'num' : delta});
return delta == 1 ? MSG_IN_DAYS_SINGULAR : MSG_IN_DAYS_PLURAL;
} else {
return '';
}
};
|
module.exports = require('./lib/exif');
|
'use strict';
/* global VALID_CLASS: true,
INVALID_CLASS: true,
PRISTINE_CLASS: true,
DIRTY_CLASS: true,
UNTOUCHED_CLASS: true,
TOUCHED_CLASS: true,
*/
// Regex code is obtained from SO: https://stackoverflow.com/questions/3143070/javascript-regex-iso-datetime#answer-3143231
var ISO_DATE_REGEXP = /\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z)/;
var URL_REGEXP = /^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/;
var EMAIL_REGEXP = /^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i;
var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))\s*$/;
var DATE_REGEXP = /^(\d{4})-(\d{2})-(\d{2})$/;
var DATETIMELOCAL_REGEXP = /^(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
var WEEK_REGEXP = /^(\d{4})-W(\d\d)$/;
var MONTH_REGEXP = /^(\d{4})-(\d\d)$/;
var TIME_REGEXP = /^(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
var DEFAULT_REGEXP = /(\s+|^)default(\s+|$)/;
var $ngModelMinErr = new minErr('ngModel');
var inputType = {
/**
* @ngdoc input
* @name input[text]
*
* @description
* Standard HTML text input with angular data binding, inherited by most of the `input` elements.
*
* *NOTE* Not every feature offered is available for all input types.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} required Adds `required` validation error key if the value is not entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength.
* @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
* RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
* patterns defined as scope expressions.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
* @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
* This parameter is ignored for input[type=password] controls, which will never trim the
* input.
*
* @example
<example name="text-input-directive" module="textInputExample">
<file name="index.html">
<script>
angular.module('textInputExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.text = 'guest';
$scope.word = /^\s*\w*\s*$/;
}]);
</script>
<form name="myForm" ng-controller="ExampleController">
Single word: <input type="text" name="input" ng-model="text"
ng-pattern="word" required ng-trim="false">
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.pattern">
Single word only!</span>
<tt>text = {{text}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
</form>
</file>
<file name="protractor.js" type="protractor">
var text = element(by.binding('text'));
var valid = element(by.binding('myForm.input.$valid'));
var input = element(by.model('text'));
it('should initialize to model', function() {
expect(text.getText()).toContain('guest');
expect(valid.getText()).toContain('true');
});
it('should be invalid if empty', function() {
input.clear();
input.sendKeys('');
expect(text.getText()).toEqual('text =');
expect(valid.getText()).toContain('false');
});
it('should be invalid if multi word', function() {
input.clear();
input.sendKeys('hello world');
expect(valid.getText()).toContain('false');
});
</file>
</example>
*/
'text': textInputType,
/**
* @ngdoc input
* @name input[date]
*
* @description
* Input with date validation and transformation. In browsers that do not yet support
* the HTML5 date input, a text element will be used. In that case, text must be entered in a valid ISO-8601
* date format (yyyy-MM-dd), for example: `2009-01-06`. Since many
* modern browsers do not yet support this input type, it is important to provide cues to users on the
* expected input format via a placeholder or label. The model must always be a Date object.
*
* The timezone to be used to read/write the `Date` instance in the model can be defined using
* {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
* valid ISO date string (yyyy-MM-dd).
* @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
* a valid ISO date string (yyyy-MM-dd).
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<example name="date-input-directive" module="dateInputExample">
<file name="index.html">
<script>
angular.module('dateInputExample', [])
.controller('DateController', ['$scope', function($scope) {
$scope.value = new Date(2013, 9, 22);
}]);
</script>
<form name="myForm" ng-controller="DateController as dateCtrl">
Pick a date in 2013:
<input type="date" id="exampleInput" name="input" ng-model="value"
placeholder="yyyy-MM-dd" min="2013-01-01" max="2013-12-31" required />
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.date">
Not a valid date!</span>
<tt>value = {{value | date: "yyyy-MM-dd"}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
</form>
</file>
<file name="protractor.js" type="protractor">
var value = element(by.binding('value | date: "yyyy-MM-dd"'));
var valid = element(by.binding('myForm.input.$valid'));
var input = element(by.model('value'));
// currently protractor/webdriver does not support
// sending keys to all known HTML5 input controls
// for various browsers (see https://github.com/angular/protractor/issues/562).
function setInput(val) {
// set the value of the element and force validation.
var scr = "var ipt = document.getElementById('exampleInput'); " +
"ipt.value = '" + val + "';" +
"angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
browser.executeScript(scr);
}
it('should initialize to model', function() {
expect(value.getText()).toContain('2013-10-22');
expect(valid.getText()).toContain('myForm.input.$valid = true');
});
it('should be invalid if empty', function() {
setInput('');
expect(value.getText()).toEqual('value =');
expect(valid.getText()).toContain('myForm.input.$valid = false');
});
it('should be invalid if over max', function() {
setInput('2015-01-01');
expect(value.getText()).toContain('');
expect(valid.getText()).toContain('myForm.input.$valid = false');
});
</file>
</example>
*/
'date': createDateInputType('date', DATE_REGEXP,
createDateParser(DATE_REGEXP, ['yyyy', 'MM', 'dd']),
'yyyy-MM-dd'),
/**
* @ngdoc input
* @name input[dateTimeLocal]
*
* @description
* Input with datetime validation and transformation. In browsers that do not yet support
* the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
* local datetime format (yyyy-MM-ddTHH:mm:ss), for example: `2010-12-28T14:57:00`. The model must be a Date object.
*
* The timezone to be used to read/write the `Date` instance in the model can be defined using
* {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
* valid ISO datetime format (yyyy-MM-ddTHH:mm:ss).
* @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
* a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss).
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<example name="datetimelocal-input-directive" module="dateExample">
<file name="index.html">
<script>
angular.module('dateExample', [])
.controller('DateController', ['$scope', function($scope) {
$scope.value = new Date(2010, 11, 28, 14, 57);
}]);
</script>
<form name="myForm" ng-controller="DateController as dateCtrl">
Pick a date between in 2013:
<input type="datetime-local" id="exampleInput" name="input" ng-model="value"
placeholder="yyyy-MM-ddTHH:mm:ss" min="2001-01-01T00:00:00" max="2013-12-31T00:00:00" required />
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.datetimelocal">
Not a valid date!</span>
<tt>value = {{value | date: "yyyy-MM-ddTHH:mm:ss"}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
</form>
</file>
<file name="protractor.js" type="protractor">
var value = element(by.binding('value | date: "yyyy-MM-ddTHH:mm:ss"'));
var valid = element(by.binding('myForm.input.$valid'));
var input = element(by.model('value'));
// currently protractor/webdriver does not support
// sending keys to all known HTML5 input controls
// for various browsers (https://github.com/angular/protractor/issues/562).
function setInput(val) {
// set the value of the element and force validation.
var scr = "var ipt = document.getElementById('exampleInput'); " +
"ipt.value = '" + val + "';" +
"angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
browser.executeScript(scr);
}
it('should initialize to model', function() {
expect(value.getText()).toContain('2010-12-28T14:57:00');
expect(valid.getText()).toContain('myForm.input.$valid = true');
});
it('should be invalid if empty', function() {
setInput('');
expect(value.getText()).toEqual('value =');
expect(valid.getText()).toContain('myForm.input.$valid = false');
});
it('should be invalid if over max', function() {
setInput('2015-01-01T23:59:00');
expect(value.getText()).toContain('');
expect(valid.getText()).toContain('myForm.input.$valid = false');
});
</file>
</example>
*/
'datetime-local': createDateInputType('datetimelocal', DATETIMELOCAL_REGEXP,
createDateParser(DATETIMELOCAL_REGEXP, ['yyyy', 'MM', 'dd', 'HH', 'mm', 'ss', 'sss']),
'yyyy-MM-ddTHH:mm:ss.sss'),
/**
* @ngdoc input
* @name input[time]
*
* @description
* Input with time validation and transformation. In browsers that do not yet support
* the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
* local time format (HH:mm:ss), for example: `14:57:00`. Model must be a Date object. This binding will always output a
* Date object to the model of January 1, 1970, or local date `new Date(1970, 0, 1, HH, mm, ss)`.
*
* The timezone to be used to read/write the `Date` instance in the model can be defined using
* {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
* valid ISO time format (HH:mm:ss).
* @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be a
* valid ISO time format (HH:mm:ss).
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<example name="time-input-directive" module="timeExample">
<file name="index.html">
<script>
angular.module('timeExample', [])
.controller('DateController', ['$scope', function($scope) {
$scope.value = new Date(1970, 0, 1, 14, 57, 0);
}]);
</script>
<form name="myForm" ng-controller="DateController as dateCtrl">
Pick a between 8am and 5pm:
<input type="time" id="exampleInput" name="input" ng-model="value"
placeholder="HH:mm:ss" min="08:00:00" max="17:00:00" required />
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.time">
Not a valid date!</span>
<tt>value = {{value | date: "HH:mm:ss"}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
</form>
</file>
<file name="protractor.js" type="protractor">
var value = element(by.binding('value | date: "HH:mm:ss"'));
var valid = element(by.binding('myForm.input.$valid'));
var input = element(by.model('value'));
// currently protractor/webdriver does not support
// sending keys to all known HTML5 input controls
// for various browsers (https://github.com/angular/protractor/issues/562).
function setInput(val) {
// set the value of the element and force validation.
var scr = "var ipt = document.getElementById('exampleInput'); " +
"ipt.value = '" + val + "';" +
"angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
browser.executeScript(scr);
}
it('should initialize to model', function() {
expect(value.getText()).toContain('14:57:00');
expect(valid.getText()).toContain('myForm.input.$valid = true');
});
it('should be invalid if empty', function() {
setInput('');
expect(value.getText()).toEqual('value =');
expect(valid.getText()).toContain('myForm.input.$valid = false');
});
it('should be invalid if over max', function() {
setInput('23:59:00');
expect(value.getText()).toContain('');
expect(valid.getText()).toContain('myForm.input.$valid = false');
});
</file>
</example>
*/
'time': createDateInputType('time', TIME_REGEXP,
createDateParser(TIME_REGEXP, ['HH', 'mm', 'ss', 'sss']),
'HH:mm:ss.sss'),
/**
* @ngdoc input
* @name input[week]
*
* @description
* Input with week-of-the-year validation and transformation to Date. In browsers that do not yet support
* the HTML5 week input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
* week format (yyyy-W##), for example: `2013-W02`. The model must always be a Date object.
*
* The timezone to be used to read/write the `Date` instance in the model can be defined using
* {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
* valid ISO week format (yyyy-W##).
* @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
* a valid ISO week format (yyyy-W##).
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<example name="week-input-directive" module="weekExample">
<file name="index.html">
<script>
angular.module('weekExample', [])
.controller('DateController', ['$scope', function($scope) {
$scope.value = new Date(2013, 0, 3);
}]);
</script>
<form name="myForm" ng-controller="DateController as dateCtrl">
Pick a date between in 2013:
<input id="exampleInput" type="week" name="input" ng-model="value"
placeholder="YYYY-W##" min="2012-W32" max="2013-W52" required />
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.week">
Not a valid date!</span>
<tt>value = {{value | date: "yyyy-Www"}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
</form>
</file>
<file name="protractor.js" type="protractor">
var value = element(by.binding('value | date: "yyyy-Www"'));
var valid = element(by.binding('myForm.input.$valid'));
var input = element(by.model('value'));
// currently protractor/webdriver does not support
// sending keys to all known HTML5 input controls
// for various browsers (https://github.com/angular/protractor/issues/562).
function setInput(val) {
// set the value of the element and force validation.
var scr = "var ipt = document.getElementById('exampleInput'); " +
"ipt.value = '" + val + "';" +
"angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
browser.executeScript(scr);
}
it('should initialize to model', function() {
expect(value.getText()).toContain('2013-W01');
expect(valid.getText()).toContain('myForm.input.$valid = true');
});
it('should be invalid if empty', function() {
setInput('');
expect(value.getText()).toEqual('value =');
expect(valid.getText()).toContain('myForm.input.$valid = false');
});
it('should be invalid if over max', function() {
setInput('2015-W01');
expect(value.getText()).toContain('');
expect(valid.getText()).toContain('myForm.input.$valid = false');
});
</file>
</example>
*/
'week': createDateInputType('week', WEEK_REGEXP, weekParser, 'yyyy-Www'),
/**
* @ngdoc input
* @name input[month]
*
* @description
* Input with month validation and transformation. In browsers that do not yet support
* the HTML5 month input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
* month format (yyyy-MM), for example: `2009-01`. The model must always be a Date object. In the event the model is
* not set to the first of the month, the first of that model's month is assumed.
*
* The timezone to be used to read/write the `Date` instance in the model can be defined using
* {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be
* a valid ISO month format (yyyy-MM).
* @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must
* be a valid ISO month format (yyyy-MM).
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<example name="month-input-directive" module="monthExample">
<file name="index.html">
<script>
angular.module('monthExample', [])
.controller('DateController', ['$scope', function($scope) {
$scope.value = new Date(2013, 9, 1);
}]);
</script>
<form name="myForm" ng-controller="DateController as dateCtrl">
Pick a month int 2013:
<input id="exampleInput" type="month" name="input" ng-model="value"
placeholder="yyyy-MM" min="2013-01" max="2013-12" required />
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.month">
Not a valid month!</span>
<tt>value = {{value | date: "yyyy-MM"}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
</form>
</file>
<file name="protractor.js" type="protractor">
var value = element(by.binding('value | date: "yyyy-MM"'));
var valid = element(by.binding('myForm.input.$valid'));
var input = element(by.model('value'));
// currently protractor/webdriver does not support
// sending keys to all known HTML5 input controls
// for various browsers (https://github.com/angular/protractor/issues/562).
function setInput(val) {
// set the value of the element and force validation.
var scr = "var ipt = document.getElementById('exampleInput'); " +
"ipt.value = '" + val + "';" +
"angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
browser.executeScript(scr);
}
it('should initialize to model', function() {
expect(value.getText()).toContain('2013-10');
expect(valid.getText()).toContain('myForm.input.$valid = true');
});
it('should be invalid if empty', function() {
setInput('');
expect(value.getText()).toEqual('value =');
expect(valid.getText()).toContain('myForm.input.$valid = false');
});
it('should be invalid if over max', function() {
setInput('2015-01');
expect(value.getText()).toContain('');
expect(valid.getText()).toContain('myForm.input.$valid = false');
});
</file>
</example>
*/
'month': createDateInputType('month', MONTH_REGEXP,
createDateParser(MONTH_REGEXP, ['yyyy', 'MM']),
'yyyy-MM'),
/**
* @ngdoc input
* @name input[number]
*
* @description
* Text input with number validation and transformation. Sets the `number` validation
* error if not a valid number.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
* @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength.
* @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
* RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
* patterns defined as scope expressions.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<example name="number-input-directive" module="numberExample">
<file name="index.html">
<script>
angular.module('numberExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.value = 12;
}]);
</script>
<form name="myForm" ng-controller="ExampleController">
Number: <input type="number" name="input" ng-model="value"
min="0" max="99" required>
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.number">
Not valid number!</span>
<tt>value = {{value}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
</form>
</file>
<file name="protractor.js" type="protractor">
var value = element(by.binding('value'));
var valid = element(by.binding('myForm.input.$valid'));
var input = element(by.model('value'));
it('should initialize to model', function() {
expect(value.getText()).toContain('12');
expect(valid.getText()).toContain('true');
});
it('should be invalid if empty', function() {
input.clear();
input.sendKeys('');
expect(value.getText()).toEqual('value =');
expect(valid.getText()).toContain('false');
});
it('should be invalid if over max', function() {
input.clear();
input.sendKeys('123');
expect(value.getText()).toEqual('value =');
expect(valid.getText()).toContain('false');
});
</file>
</example>
*/
'number': numberInputType,
/**
* @ngdoc input
* @name input[url]
*
* @description
* Text input with URL validation. Sets the `url` validation error key if the content is not a
* valid URL.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength.
* @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
* RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
* patterns defined as scope expressions.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<example name="url-input-directive" module="urlExample">
<file name="index.html">
<script>
angular.module('urlExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.text = 'http://google.com';
}]);
</script>
<form name="myForm" ng-controller="ExampleController">
URL: <input type="url" name="input" ng-model="text" required>
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.url">
Not valid url!</span>
<tt>text = {{text}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
<tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/>
</form>
</file>
<file name="protractor.js" type="protractor">
var text = element(by.binding('text'));
var valid = element(by.binding('myForm.input.$valid'));
var input = element(by.model('text'));
it('should initialize to model', function() {
expect(text.getText()).toContain('http://google.com');
expect(valid.getText()).toContain('true');
});
it('should be invalid if empty', function() {
input.clear();
input.sendKeys('');
expect(text.getText()).toEqual('text =');
expect(valid.getText()).toContain('false');
});
it('should be invalid if not url', function() {
input.clear();
input.sendKeys('box');
expect(valid.getText()).toContain('false');
});
</file>
</example>
*/
'url': urlInputType,
/**
* @ngdoc input
* @name input[email]
*
* @description
* Text input with email validation. Sets the `email` validation error key if not a valid email
* address.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength.
* @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
* RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
* patterns defined as scope expressions.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<example name="email-input-directive" module="emailExample">
<file name="index.html">
<script>
angular.module('emailExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.text = 'me@example.com';
}]);
</script>
<form name="myForm" ng-controller="ExampleController">
Email: <input type="email" name="input" ng-model="text" required>
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.email">
Not valid email!</span>
<tt>text = {{text}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
<tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>
</form>
</file>
<file name="protractor.js" type="protractor">
var text = element(by.binding('text'));
var valid = element(by.binding('myForm.input.$valid'));
var input = element(by.model('text'));
it('should initialize to model', function() {
expect(text.getText()).toContain('me@example.com');
expect(valid.getText()).toContain('true');
});
it('should be invalid if empty', function() {
input.clear();
input.sendKeys('');
expect(text.getText()).toEqual('text =');
expect(valid.getText()).toContain('false');
});
it('should be invalid if not email', function() {
input.clear();
input.sendKeys('xxx');
expect(valid.getText()).toContain('false');
});
</file>
</example>
*/
'email': emailInputType,
/**
* @ngdoc input
* @name input[radio]
*
* @description
* HTML radio button.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string} value The value to which the expression should be set when selected.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
* @param {string} ngValue Angular expression which sets the value to which the expression should
* be set when selected.
*
* @example
<example name="radio-input-directive" module="radioExample">
<file name="index.html">
<script>
angular.module('radioExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.color = 'blue';
$scope.specialValue = {
"id": "12345",
"value": "green"
};
}]);
</script>
<form name="myForm" ng-controller="ExampleController">
<input type="radio" ng-model="color" value="red"> Red <br/>
<input type="radio" ng-model="color" ng-value="specialValue"> Green <br/>
<input type="radio" ng-model="color" value="blue"> Blue <br/>
<tt>color = {{color | json}}</tt><br/>
</form>
Note that `ng-value="specialValue"` sets radio item's value to be the value of `$scope.specialValue`.
</file>
<file name="protractor.js" type="protractor">
it('should change state', function() {
var color = element(by.binding('color'));
expect(color.getText()).toContain('blue');
element.all(by.model('color')).get(0).click();
expect(color.getText()).toContain('red');
});
</file>
</example>
*/
'radio': radioInputType,
/**
* @ngdoc input
* @name input[checkbox]
*
* @description
* HTML checkbox.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {expression=} ngTrueValue The value to which the expression should be set when selected.
* @param {expression=} ngFalseValue The value to which the expression should be set when not selected.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<example name="checkbox-input-directive" module="checkboxExample">
<file name="index.html">
<script>
angular.module('checkboxExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.value1 = true;
$scope.value2 = 'YES'
}]);
</script>
<form name="myForm" ng-controller="ExampleController">
Value1: <input type="checkbox" ng-model="value1"> <br/>
Value2: <input type="checkbox" ng-model="value2"
ng-true-value="'YES'" ng-false-value="'NO'"> <br/>
<tt>value1 = {{value1}}</tt><br/>
<tt>value2 = {{value2}}</tt><br/>
</form>
</file>
<file name="protractor.js" type="protractor">
it('should change state', function() {
var value1 = element(by.binding('value1'));
var value2 = element(by.binding('value2'));
expect(value1.getText()).toContain('true');
expect(value2.getText()).toContain('YES');
element(by.model('value1')).click();
element(by.model('value2')).click();
expect(value1.getText()).toContain('false');
expect(value2.getText()).toContain('NO');
});
</file>
</example>
*/
'checkbox': checkboxInputType,
'hidden': noop,
'button': noop,
'submit': noop,
'reset': noop,
'file': noop
};
function testFlags(validity, flags) {
var i, flag;
if (flags) {
for (i=0; i<flags.length; ++i) {
flag = flags[i];
if (validity[flag]) {
return true;
}
}
}
return false;
}
function stringBasedInputType(ctrl) {
ctrl.$formatters.push(function(value) {
return ctrl.$isEmpty(value) ? value : value.toString();
});
}
function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
stringBasedInputType(ctrl);
}
function baseInputType(scope, element, attr, ctrl, $sniffer, $browser) {
var validity = element.prop(VALIDITY_STATE_PROPERTY);
var placeholder = element[0].placeholder, noevent = {};
var type = lowercase(element[0].type);
// In composition mode, users are still inputing intermediate text buffer,
// hold the listener until composition is done.
// More about composition events: https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent
if (!$sniffer.android) {
var composing = false;
element.on('compositionstart', function(data) {
composing = true;
});
element.on('compositionend', function() {
composing = false;
listener();
});
}
var listener = function(ev) {
if (composing) return;
var value = element.val(),
event = ev && ev.type;
// IE (11 and under) seem to emit an 'input' event if the placeholder value changes.
// We don't want to dirty the value when this happens, so we abort here. Unfortunately,
// IE also sends input events for other non-input-related things, (such as focusing on a
// form control), so this change is not entirely enough to solve this.
if (msie && (ev || noevent).type === 'input' && element[0].placeholder !== placeholder) {
placeholder = element[0].placeholder;
return;
}
// By default we will trim the value
// If the attribute ng-trim exists we will avoid trimming
// If input type is 'password', the value is never trimmed
if (type !== 'password' && (!attr.ngTrim || attr.ngTrim !== 'false')) {
value = trim(value);
}
// If a control is suffering from bad input (due to native validators), browsers discard its
// value, so it may be necessary to revalidate (by calling $setViewValue again) even if the
// control's value is the same empty value twice in a row.
if (ctrl.$viewValue !== value || (value === '' && ctrl.$$hasNativeValidators)) {
ctrl.$setViewValue(value, event);
}
};
// if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the
// input event on backspace, delete or cut
if ($sniffer.hasEvent('input')) {
element.on('input', listener);
} else {
var timeout;
var deferListener = function(ev) {
if (!timeout) {
timeout = $browser.defer(function() {
listener(ev);
timeout = null;
});
}
};
element.on('keydown', function(event) {
var key = event.keyCode;
// ignore
// command modifiers arrows
if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return;
deferListener(event);
});
// if user modifies input value using context menu in IE, we need "paste" and "cut" events to catch it
if ($sniffer.hasEvent('paste')) {
element.on('paste cut', deferListener);
}
}
// if user paste into input using mouse on older browser
// or form autocomplete on newer browser, we need "change" event to catch it
element.on('change', listener);
ctrl.$render = function() {
element.val(ctrl.$isEmpty(ctrl.$modelValue) ? '' : ctrl.$viewValue);
};
}
function weekParser(isoWeek, existingDate) {
if (isDate(isoWeek)) {
return isoWeek;
}
if (isString(isoWeek)) {
WEEK_REGEXP.lastIndex = 0;
var parts = WEEK_REGEXP.exec(isoWeek);
if (parts) {
var year = +parts[1],
week = +parts[2],
hours = 0,
minutes = 0,
seconds = 0,
milliseconds = 0,
firstThurs = getFirstThursdayOfYear(year),
addDays = (week - 1) * 7;
if (existingDate) {
hours = existingDate.getHours();
minutes = existingDate.getMinutes();
seconds = existingDate.getSeconds();
milliseconds = existingDate.getMilliseconds();
}
return new Date(year, 0, firstThurs.getDate() + addDays, hours, minutes, seconds, milliseconds);
}
}
return NaN;
}
function createDateParser(regexp, mapping) {
return function(iso, date) {
var parts, map;
if (isDate(iso)) {
return iso;
}
if (isString(iso)) {
// When a date is JSON'ified to wraps itself inside of an extra
// set of double quotes. This makes the date parsing code unable
// to match the date string and parse it as a date.
if (iso.charAt(0) == '"' && iso.charAt(iso.length-1) == '"') {
iso = iso.substring(1, iso.length-1);
}
if (ISO_DATE_REGEXP.test(iso)) {
return new Date(iso);
}
regexp.lastIndex = 0;
parts = regexp.exec(iso);
if (parts) {
parts.shift();
if (date) {
map = {
yyyy: date.getFullYear(),
MM: date.getMonth() + 1,
dd: date.getDate(),
HH: date.getHours(),
mm: date.getMinutes(),
ss: date.getSeconds(),
sss: date.getMilliseconds() / 1000
};
} else {
map = { yyyy: 1970, MM: 1, dd: 1, HH: 0, mm: 0, ss: 0, sss: 0 };
}
forEach(parts, function(part, index) {
if (index < mapping.length) {
map[mapping[index]] = +part;
}
});
return new Date(map.yyyy, map.MM - 1, map.dd, map.HH, map.mm, map.ss || 0, map.sss * 1000 || 0);
}
}
return NaN;
};
}
function createDateInputType(type, regexp, parseDate, format) {
return function dynamicDateInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter) {
badInputChecker(scope, element, attr, ctrl);
baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
var timezone = ctrl && ctrl.$options && ctrl.$options.timezone;
var previousDate;
ctrl.$$parserName = type;
ctrl.$parsers.push(function(value) {
if (ctrl.$isEmpty(value)) return null;
if (regexp.test(value)) {
// Note: We cannot read ctrl.$modelValue, as there might be a different
// parser/formatter in the processing chain so that the model
// contains some different data format!
var parsedDate = parseDate(value, previousDate);
if (timezone === 'UTC') {
parsedDate.setMinutes(parsedDate.getMinutes() - parsedDate.getTimezoneOffset());
}
return parsedDate;
}
return undefined;
});
ctrl.$formatters.push(function(value) {
if (!ctrl.$isEmpty(value)) {
if (!isDate(value)) {
throw $ngModelMinErr('datefmt', 'Expected `{0}` to be a date', value);
}
previousDate = value;
if (previousDate && timezone === 'UTC') {
var timezoneOffset = 60000 * previousDate.getTimezoneOffset();
previousDate = new Date(previousDate.getTime() + timezoneOffset);
}
return $filter('date')(value, format, timezone);
} else {
previousDate = null;
}
return '';
});
if (isDefined(attr.min) || attr.ngMin) {
var minVal;
ctrl.$validators.min = function(value) {
return ctrl.$isEmpty(value) || isUndefined(minVal) || parseDate(value) >= minVal;
};
attr.$observe('min', function(val) {
minVal = parseObservedDateValue(val);
ctrl.$validate();
});
}
if (isDefined(attr.max) || attr.ngMax) {
var maxVal;
ctrl.$validators.max = function(value) {
return ctrl.$isEmpty(value) || isUndefined(maxVal) || parseDate(value) <= maxVal;
};
attr.$observe('max', function(val) {
maxVal = parseObservedDateValue(val);
ctrl.$validate();
});
}
// Override the standard $isEmpty to detect invalid dates as well
ctrl.$isEmpty = function(value) {
// Invalid Date: getTime() returns NaN
return !value || (value.getTime && value.getTime() !== value.getTime());
};
function parseObservedDateValue(val) {
return isDefined(val) ? (isDate(val) ? val : parseDate(val)) : undefined;
}
};
}
function badInputChecker(scope, element, attr, ctrl) {
var node = element[0];
var nativeValidation = ctrl.$$hasNativeValidators = isObject(node.validity);
if (nativeValidation) {
ctrl.$parsers.push(function(value) {
var validity = element.prop(VALIDITY_STATE_PROPERTY) || {};
// Detect bug in FF35 for input[email] (https://bugzilla.mozilla.org/show_bug.cgi?id=1064430):
// - also sets validity.badInput (should only be validity.typeMismatch).
// - see http://www.whatwg.org/specs/web-apps/current-work/multipage/forms.html#e-mail-state-(type=email)
// - can ignore this case as we can still read out the erroneous email...
return validity.badInput && !validity.typeMismatch ? undefined : value;
});
}
}
function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) {
badInputChecker(scope, element, attr, ctrl);
baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
ctrl.$$parserName = 'number';
ctrl.$parsers.push(function(value) {
if (ctrl.$isEmpty(value)) return null;
if (NUMBER_REGEXP.test(value)) return parseFloat(value);
return undefined;
});
ctrl.$formatters.push(function(value) {
if (!ctrl.$isEmpty(value)) {
if (!isNumber(value)) {
throw $ngModelMinErr('numfmt', 'Expected `{0}` to be a number', value);
}
value = value.toString();
}
return value;
});
if (attr.min || attr.ngMin) {
var minVal;
ctrl.$validators.min = function(value) {
return ctrl.$isEmpty(value) || isUndefined(minVal) || value >= minVal;
};
attr.$observe('min', function(val) {
if (isDefined(val) && !isNumber(val)) {
val = parseFloat(val, 10);
}
minVal = isNumber(val) && !isNaN(val) ? val : undefined;
// TODO(matsko): implement validateLater to reduce number of validations
ctrl.$validate();
});
}
if (attr.max || attr.ngMax) {
var maxVal;
ctrl.$validators.max = function(value) {
return ctrl.$isEmpty(value) || isUndefined(maxVal) || value <= maxVal;
};
attr.$observe('max', function(val) {
if (isDefined(val) && !isNumber(val)) {
val = parseFloat(val, 10);
}
maxVal = isNumber(val) && !isNaN(val) ? val : undefined;
// TODO(matsko): implement validateLater to reduce number of validations
ctrl.$validate();
});
}
}
function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) {
// Note: no badInputChecker here by purpose as `url` is only a validation
// in browsers, i.e. we can always read out input.value even if it is not valid!
baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
stringBasedInputType(ctrl);
ctrl.$$parserName = 'url';
ctrl.$validators.url = function(value) {
return ctrl.$isEmpty(value) || URL_REGEXP.test(value);
};
}
function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) {
// Note: no badInputChecker here by purpose as `url` is only a validation
// in browsers, i.e. we can always read out input.value even if it is not valid!
baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
stringBasedInputType(ctrl);
ctrl.$$parserName = 'email';
ctrl.$validators.email = function(value) {
return ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value);
};
}
function radioInputType(scope, element, attr, ctrl) {
// make the name unique, if not defined
if (isUndefined(attr.name)) {
element.attr('name', nextUid());
}
var listener = function(ev) {
if (element[0].checked) {
ctrl.$setViewValue(attr.value, ev && ev.type);
}
};
element.on('click', listener);
ctrl.$render = function() {
var value = attr.value;
element[0].checked = (value == ctrl.$viewValue);
};
attr.$observe('value', ctrl.$render);
}
function parseConstantExpr($parse, context, name, expression, fallback) {
var parseFn;
if (isDefined(expression)) {
parseFn = $parse(expression);
if (!parseFn.constant) {
throw minErr('ngModel')('constexpr', 'Expected constant expression for `{0}`, but saw ' +
'`{1}`.', name, expression);
}
return parseFn(context);
}
return fallback;
}
function checkboxInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter, $parse) {
var trueValue = parseConstantExpr($parse, scope, 'ngTrueValue', attr.ngTrueValue, true);
var falseValue = parseConstantExpr($parse, scope, 'ngFalseValue', attr.ngFalseValue, false);
var listener = function(ev) {
ctrl.$setViewValue(element[0].checked, ev && ev.type);
};
element.on('click', listener);
ctrl.$render = function() {
element[0].checked = ctrl.$viewValue;
};
// Override the standard `$isEmpty` because an empty checkbox is never equal to the trueValue
ctrl.$isEmpty = function(value) {
return value !== trueValue;
};
ctrl.$formatters.push(function(value) {
return equals(value, trueValue);
});
ctrl.$parsers.push(function(value) {
return value ? trueValue : falseValue;
});
}
/**
* @ngdoc directive
* @name textarea
* @restrict E
*
* @description
* HTML textarea element control with angular data-binding. The data-binding and validation
* properties of this element are exactly the same as those of the
* {@link ng.directive:input input element}.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength.
* @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
* RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
* patterns defined as scope expressions.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
* @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
*/
/**
* @ngdoc directive
* @name input
* @restrict E
*
* @description
* HTML input element control with angular data-binding. Input control follows HTML5 input types
* and polyfills the HTML5 validation behavior for older browsers.
*
* *NOTE* Not every feature offered is available for all input types.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {boolean=} ngRequired Sets `required` attribute if set to true
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength.
* @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
* RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
* patterns defined as scope expressions.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
* @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
* This parameter is ignored for input[type=password] controls, which will never trim the
* input.
*
* @example
<example name="input-directive" module="inputExample">
<file name="index.html">
<script>
angular.module('inputExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.user = {name: 'guest', last: 'visitor'};
}]);
</script>
<div ng-controller="ExampleController">
<form name="myForm">
User name: <input type="text" name="userName" ng-model="user.name" required>
<span class="error" ng-show="myForm.userName.$error.required">
Required!</span><br>
Last name: <input type="text" name="lastName" ng-model="user.last"
ng-minlength="3" ng-maxlength="10">
<span class="error" ng-show="myForm.lastName.$error.minlength">
Too short!</span>
<span class="error" ng-show="myForm.lastName.$error.maxlength">
Too long!</span><br>
</form>
<hr>
<tt>user = {{user}}</tt><br/>
<tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br>
<tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br>
<tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br>
<tt>myForm.lastName.$error = {{myForm.lastName.$error}}</tt><br>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br>
<tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br>
<tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br>
</div>
</file>
<file name="protractor.js" type="protractor">
var user = element(by.exactBinding('user'));
var userNameValid = element(by.binding('myForm.userName.$valid'));
var lastNameValid = element(by.binding('myForm.lastName.$valid'));
var lastNameError = element(by.binding('myForm.lastName.$error'));
var formValid = element(by.binding('myForm.$valid'));
var userNameInput = element(by.model('user.name'));
var userLastInput = element(by.model('user.last'));
it('should initialize to model', function() {
expect(user.getText()).toContain('{"name":"guest","last":"visitor"}');
expect(userNameValid.getText()).toContain('true');
expect(formValid.getText()).toContain('true');
});
it('should be invalid if empty when required', function() {
userNameInput.clear();
userNameInput.sendKeys('');
expect(user.getText()).toContain('{"last":"visitor"}');
expect(userNameValid.getText()).toContain('false');
expect(formValid.getText()).toContain('false');
});
it('should be valid if empty when min length is set', function() {
userLastInput.clear();
userLastInput.sendKeys('');
expect(user.getText()).toContain('{"name":"guest","last":""}');
expect(lastNameValid.getText()).toContain('true');
expect(formValid.getText()).toContain('true');
});
it('should be invalid if less than required min length', function() {
userLastInput.clear();
userLastInput.sendKeys('xx');
expect(user.getText()).toContain('{"name":"guest"}');
expect(lastNameValid.getText()).toContain('false');
expect(lastNameError.getText()).toContain('minlength');
expect(formValid.getText()).toContain('false');
});
it('should be invalid if longer than max length', function() {
userLastInput.clear();
userLastInput.sendKeys('some ridiculously long name');
expect(user.getText()).toContain('{"name":"guest"}');
expect(lastNameValid.getText()).toContain('false');
expect(lastNameError.getText()).toContain('maxlength');
expect(formValid.getText()).toContain('false');
});
</file>
</example>
*/
var inputDirective = ['$browser', '$sniffer', '$filter', '$parse',
function($browser, $sniffer, $filter, $parse) {
return {
restrict: 'E',
require: ['?ngModel'],
link: {
pre: function(scope, element, attr, ctrls) {
if (ctrls[0]) {
(inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrls[0], $sniffer,
$browser, $filter, $parse);
}
}
}
};
}];
var VALID_CLASS = 'ng-valid',
INVALID_CLASS = 'ng-invalid',
PRISTINE_CLASS = 'ng-pristine',
DIRTY_CLASS = 'ng-dirty',
UNTOUCHED_CLASS = 'ng-untouched',
TOUCHED_CLASS = 'ng-touched',
PENDING_CLASS = 'ng-pending';
/**
* @ngdoc type
* @name ngModel.NgModelController
*
* @property {string} $viewValue Actual string value in the view.
* @property {*} $modelValue The value in the model, that the control is bound to.
* @property {Array.<Function>} $parsers Array of functions to execute, as a pipeline, whenever
the control reads value from the DOM. Each function is called, in turn, passing the value
through to the next. The last return value is used to populate the model.
Used to sanitize / convert the value as well as validation. For validation,
the parsers should update the validity state using
{@link ngModel.NgModelController#$setValidity $setValidity()},
and return `undefined` for invalid values.
*
* @property {Array.<Function>} $formatters Array of functions to execute, as a pipeline, whenever
the model value changes. Each function is called, in turn, passing the value through to the
next. Used to format / convert values for display in the control and validation.
* ```js
* function formatter(value) {
* if (value) {
* return value.toUpperCase();
* }
* }
* ngModel.$formatters.push(formatter);
* ```
*
* @property {Object.<string, function>} $validators A collection of validators that are applied
* whenever the model value changes. The key value within the object refers to the name of the
* validator while the function refers to the validation operation. The validation operation is
* provided with the model value as an argument and must return a true or false value depending
* on the response of that validation.
*
* ```js
* ngModel.$validators.validCharacters = function(modelValue, viewValue) {
* var value = modelValue || viewValue;
* return /[0-9]+/.test(value) &&
* /[a-z]+/.test(value) &&
* /[A-Z]+/.test(value) &&
* /\W+/.test(value);
* };
* ```
*
* @property {Object.<string, function>} $asyncValidators A collection of validations that are expected to
* perform an asynchronous validation (e.g. a HTTP request). The validation function that is provided
* is expected to return a promise when it is run during the model validation process. Once the promise
* is delivered then the validation status will be set to true when fulfilled and false when rejected.
* When the asynchronous validators are triggered, each of the validators will run in parallel and the model
* value will only be updated once all validators have been fulfilled. Also, keep in mind that all
* asynchronous validators will only run once all synchronous validators have passed.
*
* Please note that if $http is used then it is important that the server returns a success HTTP response code
* in order to fulfill the validation and a status level of `4xx` in order to reject the validation.
*
* ```js
* ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) {
* var value = modelValue || viewValue;
*
* // Lookup user by username
* return $http.get('/api/users/' + value).
* then(function resolved() {
* //username exists, this means validation fails
* return $q.reject('exists');
* }, function rejected() {
* //username does not exist, therefore this validation passes
* return true;
* });
* };
* ```
*
* @param {string} name The name of the validator.
* @param {Function} validationFn The validation function that will be run.
*
* @property {Array.<Function>} $viewChangeListeners Array of functions to execute whenever the
* view value has changed. It is called with no arguments, and its return value is ignored.
* This can be used in place of additional $watches against the model value.
*
* @property {Object} $error An object hash with all failing validator ids as keys.
* @property {Object} $pending An object hash with all pending validator ids as keys.
*
* @property {boolean} $untouched True if control has not lost focus yet.
* @property {boolean} $touched True if control has lost focus.
* @property {boolean} $pristine True if user has not interacted with the control yet.
* @property {boolean} $dirty True if user has already interacted with the control.
* @property {boolean} $valid True if there is no error.
* @property {boolean} $invalid True if at least one error on the control.
*
* @description
*
* `NgModelController` provides API for the `ng-model` directive. The controller contains
* services for data-binding, validation, CSS updates, and value formatting and parsing. It
* purposefully does not contain any logic which deals with DOM rendering or listening to
* DOM events. Such DOM related logic should be provided by other directives which make use of
* `NgModelController` for data-binding.
*
* ## Custom Control Example
* This example shows how to use `NgModelController` with a custom control to achieve
* data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`)
* collaborate together to achieve the desired result.
*
* Note that `contenteditable` is an HTML5 attribute, which tells the browser to let the element
* contents be edited in place by the user. This will not work on older browsers.
*
* We are using the {@link ng.service:$sce $sce} service here and include the {@link ngSanitize $sanitize}
* module to automatically remove "bad" content like inline event listener (e.g. `<span onclick="...">`).
* However, as we are using `$sce` the model can still decide to to provide unsafe content if it marks
* that content using the `$sce` service.
*
* <example name="NgModelController" module="customControl" deps="angular-sanitize.js">
<file name="style.css">
[contenteditable] {
border: 1px solid black;
background-color: white;
min-height: 20px;
}
.ng-invalid {
border: 1px solid red;
}
</file>
<file name="script.js">
angular.module('customControl', ['ngSanitize']).
directive('contenteditable', ['$sce', function($sce) {
return {
restrict: 'A', // only activate on element attribute
require: '?ngModel', // get a hold of NgModelController
link: function(scope, element, attrs, ngModel) {
if (!ngModel) return; // do nothing if no ng-model
// Specify how UI should be updated
ngModel.$render = function() {
element.html($sce.getTrustedHtml(ngModel.$viewValue || ''));
};
// Listen for change events to enable binding
element.on('blur keyup change', function() {
scope.$apply(read);
});
read(); // initialize
// Write data to the model
function read() {
var html = element.html();
// When we clear the content editable the browser leaves a <br> behind
// If strip-br attribute is provided then we strip this out
if ( attrs.stripBr && html == '<br>' ) {
html = '';
}
ngModel.$setViewValue(html);
}
}
};
}]);
</file>
<file name="index.html">
<form name="myForm">
<div contenteditable
name="myWidget" ng-model="userContent"
strip-br="true"
required>Change me!</div>
<span ng-show="myForm.myWidget.$error.required">Required!</span>
<hr>
<textarea ng-model="userContent"></textarea>
</form>
</file>
<file name="protractor.js" type="protractor">
it('should data-bind and become invalid', function() {
if (browser.params.browser == 'safari' || browser.params.browser == 'firefox') {
// SafariDriver can't handle contenteditable
// and Firefox driver can't clear contenteditables very well
return;
}
var contentEditable = element(by.css('[contenteditable]'));
var content = 'Change me!';
expect(contentEditable.getText()).toEqual(content);
contentEditable.clear();
contentEditable.sendKeys(protractor.Key.BACK_SPACE);
expect(contentEditable.getText()).toEqual('');
expect(contentEditable.getAttribute('class')).toMatch(/ng-invalid-required/);
});
</file>
* </example>
*
*
*/
var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', '$animate', '$timeout', '$rootScope', '$q', '$interpolate',
function($scope, $exceptionHandler, $attr, $element, $parse, $animate, $timeout, $rootScope, $q, $interpolate) {
this.$viewValue = Number.NaN;
this.$modelValue = Number.NaN;
this.$validators = {};
this.$asyncValidators = {};
this.$parsers = [];
this.$formatters = [];
this.$viewChangeListeners = [];
this.$untouched = true;
this.$touched = false;
this.$pristine = true;
this.$dirty = false;
this.$valid = true;
this.$invalid = false;
this.$error = {}; // keep invalid keys here
this.$$success = {}; // keep valid keys here
this.$pending = undefined; // keep pending keys here
this.$name = $interpolate($attr.name || '', false)($scope);
var parsedNgModel = $parse($attr.ngModel),
pendingDebounce = null,
ctrl = this;
var ngModelGet = function ngModelGet() {
var modelValue = parsedNgModel($scope);
if (ctrl.$options && ctrl.$options.getterSetter && isFunction(modelValue)) {
modelValue = modelValue();
}
return modelValue;
};
var ngModelSet = function ngModelSet(newValue) {
var getterSetter;
if (ctrl.$options && ctrl.$options.getterSetter &&
isFunction(getterSetter = parsedNgModel($scope))) {
getterSetter(ctrl.$modelValue);
} else {
parsedNgModel.assign($scope, ctrl.$modelValue);
}
};
this.$$setOptions = function(options) {
ctrl.$options = options;
if (!parsedNgModel.assign && (!options || !options.getterSetter)) {
throw $ngModelMinErr('nonassign', "Expression '{0}' is non-assignable. Element: {1}",
$attr.ngModel, startingTag($element));
}
};
/**
* @ngdoc method
* @name ngModel.NgModelController#$render
*
* @description
* Called when the view needs to be updated. It is expected that the user of the ng-model
* directive will implement this method.
*
* The `$render()` method is invoked in the following situations:
*
* * `$rollbackViewValue()` is called. If we are rolling back the view value to the last
* committed value then `$render()` is called to update the input control.
* * The value referenced by `ng-model` is changed programmatically and both the `$modelValue` and
* the `$viewValue` are different to last time.
*
* Since `ng-model` does not do a deep watch, `$render()` is only invoked if the values of
* `$modelValue` and `$viewValue` are actually different to their previous value. If `$modelValue`
* or `$viewValue` are objects (rather than a string or number) then `$render()` will not be
* invoked if you only change a property on the objects.
*/
this.$render = noop;
/**
* @ngdoc method
* @name ngModel.NgModelController#$isEmpty
*
* @description
* This is called when we need to determine if the value of the input is empty.
*
* For instance, the required directive does this to work out if the input has data or not.
* The default `$isEmpty` function checks whether the value is `undefined`, `''`, `null` or `NaN`.
*
* You can override this for input directives whose concept of being empty is different to the
* default. The `checkboxInputType` directive does this because in its case a value of `false`
* implies empty.
*
* @param {*} value Model value to check.
* @returns {boolean} True if `value` is empty.
*/
this.$isEmpty = function(value) {
return isUndefined(value) || value === '' || value === null || value !== value;
};
var parentForm = $element.inheritedData('$formController') || nullFormCtrl,
currentValidationRunId = 0;
/**
* @ngdoc method
* @name ngModel.NgModelController#$setValidity
*
* @description
* Change the validity state, and notifies the form.
*
* This method can be called within $parsers/$formatters. However, if possible, please use the
* `ngModel.$validators` pipeline which is designed to call this method automatically.
*
* @param {string} validationErrorKey Name of the validator. the `validationErrorKey` will assign
* to `$error[validationErrorKey]` and `$pending[validationErrorKey]`
* so that it is available for data-binding.
* The `validationErrorKey` should be in camelCase and will get converted into dash-case
* for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error`
* class and can be bound to as `{{someForm.someControl.$error.myError}}` .
* @param {boolean} isValid Whether the current state is valid (true), invalid (false), pending (undefined),
* or skipped (null).
*/
addSetValidityMethod({
ctrl: this,
$element: $element,
set: function(object, property) {
object[property] = true;
},
unset: function(object, property) {
delete object[property];
},
parentForm: parentForm,
$animate: $animate
});
/**
* @ngdoc method
* @name ngModel.NgModelController#$setPristine
*
* @description
* Sets the control to its pristine state.
*
* This method can be called to remove the 'ng-dirty' class and set the control to its pristine
* state (ng-pristine class). A model is considered to be pristine when the model has not been changed
* from when first compiled within then form.
*/
this.$setPristine = function () {
ctrl.$dirty = false;
ctrl.$pristine = true;
$animate.removeClass($element, DIRTY_CLASS);
$animate.addClass($element, PRISTINE_CLASS);
};
/**
* @ngdoc method
* @name ngModel.NgModelController#$setUntouched
*
* @description
* Sets the control to its untouched state.
*
* This method can be called to remove the 'ng-touched' class and set the control to its
* untouched state (ng-untouched class). Upon compilation, a model is set as untouched
* by default, however this function can be used to restore that state if the model has
* already been touched by the user.
*/
this.$setUntouched = function() {
ctrl.$touched = false;
ctrl.$untouched = true;
$animate.setClass($element, UNTOUCHED_CLASS, TOUCHED_CLASS);
};
/**
* @ngdoc method
* @name ngModel.NgModelController#$setTouched
*
* @description
* Sets the control to its touched state.
*
* This method can be called to remove the 'ng-untouched' class and set the control to its
* touched state (ng-touched class). A model is considered to be touched when the user has
* first interacted (focussed) on the model input element and then shifted focus away (blurred)
* from the input element.
*/
this.$setTouched = function() {
ctrl.$touched = true;
ctrl.$untouched = false;
$animate.setClass($element, TOUCHED_CLASS, UNTOUCHED_CLASS);
};
/**
* @ngdoc method
* @name ngModel.NgModelController#$rollbackViewValue
*
* @description
* Cancel an update and reset the input element's value to prevent an update to the `$modelValue`,
* which may be caused by a pending debounced event or because the input is waiting for a some
* future event.
*
* If you have an input that uses `ng-model-options` to set up debounced events or events such
* as blur you can have a situation where there is a period when the `$viewValue`
* is out of synch with the ngModel's `$modelValue`.
*
* In this case, you can run into difficulties if you try to update the ngModel's `$modelValue`
* programmatically before these debounced/future events have resolved/occurred, because Angular's
* dirty checking mechanism is not able to tell whether the model has actually changed or not.
*
* The `$rollbackViewValue()` method should be called before programmatically changing the model of an
* input which may have such events pending. This is important in order to make sure that the
* input field will be updated with the new model value and any pending operations are cancelled.
*
* <example name="ng-model-cancel-update" module="cancel-update-example">
* <file name="app.js">
* angular.module('cancel-update-example', [])
*
* .controller('CancelUpdateController', ['$scope', function($scope) {
* $scope.resetWithCancel = function (e) {
* if (e.keyCode == 27) {
* $scope.myForm.myInput1.$rollbackViewValue();
* $scope.myValue = '';
* }
* };
* $scope.resetWithoutCancel = function (e) {
* if (e.keyCode == 27) {
* $scope.myValue = '';
* }
* };
* }]);
* </file>
* <file name="index.html">
* <div ng-controller="CancelUpdateController">
* <p>Try typing something in each input. See that the model only updates when you
* blur off the input.
* </p>
* <p>Now see what happens if you start typing then press the Escape key</p>
*
* <form name="myForm" ng-model-options="{ updateOn: 'blur' }">
* <p>With $rollbackViewValue()</p>
* <input name="myInput1" ng-model="myValue" ng-keydown="resetWithCancel($event)"><br/>
* myValue: "{{ myValue }}"
*
* <p>Without $rollbackViewValue()</p>
* <input name="myInput2" ng-model="myValue" ng-keydown="resetWithoutCancel($event)"><br/>
* myValue: "{{ myValue }}"
* </form>
* </div>
* </file>
* </example>
*/
this.$rollbackViewValue = function() {
$timeout.cancel(pendingDebounce);
ctrl.$viewValue = ctrl.$$lastCommittedViewValue;
ctrl.$render();
};
/**
* @ngdoc method
* @name ngModel.NgModelController#$validate
*
* @description
* Runs each of the registered validators (first synchronous validators and then asynchronous validators).
*/
this.$validate = function() {
// ignore $validate before model is initialized
if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) {
return;
}
this.$$parseAndValidate();
};
this.$$runValidators = function(parseValid, modelValue, viewValue, doneCallback) {
currentValidationRunId++;
var localValidationRunId = currentValidationRunId;
// check parser error
if (!processParseErrors(parseValid)) {
validationDone(false);
return;
}
if (!processSyncValidators()) {
validationDone(false);
return;
}
processAsyncValidators();
function processParseErrors(parseValid) {
var errorKey = ctrl.$$parserName || 'parse';
if (parseValid === undefined) {
setValidity(errorKey, null);
} else {
setValidity(errorKey, parseValid);
if (!parseValid) {
forEach(ctrl.$validators, function(v, name) {
setValidity(name, null);
});
forEach(ctrl.$asyncValidators, function(v, name) {
setValidity(name, null);
});
return false;
}
}
return true;
}
function processSyncValidators() {
var syncValidatorsValid = true;
forEach(ctrl.$validators, function(validator, name) {
var result = validator(modelValue, viewValue);
syncValidatorsValid = syncValidatorsValid && result;
setValidity(name, result);
});
if (!syncValidatorsValid) {
forEach(ctrl.$asyncValidators, function(v, name) {
setValidity(name, null);
});
return false;
}
return true;
}
function processAsyncValidators() {
var validatorPromises = [];
var allValid = true;
forEach(ctrl.$asyncValidators, function(validator, name) {
var promise = validator(modelValue, viewValue);
if (!isPromiseLike(promise)) {
throw $ngModelMinErr("$asyncValidators",
"Expected asynchronous validator to return a promise but got '{0}' instead.", promise);
}
setValidity(name, undefined);
validatorPromises.push(promise.then(function() {
setValidity(name, true);
}, function(error) {
allValid = false;
setValidity(name, false);
}));
});
if (!validatorPromises.length) {
validationDone(true);
} else {
$q.all(validatorPromises).then(function() {
validationDone(allValid);
}, noop);
}
}
function setValidity(name, isValid) {
if (localValidationRunId === currentValidationRunId) {
ctrl.$setValidity(name, isValid);
}
}
function validationDone(allValid) {
if (localValidationRunId === currentValidationRunId) {
doneCallback(allValid);
}
}
};
/**
* @ngdoc method
* @name ngModel.NgModelController#$commitViewValue
*
* @description
* Commit a pending update to the `$modelValue`.
*
* Updates may be pending by a debounced event or because the input is waiting for a some future
* event defined in `ng-model-options`. this method is rarely needed as `NgModelController`
* usually handles calling this in response to input events.
*/
this.$commitViewValue = function() {
var viewValue = ctrl.$viewValue;
$timeout.cancel(pendingDebounce);
// If the view value has not changed then we should just exit, except in the case where there is
// a native validator on the element. In this case the validation state may have changed even though
// the viewValue has stayed empty.
if (ctrl.$$lastCommittedViewValue === viewValue && (viewValue !== '' || !ctrl.$$hasNativeValidators)) {
return;
}
ctrl.$$lastCommittedViewValue = viewValue;
// change to dirty
if (ctrl.$pristine) {
ctrl.$dirty = true;
ctrl.$pristine = false;
$animate.removeClass($element, PRISTINE_CLASS);
$animate.addClass($element, DIRTY_CLASS);
parentForm.$setDirty();
}
this.$$parseAndValidate();
};
this.$$parseAndValidate = function() {
var viewValue = ctrl.$$lastCommittedViewValue;
var modelValue = viewValue;
var parserValid = isUndefined(modelValue) ? undefined : true;
if (parserValid) {
for(var i = 0; i < ctrl.$parsers.length; i++) {
modelValue = ctrl.$parsers[i](modelValue);
if (isUndefined(modelValue)) {
parserValid = false;
break;
}
}
}
if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) {
// ctrl.$modelValue has not been touched yet...
ctrl.$modelValue = ngModelGet();
}
var prevModelValue = ctrl.$modelValue;
var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid;
if (allowInvalid) {
ctrl.$modelValue = modelValue;
writeToModelIfNeeded();
}
ctrl.$$runValidators(parserValid, modelValue, viewValue, function(allValid) {
if (!allowInvalid) {
// Note: Don't check ctrl.$valid here, as we could have
// external validators (e.g. calculated on the server),
// that just call $setValidity and need the model value
// to calculate their validity.
ctrl.$modelValue = allValid ? modelValue : undefined;
writeToModelIfNeeded();
}
});
function writeToModelIfNeeded() {
if (ctrl.$modelValue !== prevModelValue) {
ctrl.$$writeModelToScope();
}
}
};
this.$$writeModelToScope = function() {
ngModelSet(ctrl.$modelValue);
forEach(ctrl.$viewChangeListeners, function(listener) {
try {
listener();
} catch(e) {
$exceptionHandler(e);
}
});
};
/**
* @ngdoc method
* @name ngModel.NgModelController#$setViewValue
*
* @description
* Update the view value.
*
* This method should be called when an input directive want to change the view value; typically,
* this is done from within a DOM event handler.
*
* For example {@link ng.directive:input input} calls it when the value of the input changes and
* {@link ng.directive:select select} calls it when an option is selected.
*
* If the new `value` is an object (rather than a string or a number), we should make a copy of the
* object before passing it to `$setViewValue`. This is because `ngModel` does not perform a deep
* watch of objects, it only looks for a change of identity. If you only change the property of
* the object then ngModel will not realise that the object has changed and will not invoke the
* `$parsers` and `$validators` pipelines.
*
* For this reason, you should not change properties of the copy once it has been passed to
* `$setViewValue`. Otherwise you may cause the model value on the scope to change incorrectly.
*
* When this method is called, the new `value` will be staged for committing through the `$parsers`
* and `$validators` pipelines. If there are no special {@link ngModelOptions} specified then the staged
* value sent directly for processing, finally to be applied to `$modelValue` and then the
* **expression** specified in the `ng-model` attribute.
*
* Lastly, all the registered change listeners, in the `$viewChangeListeners` list, are called.
*
* In case the {@link ng.directive:ngModelOptions ngModelOptions} directive is used with `updateOn`
* and the `default` trigger is not listed, all those actions will remain pending until one of the
* `updateOn` events is triggered on the DOM element.
* All these actions will be debounced if the {@link ng.directive:ngModelOptions ngModelOptions}
* directive is used with a custom debounce for this particular event.
*
* Note that calling this function does not trigger a `$digest`.
*
* @param {string} value Value from the view.
* @param {string} trigger Event that triggered the update.
*/
this.$setViewValue = function(value, trigger) {
ctrl.$viewValue = value;
if (!ctrl.$options || ctrl.$options.updateOnDefault) {
ctrl.$$debounceViewValueCommit(trigger);
}
};
this.$$debounceViewValueCommit = function(trigger) {
var debounceDelay = 0,
options = ctrl.$options,
debounce;
if (options && isDefined(options.debounce)) {
debounce = options.debounce;
if (isNumber(debounce)) {
debounceDelay = debounce;
} else if (isNumber(debounce[trigger])) {
debounceDelay = debounce[trigger];
} else if (isNumber(debounce['default'])) {
debounceDelay = debounce['default'];
}
}
$timeout.cancel(pendingDebounce);
if (debounceDelay) {
pendingDebounce = $timeout(function() {
ctrl.$commitViewValue();
}, debounceDelay);
} else if ($rootScope.$$phase) {
ctrl.$commitViewValue();
} else {
$scope.$apply(function() {
ctrl.$commitViewValue();
});
}
};
// model -> value
// Note: we cannot use a normal scope.$watch as we want to detect the following:
// 1. scope value is 'a'
// 2. user enters 'b'
// 3. ng-change kicks in and reverts scope value to 'a'
// -> scope value did not change since the last digest as
// ng-change executes in apply phase
// 4. view should be changed back to 'a'
$scope.$watch(function ngModelWatch() {
var modelValue = ngModelGet();
// if scope model value and ngModel value are out of sync
// TODO(perf): why not move this to the action fn?
if (modelValue !== ctrl.$modelValue) {
ctrl.$modelValue = modelValue;
var formatters = ctrl.$formatters,
idx = formatters.length;
var viewValue = modelValue;
while(idx--) {
viewValue = formatters[idx](viewValue);
}
if (ctrl.$viewValue !== viewValue) {
ctrl.$viewValue = ctrl.$$lastCommittedViewValue = viewValue;
ctrl.$render();
ctrl.$$runValidators(undefined, modelValue, viewValue, noop);
}
}
return modelValue;
});
}];
/**
* @ngdoc directive
* @name ngModel
*
* @element input
*
* @description
* The `ngModel` directive binds an `input`,`select`, `textarea` (or custom form control) to a
* property on the scope using {@link ngModel.NgModelController NgModelController},
* which is created and exposed by this directive.
*
* `ngModel` is responsible for:
*
* - Binding the view into the model, which other directives such as `input`, `textarea` or `select`
* require.
* - Providing validation behavior (i.e. required, number, email, url).
* - Keeping the state of the control (valid/invalid, dirty/pristine, touched/untouched, validation errors).
* - Setting related css classes on the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`, `ng-touched`, `ng-untouched`) including animations.
* - Registering the control with its parent {@link ng.directive:form form}.
*
* Note: `ngModel` will try to bind to the property given by evaluating the expression on the
* current scope. If the property doesn't already exist on this scope, it will be created
* implicitly and added to the scope.
*
* For best practices on using `ngModel`, see:
*
* - [https://github.com/angular/angular.js/wiki/Understanding-Scopes]
*
* For basic examples, how to use `ngModel`, see:
*
* - {@link ng.directive:input input}
* - {@link input[text] text}
* - {@link input[checkbox] checkbox}
* - {@link input[radio] radio}
* - {@link input[number] number}
* - {@link input[email] email}
* - {@link input[url] url}
* - {@link input[date] date}
* - {@link input[dateTimeLocal] dateTimeLocal}
* - {@link input[time] time}
* - {@link input[month] month}
* - {@link input[week] week}
* - {@link ng.directive:select select}
* - {@link ng.directive:textarea textarea}
*
* # CSS classes
* The following CSS classes are added and removed on the associated input/select/textarea element
* depending on the validity of the model.
*
* - `ng-valid` is set if the model is valid.
* - `ng-invalid` is set if the model is invalid.
* - `ng-pristine` is set if the model is pristine.
* - `ng-dirty` is set if the model is dirty.
*
* Keep in mind that ngAnimate can detect each of these classes when added and removed.
*
* ## Animation Hooks
*
* Animations within models are triggered when any of the associated CSS classes are added and removed
* on the input element which is attached to the model. These classes are: `.ng-pristine`, `.ng-dirty`,
* `.ng-invalid` and `.ng-valid` as well as any other validations that are performed on the model itself.
* The animations that are triggered within ngModel are similar to how they work in ngClass and
* animations can be hooked into using CSS transitions, keyframes as well as JS animations.
*
* The following example shows a simple way to utilize CSS transitions to style an input element
* that has been rendered as invalid after it has been validated:
*
* <pre>
* //be sure to include ngAnimate as a module to hook into more
* //advanced animations
* .my-input {
* transition:0.5s linear all;
* background: white;
* }
* .my-input.ng-invalid {
* background: red;
* color:white;
* }
* </pre>
*
* @example
* <example deps="angular-animate.js" animations="true" fixBase="true" module="inputExample">
<file name="index.html">
<script>
angular.module('inputExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.val = '1';
}]);
</script>
<style>
.my-input {
-webkit-transition:all linear 0.5s;
transition:all linear 0.5s;
background: transparent;
}
.my-input.ng-invalid {
color:white;
background: red;
}
</style>
Update input to see transitions when valid/invalid.
Integer is a valid value.
<form name="testForm" ng-controller="ExampleController">
<input ng-model="val" ng-pattern="/^\d+$/" name="anim" class="my-input" />
</form>
</file>
* </example>
*
* ## Binding to a getter/setter
*
* Sometimes it's helpful to bind `ngModel` to a getter/setter function. A getter/setter is a
* function that returns a representation of the model when called with zero arguments, and sets
* the internal state of a model when called with an argument. It's sometimes useful to use this
* for models that have an internal representation that's different than what the model exposes
* to the view.
*
* <div class="alert alert-success">
* **Best Practice:** It's best to keep getters fast because Angular is likely to call them more
* frequently than other parts of your code.
* </div>
*
* You use this behavior by adding `ng-model-options="{ getterSetter: true }"` to an element that
* has `ng-model` attached to it. You can also add `ng-model-options="{ getterSetter: true }"` to
* a `<form>`, which will enable this behavior for all `<input>`s within it. See
* {@link ng.directive:ngModelOptions `ngModelOptions`} for more.
*
* The following example shows how to use `ngModel` with a getter/setter:
*
* @example
* <example name="ngModel-getter-setter" module="getterSetterExample">
<file name="index.html">
<div ng-controller="ExampleController">
<form name="userForm">
Name:
<input type="text" name="userName"
ng-model="user.name"
ng-model-options="{ getterSetter: true }" />
</form>
<pre>user.name = <span ng-bind="user.name()"></span></pre>
</div>
</file>
<file name="app.js">
angular.module('getterSetterExample', [])
.controller('ExampleController', ['$scope', function($scope) {
var _name = 'Brian';
$scope.user = {
name: function (newName) {
if (angular.isDefined(newName)) {
_name = newName;
}
return _name;
}
};
}]);
</file>
* </example>
*/
var ngModelDirective = function() {
return {
restrict: 'A',
require: ['ngModel', '^?form', '^?ngModelOptions'],
controller: NgModelController,
// Prelink needs to run before any input directive
// so that we can set the NgModelOptions in NgModelController
// before anyone else uses it.
priority: 1,
compile: function ngModelCompile(element) {
// Setup initial state of the control
element.addClass(PRISTINE_CLASS).addClass(UNTOUCHED_CLASS).addClass(VALID_CLASS);
return {
pre: function ngModelPreLink(scope, element, attr, ctrls) {
var modelCtrl = ctrls[0],
formCtrl = ctrls[1] || nullFormCtrl;
modelCtrl.$$setOptions(ctrls[2] && ctrls[2].$options);
// notify others, especially parent forms
formCtrl.$addControl(modelCtrl);
attr.$observe('name', function(newValue) {
if (modelCtrl.$name !== newValue) {
formCtrl.$$renameControl(modelCtrl, newValue);
}
});
scope.$on('$destroy', function() {
formCtrl.$removeControl(modelCtrl);
});
},
post: function ngModelPostLink(scope, element, attr, ctrls) {
var modelCtrl = ctrls[0];
if (modelCtrl.$options && modelCtrl.$options.updateOn) {
element.on(modelCtrl.$options.updateOn, function(ev) {
modelCtrl.$$debounceViewValueCommit(ev && ev.type);
});
}
element.on('blur', function(ev) {
if (modelCtrl.$touched) return;
scope.$apply(function() {
modelCtrl.$setTouched();
});
});
}
};
}
};
};
/**
* @ngdoc directive
* @name ngChange
*
* @description
* Evaluate the given expression when the user changes the input.
* The expression is evaluated immediately, unlike the JavaScript onchange event
* which only triggers at the end of a change (usually, when the user leaves the
* form element or presses the return key).
*
* The `ngChange` expression is only evaluated when a change in the input value causes
* a new value to be committed to the model.
*
* It will not be evaluated:
* * if the value returned from the `$parsers` transformation pipeline has not changed
* * if the input has continued to be invalid since the model will stay `null`
* * if the model is changed programmatically and not by a change to the input value
*
*
* Note, this directive requires `ngModel` to be present.
*
* @element input
* @param {expression} ngChange {@link guide/expression Expression} to evaluate upon change
* in input value.
*
* @example
* <example name="ngChange-directive" module="changeExample">
* <file name="index.html">
* <script>
* angular.module('changeExample', [])
* .controller('ExampleController', ['$scope', function($scope) {
* $scope.counter = 0;
* $scope.change = function() {
* $scope.counter++;
* };
* }]);
* </script>
* <div ng-controller="ExampleController">
* <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" />
* <input type="checkbox" ng-model="confirmed" id="ng-change-example2" />
* <label for="ng-change-example2">Confirmed</label><br />
* <tt>debug = {{confirmed}}</tt><br/>
* <tt>counter = {{counter}}</tt><br/>
* </div>
* </file>
* <file name="protractor.js" type="protractor">
* var counter = element(by.binding('counter'));
* var debug = element(by.binding('confirmed'));
*
* it('should evaluate the expression if changing from view', function() {
* expect(counter.getText()).toContain('0');
*
* element(by.id('ng-change-example1')).click();
*
* expect(counter.getText()).toContain('1');
* expect(debug.getText()).toContain('true');
* });
*
* it('should not evaluate the expression if changing from model', function() {
* element(by.id('ng-change-example2')).click();
* expect(counter.getText()).toContain('0');
* expect(debug.getText()).toContain('true');
* });
* </file>
* </example>
*/
var ngChangeDirective = valueFn({
restrict: 'A',
require: 'ngModel',
link: function(scope, element, attr, ctrl) {
ctrl.$viewChangeListeners.push(function() {
scope.$eval(attr.ngChange);
});
}
});
var requiredDirective = function() {
return {
restrict: 'A',
require: '?ngModel',
link: function(scope, elm, attr, ctrl) {
if (!ctrl) return;
attr.required = true; // force truthy in case we are on non input element
ctrl.$validators.required = function(value) {
return !attr.required || !ctrl.$isEmpty(value);
};
attr.$observe('required', function() {
ctrl.$validate();
});
}
};
};
var patternDirective = function() {
return {
restrict: 'A',
require: '?ngModel',
link: function(scope, elm, attr, ctrl) {
if (!ctrl) return;
var regexp, patternExp = attr.ngPattern || attr.pattern;
attr.$observe('pattern', function(regex) {
if (isString(regex) && regex.length > 0) {
regex = new RegExp(regex);
}
if (regex && !regex.test) {
throw minErr('ngPattern')('noregexp',
'Expected {0} to be a RegExp but was {1}. Element: {2}', patternExp,
regex, startingTag(elm));
}
regexp = regex || undefined;
ctrl.$validate();
});
ctrl.$validators.pattern = function(value) {
return ctrl.$isEmpty(value) || isUndefined(regexp) || regexp.test(value);
};
}
};
};
var maxlengthDirective = function() {
return {
restrict: 'A',
require: '?ngModel',
link: function(scope, elm, attr, ctrl) {
if (!ctrl) return;
var maxlength = 0;
attr.$observe('maxlength', function(value) {
maxlength = int(value) || 0;
ctrl.$validate();
});
ctrl.$validators.maxlength = function(modelValue, viewValue) {
return ctrl.$isEmpty(modelValue) || viewValue.length <= maxlength;
};
}
};
};
var minlengthDirective = function() {
return {
restrict: 'A',
require: '?ngModel',
link: function(scope, elm, attr, ctrl) {
if (!ctrl) return;
var minlength = 0;
attr.$observe('minlength', function(value) {
minlength = int(value) || 0;
ctrl.$validate();
});
ctrl.$validators.minlength = function(modelValue, viewValue) {
return ctrl.$isEmpty(modelValue) || viewValue.length >= minlength;
};
}
};
};
/**
* @ngdoc directive
* @name ngList
*
* @description
* Text input that converts between a delimited string and an array of strings. The default
* delimiter is a comma followed by a space - equivalent to `ng-list=", "`. You can specify a custom
* delimiter as the value of the `ngList` attribute - for example, `ng-list=" | "`.
*
* The behaviour of the directive is affected by the use of the `ngTrim` attribute.
* * If `ngTrim` is set to `"false"` then whitespace around both the separator and each
* list item is respected. This implies that the user of the directive is responsible for
* dealing with whitespace but also allows you to use whitespace as a delimiter, such as a
* tab or newline character.
* * Otherwise whitespace around the delimiter is ignored when splitting (although it is respected
* when joining the list items back together) and whitespace around each list item is stripped
* before it is added to the model.
*
* ### Example with Validation
*
* <example name="ngList-directive" module="listExample">
* <file name="app.js">
* angular.module('listExample', [])
* .controller('ExampleController', ['$scope', function($scope) {
* $scope.names = ['morpheus', 'neo', 'trinity'];
* }]);
* </file>
* <file name="index.html">
* <form name="myForm" ng-controller="ExampleController">
* List: <input name="namesInput" ng-model="names" ng-list required>
* <span class="error" ng-show="myForm.namesInput.$error.required">
* Required!</span>
* <br>
* <tt>names = {{names}}</tt><br/>
* <tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/>
* <tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/>
* <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
* <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
* </form>
* </file>
* <file name="protractor.js" type="protractor">
* var listInput = element(by.model('names'));
* var names = element(by.exactBinding('names'));
* var valid = element(by.binding('myForm.namesInput.$valid'));
* var error = element(by.css('span.error'));
*
* it('should initialize to model', function() {
* expect(names.getText()).toContain('["morpheus","neo","trinity"]');
* expect(valid.getText()).toContain('true');
* expect(error.getCssValue('display')).toBe('none');
* });
*
* it('should be invalid if empty', function() {
* listInput.clear();
* listInput.sendKeys('');
*
* expect(names.getText()).toContain('');
* expect(valid.getText()).toContain('false');
* expect(error.getCssValue('display')).not.toBe('none');
* });
* </file>
* </example>
*
* ### Example - splitting on whitespace
* <example name="ngList-directive-newlines">
* <file name="index.html">
* <textarea ng-model="list" ng-list=" " ng-trim="false"></textarea>
* <pre>{{ list | json }}</pre>
* </file>
* <file name="protractor.js" type="protractor">
* it("should split the text by newlines", function() {
* var listInput = element(by.model('list'));
* var output = element(by.binding('list | json'));
* listInput.sendKeys('abc\ndef\nghi');
* expect(output.getText()).toContain('[\n "abc",\n "def",\n "ghi"\n]');
* });
* </file>
* </example>
*
* @element input
* @param {string=} ngList optional delimiter that should be used to split the value.
*/
var ngListDirective = function() {
return {
restrict: 'A',
priority: 100,
require: 'ngModel',
link: function(scope, element, attr, ctrl) {
// We want to control whitespace trimming so we use this convoluted approach
// to access the ngList attribute, which doesn't pre-trim the attribute
var ngList = element.attr(attr.$attr.ngList) || ', ';
var trimValues = attr.ngTrim !== 'false';
var separator = trimValues ? trim(ngList) : ngList;
var parse = function(viewValue) {
// If the viewValue is invalid (say required but empty) it will be `undefined`
if (isUndefined(viewValue)) return;
var list = [];
if (viewValue) {
forEach(viewValue.split(separator), function(value) {
if (value) list.push(trimValues ? trim(value) : value);
});
}
return list;
};
ctrl.$parsers.push(parse);
ctrl.$formatters.push(function(value) {
if (isArray(value)) {
return value.join(ngList);
}
return undefined;
});
// Override the standard $isEmpty because an empty array means the input is empty.
ctrl.$isEmpty = function(value) {
return !value || !value.length;
};
}
};
};
var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/;
/**
* @ngdoc directive
* @name ngValue
*
* @description
* Binds the given expression to the value of `input[select]` or `input[radio]`, so
* that when the element is selected, the `ngModel` of that element is set to the
* bound value.
*
* `ngValue` is useful when dynamically generating lists of radio buttons using `ng-repeat`, as
* shown below.
*
* @element input
* @param {string=} ngValue angular expression, whose value will be bound to the `value` attribute
* of the `input` element
*
* @example
<example name="ngValue-directive" module="valueExample">
<file name="index.html">
<script>
angular.module('valueExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.names = ['pizza', 'unicorns', 'robots'];
$scope.my = { favorite: 'unicorns' };
}]);
</script>
<form ng-controller="ExampleController">
<h2>Which is your favorite?</h2>
<label ng-repeat="name in names" for="{{name}}">
{{name}}
<input type="radio"
ng-model="my.favorite"
ng-value="name"
id="{{name}}"
name="favorite">
</label>
<div>You chose {{my.favorite}}</div>
</form>
</file>
<file name="protractor.js" type="protractor">
var favorite = element(by.binding('my.favorite'));
it('should initialize to model', function() {
expect(favorite.getText()).toContain('unicorns');
});
it('should bind the values to the inputs', function() {
element.all(by.model('my.favorite')).get(0).click();
expect(favorite.getText()).toContain('pizza');
});
</file>
</example>
*/
var ngValueDirective = function() {
return {
restrict: 'A',
priority: 100,
compile: function(tpl, tplAttr) {
if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) {
return function ngValueConstantLink(scope, elm, attr) {
attr.$set('value', scope.$eval(attr.ngValue));
};
} else {
return function ngValueLink(scope, elm, attr) {
scope.$watch(attr.ngValue, function valueWatchAction(value) {
attr.$set('value', value);
});
};
}
}
};
};
/**
* @ngdoc directive
* @name ngModelOptions
*
* @description
* Allows tuning how model updates are done. Using `ngModelOptions` you can specify a custom list of
* events that will trigger a model update and/or a debouncing delay so that the actual update only
* takes place when a timer expires; this timer will be reset after another change takes place.
*
* Given the nature of `ngModelOptions`, the value displayed inside input fields in the view might
* be different than the value in the actual model. This means that if you update the model you
* should also invoke {@link ngModel.NgModelController `$rollbackViewValue`} on the relevant input field in
* order to make sure it is synchronized with the model and that any debounced action is canceled.
*
* The easiest way to reference the control's {@link ngModel.NgModelController `$rollbackViewValue`}
* method is by making sure the input is placed inside a form that has a `name` attribute. This is
* important because `form` controllers are published to the related scope under the name in their
* `name` attribute.
*
* Any pending changes will take place immediately when an enclosing form is submitted via the
* `submit` event. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
* to have access to the updated model.
*
* `ngModelOptions` has an effect on the element it's declared on and its descendants.
*
* @param {Object} ngModelOptions options to apply to the current model. Valid keys are:
* - `updateOn`: string specifying which event should be the input bound to. You can set several
* events using an space delimited list. There is a special event called `default` that
* matches the default events belonging of the control.
* - `debounce`: integer value which contains the debounce model update value in milliseconds. A
* value of 0 triggers an immediate update. If an object is supplied instead, you can specify a
* custom value for each event. For example:
* `ng-model-options="{ updateOn: 'default blur', debounce: {'default': 500, 'blur': 0} }"`
* - `allowInvalid`: boolean value which indicates that the model can be set with values that did
* not validate correctly instead of the default behavior of setting the model to undefined.
* - `getterSetter`: boolean value which determines whether or not to treat functions bound to
`ngModel` as getters/setters.
* - `timezone`: Defines the timezone to be used to read/write the `Date` instance in the model for
* `<input type="date">`, `<input type="time">`, ... . Right now, the only supported value is `'UTC'`,
* otherwise the default timezone of the browser will be used.
*
* @example
The following example shows how to override immediate updates. Changes on the inputs within the
form will update the model only when the control loses focus (blur event). If `escape` key is
pressed while the input field is focused, the value is reset to the value in the current model.
<example name="ngModelOptions-directive-blur" module="optionsExample">
<file name="index.html">
<div ng-controller="ExampleController">
<form name="userForm">
Name:
<input type="text" name="userName"
ng-model="user.name"
ng-model-options="{ updateOn: 'blur' }"
ng-keyup="cancel($event)" /><br />
Other data:
<input type="text" ng-model="user.data" /><br />
</form>
<pre>user.name = <span ng-bind="user.name"></span></pre>
</div>
</file>
<file name="app.js">
angular.module('optionsExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.user = { name: 'say', data: '' };
$scope.cancel = function (e) {
if (e.keyCode == 27) {
$scope.userForm.userName.$rollbackViewValue();
}
};
}]);
</file>
<file name="protractor.js" type="protractor">
var model = element(by.binding('user.name'));
var input = element(by.model('user.name'));
var other = element(by.model('user.data'));
it('should allow custom events', function() {
input.sendKeys(' hello');
input.click();
expect(model.getText()).toEqual('say');
other.click();
expect(model.getText()).toEqual('say hello');
});
it('should $rollbackViewValue when model changes', function() {
input.sendKeys(' hello');
expect(input.getAttribute('value')).toEqual('say hello');
input.sendKeys(protractor.Key.ESCAPE);
expect(input.getAttribute('value')).toEqual('say');
other.click();
expect(model.getText()).toEqual('say');
});
</file>
</example>
This one shows how to debounce model changes. Model will be updated only 1 sec after last change.
If the `Clear` button is pressed, any debounced action is canceled and the value becomes empty.
<example name="ngModelOptions-directive-debounce" module="optionsExample">
<file name="index.html">
<div ng-controller="ExampleController">
<form name="userForm">
Name:
<input type="text" name="userName"
ng-model="user.name"
ng-model-options="{ debounce: 1000 }" />
<button ng-click="userForm.userName.$rollbackViewValue(); user.name=''">Clear</button><br />
</form>
<pre>user.name = <span ng-bind="user.name"></span></pre>
</div>
</file>
<file name="app.js">
angular.module('optionsExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.user = { name: 'say' };
}]);
</file>
</example>
This one shows how to bind to getter/setters:
<example name="ngModelOptions-directive-getter-setter" module="getterSetterExample">
<file name="index.html">
<div ng-controller="ExampleController">
<form name="userForm">
Name:
<input type="text" name="userName"
ng-model="user.name"
ng-model-options="{ getterSetter: true }" />
</form>
<pre>user.name = <span ng-bind="user.name()"></span></pre>
</div>
</file>
<file name="app.js">
angular.module('getterSetterExample', [])
.controller('ExampleController', ['$scope', function($scope) {
var _name = 'Brian';
$scope.user = {
name: function (newName) {
return angular.isDefined(newName) ? (_name = newName) : _name;
}
};
}]);
</file>
</example>
*/
var ngModelOptionsDirective = function() {
return {
restrict: 'A',
controller: ['$scope', '$attrs', function($scope, $attrs) {
var that = this;
this.$options = $scope.$eval($attrs.ngModelOptions);
// Allow adding/overriding bound events
if (this.$options.updateOn !== undefined) {
this.$options.updateOnDefault = false;
// extract "default" pseudo-event from list of events that can trigger a model update
this.$options.updateOn = trim(this.$options.updateOn.replace(DEFAULT_REGEXP, function() {
that.$options.updateOnDefault = true;
return ' ';
}));
} else {
this.$options.updateOnDefault = true;
}
}]
};
};
// helper methods
function addSetValidityMethod(context) {
var ctrl = context.ctrl,
$element = context.$element,
classCache = {},
set = context.set,
unset = context.unset,
parentForm = context.parentForm,
$animate = context.$animate;
classCache[INVALID_CLASS] = !(classCache[VALID_CLASS] = $element.hasClass(VALID_CLASS));
ctrl.$setValidity = setValidity;
function setValidity(validationErrorKey, state, options) {
if (state === undefined) {
createAndSet('$pending', validationErrorKey, options);
} else {
unsetAndCleanup('$pending', validationErrorKey, options);
}
if (!isBoolean(state)) {
unset(ctrl.$error, validationErrorKey, options);
unset(ctrl.$$success, validationErrorKey, options);
} else {
if (state) {
unset(ctrl.$error, validationErrorKey, options);
set(ctrl.$$success, validationErrorKey, options);
} else {
set(ctrl.$error, validationErrorKey, options);
unset(ctrl.$$success, validationErrorKey, options);
}
}
if (ctrl.$pending) {
cachedToggleClass(PENDING_CLASS, true);
ctrl.$valid = ctrl.$invalid = undefined;
toggleValidationCss('', null);
} else {
cachedToggleClass(PENDING_CLASS, false);
ctrl.$valid = isObjectEmpty(ctrl.$error);
ctrl.$invalid = !ctrl.$valid;
toggleValidationCss('', ctrl.$valid);
}
// re-read the state as the set/unset methods could have
// combined state in ctrl.$error[validationError] (used for forms),
// where setting/unsetting only increments/decrements the value,
// and does not replace it.
var combinedState;
if (ctrl.$pending && ctrl.$pending[validationErrorKey]) {
combinedState = undefined;
} else if (ctrl.$error[validationErrorKey]) {
combinedState = false;
} else if (ctrl.$$success[validationErrorKey]) {
combinedState = true;
} else {
combinedState = null;
}
toggleValidationCss(validationErrorKey, combinedState);
parentForm.$setValidity(validationErrorKey, combinedState, ctrl);
}
function createAndSet(name, value, options) {
if (!ctrl[name]) {
ctrl[name] = {};
}
set(ctrl[name], value, options);
}
function unsetAndCleanup(name, value, options) {
if (ctrl[name]) {
unset(ctrl[name], value, options);
}
if (isObjectEmpty(ctrl[name])) {
ctrl[name] = undefined;
}
}
function cachedToggleClass(className, switchValue) {
if (switchValue && !classCache[className]) {
$animate.addClass($element, className);
classCache[className] = true;
} else if (!switchValue && classCache[className]) {
$animate.removeClass($element, className);
classCache[className] = false;
}
}
function toggleValidationCss(validationErrorKey, isValid) {
validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
cachedToggleClass(VALID_CLASS + validationErrorKey, isValid === true);
cachedToggleClass(INVALID_CLASS + validationErrorKey, isValid === false);
}
}
function isObjectEmpty(obj) {
if (obj) {
for (var prop in obj) {
return false;
}
}
return true;
}
|
fixture `page uses an unsupported protocol`
.page`mail://yourname@yourcompany.com`;
test('Test', () => {
});
|
/*
Language: Handlebars
Requires: xml.js
Author: Robin Ward <robin.ward@gmail.com>
Description: Matcher for Handlebars as well as EmberJS additions.
*/
function(hljs) {
function copy(mode, parent) {
var result = {};
for (var key in mode) {
if (key != 'contains') {
result[key] = mode[key];
}
var contains = [];
for (var i = 0; mode.contains && i < mode.contains.length; i++) {
contains.push(copy(mode.contains[i], mode));
}
contains = HANDLEBARS_CONTAINS.concat(contains);
if (contains.length) {
result.contains = contains;
}
}
return result;
}
var EXPRESSION_KEYWORDS = "each in with if else unless bindattr action collection debugger log outlet template unbound view yield";
var VARIABLE_CONTAINS =
{
className: 'variable', begin: '[a-zA-Z\.]+',
keywords: EXPRESSION_KEYWORDS
};
var HANDLEBARS_CONTAINS = [
{
className: 'expression',
begin: '{{', end: '}}',
contains: [
{
className: 'begin-block', begin: '\#[a-zA-Z\ \.]+',
keywords: EXPRESSION_KEYWORDS
},
{
className: 'string',
begin: '"', end: '"'
},
{
className: 'end-block', begin: '\\\/[a-zA-Z\ \.]+',
keywords: EXPRESSION_KEYWORDS
},
{
className: 'variable', begin: '[a-zA-Z\.]+',
keywords: EXPRESSION_KEYWORDS
}
]
}
];
var result = copy(hljs.LANGUAGES.xml);
result.case_insensitive = true;
return result;
}
|
/**! Qoopido.demand 4.2.7-alpha.1 | https://github.com/dlueth/qoopido.demand | (c) 2018 Dirk Lueth */
!function(){"use strict";provide(["/demand/abstract/handler"],function(n){var t=/^application\/json/;function e(){}return e.prototype={validate:function(n){return t.test(n)},onPreRequest:function(n){var t=n.url.pathname;n.url.pathname=".json"!==t.slice(-".json".length)?t+".json":t},process:function(n){var t=JSON.parse(n.source);provide(function(){return t})}},new(e.extends(n))})}();
//# sourceMappingURL=json.js.map
|
// SmoothScroll v0.9.9
// Licensed under the terms of the MIT license.
// People involved
// - Balazs Galambosi: maintainer (CHANGELOG.txt)
// - Patrick Brunner (patrickb1991@gmail.com)
// - Michael Herf: ssc_pulse Algorithm
function ssc_init(){if(!document.body)return;var e=document.body;var t=document.documentElement;var n=window.innerHeight;var r=e.scrollHeight;ssc_root=document.compatMode.indexOf("CSS")>=0?t:e;ssc_activeElement=e;ssc_initdone=true;if(top!=self){ssc_frame=true}else if(r>n&&(e.offsetHeight<=n||t.offsetHeight<=n)){ssc_root.style.height="auto";if(ssc_root.offsetHeight<=n){var i=document.createElement("div");i.style.clear="both";e.appendChild(i)}}
if(!ssc_fixedback){e.style.backgroundAttachment="scroll";t.style.backgroundAttachment="scroll"}
if(ssc_keyboardsupport){ssc_addEvent("keydown",ssc_keydown)}}
function ssc_scrollArray(e,t,n,r){r||(r=1e3);ssc_directionCheck(t,n);ssc_que.push({x:t,y:n,lastX:t<0?.99:-.99,lastY:n<0?.99:-.99,start:+(new Date)});if(ssc_pending){return}
var i=function(){var s=+(new Date);var o=0;var u=0;for(var a=0;a<ssc_que.length;a++){var f=ssc_que[a];var l=s- f.start;var c=l>=ssc_animtime;var h=c?1:l/ssc_animtime;if(ssc_pulseAlgorithm){h=ssc_pulse(h)}
var p=f.x*h- f.lastX>>0;var d=f.y*h- f.lastY>>0;o+=p;u+=d;f.lastX+=p;f.lastY+=d;if(c){ssc_que.splice(a,1);a--}}
if(t){var v=e.scrollLeft;e.scrollLeft+=o;if(o&&e.scrollLeft===v){t=0}}
if(n){var m=e.scrollTop;e.scrollTop+=u;if(u&&e.scrollTop===m){n=0}}
if(!t&&!n){ssc_que=[]}
if(ssc_que.length){setTimeout(i,r/ssc_framerate+ 1)}else{ssc_pending=false}};setTimeout(i,0);ssc_pending=true}
function ssc_wheel(e){if(!ssc_initdone){ssc_init()}
var t=e.target;var n=ssc_overflowingAncestor(t);if(!n||e.defaultPrevented||ssc_isNodeName(ssc_activeElement,"embed")||ssc_isNodeName(t,"embed")&&/\.pdf/i.test(t.src)){return true}
var r=e.wheelDeltaX||0;var i=e.wheelDeltaY||0;if(!r&&!i){i=e.wheelDelta||0}
if(Math.abs(r)>1.2){r*=ssc_stepsize/120}
if(Math.abs(i)>1.2){i*=ssc_stepsize/120}
ssc_scrollArray(n,-r,-i);e.preventDefault()}
function ssc_keydown(e){var t=e.target;var n=e.ctrlKey||e.altKey||e.metaKey;if(/input|textarea|embed/i.test(t.nodeName)||t.isContentEditable||e.defaultPrevented||n){return true}
if(ssc_isNodeName(t,"button")&&e.keyCode===ssc_key.spacebar){return true}
var r,i=0,s=0;var o=ssc_overflowingAncestor(ssc_activeElement);var u=o.clientHeight;if(o==document.body){u=window.innerHeight}
switch(e.keyCode){case ssc_key.up:s=-ssc_arrowscroll;break;case ssc_key.down:s=ssc_arrowscroll;break;case ssc_key.spacebar:r=e.shiftKey?1:-1;s=-r*u*.9;break;case ssc_key.pageup:s=-u*.9;break;case ssc_key.pagedown:s=u*.9;break;case ssc_key.home:s=-o.scrollTop;break;case ssc_key.end:var a=o.scrollHeight- o.scrollTop- u;s=a>0?a+ 10:0;break;case ssc_key.left:i=-ssc_arrowscroll;break;case ssc_key.right:i=ssc_arrowscroll;break;default:return true}
ssc_scrollArray(o,i,s);e.preventDefault()}
function ssc_mousedown(e){ssc_activeElement=e.target}
function ssc_setCache(e,t){for(var n=e.length;n--;)ssc_cache[ssc_uniqueID(e[n])]=t;return t}
function ssc_overflowingAncestor(e){var t=[];var n=ssc_root.scrollHeight;do{var r=ssc_cache[ssc_uniqueID(e)];if(r){return ssc_setCache(t,r)}
t.push(e);if(n===e.scrollHeight){if(!ssc_frame||ssc_root.clientHeight+ 10<n){return ssc_setCache(t,document.body)}}else if(e.clientHeight+ 10<e.scrollHeight){overflow=getComputedStyle(e,"").getPropertyValue("overflow");if(overflow==="scroll"||overflow==="auto"){return ssc_setCache(t,e)}}}while(e=e.parentNode)}
function ssc_addEvent(e,t,n){window.addEventListener(e,t,n||false)}
function ssc_removeEvent(e,t,n){window.removeEventListener(e,t,n||false)}
function ssc_isNodeName(e,t){return e.nodeName.toLowerCase()===t.toLowerCase()}
function ssc_directionCheck(e,t){e=e>0?1:-1;t=t>0?1:-1;if(ssc_direction.x!==e||ssc_direction.y!==t){ssc_direction.x=e;ssc_direction.y=t;ssc_que=[]}}
function ssc_pulse_(e){var t,n,r;e=e*ssc_pulseScale;if(e<1){t=e-(1- Math.exp(-e))}else{n=Math.exp(-1);e-=1;r=1- Math.exp(-e);t=n+ r*(1- n)}
return t*ssc_pulseNormalize}
function ssc_pulse(e){if(e>=1)return 1;if(e<=0)return 0;if(ssc_pulseNormalize==1){ssc_pulseNormalize/=ssc_pulse_(1)}
return ssc_pulse_(e)}
var ssc_framerate=150;var ssc_animtime=500;var ssc_stepsize=150;var ssc_pulseAlgorithm=true;var ssc_pulseScale=6;var ssc_pulseNormalize=1;var ssc_keyboardsupport=true;var ssc_arrowscroll=50;var ssc_frame=false;var ssc_direction={x:0,y:0};var ssc_initdone=false;var ssc_fixedback=true;var ssc_root=document.documentElement;var ssc_activeElement;var ssc_key={left:37,up:38,right:39,down:40,spacebar:32,pageup:33,pagedown:34,end:35,home:36};var ssc_que=[];var ssc_pending=false;var ssc_cache={};setInterval(function(){ssc_cache={}},10*1e3);var ssc_uniqueID=function(){var e=0;return function(t){return t.ssc_uniqueID||(t.ssc_uniqueID=e++)}}();var ischrome=/chrome/.test(navigator.userAgent.toLowerCase());if(ischrome){ssc_addEvent("mousedown",ssc_mousedown);ssc_addEvent("mousewheel",ssc_wheel);ssc_addEvent("load",ssc_init)}
|
import cheerio from "cheerio"
import fs from "fs"
import jade from "jade"
import path from "path"
function render(locals) {
const filename = path.resolve(__dirname, "../index.jade")
return jade.compile(fs.readFileSync(filename), { filename })(locals)
}
describe("metadata template", () => {
describe("without a partner", () => {
let partnerlessArtwork
beforeEach(() => {
partnerlessArtwork = {
date: "2018",
title: "A Cat Has No Name",
partner: null,
}
})
it("renders auction closed if the auction is closed", () => {
const $ = cheerio.load(render({ artwork: partnerlessArtwork }))
$.text().should.containEql("A Cat Has No Name, 2018")
$(".artwork-metadata-stub__partner").length.should.eql(0)
})
})
describe("gallery work", () => {
let artwork
beforeEach(() => {
artwork = {
is_acquireable: false,
is_inquireable: true,
date: "2007",
title: "My Artwork",
partner: { type: "Gallery", href: "/partner/auction-partner" },
}
})
it("shows an inquiry CTA if the artwork is inquireable", () => {
const $ = cheerio.load(render({ artwork }))
$.text().should.containEql("My Artwork, 2007")
$(".artwork-metadata-stub__contact")
.text()
.should.eql("Contact gallery")
})
})
describe("non-auction work by auction partner", () => {
let artwork
beforeEach(() => {
artwork = {
is_acquireable: true,
is_inquireable: true,
date: "2007",
title: "My Artwork",
partner: { type: "Auction House", href: "/partner/auction-partner" },
}
})
it("does not show an inquiry CTA if the artwork is inquireable", () => {
const $ = cheerio.load(render({ artwork }))
$.text().should.containEql("My Artwork, 2007")
$(".artwork-metadata-stub__contact").length.should.eql(0)
})
})
describe("auction artwork", () => {
let auctionArtwork
beforeEach(() => {
auctionArtwork = {
date: "2007",
title: "My Artwork",
partner: {
type: "Auction House",
href: "/partner/auction-partner",
},
sale: {
is_auction: true,
is_closed: true,
is_live_open: false,
is_open: false,
is_preview: false,
},
sale_artwork: {
opening_bid: {
display: "$100",
},
counts: {
bidder_positions: 0,
},
},
}
})
it("renders auction closed if the auction is closed", () => {
const $ = cheerio.load(render({ artwork: auctionArtwork }))
$.text().should.containEql("My Artwork, 2007")
$(".artwork-metadata-stub__bid-now")
.text()
.should.containEql("Auction closed")
$(".artwork-metadata-stub__sale-message").length.should.eql(0)
})
it("renders enter live auction if the auction is live", () => {
auctionArtwork.sale.is_closed = false
auctionArtwork.sale.is_live_open = true
const $ = cheerio.load(render({ artwork: auctionArtwork }))
$.text().should.containEql("My Artwork, 2007")
$(".artwork-metadata-stub__bid-now")
.text()
.should.containEql("Enter Live Auction")
$(".artwork-metadata-stub__sale-message").length.should.eql(0)
})
it("renders the opening bid if the auction is in preview", () => {
auctionArtwork.sale.is_closed = false
auctionArtwork.sale.is_preview = true
const $ = cheerio.load(render({ artwork: auctionArtwork }))
$.text().should.containEql("My Artwork, 2007")
$(".artwork-metadata-stub__bid-now")
.text()
.should.containEql("$100")
$(".artwork-metadata-stub__sale-message").length.should.eql(0)
})
it('renders "Sold" if artwork is sold', () => {
auctionArtwork.is_sold = true
const $ = cheerio.load(render({ artwork: auctionArtwork }))
$.text().should.containEql("My Artwork, 2007")
$(".artwork-metadata-stub__contact.artwork-metadata-stub__line")
.text()
.should.containEql("Sold")
$(".artwork-metadata-stub__bid-now").length.should.eql(0)
})
describe("auction is open", () => {
beforeEach(() => {
auctionArtwork.sale.is_closed = false
auctionArtwork.sale.is_open = true
})
it("renders the opening bid if the auction is open and has no bids", () => {
const $ = cheerio.load(render({ artwork: auctionArtwork }))
$.text().should.containEql("My Artwork, 2007")
$(".artwork-metadata-stub__bid-now")
.text()
.should.containEql("$100")
$(".artwork-metadata-stub__sale-message").length.should.eql(0)
})
it("renders the number of bids if the auction is open and has bids", () => {
auctionArtwork.sale_artwork.counts = { bidder_positions: 3 }
auctionArtwork.sale_artwork.highest_bid = { display: "$200" }
const $ = cheerio.load(render({ artwork: auctionArtwork }))
$.text().should.containEql("My Artwork, 2007")
$(".artwork-metadata-stub__bid-now")
.text()
.should.containEql("$200")
$(".artwork-metadata-stub__bid-now")
.text()
.should.containEql("(3 bids)")
$(".artwork-metadata-stub__sale-message").length.should.eql(0)
})
})
})
})
|
'use strict';
var paths = require('./.yo-rc.json')['generator-gulp-angular'].props.paths;
// An example configuration file.
exports.config = {
// The address of a running selenium server.
//seleniumAddress: 'http://localhost:4444/wd/hub',
//seleniumServerJar: deprecated, this should be set on node_modules/protractor/config.json
// Capabilities to be passed to the webdriver instance.
capabilities: {
'browserName': 'chrome'
},
// Spec patterns are relative to the current working directly when
// protractor is called.
specs: [paths.e2e + '/**/*.js'],
// Options to be passed to Jasmine-node.
jasmineNodeOpts: {
showColors: true,
defaultTimeoutInterval: 30000
}
};
|
import PropTypes from "prop-types"
import React from "react"
import block from "bem-cn-lite"
import { connect } from "react-redux"
function LoadingSpinner({ fullscreen, isFetchingArtworks }) {
const b = block("auction-LoadingSpinner")
return (
<div className={b({ fullscreen })}>
{isFetchingArtworks && <div className="loading-spinner" />}
</div>
)
}
LoadingSpinner.propTypes = {
fullscreen: PropTypes.bool,
isFetchingArtworks: PropTypes.bool.isRequired,
}
LoadingSpinner.defaultProps = {
fullscreen: false,
}
const mapStateToProps = state => ({
isFetchingArtworks: state.artworkBrowser.isFetchingArtworks,
})
export default connect(mapStateToProps)(LoadingSpinner)
|
;(function() {
if (Jmol._debugCode)return;
|
/**
* Stores error information; delivered via [NgZone.onError] stream.
*/
export class NgZoneError {
constructor(error, stackTrace) {
this.error = error;
this.stackTrace = stackTrace;
}
}
export class NgZoneImpl {
constructor({ trace, onEnter, onLeave, setMicrotask, setMacrotask, onError }) {
this.onEnter = onEnter;
this.onLeave = onLeave;
this.setMicrotask = setMicrotask;
this.setMacrotask = setMacrotask;
this.onError = onError;
if (Zone) {
this.outer = this.inner = Zone.current;
if (Zone['wtfZoneSpec']) {
this.inner = this.inner.fork(Zone['wtfZoneSpec']);
}
if (trace && Zone['longStackTraceZoneSpec']) {
this.inner = this.inner.fork(Zone['longStackTraceZoneSpec']);
}
this.inner = this.inner.fork({
name: 'angular',
properties: { 'isAngularZone': true },
onInvokeTask: (delegate, current, target, task, applyThis, applyArgs) => {
try {
this.onEnter();
return delegate.invokeTask(target, task, applyThis, applyArgs);
}
finally {
this.onLeave();
}
},
onInvoke: (delegate, current, target, callback, applyThis, applyArgs, source) => {
try {
this.onEnter();
return delegate.invoke(target, callback, applyThis, applyArgs, source);
}
finally {
this.onLeave();
}
},
onHasTask: (delegate, current, target, hasTaskState) => {
delegate.hasTask(target, hasTaskState);
if (current == target) {
// We are only interested in hasTask events which originate from our zone
// (A child hasTask event is not interesting to us)
if (hasTaskState.change == 'microTask') {
this.setMicrotask(hasTaskState.microTask);
}
else if (hasTaskState.change == 'macroTask') {
this.setMacrotask(hasTaskState.macroTask);
}
}
},
onHandleError: (delegate, current, target, error) => {
delegate.handleError(target, error);
this.onError(new NgZoneError(error, error.stack));
return false;
}
});
}
else {
throw new Error('Angular2 needs to be run with Zone.js polyfill.');
}
}
static isInAngularZone() { return Zone.current.get('isAngularZone') === true; }
runInner(fn) { return this.inner.runGuarded(fn); }
;
runOuter(fn) { return this.outer.run(fn); }
;
}
|
/*
* ------------------------------------------
* 列表模块基类实现文件
* @version 1.0
* @author genify(caijf@corp.netease.com)
* ------------------------------------------
*/
/** @module util/list/module */
NEJ.define([
'base/global',
'base/klass',
'base/util',
'base/event',
'base/element',
'ui/item/list',
'ui/pager/pager',
'util/event',
'util/template/jst',
'util/template/tpl',
'util/cache/list'
],function(NEJ,_k,_u,_v,_e,_i0,_i1,_t0,_t1,_t2,_t3,_p,_o,_f,_r){
var _pro;
/**
* 列表模块基类
*
* @class module:util/list/module._$$ListModule
* @extends module:util/event._$$EventTarget
*
* @param {Object} config - 可选配置参数
* @property {String|Node} parent - 列表容器节点
* @property {Number} limit - 每页显示数量,默认10项
* @property {Number} first - 首页显示数量,默认为limit的值
* @property {String|Object} item - 列表JST模版标识或者Item配置,{clazz:'xxx',klass:_$$Item||'jst key',prefix:'xxx'}
* @property {Object} cache - 缓存配置信息,{key:'primary key',lkey:'list key',data:{},ext:{},klass:_$$CacheList,list:[],clear:true,total:200}
* @property {Object} pager - 分页器配置信息,{parent:'xxx',klass:_$$Pager,index:2,fixed:true}
*/
/**
* 下拉刷新列表之前处理业务逻辑,可用于处理loading状态的显示
*
* @event module:util/list/module._$$ListModule#onbeforepullrefresh
* @param {Object} event - 事件信息
* @property {Node} parent - 容器节点
* @property {String} value - 设置此参数返回用以显示loading的html代码或者节点
* @property {Boolean} stopped - 设置此参数用以表明loading已处理,后续逻辑忽略处理loading状态
*/
/**
* 下拉刷新列表载入之后处理业务逻辑,可用于处理loading状态的隐藏
*
* @event module:util/list/module._$$ListModule#onafterpullrefresh
* @param {Object} event - 事件信息
* @property {Node} parent - 容器节点
* @property {String} value - 设置此参数返回用以显示loading的html代码
* @property {Boolean} stopped - 设置此参数用以表明loading已处理,后续逻辑忽略处理loading状态
*/
/**
* 加载列表之前处理业务逻辑,可用于处理loading状态的显示
*
* @event module:util/list/module._$$ListModule#onbeforelistload
* @param {Object} event - 事件信息
* @property {Node} parent - 容器节点
* @property {String} value - 设置此参数返回用以显示loading的html代码或者节点
* @property {Boolean} stopped - 设置此参数用以表明loading已处理,后续逻辑忽略处理loading状态
*/
/**
* 列表载入之后处理业务逻辑,可用于处理loading状态的隐藏
*
* @event module:util/list/module._$$ListModule#onafterlistload
* @param {Object} event - 事件信息
* @property {Node} parent - 容器节点
* @property {String} value - 设置此参数返回用以显示loading的html代码
* @property {Boolean} stopped - 设置此参数用以表明loading已处理,后续逻辑忽略处理loading状态
*/
/**
* 为空列表时显示的信息
*
* @event module:util/list/module._$$ListModule#onemptylist
* @param {Object} event - 事件信息
* @property {Node} parent - 容器节点
* @property {String} value - 设置此参数返回用以显示的html代码
* @property {Boolean} stopped - 设置此参数用以表明已处理,后续逻辑忽略处理状态
*/
/**
* 页码变化触发事件
*
* @event module:util/list/module._$$ListModule#onpagechange
* @param {Object} event - 事件信息
* @property {Number} index - 当前页码
* @property {Boolean} stopped - 设置此参数用以表明已处理,后续逻辑忽略分页处理
*/
/**
* 列表显示之前处理业务逻辑,此事件确保列表有数据
*
* @event module:util/list/module._$$ListModule#onbeforelistrender
* @param {Object} event - 事件信息
* @property {Node} parent - 容器节点
* @property {Number} offset - 当前绘制列表偏移量
* @property {Number} limit - 当前绘制列表数量
* @property {Number} total - 当前列表总数
* @property {Array} list - 当前列表
*/
/**
* 列表显示之后处理业务逻辑,此事件确保列表有数据
*
* @event module:util/list/module._$$ListModule#onafterlistrender
* @param {Object} event - 事件信息
* @property {Node} parent - 容器节点
* @property {Number} offset - 当前绘制列表偏移量
* @property {Number} limit - 当前绘制列表数量
* @property {Number} total - 当前列表总数
* @property {Array} list - 当前列表
*/
/**
* 列表清除之前处理业务逻辑
*
* @event module:util/list/module._$$ListModule#onbeforelistclear
* @param {Object} event - 事件信息
* @property {Node} parent - 容器节点
*/
/**
* 请求更新列表项数据,主要用于处理删除之前的确认,
* 确认完成后可调用模块的_$delete接口将数据从服务器上删除
*
* @event module:util/list/module._$$ListModule#ondelete
* @param {Object} event - 列表项数据
*/
/**
* 删除列表项之前回调,主要用来预处理调用Cache中的删除接口时的信息
*
* @event module:util/list/module._$$ListModule#onbeforedelete
* @param {Object} event - 事件信息
* @property {String} id - 列表项标识
* @property {String} key - 列表标识
* @property {Object} data - 列表项数据
*/
/**
* 删除列表项之后回调,主要用来额外处理列表呈现的业务逻辑
*
* @event module:util/list/module._$$ListModule#onafterdelete
* @param {Object} event - 事件信息
* @property {String} key - 列表标识
* @property {Object} data - 删除的列表项数据
* @property {Boolean} stopped - 是否阻止列表刷新逻辑
*/
/**
* 请求更新列表项数据,针对JST模版的用户点击行为,
* 主要用于处理收集更新数据,更新数据收集完成后可调用模块的_$update接口将数据更新到服务器
*
* @event module:util/list/module._$$ListModule#onupdate
* @param {Object} event - 列表项数据
*/
/**
* 更新列表项之前回调,主要用来预处理调用Cache中的更新接口时的信息
*
* @event module:util/list/module._$$ListModule#onbeforeupdate
* @param {Object} event - 事件信息
* @property {String} id - 列表项标识
* @property {String} key - 列表标识
* @property {Object} data - 列表项数据
*/
/**
* 更新列表项之后回调,主要用来额外处理列表呈现的业务逻辑
*
* @event module:util/list/module._$$ListModule#onafterupdate
* @param {Object} event - 事件信息
* @property {String} key - 列表标识
* @property {Object} data - 删除的列表项数据
* @property {Boolean} stopped - 是否阻止列表刷新逻辑
*/
/**
* 错误处理回调
*
* @event module:util/list/module._$$ListModule#onerror
*/
_p._$$ListModule = _k._$klass();
_pro = _p._$$ListModule._$extend(_t0._$$EventTarget);
/**
* 控件重置
*
* @protected
* @method module:util/list/module._$$ListModule#__reset
* @param {Object} arg0 - 配置参数
* @return {Void}
*/
_pro.__reset = function(_options){
this.__ropt = {};
this.__super(_options);
this.__lbox = _e._$get(_options.parent);
this.__iopt = {parent:this.__lbox};
this.__limit = parseInt(_options.limit)||10;
this.__first = parseInt(_options.first)||this.__limit;
this.__doResetTemplate(_options.item);
this.__doResetCache(_options.cache||_o);
this.__doResetPager(_options.pager||_o);
this._$refresh();
};
/**
* 控件销毁
*
* @protected
* @method module:util/list/module._$$ListModule#__destroy
* @return {Void}
*/
_pro.__destroy = function(){
this._$dispatchEvent('onbeforerecycle');
this.__doClearListBox();
this.__super();
if (this.__ropt.clear){
this.__cache._$clearListInCache(this.__ropt.key);
}
this.__cache._$recycle();
if (!!this.__pager){
this.__pager._$recycle();
delete this.__pager;
}
delete this.__pkls;
delete this.__popt;
delete this.__pulling;
delete this.__cache;
delete this.__lbox;
delete this.__ikls;
delete this.__iopt;
delete this.__iext;
delete this.__ropt;
};
/**
* 根据数据ID取项节点ID
*
* @protected
* @method module:util/list/module._$$ListModule#__getItemBodyId
* @param {String} 数据ID
* @return {String} 节点ID
*/
_pro.__getItemBodyId = function(_id){
return this.__getItemId(_id)+
_t1._$seed();
};
/**
* 取项标识
*
* @protected
* @method module:util/list/module._$$ListModule#__getItemId
* @param {String} arg0 - 数据标识
* @return {String} 项标识
*/
_pro.__getItemId = function(_id){
var _prefix = (this.__iopt||_o).prefix||'';
return _prefix+_id;
};
/**
* 取当前偏移量的分页信息
*
* @protected
* @method module:util/list/module._$$ListModule#__getPageInfo
* @param {Number} arg0 - 偏移位置
* @param {Number} arg1 - 长度
* @return {Object} 分页信息,如:{index:1,total:4}
*/
_pro.__getPageInfo = function(_point,_offset,_limit,_length){
var _result = {
index:1,
total:1
};
if (_offset>=_point){
_result.index = Math.floor((_offset-_point)/_limit)+2;
}
if (_length>_point){
_result.total = Math.ceil((_length-_point)/_limit)+1;
}
return _result;
};
/**
* 重置JST模版
*
* @protected
* @method module:util/list/module._$$ListModule#__doResetJSTTemplate
* @param {String} arg0 - JST标识
* @return {Void}
*/
_pro.__doResetJSTTemplate = function(_key){
delete this.__ikls;
this.__ikey = _key;
this.__doInitDomEvent([[
this.__lbox,'click',
this.__onCheckAction._$bind(this)
]]);
};
/**
* 重置列表项模版配置
*
* @protected
* @method module:util/list/module._$$ListModule#__doResetTemplate
* @param {String|Object} arg0 - 列表项模版配置
* @return {Void}
*/
_pro.__doResetTemplate = function(_item){
// if item is jst-key
if (_u._$isString(_item)){
this.__doResetJSTTemplate(_item);
return;
}
// if item is jst with options
_u._$merge(this.__iopt,_item);
// filter jst extend function
this.__iext = _u._$merge(
{},_item,function(_it){
return !_u._$isFunction(_it);
}
);
var _klass = this.__iopt.klass;
delete this.__iopt.klass;
if (_u._$isString(_klass)){
this.__doResetJSTTemplate(_klass);
return;
}
// if item is Item template
delete this.__ikey;
this.__ikls = _klass;
this.__iopt.ondelete = this
._$dispatchEvent._$bind(this,'ondelete');
this.__iopt.onupdate = this
._$dispatchEvent._$bind(this,'onupdate');
};
/**
* 重置缓存信息配置
*
* @protected
* @method module:util/list/module._$$ListModule#__doResetCache
* @param {Object} arg0 - 缓存配置
* @return {Void}
*/
_pro.__doResetCache = function(_cache){
var _klass = _cache.klass,
_copt = _u._$merge({},_cache);
this.__ropt.key = _copt.lkey;
this.__ropt.ext = _copt.ext;
this.__ropt.data = _copt.data||{};
this.__ropt.clear = !!_copt.clear;
this.__iopt.pkey = _copt.key||'id';
_copt.onerror =
this._$dispatchEvent._$bind(this,'onerror');
_copt.onlistload =
this.__cbListLoad._$bind(this);
_copt.onpullrefresh =
this.__cbPullRefresh._$bind(this);
if (!!_klass&&('onlistchange' in _klass)){
this.__doInitDomEvent([[
_klass,'listchange',
this.__cbListChange._$bind(this)
]]);
}else{
_copt.onitemadd = this.
__cbItemAdd._$bind(this);
_copt.onitemdelete = this.
__cbItemDelete._$bind(this);
_copt.onitemupdate = this.
__cbItemUpdate._$bind(this);
}
this.__cache = (_klass||_t3._$$CacheList)._$allocate(_copt);
// set total
if (_cache.total!=null){
this.__cache._$setTotal(
this.__ropt.key,
_cache.total
);
}
// set list
if (!!_cache.list){
this.__cache._$setListInCache(
this.__ropt.key,
_cache.list
);
}
};
/**
* 重置分页器配置
*
* @protected
* @method module:util/list/module._$$ListModule#__doResetPager
* @param {Object} 分页器配置
* @return {Void}
*/
_pro.__doResetPager = function(_pager){
this.__pkls = _pager.klass||_i1._$$Pager;
this.__popt = _u._$merge({},_pager);
// parse bind pager
if (_u._$isArray(_pager.parent)){
this.__popt.parent = _pager.parent[0];
this.__pbid = _pager.parent.slice(1);
if (!this.__pbid||!this.__pbid.length){
delete this.__pbid;
}
}
delete this.__popt.klass;
};
/**
* 清理列表容器
*
* @protected
* @method module:util/list/module._$$ListModule#__doClearListBox
* @return {Void}
*/
_pro.__doClearListBox = (function(){
var _reg0 = /^(?:table|tr|tbody|ul|ol|select)$/i;
return function(){
this._$dispatchEvent('onbeforelistclear',{
parent:this.__lbox
});
if (!!this.__items&&this.__items.length>0){
this.__items = this.__ikls
._$recycle(this.__items);
delete this.__items;
}
if (_reg0.test(this.__lbox.tagName)){
_e._$clearChildren(this.__lbox);
}else{
this.__lbox.innerHTML = '';
}
};
})();
/**
* 切换分页器的显示状态
*
* @protected
* @method module:util/list/module._$$ListModule#__doSwitchPagerShow
* @return {Void}
*/
_pro.__doSwitchPagerShow = function(_display){
if (!!this.__popt.fixed) return;
_e._$setStyle(this.__popt.parent,'display',_display);
_u._$forEach(
this.__pbid,function(_parent){
_e._$setStyle(_parent,'display',_display);
},this
);
};
/**
* 通过分页器刷新当前页
*
* @protected
* @method module:util/list/module._$$ListModule#__doRefreshByPager
* @return {Void}
*/
_pro.__doRefreshByPager = function(){
var _index = this.__popt.index||1;
delete this.__popt.index;
if (!!this.__pager){
_index = this.__pager._$getIndex();
}
this.__doChangePage({
last:_index,
index:_index
});
};
/**
* 页码变化处理逻辑
*
* @protected
* @method module:util/list/module._$$ListModule#__doChangePage
* @param {Object} arg0 - 页码信息
* @return {Void}
*/
_pro.__doChangePage = function(_event){
this._$dispatchEvent('onpagechange',_event);
};
/**
* 偏移量变化处理逻辑
*
* @protected
* @method module:util/list/module._$$ListModule#__doChangeOffset
* @param {Number} arg0 - 偏移量
* @return {Void}
*/
_pro.__doChangeOffset = function(_offset){
this.__ropt.offset = _offset;
this.__doBeforeListLoad();
this.__doLoadList();
};
/**
* 生成请求对象信息
*
* @protected
* @method module:util/list/module._$$ListModule#__doGenRequestOpt
* @param {Object} arg0 - 预处理请求信息
* @return {Object} 处理后请求信息
*/
_pro.__doGenRequestOpt = function(_options){
return _options;
};
/**
* 加载数据列表
*
* @protected
* @method module:util/list/module._$$ListModule#__doLoadList
* @return {Void}
*/
_pro.__doLoadList = function(){
// load data from cache
var _data = this.__ropt.data;
_data.offset = this.__ropt.offset;
var _first = _data.offset==0;
_data.total = _first;
this.__ropt.limit =
_first?this.__first:this.__limit;
_data.limit = this.__ropt.limit;
this.__cache._$getList(
this.__doGenRequestOpt(
_u._$merge({},this.__ropt)
)
);
};
/**
* 数据列表载入完成回调
*
* @protected
* @method module:util/list/module._$$ListModule#__cbListLoad
* @param {Object} arg0 - 请求信息
* @return {Void}
*/
_pro.__cbListLoad = function(_options){
if (_options.key!=this.__ropt.key||
_options.offset!=this.__ropt.offset) return;
//console.log('list load -> '+_options.key);
this.__doBeforeListShow();
// check list
var _list = this.__cache.
_$getListInCache(_options.key);
if (!_list||!_list.length){
// check load error
if (!this._$cache()._$isLoaded(_options.key)){
this.__doShowMessage('onlistloaderror','列表加载失败');
//this._$dispatchEvent('onlistloaderror',{
// parent:this.__lbox
//});
}else{
this.__doShowEmpty();
}
return !0;
}
// render list
var _limit = _options.limit,
_offset = _options.offset;
if (!this.__cache._$isFragmentFilled(_options.key,_offset,_limit)){
this.__doShowMessage('onlistloaderror','列表加载失败');
//this._$dispatchEvent('onlistloaderror',{
// parent:this.__lbox
//});
return !0;
}
if (this.__doBeforeListRender(
_list,_offset,_limit))
return;
this._$dispatchEvent('onbeforelistrender',{
list:_list,
limit:_limit,
offset:_offset,
parent:this.__lbox,
total:this.__cache._$getTotal(_options.key)
});
if (!!this.__ikey){
// render by jst
this.__iopt.xlist = _list;
this.__iopt.beg = _offset;
this.__iopt.end = Math.min(_list.length,_offset+_limit)-1;
this.__iopt.act = 'list';
var _html = _t1._$get(
this.__ikey,
this.__iopt,
this.__iext
);
this.__doShowListByJST(_html);
}else{
// render by item
this.__iopt.limit = _limit;
this.__iopt.offset = _offset;
var _items = _t2._$getItemTemplate(
_list,this.__ikls,this.__iopt);
this.__doShowListByItem(_items);
}
this._$dispatchEvent('onafterlistrender',{
list:_list,
limit:_limit,
offset:_offset,
parent:this.__lbox,
total:this.__cache._$getTotal(_options.key)
});
};
/**
* 前向刷新数据列表载入完成回调
*
* @protected
* @method module:util/list/module._$$ListModule#__cbPullRefresh
* @param {Object} arg0 - 请求信息
* @return {Void}
*/
_pro.__cbPullRefresh = function(_options){
// unlock pulling
if (!this.__pulling)
return;
delete this.__pulling;
// recycle loading
this.__doBeforeListShow('onafterpullrefresh');
this._$refresh();
};
/**
* 同步分页器
*
* @protected
* @method module:util/list/module._$$ListModule#__doSyncPager
* @param {Number} arg0 - 页码索引
* @param {Number} arg1 - 总页数
* @return {Boolean} 是否重置页码
*/
_pro.__doSyncPager = function(_index,_total){
if (!!this.__pager){
// limit page total
if ((this.__popt||_o).limit>0){
_total = Math.min(
_total,this.__popt.limit
);
}
// check pager index and total
var _index2 = this.__pager._$getIndex(),
_total2 = this.__pager._$getTotal();
if (_index2>_total||_total!=_total2){
this.__pager._$recycle();
delete this.__pager;
this.__doChangePage({
last:_index2,
index:Math.min(_index,_total)
});
return !0;
}
}else{
// check pager instance
this.__popt.index = _index;
this.__popt.total = _total;
this.__pager = this.__pkls._$allocate(this.__popt);
this.__pager._$setEvent('onchange',this.__doChangePage._$bind(this));
_u._$forEach(
this.__pbid,function(_parent){
this.__pager._$bind(_parent);
},this
);
}
};
/**
* 格式化数据
*
* @protected
* @method module:util/list/module._$$ListModule#__doFormatData
* @param {Object} arg0 - 数据信息
* @return {Void}
*/
_pro.__doFormatData = (function(){
var _seed = +new Date;
return function(_data){
var _id = _data[this.__iopt.pkey];
if (!_id){
_data['dirty-data'] = !0;
_data[this.__iopt.pkey] = 'dirty-'+_seed++;
}
return _data;
};
})();
/**
* 分离脏数据
*
* @protected
* @method module:util/list/module._$$ListModule#__doSplitDirty
* @param {Object} arg0 - 数据信息
* @return {String} 数据标识
*/
_pro.__doSplitDirty = function(_data){
var _id = _data[this.__iopt.pkey];
if (!!_data['dirty-data']){
delete _data['dirty-data'];
delete _data[this.__iopt.pkey];
}
return _id;
};
/**
* 插入单项
*
* @protected
* @method module:util/list/module._$$ListModule#__doInsertOneItem
* @param {String} arg0 - 插入位置
* @param {Object} arg1 - 数据对象
* @return {Void}
*/
_pro.__doInsertOneItem = (function(){
var _doInsert = function(_pos,_body){
this.__lbox.insertAdjacentElement(_pos,_body);
};
return function(_pos,_data){
var _xlist = [_data];
if (!!this.__ikey){
// render by jst
var _xlist = this.__cache._$getListInCache(
this.__ropt.key
),
_index = _u._$indexOf(_xlist,_data);
if (_index<0){
_index = 0;
_xlist = [_data];
}
this.__iopt.xlist = _xlist;
this.__iopt.beg = _index;
this.__iopt.end = _index;
this.__iopt.act = 'add';
this.__doShowListByJST(
_t1._$get(
this.__ikey,
this.__iopt,
this.__iext
),_pos
);
}else{
// render by item
this.__iopt.limit = 1;
this.__iopt.offset = 0;
this.__iopt.parent =
_doInsert._$bind(this,_pos);
var _items = _t2._$getItemTemplate(
_xlist,this.__ikls,this.__iopt);
this.__iopt.parent = this.__lbox;
this.__doShowListByItem(_items);
}
this._$dispatchEvent('onafterinsert');
};
})();
/**
* 加载数据之前处理逻辑,子类实现具体业务逻辑
*
* @abstract
* @method module:util/list/module._$$ListModule#__doBeforeListLoad
* @return {Void}
*/
_pro.__doBeforeListLoad = _f;
/**
* 数据载入之后处理逻辑,子类实现具体业务逻辑
*
* @abstract
* @method module:util/list/module._$$ListModule#__doBeforeListShow
* @return {Void}
*/
_pro.__doBeforeListShow = function(_name){
var _event = {
parent:this.__lbox
};
this._$dispatchEvent(_name||'onafterlistload',_event);
if (!_event.stopped){
_e._$removeByEC(this.__ntip);
}
};
/**
* 列表绘制之前处理逻辑,子类实现具体业务逻辑
*
* @abstract
* @method module:util/list/module._$$ListModule#__doBeforeListRender
* @return {Void}
*/
_pro.__doBeforeListRender = _f;
/**
* 呈现提示信息
*
* @protected
* @method module:util/list/module._$$ListModule#__doRenderMessage
* @param {String} arg0 - 消息内容
* @param {String} arg1 - 位置信息
* @return {Void}
*/
_pro.__doRenderMessage = function(_message,_pos){
if (_u._$isString(_message)){
if (!this.__ntip)
this.__ntip = _e._$create('div');
this.__ntip.innerHTML = _message;
}else{
this.__ntip = _message;
}
this.__lbox.insertAdjacentElement(
_pos||'beforeEnd',this.__ntip
);
};
/**
* 通过事件回调检测显示信息
*
* @protected
* @method module:util/list/module._$$ListModule#__doShowMessage
* @param {String} arg0 - 事件名称
* @param {String} arg1 - 默认显示内容
* @return {Void}
*/
_pro.__doShowMessage = function(_name,_default,_pos){
var _event = {
parent:this.__lbox
};
if (!!_name){
this._$dispatchEvent(_name,_event);
}
if (!_event.stopped){
this.__doRenderMessage(
_event.value||_default,_pos
);
}
};
/**
* 列表为空时处理逻辑,子类实现具体业务逻辑
*
* @abstract
* @method module:util/list/module._$$ListModule#__doShowEmpty
* @return {Void}
*/
_pro.__doShowEmpty = _f;
/**
* 以jst模版方式绘制列表,子类实现具体业务逻辑
*
* @abstract
* @method module:util/list/module._$$ListModule#__doShowListByJST
* @return {Void}
*/
_pro.__doShowListByJST = _f;
/**
* 以item模版方式绘制列表,子类实现具体业务逻辑
*
* @abstract
* @method module:util/list/module._$$ListModule#__doShowListByItem
* @return {Void}
*/
_pro.__doShowListByItem = _f;
/**
* 检查列表行为
*
* @protected
* @method module:util/list/module._$$ListModule#__onCheckAction
* @param {Event} arg0 - 事件对象
* @return {Void}
*/
_pro.__onCheckAction = (function(){
var _reg0 = /^(?:delete|update)$/;
return function(_event){
var _node = _v._$getElement(_event,'d:action');
if (!_node) return;
var _action = _e._$dataset(_node,'action');
if (!_reg0.test(_action)) return;
var _id = _e._$dataset(_node,'id');
if (!_id) return;
var _item = this.__cache._$getItemInCache(_id);
if (!_item) return;
_v._$stop(_event);
this._$dispatchEvent('on'+_action,{
data:_item,
id:_item[this.__iopt.pkey],
body:_e._$get(this.__getItemBodyId(_id))
});
};
})();
/**
* 添加列表项回调,子类按需实现具体业务逻辑
*
* @abstract
* @method module:util/list/module._$$ListModule#__cbItemAdd
* @return {Void}
*/
_pro.__cbItemAdd = _f;
/**
* 删除列表项
*
* @protected
* @method module:util/list/module._$$ListModule#__doDeleteItem
* @param {Object} arg0 - 列表项信息
* @property {String} id - 项标识
* @property {Object} data - 项绑定的数据信息
* @return {Void}
*/
_pro.__doDeleteItem = function(_event){
var _data = _event.data||{},
_options = {
data:_data,
key:this.__ropt.key,
id:_data[this.__iopt.pkey]
};
this._$dispatchEvent('onbeforedelete',_options);
this.__cache._$deleteItem(_options);
};
/**
* 删除列表项回调,子类按需实现具体业务逻辑
*
* @abstract
* @method module:util/list/module._$$ListModule#__cbItemDelete
* @return {Void}
*/
_pro.__cbItemDelete = _f;
/**
* 更新列表项
*
* @protected
* @method module:util/list/module._$$ListModule#__doUpdateItem
* @param {Object} arg0 - 列表项信息
* @property {String} id - 项标识
* @property {Object} data - 项绑定的数据信息
* @return {Void}
*/
_pro.__doUpdateItem = function(_event){
var _data = _event.data||{},
_options = {
data:_data,
key:this.__ropt.key
};
this._$dispatchEvent('onbeforeupdate',_options);
this.__cache._$updateItem(_options);
};
/**
* 更新列表项回调,子类可按需重写具体业务逻辑
*
* @protected
* @method module:util/list/module._$$ListModule#__cbItemUpdate
* @return {Void}
*/
_pro.__cbItemUpdate = function(_event){
this.__doCheckResult(_event,'onafterupdate');
if (_event.stopped) return;
var _id = _event.data[this.__iopt.pkey];
if (!!this.__items){
var _item = _t2._$getItemById(
this.__getItemId(_id)
);
if (!!_item) _item._$refresh(_event.data);
}else{
var _node = this._$getItemBody(_id);
if (!_node) return;
var _list = this.__cache._$getListInCache(this.__ropt.key),
_index = _u._$indexOf(_list,_event.data);
if (_index<0) return;
this.__iopt.xlist = _list;
this.__iopt.beg = _index;
this.__iopt.end = _index;
this.__iopt.act = 'update';
var _html = _t1._$get(
this.__ikey,
this.__iopt,
this.__iext
);
_node.insertAdjacentHTML('afterEnd',_html);
_e._$remove(_node);
}
this._$dispatchEvent('onafterupdaterender',{
data:_event.data,
parent:this.__lbox
});
};
/**
* 验证操作结果
*
* @protected
* @method module:util/list/module._$$ListModule#__doCheckResult
* @param {Object} arg0 - 事件信息
* @return {Void}
*/
_pro.__doCheckResult = function(_event,_name){
var _item = _event.data;
if (!_item||_item[this.__iopt.pkey]==null){
this._$dispatchEvent('onerror',_event);
_event.stopped = !0;
}
if (!_event.stopped){
this._$dispatchEvent(_name,_event);
}
};
/**
* 追加数据片段回调
*
* @abstract
* @method module:util/list/module._$$ListModule#__cbAppendList
* @param {Number} arg0 - 偏移量
* @param {Number} arg1 - 数量
* @return {Void}
*/
_pro.__cbAppendList = _f;
/**
* 前向追加数据片段回调
*
* @abstract
* @method module:util/list/module._$$ListModule#__cbUnshiftList
* @param {Number} arg0 - 偏移量
* @param {Number} arg1 - 数量
* @return {Void}
*/
_pro.__cbUnshiftList = _f;
/**
* 列表变化回调(删除/添加),子类按需实现具体业务逻辑
*
* @protected
* @method module:util/list/module._$$ListModule#__cbListChange
* @return {Void}
*/
_pro.__cbListChange = function(_event){
if (!!_event.key&&
_event.key!=this.__ropt.key){
return;
}
switch(_event.action){
case 'add':
this.__cbItemAdd(_event);
break;
case 'delete':
this.__cbItemDelete(_event);
break;
case 'update':
this.__cbItemUpdate(_event);
break;
case 'refresh':
this._$refresh();
break;
case 'unshift':
this.__cbUnshiftList(
_event.offset,
_event.limit
);
break;
case 'append':
this.__cbAppendList(
_event.offset,
_event.limit
);
break;
}
};
/**
* 更新某一项数据
*
* @method module:util/list/module._$$ListModule#_$update
* @param {Object} arg0 - 需要更新的数据
* @return {Void}
*/
_pro._$update = function(_item){
this.__doUpdateItem({data:_item});
};
/**
* 删除某一项数据
*
* @method module:util/list/module._$$ListModule#_$delete
* @param {Object} arg0 - 需要删除的数据
* @return {Void}
*/
_pro._$delete = function(_item){
this.__doDeleteItem({data:_item});
};
/**
* 添加一项数据
*
* @method module:util/list/module._$$ListModule#_$add
* @param {Object} arg0 - 需要添加的数据
* @return {Void}
*/
_pro._$add = function(_item){
this.__cache._$addItem({
data:_item,
key:this.__ropt.key
});
};
/**
* 取缓存实例
*
* @method module:util/list/module._$$ListModule#_$cache
* @return {module:util/cache/list._$$CacheList} 列表缓存实例
*/
_pro._$cache = function(){
return this.__cache;
};
/**
* 往前追加列表项
*
* @method module:util/list/module._$$ListModule#_$unshift
* @param {Object} arg0 - 数据信息
* @return {Number} 插入项标识
*/
_pro._$unshift = function(_data){
this.__doInsertOneItem(
'afterBegin',
this.__doFormatData(_data)
);
return this.__doSplitDirty(_data);
};
/**
* 往后追加列表项
*
* @method module:util/list/module._$$ListModule#_$append
* @param {Object} arg0 - 数据信息
* @return {Number} 插入项标识
*/
_pro._$append = function(_data){
this.__doInsertOneItem(
'beforeEnd',
this.__doFormatData(_data)
);
return this.__doSplitDirty(_data);
};
/**
* 刷新模块
*
* @method module:util/list/module._$$ListModule#_$refresh
* @param {Number} arg0 - 刷新到的页码
* @return {Void}
*/
_pro._$refresh = function(){
this.__doClearListBox();
this.__doRefreshByPager();
};
/**
* 先清数据再刷新模块
*
* @method module:util/list/module._$$ListModule#_$refreshWithClear
* @return {Void}
*/
_pro._$refreshWithClear = function(){
this.__cache._$clearListInCache(this.__ropt.key);
this._$refresh();
};
/**
* 重新加载列表
*
* @method module:util/list/module._$$ListModule#_$reload
* @param {Boolean} arg0 - 是否清除缓存数据
* @return {Void}
*/
_pro._$reload = function(noclear){
if (!noclear){
this.__cache._$clearListInCache(this.__ropt.key);
}
this.__doLoadList();
};
/**
* 前向刷新列表
*
* @method module:util/list/module._$$ListModule#_$pullRefresh
* @return {Void}
*/
_pro._$pullRefresh = function(){
// lock pulling
if (!!this.__pulling)
return;
this.__pulling = !0;
// show loading
this.__doShowMessage(
'onbeforepullrefresh',
'列表刷新中...','afterBegin'
);
// refresh data
this.__cache._$pullRefresh({
key:this.__ropt.key,
data:this.__ropt.data
});
};
/**
* 取列表总数
*
* @method module:util/list/module._$$ListModule#_$getTotal
* @return {Number} 列表总数
*/
_pro._$getTotal = function(){
return this.__cache._$getTotal(this.__ropt.key);
};
/**
* 取分页器实例
*
* @method module:util/list/module._$$ListModule#_$getPager
* @return {Void}
*/
_pro._$getPager = function(){
return this.__pager;
};
/**
* 取ITEM列表
*
* @method module:util/list/module._$$ListModule#_$items
* @return {Array} ITEM列表
*/
_pro._$items = function(){
return this.__items;
};
/**
* 取列表项节点
*
* @method module:util/list/module._$$ListModule#_$getItemBody
* @param {String} arg0 - 数据标识
* @return {Node} 节点
*/
_pro._$getItemBody = function(_id){
if (!!this.__ikey){
// render by jst
return _e._$get(
this.__getItemBodyId(_id)
);
}else{
// render by item
var _item = _t2._$getItemById(
this.__getItemId(_id)
);
if (!!_item){
return _item._$getBody();
}
}
};
/**
* 判断列表是否载入完成
*
* @method module:util/list/module._$$ListModule#_$isLoaded
* @return {Boolean}
*/
_pro._$isLoaded = function(){
return this.__cache._$isLoaded(this.__ropt.key);
};
/**
* 显示信息
*
* @method module:util/list/module._$$ListModule#_$showMessage
* @param {String|Node} arg0 - 消息内容
* @return {Void}
*/
_pro._$showMessage = function(_html){
this.__doClearListBox();
this.__doShowMessage(null,_html);
};
/**
* 去到下一页列表
*
* @method module:util/list/module._$$ListModule#_$nextPage
* @return {Boolean} 是否还有下一页
*/
_pro._$nextPage = function(){
if (!this.__pager){
return;
}
var _index = this.__pager._$getIndex()+1,
_total = this.__pager._$getTotal();
_index = Math.max(1,Math.min(_index,_total));
this._$pageTo(_index);
return _index<_total;
};
/**
* 去到上一页列表
*
* @method module:util/list/module._$$ListModule#_$nextPage
* @return {Boolean} 是否还有上一页
*/
_pro._$prevPage = function(){
if (!this.__pager){
return;
}
var _index = this.__pager._$getIndex()-1,
_total = this.__pager._$getTotal();
_index = Math.max(1,Math.min(_index,_total));
this._$pageTo(_index);
return _index<=1;
};
/**
* 去到指定页码列表
*
* @method module:util/list/module._$$ListModule#_$pageTo
* @param {Number} arg0 - 指定页码
* @return {Void}
*/
_pro._$pageTo = function(_index){
if (!this.__pager){
return;
}
var _total = this.__pager._$getTotal();
_index = Math.max(1,Math.min(_index,_total));
this.__pager._$setIndex(_index);
};
if (CMPT){
NEJ.copy(NEJ.P('nej.ut'),_p);
}
return _p;
});
|
/*
YUI 3.18.1 (build f7e7bcb)
Copyright 2014 Yahoo! Inc. All rights reserved.
Licensed under the BSD License.
http://yuilibrary.com/license/
*/
YUI.add("series-areaspline",function(e,t){e.AreaSplineSeries=e.Base.create("areaSplineSeries",e.AreaSeries,[e.CurveUtil],{drawSeries:function(){this.drawAreaSpline()}},{ATTRS:{type:{value:"areaSpline"}}})},"3.18.1",{requires:["series-area","series-curve-util"]});
|
/* */
"format cjs";
!function(ENTRIES, FN){
function $for(iterable, entries){
if(!(this instanceof $for))return new $for(iterable, entries);
this[ITER] = getIterator(iterable);
this[ENTRIES] = !!entries;
}
createIterator($for, 'Wrapper', function(){
return this[ITER].next();
});
var $forProto = $for[PROTOTYPE];
setIterator($forProto, function(){
return this[ITER]; // unwrap
});
function createChainIterator(next){
function Iter(I, fn, that){
this[ITER] = getIterator(I);
this[ENTRIES] = I[ENTRIES];
this[FN] = ctx(fn, that, I[ENTRIES] ? 2 : 1);
}
createIterator(Iter, 'Chain', next, $forProto);
setIterator(Iter[PROTOTYPE], returnThis); // override $forProto iterator
return Iter;
}
var MapIter = createChainIterator(function(){
var step = this[ITER].next();
return step.done ? step : iterResult(0, stepCall(this[FN], step.value, this[ENTRIES]));
});
var FilterIter = createChainIterator(function(){
for(;;){
var step = this[ITER].next();
if(step.done || stepCall(this[FN], step.value, this[ENTRIES]))return step;
}
});
assignHidden($forProto, {
of: function(fn, that){
forOf(this, this[ENTRIES], fn, that);
},
array: function(fn, that){
var result = [];
forOf(fn != undefined ? this.map(fn, that) : this, false, push, result);
return result;
},
filter: function(fn, that){
return new FilterIter(this, fn, that);
},
map: function(fn, that){
return new MapIter(this, fn, that);
}
});
$for.isIterable = isIterable;
$for.getIterator = getIterator;
$define(GLOBAL + FORCED, {$for: $for});
}('entries', safeSymbol('fn'));
|
version https://git-lfs.github.com/spec/v1
oid sha256:3e5745fe9c41cd07831a0bba9edfc3efa70c1cad5677285cd2ad9fe3ec1350bc
size 9238
|
declare var foo
|
module.exports={title:"Google Drive",hex:"4285F4",source:"https://developers.google.com/drive/web/branding",svg:'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Google Drive icon</title><path d="M4.433 22.396l4-6.929H24l-4 6.929H4.433zm3.566-6.929l-3.998 6.929L0 15.467 7.785 1.98l3.999 6.931-3.785 6.556zm15.784-.375h-7.999L7.999 1.605h8.002l7.785 13.486h-.003z"/></svg>'};
|
Date.now();
|
// This gives you default context menu (cut, copy, paste)
// in all input fields and textareas across your app.
(function () {
'use strict';
var remote = require('remote');
var Menu = remote.require('menu');
var MenuItem = remote.require('menu-item');
var cut = new MenuItem({
label: "Cut",
click: function () {
document.execCommand("cut");
}
});
var copy = new MenuItem({
label: "Copy",
click: function () {
document.execCommand("copy");
}
})
var paste = new MenuItem({
label: "Paste",
click: function () {
document.execCommand("paste");
}
});
var textMenu = new Menu();
textMenu.append(cut);
textMenu.append(copy);
textMenu.append(paste);
document.addEventListener('contextmenu', function(e) {
switch (e.target.nodeName) {
case 'TEXTAREA':
case 'INPUT':
e.preventDefault();
textMenu.popup(remote.getCurrentWindow());
break;
}
}, false);
}());
|
var R = require('..');
var eq = require('./shared/eq');
describe('divide', function() {
it('divides two numbers', function() {
eq(R.divide(28, 7), 4);
});
it('is curried', function() {
var into28 = R.divide(28);
eq(into28(7), 4);
});
it('behaves right curried when passed `R.__` for its first argument', function() {
var half = R.divide(R.__, 2);
eq(half(40), 20);
});
});
|
RocketChat.settings.addGroup('WebRTC', function() {
this.add('WebRTC_Enable_Channel', false, {
type: 'boolean',
group: 'WebRTC',
'public': true
});
this.add('WebRTC_Enable_Private', true, {
type: 'boolean',
group: 'WebRTC',
'public': true
});
this.add('WebRTC_Enable_Direct', true, {
type: 'boolean',
group: 'WebRTC',
'public': true
});
return this.add('WebRTC_Servers', 'stun:stun.l.google.com:19302, stun:23.21.150.121, team%40rocket.chat:demo@turn:numb.viagenie.ca:3478', {
type: 'string',
group: 'WebRTC',
'public': true
});
});
|
module.exports =
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // identity function for calling harmory imports with the correct context
/******/ __webpack_require__.i = function(value) { return value; };
/******/ // define getter function for harmory exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ };
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 226);
/******/ })
/************************************************************************/
/******/ ({
/***/ 117:
/***/ function(module, exports) {
// removed by extract-text-webpack-plugin
/***/ },
/***/ 144:
/***/ function(module, exports, __webpack_require__) {
var __vue_exports__, __vue_options__
var __vue_styles__ = {}
/* styles */
__webpack_require__(117)
/* script */
__vue_exports__ = __webpack_require__(66)
/* template */
var __vue_template__ = __webpack_require__(188)
__vue_options__ = __vue_exports__ = __vue_exports__ || {}
if (
typeof __vue_exports__.default === "object" ||
typeof __vue_exports__.default === "function"
) {
__vue_options__ = __vue_exports__ = __vue_exports__.default
}
if (typeof __vue_options__ === "function") {
__vue_options__ = __vue_options__.options
}
__vue_options__.render = __vue_template__.render
__vue_options__.staticRenderFns = __vue_template__.staticRenderFns
module.exports = __vue_exports__
/***/ },
/***/ 188:
/***/ function(module, exports) {
module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._c;
return _h('div', {
staticClass: "mint-palette-button",
class: {
expand: _vm.expanded, 'mint-palette-button-active': _vm.transforming
},
on: {
"animationend": _vm.onMainAnimationEnd,
"webkitanimationend": _vm.onMainAnimationEnd,
"mozanimationend": _vm.onMainAnimationEnd
}
}, [_h('div', {
staticClass: "mint-sub-button-container"
}, [_vm._t("default")]), " ", _h('div', {
staticClass: "mint-main-button",
style: (_vm.mainButtonStyle),
on: {
"touchstart": _vm.toggle
}
}, ["\n " + _vm._s(_vm.content) + "\n "])])
},staticRenderFns: []}
/***/ },
/***/ 226:
/***/ function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(34);
/***/ },
/***/ 34:
/***/ function(module, exports, __webpack_require__) {
"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__src_palette_button_vue__ = __webpack_require__(144);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__src_palette_button_vue___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0__src_palette_button_vue__);
/* harmony reexport (default from non-hamory) */ __webpack_require__.d(exports, "default", function() { return __WEBPACK_IMPORTED_MODULE_0__src_palette_button_vue___default.a; });
/***/ },
/***/ 66:
/***/ function(module, exports, __webpack_require__) {
"use strict";
//
//
//
//
//
//
//
//
//
//
//
//
/* harmony default export */ exports["default"] = {
name: 'mt-palette-button',
data: function() {
return {
transforming: false, // 是否正在执行动画
expanded: false // 是否已经展开子按钮
};
},
props: {
content: {
type: String,
default: ''
},
offset: {
type: Number, // 扇面偏移角,默认是四分之π,配合默认方向lt
default: Math.PI / 4
},
direction: {
type: String,
default: 'lt' // lt t rt this.radius rb b lb l 取值有8个方向,左上、上、右上、右、右下、下、左下、左,默认为左上
},
radius: {
type: Number,
default: 90
},
mainButtonStyle: {
type: String, // 应用到 mint-main-button 上的 class
default: ''
}
},
methods: {
toggle: function toggle(event) {
if (!this.transforming) {
if (this.expanded) {
this.collapse(event);
} else {
this.expand(event);
}
}
},
onMainAnimationEnd: function onMainAnimationEnd(event) {
this.transforming = false;
this.$emit('expanded');
},
expand: function expand(event) {
this.expanded = true;
this.transforming = true;
this.$emit('expand', event);
},
collapse: function collapse(event) {
this.expanded = false;
this.$emit('collapse', event);
}
},
mounted: function mounted() {
var this$1 = this;
this.slotChildren = [];
for (var i = 0; i < this.$slots.default.length; i++) {
if (this$1.$slots.default[i].elm.nodeType !== 3) {
this$1.slotChildren.push(this$1.$slots.default[i]);
}
}
var css = '';
var direction_arc = Math.PI * (3 + Math.max(['lt', 't', 'rt', 'r', 'rb', 'b', 'lb', 'l'].indexOf(this.direction), 0)) / 4;
for (var i$1 = 0; i$1 < this.slotChildren.length; i$1++) {
var arc = (Math.PI - this$1.offset * 2) / (this$1.slotChildren.length - 1) * i$1 + this$1.offset + direction_arc;
var x = Math.cos(arc) * this$1.radius;
var y = Math.sin(arc) * this$1.radius;
var item_css = '.expand .palette-button-' + this$1._uid + '-sub-' + i$1 + '{transform:translate(' + x + 'px,' + y + 'px) rotate(720deg);transition-delay:' + 0.03 * i$1 + 's}';
css += item_css;
this$1.slotChildren[i$1].elm.className += (' palette-button-' + this$1._uid + '-sub-' + i$1);
}
this.styleNode = document.createElement('style');
this.styleNode.type = 'text/css';
this.styleNode.rel = 'stylesheet';
this.styleNode.title = 'palette button style';
this.styleNode.appendChild(document.createTextNode(css));
document.getElementsByTagName('head')[0].appendChild(this.styleNode);
},
destroyed: function destroyed() {
if (this.styleNode) {
this.styleNode.parentNode.removeChild(this.styleNode);
}
}
};
/***/ }
/******/ });
|
declare module "m";
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
importScripts('angular/modules/playground/src/web_workers/worker-configure.js');
System.config({packages: {'angular/modules/playground/src/web_workers': {defaultExtension: 'js'}}});
System.import('./background_index.js')
.catch(error => console.error('error loading background', error));
|
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(global = global || self, factory(global.sq = {}));
}(this, function (exports) { 'use strict';
var fp = typeof window !== "undefined" && window.flatpickr !== undefined
? window.flatpickr
: {
l10ns: {}
};
var Albanian = {
weekdays: {
shorthand: ["Di", "Hë", "Ma", "Më", "En", "Pr", "Sh"],
longhand: [
"E Diel",
"E Hënë",
"E Martë",
"E Mërkurë",
"E Enjte",
"E Premte",
"E Shtunë",
]
},
months: {
shorthand: [
"Jan",
"Shk",
"Mar",
"Pri",
"Maj",
"Qer",
"Kor",
"Gus",
"Sht",
"Tet",
"Nën",
"Dhj",
],
longhand: [
"Janar",
"Shkurt",
"Mars",
"Prill",
"Maj",
"Qershor",
"Korrik",
"Gusht",
"Shtator",
"Tetor",
"Nëntor",
"Dhjetor",
]
},
time_24hr: true
};
fp.l10ns.sq = Albanian;
var sq = fp.l10ns;
exports.Albanian = Albanian;
exports.default = sq;
Object.defineProperty(exports, '__esModule', { value: true });
}));
|
'use strict'
module.exports = isRegistry
function isRegistry (req) {
if (req == null) return false
// modern metadata
if ('registry' in req) return req.registry
// legacy metadata
if (req.type === 'range' || req.type === 'version' || req.type === 'tag') return true
return false
}
|
import _extends from "@babel/runtime/helpers/esm/extends";
import React from 'react';
import SvgIcon from '../SvgIcon';
/**
* Private module reserved for @material-ui/x packages.
*/
export default function createSvgIcon(path, displayName) {
var Component = function Component(props, ref) {
return /*#__PURE__*/React.createElement(SvgIcon, _extends({
ref: ref
}, props), path);
};
if (process.env.NODE_ENV !== 'production') {
// Need to set `displayName` on the inner component for React.memo.
// React prior to 16.14 ignores `displayName` on the wrapper.
Component.displayName = "".concat(displayName, "Icon");
}
Component.muiName = SvgIcon.muiName;
return /*#__PURE__*/React.memo( /*#__PURE__*/React.forwardRef(Component));
}
|
var data = {
labels: ['Bananas', 'Apples', 'Grapes'],
series: [20, 15, 40]
};
var options = {
labelInterpolationFnc: function(value) {
return value[0]
}
};
var responsiveOptions = [
['screen and (min-width: 640px)', {
chartPadding: 30,
labelOffset: 100,
labelDirection: 'explode',
labelInterpolationFnc: function(value) {
return value;
}
}],
['screen and (min-width: 1024px)', {
labelOffset: 80,
chartPadding: 20
}]
];
new Chartist.Pie('.ct-chart', data, options, responsiveOptions);
|
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "default", {
enumerable: true,
get: function () {
return _TablePagination.default;
}
});
var _TablePagination = _interopRequireDefault(require("./TablePagination"));
|
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* Facebook, Inc. ("Facebook") owns all right, title and interest, including
* all intellectual property and other proprietary rights, in and to the React
* Native CustomComponents software (the "Software"). Subject to your
* compliance with these terms, you are hereby granted a non-exclusive,
* worldwide, royalty-free copyright license to (1) use and copy the Software;
* and (2) reproduce and distribute the Software as part of your own software
* ("Your Software"). Facebook reserves all rights not expressly granted to
* you in this license agreement.
*
* THE SOFTWARE AND DOCUMENTATION, IF ANY, ARE PROVIDED "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 FACEBOOK OR ITS AFFILIATES, OFFICERS, DIRECTORS OR
* EMPLOYEES 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 THE SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @providesModule NavigatorSceneConfigs
*/
'use strict';
var Dimensions = require('Dimensions');
var I18nManager = require('I18nManager');
var PixelRatio = require('PixelRatio');
var buildStyleInterpolator = require('buildStyleInterpolator');
var IS_RTL = I18nManager.isRTL;
var SCREEN_WIDTH = Dimensions.get('window').width;
var SCREEN_HEIGHT = Dimensions.get('window').height;
var PIXEL_RATIO = PixelRatio.get();
var ToTheLeftIOS = {
transformTranslate: {
from: {x: 0, y: 0, z: 0},
to: {x: -SCREEN_WIDTH * 0.3, y: 0, z: 0},
min: 0,
max: 1,
type: 'linear',
extrapolate: true,
round: PIXEL_RATIO,
},
opacity: {
value: 1.0,
type: 'constant',
},
};
var ToTheRightIOS = {
...ToTheLeftIOS,
transformTranslate: {
from: {x: 0, y: 0, z: 0},
to: {x: SCREEN_WIDTH * 0.3, y: 0, z: 0},
},
};
var FadeToTheLeft = {
// Rotate *requires* you to break out each individual component of
// rotation (x, y, z, w)
transformTranslate: {
from: {x: 0, y: 0, z: 0},
to: {x: -Math.round(SCREEN_WIDTH * 0.3), y: 0, z: 0},
min: 0,
max: 1,
type: 'linear',
extrapolate: true,
round: PIXEL_RATIO,
},
// Uncomment to try rotation:
// Quick guide to reasoning about rotations:
// http://www.opengl-tutorial.org/intermediate-tutorials/tutorial-17-quaternions/#Quaternions
// transformRotateRadians: {
// from: {x: 0, y: 0, z: 0, w: 1},
// to: {x: 0, y: 0, z: -0.47, w: 0.87},
// min: 0,
// max: 1,
// type: 'linear',
// extrapolate: true
// },
transformScale: {
from: {x: 1, y: 1, z: 1},
to: {x: 0.95, y: 0.95, z: 1},
min: 0,
max: 1,
type: 'linear',
extrapolate: true
},
opacity: {
from: 1,
to: 0.3,
min: 0,
max: 1,
type: 'linear',
extrapolate: false,
round: 100,
},
translateX: {
from: 0,
to: -Math.round(SCREEN_WIDTH * 0.3),
min: 0,
max: 1,
type: 'linear',
extrapolate: true,
round: PIXEL_RATIO,
},
scaleX: {
from: 1,
to: 0.95,
min: 0,
max: 1,
type: 'linear',
extrapolate: true
},
scaleY: {
from: 1,
to: 0.95,
min: 0,
max: 1,
type: 'linear',
extrapolate: true
},
};
var FadeToTheRight = {
...FadeToTheLeft,
transformTranslate: {
from: {x: 0, y: 0, z: 0},
to: {x: Math.round(SCREEN_WIDTH * 0.3), y: 0, z: 0},
},
translateX: {
from: 0,
to: Math.round(SCREEN_WIDTH * 0.3),
},
};
var FadeIn = {
opacity: {
from: 0,
to: 1,
min: 0.5,
max: 1,
type: 'linear',
extrapolate: false,
round: 100,
},
};
var FadeOut = {
opacity: {
from: 1,
to: 0,
min: 0,
max: 0.5,
type: 'linear',
extrapolate: false,
round: 100,
},
};
var ToTheLeft = {
transformTranslate: {
from: {x: 0, y: 0, z: 0},
to: {x: -SCREEN_WIDTH, y: 0, z: 0},
min: 0,
max: 1,
type: 'linear',
extrapolate: true,
round: PIXEL_RATIO,
},
opacity: {
value: 1.0,
type: 'constant',
},
translateX: {
from: 0,
to: -SCREEN_WIDTH,
min: 0,
max: 1,
type: 'linear',
extrapolate: true,
round: PIXEL_RATIO,
},
};
var ToTheRight = {
transformTranslate: {
from: {x: 0, y: 0, z: 0},
to: {x: SCREEN_WIDTH, y: 0, z: 0},
min: 0,
max: 1,
type: 'linear',
extrapolate: true,
round: PIXEL_RATIO,
},
opacity: {
value: 1.0,
type: 'constant',
},
translateX: {
from: 0,
to: SCREEN_WIDTH,
min: 0,
max: 1,
type: 'linear',
extrapolate: true,
round: PIXEL_RATIO,
},
};
var ToTheUp = {
transformTranslate: {
from: {x: 0, y: 0, z: 0},
to: {x: 0, y: -SCREEN_HEIGHT, z: 0},
min: 0,
max: 1,
type: 'linear',
extrapolate: true,
round: PIXEL_RATIO,
},
opacity: {
value: 1.0,
type: 'constant',
},
translateY: {
from: 0,
to: -SCREEN_HEIGHT,
min: 0,
max: 1,
type: 'linear',
extrapolate: true,
round: PIXEL_RATIO,
},
};
var ToTheDown = {
transformTranslate: {
from: {x: 0, y: 0, z: 0},
to: {x: 0, y: SCREEN_HEIGHT, z: 0},
min: 0,
max: 1,
type: 'linear',
extrapolate: true,
round: PIXEL_RATIO,
},
opacity: {
value: 1.0,
type: 'constant',
},
translateY: {
from: 0,
to: SCREEN_HEIGHT,
min: 0,
max: 1,
type: 'linear',
extrapolate: true,
round: PIXEL_RATIO,
},
};
var FromTheRight = {
opacity: {
value: 1.0,
type: 'constant',
},
transformTranslate: {
from: {x: SCREEN_WIDTH, y: 0, z: 0},
to: {x: 0, y: 0, z: 0},
min: 0,
max: 1,
type: 'linear',
extrapolate: true,
round: PIXEL_RATIO,
},
translateX: {
from: SCREEN_WIDTH,
to: 0,
min: 0,
max: 1,
type: 'linear',
extrapolate: true,
round: PIXEL_RATIO,
},
scaleX: {
value: 1,
type: 'constant',
},
scaleY: {
value: 1,
type: 'constant',
},
};
var FromTheLeft = {
...FromTheRight,
transformTranslate: {
from: {x: -SCREEN_WIDTH, y: 0, z: 0},
to: {x: 0, y: 0, z: 0},
min: 0,
max: 1,
type: 'linear',
extrapolate: true,
round: PIXEL_RATIO,
},
translateX: {
from: -SCREEN_WIDTH,
to: 0,
min: 0,
max: 1,
type: 'linear',
extrapolate: true,
round: PIXEL_RATIO,
},
};
var FromTheDown = {
...FromTheRight,
transformTranslate: {
from: {y: SCREEN_HEIGHT, x: 0, z: 0},
to: {x: 0, y: 0, z: 0},
min: 0,
max: 1,
type: 'linear',
extrapolate: true,
round: PIXEL_RATIO,
},
translateY: {
from: SCREEN_HEIGHT,
to: 0,
min: 0,
max: 1,
type: 'linear',
extrapolate: true,
round: PIXEL_RATIO,
},
};
var FromTheTop = {
...FromTheRight,
transformTranslate: {
from: {y: -SCREEN_HEIGHT, x: 0, z: 0},
to: {x: 0, y: 0, z: 0},
min: 0,
max: 1,
type: 'linear',
extrapolate: true,
round: PIXEL_RATIO,
},
translateY: {
from: -SCREEN_HEIGHT,
to: 0,
min: 0,
max: 1,
type: 'linear',
extrapolate: true,
round: PIXEL_RATIO,
},
};
var ToTheBack = {
// Rotate *requires* you to break out each individual component of
// rotation (x, y, z, w)
transformTranslate: {
from: {x: 0, y: 0, z: 0},
to: {x: 0, y: 0, z: 0},
min: 0,
max: 1,
type: 'linear',
extrapolate: true,
round: PIXEL_RATIO,
},
transformScale: {
from: {x: 1, y: 1, z: 1},
to: {x: 0.95, y: 0.95, z: 1},
min: 0,
max: 1,
type: 'linear',
extrapolate: true
},
opacity: {
from: 1,
to: 0.3,
min: 0,
max: 1,
type: 'linear',
extrapolate: false,
round: 100,
},
scaleX: {
from: 1,
to: 0.95,
min: 0,
max: 1,
type: 'linear',
extrapolate: true
},
scaleY: {
from: 1,
to: 0.95,
min: 0,
max: 1,
type: 'linear',
extrapolate: true
},
};
var FromTheFront = {
opacity: {
value: 1.0,
type: 'constant',
},
transformTranslate: {
from: {x: 0, y: SCREEN_HEIGHT, z: 0},
to: {x: 0, y: 0, z: 0},
min: 0,
max: 1,
type: 'linear',
extrapolate: true,
round: PIXEL_RATIO,
},
translateY: {
from: SCREEN_HEIGHT,
to: 0,
min: 0,
max: 1,
type: 'linear',
extrapolate: true,
round: PIXEL_RATIO,
},
scaleX: {
value: 1,
type: 'constant',
},
scaleY: {
value: 1,
type: 'constant',
},
};
var ToTheBackAndroid = {
opacity: {
value: 1,
type: 'constant',
},
};
var FromTheFrontAndroid = {
opacity: {
from: 0,
to: 1,
min: 0.5,
max: 1,
type: 'linear',
extrapolate: false,
round: 100,
},
transformTranslate: {
from: {x: 0, y: 100, z: 0},
to: {x: 0, y: 0, z: 0},
min: 0,
max: 1,
type: 'linear',
extrapolate: true,
round: PIXEL_RATIO,
},
translateY: {
from: 100,
to: 0,
min: 0,
max: 1,
type: 'linear',
extrapolate: true,
round: PIXEL_RATIO,
},
};
var BaseOverswipeConfig = {
frictionConstant: 1,
frictionByDistance: 1.5,
};
var BaseLeftToRightGesture = {
// If the gesture can end and restart during one continuous touch
isDetachable: false,
// How far the swipe must drag to start transitioning
gestureDetectMovement: 2,
// Amplitude of release velocity that is considered still
notMoving: 0.3,
// Fraction of directional move required.
directionRatio: 0.66,
// Velocity to transition with when the gesture release was "not moving"
snapVelocity: 2,
// Region that can trigger swipe. iOS default is 30px from the left edge
edgeHitWidth: 30,
// Ratio of gesture completion when non-velocity release will cause action
stillCompletionRatio: 3 / 5,
fullDistance: SCREEN_WIDTH,
direction: 'left-to-right',
};
var BaseRightToLeftGesture = {
...BaseLeftToRightGesture,
direction: 'right-to-left',
};
var BaseDownUpGesture = {
...BaseLeftToRightGesture,
fullDistance: SCREEN_HEIGHT,
direction: 'bottom-to-top',
};
var BaseUpDownGesture = {
...BaseLeftToRightGesture,
fullDistance: SCREEN_HEIGHT,
direction: 'top-to-bottom',
};
// For RTL experiment, we need to swap all the Left and Right gesture and animation.
// So we create a direction mapping for both LTR and RTL, and change left/right to start/end.
let directionMapping = {
ToTheStartIOS: ToTheLeftIOS,
ToTheEndIOS: ToTheRightIOS,
FadeToTheStart: FadeToTheLeft,
FadeToTheEnd: FadeToTheRight,
ToTheStart: ToTheLeft,
ToTheEnd: ToTheRight,
FromTheStart: FromTheLeft,
FromTheEnd: FromTheRight,
BaseStartToEndGesture: BaseLeftToRightGesture,
BaseEndToStartGesture: BaseRightToLeftGesture,
};
if (IS_RTL) {
directionMapping = {
ToTheStartIOS: ToTheRightIOS,
ToTheEndIOS: ToTheLeftIOS,
FadeToTheStart: FadeToTheRight,
FadeToTheEnd: FadeToTheLeft,
ToTheStart: ToTheRight,
ToTheEnd: ToTheLeft,
FromTheStart: FromTheRight,
FromTheEnd: FromTheLeft,
BaseStartToEndGesture: BaseRightToLeftGesture,
BaseEndToStartGesture: BaseLeftToRightGesture,
};
}
var BaseConfig = {
// A list of all gestures that are enabled on this scene
gestures: {
pop: directionMapping.BaseStartToEndGesture,
},
// Rebound spring parameters when transitioning FROM this scene
springFriction: 26,
springTension: 200,
// Velocity to start at when transitioning without gesture
defaultTransitionVelocity: 1.5,
// Animation interpolators for horizontal transitioning:
animationInterpolators: {
into: buildStyleInterpolator(directionMapping.FromTheEnd),
out: buildStyleInterpolator(directionMapping.FadeToTheStart),
},
};
var NavigatorSceneConfigs = {
PushFromRight: {
...BaseConfig,
animationInterpolators: {
into: buildStyleInterpolator(directionMapping.FromTheEnd),
out: buildStyleInterpolator(directionMapping.ToTheStartIOS),
},
},
PushFromLeft: {
...BaseConfig,
animationInterpolators: {
into: buildStyleInterpolator(directionMapping.FromTheStart),
out: buildStyleInterpolator(directionMapping.ToTheEndIOS),
},
},
FloatFromRight: {
...BaseConfig,
// We will want to customize this soon
},
FloatFromLeft: {
...BaseConfig,
gestures: {
pop: directionMapping.BaseEndToStartGesture,
},
animationInterpolators: {
into: buildStyleInterpolator(directionMapping.FromTheStart),
out: buildStyleInterpolator(directionMapping.FadeToTheEnd),
},
},
FloatFromBottom: {
...BaseConfig,
gestures: {
pop: {
...directionMapping.BaseStartToEndGesture,
edgeHitWidth: 150,
direction: 'top-to-bottom',
fullDistance: SCREEN_HEIGHT,
}
},
animationInterpolators: {
into: buildStyleInterpolator(FromTheFront),
out: buildStyleInterpolator(ToTheBack),
},
},
FloatFromBottomAndroid: {
...BaseConfig,
gestures: null,
defaultTransitionVelocity: 3,
springFriction: 20,
animationInterpolators: {
into: buildStyleInterpolator(FromTheFrontAndroid),
out: buildStyleInterpolator(ToTheBackAndroid),
},
},
FadeAndroid: {
...BaseConfig,
gestures: null,
animationInterpolators: {
into: buildStyleInterpolator(FadeIn),
out: buildStyleInterpolator(FadeOut),
},
},
SwipeFromLeft: {
...BaseConfig,
gestures: {
jumpBack: {
...directionMapping.BaseEndToStartGesture,
overswipe: BaseOverswipeConfig,
edgeHitWidth: null,
isDetachable: true,
},
jumpForward: {
...directionMapping.BaseStartToEndGesture,
overswipe: BaseOverswipeConfig,
edgeHitWidth: null,
isDetachable: true,
},
},
animationInterpolators: {
into: buildStyleInterpolator(directionMapping.FromTheStart),
out: buildStyleInterpolator(directionMapping.ToTheEnd),
},
},
HorizontalSwipeJump: {
...BaseConfig,
gestures: {
jumpBack: {
...directionMapping.BaseStartToEndGesture,
overswipe: BaseOverswipeConfig,
edgeHitWidth: null,
isDetachable: true,
},
jumpForward: {
...directionMapping.BaseEndToStartGesture,
overswipe: BaseOverswipeConfig,
edgeHitWidth: null,
isDetachable: true,
},
},
animationInterpolators: {
into: buildStyleInterpolator(directionMapping.FromTheEnd),
out: buildStyleInterpolator(directionMapping.ToTheStart),
},
},
HorizontalSwipeJumpFromRight: {
...BaseConfig,
gestures: {
jumpBack: {
...directionMapping.BaseEndToStartGesture,
overswipe: BaseOverswipeConfig,
edgeHitWidth: null,
isDetachable: true,
},
jumpForward: {
...directionMapping.BaseStartToEndGesture,
overswipe: BaseOverswipeConfig,
edgeHitWidth: null,
isDetachable: true,
},
pop: directionMapping.BaseEndToStartGesture,
},
animationInterpolators: {
into: buildStyleInterpolator(directionMapping.FromTheStart),
out: buildStyleInterpolator(directionMapping.FadeToTheEnd),
},
},
HorizontalSwipeJumpFromLeft: {
...BaseConfig,
gestures: {
jumpBack: {
...directionMapping.BaseEndToStartGesture,
overswipe: BaseOverswipeConfig,
edgeHitWidth: null,
isDetachable: true,
},
jumpForward: {
...directionMapping.BaseStartToEndGesture,
overswipe: BaseOverswipeConfig,
edgeHitWidth: null,
isDetachable: true,
},
pop: directionMapping.BaseEndToStartGesture,
},
animationInterpolators: {
into: buildStyleInterpolator(directionMapping.FromTheStart),
out: buildStyleInterpolator(directionMapping.ToTheEnd),
},
},
VerticalUpSwipeJump: {
...BaseConfig,
gestures: {
jumpBack: {
...BaseUpDownGesture,
overswipe: BaseOverswipeConfig,
edgeHitWidth: null,
isDetachable: true,
},
jumpForward: {
...BaseDownUpGesture,
overswipe: BaseOverswipeConfig,
edgeHitWidth: null,
isDetachable: true,
},
},
animationInterpolators: {
into: buildStyleInterpolator(FromTheDown),
out: buildStyleInterpolator(ToTheUp),
},
},
VerticalDownSwipeJump: {
...BaseConfig,
gestures: {
jumpBack: {
...BaseDownUpGesture,
overswipe: BaseOverswipeConfig,
edgeHitWidth: null,
isDetachable: true,
},
jumpForward: {
...BaseUpDownGesture,
overswipe: BaseOverswipeConfig,
edgeHitWidth: null,
isDetachable: true,
},
},
animationInterpolators: {
into: buildStyleInterpolator(FromTheTop),
out: buildStyleInterpolator(ToTheDown),
},
},
};
module.exports = NavigatorSceneConfigs;
|
var apply = require('./_apply'),
createCtor = require('./_createCtor'),
root = require('./_root');
/** Used to compose bitmasks for function metadata. */
var WRAP_BIND_FLAG = 1;
/**
* Creates a function that wraps `func` to invoke it with the `this` binding
* of `thisArg` and `partials` prepended to the arguments it receives.
*
* @private
* @param {Function} func The function to wrap.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @param {*} thisArg The `this` binding of `func`.
* @param {Array} partials The arguments to prepend to those provided to
* the new function.
* @returns {Function} Returns the new wrapped function.
*/
function createPartial(func, bitmask, thisArg, partials) {
var isBind = bitmask & WRAP_BIND_FLAG,
Ctor = createCtor(func);
function wrapper() {
var argsIndex = -1,
argsLength = arguments.length,
leftIndex = -1,
leftLength = partials.length,
args = Array(leftLength + argsLength),
fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
while (++leftIndex < leftLength) {
args[leftIndex] = partials[leftIndex];
}
while (argsLength--) {
args[leftIndex++] = arguments[++argsIndex];
}
return apply(fn, isBind ? thisArg : this, args);
}
return wrapper;
}
module.exports = createPartial;
|
var Checker = require('../../../lib/checker');
var assert = require('assert');
describe('rules/disallow-arrow-functions', function() {
var checker;
beforeEach(function() {
checker = new Checker();
checker.registerDefaultRules();
checker.configure({ disallowArrowFunctions: true, esnext: true });
});
it('should report use of arrow function', function() {
assert.strictEqual(checker.checkString('a.map(n => n + 1);').getErrorCount(), 1);
});
it('should report use of multi line arrow function', function() {
assert.strictEqual(checker.checkString([
'a.map(n => {',
'return n + 1;',
'});'
].join('\n')).getErrorCount(), 1);
});
});
|
/**
* @author Tony Parisi / http://www.tonyparisi.com/
*/
THREE.glTFLoader = function () {
this.meshesRequested = 0;
this.meshesLoaded = 0;
this.pendingMeshes = [];
this.animationsRequested = 0;
this.animationsLoaded = 0;
this.animations = [];
this.shadersRequested = 0;
this.shadersLoaded = 0;
this.shaders = {};
THREE.Loader.call( this );
};
THREE.glTFLoader.prototype = Object.create( THREE.Loader.prototype );
THREE.glTFLoader.prototype.constructor = THREE.glTFLoader;
THREE.glTFLoader.prototype.load = function( url, callback ) {
var theLoader = this;
// Utilities
function RgbArraytoHex(colorArray) {
if (!colorArray) return 0xFFFFFFFF;
var r = Math.floor(colorArray[0] * 255),
g = Math.floor(colorArray[1] * 255),
b = Math.floor(colorArray[2] * 255),
a = 255;
var color = (a << 24) + (r << 16) + (g << 8) + b;
return color;
}
function convertAxisAngleToQuaternion(rotations, count)
{
var q = new THREE.Quaternion;
var axis = new THREE.Vector3;
var euler = new THREE.Vector3;
var i;
for (i = 0; i < count; i ++) {
axis.set(rotations[i * 4], rotations[i * 4 + 1],
rotations[i * 4 + 2]).normalize();
var angle = rotations[i * 4 + 3];
q.setFromAxisAngle(axis, angle);
rotations[i * 4] = q.x;
rotations[i * 4 + 1] = q.y;
rotations[i * 4 + 2] = q.z;
rotations[i * 4 + 3] = q.w;
}
}
function componentsPerElementForGLType(glType) {
switch (glType) {
case WebGLRenderingContext.FLOAT :
case WebGLRenderingContext.UNSIGNED_BYTE :
case WebGLRenderingContext.UNSIGNED_SHORT :
return 1;
case WebGLRenderingContext.FLOAT_VEC2 :
return 2;
case WebGLRenderingContext.FLOAT_VEC3 :
return 3;
case WebGLRenderingContext.FLOAT_VEC4 :
return 4;
case WebGLRenderingContext.FLOAT_MAT4 :
return 16;
default:
return null;
}
}
function LoadTexture(src) {
if (!src) { return null; }
return THREE.ImageUtils.loadTexture(src);
}
// Geometry processing
var ClassicGeometry = function() {
this.geometry = new THREE.BufferGeometry();
this.totalAttributes = 0;
this.loadedAttributes = 0;
this.indicesLoaded = false;
this.finished = false;
this.onload = null;
this.uvs = null;
this.indexArray = null;
};
ClassicGeometry.prototype.constructor = ClassicGeometry;
ClassicGeometry.prototype.buildBufferGeometry = function() {
// Build indexed mesh
var geometry = this.geometry;
geometry.addAttribute( 'index', new THREE.BufferAttribute( this.indexArray, 1 ) );
geometry.addDrawCall( 0, this.indexArray.length );
geometry.computeBoundingSphere();
};
ClassicGeometry.prototype.checkFinished = function() {
if (this.indexArray && this.loadedAttributes === this.totalAttributes) {
this.buildBufferGeometry();
this.finished = true;
if (this.onload) {
this.onload();
}
}
};
// Delegate for processing index buffers
var IndicesDelegate = function() {};
IndicesDelegate.prototype.handleError = function(errorCode, info) {
// FIXME: report error
console.log("ERROR(IndicesDelegate):" + errorCode + ":" + info);
};
IndicesDelegate.prototype.convert = function(resource, ctx) {
return new Uint16Array(resource, 0, ctx.indices.count);
};
IndicesDelegate.prototype.resourceAvailable = function(glResource, ctx) {
var geometry = ctx.geometry;
geometry.indexArray = glResource;
geometry.checkFinished();
return true;
};
var indicesDelegate = new IndicesDelegate();
var IndicesContext = function(indices, geometry) {
this.indices = indices;
this.geometry = geometry;
};
// Delegate for processing vertex attribute buffers
var VertexAttributeDelegate = function() {};
VertexAttributeDelegate.prototype.handleError = function(errorCode, info) {
// FIXME: report error
console.log("ERROR(VertexAttributeDelegate):" + errorCode + ":" + info);
};
VertexAttributeDelegate.prototype.convert = function(resource, ctx) {
return resource;
};
VertexAttributeDelegate.prototype.arrayResourceAvailable = function(glResource, ctx) {
var geom = ctx.geometry;
var attribute = ctx.attribute;
var semantic = ctx.semantic;
var floatArray;
var i, l;
//FIXME: Float32 is assumed here, but should be checked.
if (semantic == "POSITION") {
// TODO: Should be easy to take strides into account here
floatArray = new Float32Array(glResource, 0, attribute.count * componentsPerElementForGLType(attribute.type));
for (i = 0, l = floatArray.length; i < l; i += 3) {
geom.geometry.vertices.push( new THREE.Vector3( floatArray[i], floatArray[i + 1], floatArray[i + 2] ) );
}
} else if (semantic == "NORMAL") {
geom.geometry.normals = [];
floatArray = new Float32Array(glResource, 0, attribute.count * componentsPerElementForGLType(attribute.type));
for (i = 0, l = floatArray.length; i < l; i += 3) {
geom.geometry.normals.push( new THREE.Vector3( floatArray[i], floatArray[i + 1], floatArray[i + 2] ) );
}
} else if ((semantic == "TEXCOORD_0") || (semantic == "TEXCOORD" )) {
geom.uvs = [];
floatArray = new Float32Array(glResource, 0, attribute.count * componentsPerElementForGLType(attribute.type));
for (i = 0, l = floatArray.length; i < l; i += 2) {
geom.uvs.push( new THREE.Vector2( floatArray[i], 1.0 - floatArray[i + 1] ) );
}
}
else if (semantic == "WEIGHT") {
nComponents = componentsPerElementForGLType(attribute.type);
floatArray = new Float32Array(glResource, 0, attribute.count * nComponents);
for (i = 0, l = floatArray.length; i < l; i += 4) {
geom.geometry.skinWeights.push( new THREE.Vector4( floatArray[i], floatArray[i + 1], floatArray[i + 2], floatArray[i + 3] ) );
}
}
else if (semantic == "JOINT") {
nComponents = componentsPerElementForGLType(attribute.type);
floatArray = new Float32Array(glResource, 0, attribute.count * nComponents);
for (i = 0, l = floatArray.length; i < l; i += 4) {
geom.geometry.skinIndices.push( new THREE.Vector4( floatArray[i], floatArray[i + 1], floatArray[i + 2], floatArray[i + 3] ) );
}
}
};
VertexAttributeDelegate.prototype.bufferResourceAvailable = function(glResource, ctx) {
var geom = ctx.geometry;
var attribute = ctx.attribute;
var semantic = ctx.semantic;
var floatArray;
var i, l;
var nComponents;
//FIXME: Float32 is assumed here, but should be checked.
if (semantic == "POSITION") {
// TODO: Should be easy to take strides into account here
floatArray = new Float32Array(glResource, 0, attribute.count * componentsPerElementForGLType(attribute.type));
geom.geometry.addAttribute( 'position', new THREE.BufferAttribute( floatArray, 3 ) );
} else if (semantic == "NORMAL") {
floatArray = new Float32Array(glResource, 0, attribute.count * componentsPerElementForGLType(attribute.type));
geom.geometry.addAttribute( 'normal', new THREE.BufferAttribute( floatArray, 3 ) );
} else if ((semantic == "TEXCOORD_0") || (semantic == "TEXCOORD" )) {
nComponents = componentsPerElementForGLType(attribute.type);
floatArray = new Float32Array(glResource, 0, attribute.count * nComponents);
// N.B.: flip Y value... should we just set texture.flipY everywhere?
for (i = 0; i < floatArray.length / 2; i ++) {
floatArray[i * 2 + 1] = 1.0 - floatArray[i * 2 + 1];
}
geom.geometry.addAttribute( 'uv', new THREE.BufferAttribute( floatArray, nComponents ) );
}
else if (semantic == "WEIGHT") {
nComponents = componentsPerElementForGLType(attribute.type);
floatArray = new Float32Array(glResource, 0, attribute.count * nComponents);
geom.geometry.addAttribute( 'skinWeight', new THREE.BufferAttribute( floatArray, nComponents ) );
}
else if (semantic == "JOINT") {
nComponents = componentsPerElementForGLType(attribute.type);
floatArray = new Float32Array(glResource, 0, attribute.count * nComponents);
geom.geometry.addAttribute( 'skinIndex', new THREE.BufferAttribute( floatArray, nComponents ) );
}
};
VertexAttributeDelegate.prototype.resourceAvailable = function(glResource, ctx) {
this.bufferResourceAvailable(glResource, ctx);
var geom = ctx.geometry;
geom.loadedAttributes ++;
geom.checkFinished();
return true;
};
var vertexAttributeDelegate = new VertexAttributeDelegate();
var VertexAttributeContext = function(attribute, semantic, geometry) {
this.attribute = attribute;
this.semantic = semantic;
this.geometry = geometry;
};
var Mesh = function() {
this.primitives = [];
this.materialsPending = [];
this.loadedGeometry = 0;
this.onCompleteCallbacks = [];
};
Mesh.prototype.addPrimitive = function(geometry, material) {
var self = this;
geometry.onload = function() {
self.loadedGeometry ++;
self.checkComplete();
};
this.primitives.push({
geometry: geometry,
material: material,
mesh: null
});
};
Mesh.prototype.onComplete = function(callback) {
this.onCompleteCallbacks.push(callback);
this.checkComplete();
};
Mesh.prototype.checkComplete = function() {
var self = this;
if (this.onCompleteCallbacks.length && this.primitives.length == this.loadedGeometry) {
this.onCompleteCallbacks.forEach(function(callback) {
callback(self);
});
this.onCompleteCallbacks = [];
}
};
Mesh.prototype.attachToNode = function(threeNode) {
// Assumes that the geometry is complete
this.primitives.forEach(function(primitive) {
/*if(!primitive.mesh) {
primitive.mesh = new THREE.Mesh(primitive.geometry, primitive.material);
}*/
var material = primitive.material;
if (!(material instanceof THREE.Material)) {
material = theLoader.createShaderMaterial(material);
}
var threeMesh = new THREE.Mesh(primitive.geometry.geometry, material);
threeMesh.castShadow = true;
threeNode.add(threeMesh);
});
};
// Delayed-loaded material
var Material = function(params) {
this.params = params;
};
// Delegate for processing animation parameter buffers
var AnimationParameterDelegate = function() {};
AnimationParameterDelegate.prototype.handleError = function(errorCode, info) {
// FIXME: report error
console.log("ERROR(AnimationParameterDelegate):" + errorCode + ":" + info);
};
AnimationParameterDelegate.prototype.convert = function(resource, ctx) {
var parameter = ctx.parameter;
var glResource = null;
switch (parameter.type) {
case WebGLRenderingContext.FLOAT :
case WebGLRenderingContext.FLOAT_VEC2 :
case WebGLRenderingContext.FLOAT_VEC3 :
case WebGLRenderingContext.FLOAT_VEC4 :
glResource = new Float32Array(resource, 0, parameter.count * componentsPerElementForGLType(parameter.type));
break;
default:
break;
}
return glResource;
};
AnimationParameterDelegate.prototype.resourceAvailable = function(glResource, ctx) {
var animation = ctx.animation;
var parameter = ctx.parameter;
parameter.data = glResource;
animation.handleParameterLoaded(parameter);
return true;
};
var animationParameterDelegate = new AnimationParameterDelegate();
var AnimationParameterContext = function(parameter, animation) {
this.parameter = parameter;
this.animation = animation;
};
// Animations
var Animation = function() {
// create Three.js keyframe here
this.totalParameters = 0;
this.loadedParameters = 0;
this.parameters = {};
this.finishedLoading = false;
this.onload = null;
};
Animation.prototype.constructor = Animation;
Animation.prototype.handleParameterLoaded = function(parameter) {
this.parameters[parameter.name] = parameter;
this.loadedParameters ++;
this.checkFinished();
};
Animation.prototype.checkFinished = function() {
if (this.loadedParameters === this.totalParameters) {
// Build animation
this.finishedLoading = true;
if (this.onload) {
this.onload();
}
}
};
// Delegate for processing inverse bind matrices buffer
var InverseBindMatricesDelegate = function() {};
InverseBindMatricesDelegate.prototype.handleError = function(errorCode, info) {
// FIXME: report error
console.log("ERROR(InverseBindMatricesDelegate):" + errorCode + ":" + info);
};
InverseBindMatricesDelegate.prototype.convert = function(resource, ctx) {
var parameter = ctx.parameter;
var glResource = null;
switch (parameter.type) {
case WebGLRenderingContext.FLOAT_MAT4 :
glResource = new Float32Array(resource, 0, parameter.count * componentsPerElementForGLType(parameter.type));
break;
default:
break;
}
return glResource;
};
InverseBindMatricesDelegate.prototype.resourceAvailable = function(glResource, ctx) {
var skin = ctx.skin;
skin.inverseBindMatrices = glResource;
return true;
};
var inverseBindMatricesDelegate = new InverseBindMatricesDelegate();
var InverseBindMatricesContext = function(param, skin) {
this.parameter = param;
this.skin = skin;
};
// Delegate for processing shaders from external files
var ShaderDelegate = function() {};
ShaderDelegate.prototype.handleError = function(errorCode, info) {
// FIXME: report error
console.log("ERROR(ShaderDelegate):" + errorCode + ":" + info);
};
ShaderDelegate.prototype.convert = function(resource, ctx) {
return resource;
};
ShaderDelegate.prototype.resourceAvailable = function(data, ctx) {
theLoader.shadersLoaded ++;
theLoader.shaders[ctx.id] = data;
theLoader.checkComplete();
return true;
};
var shaderDelegate = new ShaderDelegate();
var ShaderContext = function(id, path) {
this.id = id;
this.path = path;
};
// Resource management
var ResourceEntry = function(entryID, object, description) {
this.entryID = entryID;
this.object = object;
this.description = description;
};
var Resources = function() {
this._entries = {};
};
Resources.prototype.setEntry = function(entryID, object, description) {
if (!entryID) {
console.error("No EntryID provided, cannot store", description);
return;
}
if (this._entries[entryID]) {
console.warn("entry[" + entryID + "] is being overwritten");
}
this._entries[entryID] = new ResourceEntry(entryID, object, description );
};
Resources.prototype.getEntry = function(entryID) {
return this._entries[entryID];
};
Resources.prototype.clearEntries = function() {
this._entries = {};
};
LoadDelegate = function() {
};
LoadDelegate.prototype.loadCompleted = function(callback, obj) {
callback.call(Window, obj);
};
// Loader
var ThreeGLTFLoader = Object.create(glTFParser, {
load: {
enumerable: true,
value: function(userInfo, options) {
this.resources = new Resources();
this.cameras = [];
this.lights = [];
this.animations = [];
this.joints = {};
this.skeltons = {};
THREE.GLTFLoaderUtils.init();
glTFParser.load.call(this, userInfo, options);
}
},
cameras: {
enumerable: true,
writable: true,
value : []
},
lights: {
enumerable: true,
writable: true,
value : []
},
animations: {
enumerable: true,
writable: true,
value : []
},
// Implement WebGLTFLoader handlers
handleBuffer: {
value: function(entryID, description, userInfo) {
this.resources.setEntry(entryID, null, description);
description.type = "ArrayBuffer";
return true;
}
},
handleBufferView: {
value: function(entryID, description, userInfo) {
this.resources.setEntry(entryID, null, description);
var buffer = this.resources.getEntry(description.buffer);
description.type = "ArrayBufferView";
var bufferViewEntry = this.resources.getEntry(entryID);
bufferViewEntry.buffer = buffer;
return true;
}
},
handleShader: {
value: function(entryID, description, userInfo) {
this.resources.setEntry(entryID, null, description);
var shaderRequest = {
id : entryID,
path : description.path,
};
var shaderContext = new ShaderContext(entryID, description.path);
theLoader.shadersRequested ++;
THREE.GLTFLoaderUtils.getFile(shaderRequest, shaderDelegate, shaderContext);
return true;
}
},
handleProgram: {
value: function(entryID, description, userInfo) {
this.resources.setEntry(entryID, null, description);
return true;
}
},
handleTechnique: {
value: function(entryID, description, userInfo) {
this.resources.setEntry(entryID, null, description);
return true;
}
},
createShaderMaterial : {
value: function(material) {
var fragmentShader = theLoader.shaders[material.params.fragmentShader];
if (!fragmentShader) {
console.log("ERROR: Missing fragment shader definition:", material.params.fragmentShader);
return new THREE.MeshPhongMaterial;
}
var vertexShader = theLoader.shaders[material.params.vertexShader];
if (!fragmentShader) {
console.log("ERROR: Missing vertex shader definition:", material.params.vertexShader);
return new THREE.MeshPhongMaterial;
}
var uniforms = {};
var shaderMaterial = new THREE.ShaderMaterial( {
fragmentShader: fragmentShader,
vertexShader: vertexShader,
uniforms: uniforms,
} );
return new THREE.MeshPhongMaterial(material.params);
}
},
createShaderParams : {
value: function(materialId, values, params, instanceProgram) {
var program = this.resources.getEntry(instanceProgram.program);
if (program) {
params.fragmentShader = program.description.fragmentShader;
params.vertexShader = program.description.vertexShader;
params.attributes = instanceProgram.attributes;
params.uniforms = instanceProgram.uniforms;
}
}
},
threeJSMaterialType : {
value: function(materialId, technique, values, params) {
var materialType = THREE.MeshPhongMaterial;
var defaultPass = null;
if (technique && technique.description && technique.description.passes)
defaultPass = technique.description.passes.defaultPass;
if (defaultPass) {
if (defaultPass.details && defaultPass.details.commonProfile) {
var profile = technique.description.passes.defaultPass.details.commonProfile;
if (profile)
{
switch (profile.lightingModel)
{
case 'Blinn' :
case 'Phong' :
materialType = THREE.MeshPhongMaterial;
break;
case 'Lambert' :
materialType = THREE.MeshLambertMaterial;
break;
default :
materialType = THREE.MeshBasicMaterial;
break;
}
if (profile.extras && profile.extras.doubleSided)
{
params.side = THREE.DoubleSide;
}
}
}
else if (defaultPass.instanceProgram) {
var instanceProgram = defaultPass.instanceProgram;
this.createShaderParams(materialId, values, params, instanceProgram);
var loadshaders = true;
if (loadshaders) {
materialType = Material;
}
}
}
var texturePath = null;
var textureParams = null;
var diffuse = values.diffuse;
if (diffuse)
{
var texture = diffuse;
if (texture) {
var textureEntry = this.resources.getEntry(texture);
if (textureEntry) {
{
var imageEntry = this.resources.getEntry(textureEntry.description.source);
if (imageEntry) {
texturePath = imageEntry.description.path;
}
var samplerEntry = this.resources.getEntry(textureEntry.description.sampler);
if (samplerEntry) {
textureParams = samplerEntry.description;
}
}
}
}
}
var texture = LoadTexture(texturePath);
if (texture && textureParams) {
if (textureParams.wrapS == WebGLRenderingContext.REPEAT)
texture.wrapS = THREE.RepeatWrapping;
if (textureParams.wrapT == WebGLRenderingContext.REPEAT)
texture.wrapT = THREE.RepeatWrapping;
if (textureParams.magFilter == WebGLRenderingContext.LINEAR)
texture.magFilter = THREE.LinearFilter;
// if (textureParams.minFilter == "LINEAR")
// texture.minFilter = THREE.LinearFilter;
params.map = texture;
}
var envMapPath = null;
var envMapParams = null;
var reflective = values.reflective;
if (reflective)
{
var texture = reflective;
if (texture) {
var textureEntry = this.resources.getEntry(texture);
if (textureEntry) {
{
var imageEntry = this.resources.getEntry(textureEntry.description.source);
if (imageEntry) {
envMapPath = imageEntry.description.path;
}
var samplerEntry = this.resources.getEntry(textureEntry.description.sampler);
if (samplerEntry) {
envMapParams = samplerEntry.description;
}
}
}
}
}
var texture = LoadTexture(envMapPath);
if (texture && envMapParams) {
if (envMapParams.wrapS == WebGLRenderingContext.REPEAT)
texture.wrapS = THREE.RepeatWrapping;
if (envMapParams.wrapT == WebGLRenderingContext.REPEAT)
texture.wrapT = THREE.RepeatWrapping;
if (envMapParams.magFilter == WebGLRenderingContext.LINEAR)
texture.magFilter = THREE.LinearFilter;
// if (envMapParams.minFilter == WebGLRenderingContext.LINEAR)
// texture.minFilter = THREE.LinearFilter;
params.envMap = texture;
}
var shininess = values.shininesss || values.shininess; // N.B.: typo in converter!
if (shininess)
{
shininess = shininess;
}
var diffuseColor = !texturePath ? diffuse : null;
var opacity = 1.0;
if (values.hasOwnProperty("transparency"))
{
var USE_A_ONE = true; // for now, hack because file format isn't telling us
opacity = USE_A_ONE ? values.transparency : (1.0 - values.transparency);
}
// if (diffuseColor) diffuseColor = [0, 1, 0];
params.color = RgbArraytoHex(diffuseColor);
params.opacity = opacity;
params.transparent = opacity < 1.0;
// hack hack hack
if (texturePath && texturePath.toLowerCase().indexOf(".png") != -1)
params.transparent = true;
if (!(shininess === undefined))
{
params.shininess = shininess;
}
if (!(values.emission === undefined))
{
params.emissive = RgbArraytoHex(values.emission);
}
if (!(values.specular === undefined))
{
params.specular = RgbArraytoHex(values.specular);
}
return materialType;
}
},
handleMaterial: {
value: function(entryID, description, userInfo) {
//this should be rewritten using the meta datas that actually create the shader.
//here we will infer what needs to be pass to Three.js by looking inside the technique parameters.
var technique = this.resources.getEntry(description.instanceTechnique.technique);
var materialParams = {};
var values = description.instanceTechnique.values;
var materialType = this.threeJSMaterialType(entryID, technique, values, materialParams);
var material = new materialType(materialParams);
this.resources.setEntry(entryID, material, description);
return true;
}
},
handleMesh: {
value: function(entryID, description, userInfo) {
var mesh = new Mesh();
this.resources.setEntry(entryID, mesh, description);
var primitivesDescription = description.primitives;
if (!primitivesDescription) {
//FIXME: not implemented in delegate
console.log("MISSING_PRIMITIVES for mesh:" + entryID);
return false;
}
for (var i = 0 ; i < primitivesDescription.length ; i ++) {
var primitiveDescription = primitivesDescription[i];
if (primitiveDescription.primitive === WebGLRenderingContext.TRIANGLES) {
var geometry = new ClassicGeometry();
var materialEntry = this.resources.getEntry(primitiveDescription.material);
mesh.addPrimitive(geometry, materialEntry.object);
var indices = this.resources.getEntry(primitiveDescription.indices);
var bufferEntry = this.resources.getEntry(indices.description.bufferView);
var indicesObject = {
bufferView : bufferEntry,
byteOffset : indices.description.byteOffset,
count : indices.description.count,
id : indices.entryID,
type : indices.description.type
};
var indicesContext = new IndicesContext(indicesObject, geometry);
var alreadyProcessedIndices = THREE.GLTFLoaderUtils.getBuffer(indicesObject, indicesDelegate, indicesContext);
/*if(alreadyProcessedIndices) {
indicesDelegate.resourceAvailable(alreadyProcessedIndices, indicesContext);
}*/
// Load Vertex Attributes
var allAttributes = Object.keys(primitiveDescription.attributes);
allAttributes.forEach( function(semantic) {
geometry.totalAttributes ++;
var attribute;
var attributeID = primitiveDescription.attributes[semantic];
var attributeEntry = this.resources.getEntry(attributeID);
if (!attributeEntry) {
//let's just use an anonymous object for the attribute
attribute = description.attributes[attributeID];
attribute.id = attributeID;
this.resources.setEntry(attributeID, attribute, attribute);
var bufferEntry = this.resources.getEntry(attribute.bufferView);
attributeEntry = this.resources.getEntry(attributeID);
} else {
attribute = attributeEntry.object;
attribute.id = attributeID;
var bufferEntry = this.resources.getEntry(attribute.bufferView);
}
var attributeObject = {
bufferView : bufferEntry,
byteOffset : attribute.byteOffset,
byteStride : attribute.byteStride,
count : attribute.count,
max : attribute.max,
min : attribute.min,
type : attribute.type,
id : attributeID
};
var attribContext = new VertexAttributeContext(attributeObject, semantic, geometry);
var alreadyProcessedAttribute = THREE.GLTFLoaderUtils.getBuffer(attributeObject, vertexAttributeDelegate, attribContext);
/*if(alreadyProcessedAttribute) {
vertexAttributeDelegate.resourceAvailable(alreadyProcessedAttribute, attribContext);
}*/
}, this);
}
}
return true;
}
},
handleCamera: {
value: function(entryID, description, userInfo) {
var camera;
if (description.type == "perspective")
{
var znear = description.perspective.znear;
var zfar = description.perspective.zfar;
var yfov = description.perspective.yfov;
var xfov = description.perspective.xfov;
var aspect_ratio = description.perspective.aspect_ratio;
if (!aspect_ratio)
aspect_ratio = 1;
if (yfov === undefined)
{
if (xfov)
{
// According to COLLADA spec...
// aspect_ratio = xfov / yfov
yfov = xfov / aspect_ratio;
}
}
if (yfov)
{
camera = new THREE.PerspectiveCamera(yfov, aspect_ratio, znear, zfar);
}
}
else
{
camera = new THREE.OrthographicCamera( window.innerWidth / - 2, window.innerWidth / 2, window.innerHeight / 2, window.innerHeight / - 2, znear, zfar );
}
if (camera)
{
this.resources.setEntry(entryID, camera, description);
}
return true;
}
},
handleLight: {
value: function(entryID, description, userInfo) {
var light = null;
var type = description.type;
if (type && description[type])
{
var lparams = description[type];
var color = RgbArraytoHex(lparams.color);
switch (type) {
case "directional" :
light = new THREE.DirectionalLight(color);
light.position.set(0, 0, 1);
break;
case "point" :
light = new THREE.PointLight(color);
break;
case "spot " :
light = new THREE.SpotLight(color);
light.position.set(0, 0, 1);
break;
case "ambient" :
light = new THREE.AmbientLight(color);
break;
}
}
if (light)
{
this.resources.setEntry(entryID, light, description);
}
return true;
}
},
addPendingMesh: {
value: function(mesh, threeNode) {
theLoader.pendingMeshes.push({
mesh: mesh,
node: threeNode
});
}
},
handleNode: {
value: function(entryID, description, userInfo) {
var threeNode = null;
if (description.jointId) {
threeNode = new THREE.Bone();
threeNode.jointId = description.jointId;
this.joints[description.jointId] = entryID;
}
else {
threeNode = new THREE.Object3D();
}
threeNode.name = description.name;
this.resources.setEntry(entryID, threeNode, description);
var m = description.matrix;
if (m) {
threeNode.applyMatrix(new THREE.Matrix4().fromArray( m ));
threeNode.matrixAutoUpdate = false;
threeNode.matrixWorldNeedsUpdate = true;
}
else {
var t = description.translation;
var r = description.rotation;
var s = description.scale;
var position = t ? new THREE.Vector3(t[0], t[1], t[2]) :
new THREE.Vector3;
if (r) {
convertAxisAngleToQuaternion(r, 1);
}
var rotation = r ? new THREE.Quaternion(r[0], r[1], r[2], r[3]) :
new THREE.Quaternion;
var scale = s ? new THREE.Vector3(s[0], s[1], s[2]) :
new THREE.Vector3;
var matrix = new THREE.Matrix4;
matrix.compose(position, rotation, scale);
threeNode.matrixAutoUpdate = false;
threeNode.matrixWorldNeedsUpdate = true;
threeNode.applyMatrix(matrix);
}
var self = this;
// Iterate through all node meshes and attach the appropriate objects
//FIXME: decision needs to be made between these 2 ways, probably meshes will be discarded.
var meshEntry;
if (description.mesh) {
meshEntry = this.resources.getEntry(description.mesh);
theLoader.meshesRequested ++;
meshEntry.object.onComplete(function(mesh) {
self.addPendingMesh(mesh, threeNode);
theLoader.meshesLoaded ++;
theLoader.checkComplete();
});
}
if (description.meshes) {
description.meshes.forEach( function(meshID) {
meshEntry = this.resources.getEntry(meshID);
theLoader.meshesRequested ++;
meshEntry.object.onComplete(function(mesh) {
self.addPendingMesh(mesh, threeNode);
theLoader.meshesLoaded ++;
theLoader.checkComplete();
});
}, this);
}
if (description.instanceSkin) {
var skinEntry = this.resources.getEntry(description.instanceSkin.skin);
if (skinEntry) {
var skin = skinEntry.object;
description.instanceSkin.skin = skin;
threeNode.instanceSkin = description.instanceSkin;
var sources = description.instanceSkin.sources;
skin.meshes = [];
sources.forEach( function(meshID) {
meshEntry = this.resources.getEntry(meshID);
theLoader.meshesRequested ++;
meshEntry.object.onComplete(function(mesh) {
skin.meshes.push(mesh);
theLoader.meshesLoaded ++;
theLoader.checkComplete();
});
}, this);
}
}
if (description.camera) {
var cameraEntry = this.resources.getEntry(description.camera);
if (cameraEntry) {
threeNode.add(cameraEntry.object);
this.cameras.push(cameraEntry.object);
}
}
if (description.light) {
var lightEntry = this.resources.getEntry(description.light);
if (lightEntry) {
threeNode.add(lightEntry.object);
this.lights.push(lightEntry.object);
}
}
return true;
}
},
buildNodeHirerachy: {
value: function(nodeEntryId, parentThreeNode) {
var nodeEntry = this.resources.getEntry(nodeEntryId);
var threeNode = nodeEntry.object;
parentThreeNode.add(threeNode);
var children = nodeEntry.description.children;
if (children) {
children.forEach( function(childID) {
this.buildNodeHirerachy(childID, threeNode);
}, this);
}
return threeNode;
}
},
buildSkin: {
value: function(node) {
var skin = node.instanceSkin.skin;
if (skin) {
node.instanceSkin.skeletons.forEach(function(skeleton) {
var nodeEntry = this.resources.getEntry(skeleton);
if (nodeEntry) {
var rootSkeleton = nodeEntry.object;
var dobones = true;
var i, len = skin.meshes.length;
for (i = 0; i < len; i ++) {
var mesh = skin.meshes[i];
var threeMesh = null;
mesh.primitives.forEach(function(primitive) {
var material = primitive.material;
if (!(material instanceof THREE.Material)) {
material = this.createShaderMaterial(material);
}
threeMesh = new THREE.SkinnedMesh(primitive.geometry.geometry, material, false);
threeMesh.add(rootSkeleton);
var geometry = primitive.geometry.geometry;
var j;
if (geometry.vertices) {
for ( j = 0; j < geometry.vertices.length; j ++ ) {
geometry.vertices[j].applyMatrix4( skin.bindShapeMatrix );
}
}
else if (geometry.attributes.position) {
var a = geometry.attributes.position.array;
var v = new THREE.Vector3;
for ( j = 0; j < a.length / 3; j ++ ) {
v.set(a[j * 3], a[j * 3 + 1], a[j * 3 + 2]);
v.applyMatrix4( skin.bindShapeMatrix );
a[j * 3] = v.x;
a[j * 3 + 1] = v.y;
a[j * 3 + 2] = v.z;
}
}
if (threeMesh && dobones) {
material.skinning = true;
threeMesh.boneInverses = [];
var jointsIds = skin.jointsIds;
var bones = [];
var boneInverses = [];
var i, len = jointsIds.length;
for (i = 0; i < len; i ++) {
var jointId = jointsIds[i];
var nodeForJoint = this.joints[jointId];
var joint = this.resources.getEntry(nodeForJoint).object;
if (joint) {
joint.skin = threeMesh;
bones.push(joint);
var m = skin.inverseBindMatrices;
var mat = new THREE.Matrix4().set(
m[i * 16 + 0], m[i * 16 + 4], m[i * 16 + 8], m[i * 16 + 12],
m[i * 16 + 1], m[i * 16 + 5], m[i * 16 + 9], m[i * 16 + 13],
m[i * 16 + 2], m[i * 16 + 6], m[i * 16 + 10], m[i * 16 + 14],
m[i * 16 + 3], m[i * 16 + 7], m[i * 16 + 11], m[i * 16 + 15]
);
boneInverses.push(mat);
} else {
console.log("WARNING: jointId:" + jointId + " cannot be found in skeleton:" + skeleton);
}
}
threeMesh.bind( new THREE.Skeleton( bones, boneInverses, false ), threeMesh.matrixWorld );
}
if (threeMesh) {
threeMesh.castShadow = true;
node.add(threeMesh);
}
}, this);
}
}
}, this);
}
}
},
buildSkins: {
value: function(node) {
if (node.instanceSkin)
this.buildSkin(node);
var children = node.children;
if (children) {
children.forEach( function(child) {
this.buildSkins(child);
}, this);
}
}
},
createMeshAnimations : {
value : function(root) {
this.buildSkins(root);
}
},
handleScene: {
value: function(entryID, description, userInfo) {
if (!description.nodes) {
console.log("ERROR: invalid file required nodes property is missing from scene");
return false;
}
description.nodes.forEach( function(nodeUID) {
this.buildNodeHirerachy(nodeUID, userInfo.rootObj);
}, this);
if (this.delegate) {
this.delegate.loadCompleted(userInfo.callback, userInfo.rootObj);
}
return true;
}
},
handleImage: {
value: function(entryID, description, userInfo) {
this.resources.setEntry(entryID, null, description);
return true;
}
},
addNodeAnimationChannel : {
value : function(name, channel, interp) {
if (!this.nodeAnimationChannels)
this.nodeAnimationChannels = {};
if (!this.nodeAnimationChannels[name]) {
this.nodeAnimationChannels[name] = [];
}
this.nodeAnimationChannels[name].push(interp);
},
},
createAnimations : {
value : function() {
for (var name in this.nodeAnimationChannels) {
var nodeAnimationChannels = this.nodeAnimationChannels[name];
var i, len = nodeAnimationChannels.length;
//console.log(" animation channels for node " + name);
//for (i = 0; i < len; i++) {
// console.log(nodeAnimationChannels[i]);
//}
var anim = new THREE.glTFAnimation(nodeAnimationChannels);
anim.name = "animation_" + name;
this.animations.push(anim);
}
}
},
buildAnimation: {
value : function(animation) {
var interps = [];
var i, len = animation.channels.length;
for (i = 0; i < len; i ++) {
var channel = animation.channels[i];
var sampler = animation.samplers[channel.sampler];
if (sampler) {
var input = animation.parameters[sampler.input];
if (input && input.data) {
var output = animation.parameters[sampler.output];
if (output && output.data) {
var target = channel.target;
var node = this.resources.getEntry(target.id);
if (node) {
var path = target.path;
if (path == "rotation")
{
convertAxisAngleToQuaternion(output.data, output.count);
}
var interp = {
keys : input.data,
values : output.data,
count : input.count,
target : node.object,
path : path,
type : sampler.interpolation
};
this.addNodeAnimationChannel(target.id, channel, interp);
interps.push(interp);
}
}
}
}
}
}
},
handleAnimation: {
value: function(entryID, description, userInfo) {
var self = this;
theLoader.animationsRequested ++;
var animation = new Animation();
animation.name = entryID;
animation.onload = function() {
// self.buildAnimation(animation);
theLoader.animationsLoaded ++;
theLoader.animations.push(animation);
theLoader.checkComplete();
};
animation.channels = description.channels;
animation.samplers = description.samplers;
this.resources.setEntry(entryID, animation, description);
var parameters = description.parameters;
if (!parameters) {
//FIXME: not implemented in delegate
console.log("MISSING_PARAMETERS for animation:" + entryID);
return false;
}
// Load parameter buffers
var params = Object.keys(parameters);
params.forEach( function(param) {
animation.totalParameters ++;
var parameter = parameters[param];
var accessor = this.resources.getEntry(parameter);
if (!accessor)
debugger;
accessor = accessor.object;
var bufferView = this.resources.getEntry(accessor.bufferView);
var paramObject = {
bufferView : bufferView,
byteOffset : accessor.byteOffset,
count : accessor.count,
type : accessor.type,
id : accessor.bufferView,
name : param
};
var paramContext = new AnimationParameterContext(paramObject, animation);
var alreadyProcessedAttribute = THREE.GLTFLoaderUtils.getBuffer(paramObject, animationParameterDelegate, paramContext);
/*if(alreadyProcessedAttribute) {
vertexAttributeDelegate.resourceAvailable(alreadyProcessedAttribute, attribContext);
}*/
}, this);
return true;
}
},
handleAccessor: {
value: function(entryID, description, userInfo) {
// Save attribute entry
this.resources.setEntry(entryID, description, description);
return true;
}
},
handleSkin: {
value: function(entryID, description, userInfo) {
// Save skin entry
var skin = {
};
var m = description.bindShapeMatrix;
skin.bindShapeMatrix = new THREE.Matrix4().fromArray( m );
skin.jointsIds = description.joints;
var inverseBindMatricesDescription = description.inverseBindMatrices;
skin.inverseBindMatricesDescription = inverseBindMatricesDescription;
skin.inverseBindMatricesDescription.id = entryID + "_inverseBindMatrices";
var bufferEntry = this.resources.getEntry(inverseBindMatricesDescription.bufferView);
var paramObject = {
bufferView : bufferEntry,
byteOffset : inverseBindMatricesDescription.byteOffset,
count : inverseBindMatricesDescription.count,
type : inverseBindMatricesDescription.type,
id : inverseBindMatricesDescription.bufferView,
name : skin.inverseBindMatricesDescription.id
};
var context = new InverseBindMatricesContext(paramObject, skin);
var alreadyProcessedAttribute = THREE.GLTFLoaderUtils.getBuffer(paramObject, inverseBindMatricesDelegate, context);
var bufferView = this.resources.getEntry(skin.inverseBindMatricesDescription.bufferView);
skin.inverseBindMatricesDescription.bufferView =
bufferView.object;
this.resources.setEntry(entryID, skin, description);
return true;
}
},
handleSampler: {
value: function(entryID, description, userInfo) {
// Save attribute entry
this.resources.setEntry(entryID, description, description);
return true;
}
},
handleTexture: {
value: function(entryID, description, userInfo) {
// Save attribute entry
this.resources.setEntry(entryID, null, description);
return true;
}
},
handleError: {
value: function(msg) {
throw new Error(msg);
return true;
}
},
_delegate: {
value: new LoadDelegate,
writable: true
},
delegate: {
enumerable: true,
get: function() {
return this._delegate;
},
set: function(value) {
this._delegate = value;
}
}
});
// Loader
var Context = function(rootObj, callback) {
this.rootObj = rootObj;
this.callback = callback;
};
var rootObj = new THREE.Object3D();
var self = this;
var loader = Object.create(ThreeGLTFLoader);
loader.initWithPath(url);
loader.load(new Context(rootObj,
function(obj) {
}),
null);
this.loader = loader;
this.callback = callback;
this.rootObj = rootObj;
return rootObj;
};
THREE.glTFLoader.prototype.callLoadedCallback = function() {
var result = {
scene : this.rootObj,
cameras : this.loader.cameras,
animations : this.loader.animations,
};
this.callback(result);
};
THREE.glTFLoader.prototype.checkComplete = function() {
if (this.meshesLoaded == this.meshesRequested
&& this.shadersLoaded == this.shadersRequested
&& this.animationsLoaded == this.animationsRequested)
{
for (var i = 0; i < this.pendingMeshes.length; i ++) {
var pending = this.pendingMeshes[i];
pending.mesh.attachToNode(pending.node);
}
for (var i = 0; i < this.animationsLoaded; i ++) {
var animation = this.animations[i];
this.loader.buildAnimation(animation);
}
this.loader.createAnimations();
this.loader.createMeshAnimations(this.rootObj);
this.callLoadedCallback();
}
};
|
/**
* @fileoverview Config initialization wizard.
* @author Ilya Volodin
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const util = require("util"),
inquirer = require("inquirer"),
ProgressBar = require("progress"),
semver = require("semver"),
autoconfig = require("./autoconfig.js"),
ConfigFile = require("./config-file"),
ConfigOps = require("./config-ops"),
getSourceCodeOfFiles = require("../util/source-code-util").getSourceCodeOfFiles,
ModuleResolver = require("../util/module-resolver"),
npmUtil = require("../util/npm-util"),
recConfig = require("../../conf/eslint-recommended"),
log = require("../logging");
const debug = require("debug")("eslint:config-initializer");
//------------------------------------------------------------------------------
// Private
//------------------------------------------------------------------------------
/* istanbul ignore next: hard to test fs function */
/**
* Create .eslintrc file in the current working directory
* @param {Object} config object that contains user's answers
* @param {string} format The file format to write to.
* @returns {void}
*/
function writeFile(config, format) {
// default is .js
let extname = ".js";
if (format === "YAML") {
extname = ".yml";
} else if (format === "JSON") {
extname = ".json";
}
const installedESLint = config.installedESLint;
delete config.installedESLint;
ConfigFile.write(config, `./.eslintrc${extname}`);
log.info(`Successfully created .eslintrc${extname} file in ${process.cwd()}`);
if (installedESLint) {
log.info("ESLint was installed locally. We recommend using this local copy instead of your globally-installed copy.");
}
}
/**
* Get the peer dependencies of the given module.
* This adds the gotten value to cache at the first time, then reuses it.
* In a process, this function is called twice, but `npmUtil.fetchPeerDependencies` needs to access network which is relatively slow.
* @param {string} moduleName The module name to get.
* @returns {Object} The peer dependencies of the given module.
* This object is the object of `peerDependencies` field of `package.json`.
* Returns null if npm was not found.
*/
function getPeerDependencies(moduleName) {
let result = getPeerDependencies.cache.get(moduleName);
if (!result) {
log.info(`Checking peerDependencies of ${moduleName}`);
result = npmUtil.fetchPeerDependencies(moduleName);
getPeerDependencies.cache.set(moduleName, result);
}
return result;
}
getPeerDependencies.cache = new Map();
/**
* Synchronously install necessary plugins, configs, parsers, etc. based on the config
* @param {Object} config config object
* @param {boolean} [installESLint=true] If `false` is given, it does not install eslint.
* @returns {void}
*/
function installModules(config, installESLint) {
const modules = {};
// Create a list of modules which should be installed based on config
if (config.plugins) {
for (const plugin of config.plugins) {
modules[`eslint-plugin-${plugin}`] = "latest";
}
}
if (config.extends && config.extends.indexOf("eslint:") === -1) {
const moduleName = `eslint-config-${config.extends}`;
modules[moduleName] = "latest";
Object.assign(
modules,
getPeerDependencies(`${moduleName}@latest`)
);
}
// If no modules, do nothing.
if (Object.keys(modules).length === 0) {
return;
}
if (installESLint === false) {
delete modules.eslint;
} else {
const installStatus = npmUtil.checkDevDeps(["eslint"]);
// Mark to show messages if it's new installation of eslint.
if (installStatus.eslint === false) {
log.info("Local ESLint installation not found.");
modules.eslint = modules.eslint || "latest";
config.installedESLint = true;
}
}
// Install packages
const modulesToInstall = Object.keys(modules).map(name => `${name}@${modules[name]}`);
log.info(`Installing ${modulesToInstall.join(", ")}`);
npmUtil.installSyncSaveDev(modulesToInstall);
}
/**
* Set the `rules` of a config by examining a user's source code
*
* Note: This clones the config object and returns a new config to avoid mutating
* the original config parameter.
*
* @param {Object} answers answers received from inquirer
* @param {Object} config config object
* @returns {Object} config object with configured rules
*/
function configureRules(answers, config) {
const BAR_TOTAL = 20,
BAR_SOURCE_CODE_TOTAL = 4,
newConfig = Object.assign({}, config),
disabledConfigs = {};
let sourceCodes,
registry;
// Set up a progress bar, as this process can take a long time
const bar = new ProgressBar("Determining Config: :percent [:bar] :elapseds elapsed, eta :etas ", {
width: 30,
total: BAR_TOTAL
});
bar.tick(0); // Shows the progress bar
// Get the SourceCode of all chosen files
const patterns = answers.patterns.split(/[\s]+/);
try {
sourceCodes = getSourceCodeOfFiles(patterns, { baseConfig: newConfig, useEslintrc: false }, total => {
bar.tick((BAR_SOURCE_CODE_TOTAL / total));
});
} catch (e) {
log.info("\n");
throw e;
}
const fileQty = Object.keys(sourceCodes).length;
if (fileQty === 0) {
log.info("\n");
throw new Error("Automatic Configuration failed. No files were able to be parsed.");
}
// Create a registry of rule configs
registry = new autoconfig.Registry();
registry.populateFromCoreRules();
// Lint all files with each rule config in the registry
registry = registry.lintSourceCode(sourceCodes, newConfig, total => {
bar.tick((BAR_TOTAL - BAR_SOURCE_CODE_TOTAL) / total); // Subtract out ticks used at beginning
});
debug(`\nRegistry: ${util.inspect(registry.rules, { depth: null })}`);
// Create a list of recommended rules, because we don't want to disable them
const recRules = Object.keys(recConfig.rules).filter(ruleId => ConfigOps.isErrorSeverity(recConfig.rules[ruleId]));
// Find and disable rules which had no error-free configuration
const failingRegistry = registry.getFailingRulesRegistry();
Object.keys(failingRegistry.rules).forEach(ruleId => {
// If the rule is recommended, set it to error, otherwise disable it
disabledConfigs[ruleId] = (recRules.indexOf(ruleId) !== -1) ? 2 : 0;
});
// Now that we know which rules to disable, strip out configs with errors
registry = registry.stripFailingConfigs();
/*
* If there is only one config that results in no errors for a rule, we should use it.
* createConfig will only add rules that have one configuration in the registry.
*/
const singleConfigs = registry.createConfig().rules;
/*
* The "sweet spot" for number of options in a config seems to be two (severity plus one option).
* Very often, a third option (usually an object) is available to address
* edge cases, exceptions, or unique situations. We will prefer to use a config with
* specificity of two.
*/
const specTwoConfigs = registry.filterBySpecificity(2).createConfig().rules;
// Maybe a specific combination using all three options works
const specThreeConfigs = registry.filterBySpecificity(3).createConfig().rules;
// If all else fails, try to use the default (severity only)
const defaultConfigs = registry.filterBySpecificity(1).createConfig().rules;
// Combine configs in reverse priority order (later take precedence)
newConfig.rules = Object.assign({}, disabledConfigs, defaultConfigs, specThreeConfigs, specTwoConfigs, singleConfigs);
// Make sure progress bar has finished (floating point rounding)
bar.update(BAR_TOTAL);
// Log out some stats to let the user know what happened
const finalRuleIds = Object.keys(newConfig.rules);
const totalRules = finalRuleIds.length;
const enabledRules = finalRuleIds.filter(ruleId => (newConfig.rules[ruleId] !== 0)).length;
const resultMessage = [
`\nEnabled ${enabledRules} out of ${totalRules}`,
`rules based on ${fileQty}`,
`file${(fileQty === 1) ? "." : "s."}`
].join(" ");
log.info(resultMessage);
ConfigOps.normalizeToStrings(newConfig);
return newConfig;
}
/**
* process user's answers and create config object
* @param {Object} answers answers received from inquirer
* @returns {Object} config object
*/
function processAnswers(answers) {
let config = { rules: {}, env: {} };
if (answers.es6) {
config.env.es6 = true;
if (answers.modules) {
config.parserOptions = config.parserOptions || {};
config.parserOptions.sourceType = "module";
}
}
if (answers.commonjs) {
config.env.commonjs = true;
}
answers.env.forEach(env => {
config.env[env] = true;
});
if (answers.jsx) {
config.parserOptions = config.parserOptions || {};
config.parserOptions.ecmaFeatures = config.parserOptions.ecmaFeatures || {};
config.parserOptions.ecmaFeatures.jsx = true;
if (answers.react) {
config.plugins = ["react"];
config.parserOptions.ecmaFeatures.experimentalObjectRestSpread = true;
}
}
if (answers.source === "prompt") {
config.extends = "eslint:recommended";
config.rules.indent = ["error", answers.indent];
config.rules.quotes = ["error", answers.quotes];
config.rules["linebreak-style"] = ["error", answers.linebreak];
config.rules.semi = ["error", answers.semi ? "always" : "never"];
}
installModules(config);
if (answers.source === "auto") {
config = configureRules(answers, config);
config = autoconfig.extendFromRecommended(config);
}
ConfigOps.normalizeToStrings(config);
return config;
}
/**
* process user's style guide of choice and return an appropriate config object.
* @param {string} guide name of the chosen style guide
* @param {boolean} [installESLint=true] If `false` is given, it does not install eslint.
* @returns {Object} config object
*/
function getConfigForStyleGuide(guide, installESLint) {
const guides = {
google: { extends: "google" },
airbnb: { extends: "airbnb" },
"airbnb-base": { extends: "airbnb-base" },
standard: { extends: "standard" }
};
if (!guides[guide]) {
throw new Error("You referenced an unsupported guide.");
}
installModules(guides[guide], installESLint);
return guides[guide];
}
/**
* Get the version of the local ESLint.
* @returns {string|null} The version. If the local ESLint was not found, returns null.
*/
function getLocalESLintVersion() {
try {
const resolver = new ModuleResolver();
const eslintPath = resolver.resolve("eslint", process.cwd());
const eslint = require(eslintPath);
return eslint.linter.version || null;
} catch (_err) {
return null;
}
}
/**
* Get the shareable config name of the chosen style guide.
* @param {Object} answers The answers object.
* @returns {string} The shareable config name.
*/
function getStyleGuideName(answers) {
if (answers.styleguide === "airbnb" && !answers.airbnbReact) {
return "airbnb-base";
}
return answers.styleguide;
}
/**
* Check whether the local ESLint version conflicts with the required version of the chosen shareable config.
* @param {Object} answers The answers object.
* @returns {boolean} `true` if the local ESLint is found then it conflicts with the required version of the chosen shareable config.
*/
function hasESLintVersionConflict(answers) {
// Get the local ESLint version.
const localESLintVersion = getLocalESLintVersion();
if (!localESLintVersion) {
return false;
}
// Get the required range of ESLint version.
const configName = getStyleGuideName(answers);
const moduleName = `eslint-config-${configName}@latest`;
const peerDependencies = getPeerDependencies(moduleName) || {};
const requiredESLintVersionRange = peerDependencies.eslint;
if (!requiredESLintVersionRange) {
return false;
}
answers.localESLintVersion = localESLintVersion;
answers.requiredESLintVersionRange = requiredESLintVersionRange;
// Check the version.
if (semver.satisfies(localESLintVersion, requiredESLintVersionRange)) {
answers.installESLint = false;
return false;
}
return true;
}
/* istanbul ignore next: no need to test inquirer*/
/**
* Ask use a few questions on command prompt
* @returns {Promise} The promise with the result of the prompt
*/
function promptUser() {
return inquirer.prompt([
{
type: "list",
name: "source",
message: "How would you like to configure ESLint?",
default: "prompt",
choices: [
{ name: "Answer questions about your style", value: "prompt" },
{ name: "Use a popular style guide", value: "guide" },
{ name: "Inspect your JavaScript file(s)", value: "auto" }
]
},
{
type: "list",
name: "styleguide",
message: "Which style guide do you want to follow?",
choices: [{ name: "Google", value: "google" }, { name: "Airbnb", value: "airbnb" }, { name: "Standard", value: "standard" }],
when(answers) {
answers.packageJsonExists = npmUtil.checkPackageJson();
return answers.source === "guide" && answers.packageJsonExists;
}
},
{
type: "confirm",
name: "airbnbReact",
message: "Do you use React?",
default: false,
when(answers) {
return answers.styleguide === "airbnb";
}
},
{
type: "input",
name: "patterns",
message: "Which file(s), path(s), or glob(s) should be examined?",
when(answers) {
return (answers.source === "auto");
},
validate(input) {
if (input.trim().length === 0 && input.trim() !== ",") {
return "You must tell us what code to examine. Try again.";
}
return true;
}
},
{
type: "list",
name: "format",
message: "What format do you want your config file to be in?",
default: "JavaScript",
choices: ["JavaScript", "YAML", "JSON"],
when(answers) {
return ((answers.source === "guide" && answers.packageJsonExists) || answers.source === "auto");
}
},
{
type: "confirm",
name: "installESLint",
message(answers) {
const verb = semver.ltr(answers.localESLintVersion, answers.requiredESLintVersionRange)
? "upgrade"
: "downgrade";
return `The style guide "${answers.styleguide}" requires eslint@${answers.requiredESLintVersionRange}. You are currently using eslint@${answers.localESLintVersion}.\n Do you want to ${verb}?`;
},
default: true,
when(answers) {
return answers.source === "guide" && answers.packageJsonExists && hasESLintVersionConflict(answers);
}
}
]).then(earlyAnswers => {
// early exit if you are using a style guide
if (earlyAnswers.source === "guide") {
if (!earlyAnswers.packageJsonExists) {
log.info("A package.json is necessary to install plugins such as style guides. Run `npm init` to create a package.json file and try again.");
return void 0;
}
if (earlyAnswers.installESLint === false && !semver.satisfies(earlyAnswers.localESLintVersion, earlyAnswers.requiredESLintVersionRange)) {
log.info(`Note: it might not work since ESLint's version is mismatched with the ${earlyAnswers.styleguide} config.`);
}
if (earlyAnswers.styleguide === "airbnb" && !earlyAnswers.airbnbReact) {
earlyAnswers.styleguide = "airbnb-base";
}
const config = getConfigForStyleGuide(earlyAnswers.styleguide, earlyAnswers.installESLint);
writeFile(config, earlyAnswers.format);
return void 0;
}
// continue with the questions otherwise...
return inquirer.prompt([
{
type: "confirm",
name: "es6",
message: "Are you using ECMAScript 6 features?",
default: false
},
{
type: "confirm",
name: "modules",
message: "Are you using ES6 modules?",
default: false,
when(answers) {
return answers.es6 === true;
}
},
{
type: "checkbox",
name: "env",
message: "Where will your code run?",
default: ["browser"],
choices: [{ name: "Browser", value: "browser" }, { name: "Node", value: "node" }]
},
{
type: "confirm",
name: "commonjs",
message: "Do you use CommonJS?",
default: false,
when(answers) {
return answers.env.some(env => env === "browser");
}
},
{
type: "confirm",
name: "jsx",
message: "Do you use JSX?",
default: false
},
{
type: "confirm",
name: "react",
message: "Do you use React?",
default: false,
when(answers) {
return answers.jsx;
}
}
]).then(secondAnswers => {
// early exit if you are using automatic style generation
if (earlyAnswers.source === "auto") {
const combinedAnswers = Object.assign({}, earlyAnswers, secondAnswers);
const config = processAnswers(combinedAnswers);
installModules(config);
writeFile(config, earlyAnswers.format);
return void 0;
}
// continue with the style questions otherwise...
return inquirer.prompt([
{
type: "list",
name: "indent",
message: "What style of indentation do you use?",
default: "tab",
choices: [{ name: "Tabs", value: "tab" }, { name: "Spaces", value: 4 }]
},
{
type: "list",
name: "quotes",
message: "What quotes do you use for strings?",
default: "double",
choices: [{ name: "Double", value: "double" }, { name: "Single", value: "single" }]
},
{
type: "list",
name: "linebreak",
message: "What line endings do you use?",
default: "unix",
choices: [{ name: "Unix", value: "unix" }, { name: "Windows", value: "windows" }]
},
{
type: "confirm",
name: "semi",
message: "Do you require semicolons?",
default: true
},
{
type: "list",
name: "format",
message: "What format do you want your config file to be in?",
default: "JavaScript",
choices: ["JavaScript", "YAML", "JSON"]
}
]).then(answers => {
const totalAnswers = Object.assign({}, earlyAnswers, secondAnswers, answers);
const config = processAnswers(totalAnswers);
installModules(config);
writeFile(config, answers.format);
});
});
});
}
//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
const init = {
getConfigForStyleGuide,
hasESLintVersionConflict,
processAnswers,
/* istanbul ignore next */initializeConfig() {
return promptUser();
}
};
module.exports = init;
|
// generate slug on insert
Categories.before.insert(function (userId, doc) {
// if no slug has been provided, generate one
var slug = !!doc.slug ? doc.slug : Telescope.utils.slugify(doc.name);
doc.slug = Telescope.utils.getUnusedSlug(Categories, slug);
});
// generate slug on edit
Categories.before.update(function (userId, doc, fieldNames, modifier) {
if (modifier.$set && modifier.$set.slug) {
modifier.$set.slug = Telescope.utils.getUnusedSlug(Categories, modifier.$set.slug);
}
});
// add callback that adds categories CSS classes
function addCategoryClass (postClass, post) {
var classArray = _.map(Posts.getCategories(post), function (category){return "category-"+category.slug;});
return postClass + " " + classArray.join(' ');
}
Telescope.callbacks.add("postClass", addCategoryClass);
// when a category is added to a post, increment counter
function updateCategoryCountOnSubmit (post) {
if (!_.isEmpty(post.categories))
Categories.update({_id: {$in: post.categories}}, {$inc: {"postsCount": 1}}, {multi: true});
}
Telescope.callbacks.add("postSubmitAsync", updateCategoryCountOnSubmit);
function updateCategoryCountOnEdit (newPost, oldPost) {
var categoriesAdded = _.difference(newPost.categories, oldPost.categories);
var categoriesRemoved = _.difference(oldPost.categories, newPost.categories);
if (!_.isEmpty(categoriesAdded))
Categories.update({_id: {$in: categoriesAdded}}, {$inc: {"postsCount": 1}}, {multi: true});
if (!_.isEmpty(categoriesRemoved))
Categories.update({_id: {$in: categoriesRemoved}}, {$inc: {"postsCount": -1}}, {multi: true});
}
Telescope.callbacks.add("postEditAsync", updateCategoryCountOnEdit);
// when a post is deleted, decrement counter
function updateCategoryCountOnDelete (post) {
Categories.update({_id: {$in: post.categories}}, {$inc: {"postsCount": -1}}, {multi: true});
}
Telescope.callbacks.add("postDeleteAsync", updateCategoryCountOnDelete);
|
/*
Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang("specialchar","pl",{euro:"Znak euro",lsquo:"Cudzysłów pojedynczy otwierający",rsquo:"Cudzysłów pojedynczy zamykający",ldquo:"Cudzysłów apostrofowy otwierający",rdquo:"Cudzysłów apostrofowy zamykający",ndash:"Półpauza",mdash:"Pauza",iexcl:"Odwrócony wykrzyknik",cent:"Znak centa",pound:"Znak funta",curren:"Znak waluty",yen:"Znak jena",brvbar:"Przerwana pionowa kreska",sect:"Paragraf",uml:"Diereza",copy:"Znak praw autorskich",ordf:"Wskaźnik rodzaju żeńskiego liczebnika porządkowego",
laquo:"Lewy cudzysłów ostrokątny",not:"Znak negacji",reg:"Zastrzeżony znak towarowy",macr:"Makron",deg:"Znak stopnia",sup2:"Druga potęga",sup3:"Trzecia potęga",acute:"Akcent ostry",micro:"Znak mikro",para:"Znak akapitu",middot:"Kropka środkowa",cedil:"Cedylla",sup1:"Pierwsza potęga",ordm:"Wskaźnik rodzaju męskiego liczebnika porządkowego",raquo:"Prawy cudzysłów ostrokątny",frac14:"Ułamek zwykły jedna czwarta",frac12:"Ułamek zwykły jedna druga",frac34:"Ułamek zwykły trzy czwarte",iquest:"Odwrócony znak zapytania",
Agrave:"Wielka litera A z akcentem ciężkim",Aacute:"Wielka litera A z akcentem ostrym",Acirc:"Wielka litera A z akcentem przeciągłym",Atilde:"Wielka litera A z tyldą",Auml:"Wielka litera A z dierezą",Aring:"Wielka litera A z kółkiem",AElig:"Wielka ligatura Æ",Ccedil:"Wielka litera C z cedyllą",Egrave:"Wielka litera E z akcentem ciężkim",Eacute:"Wielka litera E z akcentem ostrym",Ecirc:"Wielka litera E z akcentem przeciągłym",Euml:"Wielka litera E z dierezą",Igrave:"Wielka litera I z akcentem ciężkim",
Iacute:"Wielka litera I z akcentem ostrym",Icirc:"Wielka litera I z akcentem przeciągłym",Iuml:"Wielka litera I z dierezą",ETH:"Wielka litera Eth",Ntilde:"Wielka litera N z tyldą",Ograve:"Wielka litera O z akcentem ciężkim",Oacute:"Wielka litera O z akcentem ostrym",Ocirc:"Wielka litera O z akcentem przeciągłym",Otilde:"Wielka litera O z tyldą",Ouml:"Wielka litera O z dierezą",times:"Znak mnożenia wektorowego",Oslash:"Wielka litera O z przekreśleniem",Ugrave:"Wielka litera U z akcentem ciężkim",Uacute:"Wielka litera U z akcentem ostrym",
Ucirc:"Wielka litera U z akcentem przeciągłym",Uuml:"Wielka litera U z dierezą",Yacute:"Wielka litera Y z akcentem ostrym",THORN:"Wielka litera Thorn",szlig:"Mała litera ostre s (eszet)",agrave:"Mała litera a z akcentem ciężkim",aacute:"Mała litera a z akcentem ostrym",acirc:"Mała litera a z akcentem przeciągłym",atilde:"Mała litera a z tyldą",auml:"Mała litera a z dierezą",aring:"Mała litera a z kółkiem",aelig:"Mała ligatura æ",ccedil:"Mała litera c z cedyllą",egrave:"Mała litera e z akcentem ciężkim",
eacute:"Mała litera e z akcentem ostrym",ecirc:"Mała litera e z akcentem przeciągłym",euml:"Mała litera e z dierezą",igrave:"Mała litera i z akcentem ciężkim",iacute:"Mała litera i z akcentem ostrym",icirc:"Mała litera i z akcentem przeciągłym",iuml:"Mała litera i z dierezą",eth:"Mała litera eth",ntilde:"Mała litera n z tyldą",ograve:"Mała litera o z akcentem ciężkim",oacute:"Mała litera o z akcentem ostrym",ocirc:"Mała litera o z akcentem przeciągłym",otilde:"Mała litera o z tyldą",ouml:"Mała litera o z dierezą",
divide:"Anglosaski znak dzielenia",oslash:"Mała litera o z przekreśleniem",ugrave:"Mała litera u z akcentem ciężkim",uacute:"Mała litera u z akcentem ostrym",ucirc:"Mała litera u z akcentem przeciągłym",uuml:"Mała litera u z dierezą",yacute:"Mała litera y z akcentem ostrym",thorn:"Mała litera thorn",yuml:"Mała litera y z dierezą",OElig:"Wielka ligatura OE",oelig:"Mała ligatura oe",372:"Wielka litera W z akcentem przeciągłym",374:"Wielka litera Y z akcentem przeciągłym",373:"Mała litera w z akcentem przeciągłym",
375:"Mała litera y z akcentem przeciągłym",sbquo:"Pojedynczy apostrof dolny",8219:"Pojedynczy apostrof górny",bdquo:"Podwójny apostrof dolny",hellip:"Wielokropek",trade:"Znak towarowy",9658:"Czarny wskaźnik wskazujący w prawo",bull:"Punktor",rarr:"Strzałka w prawo",rArr:"Podwójna strzałka w prawo",hArr:"Podwójna strzałka w lewo",diams:"Czarny znak karo",asymp:"Znak prawie równe"});
|
/**
* @ngdoc directive
* @name mdTabs
* @module material.components.tabs
*
* @restrict E
*
* @description
* The `<md-tabs>` directive serves as the container for 1..n `<md-tab>` child directives to produces a Tabs components.
* In turn, the nested `<md-tab>` directive is used to specify a tab label for the **header button** and a [optional] tab view
* content that will be associated with each tab button.
*
* Below is the markup for its simplest usage:
*
* <hljs lang="html">
* <md-tabs>
* <md-tab label="Tab #1"></md-tab>
* <md-tab label="Tab #2"></md-tab>
* <md-tab label="Tab #3"></md-tab>
* </md-tabs>
* </hljs>
*
* Tabs supports three (3) usage scenarios:
*
* 1. Tabs (buttons only)
* 2. Tabs with internal view content
* 3. Tabs with external view content
*
* **Tab-only** support is useful when tab buttons are used for custom navigation regardless of any other components, content, or views.
* **Tabs with internal views** are the traditional usages where each tab has associated view content and the view switching is managed internally by the Tabs component.
* **Tabs with external view content** is often useful when content associated with each tab is independently managed and data-binding notifications announce tab selection changes.
*
* Additional features also include:
*
* * Content can include any markup.
* * If a tab is disabled while active/selected, then the next tab will be auto-selected.
*
* ### Explanation of tab stretching
*
* Initially, tabs will have an inherent size. This size will either be defined by how much space is needed to accommodate their text or set by the user through CSS. Calculations will be based on this size.
*
* On mobile devices, tabs will be expanded to fill the available horizontal space. When this happens, all tabs will become the same size.
*
* On desktops, by default, stretching will never occur.
*
* This default behavior can be overridden through the `md-stretch-tabs` attribute. Here is a table showing when stretching will occur:
*
* `md-stretch-tabs` | mobile | desktop
* ------------------|-----------|--------
* `auto` | stretched | ---
* `always` | stretched | stretched
* `never` | --- | ---
*
* @param {integer=} md-selected Index of the active/selected tab
* @param {boolean=} md-no-ink If present, disables ink ripple effects.
* @param {boolean=} md-no-bar If present, disables the selection ink bar.
* @param {string=} md-align-tabs Attribute to indicate position of tab buttons: `bottom` or `top`; default is `top`
* @param {string=} md-stretch-tabs Attribute to indicate whether or not to stretch tabs: `auto`, `always`, or `never`; default is `auto`
* @param {boolean=} md-dynamic-height When enabled, the tab wrapper will resize based on the contents of the selected tab
* @param {boolean=} md-center-tabs When enabled, tabs will be centered provided there is no need for pagination
* @param {boolean=} md-no-pagination When enabled, pagination will remain off
* @param {boolean=} md-swipe-content When enabled, swipe gestures will be enabled for the content area to jump between tabs
* @param {boolean=} md-no-disconnect If your tab content has background tasks (ie. event listeners), you will want to include this to prevent the scope from being disconnected
* @param {boolean=} md-autoselect When present, any tabs added after the initial load will be automatically selected
*
* @usage
* <hljs lang="html">
* <md-tabs md-selected="selectedIndex" >
* <img ng-src="img/angular.png" class="centered">
* <md-tab
* ng-repeat="tab in tabs | orderBy:predicate:reversed"
* md-on-select="onTabSelected(tab)"
* md-on-deselect="announceDeselected(tab)"
* ng-disabled="tab.disabled">
* <md-tab-label>
* {{tab.title}}
* <img src="img/removeTab.png" ng-click="removeTab(tab)" class="delete">
* </md-tab-label>
* <md-tab-body>
* {{tab.content}}
* </md-tab-body>
* </md-tab>
* </md-tabs>
* </hljs>
*
*/
angular
.module('material.components.tabs')
.directive('mdTabs', MdTabs);
function MdTabs ($mdTheming, $mdUtil, $compile) {
return {
scope: {
selectedIndex: '=?mdSelected',
},
template: function (element, attr) {
attr[ "$mdTabsTemplate" ] = element.html();
return '\
<md-tabs-wrapper>\
<md-tab-data></md-tab-data>\
<md-prev-button\
tabindex="-1"\
role="button"\
aria-label="Previous Page"\
aria-disabled="{{!$mdTabsCtrl.canPageBack()}}"\
ng-class="{ \'md-disabled\': !$mdTabsCtrl.canPageBack() }"\
ng-if="$mdTabsCtrl.shouldPaginate"\
ng-click="$mdTabsCtrl.previousPage()">\
<md-icon md-svg-icon="md-tabs-arrow"></md-icon>\
</md-prev-button>\
<md-next-button\
tabindex="-1"\
role="button"\
aria-label="Next Page"\
aria-disabled="{{!$mdTabsCtrl.canPageForward()}}"\
ng-class="{ \'md-disabled\': !$mdTabsCtrl.canPageForward() }"\
ng-if="$mdTabsCtrl.shouldPaginate"\
ng-click="$mdTabsCtrl.nextPage()">\
<md-icon md-svg-icon="md-tabs-arrow"></md-icon>\
</md-next-button>\
<md-tabs-canvas\
tabindex="0"\
aria-activedescendant="tab-item-{{$mdTabsCtrl.tabs[$mdTabsCtrl.focusIndex].id}}"\
ng-focus="$mdTabsCtrl.redirectFocus()"\
ng-class="{\
\'md-paginated\': $mdTabsCtrl.shouldPaginate,\
\'md-center-tabs\': $mdTabsCtrl.shouldCenterTabs\
}"\
ng-keydown="$mdTabsCtrl.keydown($event)"\
role="tablist">\
<md-pagination-wrapper\
ng-class="{ \'md-center-tabs\': $mdTabsCtrl.shouldCenterTabs }"\
md-tab-scroll="$mdTabsCtrl.scroll($event)">\
<md-tab-item\
tabindex="-1"\
class="md-tab"\
style="max-width: {{ $mdTabsCtrl.maxTabWidth + \'px\' }}"\
ng-repeat="tab in $mdTabsCtrl.tabs"\
role="tab"\
aria-controls="tab-content-{{::tab.id}}"\
aria-selected="{{tab.isActive()}}"\
aria-disabled="{{tab.scope.disabled || \'false\'}}"\
ng-click="$mdTabsCtrl.select(tab.getIndex())"\
ng-class="{\
\'md-active\': tab.isActive(),\
\'md-focused\': tab.hasFocus(),\
\'md-disabled\': tab.scope.disabled\
}"\
ng-disabled="tab.scope.disabled"\
md-swipe-left="$mdTabsCtrl.nextPage()"\
md-swipe-right="$mdTabsCtrl.previousPage()"\
md-template="::tab.label"\
md-scope="::tab.parent"></md-tab-item>\
<md-ink-bar></md-ink-bar>\
</md-pagination-wrapper>\
<div class="md-visually-hidden md-dummy-wrapper">\
<md-dummy-tab\
class="md-tab"\
tabindex="-1"\
id="tab-item-{{::tab.id}}"\
role="tab"\
aria-controls="tab-content-{{::tab.id}}"\
aria-selected="{{tab.isActive()}}"\
aria-disabled="{{tab.scope.disabled || \'false\'}}"\
ng-focus="$mdTabsCtrl.hasFocus = true"\
ng-blur="$mdTabsCtrl.hasFocus = false"\
ng-repeat="tab in $mdTabsCtrl.tabs"\
md-template="::tab.label"\
md-scope="::tab.parent"></md-dummy-tab>\
</div>\
</md-tabs-canvas>\
</md-tabs-wrapper>\
<md-tabs-content-wrapper ng-show="$mdTabsCtrl.hasContent && $mdTabsCtrl.selectedIndex >= 0">\
<md-tab-content\
id="tab-content-{{::tab.id}}"\
role="tabpanel"\
aria-labelledby="tab-item-{{::tab.id}}"\
md-swipe-left="$mdTabsCtrl.swipeContent && $mdTabsCtrl.incrementIndex(1)"\
md-swipe-right="$mdTabsCtrl.swipeContent && $mdTabsCtrl.incrementIndex(-1)"\
ng-if="$mdTabsCtrl.hasContent"\
ng-repeat="(index, tab) in $mdTabsCtrl.tabs"\
md-connected-if="tab.isActive()"\
ng-class="{\
\'md-no-transition\': $mdTabsCtrl.lastSelectedIndex == null,\
\'md-active\': tab.isActive(),\
\'md-left\': tab.isLeft(),\
\'md-right\': tab.isRight(),\
\'md-no-scroll\': $mdTabsCtrl.dynamicHeight\
}">\
<div\
md-template="::tab.template"\
md-scope="::tab.parent"\
ng-if="tab.shouldRender()"></div>\
</md-tab-content>\
</md-tabs-content-wrapper>\
';
},
controller: 'MdTabsController',
controllerAs: '$mdTabsCtrl',
bindToController: true
};
}
|
(function() {
var count = "";
function pushCountDigit(digit) { return function(cm) {count += digit;} }
function popCount() { var i = parseInt(count); count = ""; return i || 1; }
function countTimes(func) {
if (typeof func == "string") func = CodeMirror.commands[func];
return function(cm) { for (var i = 0, c = popCount(); i < c; ++i) func(cm); }
}
function iterObj(o, f) {
for (var prop in o) if (o.hasOwnProperty(prop)) f(prop, o[prop]);
}
var word = [/\w/, /[^\w\s]/], bigWord = [/\S/];
function findWord(line, pos, dir, regexps) {
var stop = 0, next = -1;
if (dir > 0) { stop = line.length; next = 0; }
var start = stop, end = stop;
// Find bounds of next one.
outer: for (; pos != stop; pos += dir) {
for (var i = 0; i < regexps.length; ++i) {
if (regexps[i].test(line.charAt(pos + next))) {
start = pos;
for (; pos != stop; pos += dir) {
if (!regexps[i].test(line.charAt(pos + next))) break;
}
end = pos;
break outer;
}
}
}
return {from: Math.min(start, end), to: Math.max(start, end)};
}
function moveToWord(cm, regexps, dir, where) {
var cur = cm.getCursor(), ch = cur.ch, line = cm.getLine(cur.line), word;
while (true) {
word = findWord(line, ch, dir, regexps);
ch = word[where == "end" ? "to" : "from"];
if (ch == cur.ch && word.from != word.to) ch = word[dir < 0 ? "from" : "to"];
else break;
}
cm.setCursor(cur.line, word[where == "end" ? "to" : "from"], true);
}
var map = CodeMirror.keyMap.vim = {
"0": function(cm) {count.length > 0 ? pushCountDigit("0")(cm) : CodeMirror.commands.goLineStart(cm);},
"I": function(cm) {popCount(); cm.setOption("keyMap", "vim-insert");},
"G": function(cm) {cm.setOption("keyMap", "vim-prefix-g");},
catchall: function(cm) {/*ignore*/}
};
// Add bindings for number keys
for (var i = 1; i < 10; ++i) map[i] = pushCountDigit(i);
// Add bindings that are influenced by number keys
iterObj({"H": "goColumnLeft", "L": "goColumnRight", "J": "goLineDown", "K": "goLineUp",
"Left": "goColumnLeft", "Right": "goColumnRight", "Down": "goLineDown", "Up": "goLineUp",
"Backspace": "goCharLeft", "Space": "goCharRight",
"B": function(cm) {moveToWord(cm, word, -1, "end");},
"E": function(cm) {moveToWord(cm, word, 1, "end");},
"W": function(cm) {moveToWord(cm, word, 1, "start");},
"Shift-B": function(cm) {moveToWord(cm, bigWord, -1, "end");},
"Shift-E": function(cm) {moveToWord(cm, bigWord, 1, "end");},
"Shift-W": function(cm) {moveToWord(cm, bigWord, 1, "start");},
"U": "undo", "Ctrl-R": "redo", "Shift-4": "goLineEnd"},
function(key, cmd) { map[key] = countTimes(cmd); });
CodeMirror.keyMap["vim-prefix-g"] = {
"E": countTimes(function(cm) { moveToWord(cm, word, -1, "start");}),
"Shift-E": countTimes(function(cm) { moveToWord(cm, bigWord, -1, "start");}),
auto: "vim", catchall: function(cm) {/*ignore*/}
};
CodeMirror.keyMap["vim-insert"] = {
"Esc": function(cm) {cm.setOption("keyMap", "vim");},
fallthrough: ["default"]
};
})();
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.