code
stringlengths
2
1.05M
//>>built define("dojox/editor/plugins/nls/eu/latinEntities",{iexcl:"harridura ikur alderantzikatua",cent:"zentaboaren ikurra",pound:"liberaren ikurra",curren:"diruaren ikurra",yen:"yen ikurra\nyuan ikurra",brvbar:"barra zatitua\nbarra zatitu bertikala",sect:"sekzio ikurra",uml:"dieresia\nlerroarte-dieresia",copy:"copyright ikurra",ordf:"ordinal femeninoa",laquo:"ezkerreranzko angelu bikoitzeko zitazio-ikurra\nezkerreranzko zitazio-ikur latindarrak ",not:"ezezko ikurra",shy:"marratxoa\nhautazko marratxoa", reg:"erregistratu-ikurra\nmarka erregistratuaren ikurra",macr:"makroia\nlerroarte-makroia\ngaineko lerroa\nAPL gaineko barra",deg:"gradu ikurra",plusmn:"plus-minus ikurra\nplus edo minus ikurra",sup2:"bi goi-indizean\nbi digitua goi-indizean\nkarratua",sup3:"hiru goi-indizean\nhiru digitua goi-indizean\nkubikoa",acute:"azentu zorrotza\nlerroarte zorrotza",micro:"mikro ikurra",para:"paragrafo zeinua\nparagrafo ikurra",middot:"erdiko puntua\nkoma georgiarra\nerdiko puntu grekoa",cedil:"tileta\nlerroarte-tileta", sup1:"bat goi-indizean\nbat digitua goi-indizean",ordm:"ordinal maskulinoa",raquo:"eskumaranzko angelu bikoitzeko zitazio-ikurra\neskumaranzko zitazio-ikur latindarrak ",frac14:"zatiki arruntaren laurdena\nzatikiaren laurdena",frac12:"zatiki arruntaren erdia\nzatikiaren erdia",frac34:"zatiki arruntaren hiru laurdenak\nzatikiaren hiru laurdenak",iquest:"galdera ikur alderantzikatua\ngaldera ikur alderantzikatua",Agrave:"azentu kamusdun latineko A maiuskula\nkamusdun latineko A maiuskula ",Aacute:"Latineko A letra maiuskula zorrotzarekin", Acirc:"Azentu zirkunflexudun latineko A maiuskula",Atilde:"Tiletdun latineko A maiuskula",Auml:"Dieresidun latineko A maiuskula",Aring:"gainean eraztuna daukan latineko A letra maiuskula\neraztuna daukan latineko A letra ",AElig:"Latineko AE letra maiuskula\nLatineko AE lotura maiuskula",Ccedil:"Ze hautsia daukan latineko C maiuskula",Egrave:"azentu kamusdun latineko E maiuskula",Eacute:"azentu zorroztun latineko E maiuskula",Ecirc:"Azentu zirkunflexudun latineko E maiuskula",Euml:"Dieresidun latineko E maiuskula", Igrave:"Azentu kamusdun latineko I maiuskula",Iacute:"Azentu zorroztun latineko I maiuskula",Icirc:"Azentu zirkunflexudun latineko I maiuskula",Iuml:"Dieresidun latineko I maiuskula",ETH:"Latineko ETH maiuskula",Ntilde:"Tiletdun latineko N maiuskula",Ograve:"azentu kamusdun latineko O maiuskula",Oacute:"Azentu zorroztun latineko O maiuskula",Ocirc:"Azentu zirkunflexudun latineko O maiuskula",Otilde:"Tiletdun latineko O maiuskula",Ouml:"Dieresidun latineko O maiuskula",times:"biderketa ikurra",Oslash:"marradun latineko O maiuskula\nebakidun latineko O maiuskula ", Ugrave:"azentu kamusdun latineko U maiuskula",Uacute:"azentu zorroztun latineko U maiuskula",Ucirc:"Azentu zirkunflexudun latineko U maiuskula",Uuml:"Dieresidun latineko U maiuskula",Yacute:"azentu zorroztun latineko Y maiuskula",THORN:"latineko THORN maiuskula",szlig:"latineko Eszett minuskula",agrave:"azentu kamusdun latineko a minuskula\nkamusdun latineko a minuskula ",aacute:"azentu zorroztun latineko a minuskula",acirc:"Azentu zirkunflexudun latineko a minuskula",atilde:"Tiletdun latineko a minuskula", auml:"Dieresidun latineko a minuskula",aring:"gainean eraztuna daukan latineko a minuskula\neraztuna daukan latineko a minuskula ",aelig:"Latineko ae minuskula\nlatineko ae lotura minuskula",ccedil:"Ze hautsia daukan latineko c minuskula",egrave:"azentu kamusdun latineko e minuskula",eacute:"azentu zorroztun latineko e minuskula",ecirc:"Azentu zirkunflexudun latineko e minuskula",euml:"Dieresidun latineko e minuskula",igrave:"azentu kamusdun latineko i minuskula",iacute:"azentu zorroztun latineko i minuskula", icirc:"Azentu zirkunflexudun latineko i minuskula",iuml:"Dieresidun latineko i minuskula",eth:"Latineko eth minuskula",ntilde:"Tiletdun latineko n minuskula",ograve:"azentu kamusdun latineko o minuskula",oacute:"azentu zorroztun latineko o minuskula",ocirc:"Azentu zirkunflexudun latineko o minuskula",otilde:"Tiletdun latineko o minuskula",ouml:"Dieresidun latineko o minuskula",divide:"zatiketa ikurra",oslash:"marradun latineko o minuskula\nebakidun latineko o minuskula",ugrave:"azentu kamusdun latineko u minuskula", uacute:"azentu zorroztun latineko u minuskula",ucirc:"Azentu zirkunflexudun latineko u minuskula",uuml:"Dieresidun latineko u minuskula",yacute:"azentu zorroztun latineko y minuskula",thorn:"Latineko thorn minuskula",yuml:"Dieresidun latineko y minuskula",fnof:"kakodun latineko f minuskula\nfuntzioa\nflorina",Alpha:"grezierako alfa maiuskula",Beta:"grezierako beta maiuskula",Gamma:"grezierako gamma maiuskula",Delta:"grezierako delta maiuskula",Epsilon:"grezierako epsilon maiuskula",Zeta:"grezierako zeta maiuskula", Eta:"grezierako eta maiuskula",Theta:"grezierako thita maiuskula",Iota:"grezierako iota maiuskula",Kappa:"grezierako kappa maiuskula",Lambda:"grezierako lambda maiuskula",Mu:"grezierako mu maiuskula",Nu:"grezierako nu maiuskula",Xi:"grezierako xi maiuskula",Omicron:"grezierako omikron maiuskula",Pi:"grezierako pi maiuskula",Rho:"grezierako rho maiuskula",Sigma:"grezierako sigma maiuskula",Tau:"grezierako tau maiuskula",Upsilon:"grezierako upsilon maiuskula",Phi:"grezierako phi maiuskula",Chi:"grezierako khi maiuskula", Psi:"grezierako psi maiuskula",Omega:"grezierako omega maiuskula",alpha:"grezierako alfa minuskula",beta:"grezierako beta minuskula",gamma:"grezierako gamma minuskula",delta:"grezierako delta minuskula",epsilon:"grezierako epsilon minuskula",zeta:"grezierak zeta minuskula",eta:"grezierako eta minuskula",theta:"grezierako thita minuskula",iota:"grezierako iota minuskula",kappa:"grezierako kappa minuskula",lambda:"grezierako lambda minuskula",mu:"grezierako mu minuskula",nu:"grezierako nu minuskula", xi:"grezierako xi minuskula",omicron:"grezierako omikron minuskula",pi:"grezierako pi minuskula",rho:"grezierako rho minuskula",sigmaf:"grezierako amaierako sigma minuskula",sigma:"grezierako sigma minuskula",tau:"grezierako tau minuskula",upsilon:"grezierako upsilon minuskula",phi:"grezierako phi minuskula",chi:"grezierako khi minuskula",psi:"grezierako psi minuskula",omega:"grezierako omega minuskula",thetasym:"grezierako thita-sinbolo minuskula",upsih:"grezierako kakodun upsilon sinboloa",piv:"grezierako pi sinboloa", bull:"bineta\nzirkulu txiki beltza",hellip:"elipsi horizontala\netenpuntuak",prime:"prima\nminutuak\noinak",Prime:"prima bikoitza\nsegundoak\nhazbeteak",oline:"gaineko lerroa\nlerroarteko zirrimarra",frasl:"frakzio-barra",weierp:"script P maiuskula\npotentzia-multzoa\nWeierstrass-en p-a",image:"I letra gotiko maiuskula\nzati irudikaria",real:"R letra gotiko maiuskula\nzati errealaren sinboloa",trade:"marka erregistratuaren ikurra",alefsym:"alef sinboloa\nlehenengo kardinal transfinitoa",larr:"ezkerreranzko gezia", uarr:"goranzko gezia",rarr:"eskumaranzko gezia",darr:"beheranzko gezia",harr:"eskuin-ezkerreranzko gezia",crarr:"ezkerreranzko izkinadun beheranzko gezia\norga-itzulera",lArr:"ezkerreranzko gezi bikoitza",uArr:"goranzko gezi bikoitza",rArr:"eskumaranzko gezi bikoitza",dArr:"beheranzko gezi bikoitza",hArr:"eskuin-ezkerreranzko gezi bikoitza",forall:"guztientzat",part:"diferentzial partziala",exist:"existitzen da",empty:"multzo hutsa\nmultzo nulua\ndiametroa",nabla:"nabla\natzeranzko desberdintasuna", isin:"honen elementua",notin:"ez honen elementua",ni:"kide gisa dauka",prod:"enegarren produktua\nproduktu-ikurra",sum:"enegarren batura",minus:"minus-ikurra",lowast:"izartxo-eragilea",radic:"erro karratua\nerro ikurra",prop:"honekiko proportzionala",infin:"mugagabetasun",ang:"angelua",and:"logikoa eta\nbildura",or:"logikoa edo\nuve",cap:"ebaketa \nsinboloa",cup:"bildura\nsinboloa","int":"integrala",there4:"beraz",sim:"tilet-eragilea\nhonekin aldatzen da\nhonen antzekoa",cong:"gutxi gorabehera honen berdina", asymp:"honen ia berdina\nhonen asintotikoa",ne:"ez honen berdina",equiv:"honen berdin-berdina",le:"honen berdina edo txikiagoa",ge:"honen berdina edo handiagoa",sub:"honen azpimultzoa",sup:"honen gaineko multzoa",nsub:"ez honen azpimultzoa",sube:"honen azpimultzoa edo berdina",supe:"honen gaineko multzoa edo berdina",oplus:"zirkulu barruko plus ikurra\nzuzeneko batuketa",otimes:"zirkulu barruko orduak\nbektore-produktua",perp:"falsum\nhonen ortogonala\nperpendikularra",sdot:"puntu-eragilea",lceil:"ezkerreko sabaia\nAPL upstile", rceil:"eskumako sabaia",lfloor:"ezkerreko zorua\nAPL downstile",rfloor:"eskumako zorua",lang:"ezkerreranzko kako zuzena",rang:"eskumaranzko kako zuzena",loz:"erronboa",spades:"pika beltza",clubs:"hirusta beltza\nhirusta",hearts:"bihotz beltza\nbihotza",diams:"diamante beltza",OElig:"Latineko OE maiuskula",oelig:"Latineko oe minuskula",Scaron:"antizirkunflexudun latineko S maiuskula",scaron:"antizirkunflexudun latineko s minuskula",Yuml:"dieresidun latineko Y maiuskula",circ:"azentu zirkunflexua", tilde:"tilet txikia",ensp:"en hutsunea",emsp:"em hutsunea",thinsp:"hutsune mehea",zwnj:"zero zabalerako ez-bateratzailea",zwj:"zero zabalerako bateratzailea",lrm:"ezkerretik eskuinerako marka",rlm:"eskuinetik ezkerrerako marka",ndash:"marra laburra",mdash:"marra luzea",lsquo:"ezkerreko komatxo bakuna",rsquo:"eskuineko komatxo bakuna",sbquo:"9 formako komatxo baxu bakuna",ldquo:"ezkerreko komatxo bikoitza",rdquo:"eskuineko komatxo bikoitza",bdquo:"9 formako komatxo baxu boikoitza",dagger:"obeliskoa", Dagger:"obelisko bikoitza",permil:"bider mila ikurra",lsaquo:"ezkerreranzko angeludun komatxo bakuna",rsaquo:"eskuineranzko angeludun komatxo bakuna",euro:"euroaren ikurra"});
'use strict'; var util = require('util'), Store = require('../base'), _ = require('lodash'), async = require('async'), tingodb = Store.use('tingodb')(), ObjectID = tingodb.ObjectID, debug = require('debug')('eventstore:store:tingodb'); function Tingo(options) { options = options || {}; Store.call(this, options); var defaults = { dbPath: require('path').join(__dirname, '../../'), eventsCollectionName: 'events', snapshotsCollectionName: 'snapshots', transactionsCollectionName: 'transactions' }; _.defaults(options, defaults); this.options = options; } util.inherits(Tingo, Store); _.extend(Tingo.prototype, { connect: function (callback) { var options = this.options; this.db = new tingodb.Db(options.dbPath, {}); // this.db.on('close', function() { // self.emit('disconnect'); // }); this.events = this.db.collection(options.eventsCollectionName + '.tingo'); this.events.ensureIndex({ aggregateId: 1, streamRevision: 1 }, function (err) { if (err) { debug(err); } }); this.events.ensureIndex({ commitStamp: 1 }, function (err) { if (err) { debug(err); } }); this.events.ensureIndex({ dispatched: 1 }, { sparse: true }, function (err) { if (err) { debug(err); } }); this.snapshots = this.db.collection(options.snapshotsCollectionName + '.tingo'); this.snapshots.ensureIndex({ aggregateId: 1, revision: -1 }, function (err) { if (err) { debug(err); } }); this.transactions = this.db.collection(options.transactionsCollectionName + '.tingo'); this.transactions.ensureIndex({ aggregateId: 1, 'events.streamRevision': 1 }, function (err) { if (err) { debug(err); } }); this.emit('connect'); if (callback) callback(null, this); }, disconnect: function (callback) { if (!this.db) { if (callback) callback(null); return; } this.emit('disconnect'); this.db.close(callback || function () {}); }, clear: function (callback) { var self = this; async.parallel([ function (callback) { self.events.remove({}, callback); }, function (callback) { self.snapshots.remove({}, callback); }, function (callback) { self.transactions.remove({}, callback); } ], function (err) { if (err) { debug(err); } if (callback) callback(err); }); }, getNewId: function(callback) { callback(null, new ObjectID().toString()); }, addEvents: function (events, callback) { var noAggId = false; _.each(events, function (evt) { if (!evt.aggregateId) { noAggId = true; } evt._id = evt.id; evt.dispatched = false; }); if (noAggId) { var errMsg = 'aggregateId not defined!'; debug(errMsg); if (callback) callback(new Error(errMsg)); return; } var self = this; if (events.length === 1) { return this.events.insert(events, callback); } var tx = { _id: events[0].commitId, events: events, aggregateId: events[0].aggregateId, aggregate: events[0].aggregate, context: events[0].context }; this.transactions.insert(tx, function (err) { if (err) { debug(err); if (callback) callback(err); return; } self.events.insert(events, function (err) { if (err) { debug(err); if (callback) callback(err); return; } self.removeTransactions(events[events.length - 1]); if (callback) { callback(null); } }); }); }, getEvents: function (query, skip, limit, callback) { var findStatement = {}; if (query.aggregate) { findStatement.aggregate = query.aggregate; } if (query.context) { findStatement.context = query.context; } if (query.aggregateId) { findStatement['$or'] = [ { aggregateId: query.aggregateId }, { streamId: query.aggregateId } // just for compatability of < 1.0.0 ]; } if (limit === -1) { return this.events.find(findStatement, { sort: [['commitStamp', 'asc'], ['streamRevision', 'asc'], ['commitSequence', 'asc']] }).skip(skip).toArray(callback); } this.events.find(findStatement, { sort: [['commitStamp', 'asc'], ['streamRevision', 'asc'], ['commitSequence', 'asc']] }).skip(skip).limit(limit).toArray(callback); }, getEventsSince: function (date, skip, limit, callback) { var findStatement = { commitStamp: { '$gte': date } }; if (limit === -1) { return this.events.find(findStatement, { sort: [['commitStamp', 'asc'], ['streamRevision', 'asc'], ['commitSequence', 'asc']] }).skip(skip).toArray(callback); } this.events.find(findStatement, { sort: [['commitStamp', 'asc'], ['streamRevision', 'asc'], ['commitSequence', 'asc']] }).skip(skip).limit(limit).toArray(callback); }, getEventsByRevision: function (query, revMin, revMax, callback) { if (!query.aggregateId) { var errMsg = 'aggregateId not defined!'; debug(errMsg); if (callback) callback(new Error(errMsg)); return; } var streamRevOptions = { '$gte': revMin, '$lt': revMax }; if (revMax == -1) { streamRevOptions = { '$gte': revMin }; } var findStatement = { '$or': [ { aggregateId: query.aggregateId }, { streamId: query.aggregateId } // just for compatability of < 1.0.0 ], streamRevision: streamRevOptions }; if (query.aggregate) { findStatement.aggregate = query.aggregate; } if (query.context) { findStatement.context = query.context; } var self = this; this.events.find(findStatement, { sort: [['commitStamp', 'asc'], ['streamRevision', 'asc'], ['commitSequence', 'asc']] }).toArray(function (err, res) { if (err) { debug(err); return callback(err); } if (!res || res.length === 0) { return callback(null, []); } var lastEvt = res[res.length - 1]; var txOk = (revMax === -1 && !lastEvt.restInCommitStream) || (revMax !== -1 && (lastEvt.streamRevision === revMax - 1 || !lastEvt.restInCommitStream)); if (txOk) { // the following is usually unnecessary self.removeTransactions(lastEvt); return callback(null, res); } self.repairFailedTransaction(lastEvt, function (err) { if (err) { if (err.message.indexOf('missing tx entry') >= 0) { return callback(null, res); } debug(err); return callback(err); } self.getEventsByRevision(query, revMin, revMax, callback); }); }); }, getUndispatchedEvents: function (query, callback) { var findStatement = { dispatched: false }; if (query && query.aggregate) { findStatement.aggregate = query.aggregate; } if (query && query.context) { findStatement.context = query.context; } if (query && query.aggregateId) { findStatement.aggregateId = query.aggregateId; } this.events.find(findStatement, { sort: [['commitStamp', 'asc'], ['streamRevision', 'asc'], ['commitSequence', 'asc']] }).toArray(callback); }, setEventToDispatched: function (id, callback) { var updateCommand = { '$unset' : { 'dispatched': null } }; this.events.update({'_id' : id}, updateCommand, callback); }, addSnapshot: function(snap, callback) { if (!snap.aggregateId) { var errMsg = 'aggregateId not defined!'; debug(errMsg); if (callback) callback(new Error(errMsg)); return; } snap._id = snap.id; this.snapshots.insert(snap, callback); }, getSnapshot: function (query, revMax, callback) { if (!query.aggregateId) { var errMsg = 'aggregateId not defined!'; debug(errMsg); if (callback) callback(new Error(errMsg)); return; } var findStatement = { '$or': [ { aggregateId: query.aggregateId }, { streamId: query.aggregateId } // just for compatability of < 1.0.0 ] }; if (query.aggregate) { findStatement.aggregate = query.aggregate; } if (query.context) { findStatement.context = query.context; } if (revMax > -1) { findStatement.revision = { '$lte': revMax }; } this.snapshots.findOne(findStatement, { sort: [['revision', 'desc'], ['version', 'desc'], ['commitStamp', 'desc']] }, callback); }, removeTransactions: function (evt, callback) { if (!evt.aggregateId) { var errMsg = 'aggregateId not defined!'; debug(errMsg); if (callback) callback(new Error(errMsg)); return; } var findStatement = { aggregateId: evt.aggregateId }; if (evt.aggregate) { findStatement.aggregate = evt.aggregate; } if (evt.context) { findStatement.context = evt.context; } // the following is usually unnecessary this.transactions.remove(findStatement, function (err) { if (err) { debug(err); } if (callback) { callback(err); } }); }, getPendingTransactions: function (callback) { var self = this; this.transactions.find({}).toArray(function (err, txs) { if (err) { debug(err); return callback(err); } if (txs.length === 0) { return callback(null, txs); } var goodTxs = []; async.map(txs, function (tx, clb) { var findStatement = { commitId: tx._id, aggregateId: tx.aggregateId }; if (tx.aggregate) { findStatement.aggregate = tx.aggregate; } if (tx.context) { findStatement.context = tx.context; } self.events.findOne(findStatement, function (err, evt) { if (err) { return clb(err); } if (evt) { goodTxs.push(evt); } else { self.transactions.remove({ _id: tx._id }, function (err) { if (err) { debug(err); } }); } clb(null); }); }, function (err) { if (err) { debug(err); return callback(err); } callback(null, goodTxs); }) }); }, getLastEvent: function (query, callback) { if (!query.aggregateId) { var errMsg = 'aggregateId not defined!'; debug(errMsg); if (callback) callback(new Error(errMsg)); return; } var findStatement = { aggregateId: query.aggregateId }; if (query.aggregate) { findStatement.aggregate = query.aggregate; } if (query.context) { findStatement.context = query.context; } this.events.findOne(findStatement, { sort: [['commitStamp', 'desc'], ['streamRevision', 'desc'], ['commitSequence', 'desc']] }, callback); }, repairFailedTransaction: function (lastEvt, callback) { var self = this; //var findStatement = { // aggregateId: lastEvt.aggregateId, // 'events.streamRevision': lastEvt.streamRevision + 1 //}; // //if (lastEvt.aggregate) { // findStatement.aggregate = lastEvt.aggregate; //} // //if (lastEvt.context) { // findStatement.context = lastEvt.context; //} //this.transactions.findOne(findStatement, function (err, tx) { this.transactions.findOne({ _id: lastEvt.commitId }, function (err, tx) { if (err) { debug(err); return callback(err); } if (!tx) { var err = new Error('missing tx entry for aggregate ' + lastEvt.aggregateId); debug(err); return callback(err); } var missingEvts = tx.events.slice(tx.events.length - lastEvt.restInCommitStream); self.events.insert(missingEvts, function (err) { if (err) { debug(err); return callback(err); } self.removeTransactions(lastEvt); callback(null); }); }); } }); module.exports = Tingo;
define( "gridx/nls/kk/PaginationBar", ({ pagerWai: 'Пейджер', pageIndex: '${0}', pageIndexTitle: '${0}-бет', firstPageTitle: 'Бірінші бет', prevPageTitle: 'Алдыңғы бет', nextPageTitle: 'Келесі бет', lastPageTitle: 'Соңғы бет', pageSize: '${0}', pageSizeTitle: 'Бетіне ${0} элемент', pageSizeAll: 'Барлығы', pageSizeAllTitle: 'Барлық элементтер', description: '${0} - ${2} элементтің ${1} элементі.', descriptionEmpty: 'Тор – бос.', // OneUI blueprint summary: 'Барлығы: ${0}', summaryWithSelection: 'Барлығы: ${0} Таңдалды: ${1}', gotoBtnTitle: 'Белгілі бір бетке өту', gotoDialogTitle: 'Бетке өту', gotoDialogMainMsg: 'Бет санын көрсетіңіз:', gotoDialogPageCount: ' (${0} бет)', gotoDialogOKBtn: 'Өту', gotoDialogCancelBtn: 'Болдырмау', // for drop down pagination bar pageLabel: 'Бет', pageSizeLabel: 'Жолдар' }) );
var searchData= [ ['readonlyprototype',['ReadOnlyPrototype',['../classv8_1_1FunctionTemplate.html#a91d2e0643e8c5a53ab1d75f7766c2422',1,'v8::FunctionTemplate']]], ['release',['Release',['../classv8_1_1PersistentValueMapBase.html#a9ffa7a4e0c59121c0471d71c04112966',1,'v8::PersistentValueMapBase']]], ['remove',['Remove',['../classv8_1_1PersistentValueMapBase.html#abd75a4c050416712167ba0bb9eace097',1,'v8::PersistentValueMapBase']]], ['removecallcompletedcallback',['RemoveCallCompletedCallback',['../classv8_1_1Isolate.html#a46f0a5d35f8b29030922bdb433c0dc4f',1,'v8::Isolate']]], ['removegcepiloguecallback',['RemoveGCEpilogueCallback',['../classv8_1_1Isolate.html#a277144482f5fefd58d822c22a173b01a',1,'v8::Isolate']]], ['removegcprologuecallback',['RemoveGCPrologueCallback',['../classv8_1_1Isolate.html#a7902b8b58f3c85bac9b7dd1086fa81ce',1,'v8::Isolate']]], ['removememoryallocationcallback',['RemoveMemoryAllocationCallback',['../classv8_1_1Isolate.html#a99349e062c11085eeb63a0d825226487',1,'v8::Isolate']]], ['removemessagelisteners',['RemoveMessageListeners',['../classv8_1_1Isolate.html#a0319e55b26ba3ac51d867b37b917a21f',1,'v8::Isolate']]], ['removeprototype',['RemovePrototype',['../classv8_1_1FunctionTemplate.html#a4a184aca244174c7fe52d58871d3129e',1,'v8::FunctionTemplate']]], ['reportprogressvalue',['ReportProgressValue',['../classv8_1_1ActivityControl.html#a1300f10611306a3e8f79239e057eb0bf',1,'v8::ActivityControl']]], ['requestgarbagecollectionfortesting',['RequestGarbageCollectionForTesting',['../classv8_1_1Isolate.html#a59fe893ed7e9df52cef2d59b2d98ab23',1,'v8::Isolate']]], ['requestinterrupt',['RequestInterrupt',['../classv8_1_1Isolate.html#a971b6094ecc6c7f55eb6f58a71a8afd3',1,'v8::Isolate']]], ['reservecapacity',['ReserveCapacity',['../classv8_1_1PersistentValueVector.html#ad4cccfee3a275986578276efe0c78510',1,'v8::PersistentValueVector']]], ['reset',['Reset',['../singletonv8_1_1PersistentBase.html#a174bb1e45b18fd4eeaee033622825bb8',1,'v8::PersistentBase::Reset()'],['../singletonv8_1_1PersistentBase.html#a11164f0dfc9a16d79809236e7a9670aa',1,'v8::PersistentBase::Reset(Isolate *isolate, const Local&lt; S &gt; &amp;other)'],['../singletonv8_1_1PersistentBase.html#af6b8f929b0cbaa83341df48ca3b03ef5',1,'v8::PersistentBase::Reset(Isolate *isolate, const PersistentBase&lt; S &gt; &amp;other)'],['../classv8_1_1TryCatch.html#a3aae8acab4c99b374b7d782763d4c8e1',1,'v8::TryCatch::Reset()']]], ['resettobookmark',['ResetToBookmark',['../classv8_1_1ScriptCompiler_1_1ExternalSourceStream.html#a425cf1ba265eeca194b805fe5c52bc19',1,'v8::ScriptCompiler::ExternalSourceStream']]], ['rethrow',['ReThrow',['../classv8_1_1TryCatch.html#ab8c3a1dbb38e6fd00e37436034daf707',1,'v8::TryCatch']]], ['runmicrotasks',['RunMicrotasks',['../classv8_1_1Isolate.html#ac3cbe2a1632eb863912640dcfc98b6c8',1,'v8::Isolate']]] ];
module("Script Value", { setup : function() { stop(); var that = this; this.cb = function(e) { ok(true, "Scene loaded"); that.doc = document.getElementById("xml3dframe").contentDocument; start(); }; loadDocument("scenes/script-value.xhtml"+window.location.search, this.cb); }, teardown : function() { var v = document.getElementById("xml3dframe"); v.removeEventListener("load", this.cb, true); } }); test("Set script value attached to document", function() { var posValue = this.doc.getElementById("posValue"), sizeValue = this.doc.getElementById("pointSize"), dataElement = this.doc.getElementById("pointData"), originalContent = "0 -1 0 1 0 0"; equal(posValue.textContent, originalContent, "Position has correct text content"); var result = dataElement.getResult(); QUnit.closeArray(result.getValue("position"), new Float32Array(originalContent.split(/\s+/)), EPSILON, "Position has correct Xflow result"); var newPos = new Float32Array([0,0,0, 1, 1, 1]); posValue.setScriptValue(newPos); equal(posValue.textContent, "[value set by script]", "Position has correct text content after setScriptValue()"); result = dataElement.getResult(); QUnit.closeArray(result.getValue("position"), newPos, EPSILON, "Position has correct Xflow result after setScriptValue()"); newPos[1] = 2; posValue.setScriptValue(newPos); equal(posValue.textContent, "[value set by script]", "Position has correct text content after setScriptValue() #2"); result = dataElement.getResult(); QUnit.closeArray(result.getValue("position"), newPos, EPSILON, "Position has correct Xflow result after setScriptValue() #2"); var newSize = new Float32Array([1.0]); sizeValue.setScriptValue(newSize); equal(sizeValue.textContent, "[value set by script]", "PointSize has correct text content after setScriptValue()"); result = dataElement.getResult(); QUnit.closeArray(result.getValue("pointSize"), newSize, EPSILON, "PointSize has correct Xflow result after setScriptValue()"); posValue.textContent = originalContent; equal(posValue.textContent, originalContent, "Position has correct text content after undoing changes"); var result = dataElement.getResult(); QUnit.closeArray(result.getValue("position"), new Float32Array(originalContent.split(/\s+/)), EPSILON, "Position has correct Xflow result after undoing changes"); }); test("Set script value detached from document", function() { var colorValue = this.doc.createElementNS(XML3D.xml3dNS, "float3"), dataElement = this.doc.getElementById("pointData"); var colorArray = new Float32Array([1,0,0, 0,0,1]); colorValue.name = "color"; colorValue.setScriptValue(colorArray); dataElement.appendChild(colorValue); equal(colorValue.textContent, "[value set by script]", "Color has correct text content"); var result = dataElement.getResult(); QUnit.closeArray(result.getValue("color"), colorArray, EPSILON, "Color has correct Xflow result"); dataElement.removeChild(colorValue); equal(colorValue.textContent, "[value set by script]", "Color has correct text content after removal"); var result = dataElement.getResult(); equal(result.getValue("color"), null, EPSILON, "Color has correct Xflow result after removal"); dataElement.appendChild(colorValue); equal(colorValue.textContent, "[value set by script]", "Color has correct text content after readding"); var result = dataElement.getResult(); QUnit.closeArray(result.getValue("color"), colorArray, EPSILON, "Color has correct Xflow result after readding"); dataElement.removeChild(colorValue); var colorTextValue = "1 1 0 0 1 1"; colorValue.textContent = colorTextValue; dataElement.appendChild(colorValue); var result = dataElement.getResult(); QUnit.closeArray(result.getValue("color"), new Float32Array(colorTextValue.split(/\s+/)), EPSILON, "Color has correct Xflow result after readding #2"); });
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(require('jquery')) : typeof define === 'function' && define.amd ? define(['jquery'], factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.jQuery)); }(this, (function ($) { 'use strict'; function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } var $__default = /*#__PURE__*/_interopDefaultLegacy($); var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; function createCommonjsModule(fn, module) { return module = { exports: {} }, fn(module, module.exports), module.exports; } var check = function (it) { return it && it.Math == Math && it; }; // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 var global_1 = /* global globalThis -- safe */ check(typeof globalThis == 'object' && globalThis) || check(typeof window == 'object' && window) || check(typeof self == 'object' && self) || check(typeof commonjsGlobal == 'object' && commonjsGlobal) || // eslint-disable-next-line no-new-func -- fallback (function () { return this; })() || Function('return this')(); var fails = function (exec) { try { return !!exec(); } catch (error) { return true; } }; // Detect IE8's incomplete defineProperty implementation var descriptors = !fails(function () { return Object.defineProperty({}, 1, { get: function () { return 7; } })[1] != 7; }); var nativePropertyIsEnumerable = {}.propertyIsEnumerable; var getOwnPropertyDescriptor$1 = Object.getOwnPropertyDescriptor; // Nashorn ~ JDK8 bug var NASHORN_BUG = getOwnPropertyDescriptor$1 && !nativePropertyIsEnumerable.call({ 1: 2 }, 1); // `Object.prototype.propertyIsEnumerable` method implementation // https://tc39.es/ecma262/#sec-object.prototype.propertyisenumerable var f$4 = NASHORN_BUG ? function propertyIsEnumerable(V) { var descriptor = getOwnPropertyDescriptor$1(this, V); return !!descriptor && descriptor.enumerable; } : nativePropertyIsEnumerable; var objectPropertyIsEnumerable = { f: f$4 }; var createPropertyDescriptor = function (bitmap, value) { return { enumerable: !(bitmap & 1), configurable: !(bitmap & 2), writable: !(bitmap & 4), value: value }; }; var toString = {}.toString; var classofRaw = function (it) { return toString.call(it).slice(8, -1); }; var split = ''.split; // fallback for non-array-like ES3 and non-enumerable old V8 strings var indexedObject = fails(function () { // throws an error in rhino, see https://github.com/mozilla/rhino/issues/346 // eslint-disable-next-line no-prototype-builtins -- safe return !Object('z').propertyIsEnumerable(0); }) ? function (it) { return classofRaw(it) == 'String' ? split.call(it, '') : Object(it); } : Object; // `RequireObjectCoercible` abstract operation // https://tc39.es/ecma262/#sec-requireobjectcoercible var requireObjectCoercible = function (it) { if (it == undefined) throw TypeError("Can't call method on " + it); return it; }; // toObject with fallback for non-array-like ES3 strings var toIndexedObject = function (it) { return indexedObject(requireObjectCoercible(it)); }; var isObject = function (it) { return typeof it === 'object' ? it !== null : typeof it === 'function'; }; // `ToPrimitive` abstract operation // https://tc39.es/ecma262/#sec-toprimitive // instead of the ES6 spec version, we didn't implement @@toPrimitive case // and the second argument - flag - preferred type is a string var toPrimitive = function (input, PREFERRED_STRING) { if (!isObject(input)) return input; var fn, val; if (PREFERRED_STRING && typeof (fn = input.toString) == 'function' && !isObject(val = fn.call(input))) return val; if (typeof (fn = input.valueOf) == 'function' && !isObject(val = fn.call(input))) return val; if (!PREFERRED_STRING && typeof (fn = input.toString) == 'function' && !isObject(val = fn.call(input))) return val; throw TypeError("Can't convert object to primitive value"); }; var hasOwnProperty = {}.hasOwnProperty; var has$1 = function (it, key) { return hasOwnProperty.call(it, key); }; var document = global_1.document; // typeof document.createElement is 'object' in old IE var EXISTS = isObject(document) && isObject(document.createElement); var documentCreateElement = function (it) { return EXISTS ? document.createElement(it) : {}; }; // Thank's IE8 for his funny defineProperty var ie8DomDefine = !descriptors && !fails(function () { return Object.defineProperty(documentCreateElement('div'), 'a', { get: function () { return 7; } }).a != 7; }); var nativeGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; // `Object.getOwnPropertyDescriptor` method // https://tc39.es/ecma262/#sec-object.getownpropertydescriptor var f$3 = descriptors ? nativeGetOwnPropertyDescriptor : function getOwnPropertyDescriptor(O, P) { O = toIndexedObject(O); P = toPrimitive(P, true); if (ie8DomDefine) try { return nativeGetOwnPropertyDescriptor(O, P); } catch (error) { /* empty */ } if (has$1(O, P)) return createPropertyDescriptor(!objectPropertyIsEnumerable.f.call(O, P), O[P]); }; var objectGetOwnPropertyDescriptor = { f: f$3 }; var anObject = function (it) { if (!isObject(it)) { throw TypeError(String(it) + ' is not an object'); } return it; }; var nativeDefineProperty = Object.defineProperty; // `Object.defineProperty` method // https://tc39.es/ecma262/#sec-object.defineproperty var f$2 = descriptors ? nativeDefineProperty : function defineProperty(O, P, Attributes) { anObject(O); P = toPrimitive(P, true); anObject(Attributes); if (ie8DomDefine) try { return nativeDefineProperty(O, P, Attributes); } catch (error) { /* empty */ } if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported'); if ('value' in Attributes) O[P] = Attributes.value; return O; }; var objectDefineProperty = { f: f$2 }; var createNonEnumerableProperty = descriptors ? function (object, key, value) { return objectDefineProperty.f(object, key, createPropertyDescriptor(1, value)); } : function (object, key, value) { object[key] = value; return object; }; var setGlobal = function (key, value) { try { createNonEnumerableProperty(global_1, key, value); } catch (error) { global_1[key] = value; } return value; }; var SHARED = '__core-js_shared__'; var store$1 = global_1[SHARED] || setGlobal(SHARED, {}); var sharedStore = store$1; var functionToString = Function.toString; // this helper broken in `3.4.1-3.4.4`, so we can't use `shared` helper if (typeof sharedStore.inspectSource != 'function') { sharedStore.inspectSource = function (it) { return functionToString.call(it); }; } var inspectSource = sharedStore.inspectSource; var WeakMap$1 = global_1.WeakMap; var nativeWeakMap = typeof WeakMap$1 === 'function' && /native code/.test(inspectSource(WeakMap$1)); var shared = createCommonjsModule(function (module) { (module.exports = function (key, value) { return sharedStore[key] || (sharedStore[key] = value !== undefined ? value : {}); })('versions', []).push({ version: '3.9.1', mode: 'global', copyright: '© 2021 Denis Pushkarev (zloirock.ru)' }); }); var id = 0; var postfix = Math.random(); var uid = function (key) { return 'Symbol(' + String(key === undefined ? '' : key) + ')_' + (++id + postfix).toString(36); }; var keys = shared('keys'); var sharedKey = function (key) { return keys[key] || (keys[key] = uid(key)); }; var hiddenKeys$1 = {}; var WeakMap = global_1.WeakMap; var set, get, has; var enforce = function (it) { return has(it) ? get(it) : set(it, {}); }; var getterFor = function (TYPE) { return function (it) { var state; if (!isObject(it) || (state = get(it)).type !== TYPE) { throw TypeError('Incompatible receiver, ' + TYPE + ' required'); } return state; }; }; if (nativeWeakMap) { var store = sharedStore.state || (sharedStore.state = new WeakMap()); var wmget = store.get; var wmhas = store.has; var wmset = store.set; set = function (it, metadata) { metadata.facade = it; wmset.call(store, it, metadata); return metadata; }; get = function (it) { return wmget.call(store, it) || {}; }; has = function (it) { return wmhas.call(store, it); }; } else { var STATE = sharedKey('state'); hiddenKeys$1[STATE] = true; set = function (it, metadata) { metadata.facade = it; createNonEnumerableProperty(it, STATE, metadata); return metadata; }; get = function (it) { return has$1(it, STATE) ? it[STATE] : {}; }; has = function (it) { return has$1(it, STATE); }; } var internalState = { set: set, get: get, has: has, enforce: enforce, getterFor: getterFor }; var redefine = createCommonjsModule(function (module) { var getInternalState = internalState.get; var enforceInternalState = internalState.enforce; var TEMPLATE = String(String).split('String'); (module.exports = function (O, key, value, options) { var unsafe = options ? !!options.unsafe : false; var simple = options ? !!options.enumerable : false; var noTargetGet = options ? !!options.noTargetGet : false; var state; if (typeof value == 'function') { if (typeof key == 'string' && !has$1(value, 'name')) { createNonEnumerableProperty(value, 'name', key); } state = enforceInternalState(value); if (!state.source) { state.source = TEMPLATE.join(typeof key == 'string' ? key : ''); } } if (O === global_1) { if (simple) O[key] = value; else setGlobal(key, value); return; } else if (!unsafe) { delete O[key]; } else if (!noTargetGet && O[key]) { simple = true; } if (simple) O[key] = value; else createNonEnumerableProperty(O, key, value); // add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative })(Function.prototype, 'toString', function toString() { return typeof this == 'function' && getInternalState(this).source || inspectSource(this); }); }); var path = global_1; var aFunction = function (variable) { return typeof variable == 'function' ? variable : undefined; }; var getBuiltIn = function (namespace, method) { return arguments.length < 2 ? aFunction(path[namespace]) || aFunction(global_1[namespace]) : path[namespace] && path[namespace][method] || global_1[namespace] && global_1[namespace][method]; }; var ceil = Math.ceil; var floor = Math.floor; // `ToInteger` abstract operation // https://tc39.es/ecma262/#sec-tointeger var toInteger = function (argument) { return isNaN(argument = +argument) ? 0 : (argument > 0 ? floor : ceil)(argument); }; var min$1 = Math.min; // `ToLength` abstract operation // https://tc39.es/ecma262/#sec-tolength var toLength = function (argument) { return argument > 0 ? min$1(toInteger(argument), 0x1FFFFFFFFFFFFF) : 0; // 2 ** 53 - 1 == 9007199254740991 }; var max = Math.max; var min = Math.min; // Helper for a popular repeating case of the spec: // Let integer be ? ToInteger(index). // If integer < 0, let result be max((length + integer), 0); else let result be min(integer, length). var toAbsoluteIndex = function (index, length) { var integer = toInteger(index); return integer < 0 ? max(integer + length, 0) : min(integer, length); }; // `Array.prototype.{ indexOf, includes }` methods implementation var createMethod = function (IS_INCLUDES) { return function ($this, el, fromIndex) { var O = toIndexedObject($this); var length = toLength(O.length); var index = toAbsoluteIndex(fromIndex, length); var value; // Array#includes uses SameValueZero equality algorithm // eslint-disable-next-line no-self-compare -- NaN check if (IS_INCLUDES && el != el) while (length > index) { value = O[index++]; // eslint-disable-next-line no-self-compare -- NaN check if (value != value) return true; // Array#indexOf ignores holes, Array#includes - not } else for (;length > index; index++) { if ((IS_INCLUDES || index in O) && O[index] === el) return IS_INCLUDES || index || 0; } return !IS_INCLUDES && -1; }; }; var arrayIncludes = { // `Array.prototype.includes` method // https://tc39.es/ecma262/#sec-array.prototype.includes includes: createMethod(true), // `Array.prototype.indexOf` method // https://tc39.es/ecma262/#sec-array.prototype.indexof indexOf: createMethod(false) }; var indexOf = arrayIncludes.indexOf; var objectKeysInternal = function (object, names) { var O = toIndexedObject(object); var i = 0; var result = []; var key; for (key in O) !has$1(hiddenKeys$1, key) && has$1(O, key) && result.push(key); // Don't enum bug & hidden keys while (names.length > i) if (has$1(O, key = names[i++])) { ~indexOf(result, key) || result.push(key); } return result; }; // IE8- don't enum bug keys var enumBugKeys = [ 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf' ]; var hiddenKeys = enumBugKeys.concat('length', 'prototype'); // `Object.getOwnPropertyNames` method // https://tc39.es/ecma262/#sec-object.getownpropertynames var f$1 = Object.getOwnPropertyNames || function getOwnPropertyNames(O) { return objectKeysInternal(O, hiddenKeys); }; var objectGetOwnPropertyNames = { f: f$1 }; var f = Object.getOwnPropertySymbols; var objectGetOwnPropertySymbols = { f: f }; // all object keys, includes non-enumerable and symbols var ownKeys = getBuiltIn('Reflect', 'ownKeys') || function ownKeys(it) { var keys = objectGetOwnPropertyNames.f(anObject(it)); var getOwnPropertySymbols = objectGetOwnPropertySymbols.f; return getOwnPropertySymbols ? keys.concat(getOwnPropertySymbols(it)) : keys; }; var copyConstructorProperties = function (target, source) { var keys = ownKeys(source); var defineProperty = objectDefineProperty.f; var getOwnPropertyDescriptor = objectGetOwnPropertyDescriptor.f; for (var i = 0; i < keys.length; i++) { var key = keys[i]; if (!has$1(target, key)) defineProperty(target, key, getOwnPropertyDescriptor(source, key)); } }; var replacement = /#|\.prototype\./; var isForced = function (feature, detection) { var value = data[normalize(feature)]; return value == POLYFILL ? true : value == NATIVE ? false : typeof detection == 'function' ? fails(detection) : !!detection; }; var normalize = isForced.normalize = function (string) { return String(string).replace(replacement, '.').toLowerCase(); }; var data = isForced.data = {}; var NATIVE = isForced.NATIVE = 'N'; var POLYFILL = isForced.POLYFILL = 'P'; var isForced_1 = isForced; var getOwnPropertyDescriptor = objectGetOwnPropertyDescriptor.f; /* options.target - name of the target object options.global - target is the global object options.stat - export as static methods of target options.proto - export as prototype methods of target options.real - real prototype method for the `pure` version options.forced - export even if the native feature is available options.bind - bind methods to the target, required for the `pure` version options.wrap - wrap constructors to preventing global pollution, required for the `pure` version options.unsafe - use the simple assignment of property instead of delete + defineProperty options.sham - add a flag to not completely full polyfills options.enumerable - export as enumerable property options.noTargetGet - prevent calling a getter on target */ var _export = function (options, source) { var TARGET = options.target; var GLOBAL = options.global; var STATIC = options.stat; var FORCED, target, key, targetProperty, sourceProperty, descriptor; if (GLOBAL) { target = global_1; } else if (STATIC) { target = global_1[TARGET] || setGlobal(TARGET, {}); } else { target = (global_1[TARGET] || {}).prototype; } if (target) for (key in source) { sourceProperty = source[key]; if (options.noTargetGet) { descriptor = getOwnPropertyDescriptor(target, key); targetProperty = descriptor && descriptor.value; } else targetProperty = target[key]; FORCED = isForced_1(GLOBAL ? key : TARGET + (STATIC ? '.' : '#') + key, options.forced); // contained in target if (!FORCED && targetProperty !== undefined) { if (typeof sourceProperty === typeof targetProperty) continue; copyConstructorProperties(sourceProperty, targetProperty); } // add a flag to not completely full polyfills if (options.sham || (targetProperty && targetProperty.sham)) { createNonEnumerableProperty(sourceProperty, 'sham', true); } // extend global redefine(target, key, sourceProperty, options); } }; // `IsArray` abstract operation // https://tc39.es/ecma262/#sec-isarray var isArray = Array.isArray || function isArray(arg) { return classofRaw(arg) == 'Array'; }; // `ToObject` abstract operation // https://tc39.es/ecma262/#sec-toobject var toObject = function (argument) { return Object(requireObjectCoercible(argument)); }; var createProperty = function (object, key, value) { var propertyKey = toPrimitive(key); if (propertyKey in object) objectDefineProperty.f(object, propertyKey, createPropertyDescriptor(0, value)); else object[propertyKey] = value; }; var engineIsNode = classofRaw(global_1.process) == 'process'; var engineUserAgent = getBuiltIn('navigator', 'userAgent') || ''; var process = global_1.process; var versions = process && process.versions; var v8 = versions && versions.v8; var match, version; if (v8) { match = v8.split('.'); version = match[0] + match[1]; } else if (engineUserAgent) { match = engineUserAgent.match(/Edge\/(\d+)/); if (!match || match[1] >= 74) { match = engineUserAgent.match(/Chrome\/(\d+)/); if (match) version = match[1]; } } var engineV8Version = version && +version; var nativeSymbol = !!Object.getOwnPropertySymbols && !fails(function () { /* global Symbol -- required for testing */ return !Symbol.sham && // Chrome 38 Symbol has incorrect toString conversion // Chrome 38-40 symbols are not inherited from DOM collections prototypes to instances (engineIsNode ? engineV8Version === 38 : engineV8Version > 37 && engineV8Version < 41); }); var useSymbolAsUid = nativeSymbol /* global Symbol -- safe */ && !Symbol.sham && typeof Symbol.iterator == 'symbol'; var WellKnownSymbolsStore = shared('wks'); var Symbol$1 = global_1.Symbol; var createWellKnownSymbol = useSymbolAsUid ? Symbol$1 : Symbol$1 && Symbol$1.withoutSetter || uid; var wellKnownSymbol = function (name) { if (!has$1(WellKnownSymbolsStore, name) || !(nativeSymbol || typeof WellKnownSymbolsStore[name] == 'string')) { if (nativeSymbol && has$1(Symbol$1, name)) { WellKnownSymbolsStore[name] = Symbol$1[name]; } else { WellKnownSymbolsStore[name] = createWellKnownSymbol('Symbol.' + name); } } return WellKnownSymbolsStore[name]; }; var SPECIES$1 = wellKnownSymbol('species'); // `ArraySpeciesCreate` abstract operation // https://tc39.es/ecma262/#sec-arrayspeciescreate var arraySpeciesCreate = function (originalArray, length) { var C; if (isArray(originalArray)) { C = originalArray.constructor; // cross-realm fallback if (typeof C == 'function' && (C === Array || isArray(C.prototype))) C = undefined; else if (isObject(C)) { C = C[SPECIES$1]; if (C === null) C = undefined; } } return new (C === undefined ? Array : C)(length === 0 ? 0 : length); }; var SPECIES = wellKnownSymbol('species'); var arrayMethodHasSpeciesSupport = function (METHOD_NAME) { // We can't use this feature detection in V8 since it causes // deoptimization and serious performance degradation // https://github.com/zloirock/core-js/issues/677 return engineV8Version >= 51 || !fails(function () { var array = []; var constructor = array.constructor = {}; constructor[SPECIES] = function () { return { foo: 1 }; }; return array[METHOD_NAME](Boolean).foo !== 1; }); }; var IS_CONCAT_SPREADABLE = wellKnownSymbol('isConcatSpreadable'); var MAX_SAFE_INTEGER = 0x1FFFFFFFFFFFFF; var MAXIMUM_ALLOWED_INDEX_EXCEEDED = 'Maximum allowed index exceeded'; // We can't use this feature detection in V8 since it causes // deoptimization and serious performance degradation // https://github.com/zloirock/core-js/issues/679 var IS_CONCAT_SPREADABLE_SUPPORT = engineV8Version >= 51 || !fails(function () { var array = []; array[IS_CONCAT_SPREADABLE] = false; return array.concat()[0] !== array; }); var SPECIES_SUPPORT = arrayMethodHasSpeciesSupport('concat'); var isConcatSpreadable = function (O) { if (!isObject(O)) return false; var spreadable = O[IS_CONCAT_SPREADABLE]; return spreadable !== undefined ? !!spreadable : isArray(O); }; var FORCED = !IS_CONCAT_SPREADABLE_SUPPORT || !SPECIES_SUPPORT; // `Array.prototype.concat` method // https://tc39.es/ecma262/#sec-array.prototype.concat // with adding support of @@isConcatSpreadable and @@species _export({ target: 'Array', proto: true, forced: FORCED }, { // eslint-disable-next-line no-unused-vars -- required for `.length` concat: function concat(arg) { var O = toObject(this); var A = arraySpeciesCreate(O, 0); var n = 0; var i, k, length, len, E; for (i = -1, length = arguments.length; i < length; i++) { E = i === -1 ? O : arguments[i]; if (isConcatSpreadable(E)) { len = toLength(E.length); if (n + len > MAX_SAFE_INTEGER) throw TypeError(MAXIMUM_ALLOWED_INDEX_EXCEEDED); for (k = 0; k < len; k++, n++) if (k in E) createProperty(A, n, E[k]); } else { if (n >= MAX_SAFE_INTEGER) throw TypeError(MAXIMUM_ALLOWED_INDEX_EXCEEDED); createProperty(A, n++, E); } } A.length = n; return A; } }); /** * Bootstrap Table English translation * Author: Zhixin Wen<wenzhixin2010@gmail.com> */ $__default['default'].fn.bootstrapTable.locales['en-US'] = $__default['default'].fn.bootstrapTable.locales['en'] = { formatCopyRows: function formatCopyRows() { return 'Copy Rows'; }, formatPrint: function formatPrint() { return 'Print'; }, formatLoadingMessage: function formatLoadingMessage() { return 'Loading, please wait'; }, formatRecordsPerPage: function formatRecordsPerPage(pageNumber) { return "".concat(pageNumber, " rows per page"); }, formatShowingRows: function formatShowingRows(pageFrom, pageTo, totalRows, totalNotFiltered) { if (totalNotFiltered !== undefined && totalNotFiltered > 0 && totalNotFiltered > totalRows) { return "Showing ".concat(pageFrom, " to ").concat(pageTo, " of ").concat(totalRows, " rows (filtered from ").concat(totalNotFiltered, " total rows)"); } return "Showing ".concat(pageFrom, " to ").concat(pageTo, " of ").concat(totalRows, " rows"); }, formatSRPaginationPreText: function formatSRPaginationPreText() { return 'previous page'; }, formatSRPaginationPageText: function formatSRPaginationPageText(page) { return "to page ".concat(page); }, formatSRPaginationNextText: function formatSRPaginationNextText() { return 'next page'; }, formatDetailPagination: function formatDetailPagination(totalRows) { return "Showing ".concat(totalRows, " rows"); }, formatClearSearch: function formatClearSearch() { return 'Clear Search'; }, formatSearch: function formatSearch() { return 'Search'; }, formatNoMatches: function formatNoMatches() { return 'No matching records found'; }, formatPaginationSwitch: function formatPaginationSwitch() { return 'Hide/Show pagination'; }, formatPaginationSwitchDown: function formatPaginationSwitchDown() { return 'Show pagination'; }, formatPaginationSwitchUp: function formatPaginationSwitchUp() { return 'Hide pagination'; }, formatRefresh: function formatRefresh() { return 'Refresh'; }, formatToggle: function formatToggle() { return 'Toggle'; }, formatToggleOn: function formatToggleOn() { return 'Show card view'; }, formatToggleOff: function formatToggleOff() { return 'Hide card view'; }, formatColumns: function formatColumns() { return 'Columns'; }, formatColumnsToggleAll: function formatColumnsToggleAll() { return 'Toggle all'; }, formatFullscreen: function formatFullscreen() { return 'Fullscreen'; }, formatAllRows: function formatAllRows() { return 'All'; }, formatAutoRefresh: function formatAutoRefresh() { return 'Auto Refresh'; }, formatExport: function formatExport() { return 'Export data'; }, formatJumpTo: function formatJumpTo() { return 'GO'; }, formatAdvancedSearch: function formatAdvancedSearch() { return 'Advanced search'; }, formatAdvancedCloseButton: function formatAdvancedCloseButton() { return 'Close'; }, formatFilterControlSwitch: function formatFilterControlSwitch() { return 'Hide/Show controls'; }, formatFilterControlSwitchHide: function formatFilterControlSwitchHide() { return 'Hide controls'; }, formatFilterControlSwitchShow: function formatFilterControlSwitchShow() { return 'Show controls'; } }; $__default['default'].extend($__default['default'].fn.bootstrapTable.defaults, $__default['default'].fn.bootstrapTable.locales['en-US']); })));
define(['jquery', 'underscore', './filter/segment-filter', './segment-choice', 'jquery-ui'], function($, _, SegmentFilter) { 'use strict'; /** * Apply segment widget */ $.widget('orosegment.segmentCondition', { options: { segmentChoice: {}, segmentChoiceClass: 'select', filters: [], filterContainerClass: 'active-filter' }, _create: function() { var data = this.element.data('value'); this.$segmentChoice = $('<input>').addClass(this.options.segmentChoiceClass); this.$filterContainer = $('<span>').addClass(this.options.filterContainerClass); this.element.append(this.$segmentChoice, this.$filterContainer); this.$segmentChoice.segmentChoice(this.options.segmentChoice); if (data && data.columnName) { this.selectSegment(data); this._renderFilter(data.columnName); } this.$segmentChoice.on('changed', _.bind(function(e, filterId) { $(':focus').blur(); // reset current value on segment change this.element.data('value', {}); this._renderFilter(filterId); e.stopPropagation(); }, this)); this.$filterContainer.on('change', _.bind(function() { if (this.filter) { this.filter.applyValue(); } }, this)); }, _getCreateOptions: function() { return $.extend(true, {}, this.options); }, _renderFilter: function(fieldId) { var segmentId = fieldId.split('_')[1]; var filterId = this._getSegmentFilterId(); var data = this.element.find('input.select').inputWidget('data'); if (_.has(data, 'id')) { data.value = segmentId; // pre-set data this.element.data('value', { criterion: { filter: 'segment', data: data } }); } var options = this.options.filters[filterId]; this._createFilter(options); }, /** * Find filter in metadata array and return it's index there * * @returns {*} * @private */ _getSegmentFilterId: function() { var filterId = null; _.each(this.options.filters, function(filter, id) { if ('segment' === filter.name) { filterId = id; } }); return filterId; }, /** * Creates filter instance * * @param options {Object} * @private */ _createFilter: function(options) { var filter = new (SegmentFilter.extend(options))(); this._appendFilter(filter); }, _appendFilter: function(filter) { var value = this.element.data('value'); this.filter = filter; if (value && value.criterion) { this.filter.value = value.criterion.data; } this.filter.render(this.$segmentChoice); this.$filterContainer.empty().append(this.filter.$el); this.filter.on('update', _.bind(this._onUpdate, this)); this._onUpdate(); }, _onUpdate: function() { var value; if (!this.filter.isEmptyValue()) { value = { columnName: this.filter.entity_ids[this.$segmentChoice.data('entity')], criteria: 'condition-segment', criterion: { filter: this.filter.name, data: this.filter.getValue() } }; } else { value = {}; } this.element.data('value', value); this.element.trigger('changed'); }, selectSegment: function(data) { this.$segmentChoice.segmentChoice('setValue', data.columnName); } }); return $; });
/* * 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'; const models = require('./index'); /** * Describes network resource usage. * */ class Usage { /** * Create a Usage. * @member {string} [id] Resource identifier. * @member {number} currentValue The current value of the usage. * @member {number} limit The limit of usage. * @member {object} name The name of the type of usage. * @member {string} [name.value] A string describing the resource name. * @member {string} [name.localizedValue] A localized string describing the * resource name. */ constructor() { } /** * Defines the metadata of Usage * * @returns {object} metadata of Usage * */ mapper() { return { required: false, serializedName: 'Usage', type: { name: 'Composite', className: 'Usage', modelProperties: { id: { required: false, readOnly: true, serializedName: 'id', type: { name: 'String' } }, unit: { required: true, isConstant: true, serializedName: 'unit', defaultValue: 'Count', type: { name: 'String' } }, currentValue: { required: true, serializedName: 'currentValue', type: { name: 'Number' } }, limit: { required: true, serializedName: 'limit', type: { name: 'Number' } }, name: { required: true, serializedName: 'name', type: { name: 'Composite', className: 'UsageName' } } } } }; } } module.exports = Usage;
module.exports = { plugins: [ require('autoprefixer')({ browsers: [ 'last 3 version', 'ie >= 10', 'safari 5' ], }) ] };
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose")); var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends")); var React = _interopRequireWildcard(require("react")); var _propTypes = _interopRequireDefault(require("prop-types")); var _clsx = _interopRequireDefault(require("clsx")); var _utils = require("@material-ui/utils"); var _unstyled = require("@material-ui/unstyled"); var _capitalize = _interopRequireDefault(require("../utils/capitalize")); var _styled = _interopRequireDefault(require("../styles/styled")); var _useControlled = _interopRequireDefault(require("../utils/useControlled")); var _useFormControl = _interopRequireDefault(require("../FormControl/useFormControl")); var _ButtonBase = _interopRequireDefault(require("../ButtonBase")); var _switchBaseClasses = require("./switchBaseClasses"); var _jsxRuntime = require("react/jsx-runtime"); const _excluded = ["autoFocus", "checked", "checkedIcon", "className", "defaultChecked", "disabled", "disableFocusRipple", "edge", "icon", "id", "inputProps", "inputRef", "name", "onBlur", "onChange", "onFocus", "readOnly", "required", "tabIndex", "type", "value"]; function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } const useUtilityClasses = styleProps => { const { classes, checked, disabled, edge } = styleProps; const slots = { root: ['root', checked && 'checked', disabled && 'disabled', edge && `edge${(0, _capitalize.default)(edge)}`], input: ['input'] }; return (0, _unstyled.unstable_composeClasses)(slots, _switchBaseClasses.getSwitchBaseUtilityClass, classes); }; const SwitchBaseRoot = (0, _styled.default)(_ButtonBase.default, { skipSx: true })(({ styleProps }) => (0, _extends2.default)({ /* Styles applied to the root element. */ padding: 9, borderRadius: '50%' }, styleProps.edge === 'start' && { marginLeft: styleProps.size === 'small' ? -3 : -12 }, styleProps.edge === 'end' && { marginRight: styleProps.size === 'small' ? -3 : -12 })); const SwitchBaseInput = (0, _styled.default)('input', { skipSx: true })({ /* Styles applied to the internal input element. */ cursor: 'inherit', position: 'absolute', opacity: 0, width: '100%', height: '100%', top: 0, left: 0, margin: 0, padding: 0, zIndex: 1 }); /** * @ignore - internal component. */ const SwitchBase = /*#__PURE__*/React.forwardRef(function SwitchBase(props, ref) { const { autoFocus, checked: checkedProp, checkedIcon, className, defaultChecked, disabled: disabledProp, disableFocusRipple = false, edge = false, icon, id, inputProps, inputRef, name, onBlur, onChange, onFocus, readOnly, required, tabIndex, type, value } = props, other = (0, _objectWithoutPropertiesLoose2.default)(props, _excluded); const [checked, setCheckedState] = (0, _useControlled.default)({ controlled: checkedProp, default: Boolean(defaultChecked), name: 'SwitchBase', state: 'checked' }); const muiFormControl = (0, _useFormControl.default)(); const handleFocus = event => { if (onFocus) { onFocus(event); } if (muiFormControl && muiFormControl.onFocus) { muiFormControl.onFocus(event); } }; const handleBlur = event => { if (onBlur) { onBlur(event); } if (muiFormControl && muiFormControl.onBlur) { muiFormControl.onBlur(event); } }; const handleInputChange = event => { // Workaround for https://github.com/facebook/react/issues/9023 if (event.nativeEvent.defaultPrevented) { return; } setCheckedState(event.target.checked); if (onChange) { onChange(event); } }; let disabled = disabledProp; if (muiFormControl) { if (typeof disabled === 'undefined') { disabled = muiFormControl.disabled; } } const hasLabelFor = type === 'checkbox' || type === 'radio'; const styleProps = (0, _extends2.default)({}, props, { checked, disabled, disableFocusRipple, edge }); const classes = useUtilityClasses(styleProps); return /*#__PURE__*/(0, _jsxRuntime.jsxs)(SwitchBaseRoot, (0, _extends2.default)({ component: "span", className: (0, _clsx.default)(classes.root, className), centerRipple: true, focusRipple: !disableFocusRipple, disabled: disabled, tabIndex: null, role: undefined, onFocus: handleFocus, onBlur: handleBlur, styleProps: styleProps, ref: ref }, other, { children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(SwitchBaseInput, (0, _extends2.default)({ autoFocus: autoFocus, checked: checkedProp, defaultChecked: defaultChecked, className: classes.input, disabled: disabled, id: hasLabelFor && id, name: name, onChange: handleInputChange, readOnly: readOnly, ref: inputRef, required: required, styleProps: styleProps, tabIndex: tabIndex, type: type, value: value }, inputProps)), checked ? checkedIcon : icon] })); }); // NB: If changed, please update Checkbox, Switch and Radio // so that the API documentation is updated. process.env.NODE_ENV !== "production" ? SwitchBase.propTypes = { /** * If `true`, the `input` element is focused during the first mount. */ autoFocus: _propTypes.default.bool, /** * If `true`, the component is checked. */ checked: _propTypes.default.bool, /** * The icon to display when the component is checked. */ checkedIcon: _propTypes.default.node.isRequired, /** * Override or extend the styles applied to the component. * See [CSS API](#css) below for more details. */ classes: _propTypes.default.object, /** * @ignore */ className: _propTypes.default.string, /** * @ignore */ defaultChecked: _propTypes.default.bool, /** * If `true`, the component is disabled. */ disabled: _propTypes.default.bool, /** * If `true`, the keyboard focus ripple is disabled. * @default false */ disableFocusRipple: _propTypes.default.bool, /** * If given, uses a negative margin to counteract the padding on one * side (this is often helpful for aligning the left or right * side of the icon with content above or below, without ruining the border * size and shape). * @default false */ edge: _propTypes.default.oneOf(['end', 'start', false]), /** * The icon to display when the component is unchecked. */ icon: _propTypes.default.node.isRequired, /** * The id of the `input` element. */ id: _propTypes.default.string, /** * [Attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Attributes) applied to the `input` element. */ inputProps: _propTypes.default.object, /** * Pass a ref to the `input` element. */ inputRef: _utils.refType, /* * @ignore */ name: _propTypes.default.string, /** * @ignore */ onBlur: _propTypes.default.func, /** * Callback fired when the state is changed. * * @param {object} event The event source of the callback. * You can pull out the new checked state by accessing `event.target.checked` (boolean). */ onChange: _propTypes.default.func, /** * @ignore */ onFocus: _propTypes.default.func, /** * It prevents the user from changing the value of the field * (not from interacting with the field). */ readOnly: _propTypes.default.bool, /** * If `true`, the `input` element is required. */ required: _propTypes.default.bool, /** * The system prop that allows defining system overrides as well as additional CSS styles. */ sx: _propTypes.default.object, /** * @ignore */ tabIndex: _propTypes.default.oneOfType([_propTypes.default.number, _propTypes.default.string]), /** * The input component prop `type`. */ type: _propTypes.default.string.isRequired, /** * The value of the component. */ value: _propTypes.default.any } : void 0; var _default = SwitchBase; exports.default = _default;
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var React = require('react'); var utils = require('primereact/utils'); var keyfilter = require('primereact/keyfilter'); var tooltip = require('primereact/tooltip'); function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } var React__default = /*#__PURE__*/_interopDefaultLegacy(React); function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var InputTextComponent = /*#__PURE__*/function (_Component) { _inherits(InputTextComponent, _Component); var _super = _createSuper(InputTextComponent); function InputTextComponent(props) { var _this; _classCallCheck(this, InputTextComponent); _this = _super.call(this, props); _this.onInput = _this.onInput.bind(_assertThisInitialized(_this)); _this.onKeyPress = _this.onKeyPress.bind(_assertThisInitialized(_this)); _this.elementRef = /*#__PURE__*/React.createRef(_this.props.forwardRef); return _this; } _createClass(InputTextComponent, [{ key: "isFilled", value: function isFilled() { return this.props.value != null && this.props.value.toString().length > 0 || this.props.defaultValue != null && this.props.defaultValue.toString().length > 0 || this.elementRef && this.elementRef.current && this.elementRef.current.value != null && this.elementRef.current.value.toString().length > 0; } }, { key: "onKeyPress", value: function onKeyPress(event) { if (this.props.onKeyPress) { this.props.onKeyPress(event); } if (this.props.keyfilter) { keyfilter.KeyFilter.onKeyPress(event, this.props.keyfilter, this.props.validateOnly); } } }, { key: "onInput", value: function onInput(event) { var validatePattern = true; if (this.props.keyfilter && this.props.validateOnly) { validatePattern = keyfilter.KeyFilter.validate(event, this.props.keyfilter); } if (this.props.onInput) { this.props.onInput(event, validatePattern); } if (!this.props.onChange) { if (event.target.value.length > 0) utils.DomHandler.addClass(event.target, 'p-filled');else utils.DomHandler.removeClass(event.target, 'p-filled'); } } }, { key: "updateForwardRef", value: function updateForwardRef() { var ref = this.props.forwardRef; if (ref) { if (typeof ref === 'function') { ref(this.elementRef.current); } else { ref.current = this.elementRef.current; } } } }, { key: "componentDidMount", value: function componentDidMount() { this.updateForwardRef(); if (this.props.tooltip) { this.renderTooltip(); } } }, { key: "componentDidUpdate", value: function componentDidUpdate(prevProps) { if (prevProps.tooltip !== this.props.tooltip || prevProps.tooltipOptions !== this.props.tooltipOptions) { if (this.tooltip) this.tooltip.update(_objectSpread({ content: this.props.tooltip }, this.props.tooltipOptions || {}));else this.renderTooltip(); } } }, { key: "componentWillUnmount", value: function componentWillUnmount() { if (this.tooltip) { this.tooltip.destroy(); this.tooltip = null; } } }, { key: "renderTooltip", value: function renderTooltip() { this.tooltip = tooltip.tip({ target: this.elementRef.current, content: this.props.tooltip, options: this.props.tooltipOptions }); } }, { key: "render", value: function render() { var className = utils.classNames('p-inputtext p-component', { 'p-disabled': this.props.disabled, 'p-filled': this.isFilled() }, this.props.className); var inputProps = utils.ObjectUtils.findDiffKeys(this.props, InputTextComponent.defaultProps); return /*#__PURE__*/React__default["default"].createElement("input", _extends({ ref: this.elementRef }, inputProps, { className: className, onInput: this.onInput, onKeyPress: this.onKeyPress })); } }]); return InputTextComponent; }(React.Component); _defineProperty(InputTextComponent, "defaultProps", { keyfilter: null, validateOnly: false, tooltip: null, tooltipOptions: null, onInput: null, onKeyPress: null, forwardRef: null }); var InputText = /*#__PURE__*/React__default["default"].forwardRef(function (props, ref) { return /*#__PURE__*/React__default["default"].createElement(InputTextComponent, _extends({ forwardRef: ref }, props)); }); exports.InputText = InputText;
module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), browserify: { control: { src: ['src/L.Realtime.js'], dest: 'dist/leaflet-realtime.js', options: { transform: [ [ 'browserify-shim', { 'leaflet': 'global:L' } ], ], browserifyOptions: { standalone: 'L.Realtime' } } } }, uglify: { options: { banner: '/*! <%= pkg.name %> - v<%= pkg.version %> - ' + '<%= grunt.template.today("yyyy-mm-dd") %> */\n\n' }, build: { src: 'dist/leaflet-realtime.js', dest: 'dist/leaflet-realtime.min.js' } } }); grunt.loadNpmTasks('grunt-browserify'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.registerTask('default', ['browserify', 'uglify']); };
/** * @license * Copyright (c) 2016 The {life-parser} Project Authors. All rights reserved. * This code may only be used under the MIT style license found at http://100dayproject.github.io/LICENSE.txt * The complete set of authors may be found at http://100dayproject.github.io/AUTHORS.txt * The complete set of contributors may be found at http://100dayproject.github.io/CONTRIBUTORS.txt * Code distributed by 100dayproject as part of the life. */ "use strict"; CKEDITOR.plugins.add('crab_media', { icon: 'timestamp', init: function (editor) { editor.addCommand('insertMedia', { exec: function (e) { var now = new Date(); e.insertHtml('The current date and time is: <em>' + now.toString() + '</em>'); } }); editor.ui.addButton('crab_media', { label: 'CrabJS: Insert Media', command: 'insertMedia', toolbar: 'insert' }); } });
define([ 'pex/geom/hem/HEMesh', 'pex/geom/hem/HEVertex', 'pex/geom/hem/HEEdge', 'pex/geom/hem/HEFace', 'pex/geom/Vec3' ], function(HEMesh, HEVertex, HEEdge, HEFace, Vec3) { function Extrude() { } HEMesh.prototype.extrude = function(height, direction) { height = height || 0.1; var numFaces = this.faces.length; var self = this; var faces = this.faces; var selectedFaces = this.getSelectedFaces(); if (selectedFaces.length > 0) { faces = selectedFaces; } faces.forEach(function(face, i) { var normal = direction || face.getNormal(); var edge = face.edge; var lastEdge = edge.findPrev(); var edgeToSplit = edge; var prevNewEdge = null; var center = face.getCenter(); var newEdges = []; //we split all the corners within the face effectively adding new internal vertices do { //var newVertexPos = edgeToSplit.vert.added(normal.scaled(height)); var newVertexPos = normal.clone().scale(height).add(edgeToSplit.vert.position); edgeToSplit.vert.edge = edgeToSplit; //TODO: fix that, making sure we split the right face var newEdge = self.splitVertex(edgeToSplit.vert, newVertexPos); newEdges.push(newEdge); if (edgeToSplit == lastEdge) { break; } edgeToSplit = edgeToSplit.next; } while(edgeToSplit != edge); //go through all new corners and cut out faces from them var prevCornerEdge = newEdges[newEdges.length-1].next; for(var i=0; i<newEdges.length; i++) { //we remember what's the next edge pointing to a new corner as //this might change when we add new face var tmp = newEdges[i].next; var newFace = self.splitFace(newEdges[i].next, prevCornerEdge); prevCornerEdge = tmp; } }); return this; } return Extrude; });
/* * A range */ module.exports = function(obj) { if(obj.type !== 'RANGE') { throw "This is not a range!"; } var parser = require('./expression.js'); return 'range(' + parser(obj.from) + ', ' + parser(obj.to) + ')'; };
import { moduleForModel, test } from 'ember-qunit'; moduleForModel('user', 'Unit | Serializer | user', { // Specify the other units that are required for this test. needs: ['serializer:user'] }); // Replace this with your real tests. test('it serializes records', function(assert) { let record = this.subject(); let serializedRecord = record.serialize(); assert.ok(serializedRecord); });
"use strict"; /* globals describe it */ require("should"); const path = require("path"); const fs = require("fs"); const webpack = require("../"); describe("Examples", () => { const examples = fs.readdirSync(path.join(__dirname, "..", "examples")).map((name) => path.join(__dirname, "..", "examples", name)).filter((p) => fs.statSync(p).isDirectory() && fs.existsSync(path.join(p, "build.js"))); examples.forEach((examplePath) => { it("should compile " + path.basename(examplePath), function(done) { this.timeout(20000); let options = {}; let webpackConfigPath = path.join(examplePath, "webpack.config.js"); webpackConfigPath = webpackConfigPath.substr(0, 1).toUpperCase() + webpackConfigPath.substr(1); if(fs.existsSync(webpackConfigPath)) options = require(webpackConfigPath); if(Array.isArray(options)) options.forEach(processOptions); else processOptions(options); function processOptions(options) { options.context = examplePath; options.output = options.output || {}; options.output.pathinfo = true; options.output.path = path.join(examplePath, "js"); options.output.publicPath = "js/"; if(!options.output.filename) options.output.filename = "output.js"; if(!options.entry) options.entry = "./example.js"; } webpack(options, (err, stats) => { if(err) return done(err); stats = stats.toJson({ errorDetails: true }); if(stats.errors.length > 0) { return done(new Error(stats.errors[0])); } done(); }); }); }); });
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow strict * @format */ // flowlint ambiguous-object-type:error 'use strict'; function createPrintRequireModuleDependency( extension: string, ): string => string { return moduleName => `require('./${moduleName}.${extension}')`; } module.exports = createPrintRequireModuleDependency;
describe('[Regression](GH-3724)', () => { it('Should correctly type text in an editable iframe', () => runTests('testcafe-fixtures/index.js')); });
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function getFailedSnapshotTests(testResults) { const failedTestPaths = []; if (testResults.numFailedTests === 0 || !testResults.testResults) { return failedTestPaths; } testResults.testResults.forEach(testResult => { if (testResult.snapshot && testResult.snapshot.unmatched) { failedTestPaths.push(testResult.testFilePath); } }); return failedTestPaths; } exports.default = getFailedSnapshotTests;
module.exports = React.createClass({ displayName: "actual", render: function render() { return null; } });
'use strict'; // Configuring the Articles module angular.module('jobs').run(['Menus', function(Menus) { // Set top bar menu items Menus.addMenuItem('topbar', 'Jobs', 'jobs', 'dropdown', '/jobs(/create)?'); Menus.addSubMenuItem('topbar', 'jobs', 'List Jobs', 'jobs'); Menus.addSubMenuItem('topbar', 'jobs', 'New Job', 'jobs/create'); } ]);
import Events from "v2/Utils/Events" import { configure, addParameters } from "@storybook/react" import { createMediaStyle } from "v2/Utils/Responsive" const req = require.context("../", true, /\.story\.tsx$/) function loadStories() { req.keys().forEach(filename => { return req(filename) }) } // Add RRM styles to Storybooks head const rrmStyle = document.createElement("style") rrmStyle.innerHTML = createMediaStyle() document.head.appendChild(rrmStyle) addParameters({ inline: true, brandTitle: "Reaction", showAddonPanel: false, sortStoriesByKind: true, }) setTimeout(() => { configure(loadStories, module) }) Events.onEvent(data => { console.log("Tracked event", data) }) if (!window.sd || !(typeof window.sd === "object")) { window.sd = {} }
/** @module ember-data */ import Ember from 'ember'; import Adapter from "ember-data/adapter"; import { AdapterError, InvalidError, TimeoutError, AbortError } from 'ember-data/-private/adapters/errors'; import EmptyObject from "ember-data/-private/system/empty-object"; import BuildURLMixin from "ember-data/-private/adapters/build-url-mixin"; import isEnabled from 'ember-data/-private/features'; const { MapWithDefault, get } = Ember; /** The REST adapter allows your store to communicate with an HTTP server by transmitting JSON via XHR. Most Ember.js apps that consume a JSON API should use the REST adapter. This adapter is designed around the idea that the JSON exchanged with the server should be conventional. ## JSON Structure The REST adapter expects the JSON returned from your server to follow these conventions. ### Object Root The JSON payload should be an object that contains the record inside a root property. For example, in response to a `GET` request for `/posts/1`, the JSON should look like this: ```js { "post": { "id": 1, "title": "I'm Running to Reform the W3C's Tag", "author": "Yehuda Katz" } } ``` Similarly, in response to a `GET` request for `/posts`, the JSON should look like this: ```js { "posts": [ { "id": 1, "title": "I'm Running to Reform the W3C's Tag", "author": "Yehuda Katz" }, { "id": 2, "title": "Rails is omakase", "author": "D2H" } ] } ``` Note that the object root can be pluralized for both a single-object response and an array response: the REST adapter is not strict on this. Further, if the HTTP server responds to a `GET` request to `/posts/1` (e.g. the response to a `findRecord` query) with more than one object in the array, Ember Data will only display the object with the matching ID. ### Conventional Names Attribute names in your JSON payload should be the camelCased versions of the attributes in your Ember.js models. For example, if you have a `Person` model: ```app/models/person.js import DS from 'ember-data'; export default DS.Model.extend({ firstName: DS.attr('string'), lastName: DS.attr('string'), occupation: DS.attr('string') }); ``` The JSON returned should look like this: ```js { "person": { "id": 5, "firstName": "Barack", "lastName": "Obama", "occupation": "President" } } ``` ## Customization ### Endpoint path customization Endpoint paths can be prefixed with a `namespace` by setting the namespace property on the adapter: ```app/adapters/application.js import DS from 'ember-data'; export default DS.RESTAdapter.extend({ namespace: 'api/1' }); ``` Requests for the `Person` model would now target `/api/1/people/1`. ### Host customization An adapter can target other hosts by setting the `host` property. ```app/adapters/application.js import DS from 'ember-data'; export default DS.RESTAdapter.extend({ host: 'https://api.example.com' }); ``` ### Headers customization Some APIs require HTTP headers, e.g. to provide an API key. Arbitrary headers can be set as key/value pairs on the `RESTAdapter`'s `headers` object and Ember Data will send them along with each ajax request. ```app/adapters/application.js import DS from 'ember-data'; export default DS.RESTAdapter.extend({ headers: { "API_KEY": "secret key", "ANOTHER_HEADER": "Some header value" } }); ``` `headers` can also be used as a computed property to support dynamic headers. In the example below, the `session` object has been injected into an adapter by Ember's container. ```app/adapters/application.js import DS from 'ember-data'; export default DS.RESTAdapter.extend({ headers: Ember.computed('session.authToken', function() { return { "API_KEY": this.get("session.authToken"), "ANOTHER_HEADER": "Some header value" }; }) }); ``` In some cases, your dynamic headers may require data from some object outside of Ember's observer system (for example `document.cookie`). You can use the [volatile](/api/classes/Ember.ComputedProperty.html#method_volatile) function to set the property into a non-cached mode causing the headers to be recomputed with every request. ```app/adapters/application.js import DS from 'ember-data'; export default DS.RESTAdapter.extend({ headers: Ember.computed(function() { return { "API_KEY": Ember.get(document.cookie.match(/apiKey\=([^;]*)/), "1"), "ANOTHER_HEADER": "Some header value" }; }).volatile() }); ``` @class RESTAdapter @constructor @namespace DS @extends DS.Adapter @uses DS.BuildURLMixin */ export default Adapter.extend(BuildURLMixin, { defaultSerializer: '-rest', /** By default, the RESTAdapter will send the query params sorted alphabetically to the server. For example: ```js store.query('posts', { sort: 'price', category: 'pets' }); ``` will generate a requests like this `/posts?category=pets&sort=price`, even if the parameters were specified in a different order. That way the generated URL will be deterministic and that simplifies caching mechanisms in the backend. Setting `sortQueryParams` to a falsey value will respect the original order. In case you want to sort the query parameters with a different criteria, set `sortQueryParams` to your custom sort function. ```app/adapters/application.js import DS from 'ember-data'; export default DS.RESTAdapter.extend({ sortQueryParams: function(params) { var sortedKeys = Object.keys(params).sort().reverse(); var len = sortedKeys.length, newParams = {}; for (var i = 0; i < len; i++) { newParams[sortedKeys[i]] = params[sortedKeys[i]]; } return newParams; } }); ``` @method sortQueryParams @param {Object} obj @return {Object} */ sortQueryParams(obj) { var keys = Object.keys(obj); var len = keys.length; if (len < 2) { return obj; } var newQueryParams = {}; var sortedKeys = keys.sort(); for (var i = 0; i < len; i++) { newQueryParams[sortedKeys[i]] = obj[sortedKeys[i]]; } return newQueryParams; }, /** By default the RESTAdapter will send each find request coming from a `store.find` or from accessing a relationship separately to the server. If your server supports passing ids as a query string, you can set coalesceFindRequests to true to coalesce all find requests within a single runloop. For example, if you have an initial payload of: ```javascript { post: { id: 1, comments: [1, 2] } } ``` By default calling `post.get('comments')` will trigger the following requests(assuming the comments haven't been loaded before): ``` GET /comments/1 GET /comments/2 ``` If you set coalesceFindRequests to `true` it will instead trigger the following request: ``` GET /comments?ids[]=1&ids[]=2 ``` Setting coalesceFindRequests to `true` also works for `store.find` requests and `belongsTo` relationships accessed within the same runloop. If you set `coalesceFindRequests: true` ```javascript store.findRecord('comment', 1); store.findRecord('comment', 2); ``` will also send a request to: `GET /comments?ids[]=1&ids[]=2` Note: Requests coalescing rely on URL building strategy. So if you override `buildURL` in your app `groupRecordsForFindMany` more likely should be overridden as well in order for coalescing to work. @property coalesceFindRequests @type {boolean} */ coalesceFindRequests: false, /** Endpoint paths can be prefixed with a `namespace` by setting the namespace property on the adapter: ```app/adapters/application.js import DS from 'ember-data'; export default DS.RESTAdapter.extend({ namespace: 'api/1' }); ``` Requests for the `Post` model would now target `/api/1/post/`. @property namespace @type {String} */ /** An adapter can target other hosts by setting the `host` property. ```app/adapters/application.js import DS from 'ember-data'; export default DS.RESTAdapter.extend({ host: 'https://api.example.com' }); ``` Requests for the `Post` model would now target `https://api.example.com/post/`. @property host @type {String} */ /** Some APIs require HTTP headers, e.g. to provide an API key. Arbitrary headers can be set as key/value pairs on the `RESTAdapter`'s `headers` object and Ember Data will send them along with each ajax request. For dynamic headers see [headers customization](/api/data/classes/DS.RESTAdapter.html#toc_headers-customization). ```app/adapters/application.js import DS from 'ember-data'; export default DS.RESTAdapter.extend({ headers: { "API_KEY": "secret key", "ANOTHER_HEADER": "Some header value" } }); ``` @property headers @type {Object} */ /** Called by the store in order to fetch the JSON for a given type and ID. The `findRecord` method makes an Ajax request to a URL computed by `buildURL`, and returns a promise for the resulting payload. This method performs an HTTP `GET` request with the id provided as part of the query string. @method findRecord @param {DS.Store} store @param {DS.Model} type @param {String} id @param {DS.Snapshot} snapshot @return {Promise} promise */ findRecord(store, type, id, snapshot) { const url = this.buildURL(type.modelName, id, snapshot, 'findRecord'); const query = this.buildQuery(snapshot); return this.ajax(url, 'GET', { data: query }); }, /** Called by the store in order to fetch a JSON array for all of the records for a given type. The `findAll` method makes an Ajax (HTTP GET) request to a URL computed by `buildURL`, and returns a promise for the resulting payload. @method findAll @param {DS.Store} store @param {DS.Model} type @param {String} sinceToken @param {DS.SnapshotRecordArray} snapshotRecordArray @return {Promise} promise */ findAll(store, type, sinceToken, snapshotRecordArray) { const url = this.buildURL(type.modelName, null, null, 'findAll'); const query = this.buildQuery(snapshotRecordArray); if (sinceToken) { query.since = sinceToken; } return this.ajax(url, 'GET', { data: query }); }, /** Called by the store in order to fetch a JSON array for the records that match a particular query. The `query` method makes an Ajax (HTTP GET) request to a URL computed by `buildURL`, and returns a promise for the resulting payload. The `query` argument is a simple JavaScript object that will be passed directly to the server as parameters. @method query @param {DS.Store} store @param {DS.Model} type @param {Object} query @return {Promise} promise */ query(store, type, query) { var url = this.buildURL(type.modelName, null, null, 'query', query); if (this.sortQueryParams) { query = this.sortQueryParams(query); } return this.ajax(url, 'GET', { data: query }); }, /** Called by the store in order to fetch a JSON object for the record that matches a particular query. The `queryRecord` method makes an Ajax (HTTP GET) request to a URL computed by `buildURL`, and returns a promise for the resulting payload. The `query` argument is a simple JavaScript object that will be passed directly to the server as parameters. @method queryRecord @param {DS.Store} store @param {DS.Model} type @param {Object} query @return {Promise} promise */ queryRecord(store, type, query) { var url = this.buildURL(type.modelName, null, null, 'queryRecord', query); if (this.sortQueryParams) { query = this.sortQueryParams(query); } return this.ajax(url, 'GET', { data: query }); }, /** Called by the store in order to fetch several records together if `coalesceFindRequests` is true For example, if the original payload looks like: ```js { "id": 1, "title": "Rails is omakase", "comments": [ 1, 2, 3 ] } ``` The IDs will be passed as a URL-encoded Array of IDs, in this form: ``` ids[]=1&ids[]=2&ids[]=3 ``` Many servers, such as Rails and PHP, will automatically convert this URL-encoded array into an Array for you on the server-side. If you want to encode the IDs, differently, just override this (one-line) method. The `findMany` method makes an Ajax (HTTP GET) request to a URL computed by `buildURL`, and returns a promise for the resulting payload. @method findMany @param {DS.Store} store @param {DS.Model} type @param {Array} ids @param {Array} snapshots @return {Promise} promise */ findMany(store, type, ids, snapshots) { var url = this.buildURL(type.modelName, ids, snapshots, 'findMany'); return this.ajax(url, 'GET', { data: { ids: ids } }); }, /** Called by the store in order to fetch a JSON array for the unloaded records in a has-many relationship that were originally specified as a URL (inside of `links`). For example, if your original payload looks like this: ```js { "post": { "id": 1, "title": "Rails is omakase", "links": { "comments": "/posts/1/comments" } } } ``` This method will be called with the parent record and `/posts/1/comments`. The `findHasMany` method will make an Ajax (HTTP GET) request to the originally specified URL. The format of your `links` value will influence the final request URL via the `urlPrefix` method: * Links beginning with `//`, `http://`, `https://`, will be used as is, with no further manipulation. * Links beginning with a single `/` will have the current adapter's `host` value prepended to it. * Links with no beginning `/` will have a parentURL prepended to it, via the current adapter's `buildURL`. @method findHasMany @param {DS.Store} store @param {DS.Snapshot} snapshot @param {String} url @return {Promise} promise */ findHasMany(store, snapshot, url, relationship) { var id = snapshot.id; var type = snapshot.modelName; url = this.urlPrefix(url, this.buildURL(type, id, null, 'findHasMany')); return this.ajax(url, 'GET'); }, /** Called by the store in order to fetch a JSON array for the unloaded records in a belongs-to relationship that were originally specified as a URL (inside of `links`). For example, if your original payload looks like this: ```js { "person": { "id": 1, "name": "Tom Dale", "links": { "group": "/people/1/group" } } } ``` This method will be called with the parent record and `/people/1/group`. The `findBelongsTo` method will make an Ajax (HTTP GET) request to the originally specified URL. The format of your `links` value will influence the final request URL via the `urlPrefix` method: * Links beginning with `//`, `http://`, `https://`, will be used as is, with no further manipulation. * Links beginning with a single `/` will have the current adapter's `host` value prepended to it. * Links with no beginning `/` will have a parentURL prepended to it, via the current adapter's `buildURL`. @method findBelongsTo @param {DS.Store} store @param {DS.Snapshot} snapshot @param {String} url @return {Promise} promise */ findBelongsTo(store, snapshot, url, relationship) { var id = snapshot.id; var type = snapshot.modelName; url = this.urlPrefix(url, this.buildURL(type, id, null, 'findBelongsTo')); return this.ajax(url, 'GET'); }, /** Called by the store when a newly created record is saved via the `save` method on a model record instance. The `createRecord` method serializes the record and makes an Ajax (HTTP POST) request to a URL computed by `buildURL`. See `serialize` for information on how to customize the serialized form of a record. @method createRecord @param {DS.Store} store @param {DS.Model} type @param {DS.Snapshot} snapshot @return {Promise} promise */ createRecord(store, type, snapshot) { var data = {}; var serializer = store.serializerFor(type.modelName); var url = this.buildURL(type.modelName, null, snapshot, 'createRecord'); serializer.serializeIntoHash(data, type, snapshot, { includeId: true }); return this.ajax(url, "POST", { data: data }); }, /** Called by the store when an existing record is saved via the `save` method on a model record instance. The `updateRecord` method serializes the record and makes an Ajax (HTTP PUT) request to a URL computed by `buildURL`. See `serialize` for information on how to customize the serialized form of a record. @method updateRecord @param {DS.Store} store @param {DS.Model} type @param {DS.Snapshot} snapshot @return {Promise} promise */ updateRecord(store, type, snapshot) { var data = {}; var serializer = store.serializerFor(type.modelName); serializer.serializeIntoHash(data, type, snapshot); var id = snapshot.id; var url = this.buildURL(type.modelName, id, snapshot, 'updateRecord'); return this.ajax(url, "PUT", { data: data }); }, /** Called by the store when a record is deleted. The `deleteRecord` method makes an Ajax (HTTP DELETE) request to a URL computed by `buildURL`. @method deleteRecord @param {DS.Store} store @param {DS.Model} type @param {DS.Snapshot} snapshot @return {Promise} promise */ deleteRecord(store, type, snapshot) { var id = snapshot.id; return this.ajax(this.buildURL(type.modelName, id, snapshot, 'deleteRecord'), "DELETE"); }, _stripIDFromURL(store, snapshot) { var url = this.buildURL(snapshot.modelName, snapshot.id, snapshot); var expandedURL = url.split('/'); //Case when the url is of the format ...something/:id var lastSegment = expandedURL[expandedURL.length - 1]; var id = snapshot.id; if (lastSegment === id) { expandedURL[expandedURL.length - 1] = ""; } else if (endsWith(lastSegment, '?id=' + id)) { //Case when the url is of the format ...something?id=:id expandedURL[expandedURL.length - 1] = lastSegment.substring(0, lastSegment.length - id.length - 1); } return expandedURL.join('/'); }, // http://stackoverflow.com/questions/417142/what-is-the-maximum-length-of-a-url-in-different-browsers maxURLLength: 2048, /** Organize records into groups, each of which is to be passed to separate calls to `findMany`. This implementation groups together records that have the same base URL but differing ids. For example `/comments/1` and `/comments/2` will be grouped together because we know findMany can coalesce them together as `/comments?ids[]=1&ids[]=2` It also supports urls where ids are passed as a query param, such as `/comments?id=1` but not those where there is more than 1 query param such as `/comments?id=2&name=David` Currently only the query param of `id` is supported. If you need to support others, please override this or the `_stripIDFromURL` method. It does not group records that have differing base urls, such as for example: `/posts/1/comments/2` and `/posts/2/comments/3` @method groupRecordsForFindMany @param {DS.Store} store @param {Array} snapshots @return {Array} an array of arrays of records, each of which is to be loaded separately by `findMany`. */ groupRecordsForFindMany(store, snapshots) { var groups = MapWithDefault.create({ defaultValue() { return []; } }); var adapter = this; var maxURLLength = this.maxURLLength; snapshots.forEach((snapshot) => { var baseUrl = adapter._stripIDFromURL(store, snapshot); groups.get(baseUrl).push(snapshot); }); function splitGroupToFitInUrl(group, maxURLLength, paramNameLength) { var baseUrl = adapter._stripIDFromURL(store, group[0]); var idsSize = 0; var splitGroups = [[]]; group.forEach((snapshot) => { var additionalLength = encodeURIComponent(snapshot.id).length + paramNameLength; if (baseUrl.length + idsSize + additionalLength >= maxURLLength) { idsSize = 0; splitGroups.push([]); } idsSize += additionalLength; var lastGroupIndex = splitGroups.length - 1; splitGroups[lastGroupIndex].push(snapshot); }); return splitGroups; } var groupsArray = []; groups.forEach((group, key) => { var paramNameLength = '&ids%5B%5D='.length; var splitGroups = splitGroupToFitInUrl(group, maxURLLength, paramNameLength); splitGroups.forEach((splitGroup) => groupsArray.push(splitGroup)); }); return groupsArray; }, /** Takes an ajax response, and returns the json payload or an error. By default this hook just returns the json payload passed to it. You might want to override it in two cases: 1. Your API might return useful results in the response headers. Response headers are passed in as the second argument. 2. Your API might return errors as successful responses with status code 200 and an Errors text or object. You can return a `DS.InvalidError` or a `DS.AdapterError` (or a sub class) from this hook and it will automatically reject the promise and put your record into the invalid or error state. Returning a `DS.InvalidError` from this method will cause the record to transition into the `invalid` state and make the `errors` object available on the record. When returning an `DS.InvalidError` the store will attempt to normalize the error data returned from the server using the serializer's `extractErrors` method. @method handleResponse @param {Number} status @param {Object} headers @param {Object} payload @param {Object} requestData - the original request information @return {Object | DS.AdapterError} response */ handleResponse(status, headers, payload, requestData) { if (this.isSuccess(status, headers, payload)) { return payload; } else if (this.isInvalid(status, headers, payload)) { return new InvalidError(payload.errors); } let errors = this.normalizeErrorResponse(status, headers, payload); let detailedMessage = this.generatedDetailedMessage(status, headers, payload, requestData); return new AdapterError(errors, detailedMessage); }, /** Default `handleResponse` implementation uses this hook to decide if the response is a success. @method isSuccess @param {Number} status @param {Object} headers @param {Object} payload @return {Boolean} */ isSuccess(status, headers, payload) { return status >= 200 && status < 300 || status === 304; }, /** Default `handleResponse` implementation uses this hook to decide if the response is a an invalid error. @method isInvalid @param {Number} status @param {Object} headers @param {Object} payload @return {Boolean} */ isInvalid(status, headers, payload) { return status === 422; }, /** Takes a URL, an HTTP method and a hash of data, and makes an HTTP request. When the server responds with a payload, Ember Data will call into `extractSingle` or `extractArray` (depending on whether the original query was for one record or many records). By default, `ajax` method has the following behavior: * It sets the response `dataType` to `"json"` * If the HTTP method is not `"GET"`, it sets the `Content-Type` to be `application/json; charset=utf-8` * If the HTTP method is not `"GET"`, it stringifies the data passed in. The data is the serialized record in the case of a save. * Registers success and failure handlers. @method ajax @private @param {String} url @param {String} type The request type GET, POST, PUT, DELETE etc. @param {Object} options @return {Promise} promise */ ajax(url, type, options) { var adapter = this; var requestData = { url: url, method: type }; return new Ember.RSVP.Promise(function(resolve, reject) { var hash = adapter.ajaxOptions(url, type, options); hash.success = function(payload, textStatus, jqXHR) { let response = adapter.handleResponse( jqXHR.status, parseResponseHeaders(jqXHR.getAllResponseHeaders()), payload, requestData ); if (response instanceof AdapterError) { Ember.run.join(null, reject, response); } else { Ember.run.join(null, resolve, response); } }; hash.error = function(jqXHR, textStatus, errorThrown) { let error; if (errorThrown instanceof Error) { error = errorThrown; } else if (textStatus === 'timeout') { error = new TimeoutError(); } else if (textStatus === 'abort') { error = new AbortError(); } else { error = adapter.handleResponse( jqXHR.status, parseResponseHeaders(jqXHR.getAllResponseHeaders()), adapter.parseErrorResponse(jqXHR.responseText) || errorThrown, requestData ); } Ember.run.join(null, reject, error); }; Ember.$.ajax(hash); }, 'DS: RESTAdapter#ajax ' + type + ' to ' + url); }, /** @method ajaxOptions @private @param {String} url @param {String} type The request type GET, POST, PUT, DELETE etc. @param {Object} options @return {Object} */ ajaxOptions(url, type, options) { var hash = options || {}; hash.url = url; hash.type = type; hash.dataType = 'json'; hash.context = this; if (hash.data && type !== 'GET') { hash.contentType = 'application/json; charset=utf-8'; hash.data = JSON.stringify(hash.data); } var headers = get(this, 'headers'); if (headers !== undefined) { hash.beforeSend = function (xhr) { Object.keys(headers).forEach((key) => xhr.setRequestHeader(key, headers[key])); }; } return hash; }, /** @method parseErrorResponse @private @param {String} responseText @return {Object} */ parseErrorResponse(responseText) { var json = responseText; try { json = Ember.$.parseJSON(responseText); } catch (e) {} return json; }, /** @method normalizeErrorResponse @private @param {Number} status @param {Object} headers @param {Object} payload @return {Object} errors payload */ normalizeErrorResponse(status, headers, payload) { if (payload && typeof payload === 'object' && payload.errors) { return payload.errors; } else { return [ { status: `${status}`, title: "The backend responded with an error", detail: `${payload}` } ]; } }, /** Generates a detailed ("friendly") error message, with plenty of information for debugging (good luck!) @method generatedDetailedMessage @private @param {Number} status @param {Object} headers @param {Object} payload @return {Object} request information */ generatedDetailedMessage: function(status, headers, payload, requestData) { var shortenedPayload; var payloadContentType = headers["Content-Type"] || "Empty Content-Type"; if (payloadContentType === "text/html" && payload.length > 250) { shortenedPayload = "[Omitted Lengthy HTML]"; } else { shortenedPayload = payload; } var requestDescription = requestData.method + ' ' + requestData.url; var payloadDescription = 'Payload (' + payloadContentType + ')'; return ['Ember Data Request ' + requestDescription + ' returned a ' + status, payloadDescription, shortenedPayload].join('\n'); }, buildQuery(snapshot) { const { include } = snapshot; let query = {}; if (isEnabled('ds-finder-include')) { if (include) { query.include = include; } } return query; } }); function parseResponseHeaders(headerStr) { var headers = new EmptyObject(); if (!headerStr) { return headers; } var headerPairs = headerStr.split('\u000d\u000a'); for (var i = 0; i < headerPairs.length; i++) { var headerPair = headerPairs[i]; // Can't use split() here because it does the wrong thing // if the header value has the string ": " in it. var index = headerPair.indexOf('\u003a\u0020'); if (index > 0) { var key = headerPair.substring(0, index); var val = headerPair.substring(index + 2); headers[key] = val; } } return headers; } //From http://stackoverflow.com/questions/280634/endswith-in-javascript function endsWith(string, suffix) { if (typeof String.prototype.endsWith !== 'function') { return string.indexOf(suffix, string.length - suffix.length) !== -1; } else { return string.endsWith(suffix); } }
function SomeComponent (props) { // Create styles as if you're calling css and the class will be applied to the component return (<div css={` color: blue; font-size: 17 px; &:hover { color: green; } & .some-class { font-size: 20px; } `}> This will be blue until hovered. <div className="some-class"> This font size will be 20px </div> </div>) } const TestComponent = ({ children, ...props }) => ( <div css={`color: white; background: black`}> {children} </div> );
/* Tabulator v4.2.4 (c) Oliver Folkerd */ var Page = function Page(table) { this.table = table; //hold Tabulator object this.mode = "local"; this.progressiveLoad = false; this.size = 0; this.page = 1; this.count = 5; this.max = 1; this.displayIndex = 0; //index in display pipeline this.pageSizes = []; this.createElements(); }; Page.prototype.createElements = function () { var button; this.element = document.createElement("span"); this.element.classList.add("tabulator-paginator"); this.pagesElement = document.createElement("span"); this.pagesElement.classList.add("tabulator-pages"); button = document.createElement("button"); button.classList.add("tabulator-page"); button.setAttribute("type", "button"); button.setAttribute("role", "button"); button.setAttribute("aria-label", ""); button.setAttribute("title", ""); this.firstBut = button.cloneNode(true); this.firstBut.setAttribute("data-page", "first"); this.prevBut = button.cloneNode(true); this.prevBut.setAttribute("data-page", "prev"); this.nextBut = button.cloneNode(true); this.nextBut.setAttribute("data-page", "next"); this.lastBut = button.cloneNode(true); this.lastBut.setAttribute("data-page", "last"); if (this.table.options.paginationSizeSelector) { this.pageSizeSelect = document.createElement("select"); this.pageSizeSelect.classList.add("tabulator-page-size"); } }; Page.prototype.generatePageSizeSelectList = function () { var _this = this; var pageSizes = []; if (this.pageSizeSelect) { if (Array.isArray(this.table.options.paginationSizeSelector)) { pageSizes = this.table.options.paginationSizeSelector; this.pageSizes = pageSizes; if (this.pageSizes.indexOf(this.size) == -1) { pageSizes.unshift(this.size); } } else { if (this.pageSizes.indexOf(this.size) == -1) { pageSizes = []; for (var i = 1; i < 5; i++) { pageSizes.push(this.size * i); } this.pageSizes = pageSizes; } else { pageSizes = this.pageSizes; } } while (this.pageSizeSelect.firstChild) { this.pageSizeSelect.removeChild(this.pageSizeSelect.firstChild); }pageSizes.forEach(function (item) { var itemEl = document.createElement("option"); itemEl.value = item; itemEl.innerHTML = item; _this.pageSizeSelect.appendChild(itemEl); }); this.pageSizeSelect.value = this.size; } }; //setup pageination Page.prototype.initialize = function (hidden) { var self = this, pageSelectLabel; //update param names for (var key in self.table.options.paginationDataSent) { self.paginationDataSentNames[key] = self.table.options.paginationDataSent[key]; } for (var _key in self.table.options.paginationDataReceived) { self.paginationDataReceivedNames[_key] = self.table.options.paginationDataReceived[_key]; } //build pagination element //bind localizations self.table.modules.localize.bind("pagination|first", function (value) { self.firstBut.innerHTML = value; }); self.table.modules.localize.bind("pagination|first_title", function (value) { self.firstBut.setAttribute("aria-label", value); self.firstBut.setAttribute("title", value); }); self.table.modules.localize.bind("pagination|prev", function (value) { self.prevBut.innerHTML = value; }); self.table.modules.localize.bind("pagination|prev_title", function (value) { self.prevBut.setAttribute("aria-label", value); self.prevBut.setAttribute("title", value); }); self.table.modules.localize.bind("pagination|next", function (value) { self.nextBut.innerHTML = value; }); self.table.modules.localize.bind("pagination|next_title", function (value) { self.nextBut.setAttribute("aria-label", value); self.nextBut.setAttribute("title", value); }); self.table.modules.localize.bind("pagination|last", function (value) { self.lastBut.innerHTML = value; }); self.table.modules.localize.bind("pagination|last_title", function (value) { self.lastBut.setAttribute("aria-label", value); self.lastBut.setAttribute("title", value); }); //click bindings self.firstBut.addEventListener("click", function () { self.setPage(1); }); self.prevBut.addEventListener("click", function () { self.previousPage(); }); self.nextBut.addEventListener("click", function () { self.nextPage().then(function () {}).catch(function () {}); }); self.lastBut.addEventListener("click", function () { self.setPage(self.max); }); if (self.table.options.paginationElement) { self.element = self.table.options.paginationElement; } if (this.pageSizeSelect) { pageSelectLabel = document.createElement("label"); self.table.modules.localize.bind("pagination|page_size", function (value) { self.pageSizeSelect.setAttribute("aria-label", value); self.pageSizeSelect.setAttribute("title", value); pageSelectLabel.innerHTML = value; }); self.element.appendChild(pageSelectLabel); self.element.appendChild(self.pageSizeSelect); self.pageSizeSelect.addEventListener("change", function (e) { self.setPageSize(self.pageSizeSelect.value); self.setPage(1).then(function () {}).catch(function () {}); }); } //append to DOM self.element.appendChild(self.firstBut); self.element.appendChild(self.prevBut); self.element.appendChild(self.pagesElement); self.element.appendChild(self.nextBut); self.element.appendChild(self.lastBut); if (!self.table.options.paginationElement && !hidden) { self.table.footerManager.append(self.element, self); } //set default values self.mode = self.table.options.pagination; self.size = self.table.options.paginationSize || Math.floor(self.table.rowManager.getElement().clientHeight / 24); self.count = self.table.options.paginationButtonCount; self.generatePageSizeSelectList(); }; Page.prototype.initializeProgressive = function (mode) { this.initialize(true); this.mode = "progressive_" + mode; this.progressiveLoad = true; }; Page.prototype.setDisplayIndex = function (index) { this.displayIndex = index; }; Page.prototype.getDisplayIndex = function () { return this.displayIndex; }; //calculate maximum page from number of rows Page.prototype.setMaxRows = function (rowCount) { if (!rowCount) { this.max = 1; } else { this.max = Math.ceil(rowCount / this.size); } if (this.page > this.max) { this.page = this.max; } }; //reset to first page without triggering action Page.prototype.reset = function (force) { if (this.mode == "local" || force) { this.page = 1; } return true; }; //set the maxmum page Page.prototype.setMaxPage = function (max) { max = parseInt(max); this.max = max || 1; if (this.page > this.max) { this.page = this.max; this.trigger(); } }; //set current page number Page.prototype.setPage = function (page) { var _this2 = this; return new Promise(function (resolve, reject) { page = parseInt(page); if (page > 0 && page <= _this2.max) { _this2.page = page; _this2.trigger().then(function () { resolve(); }).catch(function () { reject(); }); } else { console.warn("Pagination Error - Requested page is out of range of 1 - " + _this2.max + ":", page); reject(); } }); }; Page.prototype.setPageToRow = function (row) { var _this3 = this; return new Promise(function (resolve, reject) { var rows = _this3.table.rowManager.getDisplayRows(_this3.displayIndex - 1); var index = rows.indexOf(row); if (index > -1) { var page = Math.ceil((index + 1) / _this3.size); _this3.setPage(page).then(function () { resolve(); }).catch(function () { reject(); }); } else { console.warn("Pagination Error - Requested row is not visible"); reject(); } }); }; Page.prototype.setPageSize = function (size) { size = parseInt(size); if (size > 0) { this.size = size; } if (this.pageSizeSelect) { // this.pageSizeSelect.value = size; this.generatePageSizeSelectList(); } }; //setup the pagination buttons Page.prototype._setPageButtons = function () { var self = this; var leftSize = Math.floor((this.count - 1) / 2); var rightSize = Math.ceil((this.count - 1) / 2); var min = this.max - this.page + leftSize + 1 < this.count ? this.max - this.count + 1 : Math.max(this.page - leftSize, 1); var max = this.page <= rightSize ? Math.min(this.count, this.max) : Math.min(this.page + rightSize, this.max); while (self.pagesElement.firstChild) { self.pagesElement.removeChild(self.pagesElement.firstChild); }if (self.page == 1) { self.firstBut.disabled = true; self.prevBut.disabled = true; } else { self.firstBut.disabled = false; self.prevBut.disabled = false; } if (self.page == self.max) { self.lastBut.disabled = true; self.nextBut.disabled = true; } else { self.lastBut.disabled = false; self.nextBut.disabled = false; } for (var i = min; i <= max; i++) { if (i > 0 && i <= self.max) { self.pagesElement.appendChild(self._generatePageButton(i)); } } this.footerRedraw(); }; Page.prototype._generatePageButton = function (page) { var self = this, button = document.createElement("button"); button.classList.add("tabulator-page"); if (page == self.page) { button.classList.add("active"); } button.setAttribute("type", "button"); button.setAttribute("role", "button"); button.setAttribute("aria-label", "Show Page " + page); button.setAttribute("title", "Show Page " + page); button.setAttribute("data-page", page); button.textContent = page; button.addEventListener("click", function (e) { self.setPage(page); }); return button; }; //previous page Page.prototype.previousPage = function () { var _this4 = this; return new Promise(function (resolve, reject) { if (_this4.page > 1) { _this4.page--; _this4.trigger().then(function () { resolve(); }).catch(function () { reject(); }); } else { console.warn("Pagination Error - Previous page would be less than page 1:", 0); reject(); } }); }; //next page Page.prototype.nextPage = function () { var _this5 = this; return new Promise(function (resolve, reject) { if (_this5.page < _this5.max) { _this5.page++; _this5.trigger().then(function () { resolve(); }).catch(function () { reject(); }); } else { if (!_this5.progressiveLoad) { console.warn("Pagination Error - Next page would be greater than maximum page of " + _this5.max + ":", _this5.max + 1); } reject(); } }); }; //return current page number Page.prototype.getPage = function () { return this.page; }; //return max page number Page.prototype.getPageMax = function () { return this.max; }; Page.prototype.getPageSize = function (size) { return this.size; }; Page.prototype.getMode = function () { return this.mode; }; //return appropriate rows for current page Page.prototype.getRows = function (data) { var output, start, end; if (this.mode == "local") { output = []; start = this.size * (this.page - 1); end = start + parseInt(this.size); this._setPageButtons(); for (var i = start; i < end; i++) { if (data[i]) { output.push(data[i]); } } return output; } else { this._setPageButtons(); return data.slice(0); } }; Page.prototype.trigger = function () { var _this6 = this; var left; return new Promise(function (resolve, reject) { switch (_this6.mode) { case "local": left = _this6.table.rowManager.scrollLeft; _this6.table.rowManager.refreshActiveData("page"); _this6.table.rowManager.scrollHorizontal(left); _this6.table.options.pageLoaded.call(_this6.table, _this6.getPage()); resolve(); break; case "remote": case "progressive_load": case "progressive_scroll": _this6.table.modules.ajax.blockActiveRequest(); _this6._getRemotePage().then(function () { resolve(); }).catch(function () { reject(); }); break; default: console.warn("Pagination Error - no such pagination mode:", _this6.mode); reject(); } }); }; Page.prototype._getRemotePage = function () { var _this7 = this; var self = this, oldParams, pageParams; return new Promise(function (resolve, reject) { if (!self.table.modExists("ajax", true)) { reject(); } //record old params and restore after request has been made oldParams = Tabulator.prototype.helpers.deepClone(self.table.modules.ajax.getParams() || {}); pageParams = self.table.modules.ajax.getParams(); //configure request params pageParams[_this7.paginationDataSentNames.page] = self.page; //set page size if defined if (_this7.size) { pageParams[_this7.paginationDataSentNames.size] = _this7.size; } //set sort data if defined if (_this7.table.options.ajaxSorting && _this7.table.modExists("sort")) { var sorters = self.table.modules.sort.getSort(); sorters.forEach(function (item) { delete item.column; }); pageParams[_this7.paginationDataSentNames.sorters] = sorters; } //set filter data if defined if (_this7.table.options.ajaxFiltering && _this7.table.modExists("filter")) { var filters = self.table.modules.filter.getFilters(true, true); pageParams[_this7.paginationDataSentNames.filters] = filters; } self.table.modules.ajax.setParams(pageParams); self.table.modules.ajax.sendRequest(_this7.progressiveLoad).then(function (data) { self._parseRemoteData(data); resolve(); }).catch(function (e) { reject(); }); self.table.modules.ajax.setParams(oldParams); }); }; Page.prototype._parseRemoteData = function (data) { var self = this, left, data, margin; if (typeof data[this.paginationDataReceivedNames.last_page] === "undefined") { console.warn("Remote Pagination Error - Server response missing '" + this.paginationDataReceivedNames.last_page + "' property"); } if (data[this.paginationDataReceivedNames.data]) { this.max = parseInt(data[this.paginationDataReceivedNames.last_page]) || 1; if (this.progressiveLoad) { switch (this.mode) { case "progressive_load": this.table.rowManager.addRows(data[this.paginationDataReceivedNames.data]); if (this.page < this.max) { setTimeout(function () { self.nextPage().then(function () {}).catch(function () {}); }, self.table.options.ajaxProgressiveLoadDelay); } break; case "progressive_scroll": data = this.table.rowManager.getData().concat(data[this.paginationDataReceivedNames.data]); this.table.rowManager.setData(data, true); margin = this.table.options.ajaxProgressiveLoadScrollMargin || this.table.rowManager.element.clientHeight * 2; if (self.table.rowManager.element.scrollHeight <= self.table.rowManager.element.clientHeight + margin) { self.nextPage().then(function () {}).catch(function () {}); } break; } } else { left = this.table.rowManager.scrollLeft; this.table.rowManager.setData(data[this.paginationDataReceivedNames.data]); this.table.rowManager.scrollHorizontal(left); this.table.columnManager.scrollHorizontal(left); this.table.options.pageLoaded.call(this.table, this.getPage()); } } else { console.warn("Remote Pagination Error - Server response missing '" + this.paginationDataReceivedNames.data + "' property"); } }; //handle the footer element being redrawn Page.prototype.footerRedraw = function () { var footer = this.table.footerManager.element; if (Math.ceil(footer.clientWidth) - footer.scrollWidth < 0) { this.pagesElement.style.display = 'none'; } else { this.pagesElement.style.display = ''; if (Math.ceil(footer.clientWidth) - footer.scrollWidth < 0) { this.pagesElement.style.display = 'none'; } } }; //set the paramter names for pagination requests Page.prototype.paginationDataSentNames = { "page": "page", "size": "size", "sorters": "sorters", // "sort_dir":"sort_dir", "filters": "filters" }; //set the property names for pagination responses Page.prototype.paginationDataReceivedNames = { "current_page": "current_page", "last_page": "last_page", "data": "data" }; Tabulator.prototype.registerModule("page", Page);
YUI.add('node-event-delegate', function (Y, NAME) { /** * Functionality to make the node a delegated event container * @module node * @submodule node-event-delegate */ /** * <p>Sets up a delegation listener for an event occurring inside the Node. * The delegated event will be verified against a supplied selector or * filtering function to test if the event references at least one node that * should trigger the subscription callback.</p> * * <p>Selector string filters will trigger the callback if the event originated * from a node that matches it or is contained in a node that matches it. * Function filters are called for each Node up the parent axis to the * subscribing container node, and receive at each level the Node and the event * object. The function should return true (or a truthy value) if that Node * should trigger the subscription callback. Note, it is possible for filters * to match multiple Nodes for a single event. In this case, the delegate * callback will be executed for each matching Node.</p> * * <p>For each matching Node, the callback will be executed with its 'this' * object set to the Node matched by the filter (unless a specific context was * provided during subscription), and the provided event's * <code>currentTarget</code> will also be set to the matching Node. The * containing Node from which the subscription was originally made can be * referenced as <code>e.container</code>. * * @method delegate * @param type {String} the event type to delegate * @param fn {Function} the callback function to execute. This function * will be provided the event object for the delegated event. * @param spec {String|Function} a selector that must match the target of the * event or a function to test target and its parents for a match * @param context {Object} optional argument that specifies what 'this' refers to. * @param args* {any} 0..n additional arguments to pass on to the callback function. * These arguments will be added after the event object. * @return {EventHandle} the detach handle * @for Node */ Y.Node.prototype.delegate = function(type) { var args = Y.Array(arguments, 0, true), index = (Y.Lang.isObject(type) && !Y.Lang.isArray(type)) ? 1 : 2; args.splice(index, 0, this._node); return Y.delegate.apply(Y, args); }; }, 'patched-v3.16.0', {"requires": ["node-base", "event-delegate"]});
'use strict'; var docsURL = 'http://bitcore.io/'; module.exports = [{ name: 'InvalidB58Char', message: 'Invalid Base58 character: {0} in {1}' }, { name: 'InvalidB58Checksum', message: 'Invalid Base58 checksum for {0}' }, { name: 'InvalidNetwork', message: 'Invalid version for network: got {0}' }, { name: 'InvalidState', message: 'Invalid state: {0}' }, { name: 'NotImplemented', message: 'Function {0} was not implemented yet' }, { name: 'InvalidNetworkArgument', message: 'Invalid network: must be "livenet" or "testnet", got {0}' }, { name: 'InvalidArgument', message: function() { return 'Invalid Argument' + (arguments[0] ? (': ' + arguments[0]) : '') + (arguments[1] ? (' Documentation: ' + docsURL + arguments[1]) : ''); } }, { name: 'AbstractMethodInvoked', message: 'Abstract Method Invocation: {0}' }, { name: 'InvalidArgumentType', message: function() { return 'Invalid Argument for ' + arguments[2] + ', expected ' + arguments[1] + ' but got ' + typeof arguments[0]; } }, { name: 'Unit', message: 'Internal Error on Unit {0}', errors: [{ 'name': 'UnknownCode', 'message': 'Unrecognized unit code: {0}' }, { 'name': 'InvalidRate', 'message': 'Invalid exchange rate: {0}' }] }, { name: 'Transaction', message: 'Internal Error on Transaction {0}', errors: [{ name: 'Input', message: 'Internal Error on Input {0}', errors: [{ name: 'MissingScript', message: 'Need a script to create an input' }, { name: 'UnsupportedScript', message: 'Unsupported input script type: {0}' }, { name: 'MissingPreviousOutput', message: 'No previous output information.' }] }, { name: 'NeedMoreInfo', message: '{0}' }, { name: 'InvalidSorting', message: 'The sorting function provided did not return the change output as one of the array elements' }, { name: 'InvalidOutputAmountSum', message: '{0}' }, { name: 'MissingSignatures', message: 'Some inputs have not been fully signed' }, { name: 'InvalidIndex', message: 'Invalid index: {0} is not between 0, {1}' }, { name: 'UnableToVerifySignature', message: 'Unable to verify signature: {0}' }, { name: 'DustOutputs', message: 'Dust amount detected in one output' }, { name: 'InvalidSatoshis', message: 'Output satoshis are invalid', }, { name: 'FeeError', message: 'Internal Error on Fee {0}', errors: [{ name: 'TooSmall', message: 'Fee is too small: {0}', }, { name: 'TooLarge', message: 'Fee is too large: {0}', }, { name: 'Different', message: 'Unspent value is different from specified fee: {0}', }] }, { name: 'ChangeAddressMissing', message: 'Change address is missing' }, { name: 'BlockHeightTooHigh', message: 'Block Height can be at most 2^32 -1' }, { name: 'NLockTimeOutOfRange', message: 'Block Height can only be between 0 and 499 999 999' }, { name: 'LockTimeTooEarly', message: 'Lock Time can\'t be earlier than UNIX date 500 000 000' }] }, { name: 'Script', message: 'Internal Error on Script {0}', errors: [{ name: 'UnrecognizedAddress', message: 'Expected argument {0} to be an address' }, { name: 'CantDeriveAddress', message: 'Can\'t derive address associated with script {0}, needs to be p2pkh in, p2pkh out, p2sh in, or p2sh out.' }, { name: 'InvalidBuffer', message: 'Invalid script buffer: can\'t parse valid script from given buffer {0}' }] }, { name: 'HDPrivateKey', message: 'Internal Error on HDPrivateKey {0}', errors: [{ name: 'InvalidDerivationArgument', message: 'Invalid derivation argument {0}, expected string, or number and boolean' }, { name: 'InvalidEntropyArgument', message: 'Invalid entropy: must be an hexa string or binary buffer, got {0}', errors: [{ name: 'TooMuchEntropy', message: 'Invalid entropy: more than 512 bits is non standard, got "{0}"' }, { name: 'NotEnoughEntropy', message: 'Invalid entropy: at least 128 bits needed, got "{0}"' }] }, { name: 'InvalidLength', message: 'Invalid length for xprivkey string in {0}' }, { name: 'InvalidPath', message: 'Invalid derivation path: {0}' }, { name: 'UnrecognizedArgument', message: 'Invalid argument: creating a HDPrivateKey requires a string, buffer, json or object, got "{0}"' }] }, { name: 'HDPublicKey', message: 'Internal Error on HDPublicKey {0}', errors: [{ name: 'ArgumentIsPrivateExtended', message: 'Argument is an extended private key: {0}' }, { name: 'InvalidDerivationArgument', message: 'Invalid derivation argument: got {0}' }, { name: 'InvalidLength', message: 'Invalid length for xpubkey: got "{0}"' }, { name: 'InvalidPath', message: 'Invalid derivation path, it should look like: "m/1/100", got "{0}"' }, { name: 'MustSupplyArgument', message: 'Must supply an argument to create a HDPublicKey' }, { name: 'UnrecognizedArgument', message: 'Invalid argument for creation, must be string, json, buffer, or object' }] }];
'use strict'; var SERVER_ROOT = 'http://localhost:3000'; servicesModule .factory('Events', function($http){ // helper function to extract data from response var getData = function(res) { return res.data; }; // ---- Export functions ---- var addOne = function(friendId, eventObj){ return $http.post(SERVER_ROOT + '/api/friends/' + friendId + '/events', eventObj) .then(getData); }; var getAllForFriend = function(friendId){ return $http.get(SERVER_ROOT + '/api/friends/' + friendId + '/events') .then(getData); } var getOne = function(eventId) { return $http.get(SERVER_ROOT + '/api/events/' + eventId) .then(getData); }; var updateOne = function(eventId, newEventObj){ return $http.put(SERVER_ROOT + '/api/events/' + eventId, newEventObj) .then(getData); } var deleteOne = function(eventId){ return $http.delete(SERVER_ROOT + '/api/events/' + eventId) .then(getData); } var prettifyDate = function(dateStr) { //date is of format TIMESTAMP from sql var dateObj = new Date(dateStr); var month = (dateObj.getUTCMonth()+1 % 12); var date = dateObj.getUTCDate(); var year = dateObj.getUTCFullYear(); var hours = (dateObj.getHours() + 4) % 24; // 24 hour clock, but then plus 4 for timezone var minutes = dateObj.getMinutes(); var monthString = month; var dateString = date; var yearString = year; var hoursString = (hours % 12 === 0 ? 12 : hours % 12).toString(); var minutesString = ((minutes <= 10) ? '0' : '') + minutes.toString(); var suffix = (hours <= 12) ? 'am' : 'pm'; console.log(hoursString + ":" + minutesString + suffix); return monthString + '/' + dateString + '/' + yearString + ', ' + hoursString + ":" + minutesString + suffix; }; return { addOne: addOne, getAllForFriend: getAllForFriend, getOne: getOne, updateOne: updateOne, deleteOne: deleteOne, prettifyDate: prettifyDate } });
/* Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'save', 'no', { toolbar: 'Lagre' });
var hasMap = typeof Map === 'function' && Map.prototype; var mapSizeDescriptor = Object.getOwnPropertyDescriptor && hasMap ? Object.getOwnPropertyDescriptor(Map.prototype, 'size') : null; var mapSize = hasMap && mapSizeDescriptor && typeof mapSizeDescriptor.get === 'function' ? mapSizeDescriptor.get : null; var mapForEach = hasMap && Map.prototype.forEach; var hasSet = typeof Set === 'function' && Set.prototype; var setSizeDescriptor = Object.getOwnPropertyDescriptor && hasSet ? Object.getOwnPropertyDescriptor(Set.prototype, 'size') : null; var setSize = hasSet && setSizeDescriptor && typeof setSizeDescriptor.get === 'function' ? setSizeDescriptor.get : null; var setForEach = hasSet && Set.prototype.forEach; var booleanValueOf = Boolean.prototype.valueOf; var objectToString = Object.prototype.toString; var inspectCustom = require('./util.inspect').custom; var inspectSymbol = (inspectCustom && isSymbol(inspectCustom)) ? inspectCustom : null; module.exports = function inspect_ (obj, opts, depth, seen) { if (typeof obj === 'undefined') { return 'undefined'; } if (obj === null) { return 'null'; } if (typeof obj === 'boolean') { return obj ? 'true' : 'false'; } if (typeof obj === 'string') { return inspectString(obj); } if (typeof obj === 'number') { if (obj === 0) { return Infinity / obj > 0 ? '0' : '-0'; } return String(obj); } if (!opts) opts = {}; var maxDepth = typeof opts.depth === 'undefined' ? 5 : opts.depth; if (typeof depth === 'undefined') depth = 0; if (depth >= maxDepth && maxDepth > 0 && typeof obj === 'object') { return '[Object]'; } if (typeof seen === 'undefined') seen = []; else if (indexOf(seen, obj) >= 0) { return '[Circular]'; } function inspect (value, from) { if (from) { seen = seen.slice(); seen.push(from); } return inspect_(value, opts, depth + 1, seen); } if (typeof obj === 'function') { var name = nameOf(obj); return '[Function' + (name ? ': ' + name : '') + ']'; } if (isSymbol(obj)) { var symString = Symbol.prototype.toString.call(obj); return typeof obj === 'object' ? markBoxed(symString) : symString; } if (isElement(obj)) { var s = '<' + String(obj.nodeName).toLowerCase(); var attrs = obj.attributes || []; for (var i = 0; i < attrs.length; i++) { s += ' ' + attrs[i].name + '="' + quote(attrs[i].value) + '"'; } s += '>'; if (obj.childNodes && obj.childNodes.length) s += '...'; s += '</' + String(obj.nodeName).toLowerCase() + '>'; return s; } if (isArray(obj)) { if (obj.length === 0) return '[]'; return '[ ' + arrObjKeys(obj, inspect).join(', ') + ' ]'; } if (isError(obj)) { var parts = arrObjKeys(obj, inspect); if (parts.length === 0) return '[' + String(obj) + ']'; return '{ [' + String(obj) + '] ' + parts.join(', ') + ' }'; } if (typeof obj === 'object') { if (inspectSymbol && typeof obj[inspectSymbol] === 'function') { return obj[inspectSymbol](); } else if (typeof obj.inspect === 'function') { return obj.inspect(); } } if (isMap(obj)) { var parts = []; mapForEach.call(obj, function (value, key) { parts.push(inspect(key, obj) + ' => ' + inspect(value, obj)); }); return collectionOf('Map', mapSize.call(obj), parts); } if (isSet(obj)) { var parts = []; setForEach.call(obj, function (value ) { parts.push(inspect(value, obj)); }); return collectionOf('Set', setSize.call(obj), parts); } if (isNumber(obj)) { return markBoxed(inspect(Number(obj))); } if (isBoolean(obj)) { return markBoxed(booleanValueOf.call(obj)); } if (isString(obj)) { return markBoxed(inspect(String(obj))); } if (!isDate(obj) && !isRegExp(obj)) { var xs = arrObjKeys(obj, inspect); if (xs.length === 0) return '{}'; return '{ ' + xs.join(', ') + ' }'; } return String(obj); }; function quote (s) { return String(s).replace(/"/g, '&quot;'); } function isArray (obj) { return toStr(obj) === '[object Array]' } function isDate (obj) { return toStr(obj) === '[object Date]' } function isRegExp (obj) { return toStr(obj) === '[object RegExp]' } function isError (obj) { return toStr(obj) === '[object Error]' } function isSymbol (obj) { return toStr(obj) === '[object Symbol]' } function isString (obj) { return toStr(obj) === '[object String]' } function isNumber (obj) { return toStr(obj) === '[object Number]' } function isBoolean (obj) { return toStr(obj) === '[object Boolean]' } var hasOwn = Object.prototype.hasOwnProperty || function (key) { return key in this; }; function has (obj, key) { return hasOwn.call(obj, key); } function toStr (obj) { return objectToString.call(obj); } function nameOf (f) { if (f.name) return f.name; var m = String(f).match(/^function\s*([\w$]+)/); if (m) return m[1]; } function indexOf (xs, x) { if (xs.indexOf) return xs.indexOf(x); for (var i = 0, l = xs.length; i < l; i++) { if (xs[i] === x) return i; } return -1; } function isMap (x) { if (!mapSize) { return false; } try { mapSize.call(x); try { setSize.call(x); } catch (s) { return true; } return x instanceof Map; // core-js workaround, pre-v2.5.0 } catch (e) {} return false; } function isSet (x) { if (!setSize) { return false; } try { setSize.call(x); try { mapSize.call(x); } catch (m) { return true; } return x instanceof Set; // core-js workaround, pre-v2.5.0 } catch (e) {} return false; } function isElement (x) { if (!x || typeof x !== 'object') return false; if (typeof HTMLElement !== 'undefined' && x instanceof HTMLElement) { return true; } return typeof x.nodeName === 'string' && typeof x.getAttribute === 'function' ; } function inspectString (str) { var s = str.replace(/(['\\])/g, '\\$1').replace(/[\x00-\x1f]/g, lowbyte); return "'" + s + "'"; } function lowbyte (c) { var n = c.charCodeAt(0); var x = { 8: 'b', 9: 't', 10: 'n', 12: 'f', 13: 'r' }[n]; if (x) return '\\' + x; return '\\x' + (n < 0x10 ? '0' : '') + n.toString(16); } function markBoxed (str) { return 'Object(' + str + ')'; } function collectionOf (type, size, entries) { return type + ' (' + size + ') {' + entries.join(', ') + '}'; } function arrObjKeys (obj, inspect) { var isArr = isArray(obj); var xs = []; if (isArr) { xs.length = obj.length; for (var i = 0; i < obj.length; i++) { xs[i] = has(obj, i) ? inspect(obj[i], obj) : ''; } } for (var key in obj) { if (!has(obj, key)) continue; if (isArr && String(Number(key)) === key && key < obj.length) continue; if (/[^\w$]/.test(key)) { xs.push(inspect(key, obj) + ': ' + inspect(obj[key], obj)); } else { xs.push(key + ': ' + inspect(obj[key], obj)); } } return xs; }
(function(window,document,Laya){ var __un=Laya.un,__uns=Laya.uns,__static=Laya.static,__class=Laya.class,__getset=Laya.getset,__newvec=Laya.__newvec; /** *... *@author dongketao */ //class PathFinding.core.DiagonalMovement var DiagonalMovement=(function(){ function DiagonalMovement(){} __class(DiagonalMovement,'PathFinding.core.DiagonalMovement'); DiagonalMovement.Always=1; DiagonalMovement.Never=2; DiagonalMovement.IfAtMostOneObstacle=3; DiagonalMovement.OnlyWhenNoObstacles=4; return DiagonalMovement; })() /** *... *@author dongketao */ //class PathFinding.core.Grid var Grid=(function(){ function Grid(width_or_matrix,height,matrix){ this.width=0; this.height=0; this.nodes=null; var width=0; if ((typeof width_or_matrix=='number')){ width=width_or_matrix; } else{ height=width_or_matrix.length; width=width_or_matrix[0].length; matrix=width_or_matrix; } this.width=width; this.height=height; this.nodes=this._buildNodes(width,height,matrix); } __class(Grid,'PathFinding.core.Grid'); var __proto=Grid.prototype; /** *Build and return the nodes. *@private *@param {number}width *@param {number}height *@param {Array<Array<number|boolean>>}[matrix]-A 0-1 matrix representing *the walkable status of the nodes. *@see Grid */ __proto._buildNodes=function(width,height,matrix){ var i=0,j=0,nodes=[]; for (i=0;i < height;++i){ nodes[i]=[]; for (j=0;j < width;++j){ nodes[i][j]=new Node$1(j,i); } } if (matrix==null){ return nodes; } if (matrix.length !=height || matrix[0].length !=width){ throw new Error('Matrix size does not fit'); } for (i=0;i < height;++i){ for (j=0;j < width;++j){ if (matrix[i][j]){ nodes[i][j].walkable=false; } } } return nodes; } __proto.getNodeAt=function(x,y){ return this.nodes[y][x]; } /** *Determine whether the node at the given position is walkable. *(Also returns false if the position is outside the grid.) *@param {number}x-The x coordinate of the node. *@param {number}y-The y coordinate of the node. *@return {boolean}-The walkability of the node. */ __proto.isWalkableAt=function(x,y){ return this.isInside(x,y)&& this.nodes[y][x].walkable; } /** *Determine whether the position is inside the grid. *XXX:`grid.isInside(x,y)` is wierd to read. *It should be `(x,y)is inside grid`,but I failed to find a better *name for this method. *@param {number}x *@param {number}y *@return {boolean} */ __proto.isInside=function(x,y){ return (x >=0 && x < this.width)&& (y >=0 && y < this.height); } /** *Set whether the node on the given position is walkable. *NOTE:throws exception if the coordinate is not inside the grid. *@param {number}x-The x coordinate of the node. *@param {number}y-The y coordinate of the node. *@param {boolean}walkable-Whether the position is walkable. */ __proto.setWalkableAt=function(x,y,walkable){ this.nodes[y][x].walkable=walkable; } /** *Get the neighbors of the given node. * *offsets diagonalOffsets: *+---+---+---++---+---+---+ *| | 0 | | | 0 | | 1 | *+---+---+---++---+---+---+ *| 3 | | 1 | | | | | *+---+---+---++---+---+---+ *| | 2 | | | 3 | | 2 | *+---+---+---++---+---+---+ * *When allowDiagonal is true,if offsets[i] is valid,then *diagonalOffsets[i] and *diagonalOffsets[(i+1)% 4] is valid. *@param {Node}node *@param {diagonalMovement}diagonalMovement */ __proto.getNeighbors=function(node,diagonalMovement){ var x=node.x,y=node.y,neighbors=[],s0=false,d0=false,s1=false,d1=false,s2=false,d2=false,s3=false,d3=false,nodes=this.nodes; if (this.isWalkableAt(x,y-1)){ neighbors.push(nodes[y-1][x]); s0=true; } if (this.isWalkableAt(x+1,y)){ neighbors.push(nodes[y][x+1]); s1=true; } if (this.isWalkableAt(x,y+1)){ neighbors.push(nodes[y+1][x]); s2=true; } if (this.isWalkableAt(x-1,y)){ neighbors.push(nodes[y][x-1]); s3=true; } if (diagonalMovement==DiagonalMovement.Never){ return neighbors; } if (diagonalMovement==DiagonalMovement.OnlyWhenNoObstacles){ d0=s3 && s0; d1=s0 && s1; d2=s1 && s2; d3=s2 && s3; } else if (diagonalMovement==DiagonalMovement.IfAtMostOneObstacle){ d0=s3 || s0; d1=s0 || s1; d2=s1 || s2; d3=s2 || s3; } else if (diagonalMovement==DiagonalMovement.Always){ d0=true; d1=true; d2=true; d3=true; } else{ throw new Error('Incorrect value of diagonalMovement'); } if (d0 && this.isWalkableAt(x-1,y-1)){ neighbors.push(nodes[y-1][x-1]); } if (d1 && this.isWalkableAt(x+1,y-1)){ neighbors.push(nodes[y-1][x+1]); } if (d2 && this.isWalkableAt(x+1,y+1)){ neighbors.push(nodes[y+1][x+1]); } if (d3 && this.isWalkableAt(x-1,y+1)){ neighbors.push(nodes[y+1][x-1]); } return neighbors; } /** *Get a clone of this grid. *@return {Grid}Cloned grid. */ __proto.clone=function(){ var i=0,j=0, width=this.width,height=this.height,thisNodes=this.nodes, newGrid=new Grid(width,height),newNodes=[]; for (i=0;i < height;++i){ newNodes[i]=[]; for (j=0;j < width;++j){ newNodes[i][j]=new Node$1(j,i,thisNodes[i][j].walkable); } } newGrid.nodes=newNodes; return newGrid; } __proto.reset=function(){ var _node; for (var i=0;i < this.height;++i){ for (var j=0;j < this.width;++j){ _node=this.nodes[i][j]; _node.g=0; _node.f=0; _node.h=0; _node.by=0; _node.parent=null; _node.opened=null; _node.closed=null; _node.tested=null; } } } Grid.createGridFromAStarMap=function(texture){ var textureWidth=texture.width; var textureHeight=texture.height; var pixelsInfo=texture.getPixels(); var aStarArr=[]; var index=0; for (var w=0;w < textureWidth;w++){ var colaStarArr=aStarArr[w]=[]; for (var h=0;h < textureHeight;h++){ var r=pixelsInfo[index++]; var g=pixelsInfo[index++]; var b=pixelsInfo[index++]; var a=pixelsInfo[index++]; if (r==255 && g==255 && b==255 && a==255) colaStarArr[h]=1; else { colaStarArr[h]=0; } } }; var gird=new Grid(textureWidth,textureHeight,aStarArr); return gird; } return Grid; })() /** *... *@author dongketao */ //class PathFinding.core.Heuristic var Heuristic=(function(){ function Heuristic(){} __class(Heuristic,'PathFinding.core.Heuristic'); Heuristic.manhattan=function(dx,dy){ return dx+dy; } Heuristic.euclidean=function(dx,dy){ return Math.sqrt(dx *dx+dy *dy); } Heuristic.octile=function(dx,dy){ var F=Math.SQRT2-1; return (dx < dy)? F *dx+dy :F *dy+dx; } Heuristic.chebyshev=function(dx,dy){ return Math.max(dx,dy); } return Heuristic; })() /** *... *@author dongketao */ //class PathFinding.core.Node var Node$1=(function(){ function Node(x,y,walkable){ this.x=0; this.y=0; this.g=0; this.f=0; this.h=0; this.by=0; this.parent=null; this.opened=null; this.closed=null; this.tested=null; this.retainCount=null; this.walkable=false; (walkable===void 0)&& (walkable=true); this.x=x; this.y=y; this.walkable=walkable; } __class(Node,'PathFinding.core.Node',null,'Node$1'); return Node; })() /** *... *@author dongketao */ //class PathFinding.core.Util var Util=(function(){ function Util(){} __class(Util,'PathFinding.core.Util'); Util.backtrace=function(node){ var path=[[node.x,node.y]]; while (node.parent){ node=node.parent; path.push([node.x,node.y]); } return path.reverse(); } Util.biBacktrace=function(nodeA,nodeB){ var pathA=Util.backtrace(nodeA),pathB=Util.backtrace(nodeB); return pathA.concat(pathB.reverse()); } Util.pathLength=function(path){ var i=0,sum=0,a=0,b=0,dx=0,dy=0; for (i=1;i < path.length;++i){ a=path[i-1]; b=path[i]; dx=a[0]-b[0]; dy=a[1]-b[1]; sum+=Math.sqrt(dx *dx+dy *dy); } return sum; } Util.interpolate=function(x0,y0,x1,y1){ var abs=Math.abs,line=[],sx=0,sy=0,dx=0,dy=0,err=0,e2=0; dx=abs(x1-x0); dy=abs(y1-y0); sx=(x0 < x1)? 1 :-1; sy=(y0 < y1)? 1 :-1; err=dx-dy; while (true){ line.push([x0,y0]); if (x0==x1 && y0==y1){ break ; } e2=2 *err; if (e2 >-dy){ err=err-dy; x0=x0+sx; } if (e2 < dx){ err=err+dx; y0=y0+sy; } } return line; } Util.expandPath=function(path){ var expanded=[],len=path.length,coord0,coord1,interpolated,interpolatedLen=0,i=0,j=0; if (len < 2){ return expanded; } for (i=0;i < len-1;++i){ coord0=path[i]; coord1=path[i+1]; interpolated=Util.interpolate(coord0[0],coord0[1],coord1[0],coord1[1]); interpolatedLen=interpolated.length; for (j=0;j < interpolatedLen-1;++j){ expanded.push(interpolated[j]); } } expanded.push(path[len-1]); return expanded; } Util.smoothenPath=function(grid,path){ var len=path.length,x0=path[0][0], y0=path[0][1], x1=path[len-1][0], y1=path[len-1][1], sx=0,sy=0, ex=0,ey=0, newPath,i=0,j=0,coord,line,testCoord,blocked=false,lastValidCoord; sx=x0; sy=y0; newPath=[[sx,sy]]; for (i=2;i < len;++i){ coord=path[i]; ex=coord[0]; ey=coord[1]; line=Util.interpolate(sx,sy,ex,ey); blocked=false; for (j=1;j < line.length;++j){ testCoord=line[j]; if (!grid.isWalkableAt(testCoord[0],testCoord[1])){ blocked=true; break ; } } if (blocked){ lastValidCoord=path[i-1]; newPath.push(lastValidCoord); sx=lastValidCoord[0]; sy=lastValidCoord[1]; } } newPath.push([x1,y1]); return newPath; } Util.compressPath=function(path){ if (path.length < 3){ return path; }; var compressed=[],sx=path[0][0], sy=path[0][1], px=path[1][0], py=path[1][1], dx=px-sx, dy=py-sy, lx=0,ly=0,ldx=0,ldy=0,sq=NaN,i=0; sq=Math.sqrt(dx *dx+dy *dy); dx /=sq; dy /=sq; compressed.push([sx,sy]); for (i=2;i < path.length;i++){ lx=px; ly=py; ldx=dx; ldy=dy; px=path[i][0]; py=path[i][1]; dx=px-lx; dy=py-ly; sq=Math.sqrt(dx *dx+dy *dy); dx /=sq; dy /=sq; if (dx!==ldx || dy!==ldy){ compressed.push([lx,ly]); } } compressed.push([px,py]); return compressed; } return Util; })() /** *... *@author dongketao */ //class PathFinding.finders.AStarFinder var AStarFinder=(function(){ function AStarFinder(opt){ this.allowDiagonal=false; this.dontCrossCorners=false; this.heuristic=null; this.weight=0; this.diagonalMovement=0; opt=opt || {}; this.allowDiagonal=opt.allowDiagonal; this.dontCrossCorners=opt.dontCrossCorners; this.heuristic=opt.heuristic || Heuristic.manhattan; this.weight=opt.weight || 1; this.diagonalMovement=opt.diagonalMovement; if (!this.diagonalMovement){ if (!this.allowDiagonal){ this.diagonalMovement=DiagonalMovement.Never; } else{ if (this.dontCrossCorners){ this.diagonalMovement=DiagonalMovement.OnlyWhenNoObstacles; } else{ this.diagonalMovement=DiagonalMovement.IfAtMostOneObstacle; } } } if (this.diagonalMovement===DiagonalMovement.Never){ this.heuristic=opt.heuristic || Heuristic.manhattan; } else{ this.heuristic=opt.heuristic || Heuristic.octile; } } __class(AStarFinder,'PathFinding.finders.AStarFinder'); var __proto=AStarFinder.prototype; /** *Find and return the the path. *@return {Array<Array<number>>}The path,including both start and *end positions. */ __proto.findPath=function(startX,startY,endX,endY,grid){ var openList=new Heap(function(nodeA,nodeB){ return nodeA.f-nodeB.f; }),startNode=grid.getNodeAt(startX,startY),endNode=grid.getNodeAt(endX,endY),heuristic=this.heuristic,diagonalMovement=this.diagonalMovement,weight=this.weight,abs=Math.abs,SQRT2=Math.SQRT2,node,neighbors,neighbor,i=0,l=0,x=0,y=0,ng=0; startNode.g=0; startNode.f=0; openList.push(startNode); startNode.opened=true; while (!openList.empty()){ node=openList.pop(); node.closed=true; if (node===endNode){ return Util.backtrace(endNode); } neighbors=grid.getNeighbors(node,diagonalMovement); for (i=0,l=neighbors.length;i < l;++i){ neighbor=neighbors[i]; if (neighbor.closed){ continue ; } x=neighbor.x; y=neighbor.y; ng=node.g+((x-node.x===0 || y-node.y===0)? 1 :SQRT2); if (!neighbor.opened || ng < neighbor.g){ neighbor.g=ng; neighbor.h=neighbor.h || weight *heuristic(abs(x-endX),abs(y-endY)); neighbor.f=neighbor.g+neighbor.h; neighbor.parent=node; if (!neighbor.opened){ openList.push(neighbor); neighbor.opened=true; } else{ openList.updateItem(neighbor); } } } } return []; } return AStarFinder; })() /** *... *@author ... */ //class PathFinding.finders.BiAStarFinder var BiAStarFinder=(function(){ function BiAStarFinder(opt){ this.allowDiagonal=false; this.dontCrossCorners=false; this.diagonalMovement=0; this.heuristic=null; this.weight=0; opt=opt || {}; this.allowDiagonal=opt.allowDiagonal; this.dontCrossCorners=opt.dontCrossCorners; this.diagonalMovement=opt.diagonalMovement; this.heuristic=opt.heuristic || Heuristic.manhattan; this.weight=opt.weight || 1; if (!this.diagonalMovement){ if (!this.allowDiagonal){ this.diagonalMovement=DiagonalMovement.Never; } else{ if (this.dontCrossCorners){ this.diagonalMovement=DiagonalMovement.OnlyWhenNoObstacles; } else{ this.diagonalMovement=DiagonalMovement.IfAtMostOneObstacle; } } } if (this.diagonalMovement==DiagonalMovement.Never){ this.heuristic=opt.heuristic || Heuristic.manhattan; } else{ this.heuristic=opt.heuristic || Heuristic.octile; } } __class(BiAStarFinder,'PathFinding.finders.BiAStarFinder'); var __proto=BiAStarFinder.prototype; /** *Find and return the the path. *@return {Array<Array<number>>}The path,including both start and *end positions. */ __proto.findPath=function(startX,startY,endX,endY,grid){ var cmp=function (nodeA,nodeB){ return nodeA.f-nodeB.f; }; var startOpenList=new Heap(cmp),endOpenList=new Heap(cmp),startNode=grid.getNodeAt(startX,startY),endNode=grid.getNodeAt(endX,endY),heuristic=this.heuristic,diagonalMovement=this.diagonalMovement,weight=this.weight,abs=Math.abs,SQRT2=Math.SQRT2,node,neighbors,neighbor,i=0,l=0,x=0,y=0,ng=0,BY_START=1,BY_END=2; startNode.g=0; startNode.f=0; startOpenList.push(startNode); startNode.opened=BY_START; endNode.g=0; endNode.f=0; endOpenList.push(endNode); endNode.opened=BY_END; while (!startOpenList.empty()&& !endOpenList.empty()){ node=startOpenList.pop(); node.closed=true; neighbors=grid.getNeighbors(node,diagonalMovement); for (i=0,l=neighbors.length;i < l;++i){ neighbor=neighbors[i]; if (neighbor.closed){ continue ; } if (neighbor.opened===BY_END){ return Util.biBacktrace(node,neighbor); } x=neighbor.x; y=neighbor.y; ng=node.g+((x-node.x===0 || y-node.y===0)? 1 :SQRT2); if (!neighbor.opened || ng < neighbor.g){ neighbor.g=ng; neighbor.h=neighbor.h || weight *heuristic(abs(x-endX),abs(y-endY)); neighbor.f=neighbor.g+neighbor.h; neighbor.parent=node; if (!neighbor.opened){ startOpenList.push(neighbor); neighbor.opened=BY_START; } else{ startOpenList.updateItem(neighbor); } } } node=endOpenList.pop(); node.closed=true; neighbors=grid.getNeighbors(node,diagonalMovement); for (i=0,l=neighbors.length;i < l;++i){ neighbor=neighbors[i]; if (neighbor.closed){ continue ; } if (neighbor.opened===BY_START){ return Util.biBacktrace(neighbor,node); } x=neighbor.x; y=neighbor.y; ng=node.g+((x-node.x===0 || y-node.y===0)? 1 :SQRT2); if (!neighbor.opened || ng < neighbor.g){ neighbor.g=ng; neighbor.h=neighbor.h || weight *heuristic(abs(x-startX),abs(y-startY)); neighbor.f=neighbor.g+neighbor.h; neighbor.parent=node; if (!neighbor.opened){ endOpenList.push(neighbor); neighbor.opened=BY_END; } else{ endOpenList.updateItem(neighbor); } } } } return []; } return BiAStarFinder; })() /** *... *@author dongketao */ //class PathFinding.finders.BiBreadthFirstFinder var BiBreadthFirstFinder=(function(){ function BiBreadthFirstFinder(opt){ this.allowDiagonal=false; this.dontCrossCorners=false; this.heuristic=null; this.weight=0; this.diagonalMovement=0; opt=opt || {}; this.allowDiagonal=opt.allowDiagonal; this.dontCrossCorners=opt.dontCrossCorners; this.diagonalMovement=opt.diagonalMovement; if (!this.diagonalMovement){ if (!this.allowDiagonal){ this.diagonalMovement=DiagonalMovement.Never; } else{ if (this.dontCrossCorners){ this.diagonalMovement=DiagonalMovement.OnlyWhenNoObstacles; } else{ this.diagonalMovement=DiagonalMovement.IfAtMostOneObstacle; } } } } __class(BiBreadthFirstFinder,'PathFinding.finders.BiBreadthFirstFinder'); var __proto=BiBreadthFirstFinder.prototype; /** *Find and return the the path. *@return {Array<Array<number>>}The path,including both start and *end positions. */ __proto.findPath=function(startX,startY,endX,endY,grid){ var startNode=grid.getNodeAt(startX,startY),endNode=grid.getNodeAt(endX,endY),startOpenList=[],endOpenList=[],neighbors,neighbor,node,diagonalMovement=this.diagonalMovement,BY_START=0,BY_END=1,i=0,l=0; startOpenList.push(startNode); startNode.opened=true; startNode.by=BY_START; endOpenList.push(endNode); endNode.opened=true; endNode.by=BY_END; while (startOpenList.length && endOpenList.length){ node=startOpenList.shift(); node.closed=true; neighbors=grid.getNeighbors(node,diagonalMovement); for (i=0,l=neighbors.length;i < l;++i){ neighbor=neighbors[i]; if (neighbor.closed){ continue ; } if (neighbor.opened){ if (neighbor.by===BY_END){ return Util.biBacktrace(node,neighbor); } continue ; } startOpenList.push(neighbor); neighbor.parent=node; neighbor.opened=true; neighbor.by=BY_START; } node=endOpenList.shift(); node.closed=true; neighbors=grid.getNeighbors(node,diagonalMovement); for (i=0,l=neighbors.length;i < l;++i){ neighbor=neighbors[i]; if (neighbor.closed){ continue ; } if (neighbor.opened){ if (neighbor.by===BY_START){ return Util.biBacktrace(neighbor,node); } continue ; } endOpenList.push(neighbor); neighbor.parent=node; neighbor.opened=true; neighbor.by=BY_END; } } return []; } return BiBreadthFirstFinder; })() /** *... *@author dongketao */ //class PathFinding.finders.BreadthFirstFinder var BreadthFirstFinder=(function(){ function BreadthFirstFinder(opt){ this.allowDiagonal=false; this.dontCrossCorners=false; this.heuristic=null; this.weight=0; this.diagonalMovement=0; opt=opt || {}; this.allowDiagonal=opt.allowDiagonal; this.dontCrossCorners=opt.dontCrossCorners; this.diagonalMovement=opt.diagonalMovement; if (!this.diagonalMovement){ if (!this.allowDiagonal){ this.diagonalMovement=DiagonalMovement.Never; } else{ if (this.dontCrossCorners){ this.diagonalMovement=DiagonalMovement.OnlyWhenNoObstacles; } else{ this.diagonalMovement=DiagonalMovement.IfAtMostOneObstacle; } } } } __class(BreadthFirstFinder,'PathFinding.finders.BreadthFirstFinder'); var __proto=BreadthFirstFinder.prototype; /** *Find and return the the path. *@return {Array<Array<number>>}The path,including both start and *end positions. */ __proto.findPath=function(startX,startY,endX,endY,grid){ var openList=[],diagonalMovement=this.diagonalMovement,startNode=grid.getNodeAt(startX,startY),endNode=grid.getNodeAt(endX,endY),neighbors,neighbor,node,i=0,l=0; openList.push(startNode); startNode.opened=true; while (openList.length){ node=openList.shift(); node.closed=true; if (node===endNode){ return Util.backtrace(endNode); } neighbors=grid.getNeighbors(node,diagonalMovement); for (i=0,l=neighbors.length;i < l;++i){ neighbor=neighbors[i]; if (neighbor.closed || neighbor.opened){ continue ; } openList.push(neighbor); neighbor.opened=true; neighbor.parent=node; } } return []; } return BreadthFirstFinder; })() /** *... *@author dongketao */ //class PathFinding.finders.IDAStarFinder var IDAStarFinder=(function(){ function IDAStarFinder(opt){ this.allowDiagonal=false; this.dontCrossCorners=false; this.heuristic=null; this.weight=0; this.diagonalMovement=0; this.trackRecursion=false; this.timeLimit=NaN; opt=opt || {}; this.allowDiagonal=opt.allowDiagonal; this.dontCrossCorners=opt.dontCrossCorners; this.diagonalMovement=opt.diagonalMovement; this.heuristic=opt.heuristic || Heuristic.manhattan; this.weight=opt.weight || 1; this.trackRecursion=opt.trackRecursion || false; this.timeLimit=opt.timeLimit || Infinity; if (!this.diagonalMovement){ if (!this.allowDiagonal){ this.diagonalMovement=DiagonalMovement.Never; } else{ if (this.dontCrossCorners){ this.diagonalMovement=DiagonalMovement.OnlyWhenNoObstacles; } else{ this.diagonalMovement=DiagonalMovement.IfAtMostOneObstacle; } } } if (this.diagonalMovement===DiagonalMovement.Never){ this.heuristic=opt.heuristic || Heuristic.manhattan; } else{ this.heuristic=opt.heuristic || Heuristic.octile; } } __class(IDAStarFinder,'PathFinding.finders.IDAStarFinder'); var __proto=IDAStarFinder.prototype; /** *Find and return the the path. When an empty array is returned,either *no path is possible,or the maximum execution time is reached. * *@return {Array<Array<number>>}The path,including both start and *end positions. */ __proto.findPath=function(startX,startY,endX,endY,grid){ var _$this=this; var nodesVisited=0; var startTime=new Date().getTime(); var h=function (a,b){ return _$this.heuristic(Math.abs(b.x-a.x),Math.abs(b.y-a.y)); }; var cost=function (a,b){ return (a.x===b.x || a.y===b.y)? 1 :Math.SQRT2; }; var search=function (node,g,cutoff,route,depth){ nodesVisited++; if (_$this.timeLimit > 0 && new Date().getTime()-startTime > _$this.timeLimit *1000){ return Infinity; }; var f=g+h(node,end)*_$this.weight; if (f > cutoff){ return f; } if (node==end){ route[depth]=[node.x,node.y]; return node; }; var min=0,t=0,k=0,neighbour; var neighbours=grid.getNeighbors(node,_$this.diagonalMovement); for (k=0,min=Infinity;neighbour=neighbours[k];++k){ if (_$this.trackRecursion){ neighbour.retainCount=neighbour.retainCount+1 || 1; if (neighbour.tested !=true){ neighbour.tested=true; } } t=search(neighbour,g+cost(node,neighbour),cutoff,route,depth+1); if ((t instanceof PathFinding.core.Node )){ route[depth]=[node.x,node.y]; return t; } if (_$this.trackRecursion && (--neighbour.retainCount)===0){ neighbour.tested=false; } if (t < min){ min=t; } } return min; }; var start=grid.getNodeAt(startX,startY); var end=grid.getNodeAt(endX,endY); var cutOff=h(start,end); var j=0,route,t=0; for (j=0;true;++j){ route=[]; t=search(start,0,cutOff,route,0); if (t==Infinity){ route=[]; break ; } if ((t instanceof PathFinding.core.Node )){ break ; } cutOff=t; } return route; } return IDAStarFinder; })() /** *... *@author ... */ //class PathFinding.finders.JumpPointFinderBase var JumpPointFinderBase=(function(){ function JumpPointFinderBase(opt){ this.grid=null; this.openList=null; this.startNode=null; this.endNode=null; this.heuristic=null; this.trackJumpRecursion=false; opt=opt || {}; this.heuristic=opt.heuristic || Heuristic.manhattan; this.trackJumpRecursion=opt.trackJumpRecursion || false; } __class(JumpPointFinderBase,'PathFinding.finders.JumpPointFinderBase'); var __proto=JumpPointFinderBase.prototype; /** *Find and return the path. *@return {Array<Array<number>>}The path,including both start and *end positions. */ __proto.findPath=function(startX,startY,endX,endY,grid){ var openList=this.openList=new Heap(function(nodeA,nodeB){ return nodeA.f-nodeB.f; }),startNode=this.startNode=grid.getNodeAt(startX,startY),endNode=this.endNode=grid.getNodeAt(endX,endY),node; this.grid=grid; startNode.g=0; startNode.f=0; openList.push(startNode); startNode.opened=true; while (!openList.empty()){ node=openList.pop(); node.closed=true; if (node==endNode){ return Util.expandPath(Util.backtrace(endNode)); } this._identifySuccessors(node); } return []; } /** *Identify successors for the given node. Runs a jump point search in the *direction of each available neighbor,adding any points found to the open *list. *@protected */ __proto._identifySuccessors=function(node){ var grid=this.grid,heuristic=this.heuristic,openList=this.openList,endX=this.endNode.x,endY=this.endNode.y,neighbors,neighbor,jumpPoint,i=0,l=0,x=node.x,y=node.y,jx=0,jy=0,dx=0,dy=0,d=0,ng=0,jumpNode,abs=Math.abs,max=Math.max; neighbors=this._findNeighbors(node); for (i=0,l=neighbors.length;i < l;++i){ neighbor=neighbors[i]; jumpPoint=this._jump(neighbor[0],neighbor[1],x,y); if (jumpPoint){ jx=jumpPoint[0]; jy=jumpPoint[1]; jumpNode=grid.getNodeAt(jx,jy); if (jumpNode.closed){ continue ; } d=Heuristic.octile(abs(jx-x),abs(jy-y)); ng=node.g+d; if (!jumpNode.opened || ng < jumpNode.g){ jumpNode.g=ng; jumpNode.h=jumpNode.h || heuristic(abs(jx-endX),abs(jy-endY)); jumpNode.f=jumpNode.g+jumpNode.h; jumpNode.parent=node; if (!jumpNode.opened){ openList.push(jumpNode); jumpNode.opened=true; } else{ openList.updateItem(jumpNode); } } } } } __proto._jump=function(x,y,px,py){ return []; } __proto._findNeighbors=function(node){ return []; } return JumpPointFinderBase; })() /** *... *@author ... */ //class PathFinding.finders.JumpPointFinder var JumpPointFinder=(function(){ /** *Path finder using the Jump Point Search algorithm *@param {Object}opt *@param {function}opt.heuristic Heuristic function to estimate the distance *(defaults to manhattan). *@param {DiagonalMovement}opt.diagonalMovement Condition under which diagonal *movement will be allowed. */ function JumpPointFinder(opt){} __class(JumpPointFinder,'PathFinding.finders.JumpPointFinder'); return JumpPointFinder; })() /** *... *@author dongketao */ //class PathFinding.finders.TraceFinder var TraceFinder=(function(){ function TraceFinder(opt){ this.allowDiagonal=false; this.dontCrossCorners=false; this.diagonalMovement=0; this.heuristic=null; opt=opt || {}; this.allowDiagonal=opt.allowDiagonal; this.dontCrossCorners=opt.dontCrossCorners; this.heuristic=opt.heuristic || Heuristic.manhattan; this.diagonalMovement=opt.diagonalMovement; if (!this.diagonalMovement){ if (!this.allowDiagonal){ this.diagonalMovement=DiagonalMovement.Never; } else{ if (this.dontCrossCorners){ this.diagonalMovement=DiagonalMovement.OnlyWhenNoObstacles; } else{ this.diagonalMovement=DiagonalMovement.IfAtMostOneObstacle; } } } if (this.diagonalMovement==DiagonalMovement.Never){ this.heuristic=opt.heuristic || Heuristic.manhattan; } else{ this.heuristic=opt.heuristic || Heuristic.octile; } } __class(TraceFinder,'PathFinding.finders.TraceFinder'); var __proto=TraceFinder.prototype; __proto.findPath=function(startX,startY,endX,endY,grid){ var openList=new Heap(function(nodeA,nodeB){ return nodeA.f-nodeB.f; }),startNode=grid.getNodeAt(startX,startY),endNode=grid.getNodeAt(endX,endY),heuristic=this.heuristic,allowDiagonal=this.allowDiagonal,dontCrossCorners=this.dontCrossCorners,abs=Math.abs,SQRT2=Math.SQRT2,node,neighbors,neighbor,i=0,l=0,x=0,y=0,ng=0; startNode.g=0; startNode.f=0; openList.push(startNode); startNode.opened=true; while (!openList.empty()){ node=openList.pop(); node.closed=true; if (node===endNode){ return Util.backtrace(endNode); } neighbors=grid.getNeighbors(node,this.diagonalMovement); for (i=0,l=neighbors.length;i < l;++i){ neighbor=neighbors[i]; if (neighbor.closed){ continue ; } x=neighbor.x; y=neighbor.y; ng=node.g+((x-node.x===0 || y-node.y===0)? 1 :SQRT2); if (!neighbor.opened || ng < neighbor.g){ neighbor.g=ng *l / 9; neighbor.h=neighbor.h || heuristic(abs(x-endX),abs(y-endY)); neighbor.f=neighbor.g+neighbor.h; neighbor.parent=node; if (!neighbor.opened){ openList.push(neighbor); neighbor.opened=true; } else{ openList.updateItem(neighbor); } } } } return []; } return TraceFinder; })() /** *... *@author dongketao */ //class PathFinding.libs.Heap var Heap=(function(){ function Heap(cmp){ this.cmp=null; this.nodes=null; this.heapFunction=new HeapFunction(); this.cmp=cmp !=null ? cmp :this.heapFunction.defaultCmp; this.nodes=[]; } __class(Heap,'PathFinding.libs.Heap'); var __proto=Heap.prototype; __proto.push=function(x){ return this.heapFunction.heappush(this.nodes,x,this.cmp); } __proto.pop=function(){ return this.heapFunction.heappop(this.nodes,this.cmp); } __proto.peek=function(){ return this.nodes[0]; } __proto.contains=function(x){ return this.nodes.indexOf(x)!==-1; } __proto.replace=function(x){ return this.heapFunction.heapreplace(this.nodes,x,this.cmp); } __proto.pushpop=function(x){ return this.heapFunction.heappushpop(this.nodes,x,this.cmp); } __proto.heapify=function(){ return this.heapFunction.heapify(this.nodes,this.cmp); } __proto.updateItem=function(x){ return this.heapFunction.updateItem(this.nodes,x,this.cmp); } __proto.clear=function(){ return this.nodes=[]; } __proto.empty=function(){ return this.nodes.length===0; } __proto.size=function(){ return this.nodes.length; } __proto.clone=function(){ var heap=new Heap(); heap.nodes=this.nodes.slice(0); return heap; } __proto.toArray=function(){ return this.nodes.slice(0); } return Heap; })() /** *... *@author dongketao */ //class PathFinding.libs.HeapFunction var HeapFunction=(function(){ function HeapFunction(){ //}; this.defaultCmp=function(x,y){ if (x < y){ return-1; } if (x > y){ return 1; } return 0; } } __class(HeapFunction,'PathFinding.libs.HeapFunction'); var __proto=HeapFunction.prototype; //}; __proto.insort=function(a,x,lo,hi,cmp){ var mid=NaN; if (lo==null){ lo=0; } if (cmp==null){ cmp=this.defaultCmp; } if (lo < 0){ throw new Error('lo must be non-negative'); } if (hi==null){ hi=a.length; } while (lo < hi){ mid=Math.floor((lo+hi)/ 2); if (cmp(x,a[mid])< 0){ hi=mid; } else{ lo=mid+1; } } return ([].splice.apply(a,[lo,lo-lo].concat(x)),x); } //}; __proto.heappush=function(array,item,cmp){ if (cmp==null){ cmp=this.defaultCmp; } array.push(item); return this._siftdown(array,0,array.length-1,cmp); } //}; __proto.heappop=function(array,cmp){ var lastelt,returnitem; if (cmp==null){ cmp=this.defaultCmp; } lastelt=array.pop(); if (array.length){ returnitem=array[0]; array[0]=lastelt; this._siftup(array,0,cmp); } else{ returnitem=lastelt; } return returnitem; } //}; __proto.heapreplace=function(array,item,cmp){ var returnitem; if (cmp==null){ cmp=this.defaultCmp; } returnitem=array[0]; array[0]=item; this._siftup(array,0,cmp); return returnitem; } //}; __proto.heappushpop=function(array,item,cmp){ var _ref; if (cmp==null){ cmp=this.defaultCmp; } if (array.length && cmp(array[0],item)< 0){ _ref=[array[0],item],item=_ref[0],array[0]=_ref[1]; this._siftup(array,0,cmp); } return item; } //}; __proto.heapify=function(array,cmp){ var i=0,_i=0,_j=0,_len=0,_ref,_ref1,_results,_results1; if (cmp==null){ cmp=this.defaultCmp; } _ref1=(function(){ _results1=[]; for (_j=0,_ref=Math.floor(array.length / 2);0 <=_ref ? _j < _ref :_j > _ref;0 <=_ref ? _j++:_j--){ _results1.push(_j); } return _results1; }).apply(this).reverse(); _results=[]; for (_i=0,_len=_ref1.length;_i < _len;_i++){ i=_ref1[_i]; _results.push(this._siftup(array,i,cmp)); } return _results; } //}; __proto.updateItem=function(array,item,cmp){ var pos=0; if (cmp==null){ cmp=this.defaultCmp; } pos=array.indexOf(item); if (pos===-1){ return null; } this._siftdown(array,0,pos,cmp); return this._siftup(array,pos,cmp); } //}; __proto.nlargest=function(array,n,cmp){ var elem,result,_i=0,_len=0,_ref; if (cmp==null){ cmp=this.defaultCmp; } result=array.slice(0,n); if (!result.length){ return result; } this.heapify(result,cmp); _ref=array.slice(n); for (_i=0,_len=_ref.length;_i < _len;_i++){ elem=_ref[_i]; this.heappushpop(result,elem,cmp); } return result.sort(cmp).reverse(); } //}; __proto.nsmallest=function(array,n,cmp){ var elem,i,los,result,_i=0,_j=0,_len,_ref,_ref1,_results; if (cmp==null){ cmp=this.defaultCmp; } if (n *10 <=array.length){ result=array.slice(0,n).sort(cmp); if (!result.length){ return result; } los=result[result.length-1]; _ref=array.slice(n); for (_i=0,_len=_ref.length;_i < _len;_i++){ elem=_ref[_i]; if (cmp(elem,los)< 0){ this.insort(result,elem,0,null,cmp); result.pop(); los=result[result.length-1]; } } return result; } this.heapify(array,cmp); _results=[]; for (i=_j=0,_ref1=Math.min(n,array.length);0 <=_ref1 ? _j < _ref1 :_j > _ref1;i=0 <=_ref1 ?++_j :--_j){ _results.push(this.heappop(array,cmp)); } return _results; } //}; __proto._siftdown=function(array,startpos,pos,cmp){ var newitem,parent,parentpos=0; if (cmp==null){ cmp=this.defaultCmp; } newitem=array[pos]; while (pos > startpos){ parentpos=(pos-1)>> 1; parent=array[parentpos]; if (cmp(newitem,parent)< 0){ array[pos]=parent; pos=parentpos; continue ; } break ; } return array[pos]=newitem; } //}; __proto._siftup=function(array,pos,cmp){ var childpos=0,endpos=0,newitem,rightpos=0,startpos=0; if (cmp==null){ cmp=this.defaultCmp; } endpos=array.length; startpos=pos; newitem=array[pos]; childpos=2 *pos+1; while (childpos < endpos){ rightpos=childpos+1; if (rightpos < endpos && !(cmp(array[childpos],array[rightpos])< 0)){ childpos=rightpos; } array[pos]=array[childpos]; pos=childpos; childpos=2 *pos+1; } array[pos]=newitem; return this._siftdown(array,startpos,pos,cmp); } return HeapFunction; })() /** *... *@author ... */ //class PathFinding.finders.BestFirstFinder extends PathFinding.finders.AStarFinder var BestFirstFinder=(function(_super){ function BestFirstFinder(opt){ BestFirstFinder.__super.call(this,opt); var orig=this.heuristic; this.heuristic=function (dx,dy){ return orig(dx,dy)*1000000; }; } __class(BestFirstFinder,'PathFinding.finders.BestFirstFinder',_super); return BestFirstFinder; })(AStarFinder) /** *... *@author ... */ //class PathFinding.finders.BiBestFirstFinder extends PathFinding.finders.BiAStarFinder var BiBestFirstFinder=(function(_super){ function BiBestFirstFinder(opt){ BiBestFirstFinder.__super.call(this,opt); var orig=this.heuristic; this.heuristic=function (dx,dy){ return orig(dx,dy)*1000000; }; } __class(BiBestFirstFinder,'PathFinding.finders.BiBestFirstFinder',_super); return BiBestFirstFinder; })(BiAStarFinder) /** *... *@author ... */ //class PathFinding.finders.BiDijkstraFinder extends PathFinding.finders.BiAStarFinder var BiDijkstraFinder=(function(_super){ function BiDijkstraFinder(opt){ BiDijkstraFinder.__super.call(this,opt); this.heuristic=function (dx,dy){ return 0; }; } __class(BiDijkstraFinder,'PathFinding.finders.BiDijkstraFinder',_super); return BiDijkstraFinder; })(BiAStarFinder) /** *... *@author ... */ //class PathFinding.finders.DijkstraFinder extends PathFinding.finders.AStarFinder var DijkstraFinder=(function(_super){ function DijkstraFinder(opt){ DijkstraFinder.__super.call(this,opt); this.heuristic=function (dx,dy){ return 0; }; } __class(DijkstraFinder,'PathFinding.finders.DijkstraFinder',_super); return DijkstraFinder; })(AStarFinder) /** *... *@author ... */ //class PathFinding.finders.JPFAlwaysMoveDiagonally extends PathFinding.finders.JumpPointFinderBase var JPFAlwaysMoveDiagonally=(function(_super){ function JPFAlwaysMoveDiagonally(opt){ JPFAlwaysMoveDiagonally.__super.call(this,opt); } __class(JPFAlwaysMoveDiagonally,'PathFinding.finders.JPFAlwaysMoveDiagonally',_super); var __proto=JPFAlwaysMoveDiagonally.prototype; /** *Search recursively in the direction (parent-> child),stopping only when a *jump point is found. *@protected *@return {Array<Array<number>>}The x,y coordinate of the jump point *found,or null if not found */ __proto._jump=function(x,y,px,py){ var grid=this.grid,dx=x-px,dy=y-py; if (!grid.isWalkableAt(x,y)){ return null; } if (this.trackJumpRecursion==true){ grid.getNodeAt(x,y).tested=true; } if (grid.getNodeAt(x,y)==this.endNode){ return [x,y]; } if (dx!==0 && dy!==0){ if ((grid.isWalkableAt(x-dx,y+dy)&& !grid.isWalkableAt(x-dx,y))|| (grid.isWalkableAt(x+dx,y-dy)&& !grid.isWalkableAt(x,y-dy))){ return [x,y]; } if (this._jump(x+dx,y,x,y)|| this._jump(x,y+dy,x,y)){ return [x,y]; } } else{ if (dx!==0){ if ((grid.isWalkableAt(x+dx,y+1)&& !grid.isWalkableAt(x,y+1))|| (grid.isWalkableAt(x+dx,y-1)&& !grid.isWalkableAt(x,y-1))){ return [x,y]; } } else{ if ((grid.isWalkableAt(x+1,y+dy)&& !grid.isWalkableAt(x+1,y))|| (grid.isWalkableAt(x-1,y+dy)&& !grid.isWalkableAt(x-1,y))){ return [x,y]; } } } return this._jump(x+dx,y+dy,x,y); } /** *Find the neighbors for the given node. If the node has a parent, *prune the neighbors based on the jump point search algorithm,otherwise *return all available neighbors. *@return {Array<Array<number>>}The neighbors found. */ __proto._findNeighbors=function(node){ var parent=node.parent,x=node.x,y=node.y,grid=this.grid,px=0,py=0,nx=0,ny=0,dx=0,dy=0,neighbors=[],neighborNodes,neighborNode,i=0,l=0; if (parent){ px=parent.x; py=parent.y; dx=(x-px)/ Math.max(Math.abs(x-px),1); dy=(y-py)/ Math.max(Math.abs(y-py),1); if (dx!==0 && dy!==0){ if (grid.isWalkableAt(x,y+dy)){ neighbors.push([x,y+dy]); } if (grid.isWalkableAt(x+dx,y)){ neighbors.push([x+dx,y]); } if (grid.isWalkableAt(x+dx,y+dy)){ neighbors.push([x+dx,y+dy]); } if (!grid.isWalkableAt(x-dx,y)){ neighbors.push([x-dx,y+dy]); } if (!grid.isWalkableAt(x,y-dy)){ neighbors.push([x+dx,y-dy]); } } else{ if (dx===0){ if (grid.isWalkableAt(x,y+dy)){ neighbors.push([x,y+dy]); } if (!grid.isWalkableAt(x+1,y)){ neighbors.push([x+1,y+dy]); } if (!grid.isWalkableAt(x-1,y)){ neighbors.push([x-1,y+dy]); } } else{ if (grid.isWalkableAt(x+dx,y)){ neighbors.push([x+dx,y]); } if (!grid.isWalkableAt(x,y+1)){ neighbors.push([x+dx,y+1]); } if (!grid.isWalkableAt(x,y-1)){ neighbors.push([x+dx,y-1]); } } } } else{ neighborNodes=grid.getNeighbors(node,DiagonalMovement.Always); for (i=0,l=neighborNodes.length;i < l;++i){ neighborNode=neighborNodes[i]; neighbors.push([neighborNode.x,neighborNode.y]); } } return neighbors; } return JPFAlwaysMoveDiagonally; })(JumpPointFinderBase) /** *... *@author ... */ //class PathFinding.finders.JPFMoveDiagonallyIfAtMostOneObstacle extends PathFinding.finders.JumpPointFinderBase var JPFMoveDiagonallyIfAtMostOneObstacle=(function(_super){ function JPFMoveDiagonallyIfAtMostOneObstacle(opt){ JPFMoveDiagonallyIfAtMostOneObstacle.__super.call(this,opt); } __class(JPFMoveDiagonallyIfAtMostOneObstacle,'PathFinding.finders.JPFMoveDiagonallyIfAtMostOneObstacle',_super); var __proto=JPFMoveDiagonallyIfAtMostOneObstacle.prototype; /** *Search recursively in the direction (parent-> child),stopping only when a *jump point is found. *@protected *@return {Array<Array<number>>}The x,y coordinate of the jump point *found,or null if not found */ __proto._jump=function(x,y,px,py){ var grid=this.grid,dx=x-px,dy=y-py; if (!grid.isWalkableAt(x,y)){ return null; } if (this.trackJumpRecursion===true){ grid.getNodeAt(x,y).tested=true; } if (grid.getNodeAt(x,y)==this.endNode){ return [x,y]; } if (dx!==0 && dy!==0){ if ((grid.isWalkableAt(x-dx,y+dy)&& !grid.isWalkableAt(x-dx,y))|| (grid.isWalkableAt(x+dx,y-dy)&& !grid.isWalkableAt(x,y-dy))){ return [x,y]; } if (this._jump(x+dx,y,x,y)|| this._jump(x,y+dy,x,y)){ return [x,y]; } } else{ if (dx!==0){ if ((grid.isWalkableAt(x+dx,y+1)&& !grid.isWalkableAt(x,y+1))|| (grid.isWalkableAt(x+dx,y-1)&& !grid.isWalkableAt(x,y-1))){ return [x,y]; } } else{ if ((grid.isWalkableAt(x+1,y+dy)&& !grid.isWalkableAt(x+1,y))|| (grid.isWalkableAt(x-1,y+dy)&& !grid.isWalkableAt(x-1,y))){ return [x,y]; } } } if (grid.isWalkableAt(x+dx,y)|| grid.isWalkableAt(x,y+dy)){ return this._jump(x+dx,y+dy,x,y); } else{ return null; } } /** *Find the neighbors for the given node. If the node has a parent, *prune the neighbors based on the jump point search algorithm,otherwise *return all available neighbors. *@return {Array<Array<number>>}The neighbors found. */ __proto._findNeighbors=function(node){ var parent=node.parent,x=node.x,y=node.y,grid=this.grid,px=0,py=0,nx=0,ny=0,dx=0,dy=0,neighbors=[],neighborNodes,neighborNode,i=0,l=0; if (parent){ px=parent.x; py=parent.y; dx=(x-px)/ Math.max(Math.abs(x-px),1); dy=(y-py)/ Math.max(Math.abs(y-py),1); if (dx!==0 && dy!==0){ if (grid.isWalkableAt(x,y+dy)){ neighbors.push([x,y+dy]); } if (grid.isWalkableAt(x+dx,y)){ neighbors.push([x+dx,y]); } if (grid.isWalkableAt(x,y+dy)|| grid.isWalkableAt(x+dx,y)){ neighbors.push([x+dx,y+dy]); } if (!grid.isWalkableAt(x-dx,y)&& grid.isWalkableAt(x,y+dy)){ neighbors.push([x-dx,y+dy]); } if (!grid.isWalkableAt(x,y-dy)&& grid.isWalkableAt(x+dx,y)){ neighbors.push([x+dx,y-dy]); } } else{ if (dx===0){ if (grid.isWalkableAt(x,y+dy)){ neighbors.push([x,y+dy]); if (!grid.isWalkableAt(x+1,y)){ neighbors.push([x+1,y+dy]); } if (!grid.isWalkableAt(x-1,y)){ neighbors.push([x-1,y+dy]); } } } else{ if (grid.isWalkableAt(x+dx,y)){ neighbors.push([x+dx,y]); if (!grid.isWalkableAt(x,y+1)){ neighbors.push([x+dx,y+1]); } if (!grid.isWalkableAt(x,y-1)){ neighbors.push([x+dx,y-1]); } } } } } else{ neighborNodes=grid.getNeighbors(node,DiagonalMovement.IfAtMostOneObstacle); for (i=0,l=neighborNodes.length;i < l;++i){ neighborNode=neighborNodes[i]; neighbors.push([neighborNode.x,neighborNode.y]); } } return neighbors; } return JPFMoveDiagonallyIfAtMostOneObstacle; })(JumpPointFinderBase) /** *... *@author ... */ //class PathFinding.finders.JPFMoveDiagonallyIfNoObstacles extends PathFinding.finders.JumpPointFinderBase var JPFMoveDiagonallyIfNoObstacles=(function(_super){ function JPFMoveDiagonallyIfNoObstacles(opt){ JPFMoveDiagonallyIfNoObstacles.__super.call(this,opt); } __class(JPFMoveDiagonallyIfNoObstacles,'PathFinding.finders.JPFMoveDiagonallyIfNoObstacles',_super); var __proto=JPFMoveDiagonallyIfNoObstacles.prototype; /** *Search recursively in the direction (parent-> child),stopping only when a *jump point is found. *@protected *@return {Array<Array<number>>}The x,y coordinate of the jump point *found,or null if not found */ __proto._jump=function(x,y,px,py){ var grid=this.grid,dx=x-px,dy=y-py; if (!grid.isWalkableAt(x,y)){ return null; } if (this.trackJumpRecursion===true){ grid.getNodeAt(x,y).tested=true; } if (grid.getNodeAt(x,y)===this.endNode){ return [x,y]; } if (dx!==0 && dy!==0){ if (this._jump(x+dx,y,x,y)|| this._jump(x,y+dy,x,y)){ return [x,y]; } } else{ if (dx!==0){ if ((grid.isWalkableAt(x,y-1)&& !grid.isWalkableAt(x-dx,y-1))|| (grid.isWalkableAt(x,y+1)&& !grid.isWalkableAt(x-dx,y+1))){ return [x,y]; } } else if (dy!==0){ if ((grid.isWalkableAt(x-1,y)&& !grid.isWalkableAt(x-1,y-dy))|| (grid.isWalkableAt(x+1,y)&& !grid.isWalkableAt(x+1,y-dy))){ return [x,y]; } } } if (grid.isWalkableAt(x+dx,y)&& grid.isWalkableAt(x,y+dy)){ return this._jump(x+dx,y+dy,x,y); } else{ return null; } } /** *Find the neighbors for the given node. If the node has a parent, *prune the neighbors based on the jump point search algorithm,otherwise *return all available neighbors. *@return {Array<Array<number>>}The neighbors found. */ __proto._findNeighbors=function(node){ var parent=node.parent,x=node.x,y=node.y,grid=this.grid,px=0,py=0,nx=0,ny=0,dx=0,dy=0,neighbors=[],neighborNodes,neighborNode,i=0,l=0; if (parent){ px=parent.x; py=parent.y; dx=(x-px)/ Math.max(Math.abs(x-px),1); dy=(y-py)/ Math.max(Math.abs(y-py),1); if (dx!==0 && dy!==0){ if (grid.isWalkableAt(x,y+dy)){ neighbors.push([x,y+dy]); } if (grid.isWalkableAt(x+dx,y)){ neighbors.push([x+dx,y]); } if (grid.isWalkableAt(x,y+dy)&& grid.isWalkableAt(x+dx,y)){ neighbors.push([x+dx,y+dy]); } } else{ var isNextWalkable=false; if (dx!==0){ isNextWalkable=grid.isWalkableAt(x+dx,y); var isTopWalkable=grid.isWalkableAt(x,y+1); var isBottomWalkable=grid.isWalkableAt(x,y-1); if (isNextWalkable){ neighbors.push([x+dx,y]); if (isTopWalkable){ neighbors.push([x+dx,y+1]); } if (isBottomWalkable){ neighbors.push([x+dx,y-1]); } } if (isTopWalkable){ neighbors.push([x,y+1]); } if (isBottomWalkable){ neighbors.push([x,y-1]); } } else if (dy!==0){ isNextWalkable=grid.isWalkableAt(x,y+dy); var isRightWalkable=grid.isWalkableAt(x+1,y); var isLeftWalkable=grid.isWalkableAt(x-1,y); if (isNextWalkable){ neighbors.push([x,y+dy]); if (isRightWalkable){ neighbors.push([x+1,y+dy]); } if (isLeftWalkable){ neighbors.push([x-1,y+dy]); } } if (isRightWalkable){ neighbors.push([x+1,y]); } if (isLeftWalkable){ neighbors.push([x-1,y]); } } } } else{ neighborNodes=grid.getNeighbors(node,DiagonalMovement.OnlyWhenNoObstacles); for (i=0,l=neighborNodes.length;i < l;++i){ neighborNode=neighborNodes[i]; neighbors.push([neighborNode.x,neighborNode.y]); } } return neighbors; } return JPFMoveDiagonallyIfNoObstacles; })(JumpPointFinderBase) /** *... *@author ... */ //class PathFinding.finders.JPFNeverMoveDiagonally extends PathFinding.finders.JumpPointFinderBase var JPFNeverMoveDiagonally=(function(_super){ function JPFNeverMoveDiagonally(opt){ JPFNeverMoveDiagonally.__super.call(this,opt); } __class(JPFNeverMoveDiagonally,'PathFinding.finders.JPFNeverMoveDiagonally',_super); var __proto=JPFNeverMoveDiagonally.prototype; /** *Search recursively in the direction (parent-> child),stopping only when a *jump point is found. *@protected *@return {Array<Array<number>>}The x,y coordinate of the jump point *found,or null if not found */ __proto._jump=function(x,y,px,py){ var grid=this.grid,dx=x-px,dy=y-py; if (!grid.isWalkableAt(x,y)){ return null; } if (this.trackJumpRecursion===true){ grid.getNodeAt(x,y).tested=true; } if (grid.getNodeAt(x,y)==this.endNode){ return [x,y]; } if (dx!==0){ if ((grid.isWalkableAt(x,y-1)&& !grid.isWalkableAt(x-dx,y-1))|| (grid.isWalkableAt(x,y+1)&& !grid.isWalkableAt(x-dx,y+1))){ return [x,y]; } } else if (dy!==0){ if ((grid.isWalkableAt(x-1,y)&& !grid.isWalkableAt(x-1,y-dy))|| (grid.isWalkableAt(x+1,y)&& !grid.isWalkableAt(x+1,y-dy))){ return [x,y]; } if (this._jump(x+1,y,x,y)|| this._jump(x-1,y,x,y)){ return [x,y]; } } else{ throw new Error("Only horizontal and vertical movements are allowed"); } return this._jump(x+dx,y+dy,x,y); } /** *Find the neighbors for the given node. If the node has a parent, *prune the neighbors based on the jump point search algorithm,otherwise *return all available neighbors. *@return {Array<Array<number>>}The neighbors found. */ __proto._findNeighbors=function(node){ var parent=node.parent,x=node.x,y=node.y,grid=this.grid,px=0,py=0,nx=0,ny=0,dx=0,dy=0,neighbors=[],neighborNodes,neighborNode,i=0,l=0; if (parent){ px=parent.x; py=parent.y; dx=(x-px)/ Math.max(Math.abs(x-px),1); dy=(y-py)/ Math.max(Math.abs(y-py),1); if (dx!==0){ if (grid.isWalkableAt(x,y-1)){ neighbors.push([x,y-1]); } if (grid.isWalkableAt(x,y+1)){ neighbors.push([x,y+1]); } if (grid.isWalkableAt(x+dx,y)){ neighbors.push([x+dx,y]); } } else if (dy!==0){ if (grid.isWalkableAt(x-1,y)){ neighbors.push([x-1,y]); } if (grid.isWalkableAt(x+1,y)){ neighbors.push([x+1,y]); } if (grid.isWalkableAt(x,y+dy)){ neighbors.push([x,y+dy]); } } } else{ neighborNodes=grid.getNeighbors(node,DiagonalMovement.Never); for (i=0,l=neighborNodes.length;i < l;++i){ neighborNode=neighborNodes[i]; neighbors.push([neighborNode.x,neighborNode.y]); } } return neighbors; } return JPFNeverMoveDiagonally; })(JumpPointFinderBase) })(window,document,Laya); if (typeof define === 'function' && define.amd){ define('laya.core', ['require', "exports"], function(require, exports) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); for (var i in Laya) { var o = Laya[i]; o && o.__isclass && (exports[i] = o); } }); }
/** @license Copyright (c) 2015 The Polymer Project Authors. All rights reserved. This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt Code distributed by Google as part of the polymer project is also subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt */ import "../polymer/polymer-legacy.js"; import { NeonAnimationBehavior } from './neon-animation-behavior.js'; /** * Use `NeonSharedElementAnimationBehavior` to implement shared element * animations. * @polymerBehavior NeonSharedElementAnimationBehavior */ export const NeonSharedElementAnimationBehaviorImpl = { properties: { /** * Cached copy of shared elements. */ sharedElements: { type: Object } }, /** * Finds shared elements based on `config`. */ findSharedElements: function (config) { var fromPage = config.fromPage; var toPage = config.toPage; if (!fromPage || !toPage) { console.warn(this.is + ':', !fromPage ? 'fromPage' : 'toPage', 'is undefined!'); return null; } ; if (!fromPage.sharedElements || !toPage.sharedElements) { console.warn(this.is + ':', 'sharedElements are undefined for', !fromPage.sharedElements ? fromPage : toPage); return null; } ; var from = fromPage.sharedElements[config.id]; var to = toPage.sharedElements[config.id]; if (!from || !to) { console.warn(this.is + ':', 'sharedElement with id', config.id, 'not found in', !from ? fromPage : toPage); return null; } this.sharedElements = { from: from, to: to }; return this.sharedElements; } }; /** @polymerBehavior */ export const NeonSharedElementAnimationBehavior = [NeonAnimationBehavior, NeonSharedElementAnimationBehaviorImpl];
'use strict'; var path = require('path'); var gulp = require('gulp'); var shell = require('gulp-shell'); var clean = require('gulp-clean'); var config = require('../../../config'); // 启动browser sync gulp.task('browser-sync', function() { setTimeout(function() { shell.task('browser-sync start --config build/bs/bs-config.js', { cwd: config.root })(); }, 15000); }); gulp.task('webpack', shell.task('webpack --config ../../webpack/webpack.config.js')); gulp.task('webpack-watch', shell.task('webpack --config ../../webpack/webpack.config.js --watch')); // 开始处断点调试~~ gulp.task('inspector-brk', function() { shell.task('node-inspector --web-port=8081', { cwd: config.root })(); setTimeout(function() { shell.task('node-dev --debug-brk server/index.js', { cwd: config.root })(); }, 12000); }); gulp.task('fis3-debug', function() { shell.task('node-inspector --web-port=8081', { cwd: config.root })(); shell.task(path.join('node --debug ' + process.env['APPDATA'], 'npm/node_modules/fis3/bin/fis.js') + ' release -w -d ' + path.resolve(config.root, config.dest))(); }); gulp.task('fis3-server', function() { shell.task('node-inspector --web-port=8081', { cwd: config.root })(); setTimeout(function() { shell.task('node-dev --debug server/index.js', { cwd: config.root })(); }, 12000); }); gulp.task('fis3-clean', function() { return gulp.src('process.env["LOCALAPPDATA"]' + '/.fis3-tmp/cache', {read: false}) .pipe(clean()); }); gulp.task('fis3-release', ['fis3-clean', 'webpack'], shell.task('fis3 release --verbose -d ' + path.resolve(config.root, config.dest))); gulp.task('fis3-watch', shell.task('fis3 release -w -d ' + path.resolve(config.root, config.dest))); // 对外命令 gulp.task('debug', ['fis3-watch', 'inspector-brk']); gulp.task('dev', ['fis3-release'], function() { gulp.start('webpack-watch'); gulp.start('fis3-watch'); gulp.start('fis3-server'); gulp.start('browser-sync'); });
'use strict'; module.exports.hash = function hash(plainPassword) { const bcrypt = require('bcryptjs'), bcryptGenSalt = Promise.promisify(bcrypt.genSalt), bcryptHash = Promise.promisify(bcrypt.hash); return bcryptGenSalt().then(function (salt) { return bcryptHash(plainPassword, salt); }); }; module.exports.compare = function compare(plainPassword, hashedPassword) { const bcrypt = require('bcryptjs'), bcryptCompare = Promise.promisify(bcrypt.compare); return bcryptCompare(plainPassword, hashedPassword); };
/*global define*/ define([ '../Core/defined', '../Core/defineProperties', '../Core/destroyObject', './ShaderProgram', './ShaderSource' ], function( defined, defineProperties, destroyObject, ShaderProgram, ShaderSource) { "use strict"; /** * @private */ var ShaderCache = function(context) { this._context = context; this._shaders = {}; this._numberOfShaders = 0; this._shadersToRelease = {}; }; defineProperties(ShaderCache.prototype, { numberOfShaders : { get : function() { return this._numberOfShaders; } } }); /** * Returns a shader program from the cache, or creates and caches a new shader program, * given the GLSL vertex and fragment shader source and attribute locations. * <p> * The difference between this and {@link ShaderCache#getShaderProgram}, is this is used to * replace an existing reference to a shader program, which is passed as the first argument. * </p> * * @param {Object} options Object with the following properties: * @param {ShaderProgram} [options.shaderProgram] The shader program that is being reassigned. * @param {String|ShaderSource} options.vertexShaderSource The GLSL source for the vertex shader. * @param {String|ShaderSource} options.fragmentShaderSource The GLSL source for the fragment shader. * @param {Object} options.attributeLocations Indices for the attribute inputs to the vertex shader. * @returns {ShaderProgram} The cached or newly created shader program. * * @see ShaderCache#getShaderProgram * * @example * this._shaderProgram = context.shaderCache.replaceShaderProgram({ * shaderProgram : this._shaderProgram, * vertexShaderSource : vs, * fragmentShaderSource : fs, * attributeLocations : attributeLocations * }); */ ShaderCache.prototype.replaceShaderProgram = function(options) { if (defined(options.shaderProgram)) { options.shaderProgram.destroy(); } return this.getShaderProgram(options); }; /** * Returns a shader program from the cache, or creates and caches a new shader program, * given the GLSL vertex and fragment shader source and attribute locations. * * @param {Object} options Object with the following properties: * @param {String|ShaderSource} options.vertexShaderSource The GLSL source for the vertex shader. * @param {String|ShaderSource} options.fragmentShaderSource The GLSL source for the fragment shader. * @param {Object} options.attributeLocations Indices for the attribute inputs to the vertex shader. * * @returns {ShaderProgram} The cached or newly created shader program. */ ShaderCache.prototype.getShaderProgram = function(options) { // convert shaders which are provided as strings into ShaderSource objects // because ShaderSource handles all the automatic including of built-in functions, etc. var vertexShaderSource = options.vertexShaderSource; var fragmentShaderSource = options.fragmentShaderSource; var attributeLocations = options.attributeLocations; if (typeof vertexShaderSource === 'string') { vertexShaderSource = new ShaderSource({ sources : [vertexShaderSource] }); } if (typeof fragmentShaderSource === 'string') { fragmentShaderSource = new ShaderSource({ sources : [fragmentShaderSource] }); } var vertexShaderText = vertexShaderSource.createCombinedVertexShader(); var fragmentShaderText = fragmentShaderSource.createCombinedFragmentShader(); var keyword = vertexShaderText + fragmentShaderText + JSON.stringify(attributeLocations); var cachedShader; if (this._shaders[keyword]) { cachedShader = this._shaders[keyword]; // No longer want to release this if it was previously released. delete this._shadersToRelease[keyword]; } else { var context = this._context; var shaderProgram = new ShaderProgram({ gl : context._gl, logShaderCompilation : context.logShaderCompilation, debugShaders : context.debugShaders, vertexShaderSource : vertexShaderSource, vertexShaderText : vertexShaderText, fragmentShaderSource : fragmentShaderSource, fragmentShaderText : fragmentShaderText, attributeLocations : attributeLocations }); cachedShader = { cache : this, shaderProgram : shaderProgram, keyword : keyword, count : 0 }; // A shader can't be in more than one cache. shaderProgram._cachedShader = cachedShader; this._shaders[keyword] = cachedShader; ++this._numberOfShaders; } ++cachedShader.count; return cachedShader.shaderProgram; }; ShaderCache.prototype.destroyReleasedShaderPrograms = function() { var shadersToRelease = this._shadersToRelease; for ( var keyword in shadersToRelease) { if (shadersToRelease.hasOwnProperty(keyword)) { var cachedShader = shadersToRelease[keyword]; delete this._shaders[cachedShader.keyword]; cachedShader.shaderProgram.finalDestroy(); --this._numberOfShaders; } } this._shadersToRelease = {}; }; ShaderCache.prototype.releaseShaderProgram = function(shaderProgram) { if (shaderProgram) { var cachedShader = shaderProgram._cachedShader; if (cachedShader && (--cachedShader.count === 0)) { this._shadersToRelease[cachedShader.keyword] = cachedShader; } } }; ShaderCache.prototype.isDestroyed = function() { return false; }; ShaderCache.prototype.destroy = function() { var shaders = this._shaders; for ( var keyword in shaders) { if (shaders.hasOwnProperty(keyword)) { shaders[keyword].shaderProgram.finalDestroy(); } } return destroyObject(this); }; return ShaderCache; });
angular.module('ai.common.directives.dropdown', []) .directive('aiDropdown', function() { return { restrict: 'EA', require: 'ngModel', scope: { ngModel: '=', list: '=' }, link: function(scope, elem, attrs, ngModel) { var data = []; _.each(scope.list, function (item) { data.push({ 'text': item, 'click': 'setter('+item+')' }); }); scope.setter = function (val) { scope.ngModel = val; }; scope.data = data; scope.$watch(function () { return ngModel.$modelValue; }, function() { scope.selected = scope.ngModel; }); }, template: '<button type="button" class="btn-dropdown full-width" bs-dropdown="data" html="true"> {{selected}} </button>' }; }) ;
/** * (c) 2010-2018 Torstein Honsi * * License: www.highcharts.com/license */ 'use strict'; import H from './Globals.js'; import './Utilities.js'; var doc = H.doc, extend = H.extend, format = H.format, isNumber = H.isNumber, merge = H.merge, pick = H.pick, splat = H.splat, syncTimeout = H.syncTimeout, timeUnits = H.timeUnits; /** * Tooltip of a chart. * * @class * @name Highcharts.Tooltip * * @param {Highcharts.Chart} chart * The chart instance. * * @param {Highcharts.TooltipOptions} options * Tooltip options. */ H.Tooltip = function () { this.init.apply(this, arguments); }; H.Tooltip.prototype = { /** * @private * @function Highcharts.Tooltip#init * * @param {Highcharts.Chart} chart * The chart instance. * * @param {Highcharts.TooltipOptions} options * Tooltip options. */ init: function (chart, options) { /** * Chart of the tooltip. * * @readonly * @name Highcharts.Tooltip#chart * @type {Highcharts.Chart} */ this.chart = chart; /** * Used tooltip options. * * @readonly * @name Highcharts.Tooltip#options * @type {Highcharts.TooltipOptions} */ this.options = options; /** * List of crosshairs. * * @private * @readonly * @name Highcharts.Tooltip#crosshairs * @type {Array<*>} */ this.crosshairs = []; /** * Current values of x and y when animating. * * @private * @readonly * @name Highcharts.Tooltip#now * @type {*} */ this.now = { x: 0, y: 0 }; /** * Tooltips are initially hidden. * * @readonly * @name Highcharts.Tooltip#isHidden * @type {boolean} */ this.isHidden = true; /** * True, if the tooltip is splitted into one label per series, with the * header close to the axis. * * @readonly * @name Highcharts.Tooltip#split * @type {boolean} */ this.split = options.split && !chart.inverted; /** * When the tooltip is shared, the entire plot area will capture mouse * movement or touch events. * * @readonly * @name Highcharts.Tooltip#shared * @type {boolean} */ this.shared = options.shared || this.split; /** * Whether to allow the tooltip to render outside the chart's SVG * element box. By default (false), the tooltip is rendered within the * chart's SVG element, which results in the tooltip being aligned * inside the chart area. * * @readonly * @name Highcharts.Tooltip#outside * @type {boolean} * * @todo * Split tooltip does not support outside in the first iteration. Should * not be too complicated to implement. */ this.outside = options.outside && !this.split; }, /** * Destroy the single tooltips in a split tooltip. * If the tooltip is active then it is not destroyed, unless forced to. * * @private * @function Highcharts.Tooltip#cleanSplit * * @param {boolean} force * Force destroy all tooltips. */ cleanSplit: function (force) { this.chart.series.forEach(function (series) { var tt = series && series.tt; if (tt) { if (!tt.isActive || force) { series.tt = tt.destroy(); } else { tt.isActive = false; } } }); }, /** * In styled mode, apply the default filter for the tooltip drop-shadow. It * needs to have an id specific to the chart, otherwise there will be issues * when one tooltip adopts the filter of a different chart, specifically one * where the container is hidden. * * @private * @function Highcharts.Tooltip#applyFilter */ applyFilter: function () { var chart = this.chart; chart.renderer.definition({ tagName: 'filter', id: 'drop-shadow-' + chart.index, opacity: 0.5, children: [{ tagName: 'feGaussianBlur', in: 'SourceAlpha', stdDeviation: 1 }, { tagName: 'feOffset', dx: 1, dy: 1 }, { tagName: 'feComponentTransfer', children: [{ tagName: 'feFuncA', type: 'linear', slope: 0.3 }] }, { tagName: 'feMerge', children: [{ tagName: 'feMergeNode' }, { tagName: 'feMergeNode', in: 'SourceGraphic' }] }] }); chart.renderer.definition({ tagName: 'style', textContent: '.highcharts-tooltip-' + chart.index + '{' + 'filter:url(#drop-shadow-' + chart.index + ')' + '}' }); }, /** * Creates the Tooltip label element if it does not exist, then returns it. * * @function Highcharts.Tooltip#getLabel * * @return {Highcharts.SVGElement} */ getLabel: function () { var renderer = this.chart.renderer, styledMode = this.chart.styledMode, options = this.options, container; if (!this.label) { if (this.outside) { this.container = container = H.doc.createElement('div'); container.className = 'highcharts-tooltip-container'; H.css(container, { position: 'absolute', top: '1px', pointerEvents: options.style && options.style.pointerEvents }); H.doc.body.appendChild(container); this.renderer = renderer = new H.Renderer(container, 0, 0); } // Create the label if (this.split) { this.label = renderer.g('tooltip'); } else { this.label = renderer.label( '', 0, 0, options.shape || 'callout', null, null, options.useHTML, null, 'tooltip' ) .attr({ padding: options.padding, r: options.borderRadius }); if (!styledMode) { this.label .attr({ 'fill': options.backgroundColor, 'stroke-width': options.borderWidth }) // #2301, #2657 .css(options.style) .shadow(options.shadow); } } if (styledMode) { // Apply the drop-shadow filter this.applyFilter(); this.label.addClass('highcharts-tooltip-' + this.chart.index); } if (this.outside) { this.label.attr({ x: this.distance, y: this.distance }); this.label.xSetter = function (value) { container.style.left = value + 'px'; }; this.label.ySetter = function (value) { container.style.top = value + 'px'; }; } this.label .attr({ zIndex: 8 }) .add(); } return this.label; }, /** * Updates the tooltip with the provided tooltip options. * * @function Highcharts.Tooltip#update * * @param {Highcharts.TooltipOptions} options */ update: function (options) { this.destroy(); // Update user options (#6218) merge(true, this.chart.options.tooltip.userOptions, options); this.init(this.chart, merge(true, this.options, options)); }, /** * Removes and destroys the tooltip and its elements. * * @function Highcharts.Tooltip#destroy */ destroy: function () { // Destroy and clear local variables if (this.label) { this.label = this.label.destroy(); } if (this.split && this.tt) { this.cleanSplit(this.chart, true); this.tt = this.tt.destroy(); } if (this.renderer) { this.renderer = this.renderer.destroy(); H.discardElement(this.container); } H.clearTimeout(this.hideTimer); H.clearTimeout(this.tooltipTimeout); }, /** * Moves the tooltip with a soft animation to a new position. * * @function Highcharts.Tooltip#move * * @param {number} x * * @param {number} y * * @param {number} anchorX * * @param {number} anchorY */ move: function (x, y, anchorX, anchorY) { var tooltip = this, now = tooltip.now, animate = tooltip.options.animation !== false && !tooltip.isHidden && // When we get close to the target position, abort animation and // land on the right place (#3056) (Math.abs(x - now.x) > 1 || Math.abs(y - now.y) > 1), skipAnchor = tooltip.followPointer || tooltip.len > 1; // Get intermediate values for animation extend(now, { x: animate ? (2 * now.x + x) / 3 : x, y: animate ? (now.y + y) / 2 : y, anchorX: skipAnchor ? undefined : animate ? (2 * now.anchorX + anchorX) / 3 : anchorX, anchorY: skipAnchor ? undefined : animate ? (now.anchorY + anchorY) / 2 : anchorY }); // Move to the intermediate value tooltip.getLabel().attr(now); // Run on next tick of the mouse tracker if (animate) { // Never allow two timeouts H.clearTimeout(this.tooltipTimeout); // Set the fixed interval ticking for the smooth tooltip this.tooltipTimeout = setTimeout(function () { // The interval function may still be running during destroy, // so check that the chart is really there before calling. if (tooltip) { tooltip.move(x, y, anchorX, anchorY); } }, 32); } }, /** * Hides the tooltip with a fade out animation. * * @function Highcharts.Tooltip#hide * * @param {number} [delay] * The fade out in milliseconds. If no value is provided the value * of the tooltip.hideDelay option is used. A value of 0 disables * the fade out animation. */ hide: function (delay) { var tooltip = this; // disallow duplicate timers (#1728, #1766) H.clearTimeout(this.hideTimer); delay = pick(delay, this.options.hideDelay, 500); if (!this.isHidden) { this.hideTimer = syncTimeout(function () { tooltip.getLabel()[delay ? 'fadeOut' : 'hide'](); tooltip.isHidden = true; }, delay); } }, /** * Extendable method to get the anchor position of the tooltip * from a point or set of points * * @private * @function Highcharts.Tooltip#getAnchor * * @param {Array<Highchart.Points>} points * * @param {global.Event} [mouseEvent] */ getAnchor: function (points, mouseEvent) { var ret, chart = this.chart, pointer = chart.pointer, inverted = chart.inverted, plotTop = chart.plotTop, plotLeft = chart.plotLeft, plotX = 0, plotY = 0, yAxis, xAxis; points = splat(points); // When tooltip follows mouse, relate the position to the mouse if (this.followPointer && mouseEvent) { if (mouseEvent.chartX === undefined) { mouseEvent = pointer.normalize(mouseEvent); } ret = [ mouseEvent.chartX - chart.plotLeft, mouseEvent.chartY - plotTop ]; // Pie uses a special tooltipPos } else if (points[0].tooltipPos) { ret = points[0].tooltipPos; // When shared, use the average position } else { points.forEach(function (point) { yAxis = point.series.yAxis; xAxis = point.series.xAxis; plotX += point.plotX + (!inverted && xAxis ? xAxis.left - plotLeft : 0); plotY += ( point.plotLow ? (point.plotLow + point.plotHigh) / 2 : point.plotY ) + (!inverted && yAxis ? yAxis.top - plotTop : 0); // #1151 }); plotX /= points.length; plotY /= points.length; ret = [ inverted ? chart.plotWidth - plotY : plotX, this.shared && !inverted && points.length > 1 && mouseEvent ? // place shared tooltip next to the mouse (#424) mouseEvent.chartY - plotTop : inverted ? chart.plotHeight - plotX : plotY ]; } return ret.map(Math.round); }, /** * Place the tooltip in a chart without spilling over * and not covering the point it self. * * @private * @function Highcharts.Tooltip#getPosition * * @param {number} boxWidth * * @param {number} boxHeight * * @param {Highcharts.Point} point * * @return {*} */ getPosition: function (boxWidth, boxHeight, point) { var chart = this.chart, distance = this.distance, ret = {}, // Don't use h if chart isn't inverted (#7242) h = (chart.inverted && point.h) || 0, // #4117 swapped, outside = this.outside, outerWidth = outside ? // substract distance to prevent scrollbars doc.documentElement.clientWidth - 2 * distance : chart.chartWidth, outerHeight = outside ? Math.max( doc.body.scrollHeight, doc.documentElement.scrollHeight, doc.body.offsetHeight, doc.documentElement.offsetHeight, doc.documentElement.clientHeight ) : chart.chartHeight, chartPosition = chart.pointer.chartPosition, first = [ 'y', outerHeight, boxHeight, (outside ? chartPosition.top - distance : 0) + point.plotY + chart.plotTop, outside ? 0 : chart.plotTop, outside ? outerHeight : chart.plotTop + chart.plotHeight ], second = [ 'x', outerWidth, boxWidth, (outside ? chartPosition.left - distance : 0) + point.plotX + chart.plotLeft, outside ? 0 : chart.plotLeft, outside ? outerWidth : chart.plotLeft + chart.plotWidth ], // The far side is right or bottom preferFarSide = !this.followPointer && pick( point.ttBelow, !chart.inverted === !!point.negative ), // #4984 /* * Handle the preferred dimension. When the preferred dimension is * tooltip on top or bottom of the point, it will look for space * there. * * @private */ firstDimension = function ( dim, outerSize, innerSize, point, min, max ) { var roomLeft = innerSize < point - distance, roomRight = point + distance + innerSize < outerSize, alignedLeft = point - distance - innerSize, alignedRight = point + distance; if (preferFarSide && roomRight) { ret[dim] = alignedRight; } else if (!preferFarSide && roomLeft) { ret[dim] = alignedLeft; } else if (roomLeft) { ret[dim] = Math.min( max - innerSize, alignedLeft - h < 0 ? alignedLeft : alignedLeft - h ); } else if (roomRight) { ret[dim] = Math.max( min, alignedRight + h + innerSize > outerSize ? alignedRight : alignedRight + h ); } else { return false; } }, /* * Handle the secondary dimension. If the preferred dimension is * tooltip on top or bottom of the point, the second dimension is to * align the tooltip above the point, trying to align center but * allowing left or right align within the chart box. * * @private */ secondDimension = function (dim, outerSize, innerSize, point) { var retVal; // Too close to the edge, return false and swap dimensions if (point < distance || point > outerSize - distance) { retVal = false; // Align left/top } else if (point < innerSize / 2) { ret[dim] = 1; // Align right/bottom } else if (point > outerSize - innerSize / 2) { ret[dim] = outerSize - innerSize - 2; // Align center } else { ret[dim] = point - innerSize / 2; } return retVal; }, /* * Swap the dimensions */ swap = function (count) { var temp = first; first = second; second = temp; swapped = count; }, run = function () { if (firstDimension.apply(0, first) !== false) { if ( secondDimension.apply(0, second) === false && !swapped ) { swap(true); run(); } } else if (!swapped) { swap(true); run(); } else { ret.x = ret.y = 0; } }; // Under these conditions, prefer the tooltip on the side of the point if (chart.inverted || this.len > 1) { swap(); } run(); return ret; }, /** * In case no user defined formatter is given, this will be used. Note that * the context here is an object holding point, series, x, y etc. * * @private * @function Highcharts.Tooltip#defaultFormatter * * @param {Highcharts.Tooltip} tooltip * * @return {Array<string>} */ defaultFormatter: function (tooltip) { var items = this.points || splat(this), s; // Build the header s = [tooltip.tooltipFooterHeaderFormatter(items[0])]; // build the values s = s.concat(tooltip.bodyFormatter(items)); // footer s.push(tooltip.tooltipFooterHeaderFormatter(items[0], true)); return s; }, /** * Refresh the tooltip's text and position. * * @function Highcharts.Tooltip#refresh * * @param {Highcharts.Point|Array<Highcharts.Point>} pointOrPoints * Either a point or an array of points. * * @param {global.Event} [mouseEvent] * Mouse event, that is responsible for the refresh and should be * used for the tooltip update. */ refresh: function (pointOrPoints, mouseEvent) { var tooltip = this, label, options = tooltip.options, x, y, point = pointOrPoints, anchor, textConfig = {}, text, pointConfig = [], formatter = options.formatter || tooltip.defaultFormatter, shared = tooltip.shared, currentSeries, styledMode = this.chart.styledMode; if (!options.enabled) { return; } H.clearTimeout(this.hideTimer); // get the reference point coordinates (pie charts use tooltipPos) tooltip.followPointer = splat(point)[0].series.tooltipOptions .followPointer; anchor = tooltip.getAnchor(point, mouseEvent); x = anchor[0]; y = anchor[1]; // shared tooltip, array is sent over if (shared && !(point.series && point.series.noSharedTooltip)) { point.forEach(function (item) { item.setState('hover'); pointConfig.push(item.getLabelConfig()); }); textConfig = { x: point[0].category, y: point[0].y }; textConfig.points = pointConfig; point = point[0]; // single point tooltip } else { textConfig = point.getLabelConfig(); } this.len = pointConfig.length; // #6128 text = formatter.call(textConfig, tooltip); // register the current series currentSeries = point.series; this.distance = pick(currentSeries.tooltipOptions.distance, 16); // update the inner HTML if (text === false) { this.hide(); } else { label = tooltip.getLabel(); // show it if (tooltip.isHidden) { label.attr({ opacity: 1 }).show(); } // update text if (tooltip.split) { this.renderSplit(text, splat(pointOrPoints)); } else { // Prevent the tooltip from flowing over the chart box (#6659) if (!options.style.width || styledMode) { label.css({ width: this.chart.spacingBox.width }); } label.attr({ text: text && text.join ? text.join('') : text }); // Set the stroke color of the box to reflect the point label.removeClass(/highcharts-color-[\d]+/g) .addClass( 'highcharts-color-' + pick(point.colorIndex, currentSeries.colorIndex) ); if (!styledMode) { label.attr({ stroke: ( options.borderColor || point.color || currentSeries.color || '#666666' ) }); } tooltip.updatePosition({ plotX: x, plotY: y, negative: point.negative, ttBelow: point.ttBelow, h: anchor[2] || 0 }); } this.isHidden = false; } }, /** * Render the split tooltip. Loops over each point's text and adds * a label next to the point, then uses the distribute function to * find best non-overlapping positions. * * @private * @function Highcharts.Tooltip#renderSplit * * @param {Array<Highcharts.Label>} labels * * @param {Array<Highcharts.Point>} points */ renderSplit: function (labels, points) { var tooltip = this, boxes = [], chart = this.chart, ren = chart.renderer, rightAligned = true, options = this.options, headerHeight = 0, headerTop, tooltipLabel = this.getLabel(), distributionBoxTop = chart.plotTop; // Graceful degradation for legacy formatters if (H.isString(labels)) { labels = [false, labels]; } // Create the individual labels for header and points, ignore footer labels.slice(0, points.length + 1).forEach(function (str, i) { if (str !== false && str !== '') { var point = points[i - 1] || { // Item 0 is the header. Instead of this, we could also // use the crosshair label isHeader: true, plotX: points[0].plotX, plotY: chart.plotHeight }, owner = point.series || tooltip, tt = owner.tt, series = point.series || {}, colorClass = 'highcharts-color-' + pick( point.colorIndex, series.colorIndex, 'none' ), target, x, bBox, boxWidth, attribs; // Store the tooltip referance on the series if (!tt) { attribs = { padding: options.padding, r: options.borderRadius }; if (!chart.styledMode) { attribs.fill = options.backgroundColor; attribs.stroke = ( options.borderColor || point.color || series.color || '#333333' ); attribs['stroke-width'] = options.borderWidth; } owner.tt = tt = ren.label( null, null, null, ( point.isHeader ? options.headerShape : options.shape ) || 'callout', null, null, options.useHTML ) .addClass('highcharts-tooltip-box ' + colorClass) .attr(attribs) .add(tooltipLabel); } tt.isActive = true; tt.attr({ text: str }); if (!chart.styledMode) { tt.css(options.style) .shadow(options.shadow); } // Get X position now, so we can move all to the other side in // case of overflow bBox = tt.getBBox(); boxWidth = bBox.width + tt.strokeWidth(); if (point.isHeader) { headerHeight = bBox.height; if (chart.xAxis[0].opposite) { headerTop = true; distributionBoxTop -= headerHeight; } x = Math.max( 0, // No left overflow Math.min( point.plotX + chart.plotLeft - boxWidth / 2, // No right overflow (#5794) chart.chartWidth + ( // Scrollable plot area chart.scrollablePixels ? chart.scrollablePixels - chart.marginRight : 0 ) - boxWidth ) ); } else { x = point.plotX + chart.plotLeft - pick(options.distance, 16) - boxWidth; } // If overflow left, we don't use this x in the next loop if (x < 0) { rightAligned = false; } // Prepare for distribution target = (point.series && point.series.yAxis && point.series.yAxis.pos) + (point.plotY || 0); target -= distributionBoxTop; if (point.isHeader) { target = headerTop ? -headerHeight : chart.plotHeight + headerHeight; } boxes.push({ target: target, rank: point.isHeader ? 1 : 0, size: owner.tt.getBBox().height + 1, point: point, x: x, tt: tt }); } }); // Clean previous run (for missing points) this.cleanSplit(); if (options.positioner) { boxes.forEach(function (box) { var boxPosition = options.positioner.call( tooltip, box.tt.getBBox().width, box.size, box.point ); box.x = boxPosition.x; box.align = 0; // 0-align to the top, 1-align to the bottom box.target = boxPosition.y; box.rank = pick(boxPosition.rank, box.rank); }); } // Distribute and put in place H.distribute(boxes, chart.plotHeight + headerHeight); boxes.forEach(function (box) { var point = box.point, series = point.series; // Put the label in place box.tt.attr({ visibility: box.pos === undefined ? 'hidden' : 'inherit', x: (rightAligned || point.isHeader || options.positioner ? box.x : point.plotX + chart.plotLeft + pick(options.distance, 16)), y: box.pos + distributionBoxTop, anchorX: point.isHeader ? point.plotX + chart.plotLeft : point.plotX + series.xAxis.pos, anchorY: point.isHeader ? chart.plotTop + chart.plotHeight / 2 : point.plotY + series.yAxis.pos }); }); }, /** * Find the new position and perform the move * * @private * @function Highcharts.Tooltip#updatePosition * * @param {Highcharts.Point} point */ updatePosition: function (point) { var chart = this.chart, label = this.getLabel(), pos = (this.options.positioner || this.getPosition).call( this, label.width, label.height, point ), anchorX = point.plotX + chart.plotLeft, anchorY = point.plotY + chart.plotTop, pad; // Set the renderer size dynamically to prevent document size to change if (this.outside) { pad = (this.options.borderWidth || 0) + 2 * this.distance; this.renderer.setSize( label.width + pad, label.height + pad, false ); anchorX += chart.pointer.chartPosition.left - pos.x; anchorY += chart.pointer.chartPosition.top - pos.y; } // do the move this.move( Math.round(pos.x), Math.round(pos.y || 0), // can be undefined (#3977) anchorX, anchorY ); }, /** * Get the optimal date format for a point, based on a range. * * @private * @function Highcharts.Tooltip#getDateFormat * * @param {number} range * The time range * * @param {number|Date} date * The date of the point in question * * @param {number} startOfWeek * An integer representing the first day of the week, where 0 is * Sunday. * * @param {Highcharts.Dictionary<string>} dateTimeLabelFormats * A map of time units to formats. * * @return {string} * The optimal date format for a point. */ getDateFormat: function (range, date, startOfWeek, dateTimeLabelFormats) { var time = this.chart.time, dateStr = time.dateFormat('%m-%d %H:%M:%S.%L', date), format, n, blank = '01-01 00:00:00.000', strpos = { millisecond: 15, second: 12, minute: 9, hour: 6, day: 3 }, lastN = 'millisecond'; // for sub-millisecond data, #4223 for (n in timeUnits) { // If the range is exactly one week and we're looking at a // Sunday/Monday, go for the week format if ( range === timeUnits.week && +time.dateFormat('%w', date) === startOfWeek && dateStr.substr(6) === blank.substr(6) ) { n = 'week'; break; } // The first format that is too great for the range if (timeUnits[n] > range) { n = lastN; break; } // If the point is placed every day at 23:59, we need to show // the minutes as well. #2637. if ( strpos[n] && dateStr.substr(strpos[n]) !== blank.substr(strpos[n]) ) { break; } // Weeks are outside the hierarchy, only apply them on // Mondays/Sundays like in the first condition if (n !== 'week') { lastN = n; } } if (n) { format = time.resolveDTLFormat(dateTimeLabelFormats[n]).main; } return format; }, /** * Get the best X date format based on the closest point range on the axis. * * @private * @function Highcharts.Tooltip#getXDateFormat * * @param {Highcharts.Point} point * * @param {Highcharts.TooltipOptions} options * * @param {Highcharts.Axis} xAxis * * @return {string} */ getXDateFormat: function (point, options, xAxis) { var xDateFormat, dateTimeLabelFormats = options.dateTimeLabelFormats, closestPointRange = xAxis && xAxis.closestPointRange; if (closestPointRange) { xDateFormat = this.getDateFormat( closestPointRange, point.x, xAxis.options.startOfWeek, dateTimeLabelFormats ); } else { xDateFormat = dateTimeLabelFormats.day; } return xDateFormat || dateTimeLabelFormats.year; // #2546, 2581 }, /** * Format the footer/header of the tooltip * #3397: abstraction to enable formatting of footer and header * * @private * @function Highcharts.Tooltip#tooltipFooterHeaderFormatter * * @param {*} labelConfig * * @param {boolean} isFooter * * @return {string} */ tooltipFooterHeaderFormatter: function (labelConfig, isFooter) { var footOrHead = isFooter ? 'footer' : 'header', series = labelConfig.series, tooltipOptions = series.tooltipOptions, xDateFormat = tooltipOptions.xDateFormat, xAxis = series.xAxis, isDateTime = ( xAxis && xAxis.options.type === 'datetime' && isNumber(labelConfig.key) ), formatString = tooltipOptions[footOrHead + 'Format']; // Guess the best date format based on the closest point distance (#568, // #3418) if (isDateTime && !xDateFormat) { xDateFormat = this.getXDateFormat( labelConfig, tooltipOptions, xAxis ); } // Insert the footer date format if any if (isDateTime && xDateFormat) { ((labelConfig.point && labelConfig.point.tooltipDateKeys) || ['key']).forEach( function (key) { formatString = formatString.replace( '{point.' + key + '}', '{point.' + key + ':' + xDateFormat + '}' ); } ); } // Replace default header style with class name if (series.chart.styledMode) { formatString = this.styledModeFormat(formatString); } return format(formatString, { point: labelConfig, series: series }, this.chart.time); }, /** * Build the body (lines) of the tooltip by iterating over the items and * returning one entry for each item, abstracting this functionality allows * to easily overwrite and extend it. * * @private * @function Highcharts.Tooltip#bodyFormatter * * @param {Array<Highcharts.Point>} items * * @return {string} */ bodyFormatter: function (items) { return items.map(function (item) { var tooltipOptions = item.series.tooltipOptions; return ( tooltipOptions[ (item.point.formatPrefix || 'point') + 'Formatter' ] || item.point.tooltipFormatter ).call( item.point, tooltipOptions[ (item.point.formatPrefix || 'point') + 'Format' ] || '' ); }); }, styledModeFormat: function (formatString) { return formatString .replace( 'style="font-size: 10px"', 'class="highcharts-header"' ) .replace( /style="color:{(point|series)\.color}"/g, 'class="highcharts-color-{$1.colorIndex}"' ); } };
/*! * # Semantic UI 2.6.3 - Calendar * http://github.com/semantic-org/semantic-ui/ * * * Released under the MIT license * http://opensource.org/licenses/MIT * */ ;(function ($, window, document, undefined) { 'use strict'; window = (typeof window != 'undefined' && window.Math == Math) ? window : (typeof self != 'undefined' && self.Math == Math) ? self : Function('return this')() ; $.fn.calendar = function(parameters) { var $allModules = $(this), moduleSelector = $allModules.selector || '', time = new Date().getTime(), performance = [], query = arguments[0], methodInvoked = (typeof query == 'string'), queryArguments = [].slice.call(arguments, 1), returnedValue ; $allModules .each(function () { var settings = ( $.isPlainObject(parameters) ) ? $.extend(true, {}, $.fn.calendar.settings, parameters) : $.extend({}, $.fn.calendar.settings), className = settings.className, namespace = settings.namespace, selector = settings.selector, formatter = settings.formatter, parser = settings.parser, metadata = settings.metadata, error = settings.error, eventNamespace = '.' + namespace, moduleNamespace = 'module-' + namespace, $module = $(this), $input = $module.find(selector.input), $container = $module.find(selector.popup), $activator = $module.find(selector.activator), element = this, instance = $module.data(moduleNamespace), isTouch, isTouchDown = false, focusDateUsedForRange = false, module ; module = { initialize: function () { module.debug('Initializing calendar for', element, $module); isTouch = module.get.isTouch(); module.setup.config(); module.setup.popup(); module.setup.inline(); module.setup.input(); module.setup.date(); module.create.calendar(); module.bind.events(); module.instantiate(); }, instantiate: function () { module.verbose('Storing instance of calendar'); instance = module; $module.data(moduleNamespace, instance); }, destroy: function () { module.verbose('Destroying previous calendar for', element); $module.removeData(moduleNamespace); module.unbind.events(); }, setup: { config: function () { if (module.get.minDate() !== null) { module.set.minDate($module.data(metadata.minDate)); } if (module.get.maxDate() !== null) { module.set.maxDate($module.data(metadata.maxDate)); } }, popup: function () { if (settings.inline) { return; } if (!$activator.length) { $activator = $module.children().first(); if (!$activator.length) { return; } } if ($.fn.popup === undefined) { module.error(error.popup); return; } if (!$container.length) { //prepend the popup element to the activator's parent so that it has less chance of messing with //the styling (eg input action button needs to be the last child to have correct border radius) $container = $('<div/>').addClass(className.popup).prependTo($activator.parent()); } $container.addClass(className.calendar); var onVisible = settings.onVisible; var onHidden = settings.onHidden; if (!$input.length) { //no input, $container has to handle focus/blur $container.attr('tabindex', '0'); onVisible = function () { module.focus(); return settings.onVisible.apply($container, arguments); }; onHidden = function () { module.blur(); return settings.onHidden.apply($container, arguments); }; } var onShow = function () { //reset the focus date onShow module.set.focusDate(module.get.date()); module.set.mode(settings.startMode); return settings.onShow.apply($container, arguments); }; var on = settings.on || ($input.length ? 'focus' : 'click'); var options = $.extend({}, settings.popupOptions, { popup: $container, on: on, hoverable: on === 'hover', onShow: onShow, onVisible: onVisible, onHide: settings.onHide, onHidden: onHidden }); module.popup(options); }, inline: function () { if ($activator.length && !settings.inline) { return; } $container = $('<div/>').addClass(className.calendar).appendTo($module); if (!$input.length) { $container.attr('tabindex', '0'); } }, input: function () { if (settings.touchReadonly && $input.length && isTouch) { $input.prop('readonly', true); } }, date: function () { if ($input.length) { var val = $input.val(); var date = parser.date(val, settings); module.set.date(date, settings.formatInput, false); } } }, create: { calendar: function () { var i, r, c, p, row, cell, pageGrid; var mode = module.get.mode(); var today = new Date(); var date = module.get.date(); var focusDate = module.get.focusDate(); var display = focusDate || date || settings.initialDate || today; display = module.helper.dateInRange(display); if (!focusDate) { focusDate = display; module.set.focusDate(focusDate, false, false); } var isYear = mode === 'year'; var isMonth = mode === 'month'; var isDay = mode === 'day'; var isHour = mode === 'hour'; var isMinute = mode === 'minute'; var isTimeOnly = settings.type === 'time'; var multiMonth = Math.max(settings.multiMonth, 1); var monthOffset = !isDay ? 0 : module.get.monthOffset(); var minute = display.getMinutes(); var hour = display.getHours(); var day = display.getDate(); var startMonth = display.getMonth() + monthOffset; var year = display.getFullYear(); var columns = isDay ? settings.showWeekNumbers ? 8 : 7 : isHour ? 4 : 3; var rows = isDay || isHour ? 6 : 4; var pages = isDay ? multiMonth : 1; var container = $container; container.empty(); if (pages > 1) { pageGrid = $('<div/>').addClass(className.grid).appendTo(container); } for (p = 0; p < pages; p++) { if (pages > 1) { var pageColumn = $('<div/>').addClass(className.column).appendTo(pageGrid); container = pageColumn; } var month = startMonth + p; var firstMonthDayColumn = (new Date(year, month, 1).getDay() - settings.firstDayOfWeek % 7 + 7) % 7; if (!settings.constantHeight && isDay) { var requiredCells = new Date(year, month + 1, 0).getDate() + firstMonthDayColumn; rows = Math.ceil(requiredCells / 7); } var yearChange = isYear ? 10 : isMonth ? 1 : 0; var monthChange = isDay ? 1 : 0; var dayChange = isHour || isMinute ? 1 : 0; var prevNextDay = isHour || isMinute ? day : 1; var prevDate = new Date(year - yearChange, month - monthChange, prevNextDay - dayChange, hour); var nextDate = new Date(year + yearChange, month + monthChange, prevNextDay + dayChange, hour); var prevLast = isYear ? new Date(Math.ceil(year / 10) * 10 - 9, 0, 0) : isMonth ? new Date(year, 0, 0) : isDay ? new Date(year, month, 0) : new Date(year, month, day, -1); var nextFirst = isYear ? new Date(Math.ceil(year / 10) * 10 + 1, 0, 1) : isMonth ? new Date(year + 1, 0, 1) : isDay ? new Date(year, month + 1, 1) : new Date(year, month, day + 1); var tempMode = mode; if (isDay && settings.showWeekNumbers){ tempMode += ' andweek'; } var table = $('<table/>').addClass(className.table).addClass(tempMode).appendTo(container); var textColumns = columns; //no header for time-only mode if (!isTimeOnly) { var thead = $('<thead/>').appendTo(table); row = $('<tr/>').appendTo(thead); cell = $('<th/>').attr('colspan', '' + columns).appendTo(row); var headerDate = isYear || isMonth ? new Date(year, 0, 1) : isDay ? new Date(year, month, 1) : new Date(year, month, day, hour, minute); var headerText = $('<span/>').addClass(className.link).appendTo(cell); headerText.text(formatter.header(headerDate, mode, settings)); var newMode = isMonth ? (settings.disableYear ? 'day' : 'year') : isDay ? (settings.disableMonth ? 'year' : 'month') : 'day'; headerText.data(metadata.mode, newMode); if (p === 0) { var prev = $('<span/>').addClass(className.prev).appendTo(cell); prev.data(metadata.focusDate, prevDate); prev.toggleClass(className.disabledCell, !module.helper.isDateInRange(prevLast, mode)); $('<i/>').addClass(className.prevIcon).appendTo(prev); } if (p === pages - 1) { var next = $('<span/>').addClass(className.next).appendTo(cell); next.data(metadata.focusDate, nextDate); next.toggleClass(className.disabledCell, !module.helper.isDateInRange(nextFirst, mode)); $('<i/>').addClass(className.nextIcon).appendTo(next); } if (isDay) { row = $('<tr/>').appendTo(thead); if(settings.showWeekNumbers) { cell = $('<th/>').appendTo(row); cell.text(settings.text.weekNo); cell.addClass(className.disabledCell); textColumns--; } for (i = 0; i < textColumns; i++) { cell = $('<th/>').appendTo(row); cell.text(formatter.dayColumnHeader((i + settings.firstDayOfWeek) % 7, settings)); } } } var tbody = $('<tbody/>').appendTo(table); i = isYear ? Math.ceil(year / 10) * 10 - 9 : isDay ? 1 - firstMonthDayColumn : 0; for (r = 0; r < rows; r++) { row = $('<tr/>').appendTo(tbody); if(isDay && settings.showWeekNumbers){ cell = $('<th/>').appendTo(row); cell.text(module.get.weekOfYear(year,month,i+1-settings.firstDayOfWeek)); cell.addClass(className.disabledCell); } for (c = 0; c < textColumns; c++, i++) { var cellDate = isYear ? new Date(i, month, 1, hour, minute) : isMonth ? new Date(year, i, 1, hour, minute) : isDay ? new Date(year, month, i, hour, minute) : isHour ? new Date(year, month, day, i) : new Date(year, month, day, hour, i * 5); var cellText = isYear ? i : isMonth ? settings.text.monthsShort[i] : isDay ? cellDate.getDate() : formatter.time(cellDate, settings, true); cell = $('<td/>').addClass(className.cell).appendTo(row); cell.text(cellText); cell.data(metadata.date, cellDate); var adjacent = isDay && cellDate.getMonth() !== ((month + 12) % 12); var disabled = adjacent || !module.helper.isDateInRange(cellDate, mode) || settings.isDisabled(cellDate, mode); var active = module.helper.dateEqual(cellDate, date, mode); var isToday = module.helper.dateEqual(cellDate, today, mode); cell.toggleClass(className.adjacentCell, adjacent); cell.toggleClass(className.disabledCell, disabled); cell.toggleClass(className.activeCell, active && !adjacent); if (!isHour && !isMinute) { cell.toggleClass(className.todayCell, !adjacent && isToday); } // Allow for external modifications of each cell var cellOptions = { mode: mode, adjacent: adjacent, disabled: disabled, active: active, today: isToday }; formatter.cell(cell, cellDate, cellOptions); if (module.helper.dateEqual(cellDate, focusDate, mode)) { //ensure that the focus date is exactly equal to the cell date //so that, if selected, the correct value is set module.set.focusDate(cellDate, false, false); } } } if (settings.today) { var todayRow = $('<tr/>').appendTo(tbody); var todayButton = $('<td/>').attr('colspan', '' + columns).addClass(className.today).appendTo(todayRow); todayButton.text(formatter.today(settings)); todayButton.data(metadata.date, today); } module.update.focus(false, table); } } }, update: { focus: function (updateRange, container) { container = container || $container; var mode = module.get.mode(); var date = module.get.date(); var focusDate = module.get.focusDate(); var startDate = module.get.startDate(); var endDate = module.get.endDate(); var rangeDate = (updateRange ? focusDate : null) || date || (!isTouch ? focusDate : null); container.find('td').each(function () { var cell = $(this); var cellDate = cell.data(metadata.date); if (!cellDate) { return; } var disabled = cell.hasClass(className.disabledCell); var active = cell.hasClass(className.activeCell); var adjacent = cell.hasClass(className.adjacentCell); var focused = module.helper.dateEqual(cellDate, focusDate, mode); var inRange = !rangeDate ? false : ((!!startDate && module.helper.isDateInRange(cellDate, mode, startDate, rangeDate)) || (!!endDate && module.helper.isDateInRange(cellDate, mode, rangeDate, endDate))); cell.toggleClass(className.focusCell, focused && (!isTouch || isTouchDown) && !adjacent); cell.toggleClass(className.rangeCell, inRange && !active && !disabled); }); } }, refresh: function () { module.create.calendar(); }, bind: { events: function () { module.debug('Binding events'); $container.on('mousedown' + eventNamespace, module.event.mousedown); $container.on('touchstart' + eventNamespace, module.event.mousedown); $container.on('mouseup' + eventNamespace, module.event.mouseup); $container.on('touchend' + eventNamespace, module.event.mouseup); $container.on('mouseover' + eventNamespace, module.event.mouseover); if ($input.length) { $input.on('input' + eventNamespace, module.event.inputChange); $input.on('focus' + eventNamespace, module.event.inputFocus); $input.on('blur' + eventNamespace, module.event.inputBlur); $input.on('click' + eventNamespace, module.event.inputClick); $input.on('keydown' + eventNamespace, module.event.keydown); } else { $container.on('keydown' + eventNamespace, module.event.keydown); } } }, unbind: { events: function () { module.debug('Unbinding events'); $container.off(eventNamespace); if ($input.length) { $input.off(eventNamespace); } } }, event: { mouseover: function (event) { var target = $(event.target); var date = target.data(metadata.date); var mousedown = event.buttons === 1; if (date) { module.set.focusDate(date, false, true, mousedown); } }, mousedown: function (event) { if ($input.length) { //prevent the mousedown on the calendar causing the input to lose focus event.preventDefault(); } isTouchDown = event.type.indexOf('touch') >= 0; var target = $(event.target); var date = target.data(metadata.date); if (date) { module.set.focusDate(date, false, true, true); } }, mouseup: function (event) { //ensure input has focus so that it receives keydown events for calendar navigation module.focus(); event.preventDefault(); event.stopPropagation(); isTouchDown = false; var target = $(event.target); var parent = target.parent(); if (parent.data(metadata.date) || parent.data(metadata.focusDate) || parent.data(metadata.mode)) { //clicked on a child element, switch to parent (used when clicking directly on prev/next <i> icon element) target = parent; } var date = target.data(metadata.date); var focusDate = target.data(metadata.focusDate); var mode = target.data(metadata.mode); if (date) { var forceSet = target.hasClass(className.today); module.selectDate(date, forceSet); } else if (focusDate) { module.set.focusDate(focusDate); } else if (mode) { module.set.mode(mode); } }, keydown: function (event) { if (event.keyCode === 27 || event.keyCode === 9) { //esc || tab module.popup('hide'); } if (module.popup('is visible')) { if (event.keyCode === 37 || event.keyCode === 38 || event.keyCode === 39 || event.keyCode === 40) { //arrow keys var mode = module.get.mode(); var bigIncrement = mode === 'day' ? 7 : mode === 'hour' ? 4 : 3; var increment = event.keyCode === 37 ? -1 : event.keyCode === 38 ? -bigIncrement : event.keyCode == 39 ? 1 : bigIncrement; increment *= mode === 'minute' ? 5 : 1; var focusDate = module.get.focusDate() || module.get.date() || new Date(); var year = focusDate.getFullYear() + (mode === 'year' ? increment : 0); var month = focusDate.getMonth() + (mode === 'month' ? increment : 0); var day = focusDate.getDate() + (mode === 'day' ? increment : 0); var hour = focusDate.getHours() + (mode === 'hour' ? increment : 0); var minute = focusDate.getMinutes() + (mode === 'minute' ? increment : 0); var newFocusDate = new Date(year, month, day, hour, minute); if (settings.type === 'time') { newFocusDate = module.helper.mergeDateTime(focusDate, newFocusDate); } if (module.helper.isDateInRange(newFocusDate, mode)) { module.set.focusDate(newFocusDate); } } else if (event.keyCode === 13) { //enter var mode = module.get.mode(); var date = module.get.focusDate(); if (date && !settings.isDisabled(date, mode)) { module.selectDate(date); } //disable form submission: event.preventDefault(); event.stopPropagation(); } } if (event.keyCode === 38 || event.keyCode === 40) { //arrow-up || arrow-down event.preventDefault(); //don't scroll module.popup('show'); } }, inputChange: function () { var val = $input.val(); var date = parser.date(val, settings); module.set.date(date, false); }, inputFocus: function () { $container.addClass(className.active); }, inputBlur: function () { $container.removeClass(className.active); if (settings.formatInput) { var date = module.get.date(); var text = formatter.datetime(date, settings); $input.val(text); } }, inputClick: function () { module.popup('show'); } }, get: { weekOfYear: function(weekYear,weekMonth,weekDay) { // adapted from http://www.merlyn.demon.co.uk/weekcalc.htm var ms1d = 864e5, // milliseconds in a day ms7d = 7 * ms1d; // milliseconds in a week return function() { // return a closure so constants get calculated only once var DC3 = Date.UTC(weekYear, weekMonth, weekDay + 3) / ms1d, // an Absolute Day Number AWN = Math.floor(DC3 / 7), // an Absolute Week Number Wyr = new Date(AWN * ms7d).getUTCFullYear(); return AWN - Math.floor(Date.UTC(Wyr, 0, 7) / ms7d) + 1; }(); }, date: function () { return $module.data(metadata.date) || null; }, focusDate: function () { return $module.data(metadata.focusDate) || null; }, startDate: function () { var startModule = module.get.calendarModule(settings.startCalendar); return (startModule ? startModule.get.date() : $module.data(metadata.startDate)) || null; }, endDate: function () { var endModule = module.get.calendarModule(settings.endCalendar); return (endModule ? endModule.get.date() : $module.data(metadata.endDate)) || null; }, minDate: function() { return $module.data(metadata.minDate) || null; }, maxDate: function() { return $module.data(metadata.maxDate) || null; }, monthOffset: function () { return $module.data(metadata.monthOffset) || 0; }, mode: function () { //only returns valid modes for the current settings var mode = $module.data(metadata.mode) || settings.startMode; var validModes = module.get.validModes(); if ($.inArray(mode, validModes) >= 0) { return mode; } return settings.type === 'time' ? 'hour' : settings.type === 'month' ? 'month' : settings.type === 'year' ? 'year' : 'day'; }, validModes: function () { var validModes = []; if (settings.type !== 'time') { if (!settings.disableYear || settings.type === 'year') { validModes.push('year'); } if (!(settings.disableMonth || settings.type === 'year') || settings.type === 'month') { validModes.push('month'); } if (settings.type.indexOf('date') >= 0) { validModes.push('day'); } } if (settings.type.indexOf('time') >= 0) { validModes.push('hour'); if (!settings.disableMinute) { validModes.push('minute'); } } return validModes; }, isTouch: function () { try { document.createEvent('TouchEvent'); return true; } catch (e) { return false; } }, calendarModule: function (selector) { if (!selector) { return null; } if (!(selector instanceof $)) { selector = $module.parent().children(selector).first(); } //assume range related calendars are using the same namespace return selector.data(moduleNamespace); } }, set: { date: function (date, updateInput, fireChange) { updateInput = updateInput !== false; fireChange = fireChange !== false; date = module.helper.sanitiseDate(date); date = module.helper.dateInRange(date); var mode = module.get.mode(); var text = formatter.datetime(date, settings); if (fireChange && settings.onChange.call(element, date, text, mode) === false) { return false; } module.set.focusDate(date); if (settings.isDisabled(date, mode)) { return false; } var endDate = module.get.endDate(); if (!!endDate && !!date && date > endDate) { //selected date is greater than end date in range, so clear end date module.set.endDate(undefined); } module.set.dataKeyValue(metadata.date, date); if (updateInput && $input.length) { $input.val(text); } }, startDate: function (date, refreshCalendar) { date = module.helper.sanitiseDate(date); var startModule = module.get.calendarModule(settings.startCalendar); if (startModule) { startModule.set.date(date); } module.set.dataKeyValue(metadata.startDate, date, refreshCalendar); }, endDate: function (date, refreshCalendar) { date = module.helper.sanitiseDate(date); var endModule = module.get.calendarModule(settings.endCalendar); if (endModule) { endModule.set.date(date); } module.set.dataKeyValue(metadata.endDate, date, refreshCalendar); }, focusDate: function (date, refreshCalendar, updateFocus, updateRange) { date = module.helper.sanitiseDate(date); date = module.helper.dateInRange(date); var isDay = module.get.mode() === 'day'; var oldFocusDate = module.get.focusDate(); if (isDay && date && oldFocusDate) { var yearDelta = date.getFullYear() - oldFocusDate.getFullYear(); var monthDelta = yearDelta * 12 + date.getMonth() - oldFocusDate.getMonth(); if (monthDelta) { var monthOffset = module.get.monthOffset() - monthDelta; module.set.monthOffset(monthOffset, false); } } var changed = module.set.dataKeyValue(metadata.focusDate, date, refreshCalendar); updateFocus = (updateFocus !== false && changed && refreshCalendar === false) || focusDateUsedForRange != updateRange; focusDateUsedForRange = updateRange; if (updateFocus) { module.update.focus(updateRange); } }, minDate: function (date) { date = module.helper.sanitiseDate(date); if (settings.maxDate !== null && settings.maxDate <= date) { module.verbose('Unable to set minDate variable bigger that maxDate variable', date, settings.maxDate); } else { module.setting('minDate', date); module.set.dataKeyValue(metadata.minDate, date); } }, maxDate: function (date) { date = module.helper.sanitiseDate(date); if (settings.minDate !== null && settings.minDate >= date) { module.verbose('Unable to set maxDate variable lower that minDate variable', date, settings.minDate); } else { module.setting('maxDate', date); module.set.dataKeyValue(metadata.maxDate, date); } }, monthOffset: function (monthOffset, refreshCalendar) { var multiMonth = Math.max(settings.multiMonth, 1); monthOffset = Math.max(1 - multiMonth, Math.min(0, monthOffset)); module.set.dataKeyValue(metadata.monthOffset, monthOffset, refreshCalendar); }, mode: function (mode, refreshCalendar) { module.set.dataKeyValue(metadata.mode, mode, refreshCalendar); }, dataKeyValue: function (key, value, refreshCalendar) { var oldValue = $module.data(key); var equal = oldValue === value || (oldValue <= value && oldValue >= value); //equality test for dates and string objects if (value) { $module.data(key, value); } else { $module.removeData(key); } refreshCalendar = refreshCalendar !== false && !equal; if (refreshCalendar) { module.refresh(); } return !equal; } }, selectDate: function (date, forceSet) { module.verbose('New date selection', date) var mode = module.get.mode(); var complete = forceSet || mode === 'minute' || (settings.disableMinute && mode === 'hour') || (settings.type === 'date' && mode === 'day') || (settings.type === 'month' && mode === 'month') || (settings.type === 'year' && mode === 'year'); if (complete) { var canceled = module.set.date(date) === false; if (!canceled && settings.closable) { module.popup('hide'); //if this is a range calendar, show the end date calendar popup and focus the input var endModule = module.get.calendarModule(settings.endCalendar); if (endModule) { endModule.popup('show'); endModule.focus(); } } } else { var newMode = mode === 'year' ? (!settings.disableMonth ? 'month' : 'day') : mode === 'month' ? 'day' : mode === 'day' ? 'hour' : 'minute'; module.set.mode(newMode); if (mode === 'hour' || (mode === 'day' && module.get.date())) { //the user has chosen enough to consider a valid date/time has been chosen module.set.date(date); } else { module.set.focusDate(date); } } }, changeDate: function (date) { module.set.date(date); }, clear: function () { module.set.date(undefined); }, popup: function () { return $activator.popup.apply($activator, arguments); }, focus: function () { if ($input.length) { $input.focus(); } else { $container.focus(); } }, blur: function () { if ($input.length) { $input.blur(); } else { $container.blur(); } }, helper: { sanitiseDate: function (date) { if (!date) { return undefined; } if (!(date instanceof Date)) { date = parser.date('' + date, settings); } if (isNaN(date.getTime())) { return undefined; } return date; }, dateDiff: function (date1, date2, mode) { mode = mode || 'day'; var isTimeOnly = settings.type === 'time'; var isYear = mode === 'year'; var isYearOrMonth = isYear || mode === 'month'; var isMinute = mode === 'minute'; var isHourOrMinute = isMinute || mode === 'hour'; //only care about a minute accuracy of 5 date1 = new Date( isTimeOnly ? 2000 : date1.getFullYear(), isTimeOnly ? 0 : isYear ? 0 : date1.getMonth(), isTimeOnly ? 1 : isYearOrMonth ? 1 : date1.getDate(), !isHourOrMinute ? 0 : date1.getHours(), !isMinute ? 0 : 5 * Math.floor(date1.getMinutes() / 5)); date2 = new Date( isTimeOnly ? 2000 : date2.getFullYear(), isTimeOnly ? 0 : isYear ? 0 : date2.getMonth(), isTimeOnly ? 1 : isYearOrMonth ? 1 : date2.getDate(), !isHourOrMinute ? 0 : date2.getHours(), !isMinute ? 0 : 5 * Math.floor(date2.getMinutes() / 5)); return date2.getTime() - date1.getTime(); }, dateEqual: function (date1, date2, mode) { return !!date1 && !!date2 && module.helper.dateDiff(date1, date2, mode) === 0; }, isDateInRange: function (date, mode, minDate, maxDate) { if (!minDate && !maxDate) { var startDate = module.get.startDate(); minDate = startDate && settings.minDate ? new Date(Math.max(startDate, settings.minDate)) : startDate || settings.minDate; maxDate = settings.maxDate; } minDate = minDate && new Date(minDate.getFullYear(), minDate.getMonth(), minDate.getDate(), minDate.getHours(), 5 * Math.ceil(minDate.getMinutes() / 5)); return !(!date || (minDate && module.helper.dateDiff(date, minDate, mode) > 0) || (maxDate && module.helper.dateDiff(maxDate, date, mode) > 0)); }, dateInRange: function (date, minDate, maxDate) { if (!minDate && !maxDate) { var startDate = module.get.startDate(); minDate = startDate && settings.minDate ? new Date(Math.max(startDate, settings.minDate)) : startDate || settings.minDate; maxDate = settings.maxDate; } minDate = minDate && new Date(minDate.getFullYear(), minDate.getMonth(), minDate.getDate(), minDate.getHours(), 5 * Math.ceil(minDate.getMinutes() / 5)); var isTimeOnly = settings.type === 'time'; return !date ? date : (minDate && module.helper.dateDiff(date, minDate, 'minute') > 0) ? (isTimeOnly ? module.helper.mergeDateTime(date, minDate) : minDate) : (maxDate && module.helper.dateDiff(maxDate, date, 'minute') > 0) ? (isTimeOnly ? module.helper.mergeDateTime(date, maxDate) : maxDate) : date; }, mergeDateTime: function (date, time) { return (!date || !time) ? time : new Date(date.getFullYear(), date.getMonth(), date.getDate(), time.getHours(), time.getMinutes()); } }, setting: function (name, value) { module.debug('Changing setting', name, value); if ($.isPlainObject(name)) { $.extend(true, settings, name); } else if (value !== undefined) { if ($.isPlainObject(settings[name])) { $.extend(true, settings[name], value); } else { settings[name] = value; } } else { return settings[name]; } }, internal: function (name, value) { if( $.isPlainObject(name) ) { $.extend(true, module, name); } else if(value !== undefined) { module[name] = value; } else { return module[name]; } }, debug: function () { if (!settings.silent && settings.debug) { if (settings.performance) { module.performance.log(arguments); } else { module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.debug.apply(console, arguments); } } }, verbose: function () { if (!settings.silent && settings.verbose && settings.debug) { if (settings.performance) { module.performance.log(arguments); } else { module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.verbose.apply(console, arguments); } } }, error: function () { if (!settings.silent) { module.error = Function.prototype.bind.call(console.error, console, settings.name + ':'); module.error.apply(console, arguments); } }, performance: { log: function (message) { var currentTime, executionTime, previousTime ; if (settings.performance) { currentTime = new Date().getTime(); previousTime = time || currentTime; executionTime = currentTime - previousTime; time = currentTime; performance.push({ 'Name': message[0], 'Arguments': [].slice.call(message, 1) || '', 'Element': element, 'Execution Time': executionTime }); } clearTimeout(module.performance.timer); module.performance.timer = setTimeout(module.performance.display, 500); }, display: function () { var title = settings.name + ':', totalTime = 0 ; time = false; clearTimeout(module.performance.timer); $.each(performance, function (index, data) { totalTime += data['Execution Time']; }); title += ' ' + totalTime + 'ms'; if (moduleSelector) { title += ' \'' + moduleSelector + '\''; } if ((console.group !== undefined || console.table !== undefined) && performance.length > 0) { console.groupCollapsed(title); if (console.table) { console.table(performance); } else { $.each(performance, function (index, data) { console.log(data['Name'] + ': ' + data['Execution Time'] + 'ms'); }); } console.groupEnd(); } performance = []; } }, invoke: function (query, passedArguments, context) { var object = instance, maxDepth, found, response ; passedArguments = passedArguments || queryArguments; context = element || context; if (typeof query == 'string' && object !== undefined) { query = query.split(/[\. ]/); maxDepth = query.length - 1; $.each(query, function (depth, value) { var camelCaseValue = (depth != maxDepth) ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1) : query ; if ($.isPlainObject(object[camelCaseValue]) && (depth != maxDepth)) { object = object[camelCaseValue]; } else if (object[camelCaseValue] !== undefined) { found = object[camelCaseValue]; return false; } else if ($.isPlainObject(object[value]) && (depth != maxDepth)) { object = object[value]; } else if (object[value] !== undefined) { found = object[value]; return false; } else { module.error(error.method, query); return false; } }); } if ($.isFunction(found)) { response = found.apply(context, passedArguments); } else if (found !== undefined) { response = found; } if ($.isArray(returnedValue)) { returnedValue.push(response); } else if (returnedValue !== undefined) { returnedValue = [returnedValue, response]; } else if (response !== undefined) { returnedValue = response; } return found; } }; if (methodInvoked) { if (instance === undefined) { module.initialize(); } module.invoke(query); } else { if (instance !== undefined) { instance.invoke('destroy'); } module.initialize(); } }) ; return (returnedValue !== undefined) ? returnedValue : this ; }; $.fn.calendar.settings = { name : 'Calendar', namespace : 'calendar', silent: false, debug: false, verbose: false, performance: false, type : 'datetime', // picker type, can be 'datetime', 'date', 'time', 'month', or 'year' firstDayOfWeek : 0, // day for first day column (0 = Sunday) constantHeight : true, // add rows to shorter months to keep day calendar height consistent (6 rows) today : false, // show a 'today/now' button at the bottom of the calendar closable : true, // close the popup after selecting a date/time monthFirst : true, // month before day when parsing/converting date from/to text touchReadonly : true, // set input to readonly on touch devices inline : false, // create the calendar inline instead of inside a popup on : null, // when to show the popup (defaults to 'focus' for input, 'click' for others) initialDate : null, // date to display initially when no date is selected (null = now) startMode : false, // display mode to start in, can be 'year', 'month', 'day', 'hour', 'minute' (false = 'day') minDate : null, // minimum date/time that can be selected, dates/times before are disabled maxDate : null, // maximum date/time that can be selected, dates/times after are disabled ampm : true, // show am/pm in time mode disableYear : false, // disable year selection mode disableMonth : false, // disable month selection mode disableMinute : false, // disable minute selection mode formatInput : true, // format the input text upon input blur and module creation startCalendar : null, // jquery object or selector for another calendar that represents the start date of a date range endCalendar : null, // jquery object or selector for another calendar that represents the end date of a date range multiMonth : 1, // show multiple months when in 'day' mode showWeekNumbers: null, // show Number of Week at the very first column of a dayView // popup options ('popup', 'on', 'hoverable', and show/hide callbacks are overridden) popupOptions: { position: 'bottom left', lastResort: 'bottom left', prefer: 'opposite', hideOnScroll: false }, text: { days: ['S', 'M', 'T', 'W', 'T', 'F', 'S'], months: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], monthsShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], today: 'Today', now: 'Now', am: 'AM', pm: 'PM', weekNo: 'Week' }, formatter: { header: function (date, mode, settings) { return mode === 'year' ? settings.formatter.yearHeader(date, settings) : mode === 'month' ? settings.formatter.monthHeader(date, settings) : mode === 'day' ? settings.formatter.dayHeader(date, settings) : mode === 'hour' ? settings.formatter.hourHeader(date, settings) : settings.formatter.minuteHeader(date, settings); }, yearHeader: function (date, settings) { var decadeYear = Math.ceil(date.getFullYear() / 10) * 10; return (decadeYear - 9) + ' - ' + (decadeYear + 2); }, monthHeader: function (date, settings) { return date.getFullYear(); }, dayHeader: function (date, settings) { var month = settings.text.months[date.getMonth()]; var year = date.getFullYear(); return month + ' ' + year; }, hourHeader: function (date, settings) { return settings.formatter.date(date, settings); }, minuteHeader: function (date, settings) { return settings.formatter.date(date, settings); }, dayColumnHeader: function (day, settings) { return settings.text.days[day]; }, datetime: function (date, settings) { if (!date) { return ''; } var day = settings.type === 'time' ? '' : settings.formatter.date(date, settings); var time = settings.type.indexOf('time') < 0 ? '' : settings.formatter.time(date, settings, false); var separator = settings.type === 'datetime' ? ' ' : ''; return day + separator + time; }, date: function (date, settings) { if (!date) { return ''; } var day = date.getDate(); var month = settings.text.months[date.getMonth()]; var year = date.getFullYear(); return settings.type === 'year' ? year : settings.type === 'month' ? month + ' ' + year : (settings.monthFirst ? month + ' ' + day : day + ' ' + month) + ', ' + year; }, time: function (date, settings, forCalendar) { if (!date) { return ''; } var hour = date.getHours(); var minute = date.getMinutes(); var ampm = ''; if (settings.ampm) { ampm = ' ' + (hour < 12 ? settings.text.am : settings.text.pm); hour = hour === 0 ? 12 : hour > 12 ? hour - 12 : hour; } return hour + ':' + (minute < 10 ? '0' : '') + minute + ampm; }, today: function (settings) { return settings.type === 'date' ? settings.text.today : settings.text.now; }, cell: function (cell, date, cellOptions) { } }, parser: { date: function (text, settings) { if (!text) { return null; } text = ('' + text).trim().toLowerCase(); if (text.length === 0) { return null; } var i, j, k; var minute = -1, hour = -1, day = -1, month = -1, year = -1; var isAm = undefined; var isTimeOnly = settings.type === 'time'; var isDateOnly = settings.type.indexOf('time') < 0; var words = text.split(settings.regExp.dateWords); var numbers = text.split(settings.regExp.dateNumbers); if (!isDateOnly) { //am/pm isAm = $.inArray(settings.text.am.toLowerCase(), words) >= 0 ? true : $.inArray(settings.text.pm.toLowerCase(), words) >= 0 ? false : undefined; //time with ':' for (i = 0; i < numbers.length; i++) { var number = numbers[i]; if (number.indexOf(':') >= 0) { if (hour < 0 || minute < 0) { var parts = number.split(':'); for (k = 0; k < Math.min(2, parts.length); k++) { j = parseInt(parts[k]); if (isNaN(j)) { j = 0; } if (k === 0) { hour = j % 24; } else { minute = j % 60; } } } numbers.splice(i, 1); } } } if (!isTimeOnly) { //textual month for (i = 0; i < words.length; i++) { var word = words[i]; if (word.length <= 0) { continue; } word = word.substring(0, Math.min(word.length, 3)); for (j = 0; j < settings.text.months.length; j++) { var monthString = settings.text.months[j]; monthString = monthString.substring(0, Math.min(word.length, Math.min(monthString.length, 3))).toLowerCase(); if (monthString === word) { month = j + 1; break; } } if (month >= 0) { break; } } //year > 59 for (i = 0; i < numbers.length; i++) { j = parseInt(numbers[i]); if (isNaN(j)) { continue; } if (j > 59) { year = j; numbers.splice(i, 1); break; } } //numeric month if (month < 0) { for (i = 0; i < numbers.length; i++) { k = i > 1 || settings.monthFirst ? i : i === 1 ? 0 : 1; j = parseInt(numbers[k]); if (isNaN(j)) { continue; } if (1 <= j && j <= 12) { month = j; numbers.splice(k, 1); break; } } } //day for (i = 0; i < numbers.length; i++) { j = parseInt(numbers[i]); if (isNaN(j)) { continue; } if (1 <= j && j <= 31) { day = j; numbers.splice(i, 1); break; } } //year <= 59 if (year < 0) { for (i = numbers.length - 1; i >= 0; i--) { j = parseInt(numbers[i]); if (isNaN(j)) { continue; } if (j < 99) { j += 2000; } year = j; numbers.splice(i, 1); break; } } } if (!isDateOnly) { //hour if (hour < 0) { for (i = 0; i < numbers.length; i++) { j = parseInt(numbers[i]); if (isNaN(j)) { continue; } if (0 <= j && j <= 23) { hour = j; numbers.splice(i, 1); break; } } } //minute if (minute < 0) { for (i = 0; i < numbers.length; i++) { j = parseInt(numbers[i]); if (isNaN(j)) { continue; } if (0 <= j && j <= 59) { minute = j; numbers.splice(i, 1); break; } } } } if (minute < 0 && hour < 0 && day < 0 && month < 0 && year < 0) { return null; } if (minute < 0) { minute = 0; } if (hour < 0) { hour = 0; } if (day < 0) { day = 1; } if (month < 0) { month = 1; } if (year < 0) { year = new Date().getFullYear(); } if (isAm !== undefined) { if (isAm) { if (hour === 12) { hour = 0; } } else if (hour < 12) { hour += 12; } } var date = new Date(year, month - 1, day, hour, minute); if (date.getMonth() !== month - 1 || date.getFullYear() !== year) { //month or year don't match up, switch to last day of the month date = new Date(year, month, 0, hour, minute); } return isNaN(date.getTime()) ? null : date; } }, // callback when date changes, return false to cancel the change onChange: function (date, text, mode) { return true; }, // callback before show animation, return false to prevent show onShow: function () { }, // callback after show animation onVisible: function () { }, // callback before hide animation, return false to prevent hide onHide: function () { }, // callback after hide animation onHidden: function () { }, // is the given date disabled? isDisabled: function (date, mode) { return false; }, selector: { popup: '.ui.popup', input: 'input', activator: 'input' }, regExp: { dateWords: /[^A-Za-z\u00C0-\u024F]+/g, dateNumbers: /[^\d:]+/g }, error: { popup: 'UI Popup, a required component is not included in this page', method: 'The method you called is not defined.' }, className: { calendar: 'calendar', active: 'active', popup: 'ui popup', grid: 'ui equal width grid', column: 'column', table: 'ui celled center aligned unstackable table', prev: 'prev link', next: 'next link', prevIcon: 'chevron left icon', nextIcon: 'chevron right icon', link: 'link', cell: 'link', disabledCell: 'disabled', adjacentCell: 'adjacent', activeCell: 'active', rangeCell: 'range', focusCell: 'focus', todayCell: 'today', today: 'today link' }, metadata: { date: 'date', focusDate: 'focusDate', startDate: 'startDate', endDate: 'endDate', minDate: 'minDate', maxDate: 'maxDate', mode: 'mode', monthOffset: 'monthOffset' } }; })(jQuery, window, document);
Tinytest.add('EasySearch - Unit - Core - ReactiveEngine', function (test) { var CustomReactiveEngine = TestHelpers.createReactiveEngine({ getSearchCursor: function (s, o) { test.equal(s, { name: 'testCursor' }); test.equal(o.foo, 'bar'); return new EasySearch.Cursor(new Mongo.Cursor(), 155); } }); test.throws(function () { new EasySearch.ReactiveEngine(); }); var engineInstance = new CustomReactiveEngine(), indexConfig = { name: 'testIndex' }; engineInstance.onIndexCreate(indexConfig); if (Meteor.isClient) { var counter = engineInstance.search('test', { index: { fields: ['name'], searchCollection: { find: function (d, o) { test.equal(d, 'test'); test.equal(o, { limit: 9 }); return new EasySearch.Cursor(new Mongo.Cursor(), 777); } } }, search: { limit: 9 } }); test.equal(counter.count(), 777); } else if (Meteor.isServer) { var cursor = engineInstance.search('testCursor', { foo: 'bar', index: { fields: ['name'] } }); test.instanceOf(cursor, EasySearch.Cursor); test.equal(cursor.count(), 155); } });
import conf from '../../conf/index' describe('close', () => { it('should close the current window', async function () { /** * safari doenst support `newWindow` */ if (this.client.desiredCapabilities.browserName === 'safari') { return } // get current tab id const openTab = (await this.client.getTabIds())[0] // open new tab await this.client.newWindow(conf.testPage.subPage).pause(1000); // ensure that there are two tabs open (await this.client.getTabIds()).should.have.length(2) // close window await this.client.close().pause(1000); (await this.client.getTabIds()).should.have.length(1); // test if there is only one tab open (await this.client.windowHandle()).value.should.be.equal(openTab) }) })
/** * @license * v1.2.10-4 * MIT (https://github.com/pnp/pnpjs/blob/master/LICENSE) * Copyright (c) 2019 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/sp-clientsvc'), require('@pnp/common'), require('@pnp/sp')) : typeof define === 'function' && define.amd ? define(['exports', '@pnp/sp-clientsvc', '@pnp/common', '@pnp/sp'], factory) : (factory((global.pnp = global.pnp || {}, global.pnp['sp-taxonomy'] = {}),global.pnp['sp-clientsvc'],global.pnp.common,global.pnp.sp)); }(this, (function (exports,spClientsvc,common,sp) { '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 __()); } /** * Represents a collection of labels */ var Labels = /** @class */ (function (_super) { __extends(Labels, _super); function Labels(parent, _objectPaths) { if (parent === void 0) { parent = ""; } if (_objectPaths === void 0) { _objectPaths = null; } var _this = _super.call(this, parent, _objectPaths) || this; _this._objectPaths.add(spClientsvc.property("Labels")); return _this; } /** * Gets a label from the collection by its value * * @param value The value to retrieve */ Labels.prototype.getByValue = function (value) { var params = spClientsvc.MethodParams.build().string(value); return this.getChild(Label, "GetByValue", params); }; /** * Loads the data and merges with with the ILabel instances */ Labels.prototype.get = function () { var _this = this; return this.sendGetCollection(function (d) { if (!common.stringIsNullOrEmpty(d.Value)) { return _this.getByValue(d.Value); } throw Error("Could not find Value in Labels.get(). You must include at least one of these in your select fields."); }); }; return Labels; }(spClientsvc.ClientSvcQueryable)); /** * Represents a label instance */ var Label = /** @class */ (function (_super) { __extends(Label, _super); function Label() { return _super !== null && _super.apply(this, arguments) || this; } /** * Gets the data for this Label */ Label.prototype.get = function () { return this.sendGet(Label); }; /** * Sets this label as the default */ Label.prototype.setAsDefaultForLanguage = function () { return this.invokeNonQuery("SetAsDefaultForLanguage"); }; /** * Deletes this label */ Label.prototype.delete = function () { return this.invokeNonQuery("DeleteObject"); }; return Label; }(spClientsvc.ClientSvcQueryable)); var Terms = /** @class */ (function (_super) { __extends(Terms, _super); function Terms() { return _super !== null && _super.apply(this, arguments) || this; } /** * Gets the terms in this collection */ Terms.prototype.get = function () { var _this = this; return this.sendGetCollection(function (d) { if (!common.stringIsNullOrEmpty(d.Name)) { return _this.getByName(d.Name); } else if (!common.stringIsNullOrEmpty(d.Id)) { return _this.getById(d.Id); } throw Error("Could not find Name or Id in Terms.get(). You must include at least one of these in your select fields."); }); }; /** * Gets a term by id * * @param id The id of the term */ Terms.prototype.getById = function (id) { var params = spClientsvc.MethodParams.build() .string(common.sanitizeGuid(id)); return this.getChild(Term, "GetById", params); }; /** * Gets a term by name * * @param name Term name */ Terms.prototype.getByName = function (name) { var params = spClientsvc.MethodParams.build() .string(name); return this.getChild(Term, "GetByName", params); }; return Terms; }(spClientsvc.ClientSvcQueryable)); /** * Represents the operations available on a given term */ var Term = /** @class */ (function (_super) { __extends(Term, _super); function Term() { return _super !== null && _super.apply(this, arguments) || this; } Term.prototype.addTerm = function (name, lcid, isAvailableForTagging, id) { var _this = this; if (isAvailableForTagging === void 0) { isAvailableForTagging = true; } if (id === void 0) { id = common.getGUID(); } var params = spClientsvc.MethodParams.build() .string(name) .number(lcid) .string(common.sanitizeGuid(id)); this._useCaching = false; return this.invokeMethod("CreateTerm", params, spClientsvc.setProperty("IsAvailableForTagging", "Boolean", "" + isAvailableForTagging)) .then(function (r) { return common.extend(_this.termSet.getTermById(r.Id), r); }); }; Object.defineProperty(Term.prototype, "terms", { get: function () { return this.getChildProperty(Terms, "Terms"); }, enumerable: true, configurable: true }); Object.defineProperty(Term.prototype, "labels", { get: function () { return new Labels(this); }, enumerable: true, configurable: true }); Object.defineProperty(Term.prototype, "parent", { get: function () { return this.getChildProperty(Term, "Parent"); }, enumerable: true, configurable: true }); Object.defineProperty(Term.prototype, "pinSourceTermSet", { get: function () { return this.getChildProperty(TermSet, "PinSourceTermSet"); }, enumerable: true, configurable: true }); Object.defineProperty(Term.prototype, "reusedTerms", { get: function () { return this.getChildProperty(Terms, "ReusedTerms"); }, enumerable: true, configurable: true }); Object.defineProperty(Term.prototype, "sourceTerm", { get: function () { return this.getChildProperty(Term, "SourceTerm"); }, enumerable: true, configurable: true }); Object.defineProperty(Term.prototype, "termSet", { get: function () { return this.getChildProperty(TermSet, "TermSet"); }, enumerable: true, configurable: true }); Object.defineProperty(Term.prototype, "termSets", { get: function () { return this.getChildProperty(TermSets, "TermSets"); }, enumerable: true, configurable: true }); /** * Creates a new label for this Term * * @param name label value * @param lcid language code * @param isDefault Is the default label */ Term.prototype.createLabel = function (name, lcid, isDefault) { var _this = this; if (isDefault === void 0) { isDefault = false; } var params = spClientsvc.MethodParams.build() .string(name) .number(lcid) .boolean(isDefault); this._useCaching = false; return this.invokeMethod("CreateLabel", params) .then(function (r) { return common.extend(_this.labels.getByValue(name), r); }); }; /** * Sets the deprecation flag on a term * * @param doDeprecate New value for the deprecation flag */ Term.prototype.deprecate = function (doDeprecate) { var params = spClientsvc.MethodParams.build().boolean(doDeprecate); return this.invokeNonQuery("Deprecate", params); }; /** * Loads the term data */ Term.prototype.get = function () { return this.sendGet(Term); }; /** * Gets the appropriate description for a term * * @param lcid Language code */ Term.prototype.getDescription = function (lcid) { var params = spClientsvc.MethodParams.build().number(lcid); return this.invokeMethodAction("GetDescription", params); }; /** * Sets the description * * @param description Term description * @param lcid Language code */ Term.prototype.setDescription = function (description, lcid) { var params = spClientsvc.MethodParams.build().string(description).number(lcid); return this.invokeNonQuery("SetDescription", params); }; /** * Sets a custom property on this term * * @param name Property name * @param value Property value */ Term.prototype.setLocalCustomProperty = function (name, value) { var params = spClientsvc.MethodParams.build().string(name).string(value); return this.invokeNonQuery("SetLocalCustomProperty", params); }; /** * Updates the specified properties of this term, not all properties can be updated * * @param properties Plain object representing the properties and new values to update */ Term.prototype.update = function (properties) { return this.invokeUpdate(properties, Term); }; return Term; }(spClientsvc.ClientSvcQueryable)); var TermSets = /** @class */ (function (_super) { __extends(TermSets, _super); function TermSets() { return _super !== null && _super.apply(this, arguments) || this; } /** * Gets the termsets in this collection */ TermSets.prototype.get = function () { var _this = this; return this.sendGetCollection(function (d) { if (!common.stringIsNullOrEmpty(d.Name)) { return _this.getByName(d.Name); } else if (!common.stringIsNullOrEmpty(d.Id)) { return _this.getById(d.Id); } throw Error("Could not find Value in Labels.get(). You must include at least one of these in your select fields."); }); }; /** * Gets a TermSet from this collection by id * * @param id TermSet id */ TermSets.prototype.getById = function (id) { var params = spClientsvc.MethodParams.build() .string(common.sanitizeGuid(id)); return this.getChild(TermSet, "GetById", params); }; /** * Gets a TermSet from this collection by name * * @param name TermSet name */ TermSets.prototype.getByName = function (name) { var params = spClientsvc.MethodParams.build() .string(name); return this.getChild(TermSet, "GetByName", params); }; return TermSets; }(spClientsvc.ClientSvcQueryable)); var TermSet = /** @class */ (function (_super) { __extends(TermSet, _super); function TermSet() { return _super !== null && _super.apply(this, arguments) || this; } Object.defineProperty(TermSet.prototype, "group", { /** * Gets the group containing this Term set */ get: function () { return this.getChildProperty(TermGroup, "Group"); }, enumerable: true, configurable: true }); Object.defineProperty(TermSet.prototype, "terms", { /** * Access all the terms in this termset */ get: function () { return this.getChild(Terms, "GetAllTerms", null); }, enumerable: true, configurable: true }); /** * Adds a stakeholder to the TermSet * * @param stakeholderName The login name of the user to be added as a stakeholder */ TermSet.prototype.addStakeholder = function (stakeholderName) { var params = spClientsvc.MethodParams.build() .string(stakeholderName); return this.invokeNonQuery("DeleteStakeholder", params); }; /** * Deletes a stakeholder to the TermSet * * @param stakeholderName The login name of the user to be added as a stakeholder */ TermSet.prototype.deleteStakeholder = function (stakeholderName) { var params = spClientsvc.MethodParams.build() .string(stakeholderName); return this.invokeNonQuery("AddStakeholder", params); }; /** * Gets the data for this TermSet */ TermSet.prototype.get = function () { return this.sendGet(TermSet); }; /** * Get a term by id * * @param id Term id */ TermSet.prototype.getTermById = function (id) { var params = spClientsvc.MethodParams.build() .string(common.sanitizeGuid(id)); return this.getChild(Term, "GetTerm", params); }; /** * Adds a term to this term set * * @param name Name for the term * @param lcid Language code * @param isAvailableForTagging set tagging availability (default: true) * @param id GUID id for the term (optional) */ TermSet.prototype.addTerm = function (name, lcid, isAvailableForTagging, id) { var _this = this; if (isAvailableForTagging === void 0) { isAvailableForTagging = true; } if (id === void 0) { id = common.getGUID(); } var params = spClientsvc.MethodParams.build() .string(name) .number(lcid) .string(common.sanitizeGuid(id)); this._useCaching = false; return this.invokeMethod("CreateTerm", params, spClientsvc.setProperty("IsAvailableForTagging", "Boolean", "" + isAvailableForTagging)) .then(function (r) { return common.extend(_this.getTermById(r.Id), r); }); }; /** * Copies this term set immediately */ TermSet.prototype.copy = function () { return this.invokeMethod("Copy", null); }; /** * Updates the specified properties of this term set, not all properties can be updated * * @param properties Plain object representing the properties and new values to update */ TermSet.prototype.update = function (properties) { return this.invokeUpdate(properties, TermSet); }; return TermSet; }(spClientsvc.ClientSvcQueryable)); /** * Term Groups collection in Term Store */ var TermGroups = /** @class */ (function (_super) { __extends(TermGroups, _super); function TermGroups() { return _super !== null && _super.apply(this, arguments) || this; } /** * Gets the groups in this collection */ TermGroups.prototype.get = function () { var _this = this; return this.sendGetCollection(function (d) { if (!common.stringIsNullOrEmpty(d.Name)) { return _this.getByName(d.Name); } else if (!common.stringIsNullOrEmpty(d.Id)) { return _this.getById(d.Id); } throw Error("Could not find Name or Id in TermGroups.get(). You must include at least one of these in your select fields."); }); }; /** * Gets a TermGroup from this collection by id * * @param id TermGroup id */ TermGroups.prototype.getById = function (id) { var params = spClientsvc.MethodParams.build() .string(common.sanitizeGuid(id)); return this.getChild(TermGroup, "GetById", params); }; /** * Gets a TermGroup from this collection by name * * @param name TErmGroup name */ TermGroups.prototype.getByName = function (name) { var params = spClientsvc.MethodParams.build() .string(name); return this.getChild(TermGroup, "GetByName", params); }; return TermGroups; }(spClientsvc.ClientSvcQueryable)); /** * Represents a group in the taxonomy heirarchy */ var TermGroup = /** @class */ (function (_super) { __extends(TermGroup, _super); function TermGroup(parent, _objectPaths) { if (parent === void 0) { parent = ""; } var _this = _super.call(this, parent, _objectPaths) || this; // this should mostly be true _this.store = parent instanceof TermStore ? parent : null; return _this; } Object.defineProperty(TermGroup.prototype, "termSets", { /** * Gets the collection of term sets in this group */ get: function () { return this.getChildProperty(TermSets, "TermSets"); }, enumerable: true, configurable: true }); /** * Adds a contributor to the Group * * @param principalName The login name of the user to be added as a contributor */ TermGroup.prototype.addContributor = function (principalName) { var params = spClientsvc.MethodParams.build().string(principalName); return this.invokeNonQuery("AddContributor", params); }; /** * Adds a group manager to the Group * * @param principalName The login name of the user to be added as a group manager */ TermGroup.prototype.addGroupManager = function (principalName) { var params = spClientsvc.MethodParams.build().string(principalName); return this.invokeNonQuery("AddGroupManager", params); }; /** * Creates a new TermSet in this Group using the provided language and unique identifier * * @param name The name of the new TermSet being created * @param lcid The language that the new TermSet name is in * @param id The unique identifier of the new TermSet being created (optional) */ TermGroup.prototype.createTermSet = function (name, lcid, id) { var _this = this; if (id === void 0) { id = common.getGUID(); } var params = spClientsvc.MethodParams.build() .string(name) .string(common.sanitizeGuid(id)) .number(lcid); this._useCaching = false; return this.invokeMethod("CreateTermSet", params) .then(function (r) { return common.extend(_this.store.getTermSetById(r.Id), r); }); }; /** * Gets this term store's data */ TermGroup.prototype.get = function () { return this.sendGet(TermGroup); }; /** * Updates the specified properties of this term set, not all properties can be updated * * @param properties Plain object representing the properties and new values to update */ TermGroup.prototype.update = function (properties) { return this.invokeUpdate(properties, TermGroup); }; return TermGroup; }(spClientsvc.ClientSvcQueryable)); /** * Represents the set of available term stores and the collection methods */ var TermStores = /** @class */ (function (_super) { __extends(TermStores, _super); function TermStores(parent) { if (parent === void 0) { parent = ""; } var _this = _super.call(this, parent) || this; _this._objectPaths.add(spClientsvc.property("TermStores", // actions spClientsvc.objectPath())); return _this; } /** * Gets the term stores */ TermStores.prototype.get = function () { var _this = this; return this.sendGetCollection(function (d) { if (!common.stringIsNullOrEmpty(d.Name)) { return _this.getByName(d.Name); } else if (!common.stringIsNullOrEmpty(d.Id)) { return _this.getById(d.Id); } throw Error("Could not find Name or Id in TermStores.get(). You must include at least one of these in your select fields."); }); }; /** * Returns the TermStore specified by its index name * * @param name The index name of the TermStore to be returned */ TermStores.prototype.getByName = function (name) { return this.getChild(TermStore, "GetByName", spClientsvc.MethodParams.build().string(name)); }; /** * Returns the TermStore specified by its GUID index * * @param id The GUID index of the TermStore to be returned */ TermStores.prototype.getById = function (id) { return this.getChild(TermStore, "GetById", spClientsvc.MethodParams.build().string(common.sanitizeGuid(id))); }; return TermStores; }(spClientsvc.ClientSvcQueryable)); var TermStore = /** @class */ (function (_super) { __extends(TermStore, _super); function TermStore(parent, _objectPaths) { if (parent === void 0) { parent = ""; } if (_objectPaths === void 0) { _objectPaths = null; } return _super.call(this, parent, _objectPaths) || this; } Object.defineProperty(TermStore.prototype, "hashTagsTermSet", { get: function () { return this.getChildProperty(TermSet, "HashTagsTermSet"); }, enumerable: true, configurable: true }); Object.defineProperty(TermStore.prototype, "keywordsTermSet", { get: function () { return this.getChildProperty(TermSet, "KeywordsTermSet"); }, enumerable: true, configurable: true }); Object.defineProperty(TermStore.prototype, "orphanedTermsTermSet", { get: function () { return this.getChildProperty(TermSet, "OrphanedTermsTermSet"); }, enumerable: true, configurable: true }); Object.defineProperty(TermStore.prototype, "systemGroup", { get: function () { return this.getChildProperty(TermGroup, "SystemGroup"); }, enumerable: true, configurable: true }); Object.defineProperty(TermStore.prototype, "groups", { get: function () { return this.getChildProperty(TermGroups, "Groups"); }, enumerable: true, configurable: true }); /** * Gets the term store data */ TermStore.prototype.get = function () { return this.sendGet(TermStore); }; /** * Gets term sets * * @param name * @param lcid */ TermStore.prototype.getTermSetsByName = function (name, lcid) { var params = spClientsvc.MethodParams.build() .string(name) .number(lcid); return this.getChild(TermSets, "GetTermSetsByName", params); }; /** * Provides access to an ITermSet by id * * @param id */ TermStore.prototype.getTermSetById = function (id) { var params = spClientsvc.MethodParams.build().string(common.sanitizeGuid(id)); return this.getChild(TermSet, "GetTermSet", params); }; /** * Provides access to an ITermSet by id * * @param id */ TermStore.prototype.getTermById = function (id) { var params = spClientsvc.MethodParams.build().string(common.sanitizeGuid(id)); return this.getChild(Term, "GetTerm", params); }; /** * Provides access to an ITermSet by id * * @param id */ TermStore.prototype.getTermsById = function () { var ids = []; for (var _i = 0; _i < arguments.length; _i++) { ids[_i] = arguments[_i]; } var params = spClientsvc.MethodParams.build().strArray(ids.map(function (id) { return common.sanitizeGuid(id); })); return this.getChild(Terms, "GetTermsById", params); }; /** * Gets a term from a term set based on the supplied ids * * @param termId Term Id * @param termSetId Termset Id */ TermStore.prototype.getTermInTermSet = function (termId, termSetId) { var params = spClientsvc.MethodParams.build().string(common.sanitizeGuid(termId)).string(common.sanitizeGuid(termSetId)); return this.getChild(Term, "GetTermInTermSet", params); }; /** * This method provides access to a ITermGroup by id * * @param id The group id */ TermStore.prototype.getTermGroupById = function (id) { var params = spClientsvc.MethodParams.build() .string(common.sanitizeGuid(id)); return this.getChild(TermGroup, "GetGroup", params); }; /** * Gets the terms by the supplied information (see: https://msdn.microsoft.com/en-us/library/hh626704%28v=office.12%29.aspx) * * @param info */ TermStore.prototype.getTerms = function (info) { var objectPaths = this._objectPaths.copy(); // this will be the parent of the GetTerms call, but we need to create the input param first var parentIndex = objectPaths.lastIndex; // this is our input object var input = spClientsvc.objConstructor.apply(void 0, ["{61a1d689-2744-4ea3-a88b-c95bee9803aa}", // actions spClientsvc.objectPath()].concat(spClientsvc.objectProperties(info))); // add the input object path var inputIndex = objectPaths.add(input); // this sets up the GetTerms call var params = spClientsvc.MethodParams.build().objectPath(inputIndex); // call the method var methodIndex = objectPaths.add(spClientsvc.method("GetTerms", params, // actions spClientsvc.objectPath())); // setup the parent relationship even though they are seperated in the collection objectPaths.addChildRelationship(parentIndex, methodIndex); return new Terms(this, objectPaths); }; /** * Gets the site collection group associated with the current site * * @param createIfMissing If true the group will be created, otherwise null (default: false) */ TermStore.prototype.getSiteCollectionGroup = function (createIfMissing) { if (createIfMissing === void 0) { createIfMissing = false; } var objectPaths = this._objectPaths.copy(); var methodParent = objectPaths.lastIndex; var siteIndex = objectPaths.siteIndex; var params = spClientsvc.MethodParams.build().objectPath(siteIndex).boolean(createIfMissing); var methodIndex = objectPaths.add(spClientsvc.method("GetSiteCollectionGroup", params, // actions spClientsvc.objectPath())); // the parent of this method call is this instance, not the current/site objectPaths.addChildRelationship(methodParent, methodIndex); return new TermGroup(this, objectPaths); }; /** * Adds a working language to the TermStore * * @param lcid The locale identifier of the working language to add */ TermStore.prototype.addLanguage = function (lcid) { var params = spClientsvc.MethodParams.build().number(lcid); return this.invokeNonQuery("AddLanguage", params); }; /** * Creates a new Group in this TermStore * * @param name The name of the new Group being created * @param id The ID (Guid) that the new group should have */ TermStore.prototype.addGroup = function (name, id) { var _this = this; if (id === void 0) { id = common.getGUID(); } var params = spClientsvc.MethodParams.build() .string(name) .string(common.sanitizeGuid(id)); this._useCaching = false; return this.invokeMethod("CreateGroup", params) .then(function (r) { return common.extend(_this.getTermGroupById(r.Id), r); }); }; /** * Commits all updates to the database that have occurred since the last commit or rollback */ TermStore.prototype.commitAll = function () { return this.invokeNonQuery("CommitAll"); }; /** * Delete a working language from the TermStore * * @param lcid locale ID for the language to be deleted */ TermStore.prototype.deleteLanguage = function (lcid) { var params = spClientsvc.MethodParams.build().number(lcid); return this.invokeNonQuery("DeleteLanguage", params); }; /** * Discards all updates that have occurred since the last commit or rollback */ TermStore.prototype.rollbackAll = function () { return this.invokeNonQuery("RollbackAll"); }; /** * Updates the cache */ TermStore.prototype.updateCache = function () { return this.invokeNonQuery("UpdateCache"); }; /** * Updates the specified properties of this term set, not all properties can be updated * * @param properties Plain object representing the properties and new values to update */ TermStore.prototype.update = function (properties) { return this.invokeUpdate(properties, TermStore); }; /** * This method makes sure that this instance is aware of all child terms that are used in the current site collection */ TermStore.prototype.updateUsedTermsOnSite = function () { var objectPaths = this._objectPaths.copy(); var methodParent = objectPaths.lastIndex; var siteIndex = objectPaths.siteIndex; var params = spClientsvc.MethodParams.build().objectPath(siteIndex); var methodIndex = objectPaths.add(spClientsvc.method("UpdateUsedTermsOnSite", params)); // the parent of this method call is this instance, not the current context/site objectPaths.addChildRelationship(methodParent, methodIndex); return this.send(objectPaths); }; /** * Gets a list of changes * * @param info Lookup information */ TermStore.prototype.getChanges = function (info) { var objectPaths = this._objectPaths.copy(); var methodParent = objectPaths.lastIndex; var inputIndex = objectPaths.add(spClientsvc.objConstructor.apply(void 0, ["{1f849fb0-4fcb-4a54-9b01-9152b9e482d3}", // actions spClientsvc.objectPath()].concat(spClientsvc.objectProperties(info)))); var params = spClientsvc.MethodParams.build().objectPath(inputIndex); var methodIndex = objectPaths.add(spClientsvc.method("GetChanges", params, // actions spClientsvc.objectPath(), spClientsvc.opQuery([], this.getSelects()))); objectPaths.addChildRelationship(methodParent, methodIndex); return this.send(objectPaths); }; return TermStore; }(spClientsvc.ClientSvcQueryable)); /** * The root taxonomy object */ var Session = /** @class */ (function (_super) { __extends(Session, _super); function Session(webUrl) { if (webUrl === void 0) { webUrl = ""; } var _this = _super.call(this, webUrl) || this; // everything starts with the session _this._objectPaths.add(spClientsvc.staticMethod("GetTaxonomySession", "{981cbc68-9edc-4f8d-872f-71146fcbb84f}", // actions spClientsvc.objectPath())); return _this; } Object.defineProperty(Session.prototype, "termStores", { /** * The collection of term stores */ get: function () { return new TermStores(this); }, enumerable: true, configurable: true }); /** * Provides access to sp.setup from @pnp/sp * * @param config Configuration */ Session.prototype.setup = function (config) { sp.sp.setup(config); }; /** * Creates a new batch */ Session.prototype.createBatch = function () { return new spClientsvc.ObjectPathBatch(this.toUrl()); }; /** * Gets the default keyword termstore for this session */ Session.prototype.getDefaultKeywordTermStore = function () { return this.getChild(TermStore, "GetDefaultKeywordsTermStore", null); }; /** * Gets the default site collection termstore for this session */ Session.prototype.getDefaultSiteCollectionTermStore = function () { return this.getChild(TermStore, "GetDefaultSiteCollectionTermStore", null); }; return Session; }(spClientsvc.ClientSvcQueryable)); (function (StringMatchOption) { StringMatchOption[StringMatchOption["StartsWith"] = 0] = "StartsWith"; StringMatchOption[StringMatchOption["ExactMatch"] = 1] = "ExactMatch"; })(exports.StringMatchOption || (exports.StringMatchOption = {})); (function (ChangedItemType) { ChangedItemType[ChangedItemType["Unknown"] = 0] = "Unknown"; ChangedItemType[ChangedItemType["Term"] = 1] = "Term"; ChangedItemType[ChangedItemType["TermSet"] = 2] = "TermSet"; ChangedItemType[ChangedItemType["Group"] = 3] = "Group"; ChangedItemType[ChangedItemType["TermStore"] = 4] = "TermStore"; ChangedItemType[ChangedItemType["Site"] = 5] = "Site"; })(exports.ChangedItemType || (exports.ChangedItemType = {})); (function (ChangedOperationType) { ChangedOperationType[ChangedOperationType["Unknown"] = 0] = "Unknown"; ChangedOperationType[ChangedOperationType["Add"] = 1] = "Add"; ChangedOperationType[ChangedOperationType["Edit"] = 2] = "Edit"; ChangedOperationType[ChangedOperationType["DeleteObject"] = 3] = "DeleteObject"; ChangedOperationType[ChangedOperationType["Move"] = 4] = "Move"; ChangedOperationType[ChangedOperationType["Copy"] = 5] = "Copy"; ChangedOperationType[ChangedOperationType["PathChange"] = 6] = "PathChange"; ChangedOperationType[ChangedOperationType["Merge"] = 7] = "Merge"; ChangedOperationType[ChangedOperationType["ImportObject"] = 8] = "ImportObject"; ChangedOperationType[ChangedOperationType["Restore"] = 9] = "Restore"; })(exports.ChangedOperationType || (exports.ChangedOperationType = {})); function setItemMetaDataField(item, fieldName, term) { if (!common.objectDefinedNotNull(term)) { return Promise.resolve(null); } var postData = {}; postData[fieldName] = { "Label": term.Name, "TermGuid": common.sanitizeGuid(term.Id), "WssId": "-1", "__metadata": { "type": "SP.Taxonomy.TaxonomyFieldValue" }, }; return item.update(postData); } function setItemMetaDataMultiField(item, fieldName) { var terms = []; for (var _i = 2; _i < arguments.length; _i++) { terms[_i - 2] = arguments[_i]; } if (terms.length < 1) { return Promise.resolve(null); } return item.list.fields.getByTitle(fieldName + "_0").select("InternalName").get().then(function (i) { var postData = {}; postData[i.InternalName] = terms.map(function (term) { return "-1;#" + term.Name + "|" + common.sanitizeGuid(term.Id) + ";#"; }).join(""); return item.update(postData); }); } // export an existing session instance var taxonomy = new Session(); exports.taxonomy = taxonomy; exports.Labels = Labels; exports.Label = Label; exports.Session = Session; exports.TermGroups = TermGroups; exports.TermGroup = TermGroup; exports.Terms = Terms; exports.Term = Term; exports.TermSets = TermSets; exports.TermSet = TermSet; exports.TermStores = TermStores; exports.TermStore = TermStore; exports.setItemMetaDataField = setItemMetaDataField; exports.setItemMetaDataMultiField = setItemMetaDataMultiField; Object.defineProperty(exports, '__esModule', { value: true }); }))); //# sourceMappingURL=sp-taxonomy.es5.umd.js.map
(function (factory) { typeof define === 'function' && define.amd ? define(factory) : factory(); }(function () { 'use strict'; function iterator(input) { let index = 0, col = 1, line = 1; return { curr(n = 0) { return input[index + n]; }, end() { return input.length <= index; }, info() { return { index, col, line }; }, index(n) { return (n === undefined ? index : index = n); }, next() { let next = input[index++]; if (next == '\n') line++, col = 0; else col++; return next; } }; } // I'll make it work first function parse(it) { let word = '', marks = []; let groups = [], result = {}; while(!it.end()) { let c = it.curr(); if (c == '(') { marks.push(c); word = ''; } else if (c == ')' || c == ',') { if (/^\-\-.+/.test(word)) { if (!result.name) { result.name = word; } else { if (!result.alternative) { result.alternative = []; } result.alternative.push({ name: word }); } } if (c == ')') { if (marks[marks.length - 1] == '(') { marks.pop(); } else { throw new Error('bad match'); } } if (c == ',') { if (!marks.length) { groups.push(result); result = {}; } } word = ''; } else if (!/\s/.test(c)) { word += c; } it.next(); } if (marks.length) { return []; } if (result.name) { groups.push(result); } return groups; } function parse_var(input) { input = input.trim(); let result = []; if (!/^var\(/.test(input)) { return result; } let it = iterator(input); try { result = parse(it); } catch (e) { console.error(e && e.message || 'Bad variables.'); } return result; } function make_array(arr) { return Array.isArray(arr) ? arr : [arr]; } function join(arr, spliter = '\n') { return (arr || []).join(spliter); } function last(arr) { return arr[arr.length - 1]; } function first(arr) { return arr[0]; } function shuffle(arr) { let ret = Array.from ? Array.from(arr) : arr.slice(); let m = arr.length; while (m) { let i = ~~(Math.random() * m--); let t = ret[m]; ret[m] = ret[i]; ret[i] = t; } return ret; } function flat_map(arr, fn) { if (Array.prototype.flatMap) return arr.flatMap(fn); return arr.reduce((acc, x) => acc.concat(fn(x)), []); } const Tokens = { func(name = '') { return { type: 'func', name, arguments: [] }; }, argument() { return { type: 'argument', value: [] }; }, text(value = '') { return { type: 'text', value }; }, pseudo(selector = '') { return { type: 'pseudo', selector, styles: [] }; }, cond(name = '') { return { type: 'cond', name, styles: [], arguments: [] }; }, rule(property = '') { return { type: 'rule', property, value: [] }; }, keyframes(name = '') { return { type: 'keyframes', name, steps: [] } }, step(name = '') { return { type: 'step', name, styles: [] } } }; const is = { white_space(c) { return /[\s\n\t]/.test(c); }, line_break(c) { return /\n/.test(c); }, number(n) { return !isNaN(n); }, pair(n) { return ['"', '(', ')', "'"].includes(n); }, pair_of(c, n) { return ({ '"': '"', "'": "'", '(': ')' })[c] == n; } }; function throw_error(msg, { col, line }) { console.error( `(at line ${ line }, column ${ col }) ${ msg }` ); } function get_text_value(input) { if (input.trim().length) { return is.number(+input) ? +input : input.trim() } else { return input; } } function read_until(fn) { return function(it, reset) { let index = it.index(); let word = ''; while (!it.end()) { let c = it.next(); if (fn(c)) break; else word += c; } if (reset) { it.index(index); } return word; } } function read_word(it, reset) { let check = c => /[^\w@]/.test(c); return read_until(check)(it, reset); } function read_keyframe_name(it) { return read_until(c => /[\s\{]/.test(c))(it); } function read_line(it, reset) { let check = c => is.line_break(c) || c == '{'; return read_until(check)(it, reset); } function read_step(it, extra) { let c, step = Tokens.step(); while (!it.end()) { if ((c = it.curr()) == '}') break; if (is.white_space(c)) { it.next(); continue; } else if (!step.name.length) { step.name = read_selector(it); } else { step.styles.push(read_rule(it, extra)); if (it.curr() == '}') break; } it.next(); } return step; } function read_steps(it, extra) { const steps = []; let c; while (!it.end()) { if ((c = it.curr()) == '}') break; else if (is.white_space(c)) { it.next(); continue; } else { steps.push(read_step(it, extra)); } it.next(); } return steps; } function read_keyframes(it, extra) { let keyframes = Tokens.keyframes(), c; while (!it.end()) { if ((c = it.curr()) == '}') break; else if (!keyframes.name.length) { read_word(it); keyframes.name = read_keyframe_name(it); if (!keyframes.name.length) { throw_error('missing keyframes name', it.info()); break; } continue; } else if (c == '{') { it.next(); keyframes.steps = read_steps(it, extra); break; } it.next(); } return keyframes; } function read_comments(it, flag = {}) { it.next(); while (!it.end()) { let c = it.curr(); if (flag.inline) { if (c == '\n') break; } else { if ((c = it.curr()) == '*' && it.curr(1) == '/') break; } it.next(); } if (!flag.inline) { it.next(); it.next(); } } function read_property(it) { let prop = '', c; while (!it.end()) { if ((c = it.curr()) == ':') break; else if (!is.white_space(c)) prop += c; it.next(); } return prop; } function read_arguments(it) { let args = [], group = [], stack = [], arg = '', c; while (!it.end()) { c = it.curr(); if ((/[\('"`]/.test(c) && it.curr(-1) !== '\\')) { if (stack.length) { if (c != '(' && c === last(stack)) { stack.pop(); } else { stack.push(c); } } else { stack.push(c); } arg += c; } else if (c == '@') { if (!group.length) { arg = arg.trimLeft(); } if (arg.length) { group.push(Tokens.text(arg)); arg = ''; } group.push(read_func(it)); } else if (/[,)]/.test(c)) { if (stack.length) { if (c == ')') { stack.pop(); } arg += c; } else { if (arg.length) { if (!group.length) { group.push(Tokens.text(get_text_value(arg))); } else { if (arg.length) { group.push(Tokens.text(arg)); } } } args.push(normalize_argument(group)); [group, arg] = [[], '']; if (c == ')') break; } } else { arg += c; } it.next(); } return args; } function normalize_argument(group) { let result = group.map(arg => { if (arg.type == 'text' && typeof arg.value == 'string') { let value = String(arg.value); if (value.includes('`')) { arg.value = value = value.replace(/`/g, '"'); } arg.value = value.replace(/\n+|\s+/g, ' '); } return arg; }); let ft = first(result) || {}; let ed = last(result) || {}; if (ft.type == 'text' && ed.type == 'text') { let cf = first(ft.value); let ce = last(ed.value); if (typeof ft.value == 'string' && typeof ed.value == 'string') { if (is.pair(cf) && is.pair_of(cf, ce)) { ft.value = ft.value.slice(1); ed.value = ed.value.slice(0, ed.value.length - 1); } } } return result; } function read_func(it) { let func = Tokens.func(), name = '', c; while (!it.end()) { if ((c = it.curr()) == ')') break; if (c == '(') { it.next(); func.name = name; func.arguments = read_arguments(it); func.position = it.info().index; break; } else name += c; it.next(); } return func; } function read_value(it) { let text = Tokens.text(), idx = 0, skip = true, c; const value = [], stack = []; value[idx] = []; while (!it.end()) { c = it.curr(); if (skip && is.white_space(c)) { it.next(); continue; } else { skip = false; } if (c == '\n' && !is.white_space(it.curr(-1))) { text.value += ' '; } else if (c == ',' && !stack.length) { if (text.value.length) { value[idx].push(text); text = Tokens.text(); } value[++idx] = []; skip = true; } else if (/[;}]/.test(c)) { if (text.value.length) { value[idx].push(text); text = Tokens.text(); } break; } else if (c == '@') { if (text.value.length) { value[idx].push(text); text = Tokens.text(); } value[idx].push(read_func(it)); } else if (!is.white_space(c) || !is.white_space(it.curr(-1))) { if (c == '(') stack.push(c); if (c == ')') stack.pop(); text.value += c; } it.next(); } if (text.value.length) { value[idx].push(text); } return value; } function read_selector(it) { let selector = '', c; while (!it.end()) { if ((c = it.curr()) == '{') break; else if (!is.white_space(c)) { selector += c; } it.next(); } return selector; } function read_cond_selector(it) { let selector = { name: '', arguments: [] }, c; while (!it.end()) { if ((c = it.curr()) == '(') { it.next(); selector.arguments = read_arguments(it); } else if (/[){]/.test(c)) break; else if (!is.white_space(c)) selector.name += c; it.next(); } return selector; } function read_pseudo(it, extra) { let pseudo = Tokens.pseudo(), c; while (!it.end()) { if ((c = it.curr()) == '}') break; if (is.white_space(c)) { it.next(); continue; } else if (!pseudo.selector) { pseudo.selector = read_selector(it); } else { let rule = read_rule(it, extra); if (rule.property == '@use') { pseudo.styles = pseudo.styles.concat( rule.value ); } else { pseudo.styles.push(rule); } if (it.curr() == '}') break; } it.next(); } return pseudo; } function read_rule(it, extra) { let rule = Tokens.rule(), c; while (!it.end()) { if ((c = it.curr()) == ';') break; else if (!rule.property.length) { rule.property = read_property(it); if (rule.property == '@use') { rule.value = read_var(it, extra); break; } } else { rule.value = read_value(it); break; } it.next(); } return rule; } function read_cond(it, extra) { let cond = Tokens.cond(), c; while (!it.end()) { if ((c = it.curr()) == '}') break; else if (!cond.name.length) { Object.assign(cond, read_cond_selector(it)); } else if (c == ':') { let pseudo = read_pseudo(it); if (pseudo.selector) cond.styles.push(pseudo); } else if (c == '@' && !read_line(it, true).includes(':')) { cond.styles.push(read_cond(it)); } else if (!is.white_space(c)) { let rule = read_rule(it, extra); if (rule.property) cond.styles.push(rule); if (it.curr() == '}') break; } it.next(); } return cond; } function read_property_value(extra, name) { let rule = ''; if (extra && extra.get_custom_property_value) { rule = extra.get_custom_property_value(name); } return rule; } function evaluate_value(values, extra) { values.forEach && values.forEach(v => { if (v.type == 'text' && v.value) { let vars = parse_var(v.value); v.value = vars.reduce((ret, p) => { let rule = '', other = '', parsed; rule = read_property_value(extra, p.name); if (!rule && p.alternative) { p.alternative.every(n => { other = read_property_value(extra, n.name); if (other) { rule = other; return false; } }); } try { parsed = parse$1(rule, extra); } catch (e) { } if (parsed) { ret.push.apply(ret, parsed); } return ret; }, []); } if (v.type == 'func' && v.arguments) { v.arguments.forEach(arg => { evaluate_value(arg, extra); }); } }); } function read_var(it, extra) { it.next(); let groups = read_value(it) || []; return groups.reduce((ret, group) => { evaluate_value(group, extra); let [token] = group; if (token.value && token.value.length) { ret.push(...token.value); } return ret; }, []); } function parse$1(input, extra) { const it = iterator(input); const Tokens = []; while (!it.end()) { let c = it.curr(); if (is.white_space(c)) { it.next(); continue; } else if (c == '/' && it.curr(1) == '*') { read_comments(it); } else if (c == '/' && it.curr(1) == '/') { read_comments(it, { inline: true }); } else if (c == ':') { let pseudo = read_pseudo(it, extra); if (pseudo.selector) Tokens.push(pseudo); } else if (c == '@' && read_word(it, true) === '@keyframes') { let keyframes = read_keyframes(it, extra); Tokens.push(keyframes); } else if (c == '@' && !read_line(it, true).includes(':')) { let cond = read_cond(it, extra); if (cond.name.length) Tokens.push(cond); } else if (!is.white_space(c)) { let rule = read_rule(it, extra); if (rule.property) Tokens.push(rule); } it.next(); } return Tokens; } function apply_args(fn, ...args) { return args.reduce((f, arg) => f.apply(null, make_array(arg)), fn ); } function clamp(num, min, max) { return Math.max(min, Math.min(max, num)); } function maybe(cond, value) { if (!cond) return ''; return (typeof value === 'function') ? value() : value; } function range(start, stop, step) { let count = 0, old = start; let initial = n => (n > 0 && n < 1) ? .1 : 1; let length = arguments.length; if (length == 1) [start, stop] = [initial(start), start]; if (length < 3) step = initial(start); let range = []; while ((step >= 0 && start <= stop) || (step < 0 && start > stop)) { range.push(start); start += step; if (count++ >= 1000) break; } if (!range.length) range.push(old); return range; } function alias_for(obj, names) { Object.keys(names).forEach(n => { obj[n] = obj[names[n]]; }); return obj; } function is_letter(c) { return /^[a-zA-Z]$/.test(c); } function lazy(fn) { let wrap = () => fn; wrap.lazy = true; return wrap; } const [ min, max, total ] = [ 1, 32, 32 * 32 ]; function parse_grid(size) { let [x, y] = (size + '') .replace(/\s+/g, '') .replace(/[,,xX]+/, 'x') .split('x') .map(Number); const max_val = (x == 1 || y == 1) ? total : max; const ret = { x: clamp(x || min, 1, max_val), y: clamp(y || x || min, 1, max_val) }; return Object.assign({}, ret, { count: ret.x * ret.y } ); } function create_svg_url(svg, id) { if (id) { let blob = new Blob([svg], { type: 'image/svg+xml' }); let url = URL.createObjectURL(blob); return `url(${ url }#${ id })`; } else { let encoded = encodeURIComponent(svg); return `url("data:image/svg+xml;utf8,${ encoded }")`; } } function normalize_svg(input) { const xmlns = 'xmlns="http://www.w3.org/2000/svg"'; if (!input.includes('<svg')) { input = `<svg ${ xmlns }>${ input }</svg>`; } if (!input.includes('xmlns')) { input = input.replace(/<svg([\s>])/, `<svg ${ xmlns }$1`); } return input; } function lerp(start, end, t) { return start * (1 - t) + end * t; } function rand(start = 0, end = start) { if (arguments.length == 1) { start = start < 1 ? .1 : 1; } return lerp(start, end, Math.random()); } function pick(...items) { let args = items.reduce((acc, n) => acc.concat(n), []); return args[~~(Math.random() * args.length)]; } function unique_id(prefix = '') { return prefix + Math.random().toString(32).substr(2); } function by_unit(fn) { return (...args) => { let unit = get_unit(args); return restore(fn, unit).apply(null, args); } } function restore(fn, unit) { return (...args) => { args = args.map(str => Number( String(str).replace(/\D+$/g, '') )); let result = fn.apply(null, args); if (!unit.length) { return result; } if (Array.isArray(result)) { return result.map(n => n + unit); } return result + unit; } } function get_unit(values) { let unit = ''; values.some(str => { let input = String(str).trim(); if (!input) return ''; let matched = input.match(/\d(\D+)$/); return (unit = matched ? matched[1] : ''); }); return unit; } function by_charcode(fn) { return (...args) => { let codes = args.map(n => String(n).charCodeAt(0)); let result = fn.apply(null, codes); return Array.isArray(result) ? result.map(n => String.fromCharCode(n)) : String.fromCharCode(result); } } /** * Based on the Shunting-yard algorithm. */ function calc(input) { const expr = infix_to_postfix(input), stack = []; while (expr.length) { let top = expr.shift(); if (/\d+/.test(top)) stack.push(top); else { let right = stack.pop(); let left = stack.pop(); stack.push(compute( top, Number(left), Number(right) )); } } return stack[0]; } const operator = { '*': 3, '/': 3, '%': 3, '+': 2, '-': 2, '(': 1, ')': 1 }; function get_tokens(input) { let expr = String(input); let tokens = [], num = ''; for (let i = 0; i < expr.length; ++i) { let c = expr[i]; if (operator[c]) { if (c == '-' && expr[i - 1] == 'e') { num += c; } else if (!tokens.length && !num.length && /[+-]/.test(c)) { num += c; } else { let { type, value } = last(tokens) || {}; if (type == 'operator' && !num.length && /[^()]/.test(c) && /[^()]/.test(value)) { num += c; } else { if (num.length) { tokens.push({ type: 'number', value: num }); num = ''; } tokens.push({ type: 'operator', value: c }); } } } else if (/\S/.test(c)) { num += c; } } if (num.length) { tokens.push({ type: 'number', value: num }); } return tokens; } function infix_to_postfix(input) { let tokens = get_tokens(input); const op_stack = [], expr = []; for (let i = 0; i < tokens.length; ++i) { let { type, value } = tokens[i]; if (type == 'number') { expr.push(value); } else if (type == 'operator') { if (value == '(') { op_stack.push(value); } else if (value == ')') { while (op_stack.length && last(op_stack) != '(') { expr.push(op_stack.pop()); } op_stack.pop(); } else { while (op_stack.length && operator[last(op_stack)] >= operator[value]) { let op = op_stack.pop(); if (!/[()]/.test(op)) expr.push(op); } op_stack.push(value); } } } while (op_stack.length) { expr.push(op_stack.pop()); } return expr; } function compute(op, a, b) { switch (op) { case '+': return a + b; case '-': return a - b; case '*': return a * b; case '/': return a / b; case '%': return a % b; } } const store = {}; function memo(prefix, fn) { return (...args) => { let key = prefix + args.join('-'); if (store[key]) return store[key]; return (store[key] = fn.apply(null, args)); } } function expand(fn) { return (...args) => fn.apply(null, flat_map(args, n => String(n).startsWith('[') ? build_range(n) : n )); } function Type(type, value) { return { type, value }; } function get_tokens$1(input) { let expr = String(input); let tokens = [], stack = []; if (!expr.startsWith('[') || !expr.endsWith(']')) { return tokens; } for (let i = 1; i < expr.length - 1; ++i) { let c = expr[i]; if (c == '-' && expr[i - 1] == '-') { continue; } if (c == '-') { stack.push(c); continue; } if (last(stack) == '-') { stack.pop(); let from = stack.pop(); tokens.push(from ? Type('range', [ from, c ]) : Type('char', c) ); continue; } if (stack.length) { tokens.push(Type('char', stack.pop())); } stack.push(c); } if (stack.length) { tokens.push(Type('char', stack.pop())); } return tokens; } const build_range = memo('build_range', (input) => { let tokens = get_tokens$1(input); return flat_map(tokens, ({ type, value }) => { if (type == 'char') return value; let [ from, to ] = value; let reverse = false; if (from > to) { [from, to] = [ to, from ]; reverse = true; } let result = by_charcode(range)(from, to); if (reverse) result.reverse(); return result; }); }); const Expose = { index({ count }) { return _ => count; }, row({ x }) { return _ => x; }, col({ y }) { return _ => y; }, size({ grid }) { return _ => grid.count; }, ['size-row']({ grid }) { return _ => grid.x; }, ['size-col']({ grid }) { return _ => grid.y; }, n({ idx }) { return _ => idx || 0; }, pick({ context }) { return expand((...args) => ( context.last_pick = pick(args) )); }, ['pick-n']({ idx, context, position }) { let counter = 'pn-counter' + position; return expand((...args) => { if (!context[counter]) context[counter] = 0; context[counter] += 1; let max = args.length; let pos = ((idx == undefined ? context[counter] : idx) - 1) % max; return context.last_pick = args[pos]; }); }, ['pick-d']({ idx, context, position }) { let counter = 'pd-counter' + position; let values = 'pd-values' + position; return expand((...args) => { if (!context[counter]) context[counter] = 0; context[counter] += 1; if (!context[values]) { context[values] = shuffle(args); } let max = args.length; let pos = ((idx == undefined ? context[counter] : idx) - 1) % max; return context.last_pick = context[values][pos]; }); }, ['last-pick']({ context }) { return () => context.last_pick; }, multiple: lazy((n, action) => { let result = []; if (!action || !n) return result; let count = clamp(n(), 1, 65536); for (let i = 0; i < count; ++i) { result.push(action(i + 1)); } return result.join(','); }), repeat: lazy((n, action) => { let result = ''; if (!action || !n) return result; let count = clamp(n(), 1, 65536); for (let i = 0; i < count; ++i) { result += action(i + 1); } return result; }), rand({ context }) { return (...args) => { let transform_type = args.every(is_letter) ? by_charcode : by_unit; let value = transform_type(rand).apply(null, args); return context.last_rand = value; }; }, ['last-rand']({ context }) { return () => context.last_rand; }, calc() { return value => calc(value); }, hex() { return value => parseInt(value).toString(16); }, svg: lazy(input => { if (input === undefined) return ''; let svg = normalize_svg(input().trim()); return create_svg_url(svg); }), ['svg-filter']: lazy(input => { if (input === undefined) return ''; let id = unique_id('filter-'); let svg = normalize_svg(input().trim()) .replace( /<filter([\s>])/, `<filter id="${ id }"$1` ); return create_svg_url(svg, id); }), var() { return value => `var(${ value })`; } }; var Func = alias_for(Expose, { 'multi': 'multiple', 'm': 'multiple', 'pn': 'pick-n', 'pd': 'pick-d', 'r': 'rand', 'p': 'pick', 'lp': 'last-pick', 'lr': 'last-rand', 'i': 'index', // legacy names 'pick-by-turn': 'pick-n', 'max-row': 'size-row', 'max-col': 'size-col' }); const is_seperator = c => /[,,\s]/.test(c); function skip_seperator(it) { while (!it.end()) { if (!is_seperator(it.curr(1))) break; else it.next(); } } function parse$2(input) { const it = iterator(input); const result = [], stack = []; let group = ''; while (!it.end()) { let c = it.curr(); if (c == '(') { group += c; stack.push(c); } else if (c == ')') { group += c; if (stack.length) { stack.pop(); } } else if (stack.length) { group += c; } else if (is_seperator(c)) { result.push(group); group = ''; skip_seperator(it); } else { group += c; } it.next(); } if (group) { result.push(group); } return result; } const { cos, sin, sqrt, pow, PI } = Math; const DEG = PI / 180; function polygon(option, fn) { if (typeof arguments[0] == 'function') { fn = option; option = {}; } if (!fn) { fn = t => [ cos(t), sin(t) ]; } let split = option.split || 120; let scale = option.scale || 1; let start = DEG * (option.start || 0); let deg = option.deg ? (option.deg * DEG) : (PI / (split / 2)); let points = []; for (let i = 0; i < split; ++i) { let t = start + deg * i; let [x, y] = fn(t); points.push( ((x * 50 * scale) + 50 + '% ') + ((y * 50 * scale) + 50 + '%') ); } return option.type ? `polygon(${ option.type }, ${ points.join(',') })` : `polygon(${ points.join(',') })`; } function rotate(x, y, deg) { let rad = DEG * deg; return [ x * cos(rad) - y * sin(rad), y * cos(rad) + x * sin(rad) ]; } const shapes = { circle() { return 'circle(49%)'; }, triangle() { return polygon({ split: 3, start: -90 }, t => [ cos(t) * 1.1, sin(t) * 1.1 + .2 ]); }, rhombus() { return polygon({ split: 4 }); }, pentagon() { return polygon({ split: 5, start: 54 }); }, hexgon() { return polygon({ split: 6, start: 30 }); }, hexagon() { return polygon({ split: 6, start: 30 }); }, heptagon() { return polygon({ split: 7, start: -90 }); }, octagon() { return polygon({ split: 8, start: 22.5 }); }, star() { return polygon({ split: 5, start: 54, deg: 144 }); }, diamond() { return 'polygon(50% 5%, 80% 50%, 50% 95%, 20% 50%)'; }, cross() { return `polygon( 5% 35%, 35% 35%, 35% 5%, 65% 5%, 65% 35%, 95% 35%, 95% 65%, 65% 65%, 65% 95%, 35% 95%, 35% 65%, 5% 65% )`; }, clover(k = 3) { k = clamp(k, 3, 5); if (k == 4) k = 2; return polygon({ split: 240 }, t => { let x = cos(k * t) * cos(t); let y = cos(k * t) * sin(t); if (k == 3) x -= .2; if (k == 2) { x /= 1.1; y /= 1.1; } return [x, y]; }); }, hypocycloid(k = 3) { k = clamp(k, 3, 6); let m = 1 - k; return polygon({ scale: 1 / k }, t => { let x = m * cos(t) + cos(m * (t - PI)); let y = m * sin(t) + sin(m * (t - PI)); if (k == 3) { x = x * 1.1 - .6; y = y * 1.1; } return [x, y]; }); }, astroid() { return shapes.hypocycloid(4); }, infinity() { return polygon(t => { let a = .7 * sqrt(2) * cos(t); let b = (pow(sin(t), 2) + 1); return [ a / b, a * sin(t) / b ] }); }, heart() { return polygon(t => { let x = .75 * pow(sin(t), 3); let y = cos(1 * t) * (13 / 18) - cos(2 * t) * (5 / 18) - cos(3 * t) / 18 - cos(4 * t) / 18; return rotate( x * 1.2, (y + .2) * 1.1, 180 ); }); }, bean() { return polygon(t => { let [a, b] = [pow(sin(t), 3), pow(cos(t), 3)]; return rotate( (a + b) * cos(t) * 1.3 - .45, (a + b) * sin(t) * 1.3 - .45, -90 ); }); }, bicorn() { return polygon(t => rotate( cos(t), pow(sin(t), 2) / (2 + sin(t)) - .5, 180 )); }, pear() { return polygon(t => [ sin(t), (1 + sin(t)) * cos(t) / 1.4 ]); }, fish() { return polygon(t => [ cos(t) - pow(sin(t), 2) / sqrt(2), sin(2 * t) / 2 ]); }, whale() { return polygon({ split: 240 }, t => { let r = 3.4 * (pow(sin(t), 2) - .5) * cos(t); return rotate( cos(t) * r + .75, sin(t) * r * 1.2, 180 ); }); }, bud(n = 3) { n = clamp(n, 3, 10); return polygon({ split: 240 }, t => [ ((1 + .2 * cos(n * t)) * cos(t)) * .8, ((1 + .2 * cos(n * t)) * sin(t)) * .8 ]); }, alien(...args) { let [a = 1, b = 1, c = 1, d = 1, e = 1] = args.map(n => clamp(n, 1, 9)); return polygon({ split: 480, type: 'evenodd' }, t => [ (cos(t * a) + cos(t * c) + cos(t * e)) * .31, (sin(t * b) + sin(t * d) + sin(t)) * .31 ]); } }; let all = []; function get_props(arg) { if (!all.length) { let props = new Set(); for (let n in document.head.style) { if (!n.startsWith('-')) { props.add(n.replace(/[A-Z]/g, '-$&').toLowerCase()); } } if (!props.has('grid-gap')) { props.add('grid-gap'); } all = Array.from(props); } return (arg && arg.test) ? all.filter(n => arg.test(n)) : all; } function build_mapping(prefix) { let reg = new RegExp(`\\-?${ prefix }\\-?`); return get_props(reg) .map(n => n.replace(reg, '')) .reduce((obj, n) => { return obj[n] = n, obj }, {}); } const props_webkit_mapping = build_mapping('webkit'); const props_moz_mapping = build_mapping('moz'); function prefixer(prop, rule) { if (props_webkit_mapping[prop]) { return `-webkit-${ rule } ${ rule }`; } else if (props_moz_mapping[prop]) { return `-moz-${ rule } ${ rule }`; } return rule; } var Property = { ['@size'](value, { is_special_selector }) { let [w, h = w] = parse$2(value); return ` width: ${ w }; height: ${ h }; ${ is_special_selector ? '' : ` --internal-cell-width: ${ w }; --internal-cell-height: ${ h }; `} `; }, ['@min-size'](value) { let [w, h = w] = parse$2(value); return `min-width: ${ w }; min-height: ${ h };`; }, ['@max-size'](value) { let [w, h = w] = parse$2(value); return `max-width: ${ w }; max-height: ${ h };`; }, ['@place-cell']: (() => { let map_left_right = { 'center': '50%', '0': '0%', 'left': '0%', 'right': '100%', 'top': '50%', 'bottom': '50%' }; let map_top_bottom = { 'center': '50%', '0': '0%', 'top': '0%', 'bottom': '100%', 'left': '50%', 'right': '50%', }; return value => { let [left, top = '50%'] = parse$2(value); left = map_left_right[left] || left; top = map_top_bottom[top] || top; const cw = 'var(--internal-cell-width, 25%)'; const ch = 'var(--internal-cell-height, 25%)'; return ` position: absolute; left: ${ left }; top: ${ top }; width: ${ cw }; height: ${ ch }; margin-left: calc(${ cw } / -2) !important; margin-top: calc(${ ch } / -2) !important; grid-area: unset !important; `; } })(), ['@grid'](value, options) { let [grid, size] = value.split('/').map(s => s.trim()); return { grid: parse_grid(grid), size: size ? this['@size'](size, options) : '' }; }, ['@shape']: memo('shape-property', value => { let [type, ...args] = parse$2(value); let prop = 'clip-path'; if (!shapes[type]) return ''; let rules = `${ prop }: ${ shapes[type].apply(null, args) };`; return prefixer(prop, rules) + 'overflow: hidden;'; }), ['@use'](rules) { if (rules.length > 2) { return rules; } } }; function build_expr(expr) { return n => String(expr) .replace(/(\d+)(n)/g, '$1*' + n) .replace(/n/g, n); } function nth(input, curr, max) { let expr = build_expr(input); for (let i = 0; i <= max; ++i) { if (calc(expr(i)) == curr) return true; } } const is$1 = { even: n => !!(n % 2), odd: n => !(n % 2) }; function even_or_odd(expr) { return /^(even|odd)$/.test(expr); } var Selector = { at({ x, y }) { return (x1, y1) => (x == x1 && y == y1); }, nth({ count, grid }) { return (...exprs) => exprs.some(expr => even_or_odd(expr) ? is$1[expr](count - 1) : nth(expr, count, grid.count) ); }, row({ x, grid }) { return (...exprs) => exprs.some(expr => even_or_odd(expr) ? is$1[expr](x - 1) : nth(expr, x, grid.x) ); }, col({ y, grid }) { return (...exprs) => exprs.some(expr => even_or_odd(expr) ? is$1[expr](y - 1) : nth(expr, y, grid.y) ); }, even({ count }) { return _ => is$1.even(count - 1); }, odd({ count }) { return _ => is$1.odd(count - 1); }, random() { return (ratio = .5) => { if (ratio >= 1 && ratio <= 0) ratio = .5; return Math.random() < ratio; } } }; // Expose all Math functions and constants. const methods = Object.getOwnPropertyNames(Math); var MathFunc = methods.reduce((expose, n) => { expose[n] = () => (...args) => { if (typeof Math[n] === 'number') return Math[n]; return Math[n].apply(null, args.map(calc)); }; return expose; }, {}); function is_host_selector(s) { return /^\:(host|doodle)/.test(s); } function is_parent_selector(s) { return /^\:(container|parent)/.test(s); } function is_special_selector(s) { return is_host_selector(s) || is_parent_selector(s); } class Rules { constructor(tokens) { this.tokens = tokens; this.rules = {}; this.props = {}; this.keyframes = {}; this.grid = null; this.coords = []; this.reset(); } reset() { this.styles = { host: '', container: '', cells: '', keyframes: '' }; this.coords = []; for (let key in this.rules) { if (key.startsWith('.cell')) { delete this.rules[key]; } } } add_rule(selector, rule) { let rules = this.rules[selector]; if (!rules) { rules = this.rules[selector] = []; } rules.push.apply(rules, make_array(rule)); } pick_func(name) { return Func[name] || MathFunc[name]; } compose_aname(...args) { return args.join('-'); } compose_selector(count, pseudo = '') { return `.cell:nth-of-type(${ count })${ pseudo }`; } compose_argument(argument, coords, idx) { let result = argument.map(arg => { if (arg.type == 'text') { return arg.value; } else if (arg.type == 'func') { let fn = this.pick_func(arg.name.substr(1)); if (fn) { coords.idx = idx; coords.position = arg.position; let args = arg.arguments.map(n => { return fn.lazy ? idx => this.compose_argument(n, coords, idx) : this.compose_argument(n, coords, idx); }); return apply_args(fn, coords, args); } } }); return (result.length >= 2) ? result.join('') : result[0]; } compose_value(value, coords) { if (!value || !value.reduce) return ''; return value.reduce((result, val) => { switch (val.type) { case 'text': { result += val.value; break; } case 'func': { let fname = val.name.substr(1); let fn = this.pick_func(fname); if (fn) { coords.position = val.position; let args = val.arguments.map(arg => { if (fn.lazy) { return idx => this.compose_argument(arg, coords, idx); } else { return this.compose_argument(arg, coords); } }); result += apply_args(fn, coords, args); } } } return result; }, ''); } compose_rule(token, _coords, selector) { let coords = Object.assign({}, _coords); let prop = token.property; let value_group = token.value.map(v => this.compose_value(v, coords) ); let value = value_group.join(', '); if (/^animation(\-name)?$/.test(prop)) { this.props.has_animation = true; if (coords.count > 1) { let { count } = coords; switch (prop) { case 'animation-name': { value = value_group .map(n => this.compose_aname(n, count)) .join(', '); break; } case 'animation': { value = value_group .map(n => { let group = (n || '').split(/\s+/); group[0] = this.compose_aname(group[0], count); return group.join(' '); }) .join(', '); } } } } if (prop == 'content') { if (!/["']|^(none|var|counter|counters|attr)\(/.test(value)) { value = `'${ value }'`; } } if (prop == 'transition') { this.props.has_transition = true; } let rule = `${ prop }: ${ value };`; rule = prefixer(prop, rule); if (prop == 'clip-path') { // fix clip bug rule += ';overflow: hidden;'; } if (prop == 'width' || prop == 'height') { if (!is_special_selector(selector)) { rule += `--internal-cell-${ prop }: ${ value };`; } } if (Property[prop]) { let transformed = Property[prop](value, { is_special_selector: is_special_selector(selector) }); switch (prop) { case '@grid': { if (is_host_selector(selector)) { this.grid = transformed.grid; rule = transformed.size || ''; } break; } case '@place-cell': { if (!is_host_selector(selector)) { rule = transformed; } } case '@use': { if (token.value.length) { this.compose(coords, token.value); } rule = Property[prop](token.value); } default: { rule = transformed; } } } return rule; } compose(coords, tokens) { this.coords.push(coords); (tokens || this.tokens).forEach((token, i) => { if (token.skip) return false; switch (token.type) { case 'rule': this.add_rule( this.compose_selector(coords.count), this.compose_rule(token, coords) ); break; case 'pseudo': { if (token.selector.startsWith(':doodle')) { token.selector = token.selector.replace(/^\:+doodle/, ':host'); } let special = is_special_selector(token.selector); if (special) { token.skip = true; } token.selector.split(',').forEach(selector => { let pseudo = token.styles.map(s => this.compose_rule(s, coords, selector) ); let composed = special ? selector : this.compose_selector(coords.count, selector); this.add_rule(composed, pseudo); }); break; } case 'cond': { let fn = Selector[token.name.substr(1)]; if (fn) { let args = token.arguments.map(arg => { return this.compose_argument(arg, coords); }); let result = apply_args(fn, coords, args); if (result) { this.compose(coords, token.styles); } } break; } case 'keyframes': { if (!this.keyframes[token.name]) { this.keyframes[token.name] = coords => ` ${ join(token.steps.map(step => ` ${ step.name } { ${ join( step.styles.map(s => this.compose_rule(s, coords)) )} } `)) } `; } } } }); } output() { Object.keys(this.rules).forEach((selector, i) => { if (is_parent_selector(selector)) { this.styles.container += ` .container { ${ join(this.rules[selector]) } } `; } else { let target = is_host_selector(selector) ? 'host' : 'cells'; this.styles[target] += ` ${ selector } { ${ join(this.rules[selector]) } } `; } }); let keyframes = Object.keys(this.keyframes); this.coords.forEach((coords, i) => { keyframes.forEach(name => { let aname = this.compose_aname(name, coords.count); this.styles.keyframes += ` ${ maybe(i == 0, `@keyframes ${ name } { ${ this.keyframes[name](coords) } }` )} @keyframes ${ aname } { ${ this.keyframes[name](coords) } } `; }); }); return { props: this.props, styles: this.styles, grid: this.grid } } } function generator(tokens, grid_size) { let rules = new Rules(tokens); let context = {}; rules.compose({ x : 1, y: 1, count: 1, context: {}, grid: { x : 1, y: 1, count: 1 } }); let { grid } = rules.output(); if (grid) grid_size = grid; rules.reset(); for (let x = 1, count = 0; x <= grid_size.x; ++x) { for (let y = 1; y <= grid_size.y; ++y) { rules.compose({ x, y, count: ++count, grid: grid_size, context }); } } return rules.output(); } class Doodle extends HTMLElement { constructor() { super(); this.doodle = this.attachShadow({ mode: 'open' }); this.extra = { get_custom_property_value: this.get_custom_property_value.bind(this) }; } connectedCallback() { setTimeout(() => { let compiled; let use = this.getAttribute('use') || ''; if (use) use = `@use:${ use };`; if (!this.innerHTML.trim() && !use) return false; try { let parsed = parse$1(use + this.innerHTML, this.extra); this.grid_size = parse_grid(this.getAttribute('grid')); compiled = generator(parsed, this.grid_size); compiled.grid && (this.grid_size = compiled.grid); this.build_grid(compiled); } catch (e) { this.innerHTML = ''; console.error(e && e.message || 'Error in css-doodle.'); } }); } get_custom_property_value(name) { return getComputedStyle(this).getPropertyValue(name) .trim() .replace(/^\(|\)$/g, ''); } build_grid(compiled) { const { has_transition, has_animation } = compiled.props; const { keyframes, host, container, cells } = compiled.styles; this.doodle.innerHTML = ` <style> ${ this.style_basic() } </style> <style class="style-keyframes"> ${ keyframes } </style> <style class="style-container"> ${ this.style_size() } ${ host } ${ container } </style> <style class="style-cells"> ${ (has_transition || has_animation) ? '' : cells } </style> <div class="container"> ${ this.html_cells() } </div> `; if (has_transition || has_animation) { setTimeout(() => { this.set_style('.style-cells', cells); }, 50); } } inherit_props(p) { return get_props(/grid/) .map(n => `${ n }: inherit;`).join(''); } style_basic() { return ` :host { display: block; visibility: visible; width: 1em; height: 1em; } .container { position: relative; width: 100%; height: 100%; display: grid; ${ this.inherit_props() } } .cell { position: relative; line-height: 1; box-sizing: border-box; display: flex; justify-content: center; align-items: center; } `; } style_size() { let { x, y } = this.grid_size; return ` :host { grid-template-rows: repeat(${ x }, 1fr); grid-template-columns: repeat(${ y }, 1fr); } `; } html_cells() { return '<div class="cell"></div>' .repeat(this.grid_size.count); } set_style(selector, styles) { const el = this.shadowRoot.querySelector(selector); el && (el.styleSheet ? (el.styleSheet.cssText = styles ) : (el.innerHTML = styles)); } update(styles) { let use = this.getAttribute('use') || ''; if (use) use = `@use:${ use };`; if (!styles) styles = this.innerHTML; this.innerHTML = styles; if (!this.grid_size) { this.grid_size = parse_grid(this.getAttribute('grid')); } const compiled = generator(parse$1(use + styles, this.extra), this.grid_size); if (compiled.grid) { let { x, y } = compiled.grid; if (this.grid_size.x !== x || this.grid_size.y !== y) { Object.assign(this.grid_size, compiled.grid); return this.build_grid(compiled); } Object.assign(this.grid_size, compiled.grid); } else { let grid = parse_grid(this.getAttribute('grid')); let { x, y } = grid; if (this.grid_size.x !== x || this.grid_size.y !== y) { Object.assign(this.grid_size, grid); return this.build_grid( generator(parse$1(use + styles, this.extra), this.grid_size) ); } } this.set_style('.style-keyframes', compiled.styles.keyframes ); this.set_style('.style-container', this.style_size() + compiled.styles.host + compiled.styles.container ); this.set_style('.style-cells', compiled.styles.cells ); } get grid() { return Object.assign({}, this.grid_size); } set grid(grid) { this.setAttribute('grid', grid); this.connectedCallback(); } get use() { return this.getAttribute('use'); } set use(use) { this.setAttribute('use', use); this.connectedCallback(); } static get observedAttributes() { return ['grid', 'use']; } attributeChangedCallback(name, old_val, new_val) { if (old_val == new_val) { return false; } if (name == 'grid' && old_val) { this.grid = new_val; } if (name == 'use' && old_val) { this.use = new_val; } } } customElements.define('css-doodle', Doodle); }));
const fs = require('fs-plus'); const path = require('path'); const season = require('season'); const temp = require('temp').track(); const runAtom = require('./helpers/start-atom'); describe('Smoke Test', () => { // Fails on win32 if (process.platform !== 'darwin') { return; } const atomHome = temp.mkdirSync('atom-home'); beforeEach(() => { jasmine.useRealClock(); season.writeFileSync(path.join(atomHome, 'config.cson'), { '*': { welcome: { showOnStartup: false }, core: { telemetryConsent: 'no', disabledPackages: ['github'] } } }); }); it('can open a file in Atom and perform basic operations on it', async () => { const tempDirPath = temp.mkdirSync('empty-dir'); const filePath = path.join(tempDirPath, 'new-file'); fs.writeFileSync(filePath, '', { encoding: 'utf8' }); runAtom([tempDirPath], { ATOM_HOME: atomHome }, async client => { const roots = await client.treeViewRootDirectories(); expect(roots).toEqual([tempDirPath]); await client.execute(filePath => atom.workspace.open(filePath), filePath); const textEditorElement = await client.$('atom-text-editor'); await textEditorElement.waitForExist(5000); await client.waitForPaneItemCount(1, 1000); await textEditorElement.click(); const closestElement = await client.execute(() => document.activeElement.closest('atom-text-editor') ); expect(closestElement).not.toBeNull(); await client.keys('Hello!'); const text = await client.execute(() => atom.workspace.getActiveTextEditor().getText() ); expect(text).toBe('Hello!'); await client.dispatchCommand('editor:delete-line'); }); }); });
import state from './state'; import mutations from './mutations'; import * as actions from './actions'; export default () => ({ namespaced: true, state: state(), mutations, actions, });
var chai = require('chai'); var expect = chai.expect; describe('Environment Variables', function() { describe('process.env.FACEBOOK_TEST_EMAIL', function() { it('should be set', function() { expect(process.env.FACEBOOK_TEST_EMAIL).to.exist; }); }); describe('process.env.FACEBOOK_TEST_PASSWORD', function() { it('should be set', function() { expect(process.env.FACEBOOK_TEST_PASSWORD).to.exist; }); }); describe('process.env.GOOGLE_TEST_EMAIL', function() { it('should be set', function() { expect(process.env.GOOGLE_TEST_EMAIL).to.exist; }); }); describe('process.env.GOOGLE_TEST_PASSWORD', function() { it('should be set', function() { expect(process.env.GOOGLE_TEST_PASSWORD).to.exist; }); }); });
"use strict"; var helper = require('../../helper'); var DealTrackingStageManager = require('../../../src/managers/sales/deal-tracking-stage-manager'); var generateCode = require("../../../src/utils/code-generator"); var dealTrackingBoard = require("./deal-tracking-board-data-util"); class DealTrackingStageDataUtil { getNewData() { return dealTrackingBoard.getTestData() .then((result) => { var Model = require('dl-models').sales.DealTrackingStage; var data = new Model(); var code = generateCode(); data.code = code; data.boardId = result._id; data.name = `name[${code}]`; data.deals = []; return Promise.resolve(data); }); } getTestData() { return helper .getManager(DealTrackingStageManager) .then((manager) => { return this.getNewData().then((data) => { return manager.create(data) .then((id) => manager.getSingleById(id)); }); }); } } module.exports = new DealTrackingStageDataUtil();
/** * @module ember-paper */ import Component from '@ember/component'; import { run } from '@ember/runloop'; import Translate3dMixin from '../mixins/translate3d-mixin'; /** * @class PaperDialogInner * @extends Ember.Component * @uses Translate3dMixin */ export default Component.extend(Translate3dMixin, { tagName: 'md-dialog', classNames: ['md-default-theme'], classNameBindings: ['contentOverflow:md-content-overflow', 'fullscreen:md-dialog-fullscreen'], onTranslateFromEnd() { if (this.get('focusOnOpen')) { let toFocus = this.$('[autofocus]').last(); if (toFocus.length === 0) { toFocus = this.$('md-dialog-actions button').last(); } toFocus.focus(); } }, onTranslateToEnd($origin) { if ($origin) { $origin.focus(); } }, didInsertElement() { this._super(...arguments); this.checkContentOverflow(); // content overflow might change depending on load of images inside dialog. let images = this.$().find('img'); images.on(`load.${this.elementId}`, run.bind(this, this.checkContentOverflow)); }, willDestroyElement() { this._super(...arguments); let images = this.$().find('img'); images.off(`load.${this.elementId}`); }, checkContentOverflow() { let content = this.element.querySelector('md-dialog-content'); if (content) { this.set('contentOverflow', content.scrollHeight > content.clientHeight); } } });
/** * Release * Called as last, tells the user has released the screen * @events release */ Hammer.gestures.Release = { name : 'release', index : Infinity, handler: function releaseGesture(ev, inst) { if(ev.eventType == Hammer.EVENT_END) { inst.trigger(this.name, ev); } } };
var macros = require('./macros') , statsd = require('statsd-parser') , lynx = macros.lynx , test = macros.test , udpServer = macros.udpServer , connection = macros.connection , count = 0 , finished = false ; // // TOTAL is the number of iterations to do // DESIRED is the minimum number of requests expected // SAMPLE Number of samples to send, e.g. @0.1 (1 in 10) // var DESIRED = 90 , TOTAL = 1000 , SAMPLE = 0.1 ; // // Try to do this a thousand times // [1,2,3,...,1000] // var coll = []; for(i=0; i<TOTAL; i++) { coll.push(i); } // // Remove console.log from errors, plenty of nothing to send here // connection.on_error = function () {}; // // We are going to do one thousand `TOTAL` packets // and see if we hit our minimums // // When you specify sampling `lynx` must track that it only send the amount // of packages you are specifying (e.g. 1 in each 10 for @0.1 as in `SAMPLE`) // // To do this we use random numbers, making our process not perfect but // accurate enough // // Because of the randomness that is used to select which packets are sent // this can never be an exact test and might break while the code is // perfectly fine // test('sampling', function (t) { var server = udpServer(function (message, remote) { count++; // // Add, check if its a valid statsd message and includes sample rate // that is teh same as being tested // var match = statsd.matchStatsd(message.toString()); t.ok(match, message.toString()); t.equal(SAMPLE.toString(), match.sample_rate); // // When we finally hit our lower threshold // if(count > DESIRED) { finished = true; t.ok(true, 'Reached ' + DESIRED + ' on ' + (TOTAL - coll.length) + ' packets.'); server.close(); } }); // // Run all the iterations // var runAll = function(coll, callback) { (function iterate() { if (coll.length === 0) { return callback(); } coll.pop(); setTimeout(function send_packet() { // // Send a sample // connection.gauge('spl.foo', 500, SAMPLE); process.nextTick(iterate); }, Math.ceil(Math.random() * 10)); })(); }; runAll(coll, function() { if (finished) { t.ok(true, 'Reached ' + DESIRED + ' on ' + TOTAL + ' packets.'); t.end(); return; } // // If we reached the end and this has not closed by having // the desired amount of requests // t.ok(false, 'Didnt reach the desired amount of packets ' + DESIRED + '/' + TOTAL + ' was -> ' + count); server.close(); t.end(); }); }); // // TODO: Sampling with irregular batches //
var FieldType = require('../Type'); var util = require('util'); var utils = require('keystone-utils'); /** * Text FieldType Constructor * @extends Field * @api public */ function text(list, path, options) { this._nativeType = String; this._underscoreMethods = ['crop']; text.super_.call(this, list, path, options); } util.inherits(text, FieldType); /** * Add filters to a query */ text.prototype.addFilterToQuery = function(filter, query) { query = query || {}; if (filter.mode === 'exactly' && !filter.value) { query[this.path] = filter.inverted ? { $nin: ['', null] } : { $in: ['', null] }; return; } var value = utils.escapeRegExp(filter.value); if (filter.mode === 'startsWith') { value = '^' + value; } else if (filter.mode === 'endsWith') { value = value + '$'; } else if (filter.mode === 'exactly') { value = '^' + value + '$'; } value = new RegExp(value, filter.caseSensitive ? '' : 'i'); query[this.path] = filter.inverted ? { $not: value } : value; return query; }; /** * Crops the string to the specifed length. */ text.prototype.crop = function(item, length, append, preserveWords) { return utils.cropString(item.get(this.path), length, append, preserveWords); }; /* Export Field Type */ module.exports = text;
Class.Binds = new Class({ bindMethods: function(){} });
import { Meteor } from 'meteor/meteor'; import { check } from 'meteor/check'; import { hasPermission } from '../../app/authorization'; import { Users, Subscriptions, Messages } from '../../app/models'; import { settings } from '../../app/settings'; import { Notifications } from '../../app/notifications'; Meteor.methods({ removeRoomLeader(rid, userId) { check(rid, String); check(userId, String); if (!Meteor.userId()) { throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'removeRoomLeader', }); } if (!hasPermission(Meteor.userId(), 'set-leader', rid)) { throw new Meteor.Error('error-not-allowed', 'Not allowed', { method: 'removeRoomLeader', }); } const user = Users.findOneById(userId); if (!user || !user.username) { throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'removeRoomLeader', }); } const subscription = Subscriptions.findOneByRoomIdAndUserId(rid, user._id); if (!subscription) { throw new Meteor.Error('error-user-not-in-room', 'User is not in this room', { method: 'removeRoomLeader', }); } if (Array.isArray(subscription.roles) === true && subscription.roles.includes('leader') === false) { throw new Meteor.Error('error-user-not-leader', 'User is not a leader', { method: 'removeRoomLeader', }); } Subscriptions.removeRoleById(subscription._id, 'leader'); const fromUser = Users.findOneById(Meteor.userId()); Messages.createSubscriptionRoleRemovedWithRoomIdAndUser(rid, user, { u: { _id: fromUser._id, username: fromUser.username, }, role: 'leader', }); if (settings.get('UI_DisplayRoles')) { Notifications.notifyLogged('roles-change', { type: 'removed', _id: 'leader', u: { _id: user._id, username: user.username, name: user.name, }, scope: rid, }); } return true; }, });
import AccountsServer from '@accounts/server'; import MongoAdapter from '@accounts/mongo'; import { MongoInternals } from 'meteor/mongo'; import { Meteor } from 'meteor/meteor'; Meteor.startup(() => { const mongodb = MongoInternals.defaultRemoteCollectionDriver().mongo.db; const mongoAdapter = new MongoAdapter(mongodb, { convertUserIdToMongoObjectId: false, }); AccountsServer.config({ tokenConfigs: { accessToken: { expiresIn: '3d', }, refreshToken: { expiresIn: '30d', }, }, passwordHashAlgorithm: 'sha256', }, mongoAdapter); });
const expect = require('chai').expect; const errorInEachBrowserContains = require('../../../../assertion-helper.js').errorInEachBrowserContains; describe('[Raw API] Drag actions', function () { describe('drag', function () { it('Should drag an element by an offset', function () { return runTests('./testcafe-fixtures/drag.testcafe', 'Drag to offset', { shouldFail: true }) .catch(function (errs) { errorInEachBrowserContains(errs, 'Drag to offset completed successfully', 0); }); }); }); describe('drag-to-element', function () { it('Should drag an element to another element', function () { return runTests('./testcafe-fixtures/drag.testcafe', 'Drag to element', { shouldFail: true }) .catch(function (errs) { errorInEachBrowserContains(errs, 'Drag to element completed successfully', 0); }); }); it("Should fail if a dragged element doesn't exist", function () { return runTests('./testcafe-fixtures/drag.testcafe', 'Drag non-existent element to another element', { shouldFail: true }) .catch(function (errs) { expect(errs[0]).contains( 'The specified selector does not match any element in the DOM tree.' + ' > | Selector(\'#non-existent\')' ); expect(errs[0]).contains('[[Drag non-existent element to another element callsite]]'); }); }); it('Should fail if a dragged element is invisible', function () { return runTests('./testcafe-fixtures/drag.testcafe', 'Drag invisible element to another element', { shouldFail: true }) .catch(function (errs) { expect(errs[0]).contains('The element that matches the specified selector is not visible.'); expect(errs[0]).contains('[[Drag invisible element to another element callsite]]'); }); }); it("Should fail if a destination element doesn't exist", function () { return runTests('./testcafe-fixtures/drag.testcafe', 'Drag to non-existent element', { shouldFail: true }) .catch(function (errs) { expect(errs[0]).contains( 'The specified "destinationSelector" does not match any element in the DOM tree.' + ' > | Selector(\'#non-existent\')' ); expect(errs[0]).contains('[[Drag to non-existent element callsite]]'); }); }); it('Should fail if a destination element is invisible', function () { return runTests('./testcafe-fixtures/drag.testcafe', 'Drag to invisible element', { shouldFail: true }) .catch(function (errs) { expect(errs[0]).contains('The element that matches the specified "destinationSelector" is not visible.'); expect(errs[0]).contains('[[Drag to invisible element callsite]]'); }); }); }); });
/** * Created by aleckim on 2017. 7. 11.. */ "use strict"; var Logger = require('../lib/log'); global.log = new Logger(__dirname + "/debug.log"); var assert = require('assert'); describe('unit test - kasi rise set controller', function() { //it('test gather rise set from api', function (done) { // this.timeout(24*60*60*1000); // var KasiRiseSet = require('../controllers/kasi.riseset.controller'); // // KasiRiseSet.gatherAreaRiseSetFromApi(function (err, results) { // if (err) { // log.error(err); // } // else { // log.info(results); // } // done(); // }); //}); });
import { module, test } from '../qunit'; import moment from '../../moment'; module('weeks in year'); test('isoWeeksInYear', function (assert) { assert.equal( moment([2005]).isoWeeksInYear(), 52, 'ISO year 2005 has 52 iso weeks' ); assert.equal( moment([2006]).isoWeeksInYear(), 52, 'ISO year 2006 has 52 iso weeks' ); assert.equal( moment([2009]).isoWeeksInYear(), 53, 'ISO year 2009 has 53 iso weeks' ); assert.equal( moment([2010]).isoWeeksInYear(), 52, 'ISO year 2010 has 52 iso weeks' ); }); test('isoWeeksInISOWeekYear first day of ISO Year', function (assert) { assert.equal( moment('2003-12-29').isoWeeksInISOWeekYear(), 53, 'ISO year 2004 has 53 iso weeks' ); assert.equal( moment('2005-01-03').isoWeeksInISOWeekYear(), 52, 'ISO year 2005 has 53 iso weeks' ); assert.equal( moment('2006-01-02').isoWeeksInISOWeekYear(), 52, 'ISO year 2006 has 53 iso weeks' ); assert.equal( moment('2007-01-01').isoWeeksInISOWeekYear(), 52, 'ISO year 2007 has 52 iso weeks' ); assert.equal( moment('2007-12-31').isoWeeksInISOWeekYear(), 52, 'ISO year 2008 has 53 iso weeks' ); assert.equal( moment('2008-12-29').isoWeeksInISOWeekYear(), 53, 'ISO year 2009 has 53 iso weeks' ); assert.equal( moment('2010-01-04').isoWeeksInISOWeekYear(), 52, 'ISO year 2010 has 52 iso weeks' ); assert.equal( moment('2011-01-03').isoWeeksInISOWeekYear(), 52, 'ISO year 2011 has 52 iso weeks' ); assert.equal( moment('2012-01-02').isoWeeksInISOWeekYear(), 52, 'ISO year 2012 has 52 iso weeks' ); assert.equal( moment('2012-12-31').isoWeeksInISOWeekYear(), 52, 'ISO year 2013 has 52 iso weeks' ); assert.equal( moment('2013-12-30').isoWeeksInISOWeekYear(), 52, 'ISO year 2014 has 52 iso weeks' ); assert.equal( moment('2014-12-29').isoWeeksInISOWeekYear(), 53, 'ISO year 2015 has 53 iso weeks' ); assert.equal( moment('2016-01-04').isoWeeksInISOWeekYear(), 52, 'ISO year 2016 has 52 iso weeks' ); assert.equal( moment('2017-01-02').isoWeeksInISOWeekYear(), 52, 'ISO year 2017 has 52 iso weeks' ); assert.equal( moment('2018-01-01').isoWeeksInISOWeekYear(), 52, 'ISO year 2018 has 52 iso weeks' ); assert.equal( moment('2018-12-31').isoWeeksInISOWeekYear(), 52, 'ISO year 2019 has 52 iso weeks' ); assert.equal( moment('2019-12-30').isoWeeksInISOWeekYear(), 53, 'ISO year 2020 has 53 iso weeks' ); }); test('weeksInYear doy/dow = 1/4', function (assert) { moment.locale('1/4', { week: { dow: 1, doy: 4 } }); assert.equal(moment('2004-01-01').weeksInYear(), 53, '2004 has 53 weeks'); assert.equal(moment('2005-01-01').weeksInYear(), 52, '2005 has 52 weeks'); assert.equal( moment('2005-01-01').weeksInWeekYear(), 53, '2005-01-01 is weekYear 2014, which has 53 weeks' ); assert.equal(moment('2006-01-01').weeksInYear(), 52, '2006 has 52 weeks'); assert.equal(moment('2007-01-01').weeksInYear(), 52, '2007 has 52 weeks'); assert.equal(moment('2008-01-01').weeksInYear(), 52, '2008 has 52 weeks'); assert.equal(moment('2009-01-01').weeksInYear(), 53, '2009 has 53 weeks'); assert.equal(moment('2010-01-01').weeksInYear(), 52, '2010 has 52 weeks'); assert.equal( moment('2010-01-01').weeksInWeekYear(), 53, '2010-01-01 is weekYear 2009, which has 53 weeks' ); assert.equal(moment('2011-01-01').weeksInYear(), 52, '2011 has 52 weeks'); assert.equal(moment('2012-01-01').weeksInYear(), 52, '2012 has 52 weeks'); assert.equal(moment('2013-01-01').weeksInYear(), 52, '2013 has 52 weeks'); assert.equal(moment('2014-01-01').weeksInYear(), 52, '2014 has 52 weeks'); assert.equal(moment('2015-01-01').weeksInYear(), 53, '2015 has 53 weeks'); assert.equal(moment('2016-01-01').weeksInYear(), 52, '2016 has 52 weeks'); assert.equal( moment('2016-01-01').weeksInWeekYear(), 53, '2016-01-01 is weekYear 2015, which has 53 weeks' ); }); test('weeksInYear doy/dow = 6/12', function (assert) { moment.locale('6/12', { week: { dow: 6, doy: 12 } }); assert.equal(moment([2004]).weeksInYear(), 53, '2004 has 53 weeks'); assert.equal(moment([2005]).weeksInYear(), 52, '2005 has 52 weeks'); assert.equal(moment([2006]).weeksInYear(), 52, '2006 has 52 weeks'); assert.equal(moment([2007]).weeksInYear(), 52, '2007 has 52 weeks'); assert.equal(moment([2008]).weeksInYear(), 52, '2008 has 52 weeks'); assert.equal(moment([2009]).weeksInYear(), 52, '2009 has 52 weeks'); assert.equal(moment([2010]).weeksInYear(), 53, '2010 has 53 weeks'); assert.equal(moment([2011]).weeksInYear(), 52, '2011 has 52 weeks'); assert.equal(moment([2012]).weeksInYear(), 52, '2012 has 52 weeks'); assert.equal(moment([2013]).weeksInYear(), 52, '2013 has 52 weeks'); assert.equal(moment([2014]).weeksInYear(), 52, '2014 has 52 weeks'); assert.equal(moment([2015]).weeksInYear(), 52, '2015 has 52 weeks'); }); test('weeksInYear doy/dow = 1/7', function (assert) { moment.locale('1/7', { week: { dow: 1, doy: 7 } }); assert.equal(moment([2004]).weeksInYear(), 52, '2004 has 52 weeks'); assert.equal(moment([2005]).weeksInYear(), 52, '2005 has 52 weeks'); assert.equal(moment([2006]).weeksInYear(), 53, '2006 has 53 weeks'); assert.equal(moment([2007]).weeksInYear(), 52, '2007 has 52 weeks'); assert.equal(moment([2008]).weeksInYear(), 52, '2008 has 52 weeks'); assert.equal(moment([2009]).weeksInYear(), 52, '2009 has 52 weeks'); assert.equal(moment([2010]).weeksInYear(), 52, '2010 has 52 weeks'); assert.equal(moment([2011]).weeksInYear(), 52, '2011 has 52 weeks'); assert.equal(moment([2012]).weeksInYear(), 53, '2012 has 53 weeks'); assert.equal(moment([2013]).weeksInYear(), 52, '2013 has 52 weeks'); assert.equal(moment([2014]).weeksInYear(), 52, '2014 has 52 weeks'); assert.equal(moment([2015]).weeksInYear(), 52, '2015 has 52 weeks'); assert.equal(moment([2016]).weeksInYear(), 52, '2016 has 52 weeks'); }); test('weeksInYear doy/dow = 0/6', function (assert) { moment.locale('0/6', { week: { dow: 0, doy: 6 } }); assert.equal(moment([2004]).weeksInYear(), 52, '2004 has 53 weeks'); assert.equal(moment([2005]).weeksInYear(), 53, '2005 has 53 weeks'); assert.equal(moment([2006]).weeksInYear(), 52, '2006 has 53 weeks'); assert.equal(moment([2007]).weeksInYear(), 52, '2007 has 52 weeks'); assert.equal(moment([2008]).weeksInYear(), 52, '2008 has 53 weeks'); assert.equal(moment([2009]).weeksInYear(), 52, '2009 has 53 weeks'); assert.equal(moment([2010]).weeksInYear(), 52, '2010 has 52 weeks'); assert.equal(moment([2011]).weeksInYear(), 53, '2011 has 52 weeks'); assert.equal(moment([2012]).weeksInYear(), 52, '2012 has 52 weeks'); assert.equal(moment([2013]).weeksInYear(), 52, '2013 has 52 weeks'); assert.equal(moment([2014]).weeksInYear(), 52, '2014 has 52 weeks'); assert.equal(moment([2015]).weeksInYear(), 52, '2015 has 53 weeks'); }); test('isoWeeksInYear calendar year !== ISO year', function (assert) { var m = moment('2010-01-01'); assert.equal( moment('2019-12-31').isoWeeksInISOWeekYear(), 53, 'December 31, 2019 is in ISO year 2020 and ISO year 2020 has 53 weeks' ); assert.equal( moment('2020-12-31').isoWeeksInISOWeekYear(), 53, 'December 31, 2020 is in ISO year 2020 and ISO year 2020 has 53 weeks' ); assert.equal( m.isoWeeksInISOWeekYear(), 53, '2010-01-01 is isoWeekYear 2009, which has 53 iso weeks' ); assert.equal( +m, +moment('2010-01-01'), 'isoWeeksInYear does not modify moment object' ); });
/* * arrive.js * v2.2.0 * https://github.com/uzairfarooq/arrive * MIT licensed * * Copyright (c) 2014-2015 Uzair Farooq */ (function(window, $, undefined) { "use strict"; if(!window.MutationObserver || typeof HTMLElement === 'undefined'){ return; //for unsupported browsers } var arriveUniqueId = 0; var utils = (function() { var matches = HTMLElement.prototype.matches || HTMLElement.prototype.webkitMatchesSelector || HTMLElement.prototype.mozMatchesSelector || HTMLElement.prototype.msMatchesSelector; return { matchesSelector: function(elem, selector) { return elem instanceof HTMLElement && matches.call(elem, selector); }, // to enable function overloading - By John Resig (MIT Licensed) addMethod: function (object, name, fn) { var old = object[ name ]; object[ name ] = function(){ if ( fn.length == arguments.length ) return fn.apply( this, arguments ); else if ( typeof old == 'function' ) return old.apply( this, arguments ); }; } }; })(); // Class to maintain state of all registered events of a single type var EventsBucket = (function() { var EventsBucket = function() { // holds all the events this._eventsBucket = []; // function to be called while adding an event, the function should do the event initialization/registration this._beforeAdding = null; // function to be called while removing an event, the function should do the event destruction this._beforeRemoving = null; }; EventsBucket.prototype.addEvent = function(target, selector, options, callback) { var newEvent = { target: target, selector: selector, options: options, callback: callback, firedElems: [] }; if (this._beforeAdding) { this._beforeAdding(newEvent); } this._eventsBucket.push(newEvent); return newEvent; }; EventsBucket.prototype.removeEvent = function(compareFunction) { for (var i=this._eventsBucket.length - 1, registeredEvent; registeredEvent = this._eventsBucket[i]; i--) { if (compareFunction(registeredEvent)) { if (this._beforeRemoving) { this._beforeRemoving(registeredEvent); } this._eventsBucket.splice(i, 1); } } }; EventsBucket.prototype.beforeAdding = function(beforeAdding) { this._beforeAdding = beforeAdding; }; EventsBucket.prototype.beforeRemoving = function(beforeRemoving) { this._beforeRemoving = beforeRemoving; }; return EventsBucket; })(); /** * @constructor * General class for binding/unbinding arrive and leave events */ var MutationEvents = function(getObserverConfig, defaultOptions, onMutation) { var eventsBucket = new EventsBucket(), me = this; // actual event registration before adding it to bucket eventsBucket.beforeAdding(function(registrationData) { var target = registrationData.target, selector = registrationData.selector, callback = registrationData.callback, observer; // mutation observer does not work on window or document if (target === window.document || target === window) target = document.getElementsByTagName("html")[0]; // Create an observer instance observer = new MutationObserver(function(e) { onMutation.call(this, e, registrationData); }); var config = getObserverConfig(registrationData.options); observer.observe(target, config); registrationData.observer = observer; registrationData.me = me; }); // cleanup/unregister before removing an event eventsBucket.beforeRemoving(function (eventData) { eventData.observer.disconnect(); }); function toArray(elements) { if (typeof elements.length !== "number") { elements = [elements]; } return elements; } this.bindEvent = function(selector, options, callback) { if (typeof callback === "undefined") { callback = options; options = defaultOptions; } else { options = mergeOptions(defaultOptions, options); } var elements = toArray(this); for (var i = 0; i < elements.length; i++) { eventsBucket.addEvent(elements[i], selector, options, callback); } }; this.unbindEvent = function() { var elements = toArray(this); eventsBucket.removeEvent(function(eventObj) { for (var i = 0; i < elements.length; i++) { if (eventObj.target === elements[i]) { return true; } } return false; }); }; this.unbindEventWithSelectorOrCallback = function(selector) { var elements = toArray(this), callback = selector, compareFunction; if (typeof selector === "function") { compareFunction = function(eventObj) { for (var i = 0; i < elements.length; i++) { if (eventObj.target === elements[i] && eventObj.callback === callback) { return true; } } return false; }; } else { compareFunction = function(eventObj) { for (var i = 0; i < elements.length; i++) { if (eventObj.target === elements[i] && eventObj.selector === selector) { return true; } } return false; }; } eventsBucket.removeEvent(compareFunction); }; this.unbindEventWithSelectorAndCallback = function(selector, callback) { var elements = toArray(this); eventsBucket.removeEvent(function(eventObj) { for (var i = 0; i < elements.length; i++) { if (eventObj.target === elements[i] && eventObj.selector === selector && eventObj.callback === callback) { return true; } } return false; }); }; return this; }; function checkNode(node, registrationData, callbacksToBeCalled) { // check a single node to see if it matches the selector if (utils.matchesSelector(node, registrationData.selector)) { if(node._id === undefined) { node._id = arriveUniqueId++; } // make sure the arrive event is not already fired for the element if (registrationData.firedElems.indexOf(node._id) == -1) { if (registrationData.options.onceOnly) { if (registrationData.firedElems.length === 0) { // On first callback, unbind event. registrationData.me.unbindEventWithSelectorAndCallback.call( registrationData.target, registrationData.selector, registrationData.callback); } else { // Ignore multiple mutations which may have been queued before the event was unbound. return; } } registrationData.firedElems.push(node._id); callbacksToBeCalled.push({ callback: registrationData.callback, elem: node }); } } } // traverse through all descendants of a node to check if event should be fired for any descendant function checkChildNodesRecursively(nodes, registrationData, callbacksToBeCalled) { // check each new node if it matches the selector for (var i=0, node; node = nodes[i]; i++) { checkNode(node, registrationData, callbacksToBeCalled); if (node.childNodes.length > 0) { checkChildNodesRecursively(node.childNodes, registrationData, callbacksToBeCalled); } } } function callCallbacks(callbacksToBeCalled) { for (var i = 0, cb; cb = callbacksToBeCalled[i]; i++) { cb.callback.call(cb.elem); } } function onArriveMutation(mutations, registrationData) { mutations.forEach(function( mutation ) { var newNodes = mutation.addedNodes, targetNode = mutation.target, callbacksToBeCalled = []; // If new nodes are added if( newNodes !== null && newNodes.length > 0 ) { checkChildNodesRecursively(newNodes, registrationData, callbacksToBeCalled); } else if (mutation.type === "attributes") { checkNode(targetNode, registrationData, callbacksToBeCalled); } callCallbacks(callbacksToBeCalled); }); } function onLeaveMutation(mutations, registrationData) { mutations.forEach(function( mutation ) { var removedNodes = mutation.removedNodes, targetNode = mutation.target, callbacksToBeCalled = []; if( removedNodes !== null && removedNodes.length > 0 ) { checkChildNodesRecursively(removedNodes, registrationData, callbacksToBeCalled); } callCallbacks(callbacksToBeCalled); }); } function getArriveObserverConfig(options) { var config = { attributes: false, childList: true, subtree: true }; if (options.fireOnAttributesModification) { config.attributes = true; } return config; } function getLeaveObserverConfig(options) { var config = { childList: true, subtree: true }; return config; } function mergeOptions(defaultOpts, userOpts){ // Overwrites default options with user-defined options. var options = {}; for (var attrname in defaultOpts) { options[attrname] = defaultOpts[attrname]; } for (var attrname in userOpts) { options[attrname] = userOpts[attrname]; } return options; } // Default options var arriveDefaultOptions = { fireOnAttributesModification: false, onceOnly: false }, leaveDefaultOptions = {}; var arriveEvents = new MutationEvents(getArriveObserverConfig, arriveDefaultOptions, onArriveMutation), leaveEvents = new MutationEvents(getLeaveObserverConfig, leaveDefaultOptions, onLeaveMutation); /*** expose APIs ***/ function exposeApi(exposeTo) { exposeTo.arrive = arriveEvents.bindEvent; // expose unbindArrive function with overriding utils.addMethod(exposeTo, "unbindArrive", arriveEvents.unbindEvent); utils.addMethod(exposeTo, "unbindArrive", arriveEvents.unbindEventWithSelectorOrCallback); utils.addMethod(exposeTo, "unbindArrive", arriveEvents.unbindEventWithSelectorAndCallback); exposeTo.leave = leaveEvents.bindEvent; // expose unbindLeave function with overriding utils.addMethod(exposeTo, "unbindLeave", leaveEvents.unbindEvent); utils.addMethod(exposeTo, "unbindLeave", leaveEvents.unbindEventWithSelectorOrCallback); utils.addMethod(exposeTo, "unbindLeave", leaveEvents.unbindEventWithSelectorAndCallback); } if ($) { exposeApi($.fn); } exposeApi(HTMLElement.prototype); exposeApi(NodeList.prototype); exposeApi(HTMLCollection.prototype); exposeApi(HTMLDocument.prototype); exposeApi(Window.prototype); })(this, typeof jQuery === 'undefined' ? null : jQuery, undefined);
Tinytest.add("blaze-tools - token parsers", function (test) { var run = function (func, input, expected) { var scanner = new HTMLTools.Scanner('z' + input); // make sure the parse function respects `scanner.pos` scanner.pos = 1; var result = func(scanner); if (expected === null) { test.equal(scanner.pos, 1); test.equal(result, null); } else { test.isTrue(scanner.isEOF()); test.equal(result, expected); } }; var runValue = function (func, input, expectedValue) { var expected; if (expectedValue === null) expected = null; else expected = { text: input, value: expectedValue }; run(func, input, expected); }; var parseNumber = BlazeTools.parseNumber; var parseIdentifierName = BlazeTools.parseIdentifierName; var parseStringLiteral = BlazeTools.parseStringLiteral; runValue(parseNumber, "0", 0); runValue(parseNumber, "-0", 0); runValue(parseNumber, "-", null); runValue(parseNumber, ".a", null); runValue(parseNumber, ".1", 0.1); runValue(parseNumber, "1.", 1); runValue(parseNumber, "1.1", 1.1); runValue(parseNumber, "0x", null); runValue(parseNumber, "0xa", 10); runValue(parseNumber, "-0xa", -10); runValue(parseNumber, "1e+1", 10); run(parseIdentifierName, "a", "a"); run(parseIdentifierName, "true", "true"); run(parseIdentifierName, "null", "null"); run(parseIdentifierName, "if", "if"); run(parseIdentifierName, "1", null); run(parseIdentifierName, "1a", null); run(parseIdentifierName, "+a", null); run(parseIdentifierName, "a1", "a1"); run(parseIdentifierName, "a1a", "a1a"); run(parseIdentifierName, "_a8f_f8d88_", "_a8f_f8d88_"); runValue(parseStringLiteral, '"a"', 'a'); runValue(parseStringLiteral, '"\'"', "'"); runValue(parseStringLiteral, '\'"\'', '"'); runValue(parseStringLiteral, '"a\\\nb"', 'ab'); // line continuation runValue(parseStringLiteral, '"a\u0062c"', 'abc'); // Note: IE 8 doesn't correctly parse '\v' in JavaScript. runValue(parseStringLiteral, '"\\0\\b\\f\\n\\r\\t\\v"', '\0\b\f\n\r\t\u000b'); runValue(parseStringLiteral, '"\\x41"', 'A'); runValue(parseStringLiteral, '"\\\\"', '\\'); runValue(parseStringLiteral, '"\\\""', '\"'); runValue(parseStringLiteral, '"\\\'"', '\''); runValue(parseStringLiteral, "'\\\\'", '\\'); runValue(parseStringLiteral, "'\\\"'", '\"'); runValue(parseStringLiteral, "'\\\''", '\''); });
'use strict'; var personalsApp = angular.module('personals'); personalsApp.controller('ApptSlotController', ['$scope', 'slotService', function($scope, slotService) { $scope.slotList = slotService.slotList; $scope.slot = []; $scope.disabled = false; $scope.dayOptions = [ { label: 'Monday' }, { label: 'Tuesday' }, { label: 'Wednesday' }, { label: 'Thursday' }, { label: 'Friday' }, { label: 'Saturday' }, { label: 'Sunday' } ]; var refresh = function(personal) { console.log(personal); slotService.slotList = personal.slots; $scope.slot = ''; $scope.disabled = false; }; // Create new Appt Slot $scope.addSlots = function() { console.log(slotService.slotList); slotService.slotList.push({ day: $scope.slot.selectedDay.label, location: $scope.slot.location, starttime: $scope.slot.starttime, endtime: $scope.slot.endtime }); $scope.slotList = slotService.slotList; }; // Remove existing Slot $scope.remove = function(personal, slot) { if (slot) { for (var i in this.slotList) { if (this.slotList[i] === slot) { this.slotList.splice(i, 1); } } } else { this.slot.$remove(function() { }); } }; // Update existing Slot $scope.update = function(personal) { personal.slots = []; for (var index = 0; index < slotService.slotList.length; index++) { personal.slots.push( { day: slotService.slotList[index].day, starttime: slotService.slotList[index].starttime, endtime: slotService.slotList[index].endtime, location: slotService.slotList[index].location } ); } personal.$update(function() { refresh(personal); }, function(errorResponse) { $scope.error = errorResponse.data.message; console.log(errorResponse.data.message); }); }; $scope.edit = function(slot) { for (var i in this.slotList) { if (this.slotList[i] === slot) { $scope.slot = slot; } } $scope.disabled = true; }; $scope.deselect = function() { $scope.slot = ''; $scope.disabled = false; }; } ]);
/** * @author alteredq / http://alteredqualia.com/ * * Dot screen shader * based on glfx.js sepia shader * https://github.com/evanw/glfx.js */ THREE.DotScreenRGBShader = { uniforms: { "tDiffuse": { type: "t", value: null }, "tSize": { type: "v2", value: new THREE.Vector2( 256, 256 ) }, "center": { type: "v2", value: new THREE.Vector2( 0.5, 0.5 ) }, "angle": { type: "f", value: 1.57 }, "scale": { type: "f", value: 1.0 } }, vertexShader: [ "varying vec2 vUv;", "void main() {", "vUv = uv;", "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );", "}" ].join("\n"), fragmentShader: [ "uniform vec2 center;", "uniform float angle;", "uniform float scale;", "uniform vec2 tSize;", "uniform sampler2D tDiffuse;", "varying vec2 vUv;", "float pattern() {", "float s = sin( angle ), c = cos( angle );", "vec2 tex = vUv * tSize - center;", "vec2 point = vec2( c * tex.x - s * tex.y, s * tex.x + c * tex.y ) * scale;", "return ( sin( point.x ) * sin( point.y ) ) * 4.0;", "}", "void main() {", "vec4 color = texture2D( tDiffuse, vUv );", "float r = color.r * 10.0 - 5.0 + pattern();", "float g = color.g * 10.0 - 5.0 + pattern();", "float b = color.b * 10.0 - 5.0 + pattern();", "gl_FragColor = vec4( r, g, b, color.a );", "}" ].join("\n") };
import { TempNode } from '../core/TempNode.js'; import { FunctionNode } from '../core/FunctionNode.js'; import { UVNode } from '../accessors/UVNode.js'; class CheckerNode extends TempNode { constructor( uv ) { super( 'f' ); this.uv = uv || new UVNode(); } generate( builder, output ) { const snoise = builder.include( CheckerNode.Nodes.checker ); return builder.format( snoise + '( ' + this.uv.build( builder, 'v2' ) + ' )', this.getType( builder ), output ); } copy( source ) { super.copy( source ); this.uv = source.uv; return this; } toJSON( meta ) { let data = this.getJSONNode( meta ); if ( ! data ) { data = this.createJSONNode( meta ); data.uv = this.uv.toJSON( meta ).uuid; } return data; } } CheckerNode.Nodes = ( function () { // https://github.com/mattdesl/glsl-checker/blob/master/index.glsl const checker = new FunctionNode( /* glsl */` float checker( vec2 uv ) { float cx = floor( uv.x ); float cy = floor( uv.y ); float result = mod( cx + cy, 2.0 ); return sign( result ); }` ); return { checker: checker }; } )(); CheckerNode.prototype.nodeType = 'Noise'; export { CheckerNode };
/** * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/> * Build: `lodash modularize modern exports="amd" -o ./modern/` * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE> * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <http://lodash.com/license> */ define(['../functions/createCallback', '../utilities/identity'], function(createCallback, identity) { /** * Uses a binary search to determine the smallest index at which a value * should be inserted into a given sorted array in order to maintain the sort * order of the array. If a callback is provided it will be executed for * `value` and each element of `array` to compute their sort ranking. The * callback is bound to `thisArg` and invoked with one argument; (value). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Arrays * @param {Array} array The array to inspect. * @param {*} value The value to evaluate. * @param {Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {number} Returns the index at which `value` should be inserted * into `array`. * @example * * _.sortedIndex([20, 30, 50], 40); * // => 2 * * // using "_.pluck" callback shorthand * _.sortedIndex([{ 'x': 20 }, { 'x': 30 }, { 'x': 50 }], { 'x': 40 }, 'x'); * // => 2 * * var dict = { * 'wordToNumber': { 'twenty': 20, 'thirty': 30, 'fourty': 40, 'fifty': 50 } * }; * * _.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function(word) { * return dict.wordToNumber[word]; * }); * // => 2 * * _.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function(word) { * return this.wordToNumber[word]; * }, dict); * // => 2 */ function sortedIndex(array, value, callback, thisArg) { var low = 0, high = array ? array.length : low; // explicitly reference `identity` for better inlining in Firefox callback = callback ? createCallback(callback, thisArg, 1) : identity; value = callback(value); while (low < high) { var mid = (low + high) >>> 1; (callback(array[mid]) < value) ? low = mid + 1 : high = mid; } return low; } return sortedIndex; });
window._loadedScripts = window._loadedScripts || {}; window._loadedScripts['mscorlib'] = true; //! Script# Core Runtime //! More information at http://projects.nikhilk.net/ScriptSharp //! (function () { var globals = { version: '0.7.4.0', isUndefined: function (o) { return (o === undefined); }, isNull: function (o) { return (o === null); }, isNullOrUndefined: function (o) { return (o === null) || (o === undefined); }, isValue: function (o) { return (o !== null) && (o !== undefined); } }; var started = false; var startCallbacks = []; function onStartup(cb) { startCallbacks ? startCallbacks.push(cb) : setTimeout(cb, 0); } function startup() { if (startCallbacks) { var callbacks = startCallbacks; startCallbacks = null; for (var i = 0, l = callbacks.length; i < l; i++) { callbacks[i](); } } } if (document.addEventListener) { document.readyState == 'complete' ? startup() : document.addEventListener('DOMContentLoaded', startup, false); } else if (window.attachEvent) { window.attachEvent('onload', function () { startup(); }); } var ss = window.ss; if (!ss) { window.ss = ss = { init: onStartup, ready: onStartup }; } for (var n in globals) { ss[n] = globals[n]; } })(); /////////////////////////////////////////////////////////////////////////////// // Object Extensions Object.__typeName = 'Object'; Object.__baseType = null; Object.clearKeys = function Object$clearKeys(d) { for (var n in d) { delete d[n]; } } Object.keyExists = function Object$keyExists(d, key) { return d[key] !== undefined; } if (!Object.keys) { Object.keys = function Object$keys(d) { var keys = []; for (var n in d) { keys.push(n); } return keys; } Object.getKeyCount = function Object$getKeyCount(d) { var count = 0; for (var n in d) { count++; } return count; } } else { Object.getKeyCount = function Object$getKeyCount(d) { return Object.keys(d).length; } } /////////////////////////////////////////////////////////////////////////////// // Boolean Extensions Boolean.__typeName = 'Boolean'; Boolean.parse = function Boolean$parse(s) { return (s.toLowerCase() == 'true'); } /////////////////////////////////////////////////////////////////////////////// // Number Extensions Number.__typeName = 'Number'; Number.parse = function Number$parse(s) { if (!s || !s.length) { return 0; } if ((s.indexOf('.') >= 0) || (s.indexOf('e') >= 0) || s.endsWith('f') || s.endsWith('F')) { return parseFloat(s); } return parseInt(s, 10); } Number.prototype.format = function Number$format(format) { if (ss.isNullOrUndefined(format) || (format.length == 0) || (format == 'i')) { return this.toString(); } return this._netFormat(format, false); } Number.prototype.localeFormat = function Number$format(format) { if (ss.isNullOrUndefined(format) || (format.length == 0) || (format == 'i')) { return this.toLocaleString(); } return this._netFormat(format, true); } Number._commaFormat = function Number$_commaFormat(number, groups, decimal, comma) { var decimalPart = null; var decimalIndex = number.indexOf(decimal); if (decimalIndex > 0) { decimalPart = number.substr(decimalIndex); number = number.substr(0, decimalIndex); } var negative = number.startsWith('-'); if (negative) { number = number.substr(1); } var groupIndex = 0; var groupSize = groups[groupIndex]; if (number.length < groupSize) { return decimalPart ? number + decimalPart : number; } var index = number.length; var s = ''; var done = false; while (!done) { var length = groupSize; var startIndex = index - length; if (startIndex < 0) { groupSize += startIndex; length += startIndex; startIndex = 0; done = true; } if (!length) { break; } var part = number.substr(startIndex, length); if (s.length) { s = part + comma + s; } else { s = part; } index -= length; if (groupIndex < groups.length - 1) { groupIndex++; groupSize = groups[groupIndex]; } } if (negative) { s = '-' + s; } return decimalPart ? s + decimalPart : s; } Number.prototype._netFormat = function Number$_netFormat(format, useLocale) { var nf = useLocale ? ss.CultureInfo.CurrentCulture.numberFormat : ss.CultureInfo.InvariantCulture.numberFormat; var s = ''; var precision = -1; if (format.length > 1) { precision = parseInt(format.substr(1)); } var fs = format.charAt(0); switch (fs) { case 'd': case 'D': s = parseInt(Math.abs(this)).toString(); if (precision != -1) { s = s.padLeft(precision, '0'); } if (this < 0) { s = '-' + s; } break; case 'x': case 'X': s = parseInt(Math.abs(this)).toString(16); if (fs == 'X') { s = s.toUpperCase(); } if (precision != -1) { s = s.padLeft(precision, '0'); } break; case 'e': case 'E': if (precision == -1) { s = this.toExponential(); } else { s = this.toExponential(precision); } if (fs == 'E') { s = s.toUpperCase(); } break; case 'f': case 'F': case 'n': case 'N': if (precision == -1) { precision = nf.numberDecimalDigits; } s = this.toFixed(precision).toString(); if (precision && (nf.numberDecimalSeparator != '.')) { var index = s.indexOf('.'); s = s.substr(0, index) + nf.numberDecimalSeparator + s.substr(index + 1); } if ((fs == 'n') || (fs == 'N')) { s = Number._commaFormat(s, nf.numberGroupSizes, nf.numberDecimalSeparator, nf.numberGroupSeparator); } break; case 'c': case 'C': if (precision == -1) { precision = nf.currencyDecimalDigits; } s = Math.abs(this).toFixed(precision).toString(); if (precision && (nf.currencyDecimalSeparator != '.')) { var index = s.indexOf('.'); s = s.substr(0, index) + nf.currencyDecimalSeparator + s.substr(index + 1); } s = Number._commaFormat(s, nf.currencyGroupSizes, nf.currencyDecimalSeparator, nf.currencyGroupSeparator); if (this < 0) { s = String.format(nf.currencyNegativePattern, s); } else { s = String.format(nf.currencyPositivePattern, s); } break; case 'p': case 'P': if (precision == -1) { precision = nf.percentDecimalDigits; } s = (Math.abs(this) * 100.0).toFixed(precision).toString(); if (precision && (nf.percentDecimalSeparator != '.')) { var index = s.indexOf('.'); s = s.substr(0, index) + nf.percentDecimalSeparator + s.substr(index + 1); } s = Number._commaFormat(s, nf.percentGroupSizes, nf.percentDecimalSeparator, nf.percentGroupSeparator); if (this < 0) { s = String.format(nf.percentNegativePattern, s); } else { s = String.format(nf.percentPositivePattern, s); } break; } return s; } /////////////////////////////////////////////////////////////////////////////// // String Extensions String.__typeName = 'String'; String.Empty = ''; String.compare = function String$compare(s1, s2, ignoreCase) { if (ignoreCase) { if (s1) { s1 = s1.toUpperCase(); } if (s2) { s2 = s2.toUpperCase(); } } s1 = s1 || ''; s2 = s2 || ''; if (s1 == s2) { return 0; } if (s1 < s2) { return -1; } return 1; } String.prototype.compareTo = function String$compareTo(s, ignoreCase) { return String.compare(this, s, ignoreCase); } String.concat = function String$concat() { if (arguments.length === 2) { return arguments[0] + arguments[1]; } return Array.prototype.join.call(arguments, ''); } String.prototype.endsWith = function String$endsWith(suffix) { if (!suffix.length) { return true; } if (suffix.length > this.length) { return false; } return (this.substr(this.length - suffix.length) == suffix); } String.equals = function String$equals1(s1, s2, ignoreCase) { return String.compare(s1, s2, ignoreCase) == 0; } String._format = function String$_format(format, values, useLocale) { if (!String._formatRE) { String._formatRE = /(\{[^\}^\{]+\})/g; } return format.replace(String._formatRE, function(str, m) { var index = parseInt(m.substr(1)); var value = values[index + 1]; if (ss.isNullOrUndefined(value)) { return ''; } if (value.format) { var formatSpec = null; var formatIndex = m.indexOf(':'); if (formatIndex > 0) { formatSpec = m.substring(formatIndex + 1, m.length - 1); } return useLocale ? value.localeFormat(formatSpec) : value.format(formatSpec); } else { return useLocale ? value.toLocaleString() : value.toString(); } }); } String.format = function String$format(format) { return String._format(format, arguments, /* useLocale */ false); } String.fromChar = function String$fromChar(ch, count) { var s = ch; for (var i = 1; i < count; i++) { s += ch; } return s; } String.prototype.htmlDecode = function String$htmlDecode() { var div = document.createElement('div'); div.innerHTML = this; return div.textContent || div.innerText; } String.prototype.htmlEncode = function String$htmlEncode() { var div = document.createElement('div'); div.appendChild(document.createTextNode(this)); return div.innerHTML.replace(/\"/g, '&quot;'); } String.prototype.indexOfAny = function String$indexOfAny(chars, startIndex, count) { var length = this.length; if (!length) { return -1; } startIndex = startIndex || 0; count = count || length; var endIndex = startIndex + count - 1; if (endIndex >= length) { endIndex = length - 1; } for (var i = startIndex; i <= endIndex; i++) { if (chars.indexOf(this.charAt(i)) >= 0) { return i; } } return -1; } String.prototype.insert = function String$insert(index, value) { if (!value) { return this.valueOf(); } if (!index) { return value + this; } var s1 = this.substr(0, index); var s2 = this.substr(index); return s1 + value + s2; } String.isNullOrEmpty = function String$isNullOrEmpty(s) { return !s || !s.length; } String.prototype.lastIndexOfAny = function String$lastIndexOfAny(chars, startIndex, count) { var length = this.length; if (!length) { return -1; } startIndex = startIndex || length - 1; count = count || length; var endIndex = startIndex - count + 1; if (endIndex < 0) { endIndex = 0; } for (var i = startIndex; i >= endIndex; i--) { if (chars.indexOf(this.charAt(i)) >= 0) { return i; } } return -1; } String.localeFormat = function String$localeFormat(format) { return String._format(format, arguments, /* useLocale */ true); } String.prototype.padLeft = function String$padLeft(totalWidth, ch) { if (this.length < totalWidth) { ch = ch || ' '; return String.fromChar(ch, totalWidth - this.length) + this; } return this.valueOf(); } String.prototype.padRight = function String$padRight(totalWidth, ch) { if (this.length < totalWidth) { ch = ch || ' '; return this + String.fromChar(ch, totalWidth - this.length); } return this.valueOf(); } String.prototype.remove = function String$remove(index, count) { if (!count || ((index + count) > this.length)) { return this.substr(0, index); } return this.substr(0, index) + this.substr(index + count); } String.prototype.replaceAll = function String$replaceAll(oldValue, newValue) { newValue = newValue || ''; return this.split(oldValue).join(newValue); } String.prototype.startsWith = function String$startsWith(prefix) { if (!prefix.length) { return true; } if (prefix.length > this.length) { return false; } return (this.substr(0, prefix.length) == prefix); } if (!String.prototype.trim) { String.prototype.trim = function String$trim() { return this.trimEnd().trimStart(); } } String.prototype.trimEnd = function String$trimEnd() { return this.replace(/\s*$/, ''); } String.prototype.trimStart = function String$trimStart() { return this.replace(/^\s*/, ''); } /////////////////////////////////////////////////////////////////////////////// // Array Extensions Array.__typeName = 'Array'; Array.__interfaces = [ ss.IEnumerable ]; Array.prototype.add = function Array$add(item) { this[this.length] = item; } Array.prototype.addRange = function Array$addRange(items) { this.push.apply(this, items); } Array.prototype.aggregate = function Array$aggregate(seed, callback, instance) { var length = this.length; for (var i = 0; i < length; i++) { if (i in this) { seed = callback.call(instance, seed, this[i], i, this); } } return seed; } Array.prototype.clear = function Array$clear() { this.length = 0; } Array.prototype.clone = function Array$clone() { if (this.length === 1) { return [this[0]]; } else { return Array.apply(null, this); } } Array.prototype.contains = function Array$contains(item) { var index = this.indexOf(item); return (index >= 0); } Array.prototype.dequeue = function Array$dequeue() { return this.shift(); } Array.prototype.enqueue = function Array$enqueue(item) { // We record that this array instance is a queue, so we // can implement the right behavior in the peek method. this._queue = true; this.push(item); } Array.prototype.peek = function Array$peek() { if (this.length) { var index = this._queue ? 0 : this.length - 1; return this[index]; } return null; } if (!Array.prototype.every) { Array.prototype.every = function Array$every(callback, instance) { var length = this.length; for (var i = 0; i < length; i++) { if (i in this && !callback.call(instance, this[i], i, this)) { return false; } } return true; } } Array.prototype.extract = function Array$extract(index, count) { if (!count) { return this.slice(index); } return this.slice(index, index + count); } if (!Array.prototype.filter) { Array.prototype.filter = function Array$filter(callback, instance) { var length = this.length; var filtered = []; for (var i = 0; i < length; i++) { if (i in this) { var val = this[i]; if (callback.call(instance, val, i, this)) { filtered.push(val); } } } return filtered; } } if (!Array.prototype.forEach) { Array.prototype.forEach = function Array$forEach(callback, instance) { var length = this.length; for (var i = 0; i < length; i++) { if (i in this) { callback.call(instance, this[i], i, this); } } } } Array.prototype.getEnumerator = function Array$getEnumerator() { return new ss.ArrayEnumerator(this); } Array.prototype.groupBy = function Array$groupBy(callback, instance) { var length = this.length; var groups = []; var keys = {}; for (var i = 0; i < length; i++) { if (i in this) { var key = callback.call(instance, this[i], i); if (String.isNullOrEmpty(key)) { continue; } var items = keys[key]; if (!items) { items = []; items.key = key; keys[key] = items; groups.add(items); } items.add(this[i]); } } return groups; } Array.prototype.index = function Array$index(callback, instance) { var length = this.length; var items = {}; for (var i = 0; i < length; i++) { if (i in this) { var key = callback.call(instance, this[i], i); if (String.isNullOrEmpty(key)) { continue; } items[key] = this[i]; } } return items; } if (!Array.prototype.indexOf) { Array.prototype.indexOf = function Array$indexOf(item, startIndex) { startIndex = startIndex || 0; var length = this.length; if (length) { for (var index = startIndex; index < length; index++) { if (this[index] === item) { return index; } } } return -1; } } Array.prototype.insert = function Array$insert(index, item) { this.splice(index, 0, item); } Array.prototype.insertRange = function Array$insertRange(index, items) { if (index === 0) { this.unshift.apply(this, items); } else { for (var i = 0; i < items.length; i++) { this.splice(index + i, 0, items[i]); } } } if (!Array.prototype.map) { Array.prototype.map = function Array$map(callback, instance) { var length = this.length; var mapped = new Array(length); for (var i = 0; i < length; i++) { if (i in this) { mapped[i] = callback.call(instance, this[i], i, this); } } return mapped; } } Array.parse = function Array$parse(s) { return eval('(' + s + ')'); } Array.prototype.remove = function Array$remove(item) { var index = this.indexOf(item); if (index >= 0) { this.splice(index, 1); return true; } return false; } Array.prototype.removeAt = function Array$removeAt(index) { this.splice(index, 1); } Array.prototype.removeRange = function Array$removeRange(index, count) { return this.splice(index, count); } if (!Array.prototype.some) { Array.prototype.some = function Array$some(callback, instance) { var length = this.length; for (var i = 0; i < length; i++) { if (i in this && callback.call(instance, this[i], i, this)) { return true; } } return false; } } Array.toArray = function Array$toArray(obj) { return Array.prototype.slice.call(obj); } /////////////////////////////////////////////////////////////////////////////// // RegExp Extensions RegExp.__typeName = 'RegExp'; RegExp.parse = function RegExp$parse(s) { if (s.startsWith('/')) { var endSlashIndex = s.lastIndexOf('/'); if (endSlashIndex > 1) { var expression = s.substring(1, endSlashIndex); var flags = s.substr(endSlashIndex + 1); return new RegExp(expression, flags); } } return null; } /////////////////////////////////////////////////////////////////////////////// // Date Extensions Date.__typeName = 'Date'; Date.empty = null; Date.get_now = function Date$get_now() { return new Date(); } Date.get_today = function Date$get_today() { var d = new Date(); return new Date(d.getFullYear(), d.getMonth(), d.getDate()); } Date.isEmpty = function Date$isEmpty(d) { return (d === null) || (d.valueOf() === 0); } Date.prototype.format = function Date$format(format) { if (ss.isNullOrUndefined(format) || (format.length == 0) || (format == 'i')) { return this.toString(); } if (format == 'id') { return this.toDateString(); } if (format == 'it') { return this.toTimeString(); } return this._netFormat(format, false); } Date.prototype.localeFormat = function Date$localeFormat(format) { if (ss.isNullOrUndefined(format) || (format.length == 0) || (format == 'i')) { return this.toLocaleString(); } if (format == 'id') { return this.toLocaleDateString(); } if (format == 'it') { return this.toLocaleTimeString(); } return this._netFormat(format, true); } Date.prototype._netFormat = function Date$_netFormat(format, useLocale) { var dt = this; var dtf = useLocale ? ss.CultureInfo.CurrentCulture.dateFormat : ss.CultureInfo.InvariantCulture.dateFormat; if (format.length == 1) { switch (format) { case 'f': format = dtf.longDatePattern + ' ' + dtf.shortTimePattern; break; case 'F': format = dtf.dateTimePattern; break; case 'd': format = dtf.shortDatePattern; break; case 'D': format = dtf.longDatePattern; break; case 't': format = dtf.shortTimePattern; break; case 'T': format = dtf.longTimePattern; break; case 'g': format = dtf.shortDatePattern + ' ' + dtf.shortTimePattern; break; case 'G': format = dtf.shortDatePattern + ' ' + dtf.longTimePattern; break; case 'R': case 'r': dtf = ss.CultureInfo.InvariantCulture.dateFormat; format = dtf.gmtDateTimePattern; break; case 'u': format = dtf.universalDateTimePattern; break; case 'U': format = dtf.dateTimePattern; dt = new Date(dt.getUTCFullYear(), dt.getUTCMonth(), dt.getUTCDate(), dt.getUTCHours(), dt.getUTCMinutes(), dt.getUTCSeconds(), dt.getUTCMilliseconds()); break; case 's': format = dtf.sortableDateTimePattern; break; } } if (format.charAt(0) == '%') { format = format.substr(1); } if (!Date._formatRE) { Date._formatRE = /'.*?[^\\]'|dddd|ddd|dd|d|MMMM|MMM|MM|M|yyyy|yy|y|hh|h|HH|H|mm|m|ss|s|tt|t|fff|ff|f|zzz|zz|z/g; } var re = Date._formatRE; var sb = new ss.StringBuilder(); re.lastIndex = 0; while (true) { var index = re.lastIndex; var match = re.exec(format); sb.append(format.slice(index, match ? match.index : format.length)); if (!match) { break; } var fs = match[0]; var part = fs; switch (fs) { case 'dddd': part = dtf.dayNames[dt.getDay()]; break; case 'ddd': part = dtf.shortDayNames[dt.getDay()]; break; case 'dd': part = dt.getDate().toString().padLeft(2, '0'); break; case 'd': part = dt.getDate(); break; case 'MMMM': part = dtf.monthNames[dt.getMonth()]; break; case 'MMM': part = dtf.shortMonthNames[dt.getMonth()]; break; case 'MM': part = (dt.getMonth() + 1).toString().padLeft(2, '0'); break; case 'M': part = (dt.getMonth() + 1); break; case 'yyyy': part = dt.getFullYear(); break; case 'yy': part = (dt.getFullYear() % 100).toString().padLeft(2, '0'); break; case 'y': part = (dt.getFullYear() % 100); break; case 'h': case 'hh': part = dt.getHours() % 12; if (!part) { part = '12'; } else if (fs == 'hh') { part = part.toString().padLeft(2, '0'); } break; case 'HH': part = dt.getHours().toString().padLeft(2, '0'); break; case 'H': part = dt.getHours(); break; case 'mm': part = dt.getMinutes().toString().padLeft(2, '0'); break; case 'm': part = dt.getMinutes(); break; case 'ss': part = dt.getSeconds().toString().padLeft(2, '0'); break; case 's': part = dt.getSeconds(); break; case 't': case 'tt': part = (dt.getHours() < 12) ? dtf.amDesignator : dtf.pmDesignator; if (fs == 't') { part = part.charAt(0); } break; case 'fff': part = dt.getMilliseconds().toString().padLeft(3, '0'); break; case 'ff': part = dt.getMilliseconds().toString().padLeft(3).substr(0, 2); break; case 'f': part = dt.getMilliseconds().toString().padLeft(3).charAt(0); break; case 'z': part = dt.getTimezoneOffset() / 60; part = ((part >= 0) ? '-' : '+') + Math.floor(Math.abs(part)); break; case 'zz': case 'zzz': part = dt.getTimezoneOffset() / 60; part = ((part >= 0) ? '-' : '+') + Math.floor(Math.abs(part)).toString().padLeft(2, '0'); if (fs == 'zzz') { part += dtf.timeSeparator + Math.abs(dt.getTimezoneOffset() % 60).toString().padLeft(2, '0'); } break; default: if (part.charAt(0) == '\'') { part = part.substr(1, part.length - 2).replace(/\\'/g, '\''); } break; } sb.append(part); } return sb.toString(); } Date.parseDate = function Date$parse(s) { // Date.parse returns the number of milliseconds // so we use that to create an actual Date instance return new Date(Date.parse(s)); } /////////////////////////////////////////////////////////////////////////////// // Error Extensions Error.__typeName = 'Error'; Error.prototype.popStackFrame = function Error$popStackFrame() { if (ss.isNullOrUndefined(this.stack) || ss.isNullOrUndefined(this.fileName) || ss.isNullOrUndefined(this.lineNumber)) { return; } var stackFrames = this.stack.split('\n'); var currentFrame = stackFrames[0]; var pattern = this.fileName + ':' + this.lineNumber; while (!ss.isNullOrUndefined(currentFrame) && currentFrame.indexOf(pattern) === -1) { stackFrames.shift(); currentFrame = stackFrames[0]; } var nextFrame = stackFrames[1]; if (isNullOrUndefined(nextFrame)) { return; } var nextFrameParts = nextFrame.match(/@(.*):(\d+)$/); if (ss.isNullOrUndefined(nextFrameParts)) { return; } stackFrames.shift(); this.stack = stackFrames.join("\n"); this.fileName = nextFrameParts[1]; this.lineNumber = parseInt(nextFrameParts[2]); } Error.createError = function Error$createError(message, errorInfo, innerException) { var e = new Error(message); if (errorInfo) { for (var v in errorInfo) { e[v] = errorInfo[v]; } } if (innerException) { e.innerException = innerException; } e.popStackFrame(); return e; } /////////////////////////////////////////////////////////////////////////////// // Debug Extensions ss.Debug = window.Debug || function() {}; ss.Debug.__typeName = 'Debug'; if (!ss.Debug.writeln) { ss.Debug.writeln = function Debug$writeln(text) { if (window.console) { if (window.console.debug) { window.console.debug(text); return; } else if (window.console.log) { window.console.log(text); return; } } else if (window.opera && window.opera.postError) { window.opera.postError(text); return; } } } ss.Debug._fail = function Debug$_fail(message) { ss.Debug.writeln(message); eval('debugger;'); } ss.Debug.assert = function Debug$assert(condition, message) { if (!condition) { message = 'Assert failed: ' + message; if (confirm(message + '\r\n\r\nBreak into debugger?')) { ss.Debug._fail(message); } } } ss.Debug.fail = function Debug$fail(message) { ss.Debug._fail(message); } /////////////////////////////////////////////////////////////////////////////// // Type System Implementation window.Type = Function; Type.__typeName = 'Type'; window.__Namespace = function(name) { this.__typeName = name; } __Namespace.prototype = { __namespace: true, getName: function() { return this.__typeName; } } Type.registerNamespace = function Type$registerNamespace(name) { if (!window.__namespaces) { window.__namespaces = {}; } if (!window.__rootNamespaces) { window.__rootNamespaces = []; } if (window.__namespaces[name]) { return; } var ns = window; var nameParts = name.split('.'); for (var i = 0; i < nameParts.length; i++) { var part = nameParts[i]; var nso = ns[part]; if (!nso) { ns[part] = nso = new __Namespace(nameParts.slice(0, i + 1).join('.')); if (i == 0) { window.__rootNamespaces.add(nso); } } ns = nso; } window.__namespaces[name] = ns; } Type.prototype.registerClass = function Type$registerClass(name, baseType, interfaceType) { this.prototype.constructor = this; this.__typeName = name; this.__class = true; this.__baseType = baseType || Object; if (baseType) { this.__basePrototypePending = true; } if (interfaceType) { this.__interfaces = []; for (var i = 2; i < arguments.length; i++) { interfaceType = arguments[i]; this.__interfaces.add(interfaceType); } } } Type.prototype.registerInterface = function Type$createInterface(name) { this.__typeName = name; this.__interface = true; } Type.prototype.registerEnum = function Type$createEnum(name, flags) { for (var field in this.prototype) { this[field] = this.prototype[field]; } this.__typeName = name; this.__enum = true; if (flags) { this.__flags = true; } } Type.prototype.setupBase = function Type$setupBase() { if (this.__basePrototypePending) { var baseType = this.__baseType; if (baseType.__basePrototypePending) { baseType.setupBase(); } for (var memberName in baseType.prototype) { var memberValue = baseType.prototype[memberName]; if (!this.prototype[memberName]) { this.prototype[memberName] = memberValue; } } delete this.__basePrototypePending; } } if (!Type.prototype.resolveInheritance) { // This function is not used by Script#; Visual Studio relies on it // for JavaScript IntelliSense support of derived types. Type.prototype.resolveInheritance = Type.prototype.setupBase; } Type.prototype.initializeBase = function Type$initializeBase(instance, args) { if (this.__basePrototypePending) { this.setupBase(); } if (!args) { this.__baseType.apply(instance); } else { this.__baseType.apply(instance, args); } } Type.prototype.callBaseMethod = function Type$callBaseMethod(instance, name, args) { var baseMethod = this.__baseType.prototype[name]; if (!args) { return baseMethod.apply(instance); } else { return baseMethod.apply(instance, args); } } Type.prototype.get_baseType = function Type$get_baseType() { return this.__baseType || null; } Type.prototype.get_fullName = function Type$get_fullName() { return this.__typeName; } Type.prototype.get_name = function Type$get_name() { var fullName = this.__typeName; var nsIndex = fullName.lastIndexOf('.'); if (nsIndex > 0) { return fullName.substr(nsIndex + 1); } return fullName; } Type.prototype.getInterfaces = function Type$getInterfaces() { return this.__interfaces; } Type.prototype.isInstanceOfType = function Type$isInstanceOfType(instance) { if (ss.isNullOrUndefined(instance)) { return false; } if ((this == Object) || (instance instanceof this)) { return true; } var type = Type.getInstanceType(instance); return this.isAssignableFrom(type); } Type.prototype.isAssignableFrom = function Type$isAssignableFrom(type) { if ((this == Object) || (this == type)) { return true; } if (this.__class) { var baseType = type.__baseType; while (baseType) { if (this == baseType) { return true; } baseType = baseType.__baseType; } } else if (this.__interface) { var interfaces = type.__interfaces; if (interfaces && interfaces.contains(this)) { return true; } var baseType = type.__baseType; while (baseType) { interfaces = baseType.__interfaces; if (interfaces && interfaces.contains(this)) { return true; } baseType = baseType.__baseType; } } return false; } Type.isClass = function Type$isClass(type) { return (type.__class == true); } Type.isEnum = function Type$isEnum(type) { return (type.__enum == true); } Type.isFlags = function Type$isFlags(type) { return ((type.__enum == true) && (type.__flags == true)); } Type.isInterface = function Type$isInterface(type) { return (type.__interface == true); } Type.isNamespace = function Type$isNamespace(object) { return (object.__namespace == true); } Type.canCast = function Type$canCast(instance, type) { return type.isInstanceOfType(instance); } Type.safeCast = function Type$safeCast(instance, type) { if (type.isInstanceOfType(instance)) { return instance; } return null; } Type.getInstanceType = function Type$getInstanceType(instance) { var ctor = null; // NOTE: We have to catch exceptions because the constructor // cannot be looked up on native COM objects try { ctor = instance.constructor; } catch (ex) { } if (!ctor || !ctor.__typeName) { ctor = Object; } return ctor; } Type.getType = function Type$getType(typeName) { if (!typeName) { return null; } if (!Type.__typeCache) { Type.__typeCache = {}; } var type = Type.__typeCache[typeName]; if (!type) { type = eval(typeName); Type.__typeCache[typeName] = type; } return type; } Type.parse = function Type$parse(typeName) { return Type.getType(typeName); } /////////////////////////////////////////////////////////////////////////////// // Delegate ss.Delegate = function Delegate$() { } ss.Delegate.registerClass('Delegate'); ss.Delegate.empty = function() { } ss.Delegate._contains = function Delegate$_contains(targets, object, method) { for (var i = 0; i < targets.length; i += 2) { if (targets[i] === object && targets[i + 1] === method) { return true; } } return false; } ss.Delegate._create = function Delegate$_create(targets) { var delegate = function() { if (targets.length == 2) { return targets[1].apply(targets[0], arguments); } else { var clone = targets.clone(); for (var i = 0; i < clone.length; i += 2) { if (ss.Delegate._contains(targets, clone[i], clone[i + 1])) { clone[i + 1].apply(clone[i], arguments); } } return null; } }; delegate._targets = targets; return delegate; } ss.Delegate.create = function Delegate$create(object, method) { if (!object) { return method; } return ss.Delegate._create([object, method]); } ss.Delegate.combine = function Delegate$combine(delegate1, delegate2) { if (!delegate1) { if (!delegate2._targets) { return ss.Delegate.create(null, delegate2); } return delegate2; } if (!delegate2) { if (!delegate1._targets) { return ss.Delegate.create(null, delegate1); } return delegate1; } var targets1 = delegate1._targets ? delegate1._targets : [null, delegate1]; var targets2 = delegate2._targets ? delegate2._targets : [null, delegate2]; return ss.Delegate._create(targets1.concat(targets2)); } ss.Delegate.remove = function Delegate$remove(delegate1, delegate2) { if (!delegate1 || (delegate1 === delegate2)) { return null; } if (!delegate2) { return delegate1; } var targets = delegate1._targets; var object = null; var method; if (delegate2._targets) { object = delegate2._targets[0]; method = delegate2._targets[1]; } else { method = delegate2; } for (var i = 0; i < targets.length; i += 2) { if ((targets[i] === object) && (targets[i + 1] === method)) { if (targets.length == 2) { return null; } targets.splice(i, 2); return ss.Delegate._create(targets); } } return delegate1; } ss.Delegate.createExport = function Delegate$createExport(delegate, multiUse, name) { // Generate a unique name if one is not specified name = name || '__' + (new Date()).valueOf(); // Exported delegates go on window (so they are callable using a simple identifier). // Multi-use delegates are exported directly; for the rest a stub is exported, and the stub // first deletes, and then invokes the actual delegate. window[name] = multiUse ? delegate : function() { try { delete window[name]; } catch(e) { window[name] = undefined; } delegate.apply(null, arguments); }; return name; } ss.Delegate.deleteExport = function Delegate$deleteExport(name) { delete window[name]; } ss.Delegate.clearExport = function Delegate$clearExport(name) { window[name] = ss.Delegate.empty; } /////////////////////////////////////////////////////////////////////////////// // CultureInfo ss.CultureInfo = function CultureInfo$(name, numberFormat, dateFormat) { this.name = name; this.numberFormat = numberFormat; this.dateFormat = dateFormat; } ss.CultureInfo.registerClass('CultureInfo'); ss.CultureInfo.InvariantCulture = new ss.CultureInfo('en-US', { naNSymbol: 'NaN', negativeSign: '-', positiveSign: '+', negativeInfinityText: '-Infinity', positiveInfinityText: 'Infinity', percentSymbol: '%', percentGroupSizes: [3], percentDecimalDigits: 2, percentDecimalSeparator: '.', percentGroupSeparator: ',', percentPositivePattern: '{0} %', percentNegativePattern: '-{0} %', currencySymbol:'$', currencyGroupSizes: [3], currencyDecimalDigits: 2, currencyDecimalSeparator: '.', currencyGroupSeparator: ',', currencyNegativePattern: '(${0})', currencyPositivePattern: '${0}', numberGroupSizes: [3], numberDecimalDigits: 2, numberDecimalSeparator: '.', numberGroupSeparator: ',' }, { amDesignator: 'AM', pmDesignator: 'PM', dateSeparator: '/', timeSeparator: ':', gmtDateTimePattern: 'ddd, dd MMM yyyy HH:mm:ss \'GMT\'', universalDateTimePattern: 'yyyy-MM-dd HH:mm:ssZ', sortableDateTimePattern: 'yyyy-MM-ddTHH:mm:ss', dateTimePattern: 'dddd, MMMM dd, yyyy h:mm:ss tt', longDatePattern: 'dddd, MMMM dd, yyyy', shortDatePattern: 'M/d/yyyy', longTimePattern: 'h:mm:ss tt', shortTimePattern: 'h:mm tt', firstDayOfWeek: 0, dayNames: ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'], shortDayNames: ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'], minimizedDayNames: ['Su','Mo','Tu','We','Th','Fr','Sa'], monthNames: ['January','February','March','April','May','June','July','August','September','October','November','December',''], shortMonthNames: ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec',''] }); ss.CultureInfo.CurrentCulture = ss.CultureInfo.InvariantCulture; /////////////////////////////////////////////////////////////////////////////// // IEnumerator ss.IEnumerator = function IEnumerator$() { }; ss.IEnumerator.prototype = { get_current: null, moveNext: null, reset: null } ss.IEnumerator.getEnumerator = function ss_IEnumerator$getEnumerator(enumerable) { if (enumerable) { return enumerable.getEnumerator ? enumerable.getEnumerator() : new ss.ArrayEnumerator(enumerable); } return null; } ss.IEnumerator.registerInterface('IEnumerator'); /////////////////////////////////////////////////////////////////////////////// // IEnumerable ss.IEnumerable = function IEnumerable$() { }; ss.IEnumerable.prototype = { getEnumerator: null } ss.IEnumerable.registerInterface('IEnumerable'); /////////////////////////////////////////////////////////////////////////////// // ArrayEnumerator ss.ArrayEnumerator = function ArrayEnumerator$(array) { this._array = array; this._index = -1; this.current = null; } ss.ArrayEnumerator.prototype = { moveNext: function ArrayEnumerator$moveNext() { this._index++; this.current = this._array[this._index]; return (this._index < this._array.length); }, reset: function ArrayEnumerator$reset() { this._index = -1; this.current = null; } } ss.ArrayEnumerator.registerClass('ArrayEnumerator', null, ss.IEnumerator); /////////////////////////////////////////////////////////////////////////////// // IDisposable ss.IDisposable = function IDisposable$() { }; ss.IDisposable.prototype = { dispose: null } ss.IDisposable.registerInterface('IDisposable'); /////////////////////////////////////////////////////////////////////////////// // StringBuilder ss.StringBuilder = function StringBuilder$(s) { this._parts = ss.isNullOrUndefined(s) || s === '' ? [] : [s]; this.isEmpty = this._parts.length == 0; } ss.StringBuilder.prototype = { append: function StringBuilder$append(s) { if (!ss.isNullOrUndefined(s) && s !== '') { this._parts.add(s); this.isEmpty = false; } return this; }, appendLine: function StringBuilder$appendLine(s) { this.append(s); this.append('\r\n'); this.isEmpty = false; return this; }, clear: function StringBuilder$clear() { this._parts = []; this.isEmpty = true; }, toString: function StringBuilder$toString(s) { return this._parts.join(s || ''); } }; ss.StringBuilder.registerClass('StringBuilder'); /////////////////////////////////////////////////////////////////////////////// // EventArgs ss.EventArgs = function EventArgs$() { } ss.EventArgs.registerClass('EventArgs'); ss.EventArgs.Empty = new ss.EventArgs(); /////////////////////////////////////////////////////////////////////////////// // XMLHttpRequest and XML parsing helpers if (!window.XMLHttpRequest) { window.XMLHttpRequest = function() { var progIDs = [ 'Msxml2.XMLHTTP', 'Microsoft.XMLHTTP' ]; for (var i = 0; i < progIDs.length; i++) { try { var xmlHttp = new ActiveXObject(progIDs[i]); return xmlHttp; } catch (ex) { } } return null; } } ss.parseXml = function(markup) { try { if (DOMParser) { var domParser = new DOMParser(); return domParser.parseFromString(markup, 'text/xml'); } else { var progIDs = [ 'Msxml2.DOMDocument.3.0', 'Msxml2.DOMDocument' ]; for (var i = 0; i < progIDs.length; i++) { var xmlDOM = new ActiveXObject(progIDs[i]); xmlDOM.async = false; xmlDOM.loadXML(markup); xmlDOM.setProperty('SelectionLanguage', 'XPath'); return xmlDOM; } } } catch (ex) { } return null; } /////////////////////////////////////////////////////////////////////////////// // CancelEventArgs ss.CancelEventArgs = function CancelEventArgs$() { ss.CancelEventArgs.initializeBase(this); this.cancel = false; } ss.CancelEventArgs.registerClass('CancelEventArgs', ss.EventArgs); /////////////////////////////////////////////////////////////////////////////// // Tuple ss.Tuple = function (first, second, third) { this.first = first; this.second = second; if (arguments.length == 3) { this.third = third; } } ss.Tuple.registerClass('Tuple'); /////////////////////////////////////////////////////////////////////////////// // Observable ss.Observable = function(v) { this._v = v; this._observers = null; } ss.Observable.prototype = { getValue: function () { this._observers = ss.Observable._captureObservers(this._observers); return this._v; }, setValue: function (v) { if (this._v !== v) { this._v = v; var observers = this._observers; if (observers) { this._observers = null; ss.Observable._invalidateObservers(observers); } } } }; ss.Observable._observerStack = []; ss.Observable._observerRegistration = { dispose: function () { ss.Observable._observerStack.pop(); } } ss.Observable.registerObserver = function (o) { ss.Observable._observerStack.push(o); return ss.Observable._observerRegistration; } ss.Observable._captureObservers = function (observers) { var registeredObservers = ss.Observable._observerStack; var observerCount = registeredObservers.length; if (observerCount) { observers = observers || []; for (var i = 0; i < observerCount; i++) { var observer = registeredObservers[i]; if (!observers.contains(observer)) { observers.push(observer); } } return observers; } return null; } ss.Observable._invalidateObservers = function (observers) { for (var i = 0, len = observers.length; i < len; i++) { observers[i].invalidateObserver(); } } ss.Observable.registerClass('Observable'); ss.ObservableCollection = function (items) { this._items = items || []; this._observers = null; } ss.ObservableCollection.prototype = { get_item: function (index) { this._observers = ss.Observable._captureObservers(this._observers); return this._items[index]; }, set_item: function (index, item) { this._items[index] = item; this._updated(); }, get_length: function () { this._observers = ss.Observable._captureObservers(this._observers); return this._items.length; }, add: function (item) { this._items.push(item); this._updated(); }, clear: function () { this._items.clear(); this._updated(); }, contains: function (item) { return this._items.contains(item); }, getEnumerator: function () { this._observers = ss.Observable._captureObservers(this._observers); return this._items.getEnumerator(); }, indexOf: function (item) { return this._items.indexOf(item); }, insert: function (index, item) { this._items.insert(index, item); this._updated(); }, remove: function (item) { if (this._items.remove(item)) { this._updated(); return true; } return false; }, removeAt: function (index) { this._items.removeAt(index); this._updated(); }, toArray: function () { return this._items; }, _updated: function() { var observers = this._observers; if (observers) { this._observers = null; ss.Observable._invalidateObservers(observers); } } } ss.ObservableCollection.registerClass('ObservableCollection', null, ss.IEnumerable); /////////////////////////////////////////////////////////////////////////////// // Interfaces ss.IApplication = function() { }; ss.IApplication.registerInterface('IApplication'); ss.IContainer = function () { }; ss.IContainer.registerInterface('IContainer'); ss.IObjectFactory = function () { }; ss.IObjectFactory.registerInterface('IObjectFactory'); ss.IEventManager = function () { }; ss.IEventManager.registerInterface('IEventManager'); ss.IInitializable = function () { }; ss.IInitializable.registerInterface('IInitializable');
PANDA.models.RelatedUpload = Backbone.Model.extend({ /* Equivalent of panda.models.RelatedUpload. */ urlRoot: PANDA.API + "/upload" }); PANDA.collections.RelatedUploads = Backbone.Collection.extend({ /* A collection of panda.models.RelatedUpload equivalents. */ model: PANDA.models.RelatedUpload, urlRoot: PANDA.API + "/related_upload" });
import { dateTickFormat, initDateFormats } from '~/lib/utils/tick_formats'; import { setLanguage } from '../../helpers/locale_helper'; describe('tick formats', () => { describe('dateTickFormat', () => { beforeAll(() => { setLanguage('de'); initDateFormats(); }); afterAll(() => { setLanguage(null); }); it('returns year for first of January', () => { const tick = dateTickFormat(new Date('2001-01-01')); expect(tick).toBe('2001'); }); it('returns month for first of February', () => { const tick = dateTickFormat(new Date('2001-02-01')); expect(tick).toBe('Februar'); }); it('returns day and month for second of February', () => { const tick = dateTickFormat(new Date('2001-02-02')); expect(tick).toBe('2. Feb.'); }); it('ignores time', () => { const tick = dateTickFormat(new Date('2001-02-02 12:34:56')); expect(tick).toBe('2. Feb.'); }); }); });
'use strict'; /** * @typedef {import('../lib/types').XastElement} XastElement * @typedef {import('../lib/types').XastParent} XastParent * @typedef {import('../lib/types').XastNode} XastNode */ const JSAPI = require('../lib/svgo/jsAPI.js'); exports.type = 'visitor'; exports.name = 'reusePaths'; exports.active = false; exports.description = 'Finds <path> elements with the same d, fill, and ' + 'stroke, and converts them to <use> elements ' + 'referencing a single <path> def.'; /** * Finds <path> elements with the same d, fill, and stroke, and converts them to * <use> elements referencing a single <path> def. * * @author Jacob Howcroft * * @type {import('../lib/types').Plugin<void>} */ exports.fn = () => { /** * @type {Map<string, Array<XastElement>>} */ const paths = new Map(); return { element: { enter: (node) => { if (node.name === 'path' && node.attributes.d != null) { const d = node.attributes.d; const fill = node.attributes.fill || ''; const stroke = node.attributes.stroke || ''; const key = d + ';s:' + stroke + ';f:' + fill; let list = paths.get(key); if (list == null) { list = []; paths.set(key, list); } list.push(node); } }, exit: (node, parentNode) => { if (node.name === 'svg' && parentNode.type === 'root') { /** * @type {XastElement} */ const rawDefs = { type: 'element', name: 'defs', attributes: {}, children: [], }; /** * @type {XastElement} */ const defsTag = new JSAPI(rawDefs, node); let index = 0; for (const list of paths.values()) { if (list.length > 1) { // add reusable path to defs /** * @type {XastElement} */ const rawPath = { type: 'element', name: 'path', attributes: { ...list[0].attributes }, children: [], }; delete rawPath.attributes.transform; let id; if (rawPath.attributes.id == null) { id = 'reuse-' + index; index += 1; rawPath.attributes.id = id; } else { id = rawPath.attributes.id; delete list[0].attributes.id; } /** * @type {XastElement} */ const reusablePath = new JSAPI(rawPath, defsTag); defsTag.children.push(reusablePath); // convert paths to <use> for (const pathNode of list) { pathNode.name = 'use'; pathNode.attributes['xlink:href'] = '#' + id; delete pathNode.attributes.d; delete pathNode.attributes.stroke; delete pathNode.attributes.fill; } } } if (defsTag.children.length !== 0) { if (node.attributes['xmlns:xlink'] == null) { node.attributes['xmlns:xlink'] = 'http://www.w3.org/1999/xlink'; } node.children.unshift(defsTag); } } }, }, }; };
'use strict'; var forEach; var isArray; var isString; var jqLite; /** * @ngdoc module * @name ngMessages * @description * * The `ngMessages` module provides enhanced support for displaying messages within templates * (typically within forms or when rendering message objects that return key/value data). * Instead of relying on JavaScript code and/or complex ng-if statements within your form template to * show and hide error messages specific to the state of an input field, the `ngMessages` and * `ngMessage` directives are designed to handle the complexity, inheritance and priority * sequencing based on the order of how the messages are defined in the template. * * Currently, the ngMessages module only contains the code for the `ngMessages`, `ngMessagesInclude` * `ngMessage` and `ngMessageExp` directives. * * # Usage * The `ngMessages` directive allows keys in a key/value collection to be associated with a child element * (or 'message') that will show or hide based on the truthiness of that key's value in the collection. A common use * case for `ngMessages` is to display error messages for inputs using the `$error` object exposed by the * {@link ngModel ngModel} directive. * * The child elements of the `ngMessages` directive are matched to the collection keys by a `ngMessage` or * `ngMessageExp` directive. The value of these attributes must match a key in the collection that is provided by * the `ngMessages` directive. * * Consider the following example, which illustrates a typical use case of `ngMessages`. Within the form `myForm` we * have a text input named `myField` which is bound to the scope variable `field` using the {@link ngModel ngModel} * directive. * * The `myField` field is a required input of type `email` with a maximum length of 15 characters. * * ```html * <form name="myForm"> * <label> * Enter text: * <input type="email" ng-model="field" name="myField" required maxlength="15" /> * </label> * <div ng-messages="myForm.myField.$error" role="alert"> * <div ng-message="required">Please enter a value for this field.</div> * <div ng-message="email">This field must be a valid email address.</div> * <div ng-message="maxlength">This field can be at most 15 characters long.</div> * </div> * </form> * ``` * * In order to show error messages corresponding to `myField` we first create an element with an `ngMessages` attribute * set to the `$error` object owned by the `myField` input in our `myForm` form. * * Within this element we then create separate elements for each of the possible errors that `myField` could have. * The `ngMessage` attribute is used to declare which element(s) will appear for which error - for example, * setting `ng-message="required"` specifies that this particular element should be displayed when there * is no value present for the required field `myField` (because the key `required` will be `true` in the object * `myForm.myField.$error`). * * ### Message order * * By default, `ngMessages` will only display one message for a particular key/value collection at any time. If more * than one message (or error) key is currently true, then which message is shown is determined by the order of messages * in the HTML template code (messages declared first are prioritised). This mechanism means the developer does not have * to prioritise messages using custom JavaScript code. * * Given the following error object for our example (which informs us that the field `myField` currently has both the * `required` and `email` errors): * * ```javascript * <!-- keep in mind that ngModel automatically sets these error flags --> * myField.$error = { required : true, email: true, maxlength: false }; * ``` * The `required` message will be displayed to the user since it appears before the `email` message in the DOM. * Once the user types a single character, the `required` message will disappear (since the field now has a value) * but the `email` message will be visible because it is still applicable. * * ### Displaying multiple messages at the same time * * While `ngMessages` will by default only display one error element at a time, the `ng-messages-multiple` attribute can * be applied to the `ngMessages` container element to cause it to display all applicable error messages at once: * * ```html * <!-- attribute-style usage --> * <div ng-messages="myForm.myField.$error" ng-messages-multiple>...</div> * * <!-- element-style usage --> * <ng-messages for="myForm.myField.$error" multiple>...</ng-messages> * ``` * * ## Reusing and Overriding Messages * In addition to prioritization, ngMessages also allows for including messages from a remote or an inline * template. This allows for generic collection of messages to be reused across multiple parts of an * application. * * ```html * <script type="text/ng-template" id="error-messages"> * <div ng-message="required">This field is required</div> * <div ng-message="minlength">This field is too short</div> * </script> * * <div ng-messages="myForm.myField.$error" role="alert"> * <div ng-messages-include="error-messages"></div> * </div> * ``` * * However, including generic messages may not be useful enough to match all input fields, therefore, * `ngMessages` provides the ability to override messages defined in the remote template by redefining * them within the directive container. * * ```html * <!-- a generic template of error messages known as "my-custom-messages" --> * <script type="text/ng-template" id="my-custom-messages"> * <div ng-message="required">This field is required</div> * <div ng-message="minlength">This field is too short</div> * </script> * * <form name="myForm"> * <label> * Email address * <input type="email" * id="email" * name="myEmail" * ng-model="email" * minlength="5" * required /> * </label> * <!-- any ng-message elements that appear BEFORE the ng-messages-include will * override the messages present in the ng-messages-include template --> * <div ng-messages="myForm.myEmail.$error" role="alert"> * <!-- this required message has overridden the template message --> * <div ng-message="required">You did not enter your email address</div> * * <!-- this is a brand new message and will appear last in the prioritization --> * <div ng-message="email">Your email address is invalid</div> * * <!-- and here are the generic error messages --> * <div ng-messages-include="my-custom-messages"></div> * </div> * </form> * ``` * * In the example HTML code above the message that is set on required will override the corresponding * required message defined within the remote template. Therefore, with particular input fields (such * email addresses, date fields, autocomplete inputs, etc...), specialized error messages can be applied * while more generic messages can be used to handle other, more general input errors. * * ## Dynamic Messaging * ngMessages also supports using expressions to dynamically change key values. Using arrays and * repeaters to list messages is also supported. This means that the code below will be able to * fully adapt itself and display the appropriate message when any of the expression data changes: * * ```html * <form name="myForm"> * <label> * Email address * <input type="email" * name="myEmail" * ng-model="email" * minlength="5" * required /> * </label> * <div ng-messages="myForm.myEmail.$error" role="alert"> * <div ng-message="required">You did not enter your email address</div> * <div ng-repeat="errorMessage in errorMessages"> * <!-- use ng-message-exp for a message whose key is given by an expression --> * <div ng-message-exp="errorMessage.type">{{ errorMessage.text }}</div> * </div> * </div> * </form> * ``` * * The `errorMessage.type` expression can be a string value or it can be an array so * that multiple errors can be associated with a single error message: * * ```html * <label> * Email address * <input type="email" * ng-model="data.email" * name="myEmail" * ng-minlength="5" * ng-maxlength="100" * required /> * </label> * <div ng-messages="myForm.myEmail.$error" role="alert"> * <div ng-message-exp="'required'">You did not enter your email address</div> * <div ng-message-exp="['minlength', 'maxlength']"> * Your email must be between 5 and 100 characters long * </div> * </div> * ``` * * Feel free to use other structural directives such as ng-if and ng-switch to further control * what messages are active and when. Be careful, if you place ng-message on the same element * as these structural directives, Angular may not be able to determine if a message is active * or not. Therefore it is best to place the ng-message on a child element of the structural * directive. * * ```html * <div ng-messages="myForm.myEmail.$error" role="alert"> * <div ng-if="showRequiredError"> * <div ng-message="required">Please enter something</div> * </div> * </div> * ``` * * ## Animations * If the `ngAnimate` module is active within the application then the `ngMessages`, `ngMessage` and * `ngMessageExp` directives will trigger animations whenever any messages are added and removed from * the DOM by the `ngMessages` directive. * * Whenever the `ngMessages` directive contains one or more visible messages then the `.ng-active` CSS * class will be added to the element. The `.ng-inactive` CSS class will be applied when there are no * messages present. Therefore, CSS transitions and keyframes as well as JavaScript animations can * hook into the animations whenever these classes are added/removed. * * Let's say that our HTML code for our messages container looks like so: * * ```html * <div ng-messages="myMessages" class="my-messages" role="alert"> * <div ng-message="alert" class="some-message">...</div> * <div ng-message="fail" class="some-message">...</div> * </div> * ``` * * Then the CSS animation code for the message container looks like so: * * ```css * .my-messages { * transition:1s linear all; * } * .my-messages.ng-active { * // messages are visible * } * .my-messages.ng-inactive { * // messages are hidden * } * ``` * * Whenever an inner message is attached (becomes visible) or removed (becomes hidden) then the enter * and leave animation is triggered for each particular element bound to the `ngMessage` directive. * * Therefore, the CSS code for the inner messages looks like so: * * ```css * .some-message { * transition:1s linear all; * } * * .some-message.ng-enter {} * .some-message.ng-enter.ng-enter-active {} * * .some-message.ng-leave {} * .some-message.ng-leave.ng-leave-active {} * ``` * * {@link ngAnimate Click here} to learn how to use JavaScript animations or to learn more about ngAnimate. */ angular.module('ngMessages', [], function initAngularHelpers() { // Access helpers from angular core. // Do it inside a `config` block to ensure `window.angular` is available. forEach = angular.forEach; isArray = angular.isArray; isString = angular.isString; jqLite = angular.element; }) /** * @ngdoc directive * @module ngMessages * @name ngMessages * @restrict AE * * @description * `ngMessages` is a directive that is designed to show and hide messages based on the state * of a key/value object that it listens on. The directive itself complements error message * reporting with the `ngModel` $error object (which stores a key/value state of validation errors). * * `ngMessages` manages the state of internal messages within its container element. The internal * messages use the `ngMessage` directive and will be inserted/removed from the page depending * on if they're present within the key/value object. By default, only one message will be displayed * at a time and this depends on the prioritization of the messages within the template. (This can * be changed by using the `ng-messages-multiple` or `multiple` attribute on the directive container.) * * A remote template can also be used to promote message reusability and messages can also be * overridden. * * {@link module:ngMessages Click here} to learn more about `ngMessages` and `ngMessage`. * * @usage * ```html * <!-- using attribute directives --> * <ANY ng-messages="expression" role="alert"> * <ANY ng-message="stringValue">...</ANY> * <ANY ng-message="stringValue1, stringValue2, ...">...</ANY> * <ANY ng-message-exp="expressionValue">...</ANY> * </ANY> * * <!-- or by using element directives --> * <ng-messages for="expression" role="alert"> * <ng-message when="stringValue">...</ng-message> * <ng-message when="stringValue1, stringValue2, ...">...</ng-message> * <ng-message when-exp="expressionValue">...</ng-message> * </ng-messages> * ``` * * @param {string} ngMessages an angular expression evaluating to a key/value object * (this is typically the $error object on an ngModel instance). * @param {string=} ngMessagesMultiple|multiple when set, all messages will be displayed with true * * @example * <example name="ngMessages-directive" module="ngMessagesExample" * deps="angular-messages.js" * animations="true" fixBase="true"> * <file name="index.html"> * <form name="myForm"> * <label> * Enter your name: * <input type="text" * name="myName" * ng-model="name" * ng-minlength="5" * ng-maxlength="20" * required /> * </label> * <pre>myForm.myName.$error = {{ myForm.myName.$error | json }}</pre> * * <div ng-messages="myForm.myName.$error" style="color:maroon" role="alert"> * <div ng-message="required">You did not enter a field</div> * <div ng-message="minlength">Your field is too short</div> * <div ng-message="maxlength">Your field is too long</div> * </div> * </form> * </file> * <file name="script.js"> * angular.module('ngMessagesExample', ['ngMessages']); * </file> * </example> */ .directive('ngMessages', ['$animate', function($animate) { var ACTIVE_CLASS = 'ng-active'; var INACTIVE_CLASS = 'ng-inactive'; return { require: 'ngMessages', restrict: 'AE', controller: ['$element', '$scope', '$attrs', function NgMessagesCtrl($element, $scope, $attrs) { var ctrl = this; var latestKey = 0; var nextAttachId = 0; this.getAttachId = function getAttachId() { return nextAttachId++; }; var messages = this.messages = {}; var renderLater, cachedCollection; this.render = function(collection) { collection = collection || {}; renderLater = false; cachedCollection = collection; // this is true if the attribute is empty or if the attribute value is truthy var multiple = isAttrTruthy($scope, $attrs.ngMessagesMultiple) || isAttrTruthy($scope, $attrs.multiple); var unmatchedMessages = []; var matchedKeys = {}; var messageItem = ctrl.head; var messageFound = false; var totalMessages = 0; // we use != instead of !== to allow for both undefined and null values while (messageItem != null) { totalMessages++; var messageCtrl = messageItem.message; var messageUsed = false; if (!messageFound) { forEach(collection, function(value, key) { if (!messageUsed && truthy(value) && messageCtrl.test(key)) { // this is to prevent the same error name from showing up twice if (matchedKeys[key]) return; matchedKeys[key] = true; messageUsed = true; messageCtrl.attach(); } }); } if (messageUsed) { // unless we want to display multiple messages then we should // set a flag here to avoid displaying the next message in the list messageFound = !multiple; } else { unmatchedMessages.push(messageCtrl); } messageItem = messageItem.next; } forEach(unmatchedMessages, function(messageCtrl) { messageCtrl.detach(); }); if (unmatchedMessages.length !== totalMessages) { $animate.setClass($element, ACTIVE_CLASS, INACTIVE_CLASS); } else { $animate.setClass($element, INACTIVE_CLASS, ACTIVE_CLASS); } }; $scope.$watchCollection($attrs.ngMessages || $attrs['for'], ctrl.render); // If the element is destroyed, proactively destroy all the currently visible messages $element.on('$destroy', function() { forEach(messages, function(item) { item.message.detach(); }); }); this.reRender = function() { if (!renderLater) { renderLater = true; $scope.$evalAsync(function() { if (renderLater && cachedCollection) { ctrl.render(cachedCollection); } }); } }; this.register = function(comment, messageCtrl) { var nextKey = latestKey.toString(); messages[nextKey] = { message: messageCtrl }; insertMessageNode($element[0], comment, nextKey); comment.$$ngMessageNode = nextKey; latestKey++; ctrl.reRender(); }; this.deregister = function(comment) { var key = comment.$$ngMessageNode; delete comment.$$ngMessageNode; removeMessageNode($element[0], comment, key); delete messages[key]; ctrl.reRender(); }; function findPreviousMessage(parent, comment) { var prevNode = comment; var parentLookup = []; while (prevNode && prevNode !== parent) { var prevKey = prevNode.$$ngMessageNode; if (prevKey && prevKey.length) { return messages[prevKey]; } // dive deeper into the DOM and examine its children for any ngMessage // comments that may be in an element that appears deeper in the list if (prevNode.childNodes.length && parentLookup.indexOf(prevNode) === -1) { parentLookup.push(prevNode); prevNode = prevNode.childNodes[prevNode.childNodes.length - 1]; } else if (prevNode.previousSibling) { prevNode = prevNode.previousSibling; } else { prevNode = prevNode.parentNode; parentLookup.push(prevNode); } } } function insertMessageNode(parent, comment, key) { var messageNode = messages[key]; if (!ctrl.head) { ctrl.head = messageNode; } else { var match = findPreviousMessage(parent, comment); if (match) { messageNode.next = match.next; match.next = messageNode; } else { messageNode.next = ctrl.head; ctrl.head = messageNode; } } } function removeMessageNode(parent, comment, key) { var messageNode = messages[key]; var match = findPreviousMessage(parent, comment); if (match) { match.next = messageNode.next; } else { ctrl.head = messageNode.next; } } }] }; function isAttrTruthy(scope, attr) { return (isString(attr) && attr.length === 0) || //empty attribute truthy(scope.$eval(attr)); } function truthy(val) { return isString(val) ? val.length : !!val; } }]) /** * @ngdoc directive * @name ngMessagesInclude * @restrict AE * @scope * * @description * `ngMessagesInclude` is a directive with the purpose to import existing ngMessage template * code from a remote template and place the downloaded template code into the exact spot * that the ngMessagesInclude directive is placed within the ngMessages container. This allows * for a series of pre-defined messages to be reused and also allows for the developer to * determine what messages are overridden due to the placement of the ngMessagesInclude directive. * * @usage * ```html * <!-- using attribute directives --> * <ANY ng-messages="expression" role="alert"> * <ANY ng-messages-include="remoteTplString">...</ANY> * </ANY> * * <!-- or by using element directives --> * <ng-messages for="expression" role="alert"> * <ng-messages-include src="expressionValue1">...</ng-messages-include> * </ng-messages> * ``` * * {@link module:ngMessages Click here} to learn more about `ngMessages` and `ngMessage`. * * @param {string} ngMessagesInclude|src a string value corresponding to the remote template. */ .directive('ngMessagesInclude', ['$templateRequest', '$document', '$compile', function($templateRequest, $document, $compile) { return { restrict: 'AE', require: '^^ngMessages', // we only require this for validation sake link: function($scope, element, attrs) { var src = attrs.ngMessagesInclude || attrs.src; $templateRequest(src).then(function(html) { if ($scope.$$destroyed) return; if (isString(html) && !html.trim()) { // Empty template - nothing to compile replaceElementWithMarker(element, src); } else { // Non-empty template - compile and link $compile(html)($scope, function(contents) { element.after(contents); replaceElementWithMarker(element, src); }); } }); } }; // Helpers function replaceElementWithMarker(element, src) { // A comment marker is placed for debugging purposes var comment = $compile.$$createComment ? $compile.$$createComment('ngMessagesInclude', src) : $document[0].createComment(' ngMessagesInclude: ' + src + ' '); var marker = jqLite(comment); element.after(marker); // Don't pollute the DOM anymore by keeping an empty directive element element.remove(); } }]) /** * @ngdoc directive * @name ngMessage * @restrict AE * @scope * * @description * `ngMessage` is a directive with the purpose to show and hide a particular message. * For `ngMessage` to operate, a parent `ngMessages` directive on a parent DOM element * must be situated since it determines which messages are visible based on the state * of the provided key/value map that `ngMessages` listens on. * * More information about using `ngMessage` can be found in the * {@link module:ngMessages `ngMessages` module documentation}. * * @usage * ```html * <!-- using attribute directives --> * <ANY ng-messages="expression" role="alert"> * <ANY ng-message="stringValue">...</ANY> * <ANY ng-message="stringValue1, stringValue2, ...">...</ANY> * </ANY> * * <!-- or by using element directives --> * <ng-messages for="expression" role="alert"> * <ng-message when="stringValue">...</ng-message> * <ng-message when="stringValue1, stringValue2, ...">...</ng-message> * </ng-messages> * ``` * * @param {expression} ngMessage|when a string value corresponding to the message key. */ .directive('ngMessage', ngMessageDirectiveFactory()) /** * @ngdoc directive * @name ngMessageExp * @restrict AE * @priority 1 * @scope * * @description * `ngMessageExp` is a directive with the purpose to show and hide a particular message. * For `ngMessageExp` to operate, a parent `ngMessages` directive on a parent DOM element * must be situated since it determines which messages are visible based on the state * of the provided key/value map that `ngMessages` listens on. * * @usage * ```html * <!-- using attribute directives --> * <ANY ng-messages="expression"> * <ANY ng-message-exp="expressionValue">...</ANY> * </ANY> * * <!-- or by using element directives --> * <ng-messages for="expression"> * <ng-message when-exp="expressionValue">...</ng-message> * </ng-messages> * ``` * * {@link module:ngMessages Click here} to learn more about `ngMessages` and `ngMessage`. * * @param {expression} ngMessageExp|whenExp an expression value corresponding to the message key. */ .directive('ngMessageExp', ngMessageDirectiveFactory()); function ngMessageDirectiveFactory() { return ['$animate', function($animate) { return { restrict: 'AE', transclude: 'element', priority: 1, // must run before ngBind, otherwise the text is set on the comment terminal: true, require: '^^ngMessages', link: function(scope, element, attrs, ngMessagesCtrl, $transclude) { var commentNode = element[0]; var records; var staticExp = attrs.ngMessage || attrs.when; var dynamicExp = attrs.ngMessageExp || attrs.whenExp; var assignRecords = function(items) { records = items ? (isArray(items) ? items : items.split(/[\s,]+/)) : null; ngMessagesCtrl.reRender(); }; if (dynamicExp) { assignRecords(scope.$eval(dynamicExp)); scope.$watchCollection(dynamicExp, assignRecords); } else { assignRecords(staticExp); } var currentElement, messageCtrl; ngMessagesCtrl.register(commentNode, messageCtrl = { test: function(name) { return contains(records, name); }, attach: function() { if (!currentElement) { $transclude(function(elm, newScope) { $animate.enter(elm, null, element); currentElement = elm; // Each time we attach this node to a message we get a new id that we can match // when we are destroying the node later. var $$attachId = currentElement.$$attachId = ngMessagesCtrl.getAttachId(); // in the event that the element or a parent element is destroyed // by another structural directive then it's time // to deregister the message from the controller currentElement.on('$destroy', function() { if (currentElement && currentElement.$$attachId === $$attachId) { ngMessagesCtrl.deregister(commentNode); messageCtrl.detach(); } newScope.$destroy(); }); }); } }, detach: function() { if (currentElement) { var elm = currentElement; currentElement = null; $animate.leave(elm); } } }); } }; }]; function contains(collection, key) { if (collection) { return isArray(collection) ? collection.indexOf(key) >= 0 : collection.hasOwnProperty(key); } } }
var http = require('http'), httpProxy = require('http-proxy'); // Create a proxy server with custom application logic var proxy = httpProxy.createProxyServer({}); proxy.on('error', function (err, req, res) { res.writeHead(500, { 'Content-Type': 'text/plain' }); res.end(err); }); // If "-pm" is at the end of the app/domain name, or PM_URL matches the route, // proxy to the Process Manager. Otherwise, proxy to the application itself var server = http.createServer(function(req, res) { if (req.headers.host.indexOf('-pm.') != -1){ proxy.web(req, res, { target: 'http://127.0.0.1:8701' }); } // specify something like myapp-pm.mybluemix.net else if (req.headers.host.indexOf(process.env.PM_URL) != -1){ proxy.web(req, res, { target: 'http://127.0.0.1:8701' }); } else { proxy.web(req, res, { target: 'http://127.0.0.1:3001' }); } }); console.log("listening on port " + process.env.PORT) server.listen(process.env.PORT);
/** @license * @pnp/sp-taxonomy v1.2.2-0 - pnp - Provides a fluent API to work with SharePoint taxonomy * MIT (https://github.com/pnp/pnpjs/blob/master/LICENSE) * Copyright (c) 2018 Microsoft * docs: https://pnp.github.io/pnpjs/ * source: https://github.com/pnp/pnp * bugs: https://github.com/pnp/pnp/issues */ import { ClientSvcQueryable, MethodParams, property, setProperty, method, objConstructor, objectPath, objectProperties, opQuery, ObjectPathBatch, staticMethod } from '@pnp/sp-clientsvc'; import { stringIsNullOrEmpty, extend, sanitizeGuid, getGUID } from '@pnp/common'; import { sp } from '@pnp/sp'; /** * Represents a collection of labels */ class Labels extends ClientSvcQueryable { constructor(parent = "", _objectPaths = null) { super(parent, _objectPaths); this._objectPaths.add(property("Labels")); } /** * Gets a label from the collection by its value * * @param value The value to retrieve */ getByValue(value) { const params = MethodParams.build().string(value); return this.getChild(Label, "GetByValue", params); } /** * Loads the data and merges with with the ILabel instances */ get() { return this.sendGetCollection((d) => { if (!stringIsNullOrEmpty(d.Value)) { return this.getByValue(d.Value); } throw Error("Could not find Value in Labels.get(). You must include at least one of these in your select fields."); }); } } /** * Represents a label instance */ class Label extends ClientSvcQueryable { /** * Gets the data for this Label */ get() { return this.sendGet(Label); } /** * Sets this label as the default */ setAsDefaultForLanguage() { return this.invokeNonQuery("SetAsDefaultForLanguage"); } /** * Deletes this label */ delete() { return this.invokeNonQuery("DeleteObject"); } } class Terms extends ClientSvcQueryable { /** * Gets the terms in this collection */ get() { return this.sendGetCollection((d) => { if (!stringIsNullOrEmpty(d.Name)) { return this.getByName(d.Name); } else if (!stringIsNullOrEmpty(d.Id)) { return this.getById(d.Id); } throw Error("Could not find Name or Id in Terms.get(). You must include at least one of these in your select fields."); }); } /** * Gets a term by id * * @param id The id of the term */ getById(id) { const params = MethodParams.build() .string(sanitizeGuid(id)); return this.getChild(Term, "GetById", params); } /** * Gets a term by name * * @param name Term name */ getByName(name) { const params = MethodParams.build() .string(name); return this.getChild(Term, "GetByName", params); } } /** * Represents the operations available on a given term */ class Term extends ClientSvcQueryable { get labels() { return new Labels(this); } get parent() { return this.getChildProperty(Term, "Parent"); } get pinSourceTermSet() { return this.getChildProperty(TermSet, "PinSourceTermSet"); } get reusedTerms() { return this.getChildProperty(Terms, "ReusedTerms"); } get sourceTerm() { return this.getChildProperty(Term, "SourceTerm"); } get termSet() { return this.getChildProperty(TermSet, "TermSet"); } get termSets() { return this.getChildProperty(TermSets, "TermSets"); } /** * Creates a new label for this Term * * @param name label value * @param lcid language code * @param isDefault Is the default label */ createLabel(name, lcid, isDefault = false) { const params = MethodParams.build() .string(name) .number(lcid) .boolean(isDefault); this._useCaching = false; return this.invokeMethod("CreateLabel", params) .then(r => extend(this.labels.getByValue(name), r)); } /** * Sets the deprecation flag on a term * * @param doDeprecate New value for the deprecation flag */ deprecate(doDeprecate) { const params = MethodParams.build().boolean(doDeprecate); return this.invokeNonQuery("Deprecate", params); } /** * Loads the term data */ get() { return this.sendGet(Term); } /** * Sets the description * * @param description Term description * @param lcid Language code */ setDescription(description, lcid) { const params = MethodParams.build().string(description).number(lcid); return this.invokeNonQuery("SetDescription", params); } /** * Sets a custom property on this term * * @param name Property name * @param value Property value */ setLocalCustomProperty(name, value) { const params = MethodParams.build().string(name).string(value); return this.invokeNonQuery("SetLocalCustomProperty", params); } /** * Updates the specified properties of this term, not all properties can be updated * * @param properties Plain object representing the properties and new values to update */ update(properties) { return this.invokeUpdate(properties, Term); } } class TermSets extends ClientSvcQueryable { /** * Gets the termsets in this collection */ get() { return this.sendGetCollection((d) => { if (!stringIsNullOrEmpty(d.Name)) { return this.getByName(d.Name); } else if (!stringIsNullOrEmpty(d.Id)) { return this.getById(d.Id); } throw Error("Could not find Value in Labels.get(). You must include at least one of these in your select fields."); }); } /** * Gets a TermSet from this collection by id * * @param id TermSet id */ getById(id) { const params = MethodParams.build() .string(sanitizeGuid(id)); return this.getChild(TermSet, "GetById", params); } /** * Gets a TermSet from this collection by name * * @param name TermSet name */ getByName(name) { const params = MethodParams.build() .string(name); return this.getChild(TermSet, "GetByName", params); } } class TermSet extends ClientSvcQueryable { /** * Gets the group containing this Term set */ get group() { return this.getChildProperty(TermGroup, "Group"); } /** * Access all the terms in this termset */ get terms() { return this.getChild(Terms, "GetAllTerms", null); } /** * Adds a stakeholder to the TermSet * * @param stakeholderName The login name of the user to be added as a stakeholder */ addStakeholder(stakeholderName) { const params = MethodParams.build() .string(stakeholderName); return this.invokeNonQuery("DeleteStakeholder", params); } /** * Deletes a stakeholder to the TermSet * * @param stakeholderName The login name of the user to be added as a stakeholder */ deleteStakeholder(stakeholderName) { const params = MethodParams.build() .string(stakeholderName); return this.invokeNonQuery("AddStakeholder", params); } /** * Gets the data for this TermSet */ get() { return this.sendGet(TermSet); } /** * Get a term by id * * @param id Term id */ getTermById(id) { const params = MethodParams.build() .string(sanitizeGuid(id)); return this.getChild(Term, "GetTerm", params); } /** * Adds a term to this term set * * @param name Name for the term * @param lcid Language code * @param isAvailableForTagging set tagging availability (default: true) * @param id GUID id for the term (optional) */ addTerm(name, lcid, isAvailableForTagging = true, id = getGUID()) { const params = MethodParams.build() .string(name) .number(lcid) .string(sanitizeGuid(id)); this._useCaching = false; return this.invokeMethod("CreateTerm", params, setProperty("IsAvailableForTagging", "Boolean", `${isAvailableForTagging}`)) .then(r => extend(this.getTermById(r.Id), r)); } /** * Copies this term set immediately */ copy() { return this.invokeMethod("Copy", null); } /** * Updates the specified properties of this term set, not all properties can be updated * * @param properties Plain object representing the properties and new values to update */ update(properties) { return this.invokeUpdate(properties, TermSet); } } /** * Represents a group in the taxonomy heirarchy */ class TermGroup extends ClientSvcQueryable { constructor(parent = "", _objectPaths) { super(parent, _objectPaths); // this should mostly be true this.store = parent instanceof TermStore ? parent : null; } /** * Gets the collection of term sets in this group */ get termSets() { return this.getChildProperty(TermSets, "TermSets"); } /** * Adds a contributor to the Group * * @param principalName The login name of the user to be added as a contributor */ addContributor(principalName) { const params = MethodParams.build().string(principalName); return this.invokeNonQuery("AddContributor", params); } /** * Adds a group manager to the Group * * @param principalName The login name of the user to be added as a group manager */ addGroupManager(principalName) { const params = MethodParams.build().string(principalName); return this.invokeNonQuery("AddGroupManager", params); } /** * Creates a new TermSet in this Group using the provided language and unique identifier * * @param name The name of the new TermSet being created * @param lcid The language that the new TermSet name is in * @param id The unique identifier of the new TermSet being created (optional) */ createTermSet(name, lcid, id = getGUID()) { const params = MethodParams.build() .string(name) .string(sanitizeGuid(id)) .number(lcid); this._useCaching = false; return this.invokeMethod("CreateTermSet", params) .then(r => extend(this.store.getTermSetById(r.Id), r)); } /** * Gets this term store's data */ get() { return this.sendGet(TermGroup); } /** * Updates the specified properties of this term set, not all properties can be updated * * @param properties Plain object representing the properties and new values to update */ update(properties) { return this.invokeUpdate(properties, TermGroup); } } /** * Represents the set of available term stores and the collection methods */ class TermStores extends ClientSvcQueryable { constructor(parent = "") { super(parent); this._objectPaths.add(property("TermStores", // actions objectPath())); } /** * Gets the term stores */ get() { return this.sendGetCollection((d) => { if (!stringIsNullOrEmpty(d.Name)) { return this.getByName(d.Name); } else if (!stringIsNullOrEmpty(d.Id)) { return this.getById(d.Id); } throw Error("Could not find Name or Id in TermStores.get(). You must include at least one of these in your select fields."); }); } /** * Returns the TermStore specified by its index name * * @param name The index name of the TermStore to be returned */ getByName(name) { return this.getChild(TermStore, "GetByName", MethodParams.build().string(name)); } /** * Returns the TermStore specified by its GUID index * * @param id The GUID index of the TermStore to be returned */ getById(id) { return this.getChild(TermStore, "GetById", MethodParams.build().string(sanitizeGuid(id))); } } class TermStore extends ClientSvcQueryable { constructor(parent = "", _objectPaths = null) { super(parent, _objectPaths); } get hashTagsTermSet() { return this.getChildProperty(TermSet, "HashTagsTermSet"); } get keywordsTermSet() { return this.getChildProperty(TermSet, "KeywordsTermSet"); } get orphanedTermsTermSet() { return this.getChildProperty(TermSet, "OrphanedTermsTermSet"); } get systemGroup() { return this.getChildProperty(TermGroup, "SystemGroup"); } /** * Gets the term store data */ get() { return this.sendGet(TermStore); } /** * Gets term sets * * @param name * @param lcid */ getTermSetsByName(name, lcid) { const params = MethodParams.build() .string(name) .number(lcid); return this.getChild(TermSets, "GetTermSetsByName", params); } /** * Provides access to an ITermSet by id * * @param id */ getTermSetById(id) { const params = MethodParams.build().string(sanitizeGuid(id)); return this.getChild(TermSet, "GetTermSet", params); } /** * Provides access to an ITermSet by id * * @param id */ getTermById(id) { const params = MethodParams.build().string(sanitizeGuid(id)); return this.getChild(Term, "GetTerm", params); } /** * Gets a term from a term set based on the supplied ids * * @param termId Term Id * @param termSetId Termset Id */ getTermInTermSet(termId, termSetId) { const params = MethodParams.build().string(sanitizeGuid(termId)).string(sanitizeGuid(termSetId)); return this.getChild(Term, "GetTermInTermSet", params); } /** * This method provides access to a ITermGroup by id * * @param id The group id */ getTermGroupById(id) { const params = MethodParams.build() .string(sanitizeGuid(id)); return this.getChild(TermGroup, "GetGroup", params); } /** * Gets the terms by the supplied information (see: https://msdn.microsoft.com/en-us/library/hh626704%28v=office.12%29.aspx) * * @param info */ getTerms(info) { const objectPaths = this._objectPaths.clone(); // this will be the parent of the GetTerms call, but we need to create the input param first const parentIndex = objectPaths.lastIndex; // this is our input object const input = objConstructor("{61a1d689-2744-4ea3-a88b-c95bee9803aa}", // actions objectPath(), ...objectProperties(info)); // add the input object path const inputIndex = objectPaths.add(input); // this sets up the GetTerms call const params = MethodParams.build().objectPath(inputIndex); // call the method const methodIndex = objectPaths.add(method("GetTerms", params, // actions objectPath())); // setup the parent relationship even though they are seperated in the collection objectPaths.addChildRelationship(parentIndex, methodIndex); return new Terms(this, objectPaths); } /** * Gets the site collection group associated with the current site * * @param createIfMissing If true the group will be created, otherwise null (default: false) */ getSiteCollectionGroup(createIfMissing = false) { const objectPaths = this._objectPaths.clone(); const methodParent = objectPaths.lastIndex; const siteIndex = objectPaths.siteIndex; const params = MethodParams.build().objectPath(siteIndex).boolean(createIfMissing); const methodIndex = objectPaths.add(method("GetSiteCollectionGroup", params, // actions objectPath())); // the parent of this method call is this instance, not the current/site objectPaths.addChildRelationship(methodParent, methodIndex); return new TermGroup(this, objectPaths); } /** * Adds a working language to the TermStore * * @param lcid The locale identifier of the working language to add */ addLanguage(lcid) { const params = MethodParams.build().number(lcid); return this.invokeNonQuery("AddLanguage", params); } /** * Creates a new Group in this TermStore * * @param name The name of the new Group being created * @param id The ID (Guid) that the new group should have */ addGroup(name, id = getGUID()) { const params = MethodParams.build() .string(name) .string(sanitizeGuid(id)); this._useCaching = false; return this.invokeMethod("CreateGroup", params) .then(r => extend(this.getTermGroupById(r.Id), r)); } /** * Commits all updates to the database that have occurred since the last commit or rollback */ commitAll() { return this.invokeNonQuery("CommitAll"); } /** * Delete a working language from the TermStore * * @param lcid locale ID for the language to be deleted */ deleteLanguage(lcid) { const params = MethodParams.build().number(lcid); return this.invokeNonQuery("DeleteLanguage", params); } /** * Discards all updates that have occurred since the last commit or rollback */ rollbackAll() { return this.invokeNonQuery("RollbackAll"); } /** * Updates the cache */ updateCache() { return this.invokeNonQuery("UpdateCache"); } /** * Updates the specified properties of this term set, not all properties can be updated * * @param properties Plain object representing the properties and new values to update */ update(properties) { return this.invokeUpdate(properties, TermStore); } /** * This method makes sure that this instance is aware of all child terms that are used in the current site collection */ updateUsedTermsOnSite() { const objectPaths = this._objectPaths.clone(); const methodParent = objectPaths.lastIndex; const siteIndex = objectPaths.siteIndex; const params = MethodParams.build().objectPath(siteIndex); const methodIndex = objectPaths.add(method("UpdateUsedTermsOnSite", params)); // the parent of this method call is this instance, not the current context/site objectPaths.addChildRelationship(methodParent, methodIndex); return this.send(objectPaths); } /** * Gets a list of changes * * @param info Lookup information */ getChanges(info) { const objectPaths = this._objectPaths.clone(); const methodParent = objectPaths.lastIndex; const inputIndex = objectPaths.add(objConstructor("{1f849fb0-4fcb-4a54-9b01-9152b9e482d3}", // actions objectPath(), ...objectProperties(info))); const params = MethodParams.build().objectPath(inputIndex); const methodIndex = objectPaths.add(method("GetChanges", params, // actions objectPath(), opQuery([], this.getSelects()))); objectPaths.addChildRelationship(methodParent, methodIndex); return this.send(objectPaths); } } /** * The root taxonomy object */ class Session extends ClientSvcQueryable { constructor(webUrl = "") { super(webUrl); // everything starts with the session this._objectPaths.add(staticMethod("GetTaxonomySession", "{981cbc68-9edc-4f8d-872f-71146fcbb84f}", // actions objectPath())); } /** * The collection of term stores */ get termStores() { return new TermStores(this); } /** * Provides access to sp.setup from @pnp/sp * * @param config Configuration */ setup(config) { sp.setup(config); } /** * Creates a new batch */ createBatch() { return new ObjectPathBatch(this.toUrl()); } /** * Gets the default keyword termstore for this session */ getDefaultKeywordTermStore() { return this.getChild(TermStore, "GetDefaultKeywordsTermStore", null); } /** * Gets the default site collection termstore for this session */ getDefaultSiteCollectionTermStore() { return this.getChild(TermStore, "GetDefaultSiteCollectionTermStore", null); } } var StringMatchOption; (function (StringMatchOption) { StringMatchOption[StringMatchOption["StartsWith"] = 0] = "StartsWith"; StringMatchOption[StringMatchOption["ExactMatch"] = 1] = "ExactMatch"; })(StringMatchOption || (StringMatchOption = {})); var ChangedItemType; (function (ChangedItemType) { ChangedItemType[ChangedItemType["Unknown"] = 0] = "Unknown"; ChangedItemType[ChangedItemType["Term"] = 1] = "Term"; ChangedItemType[ChangedItemType["TermSet"] = 2] = "TermSet"; ChangedItemType[ChangedItemType["Group"] = 3] = "Group"; ChangedItemType[ChangedItemType["TermStore"] = 4] = "TermStore"; ChangedItemType[ChangedItemType["Site"] = 5] = "Site"; })(ChangedItemType || (ChangedItemType = {})); var ChangedOperationType; (function (ChangedOperationType) { ChangedOperationType[ChangedOperationType["Unknown"] = 0] = "Unknown"; ChangedOperationType[ChangedOperationType["Add"] = 1] = "Add"; ChangedOperationType[ChangedOperationType["Edit"] = 2] = "Edit"; ChangedOperationType[ChangedOperationType["DeleteObject"] = 3] = "DeleteObject"; ChangedOperationType[ChangedOperationType["Move"] = 4] = "Move"; ChangedOperationType[ChangedOperationType["Copy"] = 5] = "Copy"; ChangedOperationType[ChangedOperationType["PathChange"] = 6] = "PathChange"; ChangedOperationType[ChangedOperationType["Merge"] = 7] = "Merge"; ChangedOperationType[ChangedOperationType["ImportObject"] = 8] = "ImportObject"; ChangedOperationType[ChangedOperationType["Restore"] = 9] = "Restore"; })(ChangedOperationType || (ChangedOperationType = {})); // export an existing session instance const taxonomy = new Session(); export { taxonomy, Labels, Label, Session, TermGroup, Terms, Term, TermSets, TermSet, TermStores, TermStore, StringMatchOption, ChangedItemType, ChangedOperationType }; //# sourceMappingURL=sp-taxonomy.js.map
version https://git-lfs.github.com/spec/v1 oid sha256:37458aa009289b4e322bdafbe4cf377fe339d7935c23e14bbbac5cc19e1ac4b0 size 150033
define(["pex/sys/Platform"], function(Platform) { function Test() { } if (Platform.isPlask) Test.msg = "Hello Node!"; if (Platform.isBrowser) Test.msg = "Hello World Wide Web!"; if (Platform.isEjecta) Test.msg = "Hello iOS!"; return Test; });
var HASH = '#'.charCodeAt(0); var DOT = '.'.charCodeAt(0); var TAG_NAME = 0; var ID = 1; var CLASS_NAME = 2; var parseQuery = function (query) { var tag = null; var id = null; var className = null; var mode = TAG_NAME; var offset = 0; for (var i = 0; i <= query.length; i++) { var char = query.charCodeAt(i); var isHash = char === HASH; var isDot = char === DOT; var isEnd = !char; if (isHash || isDot || isEnd) { if (mode === TAG_NAME) { if (i === 0) { tag = 'div'; } else { tag = query.substring(offset, i); } } else if (mode === ID) { id = query.substring(offset, i); } else { if (className) { className += ' ' + query.substring(offset, i); } else { className = query.substring(offset, i); } } if (isHash) { mode = ID; } else if (isDot) { mode = CLASS_NAME; } offset = i + 1; } } return { tag: tag, id: id, className: className }; }; var createElement = function (query, ns) { var ref = parseQuery(query); var tag = ref.tag; var id = ref.id; var className = ref.className; var element = ns ? document.createElementNS(ns, tag) : document.createElement(tag); if (id) { element.id = id; } if (className) { if (ns) { element.setAttribute('class', className); } else { element.className = className; } } return element; }; var unmount = function (parent, child) { var parentEl = getEl(parent); var childEl = getEl(child); if (child === childEl && childEl.__redom_view) { // try to look up the view if not provided child = childEl.__redom_view; } if (childEl.parentNode) { doUnmount(child, childEl, parentEl); parentEl.removeChild(childEl); } return child; }; var doUnmount = function (child, childEl, parentEl) { var hooks = childEl.__redom_lifecycle; if (hooksAreEmpty(hooks)) { childEl.__redom_mounted = false; return; } var traverse = parentEl; if (childEl.__redom_mounted) { trigger(childEl, 'onunmount'); } while (traverse) { var parentHooks = traverse.__redom_lifecycle || {}; for (var hook in hooks) { if (parentHooks[hook]) { parentHooks[hook] -= hooks[hook]; } } if (hooksAreEmpty(parentHooks)) { traverse.__redom_lifecycle = null; } traverse = traverse.parentNode; } }; var hooksAreEmpty = function (hooks) { if (hooks == null) { return true; } for (var key in hooks) { if (hooks[key]) { return false; } } return true; }; var hookNames = ['onmount', 'onremount', 'onunmount']; var shadowRootAvailable = typeof window !== 'undefined' && 'ShadowRoot' in window; var mount = function (parent, child, before) { var parentEl = getEl(parent); var childEl = getEl(child); if (child === childEl && childEl.__redom_view) { // try to look up the view if not provided child = childEl.__redom_view; } if (child !== childEl) { childEl.__redom_view = child; } var wasMounted = childEl.__redom_mounted; var oldParent = childEl.parentNode; if (wasMounted && (oldParent !== parentEl)) { doUnmount(child, childEl, oldParent); } if (before != null) { parentEl.insertBefore(childEl, getEl(before)); } else { parentEl.appendChild(childEl); } doMount(child, childEl, parentEl, oldParent); return child; }; var doMount = function (child, childEl, parentEl, oldParent) { var hooks = childEl.__redom_lifecycle || (childEl.__redom_lifecycle = {}); var remount = (parentEl === oldParent); var hooksFound = false; for (var i = 0, list = hookNames; i < list.length; i += 1) { var hookName = list[i]; if (!remount) { // if already mounted, skip this phase if (child !== childEl) { // only Views can have lifecycle events if (hookName in child) { hooks[hookName] = (hooks[hookName] || 0) + 1; } } } if (hooks[hookName]) { hooksFound = true; } } if (!hooksFound) { childEl.__redom_mounted = true; return; } var traverse = parentEl; var triggered = false; if (remount || (traverse && traverse.__redom_mounted)) { trigger(childEl, remount ? 'onremount' : 'onmount'); triggered = true; } while (traverse) { var parent = traverse.parentNode; var parentHooks = traverse.__redom_lifecycle || (traverse.__redom_lifecycle = {}); for (var hook in hooks) { parentHooks[hook] = (parentHooks[hook] || 0) + hooks[hook]; } if (triggered) { break; } else { if (traverse === document || (shadowRootAvailable && (traverse instanceof window.ShadowRoot)) || (parent && parent.__redom_mounted) ) { trigger(traverse, remount ? 'onremount' : 'onmount'); triggered = true; } traverse = parent; } } }; var trigger = function (el, eventName) { if (eventName === 'onmount' || eventName === 'onremount') { el.__redom_mounted = true; } else if (eventName === 'onunmount') { el.__redom_mounted = false; } var hooks = el.__redom_lifecycle; if (!hooks) { return; } var view = el.__redom_view; var hookCount = 0; view && view[eventName] && view[eventName](); for (var hook in hooks) { if (hook) { hookCount++; } } if (hookCount) { var traverse = el.firstChild; while (traverse) { var next = traverse.nextSibling; trigger(traverse, eventName); traverse = next; } } }; var setStyle = function (view, arg1, arg2) { var el = getEl(view); if (arg2 !== undefined) { el.style[arg1] = arg2; } else if (isString(arg1)) { el.setAttribute('style', arg1); } else { for (var key in arg1) { setStyle(el, key, arg1[key]); } } }; /* global SVGElement */ var xlinkns = 'http://www.w3.org/1999/xlink'; var setAttr = function (view, arg1, arg2) { var el = getEl(view); var isSVG = el instanceof SVGElement; if (arg2 !== undefined) { if (arg1 === 'style') { setStyle(el, arg2); } else if (isSVG && isFunction(arg2)) { el[arg1] = arg2; } else if (arg1 === 'dataset') { setData(el, arg2); } else if (!isSVG && (arg1 in el || isFunction(arg2))) { el[arg1] = arg2; } else { if (isSVG && (arg1 === 'xlink')) { setXlink(el, arg2); return; } el.setAttribute(arg1, arg2); } } else { for (var key in arg1) { setAttr(el, key, arg1[key]); } } }; function setXlink (el, obj) { for (var key in obj) { el.setAttributeNS(xlinkns, key, obj[key]); } } function setData (el, obj) { for (var key in obj) { el.dataset[key] = obj[key]; } } var text = function (str) { return document.createTextNode((str != null) ? str : ''); }; var parseArguments = function (element, args) { for (var i = 0, list = args; i < list.length; i += 1) { var arg = list[i]; if (arg !== 0 && !arg) { continue; } var type = typeof arg; // support middleware if (type === 'function') { arg(element); } else if (type === 'string' || type === 'number') { element.appendChild(text(arg)); } else if (isNode(getEl(arg))) { mount(element, arg); } else if (arg.length) { parseArguments(element, arg); } else if (type === 'object') { setAttr(element, arg); } } }; var ensureEl = function (parent) { return isString(parent) ? html(parent) : getEl(parent); }; var getEl = function (parent) { return (parent.nodeType && parent) || (!parent.el && parent) || getEl(parent.el); }; var isString = function (a) { return typeof a === 'string'; }; var isFunction = function (a) { return typeof a === 'function'; }; var isNode = function (a) { return a && a.nodeType; }; var htmlCache = {}; var memoizeHTML = function (query) { return htmlCache[query] || (htmlCache[query] = createElement(query)); }; var html = function (query) { var args = [], len = arguments.length - 1; while ( len-- > 0 ) args[ len ] = arguments[ len + 1 ]; var element; if (isString(query)) { element = memoizeHTML(query).cloneNode(false); } else if (isNode(query)) { element = query.cloneNode(false); } else if (isFunction(query)) { var Query = query; element = new (Function.prototype.bind.apply( Query, [ null ].concat( args) )); } else { throw new Error('At least one argument required'); } parseArguments(getEl(element), args); return element; }; html.extend = function (query) { var args = [], len = arguments.length - 1; while ( len-- > 0 ) args[ len ] = arguments[ len + 1 ]; var clone = memoizeHTML(query); return html.bind.apply(html, [ this, clone ].concat( args )); }; var el = html; var h = html; var setChildren = function (parent) { var children = [], len = arguments.length - 1; while ( len-- > 0 ) children[ len ] = arguments[ len + 1 ]; var parentEl = getEl(parent); var current = traverse(parent, children, parentEl.firstChild); while (current) { var next = current.nextSibling; unmount(parent, current); current = next; } }; function traverse (parent, children, _current) { var current = _current; for (var i = 0, list = children; i < list.length; i += 1) { var child = list[i]; if (!child) { continue; } var childEl = getEl(child); if (childEl === current) { current = current.nextSibling; continue; } if (isNode(childEl)) { mount(parent, child, current); continue; } if (child.length != null) { current = traverse(parent, child, current); } } return current; } var propKey = function (key) { return function (item) { return item[key]; }; }; var listPool = function (View, key, initData) { return new ListPool(View, key, initData); }; var ListPool = function ListPool (View, key, initData) { this.View = View; this.initData = initData; this.oldLookup = {}; this.lookup = {}; this.oldViews = []; this.views = []; if (key != null) { this.lookup = {}; this.key = isFunction(key) ? key : propKey(key); } }; ListPool.prototype.update = function update (data, context) { var ref = this; var View = ref.View; var key = ref.key; var initData = ref.initData; var keySet = key != null; var oldLookup = this.lookup; var newLookup = {}; var newViews = new Array(data.length); var oldViews = this.views; for (var i = 0; i < data.length; i++) { var item = data[i]; var view = (void 0); if (keySet) { var id = key(item); view = oldLookup[id] || new View(initData, item, i, data); newLookup[id] = view; view.__redom_id = id; } else { view = oldViews[i] || new View(initData, item, i, data); } view.update && view.update(item, i, data, context); var el = getEl(view.el); el.__redom_view = view; newViews[i] = view; } this.oldViews = oldViews; this.views = newViews; this.oldLookup = oldLookup; this.lookup = newLookup; }; var list = function (parent, View, key, initData) { return new List(parent, View, key, initData); }; var List = function List (parent, View, key, initData) { this.__redom_list = true; this.View = View; this.initData = initData; this.views = []; this.pool = new ListPool(View, key, initData); this.el = ensureEl(parent); this.keySet = key != null; }; List.prototype.update = function update (data, context) { var this$1 = this; if ( data === void 0 ) data = []; var ref = this; var keySet = ref.keySet; var oldViews = this.views; var oldLookup = keySet && this.lookup; this.pool.update(data, context); var ref$1 = this.pool; var views = ref$1.views; var lookup = ref$1.lookup; if (keySet) { for (var i = 0, list = oldViews; i < list.length; i += 1) { var oldView = list[i]; var id = oldView.__redom_id; if (!(id in lookup)) { unmount(this$1, oldLookup[id]); } } } setChildren(this, views); if (keySet) { this.lookup = lookup; } this.views = views; }; List.extend = function (parent, View, key, initData) { return List.bind(List, parent, View, key, initData); }; list.extend = List.extend; /* global Node */ var place = function (View, initData) { return new Place(View, initData); }; var Place = function Place (View, initData) { this.el = text(''); this.visible = false; this.view = null; this._placeholder = this.el; if (View instanceof Node) { this._el = View; } else { this._View = View; } this._initData = initData; }; Place.prototype.update = function update (visible, data) { var placeholder = this._placeholder; var parentNode = this.el.parentNode; if (visible) { if (!this.visible) { if (this._el) { mount(parentNode, this._el, placeholder); unmount(parentNode, placeholder); this.el = this._el; this.visible = visible; return; } var View = this._View; var view = new View(this._initData); this.el = getEl(view); this.view = view; mount(parentNode, view, placeholder); unmount(parentNode, placeholder); } this.view && this.view.update && this.view.update(data); } else { if (this.visible) { if (this._el) { mount(parentNode, placeholder, this._el); unmount(parentNode, this._el); this.el = placeholder; this.visible = visible; return; } mount(parentNode, placeholder, this.view); unmount(parentNode, this.view); this.el = placeholder; this.view = null; } } this.visible = visible; }; var router = function (parent, Views, initData) { return new Router(parent, Views, initData); }; var Router = function Router (parent, Views, initData) { this.el = ensureEl(parent); this.Views = Views; this.initData = initData; }; Router.prototype.update = function update (route, data) { if (route !== this.route) { var Views = this.Views; var View = Views[route]; this.route = route; this.view = View && new View(this.initData, data); setChildren(this.el, [ this.view ]); } this.view && this.view.update && this.view.update(data, route); }; var ns = 'http://www.w3.org/2000/svg'; var svgCache = {}; var memoizeSVG = function (query) { return svgCache[query] || (svgCache[query] = createElement(query, ns)); }; var svg = function (query) { var args = [], len = arguments.length - 1; while ( len-- > 0 ) args[ len ] = arguments[ len + 1 ]; var element; if (isString(query)) { element = memoizeSVG(query).cloneNode(false); } else if (isNode(query)) { element = query.cloneNode(false); } else if (isFunction(query)) { var Query = query; element = new (Function.prototype.bind.apply( Query, [ null ].concat( args) )); } else { throw new Error('At least one argument required'); } parseArguments(getEl(element), args); return element; }; svg.extend = function (query) { var clone = memoizeSVG(query); return svg.bind(this, clone); }; svg.ns = ns; var s = svg; export { el, h, html, list, List, listPool, ListPool, mount, unmount, place, Place, router, Router, setAttr, setStyle, setChildren, s, svg, text };
/* */ "format cjs"; "use strict"; exports.__esModule = true; exports.CallExpression = CallExpression; exports.ModuleDeclaration = ModuleDeclaration; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj["default"] = obj; return newObj; } } var _messages = require("../../../messages"); var messages = _interopRequireWildcard(_messages); var _types = require("../../../types"); var t = _interopRequireWildcard(_types); // check if the input Literal `source` is an alternate casing of "react" function check(source, file) { if (t.isLiteral(source)) { var name = source.value; var lower = name.toLowerCase(); if (lower === "react" && name !== lower) { throw file.errorWithNode(source, messages.get("didYouMean", "react")); } } } function CallExpression(node, parent, scope, file) { if (this.get("callee").isIdentifier({ name: "require" }) && node.arguments.length === 1) { check(node.arguments[0], file); } } function ModuleDeclaration(node, parent, scope, file) { check(node.source, file); }
wn.provide("wn.model"); $.extend(wn.model, { new_names: {}, new_name_count: {}, get_new_doc: function(doctype) { wn.provide("locals." + doctype); var doc = { docstatus: 0, doctype: doctype, name: wn.model.get_new_name(doctype), __islocal: 1, owner: user }; wn.model.set_default_values(doc); locals[doctype][doc.name] = doc; return doc; }, make_new_doc_and_get_name: function(doctype) { return wn.model.get_new_doc(doctype).name; }, get_new_name: function(doctype) { var cnt = wn.model.new_name_count if(!cnt[doctype]) cnt[doctype] = 0; cnt[doctype]++; return 'New '+ doctype + ' ' + cnt[doctype]; }, set_default_values: function(doc) { var doctype = doc.doctype; var docfields = wn.meta.docfield_list[doctype] || []; var updated = []; for(var fid=0;fid<docfields.length;fid++) { var f = docfields[fid]; if(!in_list(no_value_fields, f.fieldtype) && doc[f.fieldname]==null) { var v = wn.model.get_default_value(f, doc); if(v) { if(in_list(["Int", "Check"], f.fieldtype)) v = cint(v); else if(in_list(["Currency", "Float"], f.fieldtype)) v = flt(v); doc[f.fieldname] = v; updated.push(f.fieldname); } } } return updated; }, get_default_value: function(df, doc) { var def_vals = { "_Login": user, "__user": user, "Today": dateutil.get_today(), "__today": dateutil.get_today(), "Now": dateutil.get_cur_time() } if(def_vals[df["default"]]) return def_vals[df["default"]]; else if(df.fieldtype=="Time" && (!df["default"])) return dateutil.get_cur_time() else if(df["default"] && df["default"][0]!==":") return df["default"]; else if(wn.defaults.get_user_default(df.fieldname)) return wn.defaults.get_user_default(df.fieldname); else if(df["default"] && df["default"][0]===":") return wn.model.get_default_from_boot_docs(df, doc); }, get_default_from_boot_docs: function(df, doc) { // set default from partial docs passed during boot like ":Profile" if(wn.model.get(df["default"]).length > 0) { var ref_fieldname = df["default"].slice(1).toLowerCase().replace(" ", "_"); var ref_value = (doc && doc[ref_fieldname]) || (cur_frm && cur_frm.doc[ref_fieldname]); var ref_doc = ref_value ? wn.model.get_doc(df["default"], ref_value) : null; if(ref_doc && ref_doc[df.fieldname]) { return ref_doc[df.fieldname]; } } }, add_child: function(doc, childtype, parentfield) { // create row doc var d = wn.model.get_new_doc(childtype); $.extend(d, { parent: doc.name, parentfield: parentfield, parenttype: doc.doctype, idx: getchildren(childtype, d.parent, d.parentfield, d.parenttype).length }); return d; }, copy_doc: function(dt, dn, from_amend) { var no_copy_list = ['name','amended_from','amendment_date','cancel_reason']; var newdoc = wn.model.get_new_doc(dt); for(var key in locals[dt][dn]) { // dont copy name and blank fields var df = wn.meta.get_docfield(dt, key); if(key.substr(0,2)!='__' && !in_list(no_copy_list, key) && !(df && (!from_amend && cint(df.no_copy)==1))) { newdoc[key] = locals[dt][dn][key]; } } return newdoc; }, })
import { Vector4 } from '../math/Vector4'; import { Vector3 } from '../math/Vector3'; import { Vector2 } from '../math/Vector2'; import { Color } from '../math/Color'; import { _Math } from '../math/Math'; /** * @author mrdoob / http://mrdoob.com/ */ function BufferAttribute( array, itemSize, normalized ) { if ( Array.isArray( array ) ) { throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' ); } this.uuid = _Math.generateUUID(); this.array = array; this.itemSize = itemSize; this.count = array !== undefined ? array.length / itemSize : 0; this.normalized = normalized === true; this.dynamic = false; this.updateRange = { offset: 0, count: - 1 }; this.version = 0; } BufferAttribute.prototype = { constructor: BufferAttribute, isBufferAttribute: true, set needsUpdate( value ) { if ( value === true ) this.version ++; }, setDynamic: function ( value ) { this.dynamic = value; return this; }, copy: function ( source ) { this.array = new source.array.constructor( source.array ); this.itemSize = source.itemSize; this.count = source.count; this.normalized = source.normalized; this.dynamic = source.dynamic; return this; }, copyAt: function ( index1, attribute, index2 ) { index1 *= this.itemSize; index2 *= attribute.itemSize; for ( var i = 0, l = this.itemSize; i < l; i ++ ) { this.array[ index1 + i ] = attribute.array[ index2 + i ]; } return this; }, copyArray: function ( array ) { this.array.set( array ); return this; }, copyColorsArray: function ( colors ) { var array = this.array, offset = 0; for ( var i = 0, l = colors.length; i < l; i ++ ) { var color = colors[ i ]; if ( color === undefined ) { console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i ); color = new Color(); } array[ offset ++ ] = color.r; array[ offset ++ ] = color.g; array[ offset ++ ] = color.b; } return this; }, copyIndicesArray: function ( indices ) { var array = this.array, offset = 0; for ( var i = 0, l = indices.length; i < l; i ++ ) { var index = indices[ i ]; array[ offset ++ ] = index.a; array[ offset ++ ] = index.b; array[ offset ++ ] = index.c; } return this; }, copyVector2sArray: function ( vectors ) { var array = this.array, offset = 0; for ( var i = 0, l = vectors.length; i < l; i ++ ) { var vector = vectors[ i ]; if ( vector === undefined ) { console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i ); vector = new Vector2(); } array[ offset ++ ] = vector.x; array[ offset ++ ] = vector.y; } return this; }, copyVector3sArray: function ( vectors ) { var array = this.array, offset = 0; for ( var i = 0, l = vectors.length; i < l; i ++ ) { var vector = vectors[ i ]; if ( vector === undefined ) { console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i ); vector = new Vector3(); } array[ offset ++ ] = vector.x; array[ offset ++ ] = vector.y; array[ offset ++ ] = vector.z; } return this; }, copyVector4sArray: function ( vectors ) { var array = this.array, offset = 0; for ( var i = 0, l = vectors.length; i < l; i ++ ) { var vector = vectors[ i ]; if ( vector === undefined ) { console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i ); vector = new Vector4(); } array[ offset ++ ] = vector.x; array[ offset ++ ] = vector.y; array[ offset ++ ] = vector.z; array[ offset ++ ] = vector.w; } return this; }, set: function ( value, offset ) { if ( offset === undefined ) offset = 0; this.array.set( value, offset ); return this; }, getX: function ( index ) { return this.array[ index * this.itemSize ]; }, setX: function ( index, x ) { this.array[ index * this.itemSize ] = x; return this; }, getY: function ( index ) { return this.array[ index * this.itemSize + 1 ]; }, setY: function ( index, y ) { this.array[ index * this.itemSize + 1 ] = y; return this; }, getZ: function ( index ) { return this.array[ index * this.itemSize + 2 ]; }, setZ: function ( index, z ) { this.array[ index * this.itemSize + 2 ] = z; return this; }, getW: function ( index ) { return this.array[ index * this.itemSize + 3 ]; }, setW: function ( index, w ) { this.array[ index * this.itemSize + 3 ] = w; return this; }, setXY: function ( index, x, y ) { index *= this.itemSize; this.array[ index + 0 ] = x; this.array[ index + 1 ] = y; return this; }, setXYZ: function ( index, x, y, z ) { index *= this.itemSize; this.array[ index + 0 ] = x; this.array[ index + 1 ] = y; this.array[ index + 2 ] = z; return this; }, setXYZW: function ( index, x, y, z, w ) { index *= this.itemSize; this.array[ index + 0 ] = x; this.array[ index + 1 ] = y; this.array[ index + 2 ] = z; this.array[ index + 3 ] = w; return this; }, clone: function () { return new this.constructor().copy( this ); } }; // function Int8Attribute( array, itemSize ) { return new BufferAttribute( new Int8Array( array ), itemSize ); } function Uint8Attribute( array, itemSize ) { return new BufferAttribute( new Uint8Array( array ), itemSize ); } function Uint8ClampedAttribute( array, itemSize ) { return new BufferAttribute( new Uint8ClampedArray( array ), itemSize ); } function Int16Attribute( array, itemSize ) { return new BufferAttribute( new Int16Array( array ), itemSize ); } function Uint16Attribute( array, itemSize ) { return new BufferAttribute( new Uint16Array( array ), itemSize ); } function Int32Attribute( array, itemSize ) { return new BufferAttribute( new Int32Array( array ), itemSize ); } function Uint32Attribute( array, itemSize ) { return new BufferAttribute( new Uint32Array( array ), itemSize ); } function Float32Attribute( array, itemSize ) { return new BufferAttribute( new Float32Array( array ), itemSize ); } function Float64Attribute( array, itemSize ) { return new BufferAttribute( new Float64Array( array ), itemSize ); } // Deprecated function DynamicBufferAttribute( array, itemSize ) { console.warn( 'THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setDynamic( true ) instead.' ); return new BufferAttribute( array, itemSize ).setDynamic( true ); } export { DynamicBufferAttribute, Float64Attribute, Float32Attribute, Uint32Attribute, Int32Attribute, Uint16Attribute, Int16Attribute, Uint8ClampedAttribute, Uint8Attribute, Int8Attribute, BufferAttribute };
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends")); var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose")); var React = _interopRequireWildcard(require("react")); var _reactIs = require("react-is"); var _propTypes = _interopRequireDefault(require("prop-types")); var _ownerDocument = _interopRequireDefault(require("../utils/ownerDocument")); var _List = _interopRequireDefault(require("../List")); var _getScrollbarSize = _interopRequireDefault(require("../utils/getScrollbarSize")); var _useForkRef = _interopRequireDefault(require("../utils/useForkRef")); var _useEnhancedEffect = _interopRequireDefault(require("../utils/useEnhancedEffect")); var _jsxRuntime = require("react/jsx-runtime"); const _excluded = ["actions", "autoFocus", "autoFocusItem", "children", "className", "disabledItemsFocusable", "disableListWrap", "onKeyDown", "variant"]; function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } function nextItem(list, item, disableListWrap) { if (list === item) { return list.firstChild; } if (item && item.nextElementSibling) { return item.nextElementSibling; } return disableListWrap ? null : list.firstChild; } function previousItem(list, item, disableListWrap) { if (list === item) { return disableListWrap ? list.firstChild : list.lastChild; } if (item && item.previousElementSibling) { return item.previousElementSibling; } return disableListWrap ? null : list.lastChild; } function textCriteriaMatches(nextFocus, textCriteria) { if (textCriteria === undefined) { return true; } let text = nextFocus.innerText; if (text === undefined) { // jsdom doesn't support innerText text = nextFocus.textContent; } text = text.trim().toLowerCase(); if (text.length === 0) { return false; } if (textCriteria.repeating) { return text[0] === textCriteria.keys[0]; } return text.indexOf(textCriteria.keys.join('')) === 0; } function moveFocus(list, currentFocus, disableListWrap, disabledItemsFocusable, traversalFunction, textCriteria) { let wrappedOnce = false; let nextFocus = traversalFunction(list, currentFocus, currentFocus ? disableListWrap : false); while (nextFocus) { // Prevent infinite loop. if (nextFocus === list.firstChild) { if (wrappedOnce) { return; } wrappedOnce = true; } // Same logic as useAutocomplete.js const nextFocusDisabled = disabledItemsFocusable ? false : nextFocus.disabled || nextFocus.getAttribute('aria-disabled') === 'true'; if (!nextFocus.hasAttribute('tabindex') || !textCriteriaMatches(nextFocus, textCriteria) || nextFocusDisabled) { // Move to the next element. nextFocus = traversalFunction(list, nextFocus, disableListWrap); } else { nextFocus.focus(); return; } } } /** * A permanently displayed menu following https://www.w3.org/TR/wai-aria-practices/#menubutton. * It's exposed to help customization of the [`Menu`](/api/menu/) component if you * use it separately you need to move focus into the component manually. Once * the focus is placed inside the component it is fully keyboard accessible. */ const MenuList = /*#__PURE__*/React.forwardRef(function MenuList(props, ref) { const { // private // eslint-disable-next-line react/prop-types actions, autoFocus = false, autoFocusItem = false, children, className, disabledItemsFocusable = false, disableListWrap = false, onKeyDown, variant = 'selectedMenu' } = props, other = (0, _objectWithoutPropertiesLoose2.default)(props, _excluded); const listRef = React.useRef(null); const textCriteriaRef = React.useRef({ keys: [], repeating: true, previousKeyMatched: true, lastTime: null }); (0, _useEnhancedEffect.default)(() => { if (autoFocus) { listRef.current.focus(); } }, [autoFocus]); React.useImperativeHandle(actions, () => ({ adjustStyleForScrollbar: (containerElement, theme) => { // Let's ignore that piece of logic if users are already overriding the width // of the menu. const noExplicitWidth = !listRef.current.style.width; if (containerElement.clientHeight < listRef.current.clientHeight && noExplicitWidth) { const scrollbarSize = `${(0, _getScrollbarSize.default)((0, _ownerDocument.default)(containerElement))}px`; listRef.current.style[theme.direction === 'rtl' ? 'paddingLeft' : 'paddingRight'] = scrollbarSize; listRef.current.style.width = `calc(100% + ${scrollbarSize})`; } return listRef.current; } }), []); const handleKeyDown = event => { const list = listRef.current; const key = event.key; /** * @type {Element} - will always be defined since we are in a keydown handler * attached to an element. A keydown event is either dispatched to the activeElement * or document.body or document.documentElement. Only the first case will * trigger this specific handler. */ const currentFocus = (0, _ownerDocument.default)(list).activeElement; if (key === 'ArrowDown') { // Prevent scroll of the page event.preventDefault(); moveFocus(list, currentFocus, disableListWrap, disabledItemsFocusable, nextItem); } else if (key === 'ArrowUp') { event.preventDefault(); moveFocus(list, currentFocus, disableListWrap, disabledItemsFocusable, previousItem); } else if (key === 'Home') { event.preventDefault(); moveFocus(list, null, disableListWrap, disabledItemsFocusable, nextItem); } else if (key === 'End') { event.preventDefault(); moveFocus(list, null, disableListWrap, disabledItemsFocusable, previousItem); } else if (key.length === 1) { const criteria = textCriteriaRef.current; const lowerKey = key.toLowerCase(); const currTime = performance.now(); if (criteria.keys.length > 0) { // Reset if (currTime - criteria.lastTime > 500) { criteria.keys = []; criteria.repeating = true; criteria.previousKeyMatched = true; } else if (criteria.repeating && lowerKey !== criteria.keys[0]) { criteria.repeating = false; } } criteria.lastTime = currTime; criteria.keys.push(lowerKey); const keepFocusOnCurrent = currentFocus && !criteria.repeating && textCriteriaMatches(currentFocus, criteria); if (criteria.previousKeyMatched && (keepFocusOnCurrent || moveFocus(list, currentFocus, false, disabledItemsFocusable, nextItem, criteria))) { event.preventDefault(); } else { criteria.previousKeyMatched = false; } } if (onKeyDown) { onKeyDown(event); } }; const handleRef = (0, _useForkRef.default)(listRef, ref); /** * the index of the item should receive focus * in a `variant="selectedMenu"` it's the first `selected` item * otherwise it's the very first item. */ let activeItemIndex = -1; // since we inject focus related props into children we have to do a lookahead // to check if there is a `selected` item. We're looking for the last `selected` // item and use the first valid item as a fallback React.Children.forEach(children, (child, index) => { if (! /*#__PURE__*/React.isValidElement(child)) { return; } if (process.env.NODE_ENV !== 'production') { if ((0, _reactIs.isFragment)(child)) { console.error(["Material-UI: The Menu component doesn't accept a Fragment as a child.", 'Consider providing an array instead.'].join('\n')); } } if (!child.props.disabled) { if (variant === 'selectedMenu' && child.props.selected) { activeItemIndex = index; } else if (activeItemIndex === -1) { activeItemIndex = index; } } }); const items = React.Children.map(children, (child, index) => { if (index === activeItemIndex) { const newChildProps = {}; if (autoFocusItem) { newChildProps.autoFocus = true; } if (child.props.tabIndex === undefined && variant === 'selectedMenu') { newChildProps.tabIndex = 0; } return /*#__PURE__*/React.cloneElement(child, newChildProps); } return child; }); return /*#__PURE__*/(0, _jsxRuntime.jsx)(_List.default, (0, _extends2.default)({ role: "menu", ref: handleRef, className: className, onKeyDown: handleKeyDown, tabIndex: autoFocus ? 0 : -1 }, other, { children: items })); }); process.env.NODE_ENV !== "production" ? MenuList.propTypes /* remove-proptypes */ = { // ----------------------------- Warning -------------------------------- // | These PropTypes are generated from the TypeScript type definitions | // | To update them edit the d.ts file and run "yarn proptypes" | // ---------------------------------------------------------------------- /** * If `true`, will focus the `[role="menu"]` container and move into tab order. * @default false */ autoFocus: _propTypes.default.bool, /** * If `true`, will focus the first menuitem if `variant="menu"` or selected item * if `variant="selectedMenu"`. * @default false */ autoFocusItem: _propTypes.default.bool, /** * MenuList contents, normally `MenuItem`s. */ children: _propTypes.default.node, /** * @ignore */ className: _propTypes.default.string, /** * If `true`, will allow focus on disabled items. * @default false */ disabledItemsFocusable: _propTypes.default.bool, /** * If `true`, the menu items will not wrap focus. * @default false */ disableListWrap: _propTypes.default.bool, /** * @ignore */ onKeyDown: _propTypes.default.func, /** * The variant to use. Use `menu` to prevent selected items from impacting the initial focus * and the vertical alignment relative to the anchor element. * @default 'selectedMenu' */ variant: _propTypes.default.oneOf(['menu', 'selectedMenu']) } : void 0; var _default = MenuList; exports.default = _default;
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- info: Operator x / y returns ToNumber(x) / ToNumber(y) es5id: 11.5.2_A3_T1.2 description: Type(x) and Type(y) vary between primitive number and Number object ---*/ //CHECK#1 if (1 / 1 !== 1) { $ERROR('#1: 1 / 1 === 1. Actual: ' + (1 / 1)); } //CHECK#2 if (new Number(1) / 1 !== 1) { $ERROR('#2: new Number(1) / 1 === 1. Actual: ' + (new Number(1) / 1)); } //CHECK#3 if (1 / new Number(1) !== 1) { $ERROR('#3: 1 / new Number(1) === 1. Actual: ' + (1 / new Number(1))); } //CHECK#4 if (new Number(1) / new Number(1) !== 1) { $ERROR('#4: new Number(1) / new Number(1) === 1. Actual: ' + (new Number(1) / new Number(1))); }
define({ "_widgetLabel": "Ominaisuustaulu", "_featureAction_ShowRelatedRecords": "Näytä liittyvät tietueet", "_featureAction_ViewInTable": "Näytä ominaisuustaulukossa", "ok": "OK", "cancel": "Peruuta", "unsupportQueryWarning": "Karttatason on tuettava kyselytoimintoa, jotta karttatason voi näyttää Ominaisuustietotaulu-pienoisohjelmassa. Varmista, että palvelun kyselyominaisuus on käytössä.", "exportMessage": "Vie dataa CSV-tiedostoon?", "exportFiles": "Vie CSV-tiedostoon", "exportSelected": "Vie valittu kohde CSV-muotoon", "exportAll": "Vie kaikki CSV-muotoon", "options": "Valinnat", "zoomto": "Tarkenna kohteeseen", "highlight": "Korosta grafiikkaa", "selectAll": "Valitse tietueita kaikilta sivuilta", "selectPage": "Valitse tietueita nykyiseltä sivulta", "clearSelection": "Tyhjennä valinta", "filter": "Suodata", "setFilterTip": "Määritä suodatin oikein.", "noFilterTip": "Jos suodatinlauseketta ei määritetä, kyselytehtävä luetteloi kaikki määritetyn tietolähteen kohteet.", "filterByExtent": "Suodata kartan laajuuden mukaan", "showSelectedRecords": "Näytä valitut tietueet", "showAllRecords": "Näytä kaikki tietueet", "showRelatedRecords": "Näytä liittyvät tietueet", "noRelatedRecords": "Liittyviä tietueita ei löytynyt", "attachmentColumn": "Valokuvat ja tiedostot", "refresh": "Päivitä", "features": "kohteet", "records": "tietueet", "selected": "valitut", "transparent": "Läpinäkyvä tila", "indicate": "Paikanna valinta", "columns": "Näytä/Piilota sarakkeet", "selectionSymbol": "Valintasymboli", "closeMessage": "Piilota taulukko (laajenna se uudelleen alareunasta)", "dataNotAvailable": "Data ei ole käytettävissä!<br>Yritä uudelleen napsauttamalla [Päivitä]-painiketta.", "openTableTip": "Avaa ominaisuustietotaulu", "closeTableTip": "Piilota ominaisuustietotaulukko", "sortAsc": "Lajittele nousevasti", "sortDes": "Lajittele laskevasti", "statistics": "Tilastotiedot", "attachments": "Liitteet", "files": "tiedostot" });
/** @license * @pnp/config-store v1.1.3 - pnp - provides a way to manage configuration within your application * 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 */ import { Dictionary, PnPClientStorage } from '@pnp/common'; import { __extends } from 'tslib'; import { Logger } from '@pnp/logging'; /** * Class used to manage the current application settings * */ var Settings = /** @class */ (function () { /** * Creates a new instance of the settings class * * @constructor */ function Settings() { this._settings = new Dictionary(); } /** * Adds a new single setting, or overwrites a previous setting with the same key * * @param {string} key The key used to store this setting * @param {string} value The setting value to store */ Settings.prototype.add = function (key, value) { this._settings.add(key, value); }; /** * Adds a JSON value to the collection as a string, you must use getJSON to rehydrate the object when read * * @param {string} key The key used to store this setting * @param {any} value The setting value to store */ Settings.prototype.addJSON = function (key, value) { this._settings.add(key, JSON.stringify(value)); }; /** * Applies the supplied hash to the setting collection overwriting any existing value, or created new values * * @param {TypedHash<any>} hash The set of values to add */ Settings.prototype.apply = function (hash) { var _this = this; return new Promise(function (resolve, reject) { try { _this._settings.merge(hash); resolve(); } catch (e) { reject(e); } }); }; /** * Loads configuration settings into the collection from the supplied provider and returns a Promise * * @param {IConfigurationProvider} provider The provider from which we will load the settings */ Settings.prototype.load = function (provider) { var _this = this; return new Promise(function (resolve, reject) { provider.getConfiguration().then(function (value) { _this._settings.merge(value); resolve(); }).catch(reject); }); }; /** * Gets a value from the configuration * * @param {string} key The key whose value we want to return. Returns null if the key does not exist * @return {string} string value from the configuration */ Settings.prototype.get = function (key) { return this._settings.get(key); }; /** * Gets a JSON value, rehydrating the stored string to the original object * * @param {string} key The key whose value we want to return. Returns null if the key does not exist * @return {any} object from the configuration */ Settings.prototype.getJSON = function (key) { var o = this.get(key); if (typeof o === "undefined" || o === null) { return o; } return JSON.parse(o); }; return Settings; }()); var NoCacheAvailableException = /** @class */ (function (_super) { __extends(NoCacheAvailableException, _super); function NoCacheAvailableException(msg) { if (msg === void 0) { msg = "Cannot create a caching configuration provider since cache is not available."; } var _this = _super.call(this, msg) || this; _this.name = "NoCacheAvailableException"; Logger.log({ data: {}, level: 3 /* Error */, message: "[" + _this.name + "]::" + _this.message }); return _this; } return NoCacheAvailableException; }(Error)); /** * A caching provider which can wrap other non-caching providers * */ var CachingConfigurationProvider = /** @class */ (function () { /** * Creates a new caching configuration provider * @constructor * @param {IConfigurationProvider} wrappedProvider Provider which will be used to fetch the configuration * @param {string} cacheKey Key that will be used to store cached items to the cache * @param {IPnPClientStore} cacheStore OPTIONAL storage, which will be used to store cached settings. */ function CachingConfigurationProvider(wrappedProvider, cacheKey, cacheStore) { this.wrappedProvider = wrappedProvider; this.cacheKey = cacheKey; this.wrappedProvider = wrappedProvider; this.store = (cacheStore) ? cacheStore : this.selectPnPCache(); } /** * Gets the wrapped configuration providers * * @return {IConfigurationProvider} Wrapped configuration provider */ CachingConfigurationProvider.prototype.getWrappedProvider = function () { return this.wrappedProvider; }; /** * Loads the configuration values either from the cache or from the wrapped provider * * @return {Promise<TypedHash<string>>} Promise of loaded configuration values */ CachingConfigurationProvider.prototype.getConfiguration = function () { var _this = this; // Cache not available, pass control to the wrapped provider if ((!this.store) || (!this.store.enabled)) { return this.wrappedProvider.getConfiguration(); } return this.store.getOrPut(this.cacheKey, function () { return _this.wrappedProvider.getConfiguration().then(function (providedConfig) { _this.store.put(_this.cacheKey, providedConfig); return providedConfig; }); }); }; CachingConfigurationProvider.prototype.selectPnPCache = function () { var pnpCache = new PnPClientStorage(); if ((pnpCache.local) && (pnpCache.local.enabled)) { return pnpCache.local; } if ((pnpCache.session) && (pnpCache.session.enabled)) { return pnpCache.session; } throw new NoCacheAvailableException(); }; return CachingConfigurationProvider; }()); /** * A configuration provider which loads configuration values from a SharePoint list * */ var SPListConfigurationProvider = /** @class */ (function () { /** * Creates a new SharePoint list based configuration provider * @constructor * @param {string} webUrl Url of the SharePoint site, where the configuration list is located * @param {string} listTitle Title of the SharePoint list, which contains the configuration settings (optional, default: "config") * @param {string} keyFieldName The name of the field in the list to use as the setting key (optional, default: "Title") * @param {string} valueFieldName The name of the field in the list to use as the setting value (optional, default: "Value") */ function SPListConfigurationProvider(web, listTitle, keyFieldName, valueFieldName) { if (listTitle === void 0) { listTitle = "config"; } if (keyFieldName === void 0) { keyFieldName = "Title"; } if (valueFieldName === void 0) { valueFieldName = "Value"; } this.web = web; this.listTitle = listTitle; this.keyFieldName = keyFieldName; this.valueFieldName = valueFieldName; } /** * Loads the configuration values from the SharePoint list * * @return {Promise<TypedHash<string>>} Promise of loaded configuration values */ SPListConfigurationProvider.prototype.getConfiguration = function () { var _this = this; return this.web.lists.getByTitle(this.listTitle).items.select(this.keyFieldName, this.valueFieldName).get() .then(function (data) { return data.reduce(function (c, item) { c[item[_this.keyFieldName]] = item[_this.valueFieldName]; return c; }, {}); }); }; /** * Wraps the current provider in a cache enabled provider * * @return {CachingConfigurationProvider} Caching providers which wraps the current provider */ SPListConfigurationProvider.prototype.asCaching = function (cacheKey) { if (cacheKey === void 0) { cacheKey = "pnp_configcache_splist_" + this.web.toUrl() + "+" + this.listTitle; } return new CachingConfigurationProvider(this, cacheKey); }; return SPListConfigurationProvider; }()); export { Settings, CachingConfigurationProvider, SPListConfigurationProvider, NoCacheAvailableException }; //# sourceMappingURL=config-store.es5.js.map
var Test = /*#__PURE__*/ function () { "use strict"; function Test() { babelHelpers.classCallCheck(this, Test); } babelHelpers.createClass(Test, [{ key: "test", get: function get() { return 5 + 5; }, set: function set(val) { this._test = val; } }]); return Test; }();
export default { el: { colorpicker: { confirm: 'Қабылдау', clear: 'Тазалау' }, datepicker: { now: 'Қазір', today: 'Бүгін', cancel: 'Болдырмау', clear: 'Тазалау', confirm: 'Қабылдау', selectDate: 'Күнді таңдаңыз', selectTime: 'Сағатты таңдаңыз', startDate: 'Басталу күні', startTime: 'Басталу сағаты', endDate: 'Аяқталу күні', endTime: 'Аяқталу сағаты', prevYear: 'Алдыңғы жыл', nextYear: 'Келесі жыл', prevMonth: 'Алдыңғы ай', nextMonth: 'Келесі ай', year: 'Жыл', month1: 'Қаңтар', month2: 'Ақпан', month3: 'Наурыз', month4: 'Сәуір', month5: 'Мамыр', month6: 'Маусым', month7: 'Шілде', month8: 'Тамыз', month9: 'Қыркүйек', month10: 'Қазан', month11: 'Қараша', month12: 'Желтоқсан', week: 'Апта', weeks: { sun: 'Жек', mon: 'Дүй', tue: 'Сей', wed: 'Сәр', thu: 'Бей', fri: 'Жұм', sat: 'Сен' }, months: { jan: 'Қаң', feb: 'Ақп', mar: 'Нау', apr: 'Сәу', may: 'Мам', jun: 'Мау', jul: 'Шіл', aug: 'Там', sep: 'Қыр', oct: 'Қаз', nov: 'Қар', dec: 'Жел' } }, select: { loading: 'Жүктелуде', noMatch: 'Сәйкес деректер жоқ', noData: 'Деректер жоқ', placeholder: 'Таңдаңыз' }, cascader: { noMatch: 'Сәйкес деректер жоқ', loading: 'Жүктелуде', placeholder: 'Таңдаңыз' }, pagination: { goto: 'Бару', pagesize: '/page', total: 'Барлығы {total}', pageClassifier: '' }, messagebox: { title: 'Хабар', confirm: 'Қабылдау', cancel: 'Болдырмау', error: 'Жарамсыз енгізулер' }, upload: { deleteTip: 'Өшіруді басып өшіріңіз', delete: 'Өшіру', preview: 'Алдын ала қарау', continue: 'Жалғастыру' }, table: { emptyText: 'Деректер жоқ', confirmFilter: 'Қабылдау', resetFilter: 'Қалпына келтіру', clearFilter: 'Барлығы', sumText: 'Сомасы' }, tree: { emptyText: 'Деректер жоқ' }, transfer: { noMatch: 'Сәйкес деректер жоқ', noData: 'Деректер жоқ', titles: ['List 1', 'List 2'], filterPlaceholder: 'Кілт сөзді енгізіңіз', noCheckedFormat: '{total} элэмэнт', hasCheckedFormat: '{checked}/{total} құсбелгісі қойылды' } } };
/** * Ruby */ module.exports = { // find document blocks between '=begin' and '=end' docBlocksRegExp: /\=begin\uffff?(.+?)\uffff?(?:\s*)?\=end/g, // remove not needed tabs at the beginning inlineRegExp: /^(\t*)?/gm };
/* * The MIT License * * Copyright (c) 2015, Sebastian Sdorra * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ 'use strict'; /** * @ngdoc object * @name adf.dashboardProvider * @description * * The dashboardProvider can be used to register structures and widgets. */ angular.module('adf.provider', []) .provider('dashboard', function(){ var widgets = {}; var widgetsPath = ''; var structures = {}; var messageTemplate = '<div class="alert alert-danger">{}</div>'; var loadingTemplate = '\ <div class="progress progress-striped active">\n\ <div class="progress-bar" role="progressbar" style="width: 100%">\n\ <span class="sr-only">loading ...</span>\n\ </div>\n\ </div>'; /** * @ngdoc method * @name adf.dashboardProvider#widget * @methodOf adf.dashboardProvider * @description * * Registers a new widget. * * @param {string} name of the widget * @param {object} widget to be registered. * * Object properties: * * - `title` - `{string=}` - The title of the widget. * - `description` - `{string=}` - Description of the widget. * - `config` - `{object}` - Predefined widget configuration. * - `controller` - `{string=|function()=}` - Controller fn that should be * associated with newly created scope of the widget or the name of a * {@link http://docs.angularjs.org/api/angular.Module#controller registered controller} * if passed as a string. * - `controllerAs` - `{string=}` - A controller alias name. If present the controller will be * published to scope under the `controllerAs` name. * - `frameless` - `{boolean=}` - false if the widget should be shown in frameless mode. The default is false. * - `template` - `{string=|function()=}` - html template as a string. * - `templateUrl` - `{string=}` - path to an html template. * - `reload` - `{boolean=}` - true if the widget could be reloaded. The default is false. * - `resolve` - `{Object.<string, function>=}` - An optional map of dependencies which should * be injected into the controller. If any of these dependencies are promises, the widget * will wait for them all to be resolved or one to be rejected before the controller is * instantiated. * If all the promises are resolved successfully, the values of the resolved promises are * injected. * * The map object is: * - `key` – `{string}`: a name of a dependency to be injected into the controller. * - `factory` - `{string|function}`: If `string` then it is an alias for a service. * Otherwise if function, then it is {@link http://docs.angularjs.org/api/AUTO.$injector#invoke injected} * and the return value is treated as the dependency. If the result is a promise, it is * resolved before its value is injected into the controller. * - `edit` - `{object}` - Edit modus of the widget. * - `controller` - `{string=|function()=}` - Same as above, but for the edit mode of the widget. * - `controllerAs` - `{string=}` - Same as above, but for the edit mode of the widget. * - `template` - `{string=|function()=}` - Same as above, but for the edit mode of the widget. * - `templateUrl` - `{string=}` - Same as above, but for the edit mode of the widget. * - `resolve` - `{Object.<string, function>=}` - Same as above, but for the edit mode of the widget. * - `reload` - {boolean} - true if the widget should be reloaded, after the edit mode is closed. * Default is true. * * @returns {Object} self */ this.widget = function(name, widget){ var w = angular.extend({reload: false, frameless: false}, widget); if ( w.edit ){ var edit = {reload: true}; angular.extend(edit, w.edit); w.edit = edit; } widgets[name] = w; return this; }; /** * @ngdoc method * @name adf.dashboardProvider#widgetsPath * @methodOf adf.dashboardProvider * @description * * Sets the path to the directory which contains the widgets. The widgets * path is used for widgets with a templateUrl which contains the * placeholder {widgetsPath}. The placeholder is replaced with the * configured value, before the template is loaded, but the template is * cached with the unmodified templateUrl (e.g.: {widgetPath}/src/widgets). * The default value of widgetPaths is ''. * * * @param {string} path to the directory which contains the widgets * * @returns {Object} self */ this.widgetsPath = function(path){ widgetsPath = path; return this; }; /** * @ngdoc method * @name adf.dashboardProvider#structure * @methodOf adf.dashboardProvider * @description * * Registers a new structure. * * @param {string} name of the structure * @param {object} structure to be registered. * * Object properties: * * - `rows` - `{Array.<Object>}` - Rows of the dashboard structure. * - `styleClass` - `{string}` - CSS Class of the row. * - `columns` - `{Array.<Object>}` - Columns of the row. * - `styleClass` - `{string}` - CSS Class of the column. * * @returns {Object} self */ this.structure = function(name, structure){ structures[name] = structure; return this; }; /** * @ngdoc method * @name adf.dashboardProvider#messageTemplate * @methodOf adf.dashboardProvider * @description * * Changes the template for messages. * * @param {string} template for messages. * * @returns {Object} self */ this.messageTemplate = function(template){ messageTemplate = template; return this; }; /** * @ngdoc method * @name adf.dashboardProvider#loadingTemplate * @methodOf adf.dashboardProvider * @description * * Changes the template which is displayed as * long as the widget resources are not resolved. * * @param {string} template loading template * * @returns {Object} self */ this.loadingTemplate = function(template){ loadingTemplate = template; return this; }; /** * @ngdoc service * @name adf.dashboard * @description * * The dashboard holds all options, structures and widgets. * * @property {Array.<Object>} widgets Array of registered widgets. * @property {string} widgetsPath Default path for widgets. * @property {Array.<Object>} structures Array of registered structures. * @property {string} messageTemplate Template for messages. * @property {string} loadingTemplate Template for widget loading. * * @returns {Object} self */ this.$get = function(){ var cid = 0; return { widgets: widgets, widgetsPath: widgetsPath, structures: structures, messageTemplate: messageTemplate, loadingTemplate: loadingTemplate, /** * @ngdoc method * @name adf.dashboard#id * @methodOf adf.dashboard * @description * * Creates an ongoing numeric id. The method is used to create ids for * columns and widgets in the dashboard. */ id: function(){ return ++cid; } }; }; });
'use strict'; const fs = require('fs'); const path = require('path'); const ts = require('./typescript'); /** * @param name {string} * @param source {string} */ const DEPRECATED_FEATURES = (function getFeatures() { let fileName = path.join( __dirname, '..', 'packages', '@ember', 'deprecated-features', 'index.ts' ); let contents = fs.readFileSync(fileName, 'utf8'); let sourceFile = ts.createSourceFile(fileName, contents, ts.ScriptTarget.ES2017); let flags = {}; sourceFile.statements.forEach((statement) => { if ( statement.kind === ts.SyntaxKind.VariableStatement && statement.modifiers.some((m) => m.kind === ts.SyntaxKind.ExportKeyword) ) { handleExportedDeclaration(statement, flags); } }); return flags; })(); /** * @param d {ts.VariableStatement} * @param map {{[flag: string]: string}} */ function handleExportedDeclaration(d, map) { let declaration = d.declarationList.declarations[0]; /** @type {ts.StringLiteral} */ let initializer = declaration.initializer; if ( initializer && initializer.kind === ts.SyntaxKind.PrefixUnaryExpression && initializer.operand.kind === ts.SyntaxKind.PrefixUnaryExpression && initializer.operand.operand.kind === ts.SyntaxKind.StringLiteral ) { map[declaration.name.text] = initializer.operand.operand.text; } } module.exports = DEPRECATED_FEATURES;
; (function() { window.require(["ace/snippets/eiffel"], function(m) { if (typeof module == "object" && typeof exports == "object" && module) { module.exports = m; } }); })();
"use strict"; var ASSERT = require("./assert"); function arrayMove(src, srcIndex, dst, dstIndex, len) { for (var j = 0; j < len; ++j) { dst[j + dstIndex] = src[j + srcIndex]; src[j + srcIndex] = void 0; } } function Queue(capacity) { this._capacity = capacity; this._length = 0; this._front = 0; } Queue.prototype._willBeOverCapacity = function (size) { return this._capacity < size; }; Queue.prototype._pushOne = function (arg) { var length = this.length(); this._checkCapacity(length + 1); var i = (this._front + length) & (this._capacity - 1); this[i] = arg; this._length = length + 1; }; Queue.prototype._unshiftOne = function(value) { var capacity = this._capacity; this._checkCapacity(this.length() + 1); var front = this._front; var i = (((( front - 1 ) & ( capacity - 1) ) ^ capacity ) - capacity ); this[i] = value; this._front = i; this._length = this.length() + 1; }; Queue.prototype.unshift = function(fn, receiver, arg) { this._unshiftOne(arg); this._unshiftOne(receiver); this._unshiftOne(fn); }; Queue.prototype.push = function (fn, receiver, arg) { ASSERT(arguments.length === 3); ASSERT(typeof fn === "function"); var length = this.length() + 3; if (this._willBeOverCapacity(length)) { //The fast array copies expect the //underlying array to be filled completely this._pushOne(fn); this._pushOne(receiver); this._pushOne(arg); return; } var j = this._front + length - 3; this._checkCapacity(length); var wrapMask = this._capacity - 1; this[(j + 0) & wrapMask] = fn; this[(j + 1) & wrapMask] = receiver; this[(j + 2) & wrapMask] = arg; this._length = length; }; Queue.prototype.shift = function () { ASSERT(this.length() > 0); var front = this._front, ret = this[front]; this[front] = undefined; this._front = (front + 1) & (this._capacity - 1); this._length--; return ret; }; Queue.prototype.length = function () { return this._length; }; Queue.prototype._checkCapacity = function (size) { if (this._capacity < size) { this._resizeTo(this._capacity << 1); } }; Queue.prototype._resizeTo = function (capacity) { var oldCapacity = this._capacity; this._capacity = capacity; var front = this._front; var length = this._length; var moveItemsCount = (front + length) & (oldCapacity - 1); arrayMove(this, 0, this, oldCapacity, moveItemsCount); }; module.exports = Queue;
describe("uiMask", function () { "use strict"; var formHtml = "<form name='test'><input name='input' ng-model='x' ui-mask='{{mask}}'></form>"; var inputHtml = "<input name='input' ng-model='x' ui-mask='{{mask}}'>"; var compileElement, scope, config; beforeEach(module("ui.mask")); beforeEach(function() { angular.module("test",[]).directive("toUpper", function() { return { priority: 200, require: 'ngModel', restrict: 'A', link: function (scope, iElement, iAttrs, controller) { controller.$formatters.push(function(fromModelValue) { return angular.uppercase(fromModelValue); }); controller.$parsers.push(function(fromViewValue) { return angular.lowercase(fromViewValue); }); } } }); module("test"); }); beforeEach(inject(function ($rootScope, $compile, uiMaskConfig) { scope = $rootScope; config = uiMaskConfig; compileElement = function(html) { return $compile(html)(scope); }; })); describe("initialization", function () { it("should not not happen if the mask is undefined or invalid", function() { var input = compileElement(inputHtml); scope.$apply("x = 'abc123'"); expect(input.val()).toBe("abc123"); scope.$apply("mask = '()_abc123'"); expect(input.val()).toBe("abc123"); }); it("should mask the value only if it's valid", function() { var input = compileElement(inputHtml); scope.$apply("x = 'abc123'"); scope.$apply("mask = '(A) * 9'"); expect(input.val()).toBe("(a) b 1"); scope.$apply("mask = '(A) * 9 A'"); expect(input.val()).toBe(""); }); it("should not dirty or invalidate the input", function() { var input = compileElement(inputHtml); scope.$apply("x = 'abc123'"); scope.$apply("mask = '(9) * A'"); expect(input.hasClass("ng-pristine")).toBeTruthy(); scope.$apply("mask = '(9) * A 9'"); expect(input.hasClass("ng-pristine")).toBeTruthy(); }); it("should not change the model value", function() { scope.$apply("x = 'abc123'"); scope.$apply("mask = '(A) * 9'"); expect(scope.x).toBe("abc123"); scope.$apply("mask = '(A) * 9 A'"); expect(scope.x).toBe("abc123"); }); it("should set ngModelController.$viewValue to match input value", function() { compileElement(formHtml); scope.$apply("x = 'abc123'"); scope.$apply("mask = '(A) * 9'"); expect(scope.test.input.$viewValue).toBe("(a) b 1"); scope.$apply("mask = '(A) * 9 A'"); expect(scope.test.input.$viewValue).toBe(""); }); }); describe("with other directives", function() { beforeEach(function () { compileElement("<form name='test'><input to-upper name='input' ng-model='x' ui-mask='{{mask}}'></form>"); }); it("should play nicely", function() { scope.$apply("x = 'abc123'"); scope.$apply("mask = '(A) * 9'"); expect(scope.x).toBe("abc123"); expect(scope.test.input.$viewValue).toBe("(A) B 1"); scope.$apply("mask = '(A)AA'"); expect(scope.test.input.$viewValue).toBe("(A)BC"); }); describe("with model-view-value", function() { var input = undefined; beforeEach(function () { input = compileElement("<form name='test'><input to-upper name='input' ng-model='x' model-view-value='true' ui-mask='{{mask}}'></form>"); input = input.find('input') }); it("should set the model value to the masked view value parsed by other directive", function() { scope.$apply("x = '(a) b 1'"); scope.$apply("mask = '(A) * 9'"); expect(scope.test.input.$viewValue).toBe("(A) B 1"); input.val("(A) C 2").triggerHandler("input").triggerHandler("change"); scope.$apply(); expect(scope.x).toBe("(a) c 2"); }); }); }); describe("user input", function () { it("should mask-as-you-type", function() { var form = compileElement(formHtml); var input = form.find("input"); scope.$apply("x = ''"); scope.$apply("mask = '(A) * 9'"); input.val("a").triggerHandler("input"); expect(input.val()).toBe("(a) _ _"); input.val("ab").triggerHandler("input"); expect(input.val()).toBe("(a) b _"); input.val("ab1").triggerHandler("input"); expect(input.val()).toBe("(a) b 1"); }); it("should set ngModelController.$viewValue to match input value", function() { var form = compileElement(formHtml); var input = form.find("input"); scope.$apply("x = ''"); scope.$apply("mask = '(A) * 9'"); input.val("a").triggerHandler("input"); input.triggerHandler("change"); // Because IE8 and below are terrible expect(scope.test.input.$viewValue).toBe("(a) _ _"); }); it("should maintain $viewValue consistent with input value", function() { var form = compileElement(formHtml); var input = form.find("input"); scope.$apply("x = ''"); scope.$apply("mask = '99 9'"); input.val("3333").triggerHandler("input"); input.val("3333").triggerHandler("input"); // It used to has a bug when pressing a key repeatedly expect(scope.test.input.$viewValue).toBe("33 3"); }); it("should parse unmasked value to model", function() { var form = compileElement(formHtml); var input = form.find("input"); scope.$apply("x = ''"); scope.$apply("mask = '(A) * 9'"); input.val("abc123").triggerHandler("input"); input.triggerHandler("change"); // Because IE8 and below are terrible expect(scope.x).toBe("ab1"); }); it("should set model to undefined if masked value is invalid", function() { var form = compileElement(formHtml); var input = form.find("input"); scope.$apply("x = ''"); scope.$apply("mask = '(A) * 9'"); input.val("a").triggerHandler("input"); input.triggerHandler("change"); // Because IE8 and below are terrible expect(scope.x).toBeUndefined(); }); it("should not set model to an empty mask", function() { var form = compileElement(formHtml); var input = form.find("input"); scope.$apply("x = ''"); scope.$apply("mask = '(A) * 9'"); input.triggerHandler("input"); expect(scope.x).toBe(""); }); it("should not setValidity on required to false on a control that isn't required", function() { var input = compileElement("<input name='input' ng-model='x' ui-mask='{{mask}}'>"); scope.$apply("x = ''"); scope.$apply("mask = '(A) * 9'"); scope.$apply("required = true"); expect(input.data("$ngModelController").$error.required).toBeUndefined(); input.triggerHandler("input"); expect(scope.x).toBe(""); expect(input.data("$ngModelController").$error.required).toBeUndefined(); input = compileElement("<input name='input' ng-model='x' ui-mask='{{mask}}' required>"); expect(input.data("$ngModelController").$error.required).toBeUndefined(); input.triggerHandler("input"); expect(input.data("$ngModelController").$error.required).toBe(true); input.val("abc123").triggerHandler("input"); expect(scope.x).toBe("ab1"); expect(input.data("$ngModelController").$error.required).toBeUndefined(); input = compileElement("<input name='input' ng-model='x' ui-mask='{{mask}}' ng-required='required'>"); expect(input.data("$ngModelController").$error.required).toBeUndefined(); input.triggerHandler("input"); expect(input.data("$ngModelController").$error.required).toBe(true); scope.$apply("required = false"); expect(input.data("$ngModelController").$error.required).toBeUndefined(); input.triggerHandler("input"); expect(input.data("$ngModelController").$error.required).toBeUndefined(); input.triggerHandler("focus"); input.triggerHandler("blur"); expect(input.data("$ngModelController").$error.required).toBeUndefined(); input.val("").triggerHandler("input"); expect(input.data("$ngModelController").$error.required).toBeUndefined(); }); }); describe("with model-view-value", function() { var input = undefined; beforeEach(function () { input = compileElement("<form name='test'><input name='input' ng-model='x' model-view-value='true' ui-mask='{{mask}}'></form>"); input = input.find('input') }); it("should set the mask in the model", function() { scope.$apply("x = '(a) b 1'"); scope.$apply("mask = '(A) * 9'"); expect(scope.test.input.$viewValue).toBe("(a) b 1"); input.val("(a) c 2").triggerHandler("input").triggerHandler("change"); scope.$apply(); expect(scope.x).toBe("(a) c 2"); }); }); describe("changes from the model", function () { it("should set the correct ngModelController.$viewValue", function() { compileElement(formHtml); scope.$apply("mask = '(A) * 9'"); scope.$apply("x = ''"); expect(scope.test.input.$viewValue).not.toBeDefined(); scope.$apply("x = 'abc'"); expect(scope.test.input.$viewValue).not.toBeDefined(); scope.$apply("x = 'abc123'"); expect(scope.test.input.$viewValue).toBe("(a) b 1"); }); it("should accept change model and mask on same $digest", function() { compileElement(formHtml); scope.$apply(" x='1234'; mask = '99-99';"); scope.$apply(" x='123'; mask = '99-9';"); expect(scope.test.input.$viewValue).toBe('12-3'); expect(scope.x).toBe('123'); }); it("should set validity when setting model and mask on same $digest", function() { compileElement(formHtml); scope.$apply(" x='1234'; mask = '99-99';"); scope.$apply(" x='123'; mask = '99-9';"); expect(scope.test.input.$valid).toBe(true); }); }); describe("default mask definitions", function () { it("should accept optional mask after '?'", function (){ var input = compileElement(inputHtml); scope.$apply("x = ''"); scope.$apply("mask = '**?9'"); input.val("aa").triggerHandler("input"); input.triggerHandler("blur"); expect(input.val()).toBe("aa_"); input.val("99a").triggerHandler("input"); input.triggerHandler("blur"); expect(input.val()).toBe("99_"); input.val("992").triggerHandler("input"); input.triggerHandler("blur"); expect(input.val()).toBe("992"); }); }); describe("placeholders", function () { it("should have default placeholder functionality", function() { var input = compileElement(inputHtml); scope.$apply("x = ''"); scope.$apply("mask = '99/99/9999'"); expect(input.attr("placeholder")).toBe("__/__/____"); }); it("should allow mask substitutions via the placeholder attribute", function() { var placeholderHtml = "<input name='input' ng-model='x' ui-mask='{{mask}}' placeholder='MM/DD/YYYY'>", input = compileElement(placeholderHtml); scope.$apply("x = ''"); scope.$apply("mask = '99/99/9999'"); expect(input.attr("placeholder")).toBe("MM/DD/YYYY"); input.val("12").triggerHandler("input"); expect(input.val()).toBe("12/DD/YYYY"); }); it("should update mask substitutions via the placeholder attribute", function() { var placeholderHtml = "<input name='input' ng-model='x' ui-mask='{{mask}}' placeholder='{{placeholder}}'>", input = compileElement(placeholderHtml); scope.$apply("x = ''"); scope.$apply("mask = '99/99/9999'"); scope.$apply("placeholder = 'DD/MM/YYYY'"); expect(input.attr("placeholder")).toBe("DD/MM/YYYY"); input.val("12").triggerHandler("input"); expect(input.val()).toBe("12/MM/YYYY"); scope.$apply("placeholder = 'MM/DD/YYYY'"); expect(input.val()).toBe("12/DD/YYYY"); input.triggerHandler("blur"); expect(input.attr("placeholder")).toBe("MM/DD/YYYY"); }); it("should ignore the '?' character", function() { var placeholderHtml = "<input type=\"text\" ui-mask=\"99/99/9999 ?99:99\" placeholder=\"DD/MM/YYYY HH:mm\" ng-model=\"myDate\">", input = compileElement(placeholderHtml); scope.$apply("myDate = ''"); expect(input.attr("placeholder")).toBe("DD/MM/YYYY HH:mm"); }); it("should accept ui-mask-placeholder", function() { var placeholderHtml = "<input name='input' ng-model='x' ui-mask='{{mask}}' placeholder='Phone Number' ui-mask-placeholder='(XXX) XXX-XXXX'>", input = compileElement(placeholderHtml); scope.$apply("x = ''"); scope.$apply("mask = '(999) 999-9999'"); input.triggerHandler("input"); expect(input.val()).toBe("(XXX) XXX-XXXX"); expect(input.attr("placeholder")).toBe("Phone Number"); }); it("should accept ui-mask-placeholder and not set val when first showing input", function() { var placeholderHtml = "<input name='input' ng-model='x' ui-mask='{{mask}}' placeholder='Phone Number' ui-mask-placeholder='(XXX) XXX-XXXX'>", input = compileElement(placeholderHtml); scope.$apply("x = ''"); scope.$apply("mask = '(999) 999-9999'"); expect(input.val()).toBe(""); expect(input.attr("placeholder")).toBe("Phone Number"); }); it("should interpret empty ui-mask-placeholder", function() { var placeholderHtml = "<input name='input' ng-model='x' ui-mask='{{mask}}' placeholder='Phone Number' ui-mask-placeholder>", input = compileElement(placeholderHtml); scope.$apply("x = ''"); scope.$apply("mask = '(999) 999-9999'"); input.triggerHandler("input"); expect(input.val()).toBe("(___) ___-____"); expect(input.attr("placeholder")).toBe("Phone Number"); }) }); describe("configuration", function () { it("should accept the new mask definition set globally", function() { config.maskDefinitions["@"] = /[fz]/; var input = compileElement(inputHtml); scope.$apply("x = ''"); scope.$apply("mask = '@193'"); input.val("f123").triggerHandler("input"); input.triggerHandler("blur"); expect(input.val()).toBe("f123"); }); it("should accept the new mask definition set per element", function() { delete config.maskDefinitions["@"]; scope.input = { options: {maskDefinitions: {"@": /[fz]/}} }; var input = compileElement("<input type=\"text\" ng-model=\"x\" ui-mask=\"{{mask}}\" ui-options=\"input.options\">"); scope.$apply("x = ''"); scope.$apply("mask = '@999'"); input.val("f111").triggerHandler("input"); input.triggerHandler("blur"); expect(input.val()).toBe("f111"); }); }); describe("blurring", function () { it("should clear an invalid value from the input", function() { var input = compileElement(inputHtml); scope.$apply("x = ''"); scope.$apply("mask = '(9) * A'"); input.val("a").triggerHandler("input"); input.triggerHandler("blur"); expect(input.val()).toBe(""); }); it("should clear an invalid value from the ngModelController.$viewValue", function() { var form = compileElement(formHtml); var input = form.find("input"); scope.$apply("x = ''"); scope.$apply("mask = '(A) * 9'"); input.val("a").triggerHandler("input"); input.triggerHandler("blur"); expect(scope.test.input.$viewValue).toBe(""); }); var inputHtmlClearOnBlur = "<input name='input' ng-model='x' ui-mask='{{mask}}' ui-options=\"input.options\">"; it("should not clear an invalid value if clearOnBlur is false", function() { scope.input = { options: {clearOnBlur: false} }; var input = compileElement(inputHtmlClearOnBlur); scope.$apply("x = ''"); scope.$apply("mask = '(9) * A'"); input.val("9a").triggerHandler("input"); input.triggerHandler("blur"); expect(input.val()).toBe("(9) a _"); }); it("should clear an invalid value if clearOnBlur is true", function() { scope.input = { options: {clearOnBlur: true} }; var input = compileElement(inputHtmlClearOnBlur); scope.$apply("x = ''"); scope.$apply("mask = '(9) * A'"); input.val("9a").triggerHandler("input"); input.triggerHandler("blur"); expect(input.val()).toBe(""); }); }); });
'use strict'; const common = require('../common'); if (!common.hasCrypto) common.skip('missing crypto'); const tls = require('tls'); const stream = require('stream'); const delay = new stream.Duplex({ read: function read() { }, write: function write(data, enc, cb) { console.log('pending'); setImmediate(function() { console.log('done'); cb(); }); } }); const secure = tls.connect({ socket: delay }); setImmediate(function() { secure.destroy(); });
/* This file is part of Ext JS 4.2 Copyright (c) 2011-2013 Sencha Inc Contact: http://www.sencha.com/contact Commercial Usage Licensees holding valid commercial licenses may use this file in accordance with the Commercial Software License Agreement provided with the Software or, alternatively, in accordance with the terms contained in a written agreement between you and Sencha. If you are unsure which license is appropriate for your use, please contact the sales department at http://www.sencha.com/contact. Build date: 2013-09-18 17:18:59 (940c324ac822b840618a3a8b2b4b873f83a1a9b1) */ /** * Represents a 2D point with x and y properties, useful for comparison and instantiation * from an event: * * var point = Ext.util.Point.fromEvent(e); * */ Ext.define('Ext.util.Point', { /* Begin Definitions */ extend: 'Ext.util.Region', statics: { /** * Returns a new instance of Ext.util.Point base on the pageX / pageY values of the given event * @static * @param {Ext.EventObject/Event} e The event * @return {Ext.util.Point} */ fromEvent: function(e) { e = e.browserEvent || e; e = (e.changedTouches && e.changedTouches.length > 0) ? e.changedTouches[0] : e; return new this(e.pageX, e.pageY); } }, /* End Definitions */ /** * Creates a point from two coordinates. * @param {Number} x X coordinate. * @param {Number} y Y coordinate. */ constructor: function(x, y) { this.callParent([y, x, y, x]); }, /** * Returns a human-eye-friendly string that represents this point, * useful for debugging * @return {String} */ toString: function() { return "Point[" + this.x + "," + this.y + "]"; }, /** * Compare this point and another point * @param {Ext.util.Point/Object} p The point to compare with, either an instance * of Ext.util.Point or an object with left and top properties * @return {Boolean} Returns whether they are equivalent */ equals: function(p) { return (this.x == p.x && this.y == p.y); }, /** * Whether the given point is not away from this point within the given threshold amount. * @param {Ext.util.Point/Object} p The point to check with, either an instance * of Ext.util.Point or an object with left and top properties * @param {Object/Number} threshold Can be either an object with x and y properties or a number * @return {Boolean} */ isWithin: function(p, threshold) { if (!Ext.isObject(threshold)) { threshold = { x: threshold, y: threshold }; } return (this.x <= p.x + threshold.x && this.x >= p.x - threshold.x && this.y <= p.y + threshold.y && this.y >= p.y - threshold.y); }, /** * Determins whether this Point contained by the passed Region, Component or element. * @param {Ext.util.Region/Ext.Component/Ext.dom.Element/HTMLElement} region * The rectangle to check that this Point is within. * @return {Boolean} */ isContainedBy: function(region) { if (!(region instanceof Ext.util.Region)) { region = Ext.get(region.el || region).getRegion(); } return region.contains(this); }, /** * Compare this point with another point when the x and y values of both points are rounded. E.g: * [100.3,199.8] will equals to [100, 200] * @param {Ext.util.Point/Object} p The point to compare with, either an instance * of Ext.util.Point or an object with x and y properties * @return {Boolean} */ roundedEquals: function(p) { return (Math.round(this.x) == Math.round(p.x) && Math.round(this.y) == Math.round(p.y)); } }, function() { /** * @method * Alias for {@link #translateBy} * @inheritdoc Ext.util.Region#translateBy */ this.prototype.translate = Ext.util.Region.prototype.translateBy; });
describe('abide:', function() { beforeEach(function() { this.addMatchers({ // Place abide-specific matchers here... }); var origFunc = $.fn.foundation; spyOn($.fn, 'foundation').andCallFake(function() { var result = origFunc.apply(this, arguments); jasmine.Clock.tick(1000); // Let things settle... return result; }); }); describe('basic validation', function() { beforeEach(function() { document.body.innerHTML = __html__['spec/abide/basic.html']; }); it('should not mark fields as invalid on load', function() { $(document).foundation(); expect($('input[name="user_name"]')).not.toHaveData('invalid'); expect($('input[name="user_email"]')).not.toHaveData('invalid'); }); it('should trigger correct events for all required fields', function() { $(document).foundation(); var settings = Foundation.libs.abide.settings; spyOnEvent('form', 'invalid'); spyOnEvent('form', 'valid'); spyOnEvent('input[name="user_name"]', 'invalid'); spyOnEvent('input[name="user_name"]', 'valid'); spyOnEvent('input[name="user_email"]', 'invalid'); spyOnEvent('input[name="user_email"]', 'valid'); $('form').submit(); expect('valid').not.toHaveBeenTriggeredOn('form'); expect('valid').not.toHaveBeenTriggeredOn('input[name="user_name"]'); expect('valid').not.toHaveBeenTriggeredOn('input[name="user_email"]'); expect('invalid').toHaveBeenTriggeredOn('form'); expect('invalid').toHaveBeenTriggeredOn('input[name="user_name"]'); expect('invalid').toHaveBeenTriggeredOn('input[name="user_email"]'); }); it('should mark missing required fields as invalid', function() { $(document).foundation(); expect($('input[name="user_name"]')).not.toHaveData('invalid'); expect($('input[name="user_email"]')).not.toHaveData('invalid'); $('form').submit(); var invalid_fields = $('form').find('[data-invalid]'); expect(invalid_fields.length).toBe(2); expect($('input[name="user_name"]')).toHaveData('invalid'); expect($('input[name="user_email"]')).toHaveData('invalid'); }); it('should pass validation when all fields are filled out correctly', function() { $(document).foundation(); spyOnEvent('form', 'invalid'); spyOnEvent('form', 'valid'); spyOnEvent('input[name="user_name"]', 'invalid'); spyOnEvent('input[name="user_name"]', 'valid'); spyOnEvent('input[name="user_email"]', 'invalid'); spyOnEvent('input[name="user_email"]', 'valid'); $('input[name="user_name"]').val('John'); $('input[name="user_email"]').val('foo@bar.com'); $('form').submit(); expect('valid').toHaveBeenTriggeredOn('form'); expect('valid').toHaveBeenTriggeredOn('input[name="user_name"]'); expect('valid').toHaveBeenTriggeredOn('input[name="user_email"]'); expect('invalid').not.toHaveBeenTriggeredOn('form'); expect('invalid').not.toHaveBeenTriggeredOn('input[name="user_name"]'); expect('invalid').not.toHaveBeenTriggeredOn('input[name="user_email"]'); }); it('should not validate on blur or change events when validate_on_blur is false', function() { $(document).foundation({ abide: { validate_on_blur: false } }); $('input[name="user_name"]').blur(); expect($('input[name="user_name"]')).not.toHaveData('invalid'); }); }); describe('advanced validation', function() { beforeEach(function() { document.body.innerHTML = __html__['spec/abide/advanced.html']; }); it('should support builtin equalTo validator', function() { $(document).foundation({ abide: { validators: { range: function(){ return true; } } } }); expect($('input[name="user_password"]')).not.toHaveAttr('data-invalid'); expect($('input[name="user_password_confirmation"]')).not.toHaveAttr('data-invalid'); $('input[name="user_password"]').val("foobarbaz"); // now they're not equal $('form').submit(); var invalid_fields = $('form').find('[data-invalid]'); expect(invalid_fields.length).toBe(1); expect($('input[name="user_password_confirmation"]')).toHaveAttr('data-invalid'); $('input[name="user_password_confirmation"]').val("foobarbaz"); // now they're equal spyOnEvent('form', 'invalid'); spyOnEvent('form', 'valid'); $('form').submit(); expect('valid').toHaveBeenTriggeredOn('form'); expect($('input[name="user_password"]')).not.toHaveAttr('data-invalid'); expect($('input[name="user_password_confirmation"]')).not.toHaveAttr('data-invalid'); }); it('should support custom validators', function() { $(document).foundation({ abide: { validators: { range: function(el, required, parent) { var start = parseInt(this.S("[name='user_start_num']").val()), end = parseInt(el.value); return start < end; } } } }); expect($('input[name="user_start_num"]')).not.toHaveData('invalid'); expect($('input[name="user_end_num"]')).not.toHaveData('invalid'); // invalid $('input[name="user_start_num"]').val("10"); $('input[name="user_end_num"]').val("2"); $('form').submit(); //var invalid_fields = $('form').find('[data-invalid]'); // includes other fields with validators //expect(invalid_fields.length).toBe(3); //expect($('input[name="user_end_num"]')).toHaveAttr('data-invalid'); expect($('input[name="user_start_num"]')).not.toHaveAttr('data-invalid'); expect($('input[name="user_end_num"]')).toHaveAttr('data-invalid'); // valid now $('input[name="user_end_num"]').val("12"); spyOnEvent('form', 'invalid'); spyOnEvent('form', 'valid'); $('form').submit(); expect('valid').toHaveBeenTriggeredOn('form'); expect($('input[name="user_start_num"]')).not.toHaveAttr('data-invalid'); expect($('input[name="user_end_num"]')).not.toHaveAttr('data-invalid'); }); }); });
/*global angular*/ "use strict"; var lookAroundApp = angular.module("lookAroundApp", [ "lookAroundApp.services", "lookAroundApp.controllers", "lookAroundApp.filters", "lookAroundApp.directives", "ui.bootstrap" ]); lookAroundApp.config(function ($routeProvider) { $routeProvider .when("/", { controller: "ZipCodeFrmCtrl", templateUrl: "partials/zipcode.html" }) .when("/search/:zipcode/:place", { controller: "SearchCtrl", templateUrl: "partials/search.html" }) .otherwise({ redirectTo: "/" }); });
version https://git-lfs.github.com/spec/v1 oid sha256:8b9c0dee70ba4f792284eb0d9cf2f76ea7a528452581d0c4c5e321c401d4c6c3 size 22604
var faker = require('faker'); var props = require('json-api-mock-server/lib/store/props'); var attr = props.attr; var many = props.many; var one = props.one; var between = require('json-api-mock-server/lib/utils/between'); module.exports = { name: attr('string', { defaultValue: function() { return faker.lorem.words(between(3, 7)); }}), description: attr('string', { defaultValue: function() { return faker.lorem.sentences(between(3, 7)); }}), baz: one('baz', { inverse: 'complex', defaultValue: true }), foos: many('foo', { inverse: 'complex', defaultValue: 5 }) };
/* Shorthand */ "use strict"; function __export(m) { for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; } Object.defineProperty(exports, "__esModule", { value: true }); __export(require("./components/messages/messages"));
'use strict'; var React = require('react/addons'); var PureRenderMixin = React.addons.PureRenderMixin; var SvgIcon = require('../../svg-icon'); var DeviceBrightnessHigh = React.createClass({ displayName: 'DeviceBrightnessHigh', mixins: [PureRenderMixin], render: function render() { return React.createElement( SvgIcon, this.props, React.createElement('path', { d: 'M20 8.69V4h-4.69L12 .69 8.69 4H4v4.69L.69 12 4 15.31V20h4.69L12 23.31 15.31 20H20v-4.69L23.31 12 20 8.69zM12 18c-3.31 0-6-2.69-6-6s2.69-6 6-6 6 2.69 6 6-2.69 6-6 6zm0-10c-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4z' }) ); } }); module.exports = DeviceBrightnessHigh;
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _react = require('react'); exports['default'] = _react.PropTypes.oneOfType([ // [Number, Number] _react.PropTypes.arrayOf(_react.PropTypes.number), // {lat: Number, lng: Number} _react.PropTypes.shape({ lat: _react.PropTypes.number, lng: _react.PropTypes.number }), // {lat: Number, lon: Number} _react.PropTypes.shape({ lat: _react.PropTypes.number, lon: _react.PropTypes.number })]); module.exports = exports['default'];
'use strict'; angular.module('copayApp.controllers').controller('glideraController', function($scope, $timeout, $ionicModal, $log, storageService, glideraService, ongoingProcess, platformInfo, externalLinkService, popupService, lodash) { $scope.openExternalLink = function(url) { externalLinkService.open(url); }; var init = function() { ongoingProcess.set('connectingGlidera', true); glideraService.init(function(err, data) { ongoingProcess.set('connectingGlidera', false); if (err) { popupService.showAlert('Error connecting Glidera', err + '. Please re-connect to Glidera'); return; } if (!data || (data && !data.token)) return; $scope.account['token'] = data.token; $scope.account['status'] = data.status; $scope.account['txs'] = data.txs; $timeout(function() { $scope.$digest(); $scope.update(); }); }); }; $scope.update = function(opts) { $log.debug('Updating Glidera...'); glideraService.updateStatus($scope.account); }; $scope.getAuthenticateUrl = function() { return glideraService.getOauthCodeUrl(); }; $scope.submitOauthCode = function(code) { ongoingProcess.set('connectingGlidera', true); glideraService.authorize(code, function(err, data) { ongoingProcess.set('connectingGlidera', false); if (err) { popupService.showAlert('Authorisation error', err); return; } $scope.account['token'] = data.token; $scope.account['status'] = data.status; init(); }); }; $scope.openTxModal = function(tx) { $scope.tx = tx; glideraService.getTransaction($scope.account.token, tx.transactionUuid, function(err, tx) { if (err) { popupService.showAlert('Error getting transaction', 'Could not get transactions'); return; } $scope.tx = tx; }); $ionicModal.fromTemplateUrl('views/modals/glidera-tx-details.html', { scope: $scope, backdropClickToClose: false, hardwareBackButtonClose: false, animation: 'slide-in-up' }).then(function(modal) { $scope.glideraTxDetailsModal = modal; $scope.glideraTxDetailsModal.show(); }); }; $scope.openAuthenticateWindow = function() { $scope.openExternalLink($scope.getAuthenticateUrl()); $scope.showOauthForm = true } $scope.openLoginWindow = function() { var glideraUrl = ($scope.network === 'testnet') ? 'https://sandbox.glidera.io/login' : 'https://glidera.io/login'; $scope.openExternalLink(glideraUrl); } $scope.openSupportWindow = function() { var url = glideraService.getSupportUrl(); var optIn = true; var title = 'Glidera Support'; var message = 'You can email glidera at support@glidera.io for direct support, or you can contact Glidera on Twitter.'; var okText = 'Tweet @GlideraInc'; var cancelText = 'Go Back'; externalLinkService.open(url, optIn, title, message, okText, cancelText); } $scope.toggleOauthForm = function() { $scope.showOauthForm = !$scope.showOauthForm; } $scope.$on("$ionicView.afterEnter", function(event, data) { $scope.network = glideraService.getNetwork(); $scope.currency = glideraService.getCurrency(); $scope.showOauthForm = false; $scope.account = {}; if (data.stateParams && data.stateParams.code) { $scope.submitOauthCode(data.stateParams.code); } else { init(); } }); });
module.exports = { pkcs1: require('./pkcs1'), pkcs1_oaep: require('./oaep'), pss: require('./pss'), /** * Check if scheme has padding methods * @param scheme {string} * @returns {Boolean} */ isEncryption: function (scheme) { return module.exports[scheme] && module.exports[scheme].isEncryption; }, /** * Check if scheme has sign/verify methods * @param scheme {string} * @returns {Boolean} */ isSignature: function (scheme) { return module.exports[scheme] && module.exports[scheme].isSignature; } };
import { Injectable } from '@angular/core'; /** * Configuration service for the NgbCarousel component. * You can inject this service, typically in your root component, and customize the values of its properties in * order to provide default values for all the carousels used in the application. */ export var NgbCarouselConfig = (function () { function NgbCarouselConfig() { this.interval = 5000; this.wrap = true; this.keyboard = true; } NgbCarouselConfig.decorators = [ { type: Injectable }, ]; /** @nocollapse */ NgbCarouselConfig.ctorParameters = function () { return []; }; return NgbCarouselConfig; }()); //# sourceMappingURL=carousel-config.js.map