text
stringlengths
2
1.05M
var assert = module.exports = require('assert'); assert.isClient = function (client) { assert.isObject(client); !client.apiKey || assert.match(client.auth(), /^Basic .+$/); !client.token || assert.match(client.auth(), /^Bearer .+$/); } assert.isUser = function (user) { assert.isObject(user); assert.include(user, 'id'); assert.include(user, 'name'); assert.include(user, 'email'); assert.isArray(user.workspaces); }; assert.hasNameAndId = function (obj) { if (Array.isArray(obj)) { return obj.forEach(function (item) { assert.hasNameAndId(item); }); } assert.isObject(obj); assert.include(obj, 'id'); assert.include(obj, 'name'); }; assert.isTask = function (task) { assert.isNumber(task.id); assert.isArray(task.tags); assert.isString(task.created_at); assert.isString(task.modified_at); assert.isString(task.name); assert.isString(task.notes); assert.isBoolean(task.completed); assert.isString(task.assignee_status); assert.isArray(task.projects); assert.isObject(task.workspace); assert.isArray(task.followers); !task.due_on || assert.isString(task.due_on) }; assert.isTag = function (tag) { assert.isNumber(tag.id); assert.isString(tag.name); assert.isString(tag.notes); assert.isString(tag.created_at); assert.isArray(tag.followers); assert.isObject(tag.workspace); };
(window["webpackJsonp"]=window["webpackJsonp"]||[]).push([["chunk-2d6bf53a"],{"057f":function(t,r,n){var e=n("fc6a"),i=n("241c").f,o={}.toString,c="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[],a=function(t){try{return i(t)}catch(r){return c.slice()}};t.exports.f=function(t){return c&&"[object Window]"==o.call(t)?a(t):i(e(t))}},"1dde":function(t,r,n){var e=n("d039"),i=n("b622"),o=n("2d00"),c=i("species");t.exports=function(t){return o>=51||!e((function(){var r=[],n=r.constructor={};return n[c]=function(){return{foo:1}},1!==r[t](Boolean).foo}))}},"25f0":function(t,r,n){"use strict";var e=n("6eeb"),i=n("825a"),o=n("d039"),c=n("ad6d"),a="toString",f=RegExp.prototype,u=f[a],s=o((function(){return"/a/b"!=u.call({source:"a",flags:"b"})})),l=u.name!=a;(s||l)&&e(RegExp.prototype,a,(function(){var t=i(this),r=String(t.source),n=t.flags,e=String(void 0===n&&t instanceof RegExp&&!("flags"in f)?c.call(t):n);return"/"+r+"/"+e}),{unsafe:!0})},"3ca3":function(t,r,n){"use strict";var e=n("6547").charAt,i=n("69f3"),o=n("7dd0"),c="String Iterator",a=i.set,f=i.getterFor(c);o(String,"String",(function(t){a(this,{type:c,string:String(t),index:0})}),(function(){var t,r=f(this),n=r.string,i=r.index;return i>=n.length?{value:void 0,done:!0}:(t=e(n,i),r.index+=t.length,{value:t,done:!1})}))},"4df4":function(t,r,n){"use strict";var e=n("0366"),i=n("7b0b"),o=n("9bdd"),c=n("e95a"),a=n("50c4"),f=n("8418"),u=n("35a1");t.exports=function(t){var r,n,s,l,d,v,b=i(t),p="function"==typeof this?this:Array,y=arguments.length,g=y>1?arguments[1]:void 0,h=void 0!==g,S=u(b),m=0;if(h&&(g=e(g,y>2?arguments[2]:void 0,2)),void 0==S||p==Array&&c(S))for(r=a(b.length),n=new p(r);r>m;m++)v=h?g(b[m],m):b[m],f(n,m,v);else for(l=S.call(b),d=l.next,n=new p;!(s=d.call(l)).done;m++)v=h?o(l,g,[s.value,m],!0):s.value,f(n,m,v);return n.length=m,n}},6547:function(t,r,n){var e=n("a691"),i=n("1d80"),o=function(t){return function(r,n){var o,c,a=String(i(r)),f=e(n),u=a.length;return f<0||f>=u?t?"":void 0:(o=a.charCodeAt(f),o<55296||o>56319||f+1===u||(c=a.charCodeAt(f+1))<56320||c>57343?t?a.charAt(f):o:t?a.slice(f,f+2):c-56320+(o-55296<<10)+65536)}};t.exports={codeAt:o(!1),charAt:o(!0)}},"65f0":function(t,r,n){var e=n("861d"),i=n("e8b5"),o=n("b622"),c=o("species");t.exports=function(t,r){var n;return i(t)&&(n=t.constructor,"function"!=typeof n||n!==Array&&!i(n.prototype)?e(n)&&(n=n[c],null===n&&(n=void 0)):n=void 0),new(void 0===n?Array:n)(0===r?0:r)}},"746f":function(t,r,n){var e=n("428f"),i=n("5135"),o=n("e5383"),c=n("9bf2").f;t.exports=function(t){var r=e.Symbol||(e.Symbol={});i(r,t)||c(r,t,{value:o.f(t)})}},8418:function(t,r,n){"use strict";var e=n("c04e"),i=n("9bf2"),o=n("5c6c");t.exports=function(t,r,n){var c=e(r);c in t?i.f(t,c,o(0,n)):t[c]=n}},a4d3:function(t,r,n){"use strict";var e=n("23e7"),i=n("da84"),o=n("d066"),c=n("c430"),a=n("83ab"),f=n("4930"),u=n("fdbf"),s=n("d039"),l=n("5135"),d=n("e8b5"),v=n("861d"),b=n("825a"),p=n("7b0b"),y=n("fc6a"),g=n("c04e"),h=n("5c6c"),S=n("7c73"),m=n("df75"),w=n("241c"),A=n("057f"),O=n("7418"),L=n("06cf"),x=n("9bf2"),C=n("d1e7"),T=n("9112"),j=n("6eeb"),P=n("5692"),E=n("f772"),M=n("d012"),R=n("90e3"),k=n("b622"),N=n("e5383"),I=n("746f"),V=n("d44e"),D=n("69f3"),F=n("b727").forEach,G=E("hidden"),H="Symbol",J="prototype",$=k("toPrimitive"),B=D.set,q=D.getterFor(H),Q=Object[J],U=i.Symbol,W=o("JSON","stringify"),z=L.f,K=x.f,X=A.f,Y=C.f,Z=P("symbols"),_=P("op-symbols"),tt=P("string-to-symbol-registry"),rt=P("symbol-to-string-registry"),nt=P("wks"),et=i.QObject,it=!et||!et[J]||!et[J].findChild,ot=a&&s((function(){return 7!=S(K({},"a",{get:function(){return K(this,"a",{value:7}).a}})).a}))?function(t,r,n){var e=z(Q,r);e&&delete Q[r],K(t,r,n),e&&t!==Q&&K(Q,r,e)}:K,ct=function(t,r){var n=Z[t]=S(U[J]);return B(n,{type:H,tag:t,description:r}),a||(n.description=r),n},at=u?function(t){return"symbol"==typeof t}:function(t){return Object(t)instanceof U},ft=function(t,r,n){t===Q&&ft(_,r,n),b(t);var e=g(r,!0);return b(n),l(Z,e)?(n.enumerable?(l(t,G)&&t[G][e]&&(t[G][e]=!1),n=S(n,{enumerable:h(0,!1)})):(l(t,G)||K(t,G,h(1,{})),t[G][e]=!0),ot(t,e,n)):K(t,e,n)},ut=function(t,r){b(t);var n=y(r),e=m(n).concat(bt(n));return F(e,(function(r){a&&!lt.call(n,r)||ft(t,r,n[r])})),t},st=function(t,r){return void 0===r?S(t):ut(S(t),r)},lt=function(t){var r=g(t,!0),n=Y.call(this,r);return!(this===Q&&l(Z,r)&&!l(_,r))&&(!(n||!l(this,r)||!l(Z,r)||l(this,G)&&this[G][r])||n)},dt=function(t,r){var n=y(t),e=g(r,!0);if(n!==Q||!l(Z,e)||l(_,e)){var i=z(n,e);return!i||!l(Z,e)||l(n,G)&&n[G][e]||(i.enumerable=!0),i}},vt=function(t){var r=X(y(t)),n=[];return F(r,(function(t){l(Z,t)||l(M,t)||n.push(t)})),n},bt=function(t){var r=t===Q,n=X(r?_:y(t)),e=[];return F(n,(function(t){!l(Z,t)||r&&!l(Q,t)||e.push(Z[t])})),e};if(f||(U=function(){if(this instanceof U)throw TypeError("Symbol is not a constructor");var t=arguments.length&&void 0!==arguments[0]?String(arguments[0]):void 0,r=R(t),n=function(t){this===Q&&n.call(_,t),l(this,G)&&l(this[G],r)&&(this[G][r]=!1),ot(this,r,h(1,t))};return a&&it&&ot(Q,r,{configurable:!0,set:n}),ct(r,t)},j(U[J],"toString",(function(){return q(this).tag})),j(U,"withoutSetter",(function(t){return ct(R(t),t)})),C.f=lt,x.f=ft,L.f=dt,w.f=A.f=vt,O.f=bt,N.f=function(t){return ct(k(t),t)},a&&(K(U[J],"description",{configurable:!0,get:function(){return q(this).description}}),c||j(Q,"propertyIsEnumerable",lt,{unsafe:!0}))),e({global:!0,wrap:!0,forced:!f,sham:!f},{Symbol:U}),F(m(nt),(function(t){I(t)})),e({target:H,stat:!0,forced:!f},{for:function(t){var r=String(t);if(l(tt,r))return tt[r];var n=U(r);return tt[r]=n,rt[n]=r,n},keyFor:function(t){if(!at(t))throw TypeError(t+" is not a symbol");if(l(rt,t))return rt[t]},useSetter:function(){it=!0},useSimple:function(){it=!1}}),e({target:"Object",stat:!0,forced:!f,sham:!a},{create:st,defineProperty:ft,defineProperties:ut,getOwnPropertyDescriptor:dt}),e({target:"Object",stat:!0,forced:!f},{getOwnPropertyNames:vt,getOwnPropertySymbols:bt}),e({target:"Object",stat:!0,forced:s((function(){O.f(1)}))},{getOwnPropertySymbols:function(t){return O.f(p(t))}}),W){var pt=!f||s((function(){var t=U();return"[null]"!=W([t])||"{}"!=W({a:t})||"{}"!=W(Object(t))}));e({target:"JSON",stat:!0,forced:pt},{stringify:function(t,r,n){var e,i=[t],o=1;while(arguments.length>o)i.push(arguments[o++]);if(e=r,(v(r)||void 0!==t)&&!at(t))return d(r)||(r=function(t,r){if("function"==typeof e&&(r=e.call(this,t,r)),!at(r))return r}),i[1]=r,W.apply(null,i)}})}U[J][$]||T(U[J],$,U[J].valueOf),V(U,H),M[G]=!0},a630:function(t,r,n){var e=n("23e7"),i=n("4df4"),o=n("1c7e"),c=!o((function(t){Array.from(t)}));e({target:"Array",stat:!0,forced:c},{from:i})},ad6d:function(t,r,n){"use strict";var e=n("825a");t.exports=function(){var t=e(this),r="";return t.global&&(r+="g"),t.ignoreCase&&(r+="i"),t.multiline&&(r+="m"),t.dotAll&&(r+="s"),t.unicode&&(r+="u"),t.sticky&&(r+="y"),r}},ae40:function(t,r,n){var e=n("83ab"),i=n("d039"),o=n("5135"),c=Object.defineProperty,a={},f=function(t){throw t};t.exports=function(t,r){if(o(a,t))return a[t];r||(r={});var n=[][t],u=!!o(r,"ACCESSORS")&&r.ACCESSORS,s=o(r,0)?r[0]:f,l=o(r,1)?r[1]:void 0;return a[t]=!!n&&!i((function(){if(u&&!e)return!0;var t={length:-1};u?c(t,1,{enumerable:!0,get:f}):t[1]=1,n.call(t,s,l)}))}},b0c0:function(t,r,n){var e=n("83ab"),i=n("9bf2").f,o=Function.prototype,c=o.toString,a=/^\s*function ([^ (]*)/,f="name";e&&!(f in o)&&i(o,f,{configurable:!0,get:function(){try{return c.call(this).match(a)[1]}catch(t){return""}}})},b727:function(t,r,n){var e=n("0366"),i=n("44ad"),o=n("7b0b"),c=n("50c4"),a=n("65f0"),f=[].push,u=function(t){var r=1==t,n=2==t,u=3==t,s=4==t,l=6==t,d=5==t||l;return function(v,b,p,y){for(var g,h,S=o(v),m=i(S),w=e(b,p,3),A=c(m.length),O=0,L=y||a,x=r?L(v,A):n?L(v,0):void 0;A>O;O++)if((d||O in m)&&(g=m[O],h=w(g,O,S),t))if(r)x[O]=h;else if(h)switch(t){case 3:return!0;case 5:return g;case 6:return O;case 2:f.call(x,g)}else if(s)return!1;return l?-1:u||s?s:x}};t.exports={forEach:u(0),map:u(1),filter:u(2),some:u(3),every:u(4),find:u(5),findIndex:u(6)}},b85c:function(t,r,n){"use strict";n.d(r,"a",(function(){return o}));n("a4d3"),n("e01a"),n("d28b"),n("e260"),n("d3b7"),n("3ca3"),n("ddb0"),n("a630"),n("fb6a"),n("b0c0"),n("25f0");function e(t,r){(null==r||r>t.length)&&(r=t.length);for(var n=0,e=new Array(r);n<r;n++)e[n]=t[n];return e}function i(t,r){if(t){if("string"===typeof t)return e(t,r);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?e(t,r):void 0}}function o(t){if("undefined"===typeof Symbol||null==t[Symbol.iterator]){if(Array.isArray(t)||(t=i(t))){var r=0,n=function(){};return{s:n,n:function(){return r>=t.length?{done:!0}:{done:!1,value:t[r++]}},e:function(t){throw t},f:n}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var e,o,c=!0,a=!1;return{s:function(){e=t[Symbol.iterator]()},n:function(){var t=e.next();return c=t.done,t},e:function(t){a=!0,o=t},f:function(){try{c||null==e["return"]||e["return"]()}finally{if(a)throw o}}}}},d28b:function(t,r,n){var e=n("746f");e("iterator")},ddb0:function(t,r,n){var e=n("da84"),i=n("fdbc"),o=n("e260"),c=n("9112"),a=n("b622"),f=a("iterator"),u=a("toStringTag"),s=o.values;for(var l in i){var d=e[l],v=d&&d.prototype;if(v){if(v[f]!==s)try{c(v,f,s)}catch(p){v[f]=s}if(v[u]||c(v,u,l),i[l])for(var b in o)if(v[b]!==o[b])try{c(v,b,o[b])}catch(p){v[b]=o[b]}}}},e01a:function(t,r,n){"use strict";var e=n("23e7"),i=n("83ab"),o=n("da84"),c=n("5135"),a=n("861d"),f=n("9bf2").f,u=n("e893"),s=o.Symbol;if(i&&"function"==typeof s&&(!("description"in s.prototype)||void 0!==s().description)){var l={},d=function(){var t=arguments.length<1||void 0===arguments[0]?void 0:String(arguments[0]),r=this instanceof d?new s(t):void 0===t?s():s(t);return""===t&&(l[r]=!0),r};u(d,s);var v=d.prototype=s.prototype;v.constructor=d;var b=v.toString,p="Symbol(test)"==String(s("test")),y=/^Symbol\((.*)\)[^)]+$/;f(v,"description",{configurable:!0,get:function(){var t=a(this)?this.valueOf():this,r=b.call(t);if(c(l,t))return"";var n=p?r.slice(7,-1):r.replace(y,"$1");return""===n?void 0:n}}),e({global:!0,forced:!0},{Symbol:d})}},e5383:function(t,r,n){var e=n("b622");r.f=e},e8b5:function(t,r,n){var e=n("c6b6");t.exports=Array.isArray||function(t){return"Array"==e(t)}},fb6a:function(t,r,n){"use strict";var e=n("23e7"),i=n("861d"),o=n("e8b5"),c=n("23cb"),a=n("50c4"),f=n("fc6a"),u=n("8418"),s=n("b622"),l=n("1dde"),d=n("ae40"),v=l("slice"),b=d("slice",{ACCESSORS:!0,0:0,1:2}),p=s("species"),y=[].slice,g=Math.max;e({target:"Array",proto:!0,forced:!v||!b},{slice:function(t,r){var n,e,s,l=f(this),d=a(l.length),v=c(t,d),b=c(void 0===r?d:r,d);if(o(l)&&(n=l.constructor,"function"!=typeof n||n!==Array&&!o(n.prototype)?i(n)&&(n=n[p],null===n&&(n=void 0)):n=void 0,n===Array||void 0===n))return y.call(l,v,b);for(e=new(void 0===n?Array:n)(g(b-v,0)),s=0;v<b;v++,s++)v in l&&u(e,s,l[v]);return e.length=s,e}})},fdbc:function(t,r){t.exports={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0}}}]); //# sourceMappingURL=chunk-2d6bf53a.a2907c0c.js.map
class employee { constructor(firstName, lastName, roleID, managerID) { this.firstName = firstName; this.lastName = lastName; this.roleID = roleID; this.managerID = managerID; } } module.exports = employee;
const Joi = require('joi') const baseValidator = require('../../helper/validator.joi') const schema = Joi.object({ email: Joi .string() .email() .required() .label('E-mail'), password: Joi .string() .min(7) .max(100) .required() .label('Password'), first_name: Joi .string() .min(2) .max(100) .required() .label('First Name'), last_name: Joi .string() .min(2) .max(100) .required() .label('Last Name'), avatar_url: Joi .string() .uri() .label('Profile picture'), reg_ip: Joi .string() .ip() .default(Joi.ref('$ip')) .forbidden() }) module.exports = baseValidator.create(schema) module.exports.schema = schema
var sizes = { md5: 16, sha1: 20, sha224: 28, sha256: 32, sha384: 48, sha512: 64, rmd160: 20, ripemd160: 20 } var createHmac = require('create-hmac') var checkParameters = require('../lib/precondition') var defaultEncoding = require('../lib/default-encoding') var Buffer = require('safe-buffer').Buffer function pbkdf2 (password, salt, iterations, keylen, digest) { checkParameters(password, salt, iterations, keylen) if (!Buffer.isBuffer(password)) password = Buffer.from(password, defaultEncoding) if (!Buffer.isBuffer(salt)) salt = Buffer.from(salt, defaultEncoding) digest = digest || 'sha1' var DK = Buffer.allocUnsafe(keylen) var block1 = Buffer.allocUnsafe(salt.length + 4) salt.copy(block1, 0, 0, salt.length) var destPos = 0 var hLen = sizes[digest] var l = Math.ceil(keylen / hLen) for (var i = 1; i <= l; i++) { block1.writeUInt32BE(i, salt.length) var T = createHmac(digest, password).update(block1).digest() var U = T for (var j = 1; j < iterations; j++) { U = createHmac(digest, password).update(U).digest() for (var k = 0; k < hLen; k++) T[k] ^= U[k] } T.copy(DK, destPos) destPos += hLen } return DK } module.exports = pbkdf2
/* Implement a function called countUniqueValues which appects a sorted array, and counts the unique values in the array. There can be negative numbers in the array, but it will always be sorted. */ function countUniqueValues(arr) { let arrLength = arr.length; if (arrLength === 0) return 0; let i = 0; for (let j = 1; j < arrLength; j++) { if (arr[i] !== arr[j]) { i++; arr[i] = arr[j]; } } return i + 1; } console.log(countUniqueValues([1, 2, 3, 4, 4, 5, 5, 6, 7, 7, 8])); // -> 8 console.log(countUniqueValues([])); // -> 0
'use strict'; const _ = require('lodash'); const Model = require('../../').Model; const expect = require('expect.js'); const Promise = require('bluebird'); module.exports = session => { describe('Composite keys', () => { let A; let B; before(() => { return session.knex.schema .dropTableIfExists('A_B') .dropTableIfExists('A') .dropTableIfExists('B') .createTable('A', table => { table.integer('id1'); table.string('id2'); table.string('aval'); table.integer('bid3'); table.string('bid4'); table.primary(['id1', 'id2']); }) .createTable('B', table => { table.integer('id3'); table.string('id4'); table.string('bval'); table.primary(['id3', 'id4']); }) .createTable('A_B', table => { table.integer('aid1'); table.string('aid2'); table.integer('bid3'); table.string('bid4'); }); }); after(() => { return session.knex.schema .dropTableIfExists('A_B') .dropTableIfExists('A') .dropTableIfExists('B'); }); before(() => { class ModelA extends Model { static get tableName() { return 'A'; } static get idColumn() { return ['id1', 'id2']; } static get relationMappings() { return { b: { relation: Model.BelongsToOneRelation, modelClass: ModelB, join: { from: ['A.bid3', 'A.bid4'], to: ['B.id3', 'B.id4'] } }, ba: { relation: Model.ManyToManyRelation, modelClass: ModelB, join: { from: ['A.id1', 'A.id2'], through: { from: ['A_B.aid1', 'A_B.aid2'], to: ['A_B.bid3', 'A_B.bid4'] }, to: ['B.id3', 'B.id4'] } } }; } } class ModelB extends Model { static get tableName() { return 'B'; } static get idColumn() { return ['id3', 'id4']; } static get relationMappings() { return { a: { relation: Model.HasManyRelation, modelClass: ModelA, join: { from: ['B.id3', 'B.id4'], to: ['A.bid3', 'A.bid4'] } }, ab: { relation: Model.ManyToManyRelation, modelClass: ModelA, join: { from: ['B.id3', 'B.id4'], through: { from: ['A_B.bid3', 'A_B.bid4'], to: ['A_B.aid1', 'A_B.aid2'] }, to: ['A.id1', 'A.id2'] } } }; } } A = ModelA.bindKnex(session.knex); B = ModelB.bindKnex(session.knex); }); describe('insert', () => { afterEach(() => { return session.knex('A').delete(); }); it('should insert a model', () => { return A.query() .insert({id1: 1, id2: '1', aval: 'a'}) .then(ret => { expect(ret).to.eql({id1: 1, id2: '1', aval: 'a'}); return A.query().insertAndFetch({id1: 1, id2: '2', aval: 'b'}); }) .then(ret => { expect(ret.$toJson()).to.eql({id1: 1, id2: '2', aval: 'b', bid3: null, bid4: null}); return session.knex('A').orderBy('id2'); }) .then(rows => { expect(rows).to.eql([ {id1: 1, id2: '1', aval: 'a', bid3: null, bid4: null}, {id1: 1, id2: '2', aval: 'b', bid3: null, bid4: null} ]); }); }); it('insert should fail (unique violation)', done => { A.query() .insert({id1: 1, id2: '1', aval: 'a'}) .then(() => { return A.query().insert({id1: 1, id2: '1', aval: 'b'}); }) .then(() => { done(new Error('should not get here')); }) .catch(() => { done(); }); }); }); describe('find', () => { beforeEach(() => { return A.query().insertWithRelated([ {id1: 1, id2: '1', aval: 'a'}, {id1: 1, id2: '2', aval: 'b'}, {id1: 2, id2: '2', aval: 'c'}, {id1: 2, id2: '3', aval: 'd'}, {id1: 3, id2: '3', aval: 'e'} ]); }); afterEach(() => { return session.knex('A').delete(); }); it('findById should fetch one model by composite id', () => { return A.query() .findById([2, '2']) .then(model => { expect(model.toJSON()).to.eql({id1: 2, id2: '2', aval: 'c', bid3: null, bid4: null}); }); }); it('findByIds should fetch two models by composite ids', () => { return A.query() .findByIds([[1, '1'], [2, '2']]) .then(models => { expect(models).to.eql([ {id1: 1, id2: '1', aval: 'a', bid3: null, bid4: null}, {id1: 2, id2: '2', aval: 'c', bid3: null, bid4: null} ]); }); }); it('whereComposite should fetch one model by composite id', () => { return A.query() .whereComposite(['id1', 'id2'], [2, '2']) .first() .then(model => { expect(model.toJSON()).to.eql({id1: 2, id2: '2', aval: 'c', bid3: null, bid4: null}); }); }); it('whereInComposite should fetch multiple models by composite id', () => { return A.query() .whereInComposite(['id1', 'id2'], [[1, '2'], [2, '3'], [3, '3']]) .orderBy(['id1', 'id2']) .then(models => { expect(models).to.eql([ {id1: 1, id2: '2', aval: 'b', bid3: null, bid4: null}, {id1: 2, id2: '3', aval: 'd', bid3: null, bid4: null}, {id1: 3, id2: '3', aval: 'e', bid3: null, bid4: null} ]); }); }); it('whereNotInComposite should fetch multiple models by composite id', () => { return A.query() .whereNotInComposite(['id1', 'id2'], [[1, '2'], [2, '3'], [3, '3']]) .orderBy(['id1', 'id2']) .then(models => { expect(models).to.eql([ {id1: 1, id2: '1', aval: 'a', bid3: null, bid4: null}, {id1: 2, id2: '2', aval: 'c', bid3: null, bid4: null} ]); }); }); }); describe('update', () => { beforeEach(() => { return A.query().insertWithRelated([ {id1: 1, id2: '1', aval: 'a'}, {id1: 1, id2: '2', aval: 'b'}, {id1: 2, id2: '2', aval: 'c'}, {id1: 2, id2: '3', aval: 'd'}, {id1: 3, id2: '3', aval: 'e'} ]); }); afterEach(() => { return session.knex('A').delete(); }); it('updateAndFetchById should accept a composite id', () => { return A.query() .updateAndFetchById([1, '2'], {aval: 'updated'}) .orderBy(['id1', 'id2']) .then(model => { expect(model).to.eql({id1: 1, id2: '2', aval: 'updated', bid3: null, bid4: null}); return session.knex('A').orderBy(['id1', 'id2']); }) .then(rows => { expect(rows).to.eql([ {id1: 1, id2: '1', aval: 'a', bid3: null, bid4: null}, {id1: 1, id2: '2', aval: 'updated', bid3: null, bid4: null}, {id1: 2, id2: '2', aval: 'c', bid3: null, bid4: null}, {id1: 2, id2: '3', aval: 'd', bid3: null, bid4: null}, {id1: 3, id2: '3', aval: 'e', bid3: null, bid4: null} ]); }); }); }); describe('upsertGraph', () => { beforeEach(() => { return A.query().insertGraph({ id1: 1, id2: '1', aval: 'val1', b: { id3: 1, id4: '1', bval: 'val2', a: [ { id1: 1, id2: '2', aval: 'val3' }, { id1: 2, id2: '2', aval: 'val4' } ] }, ba: [ { id3: 2, id4: '1', bval: 'val5' }, { id3: 2, id4: '2', bval: 'val6' } ] }); }); afterEach(() => { return Promise.all([ session.knex('A').delete(), session.knex('B').delete(), session.knex('A_B').delete() ]); }); it('should work when `insertMissing` option is true', () => { return A.query() .upsertGraph( { // update id1: 1, id2: '1', aval: 'x', b: { // update id3: 1, id4: '1', bval: 'z', // [2, '2'] is deleted a: [ { // This is the root. Note that a is simply b in reverse. // We need to mention the root here so that is doesn't // get deleted. id1: 1, id2: '1' }, { // update id1: 1, id2: '2', aval: 'w' }, { // insert id1: 400, id2: '600', aval: 'new a' } ] }, // [2, '2'] is deleted ba: [ { // update id3: 2, id4: '1', bval: 'y' }, { // insert id3: 200, id4: '300', bval: 'new b' } ] }, {insertMissing: true} ) .then(() => { return A.query() .findById([1, '1']) .eager('[b.a, ba]') .modifyEager('b.a', qb => qb.orderBy(['id1', 'id2'])) .modifyEager('ba', qb => qb.orderBy(['id3', 'id4'])); }) .then(model => { expect(model).to.eql({ id1: 1, id2: '1', aval: 'x', bid3: 1, bid4: '1', b: { id3: 1, id4: '1', bval: 'z', a: [ { id1: 1, id2: '1', aval: 'x', bid3: 1, bid4: '1' }, { id1: 1, id2: '2', bid3: 1, bid4: '1', aval: 'w' }, { id1: 400, id2: '600', bid3: 1, bid4: '1', aval: 'new a' } ] }, ba: [ { id3: 2, id4: '1', bval: 'y' }, { id3: 200, id4: '300', bval: 'new b' } ] }); return Promise.all([ session.knex('A').orderBy(['id1', 'id2']), session.knex('B').orderBy(['id3', 'id4']) ]); }) .spread((a, b) => { expect(a).to.eql([ {id1: 1, id2: '1', aval: 'x', bid3: 1, bid4: '1'}, {id1: 1, id2: '2', aval: 'w', bid3: 1, bid4: '1'}, {id1: 400, id2: '600', aval: 'new a', bid3: 1, bid4: '1'} ]); expect(b).to.eql([ {id3: 1, id4: '1', bval: 'z'}, {id3: 2, id4: '1', bval: 'y'}, {id3: 200, id4: '300', bval: 'new b'} ]); }); }); it('should insert if partial id is given', () => { const upsert = A.fromJson({ id1: 1, id2: '1', aval: 'aUpdated', ba: [ { id3: 2, id4: '1', bval: 'bUpdated' }, { id4: '3', bval: 'bNew' } ] }); // Add the other key just before it is actually inserted // so that we don't insert a row with null id. upsert.ba[1].$beforeInsert = function() { this.id3 = 2; }; return A.query() .upsertGraph(upsert) .then(model => { return A.query() .findById([1, '1']) .eager('ba') .modifyEager('ba', qb => qb.orderBy(['id3', 'id4'])); }) .then(model => { expect(model).to.eql({ id1: 1, id2: '1', aval: 'aUpdated', bid3: 1, bid4: '1', ba: [ { id3: 2, id4: '1', bval: 'bUpdated' }, { id3: 2, id4: '3', bval: 'bNew' } ] }); }); }); }); describe('delete', () => { beforeEach(() => { return A.query().insertWithRelated([ {id1: 1, id2: '1', aval: 'a'}, {id1: 1, id2: '2', aval: 'b'}, {id1: 2, id2: '2', aval: 'c'}, {id1: 2, id2: '3', aval: 'd'}, {id1: 3, id2: '3', aval: 'e'} ]); }); afterEach(() => { return session.knex('A').delete(); }); it('deleteById should accept a composite id', () => { return A.query() .deleteById([1, '2']) .orderBy(['id1', 'id2']) .then(count => { expect(count).to.eql(1); return session.knex('A').orderBy(['id1', 'id2']); }) .then(rows => { expect(rows).to.eql([ {id1: 1, id2: '1', aval: 'a', bid3: null, bid4: null}, {id1: 2, id2: '2', aval: 'c', bid3: null, bid4: null}, {id1: 2, id2: '3', aval: 'd', bid3: null, bid4: null}, {id1: 3, id2: '3', aval: 'e', bid3: null, bid4: null} ]); }); }); }); describe('relations', () => { beforeEach(() => { return B.query().insertWithRelated([ { id3: 1, id4: '1', bval: 'b1', a: [ {id1: 1, id2: '1', aval: 'a1', '#id': 'a1'}, {id1: 1, id2: '2', aval: 'a2'}, {id1: 2, id2: '1', aval: 'a3'} ], ab: [ {id1: 11, id2: '11', aval: 'a7', '#id': 'a7'}, {id1: 11, id2: '12', aval: 'a8'}, {id1: 12, id2: '11', aval: 'a9'} ] }, { id3: 1, id4: '2', bval: 'b2', a: [ {id1: 2, id2: '2', aval: 'a4'}, {id1: 2, id2: '3', aval: 'a5'}, {id1: 3, id2: '2', aval: 'a6'} ], ab: [ {'#ref': 'a1'}, {'#ref': 'a7'}, {id1: 21, id2: '21', aval: 'a10'}, {id1: 21, id2: '22', aval: 'a11'}, {id1: 22, id2: '21', aval: 'a12'} ] } ]); }); afterEach(() => { return Promise.all([ session.knex('A').delete(), session.knex('B').delete(), session.knex('A_B').delete() ]); }); describe('eager fetch', () => { [ { eagerAlgo: Model.WhereInEagerAlgorithm, name: 'WhereInEagerAlgorithm' }, { eagerAlgo: Model.JoinEagerAlgorithm, name: 'JoinEagerAlgorithm' } ].map(eager => { it('basic ' + eager.name, () => { return B.query() .eagerAlgorithm(eager.eagerAlgo) .eager('[a(oa).b(ob), ab(oa)]', { oa: builder => { builder.orderBy(['id1', 'id2']); }, ob: builder => { builder.orderBy(['id3', 'id4']); } }) .then(models => { models = _.sortBy(models, ['id3', 'id4']); models.forEach(it => { it.a = _.sortBy(it.a, ['id1', 'id2']); }); models.forEach(it => { it.ab = _.sortBy(it.ab, ['id1', 'id2']); }); expect(models).to.eql([ { id3: 1, id4: '1', bval: 'b1', a: [ { id1: 1, id2: '1', aval: 'a1', bid3: 1, bid4: '1', b: {id3: 1, id4: '1', bval: 'b1'} }, { id1: 1, id2: '2', aval: 'a2', bid3: 1, bid4: '1', b: {id3: 1, id4: '1', bval: 'b1'} }, { id1: 2, id2: '1', aval: 'a3', bid3: 1, bid4: '1', b: {id3: 1, id4: '1', bval: 'b1'} } ], ab: [ {id1: 11, id2: '11', aval: 'a7', bid3: null, bid4: null}, {id1: 11, id2: '12', aval: 'a8', bid3: null, bid4: null}, {id1: 12, id2: '11', aval: 'a9', bid3: null, bid4: null} ] }, { id3: 1, id4: '2', bval: 'b2', a: [ { id1: 2, id2: '2', aval: 'a4', bid3: 1, bid4: '2', b: {id3: 1, id4: '2', bval: 'b2'} }, { id1: 2, id2: '3', aval: 'a5', bid3: 1, bid4: '2', b: {id3: 1, id4: '2', bval: 'b2'} }, { id1: 3, id2: '2', aval: 'a6', bid3: 1, bid4: '2', b: {id3: 1, id4: '2', bval: 'b2'} } ], ab: [ {id1: 1, id2: '1', aval: 'a1', bid3: 1, bid4: '1'}, {id1: 11, id2: '11', aval: 'a7', bid3: null, bid4: null}, {id1: 21, id2: '21', aval: 'a10', bid3: null, bid4: null}, {id1: 21, id2: '22', aval: 'a11', bid3: null, bid4: null}, {id1: 22, id2: '21', aval: 'a12', bid3: null, bid4: null} ] } ]); }); }); it('belongs to one $relatedQuery and ' + eager.name, () => { return B.query() .findById([1, '1']) .then(b => { return b .$relatedQuery('a') .eager('b') .eagerAlgorithm(eager.eagerAlgo); }) .then(b => { b = _.sortBy(b, ['id1', 'id2']); expect(b).to.eql([ { id1: 1, id2: '1', aval: 'a1', bid3: 1, bid4: '1', b: {id3: 1, id4: '1', bval: 'b1'} }, { id1: 1, id2: '2', aval: 'a2', bid3: 1, bid4: '1', b: {id3: 1, id4: '1', bval: 'b1'} }, { id1: 2, id2: '1', aval: 'a3', bid3: 1, bid4: '1', b: {id3: 1, id4: '1', bval: 'b1'} } ]); }); }); it('many to many $relatedQuery and ' + eager.name, () => { return B.query() .findById([1, '1']) .then(b => { return b .$relatedQuery('ab') .eager('ba') .eagerAlgorithm(eager.eagerAlgo); }) .then(b => { b = _.sortBy(b, ['id1', 'id2']); b[0].ba = _.sortBy(b[0].ba, ['id3', 'id4']); expect(b).to.eql([ { id1: 11, id2: '11', aval: 'a7', bid3: null, bid4: null, ba: [{bval: 'b1', id3: 1, id4: '1'}, {bval: 'b2', id3: 1, id4: '2'}] }, { id1: 11, id2: '12', aval: 'a8', bid3: null, bid4: null, ba: [{bval: 'b1', id3: 1, id4: '1'}] }, { id1: 12, id2: '11', aval: 'a9', bid3: null, bid4: null, ba: [{bval: 'b1', id3: 1, id4: '1'}] } ]); }); }); }); }); describe('belongs to one relation', () => { it('find', () => { return A.query() .findById([1, '1']) .then(a1 => { return [a1, a1.$relatedQuery('b')]; }) .spread((a1, b1) => { expect(a1.b).to.eql({id3: 1, id4: '1', bval: 'b1'}); expect(b1).to.equal(a1.b); }); }); it('insert', () => { return A.query() .findById([1, '1']) .then(a1 => { return [a1, a1.$relatedQuery('b').insert({id3: 1000, id4: '2000', bval: 'new'})]; }) .spread((a1, bNew) => { expect(a1.b).to.eql({id3: 1000, id4: '2000', bval: 'new'}); expect(bNew).to.equal(a1.b); expect(a1).to.eql({id1: 1, id2: '1', aval: 'a1', bid3: 1000, bid4: '2000', b: bNew}); return Promise.all([ session .knex('A') .where({id1: 1, id2: '1'}) .first(), session .knex('B') .where({id3: 1000, id4: '2000'}) .first() ]); }) .spread((a1, bNew) => { expect(a1).to.eql({id1: 1, id2: '1', aval: 'a1', bid3: 1000, bid4: '2000'}); expect(bNew).to.eql({id3: 1000, id4: '2000', bval: 'new'}); }); }); it('update', () => { return A.query() .findById([1, '1']) .then(a1 => { return [a1, a1.$relatedQuery('b').update({bval: 'updated'})]; }) .spread((a1, numUpdated) => { expect(numUpdated).to.equal(1); return session.knex('B').where('bval', 'updated'); }) .then(rows => { expect(rows).to.have.length(1); expect(rows[0]).to.eql({id3: 1, id4: '1', bval: 'updated'}); }); }); it('updateAndFetchById', () => { return A.query() .findById([1, '1']) .then(a1 => { return [a1, a1.$relatedQuery('b').updateAndFetchById([1, '1'], {bval: 'updated'})]; }) .spread((a1, b1) => { expect(b1).to.eql({id3: 1, id4: '1', bval: 'updated'}); return session.knex('B').where('bval', 'updated'); }) .then(rows => { expect(rows).to.have.length(1); expect(rows[0]).to.eql({id3: 1, id4: '1', bval: 'updated'}); }); }); it('delete', () => { return A.query() .findById([2, '2']) .then(a1 => { return [a1, a1.$relatedQuery('b').delete()]; }) .spread((a1, numDeleted) => { expect(numDeleted).to.equal(1); return session.knex('B'); }) .then(rows => { expect(rows).to.have.length(1); expect(rows[0].bval).to.equal('b1'); }); }); it('relate', () => { return A.query() .findById([2, '2']) .then(a1 => { expect(a1.bid3).to.equal(1); expect(a1.bid4).to.equal('2'); return [a1, a1.$relatedQuery('b').relate([1, '1'])]; }) .spread(a1 => { expect(a1.bid3).to.equal(1); expect(a1.bid4).to.equal('1'); return A.query().findById([2, '2']); }) .then(a1 => { expect(a1.bid3).to.equal(1); expect(a1.bid4).to.equal('1'); }); }); it('unrelate', () => { return A.query() .findById([2, '2']) .then(a1 => { expect(a1.bid3).to.equal(1); expect(a1.bid4).to.equal('2'); return [a1, a1.$relatedQuery('b').unrelate()]; }) .spread(a1 => { expect(a1.bid3).to.equal(null); expect(a1.bid4).to.equal(null); return A.query().findById([2, '2']); }) .then(a1 => { expect(a1.bid3).to.equal(null); expect(a1.bid4).to.equal(null); }); }); }); describe('has many relation', () => { it('find', () => { return B.query() .findById([1, '1']) .then(b1 => { return [b1, b1.$relatedQuery('a').orderBy(['id1', 'id2'])]; }) .spread((b1, a) => { expect(b1.a).to.eql(a); expect(a).to.eql([ {id1: 1, id2: '1', aval: 'a1', bid3: 1, bid4: '1'}, {id1: 1, id2: '2', aval: 'a2', bid3: 1, bid4: '1'}, {id1: 2, id2: '1', aval: 'a3', bid3: 1, bid4: '1'} ]); }); }); it('insert', () => { return B.query() .findById([1, '1']) .then(b1 => { return [b1, b1.$relatedQuery('a').insert({id1: 1000, id2: '2000', aval: 'new'})]; }) .spread((b1, aNew) => { expect(_.last(b1.a)).to.eql({ id1: 1000, id2: '2000', aval: 'new', bid3: 1, bid4: '1' }); expect(_.last(b1.a)).to.equal(aNew); return session .knex('A') .where({id1: 1000, id2: '2000'}) .first(); }) .then(aNew => { expect(aNew).to.eql({id1: 1000, id2: '2000', aval: 'new', bid3: 1, bid4: '1'}); }); }); it('update', () => { return B.query() .findById([1, '1']) .then(b1 => { return b1 .$relatedQuery('a') .update({aval: 'up'}) .where('id2', '>', '1'); }) .then(count => { expect(count).to.equal(1); return session.knex('A').orderBy(['id1', 'id2']); }) .then(rows => { expect(rows).to.eql([ {id1: 1, id2: '1', aval: 'a1', bid3: 1, bid4: '1'}, {id1: 1, id2: '2', aval: 'up', bid3: 1, bid4: '1'}, {id1: 2, id2: '1', aval: 'a3', bid3: 1, bid4: '1'}, {id1: 2, id2: '2', aval: 'a4', bid3: 1, bid4: '2'}, {id1: 2, id2: '3', aval: 'a5', bid3: 1, bid4: '2'}, {id1: 3, id2: '2', aval: 'a6', bid3: 1, bid4: '2'}, {id1: 11, id2: '11', aval: 'a7', bid3: null, bid4: null}, {id1: 11, id2: '12', aval: 'a8', bid3: null, bid4: null}, {id1: 12, id2: '11', aval: 'a9', bid3: null, bid4: null}, {id1: 21, id2: '21', aval: 'a10', bid3: null, bid4: null}, {id1: 21, id2: '22', aval: 'a11', bid3: null, bid4: null}, {id1: 22, id2: '21', aval: 'a12', bid3: null, bid4: null} ]); }); }); it('delete', () => { return B.query() .findById([1, '2']) .then(b2 => { return b2.$relatedQuery('a').delete(); }) .then(count => { expect(count).to.equal(3); return session.knex('A').orderBy(['id1', 'id2']); }) .then(rows => { expect(rows).to.eql([ {id1: 1, id2: '1', aval: 'a1', bid3: 1, bid4: '1'}, {id1: 1, id2: '2', aval: 'a2', bid3: 1, bid4: '1'}, {id1: 2, id2: '1', aval: 'a3', bid3: 1, bid4: '1'}, {id1: 11, id2: '11', aval: 'a7', bid3: null, bid4: null}, {id1: 11, id2: '12', aval: 'a8', bid3: null, bid4: null}, {id1: 12, id2: '11', aval: 'a9', bid3: null, bid4: null}, {id1: 21, id2: '21', aval: 'a10', bid3: null, bid4: null}, {id1: 21, id2: '22', aval: 'a11', bid3: null, bid4: null}, {id1: 22, id2: '21', aval: 'a12', bid3: null, bid4: null} ]); }); }); it('relate', () => { return B.query() .findById([1, '2']) .then(b2 => { return b2.$relatedQuery('a').relate([1, '1']); }) .then(() => { return session.knex('A').orderBy(['id1', 'id2']); }) .then(rows => { expect(rows).to.eql([ {id1: 1, id2: '1', aval: 'a1', bid3: 1, bid4: '2'}, {id1: 1, id2: '2', aval: 'a2', bid3: 1, bid4: '1'}, {id1: 2, id2: '1', aval: 'a3', bid3: 1, bid4: '1'}, {id1: 2, id2: '2', aval: 'a4', bid3: 1, bid4: '2'}, {id1: 2, id2: '3', aval: 'a5', bid3: 1, bid4: '2'}, {id1: 3, id2: '2', aval: 'a6', bid3: 1, bid4: '2'}, {id1: 11, id2: '11', aval: 'a7', bid3: null, bid4: null}, {id1: 11, id2: '12', aval: 'a8', bid3: null, bid4: null}, {id1: 12, id2: '11', aval: 'a9', bid3: null, bid4: null}, {id1: 21, id2: '21', aval: 'a10', bid3: null, bid4: null}, {id1: 21, id2: '22', aval: 'a11', bid3: null, bid4: null}, {id1: 22, id2: '21', aval: 'a12', bid3: null, bid4: null} ]); }); }); it('relate (object value)', () => { return B.query() .findById([1, '2']) .then(b2 => { return b2.$relatedQuery('a').relate({id1: 1, id2: '1'}); }) .then(() => { return session.knex('A').orderBy(['id1', 'id2']); }) .then(rows => { expect(rows).to.eql([ {id1: 1, id2: '1', aval: 'a1', bid3: 1, bid4: '2'}, {id1: 1, id2: '2', aval: 'a2', bid3: 1, bid4: '1'}, {id1: 2, id2: '1', aval: 'a3', bid3: 1, bid4: '1'}, {id1: 2, id2: '2', aval: 'a4', bid3: 1, bid4: '2'}, {id1: 2, id2: '3', aval: 'a5', bid3: 1, bid4: '2'}, {id1: 3, id2: '2', aval: 'a6', bid3: 1, bid4: '2'}, {id1: 11, id2: '11', aval: 'a7', bid3: null, bid4: null}, {id1: 11, id2: '12', aval: 'a8', bid3: null, bid4: null}, {id1: 12, id2: '11', aval: 'a9', bid3: null, bid4: null}, {id1: 21, id2: '21', aval: 'a10', bid3: null, bid4: null}, {id1: 21, id2: '22', aval: 'a11', bid3: null, bid4: null}, {id1: 22, id2: '21', aval: 'a12', bid3: null, bid4: null} ]); }); }); it('unrelate', () => { return B.query() .findById([1, '2']) .then(b2 => { return b2 .$relatedQuery('a') .unrelate() .where('aval', 'a5'); }) .then(() => { return session.knex('A').orderBy(['id1', 'id2']); }) .then(rows => { expect(rows).to.eql([ {id1: 1, id2: '1', aval: 'a1', bid3: 1, bid4: '1'}, {id1: 1, id2: '2', aval: 'a2', bid3: 1, bid4: '1'}, {id1: 2, id2: '1', aval: 'a3', bid3: 1, bid4: '1'}, {id1: 2, id2: '2', aval: 'a4', bid3: 1, bid4: '2'}, {id1: 2, id2: '3', aval: 'a5', bid3: null, bid4: null}, {id1: 3, id2: '2', aval: 'a6', bid3: 1, bid4: '2'}, {id1: 11, id2: '11', aval: 'a7', bid3: null, bid4: null}, {id1: 11, id2: '12', aval: 'a8', bid3: null, bid4: null}, {id1: 12, id2: '11', aval: 'a9', bid3: null, bid4: null}, {id1: 21, id2: '21', aval: 'a10', bid3: null, bid4: null}, {id1: 21, id2: '22', aval: 'a11', bid3: null, bid4: null}, {id1: 22, id2: '21', aval: 'a12', bid3: null, bid4: null} ]); }); }); }); describe('many to many relation', () => { it('find', () => { return B.query() .findById([1, '2']) .then(b2 => { return b2.$relatedQuery('ab').orderBy(['id1', 'id2']); }) .then(ret => { expect(ret).to.eql([ {id1: 1, id2: '1', aval: 'a1', bid3: 1, bid4: '1'}, {id1: 11, id2: '11', aval: 'a7', bid3: null, bid4: null}, {id1: 21, id2: '21', aval: 'a10', bid3: null, bid4: null}, {id1: 21, id2: '22', aval: 'a11', bid3: null, bid4: null}, {id1: 22, id2: '21', aval: 'a12', bid3: null, bid4: null} ]); }); }); it('insert', () => { let aOld; let abOld; return B.query() .findById([1, '2']) .then(b2 => { return Promise.all([ b2, session.knex('A').orderBy(['id1', 'id2']), session.knex('A_B').orderBy(['bid3', 'bid4', 'aid1', 'aid2']) ]); }) .spread((b2, a, ab) => { aOld = a; abOld = ab; return b2.$relatedQuery('ab').insert({id1: 1000, id2: 2000, aval: 'new'}); }) .then(() => { return Promise.all([ session.knex('A').orderBy(['id1', 'id2']), session.knex('A_B').orderBy(['bid3', 'bid4', 'aid1', 'aid2']) ]); }) .spread((a, ab) => { expect(a).to.eql( aOld.concat([{id1: 1000, id2: '2000', aval: 'new', bid3: null, bid4: null}]) ); expect(ab).to.eql(abOld.concat([{aid1: 1000, aid2: '2000', bid3: 1, bid4: '2'}])); }); }); it('update', () => { return B.query() .findById([1, '2']) .then(b2 => { return b2.$relatedQuery('ab').update({aval: 'XX'}); }) .then(() => { return session.knex('A').orderBy(['id1', 'id2']); }) .then(rows => { expect(rows).to.eql([ {id1: 1, id2: '1', aval: 'XX', bid3: 1, bid4: '1'}, {id1: 1, id2: '2', aval: 'a2', bid3: 1, bid4: '1'}, {id1: 2, id2: '1', aval: 'a3', bid3: 1, bid4: '1'}, {id1: 2, id2: '2', aval: 'a4', bid3: 1, bid4: '2'}, {id1: 2, id2: '3', aval: 'a5', bid3: 1, bid4: '2'}, {id1: 3, id2: '2', aval: 'a6', bid3: 1, bid4: '2'}, {id1: 11, id2: '11', aval: 'XX', bid3: null, bid4: null}, {id1: 11, id2: '12', aval: 'a8', bid3: null, bid4: null}, {id1: 12, id2: '11', aval: 'a9', bid3: null, bid4: null}, {id1: 21, id2: '21', aval: 'XX', bid3: null, bid4: null}, {id1: 21, id2: '22', aval: 'XX', bid3: null, bid4: null}, {id1: 22, id2: '21', aval: 'XX', bid3: null, bid4: null} ]); }); }); it('delete', () => { return B.query() .findById([1, '2']) .then(b2 => { return b2.$relatedQuery('ab').delete(); }) .then(() => { return session.knex('A').orderBy(['id1', 'id2']); }) .then(rows => { expect(rows).to.eql([ {id1: 1, id2: '2', aval: 'a2', bid3: 1, bid4: '1'}, {id1: 2, id2: '1', aval: 'a3', bid3: 1, bid4: '1'}, {id1: 2, id2: '2', aval: 'a4', bid3: 1, bid4: '2'}, {id1: 2, id2: '3', aval: 'a5', bid3: 1, bid4: '2'}, {id1: 3, id2: '2', aval: 'a6', bid3: 1, bid4: '2'}, {id1: 11, id2: '12', aval: 'a8', bid3: null, bid4: null}, {id1: 12, id2: '11', aval: 'a9', bid3: null, bid4: null} ]); }); }); it('relate', () => { let aOld; let abOld; return B.query() .findById([1, '2']) .then(b2 => { return Promise.all([ b2, session.knex('A').orderBy(['id1', 'id2']), session.knex('A_B').orderBy(['bid3', 'bid4', 'aid1', 'aid2']) ]); }) .spread((b2, a, ab) => { aOld = a; abOld = ab; return b2.$relatedQuery('ab').relate([1, '2']); }) .then(() => { return Promise.all([ session.knex('A').orderBy(['id1', 'id2']), session.knex('A_B').orderBy(['bid3', 'bid4', 'aid1', 'aid2']) ]); }) .spread((a, ab) => { expect(a).to.eql(aOld); expect(ab).to.eql( _.sortBy(abOld.concat([{aid1: 1, aid2: '2', bid3: 1, bid4: '2'}]), [ 'bid3', 'bid4', 'aid1', 'aid2' ]) ); }); }); it('unrelate', () => { let aOld; let abOld; return B.query() .findById([1, '2']) .then(b2 => { return Promise.all([ b2, session.knex('A').orderBy(['id1', 'id2']), session.knex('A_B').orderBy(['bid3', 'bid4', 'aid1', 'aid2']) ]); }) .spread((b2, a, ab) => { aOld = a; abOld = ab; return b2.$relatedQuery('ab').unrelate(); }) .then(() => { return Promise.all([ session.knex('A').orderBy(['id1', 'id2']), session.knex('A_B').orderBy(['bid3', 'bid4', 'aid1', 'aid2']) ]); }) .spread((a, ab) => { expect(a).to.eql(aOld); expect(ab).to.eql(_.reject(abOld, {bid3: 1, bid4: '2'})); }); }); }); }); }); };
/* @generated */ // prettier-ignore if (Intl.NumberFormat && typeof Intl.NumberFormat.__addLocaleData === 'function') { Intl.NumberFormat.__addLocaleData({"data":{"so-DJ":{"units":{"simple":{"degree":{"long":{"other":"{0} digrii"},"short":{"other":"{0} dig"},"narrow":{"other":"{0} dig"},"perUnit":{}},"hectare":{"long":{"other":"{0} hektar","one":"hektar"},"short":{"other":"{0} hk"},"narrow":{"other":"{0} hk"},"perUnit":{}},"acre":{"long":{"other":"{0} aakre"},"short":{"other":"{0} ak"},"narrow":{"other":"{0} ak"},"perUnit":{}},"percent":{"long":{"other":"boqolkiiba {0}"},"short":{"other":"{0}%"},"narrow":{"other":"{0}%"},"perUnit":{}},"liter-per-kilometer":{"long":{"other":"{0} litir kiilomitirkiiba","one":"litar kiilomitirkiiba"},"short":{"other":"{0} L/km"},"narrow":{"other":"{0} L/km"},"perUnit":{}},"mile-per-gallon":{"long":{"other":"{0} meyl galaankiiba"},"short":{"other":"{0} mpg US"},"narrow":{"other":"{0} mpg US"},"perUnit":{}},"petabyte":{"long":{"other":"{0} betabeyt"},"short":{"other":"{0} BB"},"narrow":{"other":"{0} BB"},"perUnit":{}},"terabyte":{"long":{"other":"{0} terabeyt"},"short":{"other":"{0} TB"},"narrow":{"other":"{0} TB"},"perUnit":{}},"terabit":{"long":{"other":"{0} terabit"},"short":{"other":"{0} Tb"},"narrow":{"other":"{0} Tb"},"perUnit":{}},"gigabyte":{"long":{"other":"{0} gigabeyt"},"short":{"other":"{0} GB"},"narrow":{"other":"{0} GB"},"perUnit":{}},"gigabit":{"long":{"other":"{0} gigabit"},"short":{"other":"{0} Gb"},"narrow":{"other":"{0} Gb"},"perUnit":{}},"megabyte":{"long":{"other":"{0} megabeyt"},"short":{"other":"{0} MB"},"narrow":{"other":"{0} MB"},"perUnit":{}},"megabit":{"long":{"other":"{0} megabit"},"short":{"other":"{0} Mb"},"narrow":{"other":"{0} Mb"},"perUnit":{}},"kilobyte":{"long":{"other":"{0} kiilobeyt"},"short":{"other":"{0} kB"},"narrow":{"other":"{0} kB"},"perUnit":{}},"kilobit":{"long":{"other":"{0} kiilobit"},"short":{"other":"{0} kb"},"narrow":{"other":"{0} kb"},"perUnit":{}},"byte":{"long":{"other":"{0} beyt"},"short":{"other":"{0} beyt"},"narrow":{"other":"{0} beyt"},"perUnit":{}},"bit":{"long":{"other":"{0} bit"},"short":{"other":"{0} bit"},"narrow":{"other":"{0} bit"},"perUnit":{}},"year":{"long":{"other":"{0} Sannado","one":"{0} Sannad"},"short":{"other":"{0} snd","one":"snd"},"narrow":{"other":"{0}s"},"perUnit":{"long":"{0} Sannadkiiba","short":"{0}/sk","narrow":"{0}/sk"}},"month":{"long":{"other":"{0} bilood","one":"{0} bil"},"short":{"other":"{0} bil"},"narrow":{"other":"{0}b"},"perUnit":{"long":"{0} bishiiba","short":"{0}/bsh","narrow":"{0}/bsh"}},"week":{"long":{"other":"{0} toddobaadyo","one":"{0} toddobaad"},"short":{"other":"{0} tdbd"},"narrow":{"other":"{0}t"},"perUnit":{"long":"{0} toddobaadkiiba","short":"{0}/tdbdk","narrow":"{0} U/K"}},"day":{"long":{"other":"{0} maalmood","one":"{0} maalin"},"short":{"other":"{0} mln"},"narrow":{"other":"{0}m"},"perUnit":{"long":"{0} maalintiiba","short":"{0}/mt","narrow":"{0}M/K"}},"hour":{"long":{"other":"{0} saacadood","one":"{0} saacad"},"short":{"other":"{0} scd"},"narrow":{"other":"{0} s","one":"{0} scd"},"perUnit":{"long":"{0} saacadiiba","short":"{0} scdi","narrow":"{0} scdi"}},"minute":{"long":{"other":"{0} daqiiqo","one":"{0} daqiiqad"},"short":{"other":"{0} daqiiqo","one":"{0} dqqd"},"narrow":{"other":"{0}d"},"perUnit":{"long":"{0} daqiiqadiiba","short":"{0} dqqdb","narrow":"{0} dqqdb"}},"second":{"long":{"other":"{0} ilbiriqsi"},"short":{"other":"{0} ilbrqsi"},"narrow":{"other":"{0}il"},"perUnit":{"long":"{0} Ilbiriqsigiiba","short":"{0}/ilbrgba","narrow":"{0}/ilbrgba"}},"millisecond":{"long":{"other":"{0} miliseken"},"short":{"other":"{0} ms"},"narrow":{"other":"{0}ms"},"perUnit":{}},"kilometer":{"long":{"other":"{0} kiilo mitir"},"short":{"other":"{0} km"},"narrow":{"other":"{0}km"},"perUnit":{"long":"{0} kiilo mitirkiiba","short":"{0}/km","narrow":"{0}/km"}},"meter":{"long":{"other":"{0} mitir"},"short":{"other":"{0} m"},"narrow":{"other":"{0}m"},"perUnit":{"long":"{0} mitirkiiba","short":"{0}/m","narrow":"{0}/m"}},"centimeter":{"long":{"other":"{0} sentimitir"},"short":{"other":"{0} cm"},"narrow":{"other":"{0}cm"},"perUnit":{"long":"{0} sentimitirkiiba","short":"{0}/cm","narrow":"{0}/cm"}},"millimeter":{"long":{"other":"{0} milimitir"},"short":{"other":"{0} mm"},"narrow":{"other":"{0}mm"},"perUnit":{}},"mile":{"long":{"other":"{0} meyl"},"short":{"other":"{0} my"},"narrow":{"other":"{0} my"},"perUnit":{}},"yard":{"long":{"other":"{0} yaardi"},"short":{"other":"{0} yd"},"narrow":{"other":"{0} yd"},"perUnit":{}},"foot":{"long":{"other":"{0} fiit","one":"Fuudh"},"short":{"other":"{0} ft"},"narrow":{"other":"{0} ft"},"perUnit":{"long":"{0} fiitkiiba","short":"{0}/ft","narrow":"{0}/ft"}},"inch":{"long":{"other":"{0} injis","one":"Injis"},"short":{"other":"{0} in"},"narrow":{"other":"{0} in"},"perUnit":{"long":"{0} injigiiba","short":"{0}/in","narrow":"{0}/in"}},"mile-scandinavian":{"long":{"other":"{0} meyl-iskanddineyfiyaan","one":"{0} meyl-iskandineyfiyaan"},"short":{"other":"{0} smy"},"narrow":{"other":"{0} smy"},"perUnit":{}},"kilogram":{"long":{"other":"{0} kiilogaraam"},"short":{"other":"{0} kg"},"narrow":{"other":"{0}kg"},"perUnit":{"long":"{0} kiilogaraam","short":"{0}/kg","narrow":"{0}/kg"}},"gram":{"long":{"other":"{0} garaam"},"short":{"other":"{0} g"},"narrow":{"other":"{0}g"},"perUnit":{"long":"{0} garaamkiiba","short":"{0}/g","narrow":"{0}/g"}},"stone":{"long":{"other":"{0} st"},"short":{"other":"{0} st"},"narrow":{"other":"{0} st"},"perUnit":{}},"pound":{"long":{"other":"{0} bownd"},"short":{"other":"{0} bw"},"narrow":{"other":"{0} bw"},"perUnit":{"long":"{0} bowndkiiba","short":"{0}/bw","narrow":"{0}/bw"}},"ounce":{"long":{"other":"{0} ownis"},"short":{"other":"{0} ow"},"narrow":{"other":"{0} ow"},"perUnit":{"long":"{0} owniskiiba","short":"{0}/ow","narrow":"{0}/ow"}},"kilometer-per-hour":{"long":{"other":"{0} kiilomitir saacadiiba","one":"{0} kiiomitir saacadiiba"},"short":{"other":"{0} km/s"},"narrow":{"other":"{0} km/s"},"perUnit":{}},"meter-per-second":{"long":{"other":"{0} mitir ilbiriqsigiiba","one":"mitir ilbiriqsigiiba"},"short":{"other":"{0} m/i"},"narrow":{"other":"{0} m/i"},"perUnit":{}},"mile-per-hour":{"long":{"other":"{0} meyl saacadiiba"},"short":{"other":"{0} my/s"},"narrow":{"other":"{0} my/s"},"perUnit":{}},"celsius":{"long":{"other":"{0} degrii Selsiyaas"},"short":{"other":"{0}°C"},"narrow":{"other":"{0}°C"},"perUnit":{}},"fahrenheit":{"long":{"other":"{0} degrii Faahrenheyt"},"short":{"other":"{0}°F"},"narrow":{"other":"{0}°F"},"perUnit":{}},"liter":{"long":{"other":"{0} litar"},"short":{"other":"{0} L"},"narrow":{"other":"{0}L"},"perUnit":{"long":"{0} litarkiiba","short":"{0}/L","narrow":"{0}/L"}},"milliliter":{"long":{"other":"{0} mililitar"},"short":{"other":"{0} mL"},"narrow":{"other":"{0} mL"},"perUnit":{}},"gallon":{"long":{"other":"{0} galaan"},"short":{"other":"{0} gal"},"narrow":{"other":"{0} gal"},"perUnit":{"long":"{0} galaankiiba","short":"{0}/gal US","narrow":"{0}/gal US"}},"fluid-ounce":{"long":{"other":"{0} owniska dareeraha"},"short":{"other":"{0} own dr"},"narrow":{"other":"{0} own dr"},"perUnit":{}}},"compound":{"per":{"long":"{0}/{1}","short":"{0}/{1}","narrow":"{0}/{1}"}}},"currencies":{"ADP":{"displayName":{"other":"ADP"},"symbol":"ADP","narrow":"ADP"},"AED":{"displayName":{"other":"dirhamka Isutaga Imaaraatka Carabta"},"symbol":"AED","narrow":"AED"},"AFA":{"displayName":{"other":"AFA"},"symbol":"AFA","narrow":"AFA"},"AFN":{"displayName":{"other":"Afgan Afgani"},"symbol":"AFN","narrow":"AFN"},"ALK":{"displayName":{"other":"ALK"},"symbol":"ALK","narrow":"ALK"},"ALL":{"displayName":{"other":"lekta Albaniya","one":"lekta Abaniya"},"symbol":"ALL","narrow":"ALL"},"AMD":{"displayName":{"other":"daraamka Armeniya"},"symbol":"AMD","narrow":"AMD"},"ANG":{"displayName":{"other":"galdarada Nadarlaan Antiliyaan","one":"galdarka Nadarlaan Antiliyaan"},"symbol":"ANG","narrow":"ANG"},"AOA":{"displayName":{"other":"kawansada Angola"},"symbol":"AOA","narrow":"Kz"},"AOK":{"displayName":{"other":"AOK"},"symbol":"AOK","narrow":"AOK"},"AON":{"displayName":{"other":"AON"},"symbol":"AON","narrow":"AON"},"AOR":{"displayName":{"other":"AOR"},"symbol":"AOR","narrow":"AOR"},"ARA":{"displayName":{"other":"Argentine Australs","one":"Argentine Austral"},"symbol":"ARA","narrow":"ARA"},"ARL":{"displayName":{"other":"Beesada Ley ee Arjentiin (1970–1983)"},"symbol":"ARL","narrow":"ARL"},"ARM":{"displayName":{"other":"Beesada Ley ee Arjentiin (1881–1970)"},"symbol":"ARM","narrow":"ARM"},"ARP":{"displayName":{"other":"Beesada Ley ee Arjentiin (1883–1985)"},"symbol":"ARP","narrow":"ARP"},"ARS":{"displayName":{"other":"Beesada Arjentiin"},"symbol":"ARS","narrow":"$"},"ATS":{"displayName":{"other":"ATS"},"symbol":"ATS","narrow":"ATS"},"AUD":{"displayName":{"other":"doolarada Astaraaliya","one":"doolarka Astaraaliya"},"symbol":"A$","narrow":"$"},"AWG":{"displayName":{"other":"foloorinta Aruban"},"symbol":"AWG","narrow":"AWG"},"AZM":{"displayName":{"other":"AZM"},"symbol":"AZM","narrow":"AZM"},"AZN":{"displayName":{"other":"manaata Asarbeyjan"},"symbol":"AZN","narrow":"AZN"},"BAD":{"displayName":{"other":"Diinaarka BBosnia-Hersogofina 1.00 konfatibal maakta Bosnia-Hersogofina 1 konfatibal maaka Bosnia-Hersogofina (1992–1994)","one":"Diinaarka BBosnia-Hersogofina (1992–1994)"},"symbol":"BAD","narrow":"BAD"},"BAM":{"displayName":{"other":"konfatibal maakta Bosnia-Hersogofina"},"symbol":"BAM","narrow":"KM"},"BAN":{"displayName":{"other":"BAN"},"symbol":"BAN","narrow":"BAN"},"BBD":{"displayName":{"other":"doolarada Barbaadiyaan","one":"doolarka Barbaadiyaan"},"symbol":"DBB","narrow":"$"},"BDT":{"displayName":{"other":"taka Bangledesh"},"symbol":"BDT","narrow":"৳"},"BEC":{"displayName":{"other":"BEC"},"symbol":"BEC","narrow":"BEC"},"BEF":{"displayName":{"other":"BEF"},"symbol":"BEF","narrow":"BEF"},"BEL":{"displayName":{"other":"BEL"},"symbol":"BEL","narrow":"BEL"},"BGL":{"displayName":{"other":"BGL"},"symbol":"BGL","narrow":"BGL"},"BGM":{"displayName":{"other":"BGM"},"symbol":"BGM","narrow":"BGM"},"BGN":{"displayName":{"other":"lefta Bulgariya"},"symbol":"BGN","narrow":"BGN"},"BGO":{"displayName":{"other":"BGO"},"symbol":"BGO","narrow":"BGO"},"BHD":{"displayName":{"other":"dinaarka Baxreyn"},"symbol":"BHD","narrow":"BHD"},"BIF":{"displayName":{"other":"faranka Burundi"},"symbol":"BIF","narrow":"BIF"},"BMD":{"displayName":{"other":"Doolarka Barmuuda","one":"doolarka Barmuuda"},"symbol":"BMD","narrow":"$"},"BND":{"displayName":{"other":"doolarada Buruney","one":"doolarka Buruney"},"symbol":"BND","narrow":"$"},"BOB":{"displayName":{"other":"Bolifiyanada Bolifiya"},"symbol":"BOB","narrow":"Bs"},"BOL":{"displayName":{"other":"Bolifiyaabka Bolifiyaano(1863–1963)"},"symbol":"BOL","narrow":"BOL"},"BOP":{"displayName":{"other":"BOP"},"symbol":"BOP","narrow":"BOP"},"BOV":{"displayName":{"other":"BOV"},"symbol":"BOV","narrow":"BOV"},"BRB":{"displayName":{"other":"BRB"},"symbol":"BRB","narrow":"BRB"},"BRC":{"displayName":{"other":"BRC"},"symbol":"BRC","narrow":"BRC"},"BRE":{"displayName":{"other":"BRE"},"symbol":"BRE","narrow":"BRE"},"BRL":{"displayName":{"other":"Realada Barasil","one":"Realka Barasil"},"symbol":"R$","narrow":"R$"},"BRN":{"displayName":{"other":"BRN"},"symbol":"BRN","narrow":"BRN"},"BRR":{"displayName":{"other":"BRR"},"symbol":"BRR","narrow":"BRR"},"BRZ":{"displayName":{"other":"BRZ"},"symbol":"BRZ","narrow":"BRZ"},"BSD":{"displayName":{"other":"doolarada Bahamaas","one":"doolarka Bahamaas"},"symbol":"BSD","narrow":"$"},"BTN":{"displayName":{"other":"nugultaramta Butan"},"symbol":"BTN","narrow":"BTN"},"BUK":{"displayName":{"other":"BUK"},"symbol":"BUK","narrow":"BUK"},"BWP":{"displayName":{"other":"buulada Botswana"},"symbol":"BWP","narrow":"P"},"BYB":{"displayName":{"other":"BYB"},"symbol":"BYB","narrow":"BYB"},"BYN":{"displayName":{"other":"rubalka Belarus"},"symbol":"BYN","narrow":"р."},"BYR":{"displayName":{"other":"BYR"},"symbol":"BYR","narrow":"BYR"},"BZD":{"displayName":{"other":"doolarada Beelisa","one":"doolarka Beelisa"},"symbol":"BZD","narrow":"$"},"CAD":{"displayName":{"other":"doolarada Kanada","one":"doolarka Kanada"},"symbol":"CA$","narrow":"$"},"CDF":{"displayName":{"other":"faranka Kongo"},"symbol":"CDF","narrow":"CDF"},"CHE":{"displayName":{"other":"CHE"},"symbol":"CHE","narrow":"CHE"},"CHF":{"displayName":{"other":"Faranka Iswiska"},"symbol":"CHF","narrow":"CHF"},"CHW":{"displayName":{"other":"CHW"},"symbol":"CHW","narrow":"CHW"},"CLE":{"displayName":{"other":"CLE"},"symbol":"CLE","narrow":"CLE"},"CLF":{"displayName":{"other":"CLF"},"symbol":"CLF","narrow":"CLF"},"CLP":{"displayName":{"other":"Beesada Jili"},"symbol":"CLP","narrow":"$"},"CNH":{"displayName":{"other":"yuwanta Shiinaha (Ofshoor)"},"symbol":"CNH","narrow":"CNH"},"CNX":{"displayName":{"other":"CNX"},"symbol":"CNX","narrow":"CNX"},"CNY":{"displayName":{"other":"yuwanta Shiinaha"},"symbol":"CN¥","narrow":"¥"},"COP":{"displayName":{"other":"Beesada Kolombiya"},"symbol":"COP","narrow":"$"},"COU":{"displayName":{"other":"COU"},"symbol":"COU","narrow":"COU"},"CRC":{"displayName":{"other":"kolonka Kosta Riika"},"symbol":"CRC","narrow":"₡"},"CSD":{"displayName":{"other":"CSD"},"symbol":"CSD","narrow":"CSD"},"CSK":{"displayName":{"other":"CSK"},"symbol":"CSK","narrow":"CSK"},"CUC":{"displayName":{"other":"beesada konfatibal ee Kuuba"},"symbol":"CUC","narrow":"$"},"CUP":{"displayName":{"other":"Beesada Kuuba"},"symbol":"CUP","narrow":"$"},"CVE":{"displayName":{"other":"eskudo Keyb Farde"},"symbol":"CVE","narrow":"CVE"},"CYP":{"displayName":{"other":"CYP"},"symbol":"CYP","narrow":"CYP"},"CZK":{"displayName":{"other":"korunada Jeek"},"symbol":"CZK","narrow":"Kč"},"DDM":{"displayName":{"other":"DDM"},"symbol":"DDM","narrow":"DDM"},"DEM":{"displayName":{"other":"DEM"},"symbol":"DEM","narrow":"DEM"},"DJF":{"displayName":{"other":"faranka Jabuuti"},"symbol":"Fdj","narrow":"Fdj"},"DKK":{"displayName":{"other":"Koronka Danishka"},"symbol":"DKK","narrow":"kr"},"DOP":{"displayName":{"other":"beesada Dominiika"},"symbol":"DOP","narrow":"$"},"DZD":{"displayName":{"other":"dinaarka Aljeriya"},"symbol":"DZD","narrow":"DZD"},"ECS":{"displayName":{"other":"ECS"},"symbol":"ECS","narrow":"ECS"},"ECV":{"displayName":{"other":"ECV"},"symbol":"ECV","narrow":"ECV"},"EEK":{"displayName":{"other":"Kroonka Estooniya"},"symbol":"EEK","narrow":"EEK"},"EGP":{"displayName":{"other":"bowndka Masar"},"symbol":"EGP","narrow":"E£"},"ERN":{"displayName":{"other":"nafkada Eritriya","one":"nakfada Eritriya"},"symbol":"ERN","narrow":"ERN"},"ESA":{"displayName":{"other":"ESA"},"symbol":"ESA","narrow":"ESA"},"ESB":{"displayName":{"other":"ESB"},"symbol":"ESB","narrow":"ESB"},"ESP":{"displayName":{"other":"ESP"},"symbol":"ESP","narrow":"₧"},"ETB":{"displayName":{"other":"birta Itoobbiya"},"symbol":"ETB","narrow":"ETB"},"EUR":{"displayName":{"other":"yuuroo"},"symbol":"€","narrow":"€"},"FIM":{"displayName":{"other":"Markkada Fiinishka ah"},"symbol":"FIM","narrow":"FIM"},"FJD":{"displayName":{"other":"doolarada Fiji","one":"doolarka Fiji"},"symbol":"FJD","narrow":"$"},"FKP":{"displayName":{"other":"Bowndka Faalklaan Aylaanis"},"symbol":"FKP","narrow":"£"},"FRF":{"displayName":{"other":"FRF"},"symbol":"FRF","narrow":"FRF"},"GBP":{"displayName":{"other":"Bowndka Biritishka"},"symbol":"£","narrow":"£"},"GEK":{"displayName":{"other":"GEK"},"symbol":"GEK","narrow":"GEK"},"GEL":{"displayName":{"other":"laariga Joorjiya"},"symbol":"GEL","narrow":"₾"},"GHC":{"displayName":{"other":"GHC"},"symbol":"GHC","narrow":"GHC"},"GHS":{"displayName":{"other":"sedida Gana"},"symbol":"GHS","narrow":"GHS"},"GIP":{"displayName":{"other":"bowndka Gibraltar"},"symbol":"GIP","narrow":"£"},"GMD":{"displayName":{"other":"Dalasida Gambiya"},"symbol":"GMD","narrow":"GMD"},"GNF":{"displayName":{"other":"faranka Gini"},"symbol":"GNF","narrow":"FG"},"GNS":{"displayName":{"other":"GNS"},"symbol":"GNS","narrow":"GNS"},"GQE":{"displayName":{"other":"GQE"},"symbol":"GQE","narrow":"GQE"},"GRD":{"displayName":{"other":"GRD"},"symbol":"GRD","narrow":"GRD"},"GTQ":{"displayName":{"other":"kuwestalka Guwatemala"},"symbol":"GTQ","narrow":"Q"},"GWE":{"displayName":{"other":"GWE"},"symbol":"GWE","narrow":"GWE"},"GWP":{"displayName":{"other":"GWP"},"symbol":"GWP","narrow":"GWP"},"GYD":{"displayName":{"other":"Doolarada Guyanes","one":"Doolarka Guyanes"},"symbol":"GYD","narrow":"$"},"HKD":{"displayName":{"other":"Doolarada Hoon Koon"},"symbol":"HK$","narrow":"$"},"HNL":{"displayName":{"other":"lembirada Honduras"},"symbol":"HNL","narrow":"L"},"HRD":{"displayName":{"other":"HRD"},"symbol":"HRD","narrow":"HRD"},"HRK":{"displayName":{"other":"kunada Korooshiya"},"symbol":"HRK","narrow":"kn"},"HTG":{"displayName":{"other":"goordada Hiyati"},"symbol":"HTG","narrow":"HTG"},"HUF":{"displayName":{"other":"forintiska Hangari"},"symbol":"HUF","narrow":"Ft"},"IDR":{"displayName":{"other":"rubiah Indonesiya"},"symbol":"IDR","narrow":"Rp"},"IEP":{"displayName":{"other":"baawnka Ayrishka"},"symbol":"IEP","narrow":"IEP"},"ILP":{"displayName":{"other":"ILP"},"symbol":"ILP","narrow":"ILP"},"ILR":{"displayName":{"other":"ILR"},"symbol":"ILR","narrow":"ILR"},"ILS":{"displayName":{"other":"niyuu shekelka Israaiil"},"symbol":"₪","narrow":"₪"},"INR":{"displayName":{"other":"rubiga Hindiya"},"symbol":"₹","narrow":"₹"},"IQD":{"displayName":{"other":"dinaarka Ciraaq"},"symbol":"IQD","narrow":"IQD"},"IRR":{"displayName":{"other":"riyaalka Iran"},"symbol":"IRR","narrow":"IRR"},"ISJ":{"displayName":{"other":"krónaha Iceland (1918–1981)"},"symbol":"ISJ","narrow":"ISJ"},"ISK":{"displayName":{"other":"Koronada Eysland"},"symbol":"ISK","narrow":"kr"},"ITL":{"displayName":{"other":"ITL"},"symbol":"ITL","narrow":"ITL"},"JMD":{"displayName":{"other":"doolarada Jamayka","one":"doolarka Jamayka"},"symbol":"JMD","narrow":"$"},"JOD":{"displayName":{"other":"dinaarka Urdun"},"symbol":"JOD","narrow":"JOD"},"JPY":{"displayName":{"other":"yenta Jabaan"},"symbol":"JP¥","narrow":"¥"},"KES":{"displayName":{"other":"shilingka Kenya"},"symbol":"KES","narrow":"KES"},"KGS":{"displayName":{"other":"somta Kiyrgiystan","one":"somta Kiyriygstan"},"symbol":"KGS","narrow":"KGS"},"KHR":{"displayName":{"other":"Riyf kambodiya","one":"Riyf Kambodiya"},"symbol":"KHR","narrow":"៛"},"KMF":{"displayName":{"other":"faranka Komoros"},"symbol":"KMF","narrow":"CF"},"KPW":{"displayName":{"other":"wonka Waqooyiga Kuuriya"},"symbol":"KPW","narrow":"₩"},"KRH":{"displayName":{"other":"KRH"},"symbol":"KRH","narrow":"KRH"},"KRO":{"displayName":{"other":"KRO"},"symbol":"KRO","narrow":"KRO"},"KRW":{"displayName":{"other":"wonka Koonfur Kuuriya"},"symbol":"₩","narrow":"₩"},"KWD":{"displayName":{"other":"dinaarka Kuweyt"},"symbol":"KWD","narrow":"KWD"},"KYD":{"displayName":{"other":"Doolarada Kayman Aylaanis","one":"doolarka Kayman Aylaanis"},"symbol":"KYD","narrow":"$"},"KZT":{"displayName":{"other":"tengeda Kasakhstan"},"symbol":"KZT","narrow":"₸"},"LAK":{"displayName":{"other":"kib Laoti"},"symbol":"LAK","narrow":"₭"},"LBP":{"displayName":{"other":"Bowndka Lubnaan","one":"bowndka Lubnaan"},"symbol":"LBP","narrow":"L£"},"LKR":{"displayName":{"other":"rubiga Siri lanka","one":"rubiga Siri Lanka"},"symbol":"LKR","narrow":"Rs"},"LRD":{"displayName":{"other":"doolarka Liberiya"},"symbol":"LRD","narrow":"$"},"LSL":{"displayName":{"other":"LSL"},"symbol":"LSL","narrow":"LSL"},"LTL":{"displayName":{"other":"LTL"},"symbol":"LTL","narrow":"Lt"},"LTT":{"displayName":{"other":"LTT"},"symbol":"LTT","narrow":"LTT"},"LUC":{"displayName":{"other":"LUC"},"symbol":"LUC","narrow":"LUC"},"LUF":{"displayName":{"other":"LUF"},"symbol":"LUF","narrow":"LUF"},"LUL":{"displayName":{"other":"LUL"},"symbol":"LUL","narrow":"LUL"},"LVL":{"displayName":{"other":"LVL"},"symbol":"LVL","narrow":"Ls"},"LVR":{"displayName":{"other":"rubalka Latfiya","one":"rubalka Latvia"},"symbol":"LVR","narrow":"LVR"},"LYD":{"displayName":{"other":"dinaarka Libya"},"symbol":"LYD","narrow":"LYD"},"MAD":{"displayName":{"other":"dirhamka Moroko"},"symbol":"MAD","narrow":"MAD"},"MAF":{"displayName":{"other":"MAF"},"symbol":"MAF","narrow":"MAF"},"MCF":{"displayName":{"other":"MCF"},"symbol":"MCF","narrow":"MCF"},"MDC":{"displayName":{"other":"MDC"},"symbol":"MDC","narrow":"MDC"},"MDL":{"displayName":{"other":"leeyuuda Moldofa"},"symbol":"MDL","narrow":"MDL"},"MGA":{"displayName":{"other":"arayrida Madagaskar"},"symbol":"MGA","narrow":"Ar"},"MGF":{"displayName":{"other":"MGF"},"symbol":"MGF","narrow":"MGF"},"MKD":{"displayName":{"other":"denaarka Masedoniya"},"symbol":"MKD","narrow":"MKD"},"MKN":{"displayName":{"other":"MKN"},"symbol":"MKN","narrow":"MKN"},"MLF":{"displayName":{"other":"MLF"},"symbol":"MLF","narrow":"MLF"},"MMK":{"displayName":{"other":"kayatda Mayanmaar"},"symbol":"MMK","narrow":"K"},"MNT":{"displayName":{"other":"tugrikta Mongoliya"},"symbol":"MNT","narrow":"₮"},"MOP":{"displayName":{"other":"bataka Makana"},"symbol":"MOP","narrow":"MOP"},"MRO":{"displayName":{"other":"Oogiya Mawritaniya (1973–2017)"},"symbol":"MRO","narrow":"MRO"},"MRU":{"displayName":{"other":"oogiyada Mawritaniya"},"symbol":"MRU","narrow":"MRU"},"MTL":{"displayName":{"other":"MTL"},"symbol":"MTL","narrow":"MTL"},"MTP":{"displayName":{"other":"MTP"},"symbol":"MTP","narrow":"MTP"},"MUR":{"displayName":{"other":"rubiga Mowrishiya"},"symbol":"MUR","narrow":"Rs"},"MVP":{"displayName":{"other":"MVP"},"symbol":"MVP","narrow":"MVP"},"MVR":{"displayName":{"other":"rufiyada Maldifiya"},"symbol":"MVR","narrow":"MVR"},"MWK":{"displayName":{"other":"kawajada Malawi"},"symbol":"MWK","narrow":"MWK"},"MXN":{"displayName":{"other":"beesada Meksiko","one":"Beesada Meksiko"},"symbol":"MX$","narrow":"$"},"MXP":{"displayName":{"other":"MXP"},"symbol":"MXP","narrow":"MXP"},"MXV":{"displayName":{"other":"MXV"},"symbol":"MXV","narrow":"MXV"},"MYR":{"displayName":{"other":"ringitda Malayshiya"},"symbol":"MYR","narrow":"RM"},"MZE":{"displayName":{"other":"MZE"},"symbol":"MZE","narrow":"MZE"},"MZM":{"displayName":{"other":"MZM"},"symbol":"MZM","narrow":"MZM"},"MZN":{"displayName":{"other":"Metikalka Mosambik","one":"metikalka Mosambik"},"symbol":"MZN","narrow":"MZN"},"NAD":{"displayName":{"other":"doolarka Namibiya"},"symbol":"NAD","narrow":"$"},"NGN":{"displayName":{"other":"nairada Neyjeeriya"},"symbol":"NGN","narrow":"₦"},"NIC":{"displayName":{"other":"NIC"},"symbol":"NIC","narrow":"NIC"},"NIO":{"displayName":{"other":"Kordobada Nikargow"},"symbol":"NIO","narrow":"C$"},"NLG":{"displayName":{"other":"NLG"},"symbol":"NLG","narrow":"NLG"},"NOK":{"displayName":{"other":"Koronka Norway"},"symbol":"NOK","narrow":"kr"},"NPR":{"displayName":{"other":"rubiga Nebal"},"symbol":"NPR","narrow":"Rs"},"NZD":{"displayName":{"other":"doolarada Niyuu Siyalaan","one":"doolarka Niyuu siyalaan"},"symbol":"NZ$","narrow":"$"},"OMR":{"displayName":{"other":"riyaalka Cumaan"},"symbol":"OMR","narrow":"OMR"},"PAB":{"displayName":{"other":"balbow Banama","one":"balbaw Banama"},"symbol":"PAB","narrow":"PAB"},"PEI":{"displayName":{"other":"PEI"},"symbol":"PEI","narrow":"PEI"},"PEN":{"displayName":{"other":"Solsha Beeru"},"symbol":"PEN","narrow":"PEN"},"PES":{"displayName":{"other":"PES"},"symbol":"PES","narrow":"PES"},"PGK":{"displayName":{"other":"kinada Babua Niyuu Gini"},"symbol":"PGK","narrow":"PGK"},"PHP":{"displayName":{"other":"biso Filibin"},"symbol":"PHP","narrow":"₱"},"PKR":{"displayName":{"other":"rubiga Bakistan"},"symbol":"PKR","narrow":"Rs"},"PLN":{"displayName":{"other":"solotida Bolaan"},"symbol":"PLN","narrow":"zł"},"PLZ":{"displayName":{"other":"PLZ"},"symbol":"PLZ","narrow":"PLZ"},"PTE":{"displayName":{"other":"PTE"},"symbol":"PTE","narrow":"PTE"},"PYG":{"displayName":{"other":"Guranida Baraguway"},"symbol":"PYG","narrow":"₲"},"QAR":{"displayName":{"other":"riyaalka Qatar"},"symbol":"QAR","narrow":"QAR"},"RHD":{"displayName":{"other":"RHD"},"symbol":"RHD","narrow":"RHD"},"ROL":{"displayName":{"other":"ROL"},"symbol":"ROL","narrow":"ROL"},"RON":{"displayName":{"other":"liyuuda Romaniya"},"symbol":"RON","narrow":"lei"},"RSD":{"displayName":{"other":"dinaarka Serbiya"},"symbol":"RSD","narrow":"RSD"},"RUB":{"displayName":{"other":"rubalka Ruushka"},"symbol":"RUB","narrow":"₽"},"RUR":{"displayName":{"other":"RUR"},"symbol":"RUR","narrow":"р."},"RWF":{"displayName":{"other":"Faranka Ruwanda"},"symbol":"RWF","narrow":"RF"},"SAR":{"displayName":{"other":"riyaalka Sacuudiga","one":"Riyaalka Sacuudiga"},"symbol":"SAR","narrow":"SAR"},"SBD":{"displayName":{"other":"doolarada Solomon Aylaanis","one":"doolarka Solomon Aylaanis"},"symbol":"SBD","narrow":"$"},"SCR":{"displayName":{"other":"rubiga Siisalis"},"symbol":"SCR","narrow":"SCR"},"SDD":{"displayName":{"other":"SDD"},"symbol":"SDD","narrow":"SDD"},"SDG":{"displayName":{"other":"bowndka Suudaan"},"symbol":"SDG","narrow":"SDG"},"SDP":{"displayName":{"other":"SDP"},"symbol":"SDP","narrow":"SDP"},"SEK":{"displayName":{"other":"Koronka Isweden"},"symbol":"SEK","narrow":"kr"},"SGD":{"displayName":{"other":"doolarka Singabuur"},"symbol":"SGD","narrow":"$"},"SHP":{"displayName":{"other":"Bowndka St Helen","one":"bowndka St Helen"},"symbol":"SHP","narrow":"£"},"SIT":{"displayName":{"other":"SIT"},"symbol":"SIT","narrow":"SIT"},"SKK":{"displayName":{"other":"SKK"},"symbol":"SKK","narrow":"SKK"},"SLL":{"displayName":{"other":"leonka Sira Leon"},"symbol":"SLL","narrow":"SLL"},"SOS":{"displayName":{"other":"Shilingka Soomaaliya"},"symbol":"S","narrow":"S"},"SRD":{"displayName":{"other":"Doolarada Surinamees","one":"Doolarka Surinamees"},"symbol":"SRD","narrow":"$"},"SRG":{"displayName":{"other":"SRG"},"symbol":"SRG","narrow":"SRG"},"SSP":{"displayName":{"other":"Bowndka Koonfurta Suudaan"},"symbol":"SSP","narrow":"£"},"STD":{"displayName":{"other":"STD"},"symbol":"STD","narrow":"STD"},"STN":{"displayName":{"other":"dobrada Sao Tome & Birinsibi","one":"dobrada Sao Tome Birinsibi"},"symbol":"STN","narrow":"Db"},"SUR":{"displayName":{"other":"SUR"},"symbol":"SUR","narrow":"SUR"},"SVC":{"displayName":{"other":"SVC"},"symbol":"SVC","narrow":"SVC"},"SYP":{"displayName":{"other":"bowndka Suuriya"},"symbol":"SYP","narrow":"£"},"SZL":{"displayName":{"other":"lilangeenida iswaasi","one":"lilengeenida Iswaasi"},"symbol":"SZL","narrow":"SZL"},"THB":{"displayName":{"other":"baatda Taylaan","one":"Baatda Taylaan"},"symbol":"THB","narrow":"฿"},"TJR":{"displayName":{"other":"TJR"},"symbol":"TJR","narrow":"TJR"},"TJS":{"displayName":{"other":"somoonida Tajikistan","one":"soomonida Tajikistan"},"symbol":"TJS","narrow":"TJS"},"TMM":{"displayName":{"other":"TMM"},"symbol":"TMM","narrow":"TMM"},"TMT":{"displayName":{"other":"manaata Turkmenistan"},"symbol":"TMT","narrow":"TMT"},"TND":{"displayName":{"other":"dinaarka Tunisiya"},"symbol":"TND","narrow":"TND"},"TOP":{"displayName":{"other":"ba’angada Tonga"},"symbol":"TOP","narrow":"T$"},"TPE":{"displayName":{"other":"TPE"},"symbol":"TPE","narrow":"TPE"},"TRL":{"displayName":{"other":"TRL"},"symbol":"TRL","narrow":"TRL"},"TRY":{"displayName":{"other":"liirada Turkiga"},"symbol":"TRY","narrow":"₺"},"TTD":{"displayName":{"other":"doolarada Tirinidad iyo Tobago","one":"doolarka Tirinidad iyo Tobago"},"symbol":"TTD","narrow":"$"},"TWD":{"displayName":{"other":"doolarada Taywaanta Cusub","one":"doolarka Taywaanta Cusub"},"symbol":"NT$","narrow":"$"},"TZS":{"displayName":{"other":"Shilingka Tansaaniya"},"symbol":"TZS","narrow":"TZS"},"UAH":{"displayName":{"other":"hirfiniyada Yukreeyn"},"symbol":"UAH","narrow":"₴"},"UAK":{"displayName":{"other":"UAK"},"symbol":"UAK","narrow":"UAK"},"UGS":{"displayName":{"other":"UGS"},"symbol":"UGS","narrow":"UGS"},"UGX":{"displayName":{"other":"shilingka Yugandha"},"symbol":"UGX","narrow":"UGX"},"USD":{"displayName":{"other":"doolarada Mareeykanka","one":"doolarka Mareeykanka"},"symbol":"US$","narrow":"$"},"USN":{"displayName":{"other":"USN"},"symbol":"USN","narrow":"USN"},"USS":{"displayName":{"other":"USS"},"symbol":"USS","narrow":"USS"},"UYI":{"displayName":{"other":"UYI"},"symbol":"UYI","narrow":"UYI"},"UYP":{"displayName":{"other":"UYP"},"symbol":"UYP","narrow":"UYP"},"UYU":{"displayName":{"other":"Beesada Urugway"},"symbol":"UYU","narrow":"$"},"UYW":{"displayName":{"other":"UYW"},"symbol":"UYW","narrow":"UYW"},"UZS":{"displayName":{"other":"somta Usbekistan"},"symbol":"UZS","narrow":"UZS"},"VEB":{"displayName":{"other":"VEB"},"symbol":"VEB","narrow":"VEB"},"VEF":{"displayName":{"other":"Bolifar Fenesuala (2008–2018)"},"symbol":"VEF","narrow":"Bs"},"VES":{"displayName":{"other":"Bolifarada Fenesuwela"},"symbol":"VES","narrow":"VES"},"VND":{"displayName":{"other":"dongta Fitnaam"},"symbol":"₫","narrow":"₫"},"VNN":{"displayName":{"other":"VNN"},"symbol":"VNN","narrow":"VNN"},"VUV":{"displayName":{"other":"fatu Fanuatu"},"symbol":"VUV","narrow":"VUV"},"WST":{"displayName":{"other":"tala Samao"},"symbol":"WST","narrow":"WST"},"XAF":{"displayName":{"other":"faranka CFA ee Bartamaha Afrika"},"symbol":"FCFA","narrow":"FCFA"},"XAG":{"displayName":{"other":"XAG"},"symbol":"XAG","narrow":"XAG"},"XAU":{"displayName":{"other":"XAU"},"symbol":"XAU","narrow":"XAU"},"XBA":{"displayName":{"other":"XBA"},"symbol":"XBA","narrow":"XBA"},"XBB":{"displayName":{"other":"XBB"},"symbol":"XBB","narrow":"XBB"},"XBC":{"displayName":{"other":"XBC"},"symbol":"XBC","narrow":"XBC"},"XBD":{"displayName":{"other":"XBD"},"symbol":"XBD","narrow":"XBD"},"XCD":{"displayName":{"other":"doolarada Iist Kaaribyan","one":"doolarka Iist Kaaribyan"},"symbol":"EC$","narrow":"$"},"XDR":{"displayName":{"other":"XDR"},"symbol":"XDR","narrow":"XDR"},"XEU":{"displayName":{"other":"XEU"},"symbol":"XEU","narrow":"XEU"},"XFO":{"displayName":{"other":"XFO"},"symbol":"XFO","narrow":"XFO"},"XFU":{"displayName":{"other":"XFU"},"symbol":"XFU","narrow":"XFU"},"XOF":{"displayName":{"other":"faranka CFA Galbeedka Afrika"},"symbol":"CFA","narrow":"CFA"},"XPD":{"displayName":{"other":"XPD"},"symbol":"XPD","narrow":"XPD"},"XPF":{"displayName":{"other":"Faranka CFP"},"symbol":"CFPF","narrow":"CFPF"},"XPT":{"displayName":{"other":"XPT"},"symbol":"XPT","narrow":"XPT"},"XRE":{"displayName":{"other":"XRE"},"symbol":"XRE","narrow":"XRE"},"XSU":{"displayName":{"other":"XSU"},"symbol":"XSU","narrow":"XSU"},"XTS":{"displayName":{"other":"XTS"},"symbol":"XTS","narrow":"XTS"},"XUA":{"displayName":{"other":"XUA"},"symbol":"XUA","narrow":"XUA"},"XXX":{"displayName":{"other":"(Lacag aan la aqoon)","one":"(halbeeg lacag aan la aqoon)"},"symbol":"¤","narrow":"¤"},"YDD":{"displayName":{"other":"YDD"},"symbol":"YDD","narrow":"YDD"},"YER":{"displayName":{"other":"riyaalka Yemen"},"symbol":"YER","narrow":"YER"},"YUD":{"displayName":{"other":"YUD"},"symbol":"YUD","narrow":"YUD"},"YUM":{"displayName":{"other":"YUM"},"symbol":"YUM","narrow":"YUM"},"YUN":{"displayName":{"other":"YUN"},"symbol":"YUN","narrow":"YUN"},"YUR":{"displayName":{"other":"YUR"},"symbol":"YUR","narrow":"YUR"},"ZAL":{"displayName":{"other":"ZAL"},"symbol":"ZAL","narrow":"ZAL"},"ZAR":{"displayName":{"other":"randka Koonfur Afrika"},"symbol":"ZAR","narrow":"R"},"ZMK":{"displayName":{"other":"ZMK"},"symbol":"ZMK","narrow":"ZMK"},"ZMW":{"displayName":{"other":"Kawajada Sambiya","one":"Kawaja Sambiya"},"symbol":"ZMW","narrow":"ZK"},"ZRN":{"displayName":{"other":"ZRN"},"symbol":"ZRN","narrow":"ZRN"},"ZRZ":{"displayName":{"other":"ZRZ"},"symbol":"ZRZ","narrow":"ZRZ"},"ZWD":{"displayName":{"other":"ZWD"},"symbol":"ZWD","narrow":"ZWD"},"ZWL":{"displayName":{"other":"ZWL"},"symbol":"ZWL","narrow":"ZWL"},"ZWR":{"displayName":{"other":"ZWR"},"symbol":"ZWR","narrow":"ZWR"}},"numbers":{"nu":["latn"],"symbols":{"latn":{"decimal":".","group":",","list":";","percentSign":"%","plusSign":"+","minusSign":"-","exponential":"E","superscriptingExponent":"×","perMille":"‰","infinity":"∞","nan":"MaL","timeSeparator":":"}},"percent":{"latn":"#,##0%"},"decimal":{"latn":{"standard":"#,##0.###","long":{"1000":{"other":"0 Kun"},"10000":{"other":"00 Kun"},"100000":{"other":"000 Kun"},"1000000":{"other":"0 Milyan"},"10000000":{"other":"00 Milyan"},"100000000":{"other":"000 Milyan"},"1000000000":{"other":"0 Bilyan"},"10000000000":{"other":"00 Bilyan"},"100000000000":{"other":"000 Bilyan"},"1000000000000":{"other":"0 Tirilyan"},"10000000000000":{"other":"00 Tirilyan"},"100000000000000":{"other":"000 Tirilyan"}},"short":{"1000":{"other":"0K"},"10000":{"other":"00K"},"100000":{"other":"000K"},"1000000":{"other":"0M"},"10000000":{"other":"00M"},"100000000":{"other":"000M"},"1000000000":{"other":"0B"},"10000000000":{"other":"00B"},"100000000000":{"other":"000B"},"1000000000000":{"other":"0T"},"10000000000000":{"other":"00T"},"100000000000000":{"other":"000T"}}}},"currency":{"latn":{"currencySpacing":{"beforeInsertBetween":" ","afterInsertBetween":" "},"standard":"¤#,##0.00","accounting":"¤#,##0.00;(¤#,##0.00)","unitPattern":"{0} {1}","short":{"1000":{"other":"¤0K"},"10000":{"other":"¤00K"},"100000":{"other":"¤000K"},"1000000":{"other":"¤0M"},"10000000":{"other":"¤00M"},"100000000":{"other":"¤000M"},"1000000000":{"other":"¤0B"},"10000000000":{"other":"¤00B"},"100000000000":{"other":"¤000B"},"1000000000000":{"other":"¤0T"},"10000000000000":{"other":"¤00T"},"100000000000000":{"other":"¤000T"}}}}},"nu":["latn"]}},"availableLocales":["so-DJ"]} ) }
import * as constants from './constants'; import * as actions from './balance'; it('creates an action to set the balance', () => { const balance = 0; const expectedAction = { type: constants.SET_BALANCE, balance }; expect(actions.setBalance(balance)).toEqual(expectedAction); }); it('creates an action to deposit into the balance', () => { const deposit = 10; const expectedAction = { type: constants.DEPOSIT, deposit }; expect(actions.deposit(deposit)).toEqual(expectedAction); }); it('creates an action to withdraw from balance', () => { const withdraw = 10; const expectedAction = { type: constants.WITHDRAW, withdraw }; expect(actions.withdraw(withdraw)).toEqual(expectedAction); });
require('dotenv').config(); const { readFileSync, unlinkSync } = require('fs'); const { argv } = require('yargs'); const FSCredStore = require('../utils/fs-cred-store'); const MongoCredStore = require('../utils/mongo-cred-store') const { browserCommands } = require('./custom-commands'); const { browserConf } = require('./browser-config'); const { keysIn } = require('lodash'); const selectedBrowser = argv.browser ? browserConf[argv.browser] : browserConf['chrome']; const specsToRun = () => { if (argv.file) { return [argv.file]; } if (argv.spec) { return argv.spec.split(','); } if (argv.dir || argv.d) { return [`./e2e/specs/${argv.dir || argv.d}/**/*.spec.js`] } if (argv.smoke) { return ['./e2e/specs/**/smoke-*spec.js']; } return ['./e2e/specs/**/*.js']; } const specs = specsToRun(); const selectedReporters = argv.log ? ['spec', 'junit'] : ['spec']; const getRunnerCount = () => { const userCount = keysIn(process.env).filter(users => users.includes('MANAGER_USER')).length; const specsCount = specs.length; const isSuite = specs[0].includes('**'); const isParallelRunner = (isSuite || specsCount > 1) && userCount > 1; return isParallelRunner ? userCount : 1; } const parallelRunners = getRunnerCount(); // NOTE: credStore provides a promise-based API. In order to work correctly with WDIO, any calls in // lifecycle methods *other than* onPrepare and onComplete should be wrapped using WDIO's browser.call // method. This blocks execution until any promises within the function passed to call are resolved. // See more at: // https://webdriver.io/docs/api/browser/call.html // const credStores = { fs: new FSCredStore('./e2e/creds.js'), mongodb: new MongoCredStore('mongodb'), mongolocal: new MongoCredStore('localhost') }; let CRED_STORE_MODE = process.env.CRED_STORE_MODE ? process.env.CRED_STORE_MODE : 'fs'; if (!(CRED_STORE_MODE in credStores)) { let msg = "CRED_STORE_MODE must be one of: "; for (cs in credStores) { msg += cs + " "; } throw new Error(msg); } const credStore = credStores[CRED_STORE_MODE]; exports.config = { // Selenium Host/Port host: process.env.DOCKER ? 'selenium' : 'localhost', port: 4444, // // ================== // Specify Test Files // ================== // Define which test specs should run. The pattern is relative to the directory // from which `wdio` was called. Notice that, if you are calling `wdio` from an // NPM script (see https://docs.npmjs.com/cli/run-script) then the current working // directory is where your package.json resides, so `wdio` will be called from there. // specs: specs, // Patterns to exclude. exclude: [ './e2e/specs/accessibility/*.spec.js' // 'path/to/excluded/files' ], // // ============ // Capabilities // ============ // Define your capabilities here. WebdriverIO can run multiple capabilities at the same // time. Depending on the number of capabilities, WebdriverIO launches several test // sessions. Within your capabilities you can overwrite the spec and exclude options in // order to group specific specs to a specific capability. // // First, you can define how many instances should be started at the same time. Let's // say you have 3 different capabilities (Chrome, Firefox, and Safari) and you have // set maxInstances to 1; wdio will spawn 3 processes. Therefore, if you have 10 spec // files and you set maxInstances to 10, all spec files will get tested at the same time // and 30 processes will get spawned. The property handles how many capabilities // from the same test should run tests. // maxInstances: parallelRunners, // // If you have trouble getting all important capabilities together, check out the // Sauce Labs platform configurator - a great tool to configure your capabilities: // https://docs.saucelabs.com/reference/platforms-configurator // capabilities: [selectedBrowser], // // =================== // Test Configurations // =================== // Define all options that are relevant for the WebdriverIO instance here // // By default WebdriverIO commands are executed in a synchronous way using // the wdio-sync package. If you still want to run your tests in an async way // e.g. using promises you can set the sync option to false. sync: true, // // Level of logging verbosity: silent | verbose | command | data | result | error logLevel: argv.logLevel ? argv.logLevel : 'error', // // Enables colors for log output. coloredLogs: true, // // Warns when a deprecated command is used deprecationWarnings: false, // // If you only want to run your tests until a specific amount of tests have failed use // bail (default is 0 - don't bail, run all tests). bail: 100, // // Saves a screenshot to a given path if a command fails. // screenshotPath: './e2e/errorShots/', // // Set a base URL in order to shorten url command calls. If your `url` parameter starts // with `/`, the base url gets prepended, not including the path portion of your baseUrl. // If your `url` parameter starts without a scheme or `/` (like `some/path`), the base url // gets prepended directly. baseUrl: process.env.REACT_APP_APP_ROOT, // // Default timeout for all waitFor* commands. waitforTimeout: process.env.DOCKER || process.env.BROWSERSTACK_USERNAME ? 30000 : 10000, // // Default timeout in milliseconds for request // if Selenium Grid doesn't send response connectionRetryTimeout: 90000, // // Default request retries count connectionRetryCount: 10, // // Initialize the browser instance with a WebdriverIO plugin. The object should have the // plugin name as key and the desired plugin options as properties. Make sure you have // the plugin installed before running any tests. The following plugins are currently // available: // WebdriverCSS: https://github.com/webdriverio/webdrivercss // WebdriverRTC: https://github.com/webdriverio/webdriverrtc // Browserevent: https://github.com/webdriverio/browserevent // plugins: { // webdrivercss: { // screenshotRoot: 'my-shots', // failedComparisonsRoot: 'diffs', // misMatchTolerance: 0.05, // screenWidth: [320,480,640,1024] // }, // webdriverrtc: {}, // browserevent: {} // }, // // Test runner services // Services take over a specific job you don't want to take care of. They enhance // your test setup with almost no effort. Unlike plugins, they don't add new // commands. Instead, they hook themselves up into the test process. // services: [],// // Framework you want to run your specs with. // The following are supported: Mocha, Jasmine, and Cucumber // see also: http://webdriver.io/guide/testrunner/frameworks.html // // Make sure you have the wdio adapter package for the specific framework installed // before running any tests. framework: 'jasmine', // // Test reporter for stdout. // The only one supported by default is 'dot' // see also: http://webdriver.io/guide/reporters/dot.html reporters: selectedReporters, reporterOptions: { junit: { outputDir: './e2e/test-results' } }, // // Options to be passed to Jasmine. jasmineNodeOpts: { // // Jasmine default timeout defaultTimeoutInterval: 60000 * 10, // // The Jasmine framework allows interception of each assertion in order to log the state of the application // or website depending on the result. For example, it is pretty handy to take a screenshot every time // an assertion fails. expectationResultHandler: function(passed, assertion) { // do something }, stopOnSpecFailure: true, }, mountebankConfig: { proxyConfig: { imposterPort: '8088', imposterProtocol: 'https', imposterName: 'Linode-API', proxyHost: 'https://api.linode.com/v4', mutualAuth: true, } }, testUser: '', // SET IN THE BEFORE HOOK PRIOR TO EACH TEST // // ===== // Hooks // ===== // WebdriverIO provides several hooks you can use to interfere with the test process in order to enhance // it and to build services around it. You can either apply a single function or an array of // methods to it. If one of them returns with a promise, WebdriverIO will wait until that promise got // resolved to continue. /** * Gets executed once before all workers get launched. * @param {Object} config wdio configuration object * @param {Array.<Object>} capabilities list of capabilities details */ onPrepare: function (config, capabilities, user) { if ((parallelRunners > 1) && (CRED_STORE_MODE === 'fs')) { throw new Error("***** Can't use filesystem cred store when parallelRunners > 1.\n***** Set CRED_STORE_MODE=mongolocal in .env and launch mongodb by running: docker run -d -p 27017:27017 mongo"); } // Generate temporary test credentials and store for use across tests credStore.generateCreds(config, parallelRunners) .catch((e) => { // if we got here, most likely mongo isn't running locally if (CRED_STORE_MODE === 'mongolocal') { console.error("***** MAKE SURE MONGO IS RUNNING, do: docker run -d -p 27017:27017 mongo *****"); } }); }, /** * Gets executed just before initialising the webdriver session and test framework. It allows you * to manipulate configurations depending on the capability or spec. * @param {Object} config wdio configuration object * @param {Array.<Object>} capabilities list of capabilities details * @param {Array.<String>} specs List of spec file paths that are to be run */ // beforeSession: function (config, capabilities, specs) { // }, /** * Gets executed before test execution begins. At this point you can access to all global * variables like `browser`. It is the perfect place to define custom commands. * @param {Array.<Object>} capabilities list of capabilities details * @param {Array.<String>} specs List of spec file paths that are to be run */ before: function (capabilities, specs) { // Load up our custom commands require('@babel/register'); browserCommands(); // Timecount needed to generate unqiue timestamp values for mocks global.timeCount = 0; if (argv.record) { browser.loadProxyImposter(browser.options.mountebankConfig.proxyConfig); } if (argv.replay) { const file = specs[0].replace('.js', '-stub.json'); const imposter = JSON.parse(readFileSync(file)); browser.loadImposter(imposter); } if (browser.options.desiredCapabilities.browserName.includes('chrome')) { browser.timeouts('page load', process.env.DOCKER ? 30000 : 20000); } if (browser.options.desiredCapabilities.browserName.includes('edge')) { browser.windowHandleMaximize(); } // inject browser object into credstore for login and a few other functions credStore.setBrowser(browser); // inject credStore into browser so it can be easily accessed from test cases // and utility code browser.credStore = credStore; let creds = null; browser.call(() => { return credStore.checkoutCreds(specs[0]) .then((testCreds) => { creds = testCreds; }).catch((err) => console.log(err)); }); credStore.login(creds.username, creds.password, false); }, /** * Runs before a WebdriverIO command gets executed. * @param {String} commandName hook command name * @param {Array} args arguments that command would receive */ // beforeCommand: function (commandName, args) { // }, /** * Hook that gets executed before the suite starts * @param {Object} suite suite details */ /*beforeSuite: function (suite) { // Click beta notice button browser.waitForVisible('[data-qa-dialog-content] button'); browser.click('[data-qa-dialog-content] button'); },*/ /** * Function to be executed before a test (in Mocha/Jasmine) or a step (in Cucumber) starts. * @param {Object} test test details */ // beforeTest: function (test) { // }, /** * Hook that gets executed _before_ a hook within the suite starts (e.g. runs before calling * beforeEach in Mocha) */ // beforeHook: function () { // }, /** * Hook that gets executed _after_ a hook within the suite ends (e.g. runs after calling * afterEach in Mocha) */ // afterHook: function () { // }, /** * Function to be executed after a test (in Mocha/Jasmine) or a step (in Cucumber) ends. * @param {Object} test test details */ // afterTest: function (test) { // }, /** * Hook that gets executed after the suite has ended * @param {Object} suite suite details */ // afterSuite: function (suite) { // }, /** * Runs after a WebdriverIO command gets executed * @param {String} commandName hook command name * @param {Array} args arguments that command would receive * @param {Number} result 0 - command success, 1 - command error * @param {Object} error error object if any */ // afterCommand: function (commandName, args, result, error) { // }, /** * Gets executed after all tests are done. You still have access to all global variables from * the test. * @param {Number} result 0 - test pass, 1 - test fail * @param {Array.<Object>} capabilities list of capabilities details * @param {Array.<String>} specs List of spec file paths that ran */ after: function (result, capabilities, specs) { if (argv.record) { const recordingFile = specs[0].replace('.js', '-stub.json'); browser.getImposters(true, recordingFile); browser.deleteImposters(); } if (argv.replay) { browser.deleteImposters(); } // Set "inUse:false" on the account under test in the credentials file browser.call( () => credStore.checkinCreds(specs[0]).then((creds) => creds) ); }, /** * Gets executed right after terminating the webdriver session. * @param {Object} config wdio configuration object * @param {Array.<Object>} capabilities list of capabilities details * @param {Array.<String>} specs List of spec file paths that ran */ // afterSession: function (config, capabilities, specs) { // }, /** * Gets executed after all workers got shut down and the process is about to exit. * @param {Object} exitCode 0 - success, 1 - fail * @param {Object} config wdio configuration object * @param {Array.<Object>} capabilities list of capabilities details */ onComplete: function(exitCode, config, capabilities) { /* delete all data created during the test and remove test credentials from the underlying store */ return credStore.cleanupAccounts(); } }
YUI.add("base-base",function(b){var g=b.Lang,e="destroy",i="init",h="bubbleTargets",c="_bubbleTargets",j=b.BaseCore,f=b.AttributeCore,a=b.Attribute;function d(){j.apply(this,arguments);}d._ATTR_CFG=a._ATTR_CFG.concat("cloneDefaultValue");d._ATTR_CFG_HASH=b.Array.hash(d._ATTR_CFG);d.NAME="base";d.ATTRS=f.prototype._protectAttrs(j.ATTRS);d.prototype={_initBase:function(k){this._eventPrefix=this.constructor.EVENT_PREFIX||this.constructor.NAME;b.BaseCore.prototype._initBase.call(this,k);},_initAttribute:function(k){this._attrCfgHash=d._ATTR_CFG_HASH;a.call(this);this._yuievt.config.prefix=this._eventPrefix;},init:function(k){this.publish(i,{queuable:false,fireOnce:true,defaultTargetOnly:true,defaultFn:this._defInitFn});this._preInitEventCfg(k);this.fire(i,{cfg:k});return this;},_preInitEventCfg:function(m){if(m){if(m.on){this.on(m.on);}if(m.after){this.after(m.after);}}var n,k,p,o=(m&&h in m);if(o||c in this){p=o?(m&&m.bubbleTargets):this._bubbleTargets;if(g.isArray(p)){for(n=0,k=p.length;n<k;n++){this.addTarget(p[n]);}}else{if(p){this.addTarget(p);}}}},destroy:function(){this.publish(e,{queuable:false,fireOnce:true,defaultTargetOnly:true,defaultFn:this._defDestroyFn});this.fire(e);this.detachAll();return this;},_defInitFn:function(k){this._baseInit(k.cfg);},_defDestroyFn:function(k){this._baseDestroy(k.cfg);}};b.mix(d,a,false,null,1);b.mix(d,j,false,null,1);d.prototype.constructor=d;b.Base=d;},"@VERSION@",{requires:["base-core","attribute-base"]});
"use strict"; var configParser_1 = require('./configParser'); /** * The taskScheduler keeps track of the spec files that needs to run next * and which task is running what. */ var TaskQueue = (function () { // A queue of specs for a particular capacity function TaskQueue(capabilities, specLists) { this.capabilities = capabilities; this.specLists = specLists; this.numRunningInstances = 0; this.specsIndex = 0; this.maxInstance = capabilities.maxInstances || 1; } return TaskQueue; }()); exports.TaskQueue = TaskQueue; var TaskScheduler = (function () { /** * A scheduler to keep track of specs that need running and their associated * capabilities. It will suggest a task (combination of capabilities and spec) * to run while observing the following config rules: * multiCapabilities, shardTestFiles, and maxInstance. * Precondition: multiCapabilities is a non-empty array * (capabilities and getCapabilities will both be ignored) * * @constructor * @param {Object} config parsed from the config file */ function TaskScheduler(config) { this.config = config; var excludes = configParser_1.ConfigParser.resolveFilePatterns(config.exclude, true, config.configDir); var allSpecs = configParser_1.ConfigParser .resolveFilePatterns(configParser_1.ConfigParser.getSpecs(config), false, config.configDir) .filter(function (path) { return excludes.indexOf(path) < 0; }); var taskQueues = []; config.multiCapabilities.forEach(function (capabilities) { var capabilitiesSpecs = allSpecs; if (capabilities.specs) { var capabilitiesSpecificSpecs = configParser_1.ConfigParser.resolveFilePatterns(capabilities.specs, false, config.configDir); capabilitiesSpecs = capabilitiesSpecs.concat(capabilitiesSpecificSpecs); } if (capabilities.exclude) { var capabilitiesSpecExcludes_1 = configParser_1.ConfigParser.resolveFilePatterns(capabilities.exclude, true, config.configDir); capabilitiesSpecs = capabilitiesSpecs.filter(function (path) { return capabilitiesSpecExcludes_1.indexOf(path) < 0; }); } var specLists = []; // If we shard, we return an array of one element arrays, each containing // the spec file. If we don't shard, we return an one element array // containing an array of all the spec files if (capabilities.shardTestFiles) { capabilitiesSpecs.forEach(function (spec) { specLists.push([spec]); }); } else { specLists.push(capabilitiesSpecs); } capabilities.count = capabilities.count || 1; for (var i = 0; i < capabilities.count; ++i) { taskQueues.push(new TaskQueue(capabilities, specLists)); } }); this.taskQueues = taskQueues; this.rotationIndex = 0; // Helps suggestions to rotate amongst capabilities } /** * Get the next task that is allowed to run without going over maxInstance. * * @return {{capabilities: Object, specs: Array.<string>, taskId: string, * done: function()}} */ TaskScheduler.prototype.nextTask = function () { for (var i = 0; i < this.taskQueues.length; ++i) { var rotatedIndex = ((i + this.rotationIndex) % this.taskQueues.length); var queue = this.taskQueues[rotatedIndex]; if (queue.numRunningInstances < queue.maxInstance && queue.specsIndex < queue.specLists.length) { this.rotationIndex = rotatedIndex + 1; ++queue.numRunningInstances; var taskId = '' + rotatedIndex + 1; if (queue.specLists.length > 1) { taskId += '-' + queue.specsIndex; } var specs = queue.specLists[queue.specsIndex]; ++queue.specsIndex; return { capabilities: queue.capabilities, specs: specs, taskId: taskId, done: function () { --queue.numRunningInstances; } }; } } return null; }; /** * Get the number of tasks left to run or are currently running. * * @return {number} */ TaskScheduler.prototype.numTasksOutstanding = function () { var count = 0; this.taskQueues.forEach(function (queue) { count += queue.numRunningInstances + (queue.specLists.length - queue.specsIndex); }); return count; }; /** * Get maximum number of concurrent tasks required/permitted. * * @return {number} */ TaskScheduler.prototype.maxConcurrentTasks = function () { if (this.config.maxSessions && this.config.maxSessions > 0) { return this.config.maxSessions; } else { var count = 0; this.taskQueues.forEach(function (queue) { count += Math.min(queue.maxInstance, queue.specLists.length); }); return count; } }; /** * Returns number of tasks currently running. * * @return {number} */ TaskScheduler.prototype.countActiveTasks = function () { var count = 0; this.taskQueues.forEach(function (queue) { count += queue.numRunningInstances; }); return count; }; return TaskScheduler; }()); exports.TaskScheduler = TaskScheduler;
// Test mongos implementation of time-limited operations: verify that mongos correctly forwards max // time to shards, and that mongos correctly times out max time sharded getmore operations (which // are run in series on shards). // // Note that mongos does not time out commands or query ops (which remains responsibility of mongod, // pending development of an interrupt framework for mongos). var st = new ShardingTest({shards: 2}); st.stopBalancer(); var mongos = st.s0; var shards = [st.shard0, st.shard1]; var coll = mongos.getCollection("foo.bar"); var admin = mongos.getDB("admin"); var cursor; // Helper function to configure "maxTimeAlwaysTimeOut" fail point on shards, which forces mongod to // throw if it receives an operation with a max time. See fail point declaration for complete // description. var configureMaxTimeAlwaysTimeOut = function(mode) { assert.commandWorked(shards[0].getDB("admin").runCommand( {configureFailPoint: "maxTimeAlwaysTimeOut", mode: mode})); assert.commandWorked(shards[1].getDB("admin").runCommand( {configureFailPoint: "maxTimeAlwaysTimeOut", mode: mode})); } // Helper function to configure "maxTimeAlwaysTimeOut" fail point on shards, which prohibits mongod // from enforcing time limits. See fail point declaration for complete description. var configureMaxTimeNeverTimeOut = function(mode) { assert.commandWorked(shards[0].getDB("admin").runCommand( {configureFailPoint: "maxTimeNeverTimeOut", mode: mode})); assert.commandWorked(shards[1].getDB("admin").runCommand( {configureFailPoint: "maxTimeNeverTimeOut", mode: mode})); } // // Pre-split collection: shard 0 takes {_id: {$lt: 0}}, shard 1 takes {_id: {$gte: 0}}. // assert.commandWorked(admin.runCommand({enableSharding: coll.getDB().getName()})); assert.commandWorked(admin.runCommand({movePrimary: coll.getDB().getName(), to: "shard0000"})); assert.commandWorked(admin.runCommand({shardCollection: coll.getFullName(), key: {_id: 1}})); assert.commandWorked(admin.runCommand({split: coll.getFullName(), middle: {_id: 0}})); assert.commandWorked(admin.runCommand({moveChunk: coll.getFullName(), find: {_id: 0}, to: "shard0001"})); // // Insert 100 documents into sharded collection, such that each shard owns 50. // for (i=-50; i<50; i++) { coll.insert({_id: i}); } assert.eq(null, coll.getDB().getLastError()); assert.eq(50, shards[0].getCollection(coll.getFullName()).count()); assert.eq(50, shards[1].getCollection(coll.getFullName()).count()); // // Test that mongos correctly forwards max time to shards for sharded queries. Uses // maxTimeAlwaysTimeOut to ensure mongod throws if it receives a max time. // // Positive test. configureMaxTimeAlwaysTimeOut("alwaysOn"); cursor = coll.find(); cursor.maxTimeMS(60*1000); assert.throws(function() { cursor.next() }, [], "expected query to fail in mongod due to maxTimeAlwaysTimeOut fail point"); // Negative test. configureMaxTimeAlwaysTimeOut("off"); cursor = coll.find(); cursor.maxTimeMS(60*1000); assert.doesNotThrow(function() { cursor.next() }, [], "expected query to not hit time limit in mongod"); // // Test that mongos correctly times out max time sharded getmore operations. Uses // maxTimeNeverTimeOut to ensure mongod doesn't enforce a time limit. // configureMaxTimeNeverTimeOut("alwaysOn"); // Positive test. ~10s operation, 5s limit. The operation takes ~10s because each shard processes // 25 batches of ~200ms each, and mongos never runs getmore in parallel on shards. cursor = coll.find({$where: function() { sleep(100); return true; }}); cursor.batchSize(2); cursor.maxTimeMS(5*1000); assert.doesNotThrow(function() { cursor.next(); }, [], "did not expect mongos to time out first batch of query"); assert.throws(function() { cursor.itcount(); }, [], "expected mongos to abort getmore due to time limit"); // Negative test. Same as above (~10s operation), with a high (1-day) limit. cursor = coll.find({$where: function() { sleep(100); return true; }}); cursor.batchSize(2); cursor.maxTimeMS(1000*60*60*24); assert.doesNotThrow(function() { cursor.next(); }, [], "did not expect mongos to time out first batch of query"); assert.doesNotThrow(function() { cursor.itcount(); }, [], "did not expect getmore ops to hit the time limit"); configureMaxTimeNeverTimeOut("off"); // // Test that mongos correctly forwards max time to shards for sharded commands. Uses // maxTimeAlwaysTimeOut to ensure mongod throws if it receives a max time. // // Positive test for "validate". configureMaxTimeAlwaysTimeOut("alwaysOn"); assert.commandFailed(coll.runCommand("validate", {maxTimeMS: 60*1000}), "expected validate to fail in mongod due to maxTimeAlwaysTimeOut fail point"); // Negative test for "validate". configureMaxTimeAlwaysTimeOut("off"); assert.commandWorked(coll.runCommand("validate", {maxTimeMS: 60*1000}), "expected validate to not hit time limit in mongod"); // Positive test for "moveChunk". configureMaxTimeAlwaysTimeOut("alwaysOn"); assert.commandFailed(admin.runCommand({moveChunk: coll.getFullName(), find: {_id: 0}, to: "shard0000", maxTimeMS: 1000*60*60*24}), "expected moveChunk to fail in mongod due to maxTimeAlwaysTimeOut fail point"); // Negative test for "moveChunk". configureMaxTimeAlwaysTimeOut("off"); assert.commandWorked(admin.runCommand({moveChunk: coll.getFullName(), find: {_id: 0}, to: "shard0000", maxTimeMS: 1000*60*60*24}), "expected moveChunk to not hit time limit in mongod"); // TODO Test additional commmands. st.stop();
import { get } from 'lodash'; import React from 'react'; import { connect } from 'react-redux'; // Components import { Item, Select } from 'components/Form'; // Entities import { getTablespaceList } from 'entities/tablespaces/selector'; const EditTablespace = ({ currentTablespace, name, tablespaces, value, }) => ( <Select format={(hash: string) => hash && tablespaces .filter(({ hash: tablespaceHash }) => tablespaceHash === hash) .map(({ hash, name }) => ({ label: name, value: hash, }))[0]} label="edit_tablespace_label" name={name} parse={(tablespace: Object) => get(tablespace, 'value')} placeholder="edit_tablespace_placeholder" > {({ inputValue, onClick, value = [] }) => tablespaces .filter(({ name }) => name.toLowerCase().indexOf(inputValue) > -1) .map(({ hash, name }) => ( <Item key={hash} label={name} onClick={onClick} value={hash} /> )) } </Select> ); const mapStateToProps = (state: Object, { value }): Object => ({ tablespaces: getTablespaceList(state), }); export default connect(mapStateToProps)(EditTablespace);
import setup from '../setup-base'; import desired from './desired'; import _ from 'lodash'; describe('testapp - wait-for-apps', function () { let test = function (desc, script, checkAfter) { script = `env.currentTest = "${desc}"; ${script}`; describe(desc, function () { let session = setup(this, _.defaults({waitForAppScript: script}, desired)); let driver = session.driver; it('should work', async function () { let el = await driver.findElement('class name', 'UIAButton'); el.should.exist; if (checkAfter) { (await driver.execute('env.currentTest')).should.equal(desc); } }); }); }; test('just waiting', '$.delay(5000); true;', true); test('waiting for one element', 'target.elements().length > 0;', true); test('bad script', 'blagimarg!!;', false); });
module.exports = { 'secret' : 'secret', 'dbURI' : 'mongodb://localhost:27017/myproject' };
import * as Error from '../error'; import * as Ast from './ast'; import * as TypeAst from './typeAst'; export const createScope = () => { return {}; }; export const createChildScope = (parentScope) => { return Object.create(parentScope); }; export const set = (scope, name, value) => { scope[name] = value; }; export const get = (scope, name) => { const v = scope[name]; if (v === undefined) { throw Error.create(Error.types.undefVar, `No variable with that name: ${name}`); } else { return v; } }; /** * Type class and instance definition functions **/ export const instance = (scope, func) => { scope[func.name] = scope[func.name] || []; scope[func.name].push(func); }; export const typeClass = () => { }; export const addFF = (scope, name, func, argTypes) => { let types = []; if (argTypes === undefined) { let i; for (i = 0; i < func.length; i += 1) { types.push(TypeAst.Generic(String(i))); } } else { types = argTypes; } scope[name] = Ast.BuiltIn(func, types); };
/**! @license handlebars v4.1.0 Copyright (C) 2011-2017 by Yehuda Katz 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. */ !function(a,b){"object"==typeof exports&&"object"==typeof module?module.exports=b():"function"==typeof define&&define.amd?define([],b):"object"==typeof exports?exports.Handlebars=b():a.Handlebars=b()}(this,function(){return function(a){function b(d){if(c[d])return c[d].exports;var e=c[d]={exports:{},id:d,loaded:!1};return a[d].call(e.exports,e,e.exports,b),e.loaded=!0,e.exports}var c={};return b.m=a,b.c=c,b.p="",b(0)}([function(a,b,c){"use strict";function d(){var a=new h.HandlebarsEnvironment;return n.extend(a,h),a.SafeString=j["default"],a.Exception=l["default"],a.Utils=n,a.escapeExpression=n.escapeExpression,a.VM=p,a.template=function(b){return p.template(b,a)},a}var e=c(1)["default"],f=c(2)["default"];b.__esModule=!0;var g=c(3),h=e(g),i=c(20),j=f(i),k=c(5),l=f(k),m=c(4),n=e(m),o=c(21),p=e(o),q=c(33),r=f(q),s=d();s.create=d,r["default"](s),s["default"]=s,b["default"]=s,a.exports=b["default"]},function(a,b){"use strict";b["default"]=function(a){if(a&&a.__esModule)return a;var b={};if(null!=a)for(var c in a)Object.prototype.hasOwnProperty.call(a,c)&&(b[c]=a[c]);return b["default"]=a,b},b.__esModule=!0},function(a,b){"use strict";b["default"]=function(a){return a&&a.__esModule?a:{"default":a}},b.__esModule=!0},function(a,b,c){"use strict";function d(a,b,c){this.helpers=a||{},this.partials=b||{},this.decorators=c||{},i.registerDefaultHelpers(this),j.registerDefaultDecorators(this)}var e=c(2)["default"];b.__esModule=!0,b.HandlebarsEnvironment=d;var f=c(4),g=c(5),h=e(g),i=c(9),j=c(17),k=c(19),l=e(k),m="4.1.0";b.VERSION=m;var n=7;b.COMPILER_REVISION=n;var o={1:"<= 1.0.rc.2",2:"== 1.0.0-rc.3",3:"== 1.0.0-rc.4",4:"== 1.x.x",5:"== 2.0.0-alpha.x",6:">= 2.0.0-beta.1",7:">= 4.0.0"};b.REVISION_CHANGES=o;var p="[object Object]";d.prototype={constructor:d,logger:l["default"],log:l["default"].log,registerHelper:function(a,b){if(f.toString.call(a)===p){if(b)throw new h["default"]("Arg not supported with multiple helpers");f.extend(this.helpers,a)}else this.helpers[a]=b},unregisterHelper:function(a){delete this.helpers[a]},registerPartial:function(a,b){if(f.toString.call(a)===p)f.extend(this.partials,a);else{if("undefined"==typeof b)throw new h["default"]('Attempting to register a partial called "'+a+'" as undefined');this.partials[a]=b}},unregisterPartial:function(a){delete this.partials[a]},registerDecorator:function(a,b){if(f.toString.call(a)===p){if(b)throw new h["default"]("Arg not supported with multiple decorators");f.extend(this.decorators,a)}else this.decorators[a]=b},unregisterDecorator:function(a){delete this.decorators[a]}};var q=l["default"].log;b.log=q,b.createFrame=f.createFrame,b.logger=l["default"]},function(a,b){"use strict";function c(a){return k[a]}function d(a){for(var b=1;b<arguments.length;b++)for(var c in arguments[b])Object.prototype.hasOwnProperty.call(arguments[b],c)&&(a[c]=arguments[b][c]);return a}function e(a,b){for(var c=0,d=a.length;c<d;c++)if(a[c]===b)return c;return-1}function f(a){if("string"!=typeof a){if(a&&a.toHTML)return a.toHTML();if(null==a)return"";if(!a)return a+"";a=""+a}return m.test(a)?a.replace(l,c):a}function g(a){return!a&&0!==a||!(!p(a)||0!==a.length)}function h(a){var b=d({},a);return b._parent=a,b}function i(a,b){return a.path=b,a}function j(a,b){return(a?a+".":"")+b}b.__esModule=!0,b.extend=d,b.indexOf=e,b.escapeExpression=f,b.isEmpty=g,b.createFrame=h,b.blockParams=i,b.appendContextPath=j;var k={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;","`":"&#x60;","=":"&#x3D;"},l=/[&<>"'`=]/g,m=/[&<>"'`=]/,n=Object.prototype.toString;b.toString=n;var o=function(a){return"function"==typeof a};o(/x/)&&(b.isFunction=o=function(a){return"function"==typeof a&&"[object Function]"===n.call(a)}),b.isFunction=o;var p=Array.isArray||function(a){return!(!a||"object"!=typeof a)&&"[object Array]"===n.call(a)};b.isArray=p},function(a,b,c){"use strict";function d(a,b){var c=b&&b.loc,g=void 0,h=void 0;c&&(g=c.start.line,h=c.start.column,a+=" - "+g+":"+h);for(var i=Error.prototype.constructor.call(this,a),j=0;j<f.length;j++)this[f[j]]=i[f[j]];Error.captureStackTrace&&Error.captureStackTrace(this,d);try{c&&(this.lineNumber=g,e?Object.defineProperty(this,"column",{value:h,enumerable:!0}):this.column=h)}catch(k){}}var e=c(6)["default"];b.__esModule=!0;var f=["description","fileName","lineNumber","message","name","number","stack"];d.prototype=new Error,b["default"]=d,a.exports=b["default"]},function(a,b,c){a.exports={"default":c(7),__esModule:!0}},function(a,b,c){var d=c(8);a.exports=function(a,b,c){return d.setDesc(a,b,c)}},function(a,b){var c=Object;a.exports={create:c.create,getProto:c.getPrototypeOf,isEnum:{}.propertyIsEnumerable,getDesc:c.getOwnPropertyDescriptor,setDesc:c.defineProperty,setDescs:c.defineProperties,getKeys:c.keys,getNames:c.getOwnPropertyNames,getSymbols:c.getOwnPropertySymbols,each:[].forEach}},function(a,b,c){"use strict";function d(a){g["default"](a),i["default"](a),k["default"](a),m["default"](a),o["default"](a),q["default"](a),s["default"](a)}var e=c(2)["default"];b.__esModule=!0,b.registerDefaultHelpers=d;var f=c(10),g=e(f),h=c(11),i=e(h),j=c(12),k=e(j),l=c(13),m=e(l),n=c(14),o=e(n),p=c(15),q=e(p),r=c(16),s=e(r)},function(a,b,c){"use strict";b.__esModule=!0;var d=c(4);b["default"]=function(a){a.registerHelper("blockHelperMissing",function(b,c){var e=c.inverse,f=c.fn;if(b===!0)return f(this);if(b===!1||null==b)return e(this);if(d.isArray(b))return b.length>0?(c.ids&&(c.ids=[c.name]),a.helpers.each(b,c)):e(this);if(c.data&&c.ids){var g=d.createFrame(c.data);g.contextPath=d.appendContextPath(c.data.contextPath,c.name),c={data:g}}return f(b,c)})},a.exports=b["default"]},function(a,b,c){"use strict";var d=c(2)["default"];b.__esModule=!0;var e=c(4),f=c(5),g=d(f);b["default"]=function(a){a.registerHelper("each",function(a,b){function c(b,c,f){j&&(j.key=b,j.index=c,j.first=0===c,j.last=!!f,k&&(j.contextPath=k+b)),i+=d(a[b],{data:j,blockParams:e.blockParams([a[b],b],[k+b,null])})}if(!b)throw new g["default"]("Must pass iterator to #each");var d=b.fn,f=b.inverse,h=0,i="",j=void 0,k=void 0;if(b.data&&b.ids&&(k=e.appendContextPath(b.data.contextPath,b.ids[0])+"."),e.isFunction(a)&&(a=a.call(this)),b.data&&(j=e.createFrame(b.data)),a&&"object"==typeof a)if(e.isArray(a))for(var l=a.length;h<l;h++)h in a&&c(h,h,h===a.length-1);else{var m=void 0;for(var n in a)a.hasOwnProperty(n)&&(void 0!==m&&c(m,h-1),m=n,h++);void 0!==m&&c(m,h-1,!0)}return 0===h&&(i=f(this)),i})},a.exports=b["default"]},function(a,b,c){"use strict";var d=c(2)["default"];b.__esModule=!0;var e=c(5),f=d(e);b["default"]=function(a){a.registerHelper("helperMissing",function(){if(1!==arguments.length)throw new f["default"]('Missing helper: "'+arguments[arguments.length-1].name+'"')})},a.exports=b["default"]},function(a,b,c){"use strict";b.__esModule=!0;var d=c(4);b["default"]=function(a){a.registerHelper("if",function(a,b){return d.isFunction(a)&&(a=a.call(this)),!b.hash.includeZero&&!a||d.isEmpty(a)?b.inverse(this):b.fn(this)}),a.registerHelper("unless",function(b,c){return a.helpers["if"].call(this,b,{fn:c.inverse,inverse:c.fn,hash:c.hash})})},a.exports=b["default"]},function(a,b){"use strict";b.__esModule=!0,b["default"]=function(a){a.registerHelper("log",function(){for(var b=[void 0],c=arguments[arguments.length-1],d=0;d<arguments.length-1;d++)b.push(arguments[d]);var e=1;null!=c.hash.level?e=c.hash.level:c.data&&null!=c.data.level&&(e=c.data.level),b[0]=e,a.log.apply(a,b)})},a.exports=b["default"]},function(a,b){"use strict";b.__esModule=!0,b["default"]=function(a){a.registerHelper("lookup",function(a,b){return a&&a[b]})},a.exports=b["default"]},function(a,b,c){"use strict";b.__esModule=!0;var d=c(4);b["default"]=function(a){a.registerHelper("with",function(a,b){d.isFunction(a)&&(a=a.call(this));var c=b.fn;if(d.isEmpty(a))return b.inverse(this);var e=b.data;return b.data&&b.ids&&(e=d.createFrame(b.data),e.contextPath=d.appendContextPath(b.data.contextPath,b.ids[0])),c(a,{data:e,blockParams:d.blockParams([a],[e&&e.contextPath])})})},a.exports=b["default"]},function(a,b,c){"use strict";function d(a){g["default"](a)}var e=c(2)["default"];b.__esModule=!0,b.registerDefaultDecorators=d;var f=c(18),g=e(f)},function(a,b,c){"use strict";b.__esModule=!0;var d=c(4);b["default"]=function(a){a.registerDecorator("inline",function(a,b,c,e){var f=a;return b.partials||(b.partials={},f=function(e,f){var g=c.partials;c.partials=d.extend({},g,b.partials);var h=a(e,f);return c.partials=g,h}),b.partials[e.args[0]]=e.fn,f})},a.exports=b["default"]},function(a,b,c){"use strict";b.__esModule=!0;var d=c(4),e={methodMap:["debug","info","warn","error"],level:"info",lookupLevel:function(a){if("string"==typeof a){var b=d.indexOf(e.methodMap,a.toLowerCase());a=b>=0?b:parseInt(a,10)}return a},log:function(a){if(a=e.lookupLevel(a),"undefined"!=typeof console&&e.lookupLevel(e.level)<=a){var b=e.methodMap[a];console[b]||(b="log");for(var c=arguments.length,d=Array(c>1?c-1:0),f=1;f<c;f++)d[f-1]=arguments[f];console[b].apply(console,d)}}};b["default"]=e,a.exports=b["default"]},function(a,b){"use strict";function c(a){this.string=a}b.__esModule=!0,c.prototype.toString=c.prototype.toHTML=function(){return""+this.string},b["default"]=c,a.exports=b["default"]},function(a,b,c){"use strict";function d(a){var b=a&&a[0]||1,c=s.COMPILER_REVISION;if(b!==c){if(b<c){var d=s.REVISION_CHANGES[c],e=s.REVISION_CHANGES[b];throw new r["default"]("Template was precompiled with an older version of Handlebars than the current runtime. Please update your precompiler to a newer version ("+d+") or downgrade your runtime to an older version ("+e+").")}throw new r["default"]("Template was precompiled with a newer version of Handlebars than the current runtime. Please update your runtime to a newer version ("+a[1]+").")}}function e(a,b){function c(c,d,e){e.hash&&(d=p.extend({},d,e.hash),e.ids&&(e.ids[0]=!0)),c=b.VM.resolvePartial.call(this,c,d,e);var f=b.VM.invokePartial.call(this,c,d,e);if(null==f&&b.compile&&(e.partials[e.name]=b.compile(c,a.compilerOptions,b),f=e.partials[e.name](d,e)),null!=f){if(e.indent){for(var g=f.split("\n"),h=0,i=g.length;h<i&&(g[h]||h+1!==i);h++)g[h]=e.indent+g[h];f=g.join("\n")}return f}throw new r["default"]("The partial "+e.name+" could not be compiled when running in runtime-only mode")}function d(b){function c(b){return""+a.main(e,b,e.helpers,e.partials,g,i,h)}var f=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],g=f.data;d._setup(f),!f.partial&&a.useData&&(g=j(b,g));var h=void 0,i=a.useBlockParams?[]:void 0;return a.useDepths&&(h=f.depths?b!=f.depths[0]?[b].concat(f.depths):f.depths:[b]),(c=k(a.main,c,e,f.depths||[],g,i))(b,f)}if(!b)throw new r["default"]("No environment passed to template");if(!a||!a.main)throw new r["default"]("Unknown template object: "+typeof a);a.main.decorator=a.main_d,b.VM.checkRevision(a.compiler);var e={strict:function(a,b){if(!(b in a))throw new r["default"]('"'+b+'" not defined in '+a);return a[b]},lookup:function(a,b){for(var c=a.length,d=0;d<c;d++)if(a[d]&&null!=a[d][b])return a[d][b]},lambda:function(a,b){return"function"==typeof a?a.call(b):a},escapeExpression:p.escapeExpression,invokePartial:c,fn:function(b){var c=a[b];return c.decorator=a[b+"_d"],c},programs:[],program:function(a,b,c,d,e){var g=this.programs[a],h=this.fn(a);return b||e||d||c?g=f(this,a,h,b,c,d,e):g||(g=this.programs[a]=f(this,a,h)),g},data:function(a,b){for(;a&&b--;)a=a._parent;return a},merge:function(a,b){var c=a||b;return a&&b&&a!==b&&(c=p.extend({},b,a)),c},nullContext:l({}),noop:b.VM.noop,compilerInfo:a.compiler};return d.isTop=!0,d._setup=function(c){c.partial?(e.helpers=c.helpers,e.partials=c.partials,e.decorators=c.decorators):(e.helpers=e.merge(c.helpers,b.helpers),a.usePartial&&(e.partials=e.merge(c.partials,b.partials)),(a.usePartial||a.useDecorators)&&(e.decorators=e.merge(c.decorators,b.decorators)))},d._child=function(b,c,d,g){if(a.useBlockParams&&!d)throw new r["default"]("must pass block params");if(a.useDepths&&!g)throw new r["default"]("must pass parent depths");return f(e,b,a[b],c,0,d,g)},d}function f(a,b,c,d,e,f,g){function h(b){var e=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],h=g;return!g||b==g[0]||b===a.nullContext&&null===g[0]||(h=[b].concat(g)),c(a,b,a.helpers,a.partials,e.data||d,f&&[e.blockParams].concat(f),h)}return h=k(c,h,a,g,d,f),h.program=b,h.depth=g?g.length:0,h.blockParams=e||0,h}function g(a,b,c){return a?a.call||c.name||(c.name=a,a=c.partials[a]):a="@partial-block"===c.name?c.data["partial-block"]:c.partials[c.name],a}function h(a,b,c){var d=c.data&&c.data["partial-block"];c.partial=!0,c.ids&&(c.data.contextPath=c.ids[0]||c.data.contextPath);var e=void 0;if(c.fn&&c.fn!==i&&!function(){c.data=s.createFrame(c.data);var a=c.fn;e=c.data["partial-block"]=function(b){var c=arguments.length<=1||void 0===arguments[1]?{}:arguments[1];return c.data=s.createFrame(c.data),c.data["partial-block"]=d,a(b,c)},a.partials&&(c.partials=p.extend({},c.partials,a.partials))}(),void 0===a&&e&&(a=e),void 0===a)throw new r["default"]("The partial "+c.name+" could not be found");if(a instanceof Function)return a(b,c)}function i(){return""}function j(a,b){return b&&"root"in b||(b=b?s.createFrame(b):{},b.root=a),b}function k(a,b,c,d,e,f){if(a.decorator){var g={};b=a.decorator(b,g,c,d&&d[0],e,f,d),p.extend(b,g)}return b}var l=c(22)["default"],m=c(1)["default"],n=c(2)["default"];b.__esModule=!0,b.checkRevision=d,b.template=e,b.wrapProgram=f,b.resolvePartial=g,b.invokePartial=h,b.noop=i;var o=c(4),p=m(o),q=c(5),r=n(q),s=c(3)},function(a,b,c){a.exports={"default":c(23),__esModule:!0}},function(a,b,c){c(24),a.exports=c(29).Object.seal},function(a,b,c){var d=c(25);c(26)("seal",function(a){return function(b){return a&&d(b)?a(b):b}})},function(a,b){a.exports=function(a){return"object"==typeof a?null!==a:"function"==typeof a}},function(a,b,c){var d=c(27),e=c(29),f=c(32);a.exports=function(a,b){var c=(e.Object||{})[a]||Object[a],g={};g[a]=b(c),d(d.S+d.F*f(function(){c(1)}),"Object",g)}},function(a,b,c){var d=c(28),e=c(29),f=c(30),g="prototype",h=function(a,b,c){var i,j,k,l=a&h.F,m=a&h.G,n=a&h.S,o=a&h.P,p=a&h.B,q=a&h.W,r=m?e:e[b]||(e[b]={}),s=m?d:n?d[b]:(d[b]||{})[g];m&&(c=b);for(i in c)j=!l&&s&&i in s,j&&i in r||(k=j?s[i]:c[i],r[i]=m&&"function"!=typeof s[i]?c[i]:p&&j?f(k,d):q&&s[i]==k?function(a){var b=function(b){return this instanceof a?new a(b):a(b)};return b[g]=a[g],b}(k):o&&"function"==typeof k?f(Function.call,k):k,o&&((r[g]||(r[g]={}))[i]=k))};h.F=1,h.G=2,h.S=4,h.P=8,h.B=16,h.W=32,a.exports=h},function(a,b){var c=a.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=c)},function(a,b){var c=a.exports={version:"1.2.6"};"number"==typeof __e&&(__e=c)},function(a,b,c){var d=c(31);a.exports=function(a,b,c){if(d(a),void 0===b)return a;switch(c){case 1:return function(c){return a.call(b,c)};case 2:return function(c,d){return a.call(b,c,d)};case 3:return function(c,d,e){return a.call(b,c,d,e)}}return function(){return a.apply(b,arguments)}}},function(a,b){a.exports=function(a){if("function"!=typeof a)throw TypeError(a+" is not a function!");return a}},function(a,b){a.exports=function(a){try{return!!a()}catch(b){return!0}}},function(a,b){(function(c){"use strict";b.__esModule=!0,b["default"]=function(a){var b="undefined"!=typeof c?c:window,d=b.Handlebars;a.noConflict=function(){return b.Handlebars===a&&(b.Handlebars=d),a}},a.exports=b["default"]}).call(b,function(){return this}())}])});
/******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "/"; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 0); /******/ }) /************************************************************************/ /******/ ({ /***/ "./node_modules/axios/index.js": /*!*************************************!*\ !*** ./node_modules/axios/index.js ***! \*************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__(/*! ./lib/axios */ "./node_modules/axios/lib/axios.js"); /***/ }), /***/ "./node_modules/axios/lib/adapters/xhr.js": /*!************************************************!*\ !*** ./node_modules/axios/lib/adapters/xhr.js ***! \************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js"); var settle = __webpack_require__(/*! ./../core/settle */ "./node_modules/axios/lib/core/settle.js"); var buildURL = __webpack_require__(/*! ./../helpers/buildURL */ "./node_modules/axios/lib/helpers/buildURL.js"); var parseHeaders = __webpack_require__(/*! ./../helpers/parseHeaders */ "./node_modules/axios/lib/helpers/parseHeaders.js"); var isURLSameOrigin = __webpack_require__(/*! ./../helpers/isURLSameOrigin */ "./node_modules/axios/lib/helpers/isURLSameOrigin.js"); var createError = __webpack_require__(/*! ../core/createError */ "./node_modules/axios/lib/core/createError.js"); module.exports = function xhrAdapter(config) { return new Promise(function dispatchXhrRequest(resolve, reject) { var requestData = config.data; var requestHeaders = config.headers; if (utils.isFormData(requestData)) { delete requestHeaders['Content-Type']; // Let the browser set it } var request = new XMLHttpRequest(); // HTTP basic authentication if (config.auth) { var username = config.auth.username || ''; var password = config.auth.password || ''; requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password); } request.open(config.method.toUpperCase(), buildURL(config.url, config.params, config.paramsSerializer), true); // Set the request timeout in MS request.timeout = config.timeout; // Listen for ready state request.onreadystatechange = function handleLoad() { if (!request || request.readyState !== 4) { return; } // The request errored out and we didn't get a response, this will be // handled by onerror instead // With one exception: request that using file: protocol, most browsers // will return status as 0 even though it's a successful request if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) { return; } // Prepare the response var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null; var responseData = !config.responseType || config.responseType === 'text' ? request.responseText : request.response; var response = { data: responseData, status: request.status, statusText: request.statusText, headers: responseHeaders, config: config, request: request }; settle(resolve, reject, response); // Clean up request request = null; }; // Handle browser request cancellation (as opposed to a manual cancellation) request.onabort = function handleAbort() { if (!request) { return; } reject(createError('Request aborted', config, 'ECONNABORTED', request)); // Clean up request request = null; }; // Handle low level network errors request.onerror = function handleError() { // Real errors are hidden from us by the browser // onerror should only fire if it's a network error reject(createError('Network Error', config, null, request)); // Clean up request request = null; }; // Handle timeout request.ontimeout = function handleTimeout() { reject(createError('timeout of ' + config.timeout + 'ms exceeded', config, 'ECONNABORTED', request)); // Clean up request request = null; }; // Add xsrf header // This is only done if running in a standard browser environment. // Specifically not if we're in a web worker, or react-native. if (utils.isStandardBrowserEnv()) { var cookies = __webpack_require__(/*! ./../helpers/cookies */ "./node_modules/axios/lib/helpers/cookies.js"); // Add xsrf header var xsrfValue = (config.withCredentials || isURLSameOrigin(config.url)) && config.xsrfCookieName ? cookies.read(config.xsrfCookieName) : undefined; if (xsrfValue) { requestHeaders[config.xsrfHeaderName] = xsrfValue; } } // Add headers to the request if ('setRequestHeader' in request) { utils.forEach(requestHeaders, function setRequestHeader(val, key) { if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') { // Remove Content-Type if data is undefined delete requestHeaders[key]; } else { // Otherwise add header to the request request.setRequestHeader(key, val); } }); } // Add withCredentials to request if needed if (config.withCredentials) { request.withCredentials = true; } // Add responseType to request if needed if (config.responseType) { try { request.responseType = config.responseType; } catch (e) { // Expected DOMException thrown by browsers not compatible XMLHttpRequest Level 2. // But, this can be suppressed for 'json' type as it can be parsed by default 'transformResponse' function. if (config.responseType !== 'json') { throw e; } } } // Handle progress if needed if (typeof config.onDownloadProgress === 'function') { request.addEventListener('progress', config.onDownloadProgress); } // Not all browsers support upload events if (typeof config.onUploadProgress === 'function' && request.upload) { request.upload.addEventListener('progress', config.onUploadProgress); } if (config.cancelToken) { // Handle cancellation config.cancelToken.promise.then(function onCanceled(cancel) { if (!request) { return; } request.abort(); reject(cancel); // Clean up request request = null; }); } if (requestData === undefined) { requestData = null; } // Send the request request.send(requestData); }); }; /***/ }), /***/ "./node_modules/axios/lib/axios.js": /*!*****************************************!*\ !*** ./node_modules/axios/lib/axios.js ***! \*****************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var utils = __webpack_require__(/*! ./utils */ "./node_modules/axios/lib/utils.js"); var bind = __webpack_require__(/*! ./helpers/bind */ "./node_modules/axios/lib/helpers/bind.js"); var Axios = __webpack_require__(/*! ./core/Axios */ "./node_modules/axios/lib/core/Axios.js"); var mergeConfig = __webpack_require__(/*! ./core/mergeConfig */ "./node_modules/axios/lib/core/mergeConfig.js"); var defaults = __webpack_require__(/*! ./defaults */ "./node_modules/axios/lib/defaults.js"); /** * Create an instance of Axios * * @param {Object} defaultConfig The default config for the instance * @return {Axios} A new instance of Axios */ function createInstance(defaultConfig) { var context = new Axios(defaultConfig); var instance = bind(Axios.prototype.request, context); // Copy axios.prototype to instance utils.extend(instance, Axios.prototype, context); // Copy context to instance utils.extend(instance, context); return instance; } // Create the default instance to be exported var axios = createInstance(defaults); // Expose Axios class to allow class inheritance axios.Axios = Axios; // Factory for creating new instances axios.create = function create(instanceConfig) { return createInstance(mergeConfig(axios.defaults, instanceConfig)); }; // Expose Cancel & CancelToken axios.Cancel = __webpack_require__(/*! ./cancel/Cancel */ "./node_modules/axios/lib/cancel/Cancel.js"); axios.CancelToken = __webpack_require__(/*! ./cancel/CancelToken */ "./node_modules/axios/lib/cancel/CancelToken.js"); axios.isCancel = __webpack_require__(/*! ./cancel/isCancel */ "./node_modules/axios/lib/cancel/isCancel.js"); // Expose all/spread axios.all = function all(promises) { return Promise.all(promises); }; axios.spread = __webpack_require__(/*! ./helpers/spread */ "./node_modules/axios/lib/helpers/spread.js"); module.exports = axios; // Allow use of default import syntax in TypeScript module.exports.default = axios; /***/ }), /***/ "./node_modules/axios/lib/cancel/Cancel.js": /*!*************************************************!*\ !*** ./node_modules/axios/lib/cancel/Cancel.js ***! \*************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * A `Cancel` is an object that is thrown when an operation is canceled. * * @class * @param {string=} message The message. */ function Cancel(message) { this.message = message; } Cancel.prototype.toString = function toString() { return 'Cancel' + (this.message ? ': ' + this.message : ''); }; Cancel.prototype.__CANCEL__ = true; module.exports = Cancel; /***/ }), /***/ "./node_modules/axios/lib/cancel/CancelToken.js": /*!******************************************************!*\ !*** ./node_modules/axios/lib/cancel/CancelToken.js ***! \******************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var Cancel = __webpack_require__(/*! ./Cancel */ "./node_modules/axios/lib/cancel/Cancel.js"); /** * A `CancelToken` is an object that can be used to request cancellation of an operation. * * @class * @param {Function} executor The executor function. */ function CancelToken(executor) { if (typeof executor !== 'function') { throw new TypeError('executor must be a function.'); } var resolvePromise; this.promise = new Promise(function promiseExecutor(resolve) { resolvePromise = resolve; }); var token = this; executor(function cancel(message) { if (token.reason) { // Cancellation has already been requested return; } token.reason = new Cancel(message); resolvePromise(token.reason); }); } /** * Throws a `Cancel` if cancellation has been requested. */ CancelToken.prototype.throwIfRequested = function throwIfRequested() { if (this.reason) { throw this.reason; } }; /** * Returns an object that contains a new `CancelToken` and a function that, when called, * cancels the `CancelToken`. */ CancelToken.source = function source() { var cancel; var token = new CancelToken(function executor(c) { cancel = c; }); return { token: token, cancel: cancel }; }; module.exports = CancelToken; /***/ }), /***/ "./node_modules/axios/lib/cancel/isCancel.js": /*!***************************************************!*\ !*** ./node_modules/axios/lib/cancel/isCancel.js ***! \***************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function isCancel(value) { return !!(value && value.__CANCEL__); }; /***/ }), /***/ "./node_modules/axios/lib/core/Axios.js": /*!**********************************************!*\ !*** ./node_modules/axios/lib/core/Axios.js ***! \**********************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js"); var buildURL = __webpack_require__(/*! ../helpers/buildURL */ "./node_modules/axios/lib/helpers/buildURL.js"); var InterceptorManager = __webpack_require__(/*! ./InterceptorManager */ "./node_modules/axios/lib/core/InterceptorManager.js"); var dispatchRequest = __webpack_require__(/*! ./dispatchRequest */ "./node_modules/axios/lib/core/dispatchRequest.js"); var mergeConfig = __webpack_require__(/*! ./mergeConfig */ "./node_modules/axios/lib/core/mergeConfig.js"); /** * Create a new instance of Axios * * @param {Object} instanceConfig The default config for the instance */ function Axios(instanceConfig) { this.defaults = instanceConfig; this.interceptors = { request: new InterceptorManager(), response: new InterceptorManager() }; } /** * Dispatch a request * * @param {Object} config The config specific for this request (merged with this.defaults) */ Axios.prototype.request = function request(config) { /*eslint no-param-reassign:0*/ // Allow for axios('example/url'[, config]) a la fetch API if (typeof config === 'string') { config = arguments[1] || {}; config.url = arguments[0]; } else { config = config || {}; } config = mergeConfig(this.defaults, config); config.method = config.method ? config.method.toLowerCase() : 'get'; // Hook up interceptors middleware var chain = [dispatchRequest, undefined]; var promise = Promise.resolve(config); this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) { chain.unshift(interceptor.fulfilled, interceptor.rejected); }); this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) { chain.push(interceptor.fulfilled, interceptor.rejected); }); while (chain.length) { promise = promise.then(chain.shift(), chain.shift()); } return promise; }; Axios.prototype.getUri = function getUri(config) { config = mergeConfig(this.defaults, config); return buildURL(config.url, config.params, config.paramsSerializer).replace(/^\?/, ''); }; // Provide aliases for supported request methods utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) { /*eslint func-names:0*/ Axios.prototype[method] = function(url, config) { return this.request(utils.merge(config || {}, { method: method, url: url })); }; }); utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { /*eslint func-names:0*/ Axios.prototype[method] = function(url, data, config) { return this.request(utils.merge(config || {}, { method: method, url: url, data: data })); }; }); module.exports = Axios; /***/ }), /***/ "./node_modules/axios/lib/core/InterceptorManager.js": /*!***********************************************************!*\ !*** ./node_modules/axios/lib/core/InterceptorManager.js ***! \***********************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js"); function InterceptorManager() { this.handlers = []; } /** * Add a new interceptor to the stack * * @param {Function} fulfilled The function to handle `then` for a `Promise` * @param {Function} rejected The function to handle `reject` for a `Promise` * * @return {Number} An ID used to remove interceptor later */ InterceptorManager.prototype.use = function use(fulfilled, rejected) { this.handlers.push({ fulfilled: fulfilled, rejected: rejected }); return this.handlers.length - 1; }; /** * Remove an interceptor from the stack * * @param {Number} id The ID that was returned by `use` */ InterceptorManager.prototype.eject = function eject(id) { if (this.handlers[id]) { this.handlers[id] = null; } }; /** * Iterate over all the registered interceptors * * This method is particularly useful for skipping over any * interceptors that may have become `null` calling `eject`. * * @param {Function} fn The function to call for each interceptor */ InterceptorManager.prototype.forEach = function forEach(fn) { utils.forEach(this.handlers, function forEachHandler(h) { if (h !== null) { fn(h); } }); }; module.exports = InterceptorManager; /***/ }), /***/ "./node_modules/axios/lib/core/createError.js": /*!****************************************************!*\ !*** ./node_modules/axios/lib/core/createError.js ***! \****************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var enhanceError = __webpack_require__(/*! ./enhanceError */ "./node_modules/axios/lib/core/enhanceError.js"); /** * Create an Error with the specified message, config, error code, request and response. * * @param {string} message The error message. * @param {Object} config The config. * @param {string} [code] The error code (for example, 'ECONNABORTED'). * @param {Object} [request] The request. * @param {Object} [response] The response. * @returns {Error} The created error. */ module.exports = function createError(message, config, code, request, response) { var error = new Error(message); return enhanceError(error, config, code, request, response); }; /***/ }), /***/ "./node_modules/axios/lib/core/dispatchRequest.js": /*!********************************************************!*\ !*** ./node_modules/axios/lib/core/dispatchRequest.js ***! \********************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js"); var transformData = __webpack_require__(/*! ./transformData */ "./node_modules/axios/lib/core/transformData.js"); var isCancel = __webpack_require__(/*! ../cancel/isCancel */ "./node_modules/axios/lib/cancel/isCancel.js"); var defaults = __webpack_require__(/*! ../defaults */ "./node_modules/axios/lib/defaults.js"); var isAbsoluteURL = __webpack_require__(/*! ./../helpers/isAbsoluteURL */ "./node_modules/axios/lib/helpers/isAbsoluteURL.js"); var combineURLs = __webpack_require__(/*! ./../helpers/combineURLs */ "./node_modules/axios/lib/helpers/combineURLs.js"); /** * Throws a `Cancel` if cancellation has been requested. */ function throwIfCancellationRequested(config) { if (config.cancelToken) { config.cancelToken.throwIfRequested(); } } /** * Dispatch a request to the server using the configured adapter. * * @param {object} config The config that is to be used for the request * @returns {Promise} The Promise to be fulfilled */ module.exports = function dispatchRequest(config) { throwIfCancellationRequested(config); // Support baseURL config if (config.baseURL && !isAbsoluteURL(config.url)) { config.url = combineURLs(config.baseURL, config.url); } // Ensure headers exist config.headers = config.headers || {}; // Transform request data config.data = transformData( config.data, config.headers, config.transformRequest ); // Flatten headers config.headers = utils.merge( config.headers.common || {}, config.headers[config.method] || {}, config.headers || {} ); utils.forEach( ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'], function cleanHeaderConfig(method) { delete config.headers[method]; } ); var adapter = config.adapter || defaults.adapter; return adapter(config).then(function onAdapterResolution(response) { throwIfCancellationRequested(config); // Transform response data response.data = transformData( response.data, response.headers, config.transformResponse ); return response; }, function onAdapterRejection(reason) { if (!isCancel(reason)) { throwIfCancellationRequested(config); // Transform response data if (reason && reason.response) { reason.response.data = transformData( reason.response.data, reason.response.headers, config.transformResponse ); } } return Promise.reject(reason); }); }; /***/ }), /***/ "./node_modules/axios/lib/core/enhanceError.js": /*!*****************************************************!*\ !*** ./node_modules/axios/lib/core/enhanceError.js ***! \*****************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Update an Error with the specified config, error code, and response. * * @param {Error} error The error to update. * @param {Object} config The config. * @param {string} [code] The error code (for example, 'ECONNABORTED'). * @param {Object} [request] The request. * @param {Object} [response] The response. * @returns {Error} The error. */ module.exports = function enhanceError(error, config, code, request, response) { error.config = config; if (code) { error.code = code; } error.request = request; error.response = response; error.isAxiosError = true; error.toJSON = function() { return { // Standard message: this.message, name: this.name, // Microsoft description: this.description, number: this.number, // Mozilla fileName: this.fileName, lineNumber: this.lineNumber, columnNumber: this.columnNumber, stack: this.stack, // Axios config: this.config, code: this.code }; }; return error; }; /***/ }), /***/ "./node_modules/axios/lib/core/mergeConfig.js": /*!****************************************************!*\ !*** ./node_modules/axios/lib/core/mergeConfig.js ***! \****************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var utils = __webpack_require__(/*! ../utils */ "./node_modules/axios/lib/utils.js"); /** * Config-specific merge-function which creates a new config-object * by merging two configuration objects together. * * @param {Object} config1 * @param {Object} config2 * @returns {Object} New object resulting from merging config2 to config1 */ module.exports = function mergeConfig(config1, config2) { // eslint-disable-next-line no-param-reassign config2 = config2 || {}; var config = {}; utils.forEach(['url', 'method', 'params', 'data'], function valueFromConfig2(prop) { if (typeof config2[prop] !== 'undefined') { config[prop] = config2[prop]; } }); utils.forEach(['headers', 'auth', 'proxy'], function mergeDeepProperties(prop) { if (utils.isObject(config2[prop])) { config[prop] = utils.deepMerge(config1[prop], config2[prop]); } else if (typeof config2[prop] !== 'undefined') { config[prop] = config2[prop]; } else if (utils.isObject(config1[prop])) { config[prop] = utils.deepMerge(config1[prop]); } else if (typeof config1[prop] !== 'undefined') { config[prop] = config1[prop]; } }); utils.forEach([ 'baseURL', 'transformRequest', 'transformResponse', 'paramsSerializer', 'timeout', 'withCredentials', 'adapter', 'responseType', 'xsrfCookieName', 'xsrfHeaderName', 'onUploadProgress', 'onDownloadProgress', 'maxContentLength', 'validateStatus', 'maxRedirects', 'httpAgent', 'httpsAgent', 'cancelToken', 'socketPath' ], function defaultToConfig2(prop) { if (typeof config2[prop] !== 'undefined') { config[prop] = config2[prop]; } else if (typeof config1[prop] !== 'undefined') { config[prop] = config1[prop]; } }); return config; }; /***/ }), /***/ "./node_modules/axios/lib/core/settle.js": /*!***********************************************!*\ !*** ./node_modules/axios/lib/core/settle.js ***! \***********************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var createError = __webpack_require__(/*! ./createError */ "./node_modules/axios/lib/core/createError.js"); /** * Resolve or reject a Promise based on response status. * * @param {Function} resolve A function that resolves the promise. * @param {Function} reject A function that rejects the promise. * @param {object} response The response. */ module.exports = function settle(resolve, reject, response) { var validateStatus = response.config.validateStatus; if (!validateStatus || validateStatus(response.status)) { resolve(response); } else { reject(createError( 'Request failed with status code ' + response.status, response.config, null, response.request, response )); } }; /***/ }), /***/ "./node_modules/axios/lib/core/transformData.js": /*!******************************************************!*\ !*** ./node_modules/axios/lib/core/transformData.js ***! \******************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js"); /** * Transform the data for a request or a response * * @param {Object|String} data The data to be transformed * @param {Array} headers The headers for the request or response * @param {Array|Function} fns A single function or Array of functions * @returns {*} The resulting transformed data */ module.exports = function transformData(data, headers, fns) { /*eslint no-param-reassign:0*/ utils.forEach(fns, function transform(fn) { data = fn(data, headers); }); return data; }; /***/ }), /***/ "./node_modules/axios/lib/defaults.js": /*!********************************************!*\ !*** ./node_modules/axios/lib/defaults.js ***! \********************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* WEBPACK VAR INJECTION */(function(process) { var utils = __webpack_require__(/*! ./utils */ "./node_modules/axios/lib/utils.js"); var normalizeHeaderName = __webpack_require__(/*! ./helpers/normalizeHeaderName */ "./node_modules/axios/lib/helpers/normalizeHeaderName.js"); var DEFAULT_CONTENT_TYPE = { 'Content-Type': 'application/x-www-form-urlencoded' }; function setContentTypeIfUnset(headers, value) { if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) { headers['Content-Type'] = value; } } function getDefaultAdapter() { var adapter; // Only Node.JS has a process variable that is of [[Class]] process if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') { // For node use HTTP adapter adapter = __webpack_require__(/*! ./adapters/http */ "./node_modules/axios/lib/adapters/xhr.js"); } else if (typeof XMLHttpRequest !== 'undefined') { // For browsers use XHR adapter adapter = __webpack_require__(/*! ./adapters/xhr */ "./node_modules/axios/lib/adapters/xhr.js"); } return adapter; } var defaults = { adapter: getDefaultAdapter(), transformRequest: [function transformRequest(data, headers) { normalizeHeaderName(headers, 'Accept'); normalizeHeaderName(headers, 'Content-Type'); if (utils.isFormData(data) || utils.isArrayBuffer(data) || utils.isBuffer(data) || utils.isStream(data) || utils.isFile(data) || utils.isBlob(data) ) { return data; } if (utils.isArrayBufferView(data)) { return data.buffer; } if (utils.isURLSearchParams(data)) { setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8'); return data.toString(); } if (utils.isObject(data)) { setContentTypeIfUnset(headers, 'application/json;charset=utf-8'); return JSON.stringify(data); } return data; }], transformResponse: [function transformResponse(data) { /*eslint no-param-reassign:0*/ if (typeof data === 'string') { try { data = JSON.parse(data); } catch (e) { /* Ignore */ } } return data; }], /** * A timeout in milliseconds to abort a request. If set to 0 (default) a * timeout is not created. */ timeout: 0, xsrfCookieName: 'XSRF-TOKEN', xsrfHeaderName: 'X-XSRF-TOKEN', maxContentLength: -1, validateStatus: function validateStatus(status) { return status >= 200 && status < 300; } }; defaults.headers = { common: { 'Accept': 'application/json, text/plain, */*' } }; utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) { defaults.headers[method] = {}; }); utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE); }); module.exports = defaults; /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../process/browser.js */ "./node_modules/process/browser.js"))) /***/ }), /***/ "./node_modules/axios/lib/helpers/bind.js": /*!************************************************!*\ !*** ./node_modules/axios/lib/helpers/bind.js ***! \************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function bind(fn, thisArg) { return function wrap() { var args = new Array(arguments.length); for (var i = 0; i < args.length; i++) { args[i] = arguments[i]; } return fn.apply(thisArg, args); }; }; /***/ }), /***/ "./node_modules/axios/lib/helpers/buildURL.js": /*!****************************************************!*\ !*** ./node_modules/axios/lib/helpers/buildURL.js ***! \****************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js"); function encode(val) { return encodeURIComponent(val). replace(/%40/gi, '@'). replace(/%3A/gi, ':'). replace(/%24/g, '$'). replace(/%2C/gi, ','). replace(/%20/g, '+'). replace(/%5B/gi, '['). replace(/%5D/gi, ']'); } /** * Build a URL by appending params to the end * * @param {string} url The base of the url (e.g., http://www.google.com) * @param {object} [params] The params to be appended * @returns {string} The formatted url */ module.exports = function buildURL(url, params, paramsSerializer) { /*eslint no-param-reassign:0*/ if (!params) { return url; } var serializedParams; if (paramsSerializer) { serializedParams = paramsSerializer(params); } else if (utils.isURLSearchParams(params)) { serializedParams = params.toString(); } else { var parts = []; utils.forEach(params, function serialize(val, key) { if (val === null || typeof val === 'undefined') { return; } if (utils.isArray(val)) { key = key + '[]'; } else { val = [val]; } utils.forEach(val, function parseValue(v) { if (utils.isDate(v)) { v = v.toISOString(); } else if (utils.isObject(v)) { v = JSON.stringify(v); } parts.push(encode(key) + '=' + encode(v)); }); }); serializedParams = parts.join('&'); } if (serializedParams) { var hashmarkIndex = url.indexOf('#'); if (hashmarkIndex !== -1) { url = url.slice(0, hashmarkIndex); } url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams; } return url; }; /***/ }), /***/ "./node_modules/axios/lib/helpers/combineURLs.js": /*!*******************************************************!*\ !*** ./node_modules/axios/lib/helpers/combineURLs.js ***! \*******************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Creates a new URL by combining the specified URLs * * @param {string} baseURL The base URL * @param {string} relativeURL The relative URL * @returns {string} The combined URL */ module.exports = function combineURLs(baseURL, relativeURL) { return relativeURL ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '') : baseURL; }; /***/ }), /***/ "./node_modules/axios/lib/helpers/cookies.js": /*!***************************************************!*\ !*** ./node_modules/axios/lib/helpers/cookies.js ***! \***************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js"); module.exports = ( utils.isStandardBrowserEnv() ? // Standard browser envs support document.cookie (function standardBrowserEnv() { return { write: function write(name, value, expires, path, domain, secure) { var cookie = []; cookie.push(name + '=' + encodeURIComponent(value)); if (utils.isNumber(expires)) { cookie.push('expires=' + new Date(expires).toGMTString()); } if (utils.isString(path)) { cookie.push('path=' + path); } if (utils.isString(domain)) { cookie.push('domain=' + domain); } if (secure === true) { cookie.push('secure'); } document.cookie = cookie.join('; '); }, read: function read(name) { var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)')); return (match ? decodeURIComponent(match[3]) : null); }, remove: function remove(name) { this.write(name, '', Date.now() - 86400000); } }; })() : // Non standard browser env (web workers, react-native) lack needed support. (function nonStandardBrowserEnv() { return { write: function write() {}, read: function read() { return null; }, remove: function remove() {} }; })() ); /***/ }), /***/ "./node_modules/axios/lib/helpers/isAbsoluteURL.js": /*!*********************************************************!*\ !*** ./node_modules/axios/lib/helpers/isAbsoluteURL.js ***! \*********************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Determines whether the specified URL is absolute * * @param {string} url The URL to test * @returns {boolean} True if the specified URL is absolute, otherwise false */ module.exports = function isAbsoluteURL(url) { // A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL). // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed // by any combination of letters, digits, plus, period, or hyphen. return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url); }; /***/ }), /***/ "./node_modules/axios/lib/helpers/isURLSameOrigin.js": /*!***********************************************************!*\ !*** ./node_modules/axios/lib/helpers/isURLSameOrigin.js ***! \***********************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js"); module.exports = ( utils.isStandardBrowserEnv() ? // Standard browser envs have full support of the APIs needed to test // whether the request URL is of the same origin as current location. (function standardBrowserEnv() { var msie = /(msie|trident)/i.test(navigator.userAgent); var urlParsingNode = document.createElement('a'); var originURL; /** * Parse a URL to discover it's components * * @param {String} url The URL to be parsed * @returns {Object} */ function resolveURL(url) { var href = url; if (msie) { // IE needs attribute set twice to normalize properties urlParsingNode.setAttribute('href', href); href = urlParsingNode.href; } urlParsingNode.setAttribute('href', href); // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils return { href: urlParsingNode.href, protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '', host: urlParsingNode.host, search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '', hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '', hostname: urlParsingNode.hostname, port: urlParsingNode.port, pathname: (urlParsingNode.pathname.charAt(0) === '/') ? urlParsingNode.pathname : '/' + urlParsingNode.pathname }; } originURL = resolveURL(window.location.href); /** * Determine if a URL shares the same origin as the current location * * @param {String} requestURL The URL to test * @returns {boolean} True if URL shares the same origin, otherwise false */ return function isURLSameOrigin(requestURL) { var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL; return (parsed.protocol === originURL.protocol && parsed.host === originURL.host); }; })() : // Non standard browser envs (web workers, react-native) lack needed support. (function nonStandardBrowserEnv() { return function isURLSameOrigin() { return true; }; })() ); /***/ }), /***/ "./node_modules/axios/lib/helpers/normalizeHeaderName.js": /*!***************************************************************!*\ !*** ./node_modules/axios/lib/helpers/normalizeHeaderName.js ***! \***************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var utils = __webpack_require__(/*! ../utils */ "./node_modules/axios/lib/utils.js"); module.exports = function normalizeHeaderName(headers, normalizedName) { utils.forEach(headers, function processHeader(value, name) { if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) { headers[normalizedName] = value; delete headers[name]; } }); }; /***/ }), /***/ "./node_modules/axios/lib/helpers/parseHeaders.js": /*!********************************************************!*\ !*** ./node_modules/axios/lib/helpers/parseHeaders.js ***! \********************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js"); // Headers whose duplicates are ignored by node // c.f. https://nodejs.org/api/http.html#http_message_headers var ignoreDuplicateOf = [ 'age', 'authorization', 'content-length', 'content-type', 'etag', 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since', 'last-modified', 'location', 'max-forwards', 'proxy-authorization', 'referer', 'retry-after', 'user-agent' ]; /** * Parse headers into an object * * ``` * Date: Wed, 27 Aug 2014 08:58:49 GMT * Content-Type: application/json * Connection: keep-alive * Transfer-Encoding: chunked * ``` * * @param {String} headers Headers needing to be parsed * @returns {Object} Headers parsed into an object */ module.exports = function parseHeaders(headers) { var parsed = {}; var key; var val; var i; if (!headers) { return parsed; } utils.forEach(headers.split('\n'), function parser(line) { i = line.indexOf(':'); key = utils.trim(line.substr(0, i)).toLowerCase(); val = utils.trim(line.substr(i + 1)); if (key) { if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) { return; } if (key === 'set-cookie') { parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]); } else { parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val; } } }); return parsed; }; /***/ }), /***/ "./node_modules/axios/lib/helpers/spread.js": /*!**************************************************!*\ !*** ./node_modules/axios/lib/helpers/spread.js ***! \**************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Syntactic sugar for invoking a function and expanding an array for arguments. * * Common use case would be to use `Function.prototype.apply`. * * ```js * function f(x, y, z) {} * var args = [1, 2, 3]; * f.apply(null, args); * ``` * * With `spread` this example can be re-written. * * ```js * spread(function(x, y, z) {})([1, 2, 3]); * ``` * * @param {Function} callback * @returns {Function} */ module.exports = function spread(callback) { return function wrap(arr) { return callback.apply(null, arr); }; }; /***/ }), /***/ "./node_modules/axios/lib/utils.js": /*!*****************************************!*\ !*** ./node_modules/axios/lib/utils.js ***! \*****************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var bind = __webpack_require__(/*! ./helpers/bind */ "./node_modules/axios/lib/helpers/bind.js"); var isBuffer = __webpack_require__(/*! is-buffer */ "./node_modules/axios/node_modules/is-buffer/index.js"); /*global toString:true*/ // utils is a library of generic helper functions non-specific to axios var toString = Object.prototype.toString; /** * Determine if a value is an Array * * @param {Object} val The value to test * @returns {boolean} True if value is an Array, otherwise false */ function isArray(val) { return toString.call(val) === '[object Array]'; } /** * Determine if a value is an ArrayBuffer * * @param {Object} val The value to test * @returns {boolean} True if value is an ArrayBuffer, otherwise false */ function isArrayBuffer(val) { return toString.call(val) === '[object ArrayBuffer]'; } /** * Determine if a value is a FormData * * @param {Object} val The value to test * @returns {boolean} True if value is an FormData, otherwise false */ function isFormData(val) { return (typeof FormData !== 'undefined') && (val instanceof FormData); } /** * Determine if a value is a view on an ArrayBuffer * * @param {Object} val The value to test * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false */ function isArrayBufferView(val) { var result; if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) { result = ArrayBuffer.isView(val); } else { result = (val) && (val.buffer) && (val.buffer instanceof ArrayBuffer); } return result; } /** * Determine if a value is a String * * @param {Object} val The value to test * @returns {boolean} True if value is a String, otherwise false */ function isString(val) { return typeof val === 'string'; } /** * Determine if a value is a Number * * @param {Object} val The value to test * @returns {boolean} True if value is a Number, otherwise false */ function isNumber(val) { return typeof val === 'number'; } /** * Determine if a value is undefined * * @param {Object} val The value to test * @returns {boolean} True if the value is undefined, otherwise false */ function isUndefined(val) { return typeof val === 'undefined'; } /** * Determine if a value is an Object * * @param {Object} val The value to test * @returns {boolean} True if value is an Object, otherwise false */ function isObject(val) { return val !== null && typeof val === 'object'; } /** * Determine if a value is a Date * * @param {Object} val The value to test * @returns {boolean} True if value is a Date, otherwise false */ function isDate(val) { return toString.call(val) === '[object Date]'; } /** * Determine if a value is a File * * @param {Object} val The value to test * @returns {boolean} True if value is a File, otherwise false */ function isFile(val) { return toString.call(val) === '[object File]'; } /** * Determine if a value is a Blob * * @param {Object} val The value to test * @returns {boolean} True if value is a Blob, otherwise false */ function isBlob(val) { return toString.call(val) === '[object Blob]'; } /** * Determine if a value is a Function * * @param {Object} val The value to test * @returns {boolean} True if value is a Function, otherwise false */ function isFunction(val) { return toString.call(val) === '[object Function]'; } /** * Determine if a value is a Stream * * @param {Object} val The value to test * @returns {boolean} True if value is a Stream, otherwise false */ function isStream(val) { return isObject(val) && isFunction(val.pipe); } /** * Determine if a value is a URLSearchParams object * * @param {Object} val The value to test * @returns {boolean} True if value is a URLSearchParams object, otherwise false */ function isURLSearchParams(val) { return typeof URLSearchParams !== 'undefined' && val instanceof URLSearchParams; } /** * Trim excess whitespace off the beginning and end of a string * * @param {String} str The String to trim * @returns {String} The String freed of excess whitespace */ function trim(str) { return str.replace(/^\s*/, '').replace(/\s*$/, ''); } /** * Determine if we're running in a standard browser environment * * This allows axios to run in a web worker, and react-native. * Both environments support XMLHttpRequest, but not fully standard globals. * * web workers: * typeof window -> undefined * typeof document -> undefined * * react-native: * navigator.product -> 'ReactNative' * nativescript * navigator.product -> 'NativeScript' or 'NS' */ function isStandardBrowserEnv() { if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' || navigator.product === 'NativeScript' || navigator.product === 'NS')) { return false; } return ( typeof window !== 'undefined' && typeof document !== 'undefined' ); } /** * Iterate over an Array or an Object invoking a function for each item. * * If `obj` is an Array callback will be called passing * the value, index, and complete array for each item. * * If 'obj' is an Object callback will be called passing * the value, key, and complete object for each property. * * @param {Object|Array} obj The object to iterate * @param {Function} fn The callback to invoke for each item */ function forEach(obj, fn) { // Don't bother if no value provided if (obj === null || typeof obj === 'undefined') { return; } // Force an array if not already something iterable if (typeof obj !== 'object') { /*eslint no-param-reassign:0*/ obj = [obj]; } if (isArray(obj)) { // Iterate over array values for (var i = 0, l = obj.length; i < l; i++) { fn.call(null, obj[i], i, obj); } } else { // Iterate over object keys for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { fn.call(null, obj[key], key, obj); } } } } /** * Accepts varargs expecting each argument to be an object, then * immutably merges the properties of each object and returns result. * * When multiple objects contain the same key the later object in * the arguments list will take precedence. * * Example: * * ```js * var result = merge({foo: 123}, {foo: 456}); * console.log(result.foo); // outputs 456 * ``` * * @param {Object} obj1 Object to merge * @returns {Object} Result of all merge properties */ function merge(/* obj1, obj2, obj3, ... */) { var result = {}; function assignValue(val, key) { if (typeof result[key] === 'object' && typeof val === 'object') { result[key] = merge(result[key], val); } else { result[key] = val; } } for (var i = 0, l = arguments.length; i < l; i++) { forEach(arguments[i], assignValue); } return result; } /** * Function equal to merge with the difference being that no reference * to original objects is kept. * * @see merge * @param {Object} obj1 Object to merge * @returns {Object} Result of all merge properties */ function deepMerge(/* obj1, obj2, obj3, ... */) { var result = {}; function assignValue(val, key) { if (typeof result[key] === 'object' && typeof val === 'object') { result[key] = deepMerge(result[key], val); } else if (typeof val === 'object') { result[key] = deepMerge({}, val); } else { result[key] = val; } } for (var i = 0, l = arguments.length; i < l; i++) { forEach(arguments[i], assignValue); } return result; } /** * Extends object a by mutably adding to it the properties of object b. * * @param {Object} a The object to be extended * @param {Object} b The object to copy properties from * @param {Object} thisArg The object to bind function to * @return {Object} The resulting value of object a */ function extend(a, b, thisArg) { forEach(b, function assignValue(val, key) { if (thisArg && typeof val === 'function') { a[key] = bind(val, thisArg); } else { a[key] = val; } }); return a; } module.exports = { isArray: isArray, isArrayBuffer: isArrayBuffer, isBuffer: isBuffer, isFormData: isFormData, isArrayBufferView: isArrayBufferView, isString: isString, isNumber: isNumber, isObject: isObject, isUndefined: isUndefined, isDate: isDate, isFile: isFile, isBlob: isBlob, isFunction: isFunction, isStream: isStream, isURLSearchParams: isURLSearchParams, isStandardBrowserEnv: isStandardBrowserEnv, forEach: forEach, merge: merge, deepMerge: deepMerge, extend: extend, trim: trim }; /***/ }), /***/ "./node_modules/axios/node_modules/is-buffer/index.js": /*!************************************************************!*\ !*** ./node_modules/axios/node_modules/is-buffer/index.js ***! \************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { /*! * Determine if an object is a Buffer * * @author Feross Aboukhadijeh <https://feross.org> * @license MIT */ module.exports = function isBuffer (obj) { return obj != null && obj.constructor != null && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) } /***/ }), /***/ "./node_modules/process/browser.js": /*!*****************************************!*\ !*** ./node_modules/process/browser.js ***! \*****************************************/ /*! no static exports found */ /***/ (function(module, exports) { // shim for using process in browser var process = module.exports = {}; // cached from whatever global is present so that test runners that stub it // don't break things. But we need to wrap it in a try catch in case it is // wrapped in strict mode code which doesn't define any globals. It's inside a // function because try/catches deoptimize in certain engines. var cachedSetTimeout; var cachedClearTimeout; function defaultSetTimout() { throw new Error('setTimeout has not been defined'); } function defaultClearTimeout () { throw new Error('clearTimeout has not been defined'); } (function () { try { if (typeof setTimeout === 'function') { cachedSetTimeout = setTimeout; } else { cachedSetTimeout = defaultSetTimout; } } catch (e) { cachedSetTimeout = defaultSetTimout; } try { if (typeof clearTimeout === 'function') { cachedClearTimeout = clearTimeout; } else { cachedClearTimeout = defaultClearTimeout; } } catch (e) { cachedClearTimeout = defaultClearTimeout; } } ()) function runTimeout(fun) { if (cachedSetTimeout === setTimeout) { //normal enviroments in sane situations return setTimeout(fun, 0); } // if setTimeout wasn't available but was latter defined if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { cachedSetTimeout = setTimeout; return setTimeout(fun, 0); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedSetTimeout(fun, 0); } catch(e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedSetTimeout.call(null, fun, 0); } catch(e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error return cachedSetTimeout.call(this, fun, 0); } } } function runClearTimeout(marker) { if (cachedClearTimeout === clearTimeout) { //normal enviroments in sane situations return clearTimeout(marker); } // if clearTimeout wasn't available but was latter defined if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { cachedClearTimeout = clearTimeout; return clearTimeout(marker); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedClearTimeout(marker); } catch (e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedClearTimeout.call(null, marker); } catch (e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. // Some versions of I.E. have different rules for clearTimeout vs setTimeout return cachedClearTimeout.call(this, marker); } } } var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { if (!draining || !currentQueue) { return; } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = runTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; runClearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { runTimeout(drainQueue); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.prependListener = noop; process.prependOnceListener = noop; process.listeners = function (name) { return [] } process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; /***/ }), /***/ "./node_modules/setimmediate/setImmediate.js": /*!***************************************************!*\ !*** ./node_modules/setimmediate/setImmediate.js ***! \***************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global, process) {(function (global, undefined) { "use strict"; if (global.setImmediate) { return; } var nextHandle = 1; // Spec says greater than zero var tasksByHandle = {}; var currentlyRunningATask = false; var doc = global.document; var registerImmediate; function setImmediate(callback) { // Callback can either be a function or a string if (typeof callback !== "function") { callback = new Function("" + callback); } // Copy function arguments var args = new Array(arguments.length - 1); for (var i = 0; i < args.length; i++) { args[i] = arguments[i + 1]; } // Store and register the task var task = { callback: callback, args: args }; tasksByHandle[nextHandle] = task; registerImmediate(nextHandle); return nextHandle++; } function clearImmediate(handle) { delete tasksByHandle[handle]; } function run(task) { var callback = task.callback; var args = task.args; switch (args.length) { case 0: callback(); break; case 1: callback(args[0]); break; case 2: callback(args[0], args[1]); break; case 3: callback(args[0], args[1], args[2]); break; default: callback.apply(undefined, args); break; } } function runIfPresent(handle) { // From the spec: "Wait until any invocations of this algorithm started before this one have completed." // So if we're currently running a task, we'll need to delay this invocation. if (currentlyRunningATask) { // Delay by doing a setTimeout. setImmediate was tried instead, but in Firefox 7 it generated a // "too much recursion" error. setTimeout(runIfPresent, 0, handle); } else { var task = tasksByHandle[handle]; if (task) { currentlyRunningATask = true; try { run(task); } finally { clearImmediate(handle); currentlyRunningATask = false; } } } } function installNextTickImplementation() { registerImmediate = function(handle) { process.nextTick(function () { runIfPresent(handle); }); }; } function canUsePostMessage() { // The test against `importScripts` prevents this implementation from being installed inside a web worker, // where `global.postMessage` means something completely different and can't be used for this purpose. if (global.postMessage && !global.importScripts) { var postMessageIsAsynchronous = true; var oldOnMessage = global.onmessage; global.onmessage = function() { postMessageIsAsynchronous = false; }; global.postMessage("", "*"); global.onmessage = oldOnMessage; return postMessageIsAsynchronous; } } function installPostMessageImplementation() { // Installs an event handler on `global` for the `message` event: see // * https://developer.mozilla.org/en/DOM/window.postMessage // * http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages var messagePrefix = "setImmediate$" + Math.random() + "$"; var onGlobalMessage = function(event) { if (event.source === global && typeof event.data === "string" && event.data.indexOf(messagePrefix) === 0) { runIfPresent(+event.data.slice(messagePrefix.length)); } }; if (global.addEventListener) { global.addEventListener("message", onGlobalMessage, false); } else { global.attachEvent("onmessage", onGlobalMessage); } registerImmediate = function(handle) { global.postMessage(messagePrefix + handle, "*"); }; } function installMessageChannelImplementation() { var channel = new MessageChannel(); channel.port1.onmessage = function(event) { var handle = event.data; runIfPresent(handle); }; registerImmediate = function(handle) { channel.port2.postMessage(handle); }; } function installReadyStateChangeImplementation() { var html = doc.documentElement; registerImmediate = function(handle) { // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called. var script = doc.createElement("script"); script.onreadystatechange = function () { runIfPresent(handle); script.onreadystatechange = null; html.removeChild(script); script = null; }; html.appendChild(script); }; } function installSetTimeoutImplementation() { registerImmediate = function(handle) { setTimeout(runIfPresent, 0, handle); }; } // If supported, we should attach to the prototype of global, since that is where setTimeout et al. live. var attachTo = Object.getPrototypeOf && Object.getPrototypeOf(global); attachTo = attachTo && attachTo.setTimeout ? attachTo : global; // Don't get fooled by e.g. browserify environments. if ({}.toString.call(global.process) === "[object process]") { // For Node.js before 0.9 installNextTickImplementation(); } else if (canUsePostMessage()) { // For non-IE10 modern browsers installPostMessageImplementation(); } else if (global.MessageChannel) { // For web workers, where supported installMessageChannelImplementation(); } else if (doc && "onreadystatechange" in doc.createElement("script")) { // For IE 6–8 installReadyStateChangeImplementation(); } else { // For older browsers installSetTimeoutImplementation(); } attachTo.setImmediate = setImmediate; attachTo.clearImmediate = clearImmediate; }(typeof self === "undefined" ? typeof global === "undefined" ? this : global : self)); /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../webpack/buildin/global.js */ "./node_modules/webpack/buildin/global.js"), __webpack_require__(/*! ./../process/browser.js */ "./node_modules/process/browser.js"))) /***/ }), /***/ "./node_modules/timers-browserify/main.js": /*!************************************************!*\ !*** ./node_modules/timers-browserify/main.js ***! \************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {var scope = (typeof global !== "undefined" && global) || (typeof self !== "undefined" && self) || window; var apply = Function.prototype.apply; // DOM APIs, for completeness exports.setTimeout = function() { return new Timeout(apply.call(setTimeout, scope, arguments), clearTimeout); }; exports.setInterval = function() { return new Timeout(apply.call(setInterval, scope, arguments), clearInterval); }; exports.clearTimeout = exports.clearInterval = function(timeout) { if (timeout) { timeout.close(); } }; function Timeout(id, clearFn) { this._id = id; this._clearFn = clearFn; } Timeout.prototype.unref = Timeout.prototype.ref = function() {}; Timeout.prototype.close = function() { this._clearFn.call(scope, this._id); }; // Does not start the time, just sets up the members needed. exports.enroll = function(item, msecs) { clearTimeout(item._idleTimeoutId); item._idleTimeout = msecs; }; exports.unenroll = function(item) { clearTimeout(item._idleTimeoutId); item._idleTimeout = -1; }; exports._unrefActive = exports.active = function(item) { clearTimeout(item._idleTimeoutId); var msecs = item._idleTimeout; if (msecs >= 0) { item._idleTimeoutId = setTimeout(function onTimeout() { if (item._onTimeout) item._onTimeout(); }, msecs); } }; // setimmediate attaches itself to the global object __webpack_require__(/*! setimmediate */ "./node_modules/setimmediate/setImmediate.js"); // On some exotic environments, it's not clear which object `setimmediate` was // able to install onto. Search each possibility in the same order as the // `setimmediate` library. exports.setImmediate = (typeof self !== "undefined" && self.setImmediate) || (typeof global !== "undefined" && global.setImmediate) || (this && this.setImmediate); exports.clearImmediate = (typeof self !== "undefined" && self.clearImmediate) || (typeof global !== "undefined" && global.clearImmediate) || (this && this.clearImmediate); /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../webpack/buildin/global.js */ "./node_modules/webpack/buildin/global.js"))) /***/ }), /***/ "./node_modules/vue/dist/vue.common.dev.js": /*!*************************************************!*\ !*** ./node_modules/vue/dist/vue.common.dev.js ***! \*************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* WEBPACK VAR INJECTION */(function(global, setImmediate) {/*! * Vue.js v2.6.10 * (c) 2014-2019 Evan You * Released under the MIT License. */ /* */ var emptyObject = Object.freeze({}); // These helpers produce better VM code in JS engines due to their // explicitness and function inlining. function isUndef (v) { return v === undefined || v === null } function isDef (v) { return v !== undefined && v !== null } function isTrue (v) { return v === true } function isFalse (v) { return v === false } /** * Check if value is primitive. */ function isPrimitive (value) { return ( typeof value === 'string' || typeof value === 'number' || // $flow-disable-line typeof value === 'symbol' || typeof value === 'boolean' ) } /** * Quick object check - this is primarily used to tell * Objects from primitive values when we know the value * is a JSON-compliant type. */ function isObject (obj) { return obj !== null && typeof obj === 'object' } /** * Get the raw type string of a value, e.g., [object Object]. */ var _toString = Object.prototype.toString; function toRawType (value) { return _toString.call(value).slice(8, -1) } /** * Strict object type check. Only returns true * for plain JavaScript objects. */ function isPlainObject (obj) { return _toString.call(obj) === '[object Object]' } function isRegExp (v) { return _toString.call(v) === '[object RegExp]' } /** * Check if val is a valid array index. */ function isValidArrayIndex (val) { var n = parseFloat(String(val)); return n >= 0 && Math.floor(n) === n && isFinite(val) } function isPromise (val) { return ( isDef(val) && typeof val.then === 'function' && typeof val.catch === 'function' ) } /** * Convert a value to a string that is actually rendered. */ function toString (val) { return val == null ? '' : Array.isArray(val) || (isPlainObject(val) && val.toString === _toString) ? JSON.stringify(val, null, 2) : String(val) } /** * Convert an input value to a number for persistence. * If the conversion fails, return original string. */ function toNumber (val) { var n = parseFloat(val); return isNaN(n) ? val : n } /** * Make a map and return a function for checking if a key * is in that map. */ function makeMap ( str, expectsLowerCase ) { var map = Object.create(null); var list = str.split(','); for (var i = 0; i < list.length; i++) { map[list[i]] = true; } return expectsLowerCase ? function (val) { return map[val.toLowerCase()]; } : function (val) { return map[val]; } } /** * Check if a tag is a built-in tag. */ var isBuiltInTag = makeMap('slot,component', true); /** * Check if an attribute is a reserved attribute. */ var isReservedAttribute = makeMap('key,ref,slot,slot-scope,is'); /** * Remove an item from an array. */ function remove (arr, item) { if (arr.length) { var index = arr.indexOf(item); if (index > -1) { return arr.splice(index, 1) } } } /** * Check whether an object has the property. */ var hasOwnProperty = Object.prototype.hasOwnProperty; function hasOwn (obj, key) { return hasOwnProperty.call(obj, key) } /** * Create a cached version of a pure function. */ function cached (fn) { var cache = Object.create(null); return (function cachedFn (str) { var hit = cache[str]; return hit || (cache[str] = fn(str)) }) } /** * Camelize a hyphen-delimited string. */ var camelizeRE = /-(\w)/g; var camelize = cached(function (str) { return str.replace(camelizeRE, function (_, c) { return c ? c.toUpperCase() : ''; }) }); /** * Capitalize a string. */ var capitalize = cached(function (str) { return str.charAt(0).toUpperCase() + str.slice(1) }); /** * Hyphenate a camelCase string. */ var hyphenateRE = /\B([A-Z])/g; var hyphenate = cached(function (str) { return str.replace(hyphenateRE, '-$1').toLowerCase() }); /** * Simple bind polyfill for environments that do not support it, * e.g., PhantomJS 1.x. Technically, we don't need this anymore * since native bind is now performant enough in most browsers. * But removing it would mean breaking code that was able to run in * PhantomJS 1.x, so this must be kept for backward compatibility. */ /* istanbul ignore next */ function polyfillBind (fn, ctx) { function boundFn (a) { var l = arguments.length; return l ? l > 1 ? fn.apply(ctx, arguments) : fn.call(ctx, a) : fn.call(ctx) } boundFn._length = fn.length; return boundFn } function nativeBind (fn, ctx) { return fn.bind(ctx) } var bind = Function.prototype.bind ? nativeBind : polyfillBind; /** * Convert an Array-like object to a real Array. */ function toArray (list, start) { start = start || 0; var i = list.length - start; var ret = new Array(i); while (i--) { ret[i] = list[i + start]; } return ret } /** * Mix properties into target object. */ function extend (to, _from) { for (var key in _from) { to[key] = _from[key]; } return to } /** * Merge an Array of Objects into a single Object. */ function toObject (arr) { var res = {}; for (var i = 0; i < arr.length; i++) { if (arr[i]) { extend(res, arr[i]); } } return res } /* eslint-disable no-unused-vars */ /** * Perform no operation. * Stubbing args to make Flow happy without leaving useless transpiled code * with ...rest (https://flow.org/blog/2017/05/07/Strict-Function-Call-Arity/). */ function noop (a, b, c) {} /** * Always return false. */ var no = function (a, b, c) { return false; }; /* eslint-enable no-unused-vars */ /** * Return the same value. */ var identity = function (_) { return _; }; /** * Generate a string containing static keys from compiler modules. */ function genStaticKeys (modules) { return modules.reduce(function (keys, m) { return keys.concat(m.staticKeys || []) }, []).join(',') } /** * Check if two values are loosely equal - that is, * if they are plain objects, do they have the same shape? */ function looseEqual (a, b) { if (a === b) { return true } var isObjectA = isObject(a); var isObjectB = isObject(b); if (isObjectA && isObjectB) { try { var isArrayA = Array.isArray(a); var isArrayB = Array.isArray(b); if (isArrayA && isArrayB) { return a.length === b.length && a.every(function (e, i) { return looseEqual(e, b[i]) }) } else if (a instanceof Date && b instanceof Date) { return a.getTime() === b.getTime() } else if (!isArrayA && !isArrayB) { var keysA = Object.keys(a); var keysB = Object.keys(b); return keysA.length === keysB.length && keysA.every(function (key) { return looseEqual(a[key], b[key]) }) } else { /* istanbul ignore next */ return false } } catch (e) { /* istanbul ignore next */ return false } } else if (!isObjectA && !isObjectB) { return String(a) === String(b) } else { return false } } /** * Return the first index at which a loosely equal value can be * found in the array (if value is a plain object, the array must * contain an object of the same shape), or -1 if it is not present. */ function looseIndexOf (arr, val) { for (var i = 0; i < arr.length; i++) { if (looseEqual(arr[i], val)) { return i } } return -1 } /** * Ensure a function is called only once. */ function once (fn) { var called = false; return function () { if (!called) { called = true; fn.apply(this, arguments); } } } var SSR_ATTR = 'data-server-rendered'; var ASSET_TYPES = [ 'component', 'directive', 'filter' ]; var LIFECYCLE_HOOKS = [ 'beforeCreate', 'created', 'beforeMount', 'mounted', 'beforeUpdate', 'updated', 'beforeDestroy', 'destroyed', 'activated', 'deactivated', 'errorCaptured', 'serverPrefetch' ]; /* */ var config = ({ /** * Option merge strategies (used in core/util/options) */ // $flow-disable-line optionMergeStrategies: Object.create(null), /** * Whether to suppress warnings. */ silent: false, /** * Show production mode tip message on boot? */ productionTip: "development" !== 'production', /** * Whether to enable devtools */ devtools: "development" !== 'production', /** * Whether to record perf */ performance: false, /** * Error handler for watcher errors */ errorHandler: null, /** * Warn handler for watcher warns */ warnHandler: null, /** * Ignore certain custom elements */ ignoredElements: [], /** * Custom user key aliases for v-on */ // $flow-disable-line keyCodes: Object.create(null), /** * Check if a tag is reserved so that it cannot be registered as a * component. This is platform-dependent and may be overwritten. */ isReservedTag: no, /** * Check if an attribute is reserved so that it cannot be used as a component * prop. This is platform-dependent and may be overwritten. */ isReservedAttr: no, /** * Check if a tag is an unknown element. * Platform-dependent. */ isUnknownElement: no, /** * Get the namespace of an element */ getTagNamespace: noop, /** * Parse the real tag name for the specific platform. */ parsePlatformTagName: identity, /** * Check if an attribute must be bound using property, e.g. value * Platform-dependent. */ mustUseProp: no, /** * Perform updates asynchronously. Intended to be used by Vue Test Utils * This will significantly reduce performance if set to false. */ async: true, /** * Exposed for legacy reasons */ _lifecycleHooks: LIFECYCLE_HOOKS }); /* */ /** * unicode letters used for parsing html tags, component names and property paths. * using https://www.w3.org/TR/html53/semantics-scripting.html#potentialcustomelementname * skipping \u10000-\uEFFFF due to it freezing up PhantomJS */ var unicodeRegExp = /a-zA-Z\u00B7\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u037D\u037F-\u1FFF\u200C-\u200D\u203F-\u2040\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD/; /** * Check if a string starts with $ or _ */ function isReserved (str) { var c = (str + '').charCodeAt(0); return c === 0x24 || c === 0x5F } /** * Define a property. */ function def (obj, key, val, enumerable) { Object.defineProperty(obj, key, { value: val, enumerable: !!enumerable, writable: true, configurable: true }); } /** * Parse simple path. */ var bailRE = new RegExp(("[^" + (unicodeRegExp.source) + ".$_\\d]")); function parsePath (path) { if (bailRE.test(path)) { return } var segments = path.split('.'); return function (obj) { for (var i = 0; i < segments.length; i++) { if (!obj) { return } obj = obj[segments[i]]; } return obj } } /* */ // can we use __proto__? var hasProto = '__proto__' in {}; // Browser environment sniffing var inBrowser = typeof window !== 'undefined'; var inWeex = typeof WXEnvironment !== 'undefined' && !!WXEnvironment.platform; var weexPlatform = inWeex && WXEnvironment.platform.toLowerCase(); var UA = inBrowser && window.navigator.userAgent.toLowerCase(); var isIE = UA && /msie|trident/.test(UA); var isIE9 = UA && UA.indexOf('msie 9.0') > 0; var isEdge = UA && UA.indexOf('edge/') > 0; var isAndroid = (UA && UA.indexOf('android') > 0) || (weexPlatform === 'android'); var isIOS = (UA && /iphone|ipad|ipod|ios/.test(UA)) || (weexPlatform === 'ios'); var isChrome = UA && /chrome\/\d+/.test(UA) && !isEdge; var isPhantomJS = UA && /phantomjs/.test(UA); var isFF = UA && UA.match(/firefox\/(\d+)/); // Firefox has a "watch" function on Object.prototype... var nativeWatch = ({}).watch; var supportsPassive = false; if (inBrowser) { try { var opts = {}; Object.defineProperty(opts, 'passive', ({ get: function get () { /* istanbul ignore next */ supportsPassive = true; } })); // https://github.com/facebook/flow/issues/285 window.addEventListener('test-passive', null, opts); } catch (e) {} } // this needs to be lazy-evaled because vue may be required before // vue-server-renderer can set VUE_ENV var _isServer; var isServerRendering = function () { if (_isServer === undefined) { /* istanbul ignore if */ if (!inBrowser && !inWeex && typeof global !== 'undefined') { // detect presence of vue-server-renderer and avoid // Webpack shimming the process _isServer = global['process'] && global['process'].env.VUE_ENV === 'server'; } else { _isServer = false; } } return _isServer }; // detect devtools var devtools = inBrowser && window.__VUE_DEVTOOLS_GLOBAL_HOOK__; /* istanbul ignore next */ function isNative (Ctor) { return typeof Ctor === 'function' && /native code/.test(Ctor.toString()) } var hasSymbol = typeof Symbol !== 'undefined' && isNative(Symbol) && typeof Reflect !== 'undefined' && isNative(Reflect.ownKeys); var _Set; /* istanbul ignore if */ // $flow-disable-line if (typeof Set !== 'undefined' && isNative(Set)) { // use native Set when available. _Set = Set; } else { // a non-standard Set polyfill that only works with primitive keys. _Set = /*@__PURE__*/(function () { function Set () { this.set = Object.create(null); } Set.prototype.has = function has (key) { return this.set[key] === true }; Set.prototype.add = function add (key) { this.set[key] = true; }; Set.prototype.clear = function clear () { this.set = Object.create(null); }; return Set; }()); } /* */ var warn = noop; var tip = noop; var generateComponentTrace = (noop); // work around flow check var formatComponentName = (noop); { var hasConsole = typeof console !== 'undefined'; var classifyRE = /(?:^|[-_])(\w)/g; var classify = function (str) { return str .replace(classifyRE, function (c) { return c.toUpperCase(); }) .replace(/[-_]/g, ''); }; warn = function (msg, vm) { var trace = vm ? generateComponentTrace(vm) : ''; if (config.warnHandler) { config.warnHandler.call(null, msg, vm, trace); } else if (hasConsole && (!config.silent)) { console.error(("[Vue warn]: " + msg + trace)); } }; tip = function (msg, vm) { if (hasConsole && (!config.silent)) { console.warn("[Vue tip]: " + msg + ( vm ? generateComponentTrace(vm) : '' )); } }; formatComponentName = function (vm, includeFile) { if (vm.$root === vm) { return '<Root>' } var options = typeof vm === 'function' && vm.cid != null ? vm.options : vm._isVue ? vm.$options || vm.constructor.options : vm; var name = options.name || options._componentTag; var file = options.__file; if (!name && file) { var match = file.match(/([^/\\]+)\.vue$/); name = match && match[1]; } return ( (name ? ("<" + (classify(name)) + ">") : "<Anonymous>") + (file && includeFile !== false ? (" at " + file) : '') ) }; var repeat = function (str, n) { var res = ''; while (n) { if (n % 2 === 1) { res += str; } if (n > 1) { str += str; } n >>= 1; } return res }; generateComponentTrace = function (vm) { if (vm._isVue && vm.$parent) { var tree = []; var currentRecursiveSequence = 0; while (vm) { if (tree.length > 0) { var last = tree[tree.length - 1]; if (last.constructor === vm.constructor) { currentRecursiveSequence++; vm = vm.$parent; continue } else if (currentRecursiveSequence > 0) { tree[tree.length - 1] = [last, currentRecursiveSequence]; currentRecursiveSequence = 0; } } tree.push(vm); vm = vm.$parent; } return '\n\nfound in\n\n' + tree .map(function (vm, i) { return ("" + (i === 0 ? '---> ' : repeat(' ', 5 + i * 2)) + (Array.isArray(vm) ? ((formatComponentName(vm[0])) + "... (" + (vm[1]) + " recursive calls)") : formatComponentName(vm))); }) .join('\n') } else { return ("\n\n(found in " + (formatComponentName(vm)) + ")") } }; } /* */ var uid = 0; /** * A dep is an observable that can have multiple * directives subscribing to it. */ var Dep = function Dep () { this.id = uid++; this.subs = []; }; Dep.prototype.addSub = function addSub (sub) { this.subs.push(sub); }; Dep.prototype.removeSub = function removeSub (sub) { remove(this.subs, sub); }; Dep.prototype.depend = function depend () { if (Dep.target) { Dep.target.addDep(this); } }; Dep.prototype.notify = function notify () { // stabilize the subscriber list first var subs = this.subs.slice(); if (!config.async) { // subs aren't sorted in scheduler if not running async // we need to sort them now to make sure they fire in correct // order subs.sort(function (a, b) { return a.id - b.id; }); } for (var i = 0, l = subs.length; i < l; i++) { subs[i].update(); } }; // The current target watcher being evaluated. // This is globally unique because only one watcher // can be evaluated at a time. Dep.target = null; var targetStack = []; function pushTarget (target) { targetStack.push(target); Dep.target = target; } function popTarget () { targetStack.pop(); Dep.target = targetStack[targetStack.length - 1]; } /* */ var VNode = function VNode ( tag, data, children, text, elm, context, componentOptions, asyncFactory ) { this.tag = tag; this.data = data; this.children = children; this.text = text; this.elm = elm; this.ns = undefined; this.context = context; this.fnContext = undefined; this.fnOptions = undefined; this.fnScopeId = undefined; this.key = data && data.key; this.componentOptions = componentOptions; this.componentInstance = undefined; this.parent = undefined; this.raw = false; this.isStatic = false; this.isRootInsert = true; this.isComment = false; this.isCloned = false; this.isOnce = false; this.asyncFactory = asyncFactory; this.asyncMeta = undefined; this.isAsyncPlaceholder = false; }; var prototypeAccessors = { child: { configurable: true } }; // DEPRECATED: alias for componentInstance for backwards compat. /* istanbul ignore next */ prototypeAccessors.child.get = function () { return this.componentInstance }; Object.defineProperties( VNode.prototype, prototypeAccessors ); var createEmptyVNode = function (text) { if ( text === void 0 ) text = ''; var node = new VNode(); node.text = text; node.isComment = true; return node }; function createTextVNode (val) { return new VNode(undefined, undefined, undefined, String(val)) } // optimized shallow clone // used for static nodes and slot nodes because they may be reused across // multiple renders, cloning them avoids errors when DOM manipulations rely // on their elm reference. function cloneVNode (vnode) { var cloned = new VNode( vnode.tag, vnode.data, // #7975 // clone children array to avoid mutating original in case of cloning // a child. vnode.children && vnode.children.slice(), vnode.text, vnode.elm, vnode.context, vnode.componentOptions, vnode.asyncFactory ); cloned.ns = vnode.ns; cloned.isStatic = vnode.isStatic; cloned.key = vnode.key; cloned.isComment = vnode.isComment; cloned.fnContext = vnode.fnContext; cloned.fnOptions = vnode.fnOptions; cloned.fnScopeId = vnode.fnScopeId; cloned.asyncMeta = vnode.asyncMeta; cloned.isCloned = true; return cloned } /* * not type checking this file because flow doesn't play well with * dynamically accessing methods on Array prototype */ var arrayProto = Array.prototype; var arrayMethods = Object.create(arrayProto); var methodsToPatch = [ 'push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse' ]; /** * Intercept mutating methods and emit events */ methodsToPatch.forEach(function (method) { // cache original method var original = arrayProto[method]; def(arrayMethods, method, function mutator () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; var result = original.apply(this, args); var ob = this.__ob__; var inserted; switch (method) { case 'push': case 'unshift': inserted = args; break case 'splice': inserted = args.slice(2); break } if (inserted) { ob.observeArray(inserted); } // notify change ob.dep.notify(); return result }); }); /* */ var arrayKeys = Object.getOwnPropertyNames(arrayMethods); /** * In some cases we may want to disable observation inside a component's * update computation. */ var shouldObserve = true; function toggleObserving (value) { shouldObserve = value; } /** * Observer class that is attached to each observed * object. Once attached, the observer converts the target * object's property keys into getter/setters that * collect dependencies and dispatch updates. */ var Observer = function Observer (value) { this.value = value; this.dep = new Dep(); this.vmCount = 0; def(value, '__ob__', this); if (Array.isArray(value)) { if (hasProto) { protoAugment(value, arrayMethods); } else { copyAugment(value, arrayMethods, arrayKeys); } this.observeArray(value); } else { this.walk(value); } }; /** * Walk through all properties and convert them into * getter/setters. This method should only be called when * value type is Object. */ Observer.prototype.walk = function walk (obj) { var keys = Object.keys(obj); for (var i = 0; i < keys.length; i++) { defineReactive$$1(obj, keys[i]); } }; /** * Observe a list of Array items. */ Observer.prototype.observeArray = function observeArray (items) { for (var i = 0, l = items.length; i < l; i++) { observe(items[i]); } }; // helpers /** * Augment a target Object or Array by intercepting * the prototype chain using __proto__ */ function protoAugment (target, src) { /* eslint-disable no-proto */ target.__proto__ = src; /* eslint-enable no-proto */ } /** * Augment a target Object or Array by defining * hidden properties. */ /* istanbul ignore next */ function copyAugment (target, src, keys) { for (var i = 0, l = keys.length; i < l; i++) { var key = keys[i]; def(target, key, src[key]); } } /** * Attempt to create an observer instance for a value, * returns the new observer if successfully observed, * or the existing observer if the value already has one. */ function observe (value, asRootData) { if (!isObject(value) || value instanceof VNode) { return } var ob; if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) { ob = value.__ob__; } else if ( shouldObserve && !isServerRendering() && (Array.isArray(value) || isPlainObject(value)) && Object.isExtensible(value) && !value._isVue ) { ob = new Observer(value); } if (asRootData && ob) { ob.vmCount++; } return ob } /** * Define a reactive property on an Object. */ function defineReactive$$1 ( obj, key, val, customSetter, shallow ) { var dep = new Dep(); var property = Object.getOwnPropertyDescriptor(obj, key); if (property && property.configurable === false) { return } // cater for pre-defined getter/setters var getter = property && property.get; var setter = property && property.set; if ((!getter || setter) && arguments.length === 2) { val = obj[key]; } var childOb = !shallow && observe(val); Object.defineProperty(obj, key, { enumerable: true, configurable: true, get: function reactiveGetter () { var value = getter ? getter.call(obj) : val; if (Dep.target) { dep.depend(); if (childOb) { childOb.dep.depend(); if (Array.isArray(value)) { dependArray(value); } } } return value }, set: function reactiveSetter (newVal) { var value = getter ? getter.call(obj) : val; /* eslint-disable no-self-compare */ if (newVal === value || (newVal !== newVal && value !== value)) { return } /* eslint-enable no-self-compare */ if (customSetter) { customSetter(); } // #7981: for accessor properties without setter if (getter && !setter) { return } if (setter) { setter.call(obj, newVal); } else { val = newVal; } childOb = !shallow && observe(newVal); dep.notify(); } }); } /** * Set a property on an object. Adds the new property and * triggers change notification if the property doesn't * already exist. */ function set (target, key, val) { if (isUndef(target) || isPrimitive(target) ) { warn(("Cannot set reactive property on undefined, null, or primitive value: " + ((target)))); } if (Array.isArray(target) && isValidArrayIndex(key)) { target.length = Math.max(target.length, key); target.splice(key, 1, val); return val } if (key in target && !(key in Object.prototype)) { target[key] = val; return val } var ob = (target).__ob__; if (target._isVue || (ob && ob.vmCount)) { warn( 'Avoid adding reactive properties to a Vue instance or its root $data ' + 'at runtime - declare it upfront in the data option.' ); return val } if (!ob) { target[key] = val; return val } defineReactive$$1(ob.value, key, val); ob.dep.notify(); return val } /** * Delete a property and trigger change if necessary. */ function del (target, key) { if (isUndef(target) || isPrimitive(target) ) { warn(("Cannot delete reactive property on undefined, null, or primitive value: " + ((target)))); } if (Array.isArray(target) && isValidArrayIndex(key)) { target.splice(key, 1); return } var ob = (target).__ob__; if (target._isVue || (ob && ob.vmCount)) { warn( 'Avoid deleting properties on a Vue instance or its root $data ' + '- just set it to null.' ); return } if (!hasOwn(target, key)) { return } delete target[key]; if (!ob) { return } ob.dep.notify(); } /** * Collect dependencies on array elements when the array is touched, since * we cannot intercept array element access like property getters. */ function dependArray (value) { for (var e = (void 0), i = 0, l = value.length; i < l; i++) { e = value[i]; e && e.__ob__ && e.__ob__.dep.depend(); if (Array.isArray(e)) { dependArray(e); } } } /* */ /** * Option overwriting strategies are functions that handle * how to merge a parent option value and a child option * value into the final value. */ var strats = config.optionMergeStrategies; /** * Options with restrictions */ { strats.el = strats.propsData = function (parent, child, vm, key) { if (!vm) { warn( "option \"" + key + "\" can only be used during instance " + 'creation with the `new` keyword.' ); } return defaultStrat(parent, child) }; } /** * Helper that recursively merges two data objects together. */ function mergeData (to, from) { if (!from) { return to } var key, toVal, fromVal; var keys = hasSymbol ? Reflect.ownKeys(from) : Object.keys(from); for (var i = 0; i < keys.length; i++) { key = keys[i]; // in case the object is already observed... if (key === '__ob__') { continue } toVal = to[key]; fromVal = from[key]; if (!hasOwn(to, key)) { set(to, key, fromVal); } else if ( toVal !== fromVal && isPlainObject(toVal) && isPlainObject(fromVal) ) { mergeData(toVal, fromVal); } } return to } /** * Data */ function mergeDataOrFn ( parentVal, childVal, vm ) { if (!vm) { // in a Vue.extend merge, both should be functions if (!childVal) { return parentVal } if (!parentVal) { return childVal } // when parentVal & childVal are both present, // we need to return a function that returns the // merged result of both functions... no need to // check if parentVal is a function here because // it has to be a function to pass previous merges. return function mergedDataFn () { return mergeData( typeof childVal === 'function' ? childVal.call(this, this) : childVal, typeof parentVal === 'function' ? parentVal.call(this, this) : parentVal ) } } else { return function mergedInstanceDataFn () { // instance merge var instanceData = typeof childVal === 'function' ? childVal.call(vm, vm) : childVal; var defaultData = typeof parentVal === 'function' ? parentVal.call(vm, vm) : parentVal; if (instanceData) { return mergeData(instanceData, defaultData) } else { return defaultData } } } } strats.data = function ( parentVal, childVal, vm ) { if (!vm) { if (childVal && typeof childVal !== 'function') { warn( 'The "data" option should be a function ' + 'that returns a per-instance value in component ' + 'definitions.', vm ); return parentVal } return mergeDataOrFn(parentVal, childVal) } return mergeDataOrFn(parentVal, childVal, vm) }; /** * Hooks and props are merged as arrays. */ function mergeHook ( parentVal, childVal ) { var res = childVal ? parentVal ? parentVal.concat(childVal) : Array.isArray(childVal) ? childVal : [childVal] : parentVal; return res ? dedupeHooks(res) : res } function dedupeHooks (hooks) { var res = []; for (var i = 0; i < hooks.length; i++) { if (res.indexOf(hooks[i]) === -1) { res.push(hooks[i]); } } return res } LIFECYCLE_HOOKS.forEach(function (hook) { strats[hook] = mergeHook; }); /** * Assets * * When a vm is present (instance creation), we need to do * a three-way merge between constructor options, instance * options and parent options. */ function mergeAssets ( parentVal, childVal, vm, key ) { var res = Object.create(parentVal || null); if (childVal) { assertObjectType(key, childVal, vm); return extend(res, childVal) } else { return res } } ASSET_TYPES.forEach(function (type) { strats[type + 's'] = mergeAssets; }); /** * Watchers. * * Watchers hashes should not overwrite one * another, so we merge them as arrays. */ strats.watch = function ( parentVal, childVal, vm, key ) { // work around Firefox's Object.prototype.watch... if (parentVal === nativeWatch) { parentVal = undefined; } if (childVal === nativeWatch) { childVal = undefined; } /* istanbul ignore if */ if (!childVal) { return Object.create(parentVal || null) } { assertObjectType(key, childVal, vm); } if (!parentVal) { return childVal } var ret = {}; extend(ret, parentVal); for (var key$1 in childVal) { var parent = ret[key$1]; var child = childVal[key$1]; if (parent && !Array.isArray(parent)) { parent = [parent]; } ret[key$1] = parent ? parent.concat(child) : Array.isArray(child) ? child : [child]; } return ret }; /** * Other object hashes. */ strats.props = strats.methods = strats.inject = strats.computed = function ( parentVal, childVal, vm, key ) { if (childVal && "development" !== 'production') { assertObjectType(key, childVal, vm); } if (!parentVal) { return childVal } var ret = Object.create(null); extend(ret, parentVal); if (childVal) { extend(ret, childVal); } return ret }; strats.provide = mergeDataOrFn; /** * Default strategy. */ var defaultStrat = function (parentVal, childVal) { return childVal === undefined ? parentVal : childVal }; /** * Validate component names */ function checkComponents (options) { for (var key in options.components) { validateComponentName(key); } } function validateComponentName (name) { if (!new RegExp(("^[a-zA-Z][\\-\\.0-9_" + (unicodeRegExp.source) + "]*$")).test(name)) { warn( 'Invalid component name: "' + name + '". Component names ' + 'should conform to valid custom element name in html5 specification.' ); } if (isBuiltInTag(name) || config.isReservedTag(name)) { warn( 'Do not use built-in or reserved HTML elements as component ' + 'id: ' + name ); } } /** * Ensure all props option syntax are normalized into the * Object-based format. */ function normalizeProps (options, vm) { var props = options.props; if (!props) { return } var res = {}; var i, val, name; if (Array.isArray(props)) { i = props.length; while (i--) { val = props[i]; if (typeof val === 'string') { name = camelize(val); res[name] = { type: null }; } else { warn('props must be strings when using array syntax.'); } } } else if (isPlainObject(props)) { for (var key in props) { val = props[key]; name = camelize(key); res[name] = isPlainObject(val) ? val : { type: val }; } } else { warn( "Invalid value for option \"props\": expected an Array or an Object, " + "but got " + (toRawType(props)) + ".", vm ); } options.props = res; } /** * Normalize all injections into Object-based format */ function normalizeInject (options, vm) { var inject = options.inject; if (!inject) { return } var normalized = options.inject = {}; if (Array.isArray(inject)) { for (var i = 0; i < inject.length; i++) { normalized[inject[i]] = { from: inject[i] }; } } else if (isPlainObject(inject)) { for (var key in inject) { var val = inject[key]; normalized[key] = isPlainObject(val) ? extend({ from: key }, val) : { from: val }; } } else { warn( "Invalid value for option \"inject\": expected an Array or an Object, " + "but got " + (toRawType(inject)) + ".", vm ); } } /** * Normalize raw function directives into object format. */ function normalizeDirectives (options) { var dirs = options.directives; if (dirs) { for (var key in dirs) { var def$$1 = dirs[key]; if (typeof def$$1 === 'function') { dirs[key] = { bind: def$$1, update: def$$1 }; } } } } function assertObjectType (name, value, vm) { if (!isPlainObject(value)) { warn( "Invalid value for option \"" + name + "\": expected an Object, " + "but got " + (toRawType(value)) + ".", vm ); } } /** * Merge two option objects into a new one. * Core utility used in both instantiation and inheritance. */ function mergeOptions ( parent, child, vm ) { { checkComponents(child); } if (typeof child === 'function') { child = child.options; } normalizeProps(child, vm); normalizeInject(child, vm); normalizeDirectives(child); // Apply extends and mixins on the child options, // but only if it is a raw options object that isn't // the result of another mergeOptions call. // Only merged options has the _base property. if (!child._base) { if (child.extends) { parent = mergeOptions(parent, child.extends, vm); } if (child.mixins) { for (var i = 0, l = child.mixins.length; i < l; i++) { parent = mergeOptions(parent, child.mixins[i], vm); } } } var options = {}; var key; for (key in parent) { mergeField(key); } for (key in child) { if (!hasOwn(parent, key)) { mergeField(key); } } function mergeField (key) { var strat = strats[key] || defaultStrat; options[key] = strat(parent[key], child[key], vm, key); } return options } /** * Resolve an asset. * This function is used because child instances need access * to assets defined in its ancestor chain. */ function resolveAsset ( options, type, id, warnMissing ) { /* istanbul ignore if */ if (typeof id !== 'string') { return } var assets = options[type]; // check local registration variations first if (hasOwn(assets, id)) { return assets[id] } var camelizedId = camelize(id); if (hasOwn(assets, camelizedId)) { return assets[camelizedId] } var PascalCaseId = capitalize(camelizedId); if (hasOwn(assets, PascalCaseId)) { return assets[PascalCaseId] } // fallback to prototype chain var res = assets[id] || assets[camelizedId] || assets[PascalCaseId]; if (warnMissing && !res) { warn( 'Failed to resolve ' + type.slice(0, -1) + ': ' + id, options ); } return res } /* */ function validateProp ( key, propOptions, propsData, vm ) { var prop = propOptions[key]; var absent = !hasOwn(propsData, key); var value = propsData[key]; // boolean casting var booleanIndex = getTypeIndex(Boolean, prop.type); if (booleanIndex > -1) { if (absent && !hasOwn(prop, 'default')) { value = false; } else if (value === '' || value === hyphenate(key)) { // only cast empty string / same name to boolean if // boolean has higher priority var stringIndex = getTypeIndex(String, prop.type); if (stringIndex < 0 || booleanIndex < stringIndex) { value = true; } } } // check default value if (value === undefined) { value = getPropDefaultValue(vm, prop, key); // since the default value is a fresh copy, // make sure to observe it. var prevShouldObserve = shouldObserve; toggleObserving(true); observe(value); toggleObserving(prevShouldObserve); } { assertProp(prop, key, value, vm, absent); } return value } /** * Get the default value of a prop. */ function getPropDefaultValue (vm, prop, key) { // no default, return undefined if (!hasOwn(prop, 'default')) { return undefined } var def = prop.default; // warn against non-factory defaults for Object & Array if (isObject(def)) { warn( 'Invalid default value for prop "' + key + '": ' + 'Props with type Object/Array must use a factory function ' + 'to return the default value.', vm ); } // the raw prop value was also undefined from previous render, // return previous default value to avoid unnecessary watcher trigger if (vm && vm.$options.propsData && vm.$options.propsData[key] === undefined && vm._props[key] !== undefined ) { return vm._props[key] } // call factory function for non-Function types // a value is Function if its prototype is function even across different execution context return typeof def === 'function' && getType(prop.type) !== 'Function' ? def.call(vm) : def } /** * Assert whether a prop is valid. */ function assertProp ( prop, name, value, vm, absent ) { if (prop.required && absent) { warn( 'Missing required prop: "' + name + '"', vm ); return } if (value == null && !prop.required) { return } var type = prop.type; var valid = !type || type === true; var expectedTypes = []; if (type) { if (!Array.isArray(type)) { type = [type]; } for (var i = 0; i < type.length && !valid; i++) { var assertedType = assertType(value, type[i]); expectedTypes.push(assertedType.expectedType || ''); valid = assertedType.valid; } } if (!valid) { warn( getInvalidTypeMessage(name, value, expectedTypes), vm ); return } var validator = prop.validator; if (validator) { if (!validator(value)) { warn( 'Invalid prop: custom validator check failed for prop "' + name + '".', vm ); } } } var simpleCheckRE = /^(String|Number|Boolean|Function|Symbol)$/; function assertType (value, type) { var valid; var expectedType = getType(type); if (simpleCheckRE.test(expectedType)) { var t = typeof value; valid = t === expectedType.toLowerCase(); // for primitive wrapper objects if (!valid && t === 'object') { valid = value instanceof type; } } else if (expectedType === 'Object') { valid = isPlainObject(value); } else if (expectedType === 'Array') { valid = Array.isArray(value); } else { valid = value instanceof type; } return { valid: valid, expectedType: expectedType } } /** * Use function string name to check built-in types, * because a simple equality check will fail when running * across different vms / iframes. */ function getType (fn) { var match = fn && fn.toString().match(/^\s*function (\w+)/); return match ? match[1] : '' } function isSameType (a, b) { return getType(a) === getType(b) } function getTypeIndex (type, expectedTypes) { if (!Array.isArray(expectedTypes)) { return isSameType(expectedTypes, type) ? 0 : -1 } for (var i = 0, len = expectedTypes.length; i < len; i++) { if (isSameType(expectedTypes[i], type)) { return i } } return -1 } function getInvalidTypeMessage (name, value, expectedTypes) { var message = "Invalid prop: type check failed for prop \"" + name + "\"." + " Expected " + (expectedTypes.map(capitalize).join(', ')); var expectedType = expectedTypes[0]; var receivedType = toRawType(value); var expectedValue = styleValue(value, expectedType); var receivedValue = styleValue(value, receivedType); // check if we need to specify expected value if (expectedTypes.length === 1 && isExplicable(expectedType) && !isBoolean(expectedType, receivedType)) { message += " with value " + expectedValue; } message += ", got " + receivedType + " "; // check if we need to specify received value if (isExplicable(receivedType)) { message += "with value " + receivedValue + "."; } return message } function styleValue (value, type) { if (type === 'String') { return ("\"" + value + "\"") } else if (type === 'Number') { return ("" + (Number(value))) } else { return ("" + value) } } function isExplicable (value) { var explicitTypes = ['string', 'number', 'boolean']; return explicitTypes.some(function (elem) { return value.toLowerCase() === elem; }) } function isBoolean () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; return args.some(function (elem) { return elem.toLowerCase() === 'boolean'; }) } /* */ function handleError (err, vm, info) { // Deactivate deps tracking while processing error handler to avoid possible infinite rendering. // See: https://github.com/vuejs/vuex/issues/1505 pushTarget(); try { if (vm) { var cur = vm; while ((cur = cur.$parent)) { var hooks = cur.$options.errorCaptured; if (hooks) { for (var i = 0; i < hooks.length; i++) { try { var capture = hooks[i].call(cur, err, vm, info) === false; if (capture) { return } } catch (e) { globalHandleError(e, cur, 'errorCaptured hook'); } } } } } globalHandleError(err, vm, info); } finally { popTarget(); } } function invokeWithErrorHandling ( handler, context, args, vm, info ) { var res; try { res = args ? handler.apply(context, args) : handler.call(context); if (res && !res._isVue && isPromise(res) && !res._handled) { res.catch(function (e) { return handleError(e, vm, info + " (Promise/async)"); }); // issue #9511 // avoid catch triggering multiple times when nested calls res._handled = true; } } catch (e) { handleError(e, vm, info); } return res } function globalHandleError (err, vm, info) { if (config.errorHandler) { try { return config.errorHandler.call(null, err, vm, info) } catch (e) { // if the user intentionally throws the original error in the handler, // do not log it twice if (e !== err) { logError(e, null, 'config.errorHandler'); } } } logError(err, vm, info); } function logError (err, vm, info) { { warn(("Error in " + info + ": \"" + (err.toString()) + "\""), vm); } /* istanbul ignore else */ if ((inBrowser || inWeex) && typeof console !== 'undefined') { console.error(err); } else { throw err } } /* */ var isUsingMicroTask = false; var callbacks = []; var pending = false; function flushCallbacks () { pending = false; var copies = callbacks.slice(0); callbacks.length = 0; for (var i = 0; i < copies.length; i++) { copies[i](); } } // Here we have async deferring wrappers using microtasks. // In 2.5 we used (macro) tasks (in combination with microtasks). // However, it has subtle problems when state is changed right before repaint // (e.g. #6813, out-in transitions). // Also, using (macro) tasks in event handler would cause some weird behaviors // that cannot be circumvented (e.g. #7109, #7153, #7546, #7834, #8109). // So we now use microtasks everywhere, again. // A major drawback of this tradeoff is that there are some scenarios // where microtasks have too high a priority and fire in between supposedly // sequential events (e.g. #4521, #6690, which have workarounds) // or even between bubbling of the same event (#6566). var timerFunc; // The nextTick behavior leverages the microtask queue, which can be accessed // via either native Promise.then or MutationObserver. // MutationObserver has wider support, however it is seriously bugged in // UIWebView in iOS >= 9.3.3 when triggered in touch event handlers. It // completely stops working after triggering a few times... so, if native // Promise is available, we will use it: /* istanbul ignore next, $flow-disable-line */ if (typeof Promise !== 'undefined' && isNative(Promise)) { var p = Promise.resolve(); timerFunc = function () { p.then(flushCallbacks); // In problematic UIWebViews, Promise.then doesn't completely break, but // it can get stuck in a weird state where callbacks are pushed into the // microtask queue but the queue isn't being flushed, until the browser // needs to do some other work, e.g. handle a timer. Therefore we can // "force" the microtask queue to be flushed by adding an empty timer. if (isIOS) { setTimeout(noop); } }; isUsingMicroTask = true; } else if (!isIE && typeof MutationObserver !== 'undefined' && ( isNative(MutationObserver) || // PhantomJS and iOS 7.x MutationObserver.toString() === '[object MutationObserverConstructor]' )) { // Use MutationObserver where native Promise is not available, // e.g. PhantomJS, iOS7, Android 4.4 // (#6466 MutationObserver is unreliable in IE11) var counter = 1; var observer = new MutationObserver(flushCallbacks); var textNode = document.createTextNode(String(counter)); observer.observe(textNode, { characterData: true }); timerFunc = function () { counter = (counter + 1) % 2; textNode.data = String(counter); }; isUsingMicroTask = true; } else if (typeof setImmediate !== 'undefined' && isNative(setImmediate)) { // Fallback to setImmediate. // Techinically it leverages the (macro) task queue, // but it is still a better choice than setTimeout. timerFunc = function () { setImmediate(flushCallbacks); }; } else { // Fallback to setTimeout. timerFunc = function () { setTimeout(flushCallbacks, 0); }; } function nextTick (cb, ctx) { var _resolve; callbacks.push(function () { if (cb) { try { cb.call(ctx); } catch (e) { handleError(e, ctx, 'nextTick'); } } else if (_resolve) { _resolve(ctx); } }); if (!pending) { pending = true; timerFunc(); } // $flow-disable-line if (!cb && typeof Promise !== 'undefined') { return new Promise(function (resolve) { _resolve = resolve; }) } } /* */ var mark; var measure; { var perf = inBrowser && window.performance; /* istanbul ignore if */ if ( perf && perf.mark && perf.measure && perf.clearMarks && perf.clearMeasures ) { mark = function (tag) { return perf.mark(tag); }; measure = function (name, startTag, endTag) { perf.measure(name, startTag, endTag); perf.clearMarks(startTag); perf.clearMarks(endTag); // perf.clearMeasures(name) }; } } /* not type checking this file because flow doesn't play well with Proxy */ var initProxy; { var allowedGlobals = makeMap( 'Infinity,undefined,NaN,isFinite,isNaN,' + 'parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,' + 'Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,' + 'require' // for Webpack/Browserify ); var warnNonPresent = function (target, key) { warn( "Property or method \"" + key + "\" is not defined on the instance but " + 'referenced during render. Make sure that this property is reactive, ' + 'either in the data option, or for class-based components, by ' + 'initializing the property. ' + 'See: https://vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.', target ); }; var warnReservedPrefix = function (target, key) { warn( "Property \"" + key + "\" must be accessed with \"$data." + key + "\" because " + 'properties starting with "$" or "_" are not proxied in the Vue instance to ' + 'prevent conflicts with Vue internals' + 'See: https://vuejs.org/v2/api/#data', target ); }; var hasProxy = typeof Proxy !== 'undefined' && isNative(Proxy); if (hasProxy) { var isBuiltInModifier = makeMap('stop,prevent,self,ctrl,shift,alt,meta,exact'); config.keyCodes = new Proxy(config.keyCodes, { set: function set (target, key, value) { if (isBuiltInModifier(key)) { warn(("Avoid overwriting built-in modifier in config.keyCodes: ." + key)); return false } else { target[key] = value; return true } } }); } var hasHandler = { has: function has (target, key) { var has = key in target; var isAllowed = allowedGlobals(key) || (typeof key === 'string' && key.charAt(0) === '_' && !(key in target.$data)); if (!has && !isAllowed) { if (key in target.$data) { warnReservedPrefix(target, key); } else { warnNonPresent(target, key); } } return has || !isAllowed } }; var getHandler = { get: function get (target, key) { if (typeof key === 'string' && !(key in target)) { if (key in target.$data) { warnReservedPrefix(target, key); } else { warnNonPresent(target, key); } } return target[key] } }; initProxy = function initProxy (vm) { if (hasProxy) { // determine which proxy handler to use var options = vm.$options; var handlers = options.render && options.render._withStripped ? getHandler : hasHandler; vm._renderProxy = new Proxy(vm, handlers); } else { vm._renderProxy = vm; } }; } /* */ var seenObjects = new _Set(); /** * Recursively traverse an object to evoke all converted * getters, so that every nested property inside the object * is collected as a "deep" dependency. */ function traverse (val) { _traverse(val, seenObjects); seenObjects.clear(); } function _traverse (val, seen) { var i, keys; var isA = Array.isArray(val); if ((!isA && !isObject(val)) || Object.isFrozen(val) || val instanceof VNode) { return } if (val.__ob__) { var depId = val.__ob__.dep.id; if (seen.has(depId)) { return } seen.add(depId); } if (isA) { i = val.length; while (i--) { _traverse(val[i], seen); } } else { keys = Object.keys(val); i = keys.length; while (i--) { _traverse(val[keys[i]], seen); } } } /* */ var normalizeEvent = cached(function (name) { var passive = name.charAt(0) === '&'; name = passive ? name.slice(1) : name; var once$$1 = name.charAt(0) === '~'; // Prefixed last, checked first name = once$$1 ? name.slice(1) : name; var capture = name.charAt(0) === '!'; name = capture ? name.slice(1) : name; return { name: name, once: once$$1, capture: capture, passive: passive } }); function createFnInvoker (fns, vm) { function invoker () { var arguments$1 = arguments; var fns = invoker.fns; if (Array.isArray(fns)) { var cloned = fns.slice(); for (var i = 0; i < cloned.length; i++) { invokeWithErrorHandling(cloned[i], null, arguments$1, vm, "v-on handler"); } } else { // return handler return value for single handlers return invokeWithErrorHandling(fns, null, arguments, vm, "v-on handler") } } invoker.fns = fns; return invoker } function updateListeners ( on, oldOn, add, remove$$1, createOnceHandler, vm ) { var name, def$$1, cur, old, event; for (name in on) { def$$1 = cur = on[name]; old = oldOn[name]; event = normalizeEvent(name); if (isUndef(cur)) { warn( "Invalid handler for event \"" + (event.name) + "\": got " + String(cur), vm ); } else if (isUndef(old)) { if (isUndef(cur.fns)) { cur = on[name] = createFnInvoker(cur, vm); } if (isTrue(event.once)) { cur = on[name] = createOnceHandler(event.name, cur, event.capture); } add(event.name, cur, event.capture, event.passive, event.params); } else if (cur !== old) { old.fns = cur; on[name] = old; } } for (name in oldOn) { if (isUndef(on[name])) { event = normalizeEvent(name); remove$$1(event.name, oldOn[name], event.capture); } } } /* */ function mergeVNodeHook (def, hookKey, hook) { if (def instanceof VNode) { def = def.data.hook || (def.data.hook = {}); } var invoker; var oldHook = def[hookKey]; function wrappedHook () { hook.apply(this, arguments); // important: remove merged hook to ensure it's called only once // and prevent memory leak remove(invoker.fns, wrappedHook); } if (isUndef(oldHook)) { // no existing hook invoker = createFnInvoker([wrappedHook]); } else { /* istanbul ignore if */ if (isDef(oldHook.fns) && isTrue(oldHook.merged)) { // already a merged invoker invoker = oldHook; invoker.fns.push(wrappedHook); } else { // existing plain hook invoker = createFnInvoker([oldHook, wrappedHook]); } } invoker.merged = true; def[hookKey] = invoker; } /* */ function extractPropsFromVNodeData ( data, Ctor, tag ) { // we are only extracting raw values here. // validation and default values are handled in the child // component itself. var propOptions = Ctor.options.props; if (isUndef(propOptions)) { return } var res = {}; var attrs = data.attrs; var props = data.props; if (isDef(attrs) || isDef(props)) { for (var key in propOptions) { var altKey = hyphenate(key); { var keyInLowerCase = key.toLowerCase(); if ( key !== keyInLowerCase && attrs && hasOwn(attrs, keyInLowerCase) ) { tip( "Prop \"" + keyInLowerCase + "\" is passed to component " + (formatComponentName(tag || Ctor)) + ", but the declared prop name is" + " \"" + key + "\". " + "Note that HTML attributes are case-insensitive and camelCased " + "props need to use their kebab-case equivalents when using in-DOM " + "templates. You should probably use \"" + altKey + "\" instead of \"" + key + "\"." ); } } checkProp(res, props, key, altKey, true) || checkProp(res, attrs, key, altKey, false); } } return res } function checkProp ( res, hash, key, altKey, preserve ) { if (isDef(hash)) { if (hasOwn(hash, key)) { res[key] = hash[key]; if (!preserve) { delete hash[key]; } return true } else if (hasOwn(hash, altKey)) { res[key] = hash[altKey]; if (!preserve) { delete hash[altKey]; } return true } } return false } /* */ // The template compiler attempts to minimize the need for normalization by // statically analyzing the template at compile time. // // For plain HTML markup, normalization can be completely skipped because the // generated render function is guaranteed to return Array<VNode>. There are // two cases where extra normalization is needed: // 1. When the children contains components - because a functional component // may return an Array instead of a single root. In this case, just a simple // normalization is needed - if any child is an Array, we flatten the whole // thing with Array.prototype.concat. It is guaranteed to be only 1-level deep // because functional components already normalize their own children. function simpleNormalizeChildren (children) { for (var i = 0; i < children.length; i++) { if (Array.isArray(children[i])) { return Array.prototype.concat.apply([], children) } } return children } // 2. When the children contains constructs that always generated nested Arrays, // e.g. <template>, <slot>, v-for, or when the children is provided by user // with hand-written render functions / JSX. In such cases a full normalization // is needed to cater to all possible types of children values. function normalizeChildren (children) { return isPrimitive(children) ? [createTextVNode(children)] : Array.isArray(children) ? normalizeArrayChildren(children) : undefined } function isTextNode (node) { return isDef(node) && isDef(node.text) && isFalse(node.isComment) } function normalizeArrayChildren (children, nestedIndex) { var res = []; var i, c, lastIndex, last; for (i = 0; i < children.length; i++) { c = children[i]; if (isUndef(c) || typeof c === 'boolean') { continue } lastIndex = res.length - 1; last = res[lastIndex]; // nested if (Array.isArray(c)) { if (c.length > 0) { c = normalizeArrayChildren(c, ((nestedIndex || '') + "_" + i)); // merge adjacent text nodes if (isTextNode(c[0]) && isTextNode(last)) { res[lastIndex] = createTextVNode(last.text + (c[0]).text); c.shift(); } res.push.apply(res, c); } } else if (isPrimitive(c)) { if (isTextNode(last)) { // merge adjacent text nodes // this is necessary for SSR hydration because text nodes are // essentially merged when rendered to HTML strings res[lastIndex] = createTextVNode(last.text + c); } else if (c !== '') { // convert primitive to vnode res.push(createTextVNode(c)); } } else { if (isTextNode(c) && isTextNode(last)) { // merge adjacent text nodes res[lastIndex] = createTextVNode(last.text + c.text); } else { // default key for nested array children (likely generated by v-for) if (isTrue(children._isVList) && isDef(c.tag) && isUndef(c.key) && isDef(nestedIndex)) { c.key = "__vlist" + nestedIndex + "_" + i + "__"; } res.push(c); } } } return res } /* */ function initProvide (vm) { var provide = vm.$options.provide; if (provide) { vm._provided = typeof provide === 'function' ? provide.call(vm) : provide; } } function initInjections (vm) { var result = resolveInject(vm.$options.inject, vm); if (result) { toggleObserving(false); Object.keys(result).forEach(function (key) { /* istanbul ignore else */ { defineReactive$$1(vm, key, result[key], function () { warn( "Avoid mutating an injected value directly since the changes will be " + "overwritten whenever the provided component re-renders. " + "injection being mutated: \"" + key + "\"", vm ); }); } }); toggleObserving(true); } } function resolveInject (inject, vm) { if (inject) { // inject is :any because flow is not smart enough to figure out cached var result = Object.create(null); var keys = hasSymbol ? Reflect.ownKeys(inject) : Object.keys(inject); for (var i = 0; i < keys.length; i++) { var key = keys[i]; // #6574 in case the inject object is observed... if (key === '__ob__') { continue } var provideKey = inject[key].from; var source = vm; while (source) { if (source._provided && hasOwn(source._provided, provideKey)) { result[key] = source._provided[provideKey]; break } source = source.$parent; } if (!source) { if ('default' in inject[key]) { var provideDefault = inject[key].default; result[key] = typeof provideDefault === 'function' ? provideDefault.call(vm) : provideDefault; } else { warn(("Injection \"" + key + "\" not found"), vm); } } } return result } } /* */ /** * Runtime helper for resolving raw children VNodes into a slot object. */ function resolveSlots ( children, context ) { if (!children || !children.length) { return {} } var slots = {}; for (var i = 0, l = children.length; i < l; i++) { var child = children[i]; var data = child.data; // remove slot attribute if the node is resolved as a Vue slot node if (data && data.attrs && data.attrs.slot) { delete data.attrs.slot; } // named slots should only be respected if the vnode was rendered in the // same context. if ((child.context === context || child.fnContext === context) && data && data.slot != null ) { var name = data.slot; var slot = (slots[name] || (slots[name] = [])); if (child.tag === 'template') { slot.push.apply(slot, child.children || []); } else { slot.push(child); } } else { (slots.default || (slots.default = [])).push(child); } } // ignore slots that contains only whitespace for (var name$1 in slots) { if (slots[name$1].every(isWhitespace)) { delete slots[name$1]; } } return slots } function isWhitespace (node) { return (node.isComment && !node.asyncFactory) || node.text === ' ' } /* */ function normalizeScopedSlots ( slots, normalSlots, prevSlots ) { var res; var hasNormalSlots = Object.keys(normalSlots).length > 0; var isStable = slots ? !!slots.$stable : !hasNormalSlots; var key = slots && slots.$key; if (!slots) { res = {}; } else if (slots._normalized) { // fast path 1: child component re-render only, parent did not change return slots._normalized } else if ( isStable && prevSlots && prevSlots !== emptyObject && key === prevSlots.$key && !hasNormalSlots && !prevSlots.$hasNormal ) { // fast path 2: stable scoped slots w/ no normal slots to proxy, // only need to normalize once return prevSlots } else { res = {}; for (var key$1 in slots) { if (slots[key$1] && key$1[0] !== '$') { res[key$1] = normalizeScopedSlot(normalSlots, key$1, slots[key$1]); } } } // expose normal slots on scopedSlots for (var key$2 in normalSlots) { if (!(key$2 in res)) { res[key$2] = proxyNormalSlot(normalSlots, key$2); } } // avoriaz seems to mock a non-extensible $scopedSlots object // and when that is passed down this would cause an error if (slots && Object.isExtensible(slots)) { (slots)._normalized = res; } def(res, '$stable', isStable); def(res, '$key', key); def(res, '$hasNormal', hasNormalSlots); return res } function normalizeScopedSlot(normalSlots, key, fn) { var normalized = function () { var res = arguments.length ? fn.apply(null, arguments) : fn({}); res = res && typeof res === 'object' && !Array.isArray(res) ? [res] // single vnode : normalizeChildren(res); return res && ( res.length === 0 || (res.length === 1 && res[0].isComment) // #9658 ) ? undefined : res }; // this is a slot using the new v-slot syntax without scope. although it is // compiled as a scoped slot, render fn users would expect it to be present // on this.$slots because the usage is semantically a normal slot. if (fn.proxy) { Object.defineProperty(normalSlots, key, { get: normalized, enumerable: true, configurable: true }); } return normalized } function proxyNormalSlot(slots, key) { return function () { return slots[key]; } } /* */ /** * Runtime helper for rendering v-for lists. */ function renderList ( val, render ) { var ret, i, l, keys, key; if (Array.isArray(val) || typeof val === 'string') { ret = new Array(val.length); for (i = 0, l = val.length; i < l; i++) { ret[i] = render(val[i], i); } } else if (typeof val === 'number') { ret = new Array(val); for (i = 0; i < val; i++) { ret[i] = render(i + 1, i); } } else if (isObject(val)) { if (hasSymbol && val[Symbol.iterator]) { ret = []; var iterator = val[Symbol.iterator](); var result = iterator.next(); while (!result.done) { ret.push(render(result.value, ret.length)); result = iterator.next(); } } else { keys = Object.keys(val); ret = new Array(keys.length); for (i = 0, l = keys.length; i < l; i++) { key = keys[i]; ret[i] = render(val[key], key, i); } } } if (!isDef(ret)) { ret = []; } (ret)._isVList = true; return ret } /* */ /** * Runtime helper for rendering <slot> */ function renderSlot ( name, fallback, props, bindObject ) { var scopedSlotFn = this.$scopedSlots[name]; var nodes; if (scopedSlotFn) { // scoped slot props = props || {}; if (bindObject) { if (!isObject(bindObject)) { warn( 'slot v-bind without argument expects an Object', this ); } props = extend(extend({}, bindObject), props); } nodes = scopedSlotFn(props) || fallback; } else { nodes = this.$slots[name] || fallback; } var target = props && props.slot; if (target) { return this.$createElement('template', { slot: target }, nodes) } else { return nodes } } /* */ /** * Runtime helper for resolving filters */ function resolveFilter (id) { return resolveAsset(this.$options, 'filters', id, true) || identity } /* */ function isKeyNotMatch (expect, actual) { if (Array.isArray(expect)) { return expect.indexOf(actual) === -1 } else { return expect !== actual } } /** * Runtime helper for checking keyCodes from config. * exposed as Vue.prototype._k * passing in eventKeyName as last argument separately for backwards compat */ function checkKeyCodes ( eventKeyCode, key, builtInKeyCode, eventKeyName, builtInKeyName ) { var mappedKeyCode = config.keyCodes[key] || builtInKeyCode; if (builtInKeyName && eventKeyName && !config.keyCodes[key]) { return isKeyNotMatch(builtInKeyName, eventKeyName) } else if (mappedKeyCode) { return isKeyNotMatch(mappedKeyCode, eventKeyCode) } else if (eventKeyName) { return hyphenate(eventKeyName) !== key } } /* */ /** * Runtime helper for merging v-bind="object" into a VNode's data. */ function bindObjectProps ( data, tag, value, asProp, isSync ) { if (value) { if (!isObject(value)) { warn( 'v-bind without argument expects an Object or Array value', this ); } else { if (Array.isArray(value)) { value = toObject(value); } var hash; var loop = function ( key ) { if ( key === 'class' || key === 'style' || isReservedAttribute(key) ) { hash = data; } else { var type = data.attrs && data.attrs.type; hash = asProp || config.mustUseProp(tag, type, key) ? data.domProps || (data.domProps = {}) : data.attrs || (data.attrs = {}); } var camelizedKey = camelize(key); var hyphenatedKey = hyphenate(key); if (!(camelizedKey in hash) && !(hyphenatedKey in hash)) { hash[key] = value[key]; if (isSync) { var on = data.on || (data.on = {}); on[("update:" + key)] = function ($event) { value[key] = $event; }; } } }; for (var key in value) loop( key ); } } return data } /* */ /** * Runtime helper for rendering static trees. */ function renderStatic ( index, isInFor ) { var cached = this._staticTrees || (this._staticTrees = []); var tree = cached[index]; // if has already-rendered static tree and not inside v-for, // we can reuse the same tree. if (tree && !isInFor) { return tree } // otherwise, render a fresh tree. tree = cached[index] = this.$options.staticRenderFns[index].call( this._renderProxy, null, this // for render fns generated for functional component templates ); markStatic(tree, ("__static__" + index), false); return tree } /** * Runtime helper for v-once. * Effectively it means marking the node as static with a unique key. */ function markOnce ( tree, index, key ) { markStatic(tree, ("__once__" + index + (key ? ("_" + key) : "")), true); return tree } function markStatic ( tree, key, isOnce ) { if (Array.isArray(tree)) { for (var i = 0; i < tree.length; i++) { if (tree[i] && typeof tree[i] !== 'string') { markStaticNode(tree[i], (key + "_" + i), isOnce); } } } else { markStaticNode(tree, key, isOnce); } } function markStaticNode (node, key, isOnce) { node.isStatic = true; node.key = key; node.isOnce = isOnce; } /* */ function bindObjectListeners (data, value) { if (value) { if (!isPlainObject(value)) { warn( 'v-on without argument expects an Object value', this ); } else { var on = data.on = data.on ? extend({}, data.on) : {}; for (var key in value) { var existing = on[key]; var ours = value[key]; on[key] = existing ? [].concat(existing, ours) : ours; } } } return data } /* */ function resolveScopedSlots ( fns, // see flow/vnode res, // the following are added in 2.6 hasDynamicKeys, contentHashKey ) { res = res || { $stable: !hasDynamicKeys }; for (var i = 0; i < fns.length; i++) { var slot = fns[i]; if (Array.isArray(slot)) { resolveScopedSlots(slot, res, hasDynamicKeys); } else if (slot) { // marker for reverse proxying v-slot without scope on this.$slots if (slot.proxy) { slot.fn.proxy = true; } res[slot.key] = slot.fn; } } if (contentHashKey) { (res).$key = contentHashKey; } return res } /* */ function bindDynamicKeys (baseObj, values) { for (var i = 0; i < values.length; i += 2) { var key = values[i]; if (typeof key === 'string' && key) { baseObj[values[i]] = values[i + 1]; } else if (key !== '' && key !== null) { // null is a speical value for explicitly removing a binding warn( ("Invalid value for dynamic directive argument (expected string or null): " + key), this ); } } return baseObj } // helper to dynamically append modifier runtime markers to event names. // ensure only append when value is already string, otherwise it will be cast // to string and cause the type check to miss. function prependModifier (value, symbol) { return typeof value === 'string' ? symbol + value : value } /* */ function installRenderHelpers (target) { target._o = markOnce; target._n = toNumber; target._s = toString; target._l = renderList; target._t = renderSlot; target._q = looseEqual; target._i = looseIndexOf; target._m = renderStatic; target._f = resolveFilter; target._k = checkKeyCodes; target._b = bindObjectProps; target._v = createTextVNode; target._e = createEmptyVNode; target._u = resolveScopedSlots; target._g = bindObjectListeners; target._d = bindDynamicKeys; target._p = prependModifier; } /* */ function FunctionalRenderContext ( data, props, children, parent, Ctor ) { var this$1 = this; var options = Ctor.options; // ensure the createElement function in functional components // gets a unique context - this is necessary for correct named slot check var contextVm; if (hasOwn(parent, '_uid')) { contextVm = Object.create(parent); // $flow-disable-line contextVm._original = parent; } else { // the context vm passed in is a functional context as well. // in this case we want to make sure we are able to get a hold to the // real context instance. contextVm = parent; // $flow-disable-line parent = parent._original; } var isCompiled = isTrue(options._compiled); var needNormalization = !isCompiled; this.data = data; this.props = props; this.children = children; this.parent = parent; this.listeners = data.on || emptyObject; this.injections = resolveInject(options.inject, parent); this.slots = function () { if (!this$1.$slots) { normalizeScopedSlots( data.scopedSlots, this$1.$slots = resolveSlots(children, parent) ); } return this$1.$slots }; Object.defineProperty(this, 'scopedSlots', ({ enumerable: true, get: function get () { return normalizeScopedSlots(data.scopedSlots, this.slots()) } })); // support for compiled functional template if (isCompiled) { // exposing $options for renderStatic() this.$options = options; // pre-resolve slots for renderSlot() this.$slots = this.slots(); this.$scopedSlots = normalizeScopedSlots(data.scopedSlots, this.$slots); } if (options._scopeId) { this._c = function (a, b, c, d) { var vnode = createElement(contextVm, a, b, c, d, needNormalization); if (vnode && !Array.isArray(vnode)) { vnode.fnScopeId = options._scopeId; vnode.fnContext = parent; } return vnode }; } else { this._c = function (a, b, c, d) { return createElement(contextVm, a, b, c, d, needNormalization); }; } } installRenderHelpers(FunctionalRenderContext.prototype); function createFunctionalComponent ( Ctor, propsData, data, contextVm, children ) { var options = Ctor.options; var props = {}; var propOptions = options.props; if (isDef(propOptions)) { for (var key in propOptions) { props[key] = validateProp(key, propOptions, propsData || emptyObject); } } else { if (isDef(data.attrs)) { mergeProps(props, data.attrs); } if (isDef(data.props)) { mergeProps(props, data.props); } } var renderContext = new FunctionalRenderContext( data, props, children, contextVm, Ctor ); var vnode = options.render.call(null, renderContext._c, renderContext); if (vnode instanceof VNode) { return cloneAndMarkFunctionalResult(vnode, data, renderContext.parent, options, renderContext) } else if (Array.isArray(vnode)) { var vnodes = normalizeChildren(vnode) || []; var res = new Array(vnodes.length); for (var i = 0; i < vnodes.length; i++) { res[i] = cloneAndMarkFunctionalResult(vnodes[i], data, renderContext.parent, options, renderContext); } return res } } function cloneAndMarkFunctionalResult (vnode, data, contextVm, options, renderContext) { // #7817 clone node before setting fnContext, otherwise if the node is reused // (e.g. it was from a cached normal slot) the fnContext causes named slots // that should not be matched to match. var clone = cloneVNode(vnode); clone.fnContext = contextVm; clone.fnOptions = options; { (clone.devtoolsMeta = clone.devtoolsMeta || {}).renderContext = renderContext; } if (data.slot) { (clone.data || (clone.data = {})).slot = data.slot; } return clone } function mergeProps (to, from) { for (var key in from) { to[camelize(key)] = from[key]; } } /* */ /* */ /* */ /* */ // inline hooks to be invoked on component VNodes during patch var componentVNodeHooks = { init: function init (vnode, hydrating) { if ( vnode.componentInstance && !vnode.componentInstance._isDestroyed && vnode.data.keepAlive ) { // kept-alive components, treat as a patch var mountedNode = vnode; // work around flow componentVNodeHooks.prepatch(mountedNode, mountedNode); } else { var child = vnode.componentInstance = createComponentInstanceForVnode( vnode, activeInstance ); child.$mount(hydrating ? vnode.elm : undefined, hydrating); } }, prepatch: function prepatch (oldVnode, vnode) { var options = vnode.componentOptions; var child = vnode.componentInstance = oldVnode.componentInstance; updateChildComponent( child, options.propsData, // updated props options.listeners, // updated listeners vnode, // new parent vnode options.children // new children ); }, insert: function insert (vnode) { var context = vnode.context; var componentInstance = vnode.componentInstance; if (!componentInstance._isMounted) { componentInstance._isMounted = true; callHook(componentInstance, 'mounted'); } if (vnode.data.keepAlive) { if (context._isMounted) { // vue-router#1212 // During updates, a kept-alive component's child components may // change, so directly walking the tree here may call activated hooks // on incorrect children. Instead we push them into a queue which will // be processed after the whole patch process ended. queueActivatedComponent(componentInstance); } else { activateChildComponent(componentInstance, true /* direct */); } } }, destroy: function destroy (vnode) { var componentInstance = vnode.componentInstance; if (!componentInstance._isDestroyed) { if (!vnode.data.keepAlive) { componentInstance.$destroy(); } else { deactivateChildComponent(componentInstance, true /* direct */); } } } }; var hooksToMerge = Object.keys(componentVNodeHooks); function createComponent ( Ctor, data, context, children, tag ) { if (isUndef(Ctor)) { return } var baseCtor = context.$options._base; // plain options object: turn it into a constructor if (isObject(Ctor)) { Ctor = baseCtor.extend(Ctor); } // if at this stage it's not a constructor or an async component factory, // reject. if (typeof Ctor !== 'function') { { warn(("Invalid Component definition: " + (String(Ctor))), context); } return } // async component var asyncFactory; if (isUndef(Ctor.cid)) { asyncFactory = Ctor; Ctor = resolveAsyncComponent(asyncFactory, baseCtor); if (Ctor === undefined) { // return a placeholder node for async component, which is rendered // as a comment node but preserves all the raw information for the node. // the information will be used for async server-rendering and hydration. return createAsyncPlaceholder( asyncFactory, data, context, children, tag ) } } data = data || {}; // resolve constructor options in case global mixins are applied after // component constructor creation resolveConstructorOptions(Ctor); // transform component v-model data into props & events if (isDef(data.model)) { transformModel(Ctor.options, data); } // extract props var propsData = extractPropsFromVNodeData(data, Ctor, tag); // functional component if (isTrue(Ctor.options.functional)) { return createFunctionalComponent(Ctor, propsData, data, context, children) } // extract listeners, since these needs to be treated as // child component listeners instead of DOM listeners var listeners = data.on; // replace with listeners with .native modifier // so it gets processed during parent component patch. data.on = data.nativeOn; if (isTrue(Ctor.options.abstract)) { // abstract components do not keep anything // other than props & listeners & slot // work around flow var slot = data.slot; data = {}; if (slot) { data.slot = slot; } } // install component management hooks onto the placeholder node installComponentHooks(data); // return a placeholder vnode var name = Ctor.options.name || tag; var vnode = new VNode( ("vue-component-" + (Ctor.cid) + (name ? ("-" + name) : '')), data, undefined, undefined, undefined, context, { Ctor: Ctor, propsData: propsData, listeners: listeners, tag: tag, children: children }, asyncFactory ); return vnode } function createComponentInstanceForVnode ( vnode, // we know it's MountedComponentVNode but flow doesn't parent // activeInstance in lifecycle state ) { var options = { _isComponent: true, _parentVnode: vnode, parent: parent }; // check inline-template render functions var inlineTemplate = vnode.data.inlineTemplate; if (isDef(inlineTemplate)) { options.render = inlineTemplate.render; options.staticRenderFns = inlineTemplate.staticRenderFns; } return new vnode.componentOptions.Ctor(options) } function installComponentHooks (data) { var hooks = data.hook || (data.hook = {}); for (var i = 0; i < hooksToMerge.length; i++) { var key = hooksToMerge[i]; var existing = hooks[key]; var toMerge = componentVNodeHooks[key]; if (existing !== toMerge && !(existing && existing._merged)) { hooks[key] = existing ? mergeHook$1(toMerge, existing) : toMerge; } } } function mergeHook$1 (f1, f2) { var merged = function (a, b) { // flow complains about extra args which is why we use any f1(a, b); f2(a, b); }; merged._merged = true; return merged } // transform component v-model info (value and callback) into // prop and event handler respectively. function transformModel (options, data) { var prop = (options.model && options.model.prop) || 'value'; var event = (options.model && options.model.event) || 'input' ;(data.attrs || (data.attrs = {}))[prop] = data.model.value; var on = data.on || (data.on = {}); var existing = on[event]; var callback = data.model.callback; if (isDef(existing)) { if ( Array.isArray(existing) ? existing.indexOf(callback) === -1 : existing !== callback ) { on[event] = [callback].concat(existing); } } else { on[event] = callback; } } /* */ var SIMPLE_NORMALIZE = 1; var ALWAYS_NORMALIZE = 2; // wrapper function for providing a more flexible interface // without getting yelled at by flow function createElement ( context, tag, data, children, normalizationType, alwaysNormalize ) { if (Array.isArray(data) || isPrimitive(data)) { normalizationType = children; children = data; data = undefined; } if (isTrue(alwaysNormalize)) { normalizationType = ALWAYS_NORMALIZE; } return _createElement(context, tag, data, children, normalizationType) } function _createElement ( context, tag, data, children, normalizationType ) { if (isDef(data) && isDef((data).__ob__)) { warn( "Avoid using observed data object as vnode data: " + (JSON.stringify(data)) + "\n" + 'Always create fresh vnode data objects in each render!', context ); return createEmptyVNode() } // object syntax in v-bind if (isDef(data) && isDef(data.is)) { tag = data.is; } if (!tag) { // in case of component :is set to falsy value return createEmptyVNode() } // warn against non-primitive key if (isDef(data) && isDef(data.key) && !isPrimitive(data.key) ) { { warn( 'Avoid using non-primitive value as key, ' + 'use string/number value instead.', context ); } } // support single function children as default scoped slot if (Array.isArray(children) && typeof children[0] === 'function' ) { data = data || {}; data.scopedSlots = { default: children[0] }; children.length = 0; } if (normalizationType === ALWAYS_NORMALIZE) { children = normalizeChildren(children); } else if (normalizationType === SIMPLE_NORMALIZE) { children = simpleNormalizeChildren(children); } var vnode, ns; if (typeof tag === 'string') { var Ctor; ns = (context.$vnode && context.$vnode.ns) || config.getTagNamespace(tag); if (config.isReservedTag(tag)) { // platform built-in elements vnode = new VNode( config.parsePlatformTagName(tag), data, children, undefined, undefined, context ); } else if ((!data || !data.pre) && isDef(Ctor = resolveAsset(context.$options, 'components', tag))) { // component vnode = createComponent(Ctor, data, context, children, tag); } else { // unknown or unlisted namespaced elements // check at runtime because it may get assigned a namespace when its // parent normalizes children vnode = new VNode( tag, data, children, undefined, undefined, context ); } } else { // direct component options / constructor vnode = createComponent(tag, data, context, children); } if (Array.isArray(vnode)) { return vnode } else if (isDef(vnode)) { if (isDef(ns)) { applyNS(vnode, ns); } if (isDef(data)) { registerDeepBindings(data); } return vnode } else { return createEmptyVNode() } } function applyNS (vnode, ns, force) { vnode.ns = ns; if (vnode.tag === 'foreignObject') { // use default namespace inside foreignObject ns = undefined; force = true; } if (isDef(vnode.children)) { for (var i = 0, l = vnode.children.length; i < l; i++) { var child = vnode.children[i]; if (isDef(child.tag) && ( isUndef(child.ns) || (isTrue(force) && child.tag !== 'svg'))) { applyNS(child, ns, force); } } } } // ref #5318 // necessary to ensure parent re-render when deep bindings like :style and // :class are used on slot nodes function registerDeepBindings (data) { if (isObject(data.style)) { traverse(data.style); } if (isObject(data.class)) { traverse(data.class); } } /* */ function initRender (vm) { vm._vnode = null; // the root of the child tree vm._staticTrees = null; // v-once cached trees var options = vm.$options; var parentVnode = vm.$vnode = options._parentVnode; // the placeholder node in parent tree var renderContext = parentVnode && parentVnode.context; vm.$slots = resolveSlots(options._renderChildren, renderContext); vm.$scopedSlots = emptyObject; // bind the createElement fn to this instance // so that we get proper render context inside it. // args order: tag, data, children, normalizationType, alwaysNormalize // internal version is used by render functions compiled from templates vm._c = function (a, b, c, d) { return createElement(vm, a, b, c, d, false); }; // normalization is always applied for the public version, used in // user-written render functions. vm.$createElement = function (a, b, c, d) { return createElement(vm, a, b, c, d, true); }; // $attrs & $listeners are exposed for easier HOC creation. // they need to be reactive so that HOCs using them are always updated var parentData = parentVnode && parentVnode.data; /* istanbul ignore else */ { defineReactive$$1(vm, '$attrs', parentData && parentData.attrs || emptyObject, function () { !isUpdatingChildComponent && warn("$attrs is readonly.", vm); }, true); defineReactive$$1(vm, '$listeners', options._parentListeners || emptyObject, function () { !isUpdatingChildComponent && warn("$listeners is readonly.", vm); }, true); } } var currentRenderingInstance = null; function renderMixin (Vue) { // install runtime convenience helpers installRenderHelpers(Vue.prototype); Vue.prototype.$nextTick = function (fn) { return nextTick(fn, this) }; Vue.prototype._render = function () { var vm = this; var ref = vm.$options; var render = ref.render; var _parentVnode = ref._parentVnode; if (_parentVnode) { vm.$scopedSlots = normalizeScopedSlots( _parentVnode.data.scopedSlots, vm.$slots, vm.$scopedSlots ); } // set parent vnode. this allows render functions to have access // to the data on the placeholder node. vm.$vnode = _parentVnode; // render self var vnode; try { // There's no need to maintain a stack becaues all render fns are called // separately from one another. Nested component's render fns are called // when parent component is patched. currentRenderingInstance = vm; vnode = render.call(vm._renderProxy, vm.$createElement); } catch (e) { handleError(e, vm, "render"); // return error render result, // or previous vnode to prevent render error causing blank component /* istanbul ignore else */ if (vm.$options.renderError) { try { vnode = vm.$options.renderError.call(vm._renderProxy, vm.$createElement, e); } catch (e) { handleError(e, vm, "renderError"); vnode = vm._vnode; } } else { vnode = vm._vnode; } } finally { currentRenderingInstance = null; } // if the returned array contains only a single node, allow it if (Array.isArray(vnode) && vnode.length === 1) { vnode = vnode[0]; } // return empty vnode in case the render function errored out if (!(vnode instanceof VNode)) { if (Array.isArray(vnode)) { warn( 'Multiple root nodes returned from render function. Render function ' + 'should return a single root node.', vm ); } vnode = createEmptyVNode(); } // set parent vnode.parent = _parentVnode; return vnode }; } /* */ function ensureCtor (comp, base) { if ( comp.__esModule || (hasSymbol && comp[Symbol.toStringTag] === 'Module') ) { comp = comp.default; } return isObject(comp) ? base.extend(comp) : comp } function createAsyncPlaceholder ( factory, data, context, children, tag ) { var node = createEmptyVNode(); node.asyncFactory = factory; node.asyncMeta = { data: data, context: context, children: children, tag: tag }; return node } function resolveAsyncComponent ( factory, baseCtor ) { if (isTrue(factory.error) && isDef(factory.errorComp)) { return factory.errorComp } if (isDef(factory.resolved)) { return factory.resolved } var owner = currentRenderingInstance; if (owner && isDef(factory.owners) && factory.owners.indexOf(owner) === -1) { // already pending factory.owners.push(owner); } if (isTrue(factory.loading) && isDef(factory.loadingComp)) { return factory.loadingComp } if (owner && !isDef(factory.owners)) { var owners = factory.owners = [owner]; var sync = true; var timerLoading = null; var timerTimeout = null ;(owner).$on('hook:destroyed', function () { return remove(owners, owner); }); var forceRender = function (renderCompleted) { for (var i = 0, l = owners.length; i < l; i++) { (owners[i]).$forceUpdate(); } if (renderCompleted) { owners.length = 0; if (timerLoading !== null) { clearTimeout(timerLoading); timerLoading = null; } if (timerTimeout !== null) { clearTimeout(timerTimeout); timerTimeout = null; } } }; var resolve = once(function (res) { // cache resolved factory.resolved = ensureCtor(res, baseCtor); // invoke callbacks only if this is not a synchronous resolve // (async resolves are shimmed as synchronous during SSR) if (!sync) { forceRender(true); } else { owners.length = 0; } }); var reject = once(function (reason) { warn( "Failed to resolve async component: " + (String(factory)) + (reason ? ("\nReason: " + reason) : '') ); if (isDef(factory.errorComp)) { factory.error = true; forceRender(true); } }); var res = factory(resolve, reject); if (isObject(res)) { if (isPromise(res)) { // () => Promise if (isUndef(factory.resolved)) { res.then(resolve, reject); } } else if (isPromise(res.component)) { res.component.then(resolve, reject); if (isDef(res.error)) { factory.errorComp = ensureCtor(res.error, baseCtor); } if (isDef(res.loading)) { factory.loadingComp = ensureCtor(res.loading, baseCtor); if (res.delay === 0) { factory.loading = true; } else { timerLoading = setTimeout(function () { timerLoading = null; if (isUndef(factory.resolved) && isUndef(factory.error)) { factory.loading = true; forceRender(false); } }, res.delay || 200); } } if (isDef(res.timeout)) { timerTimeout = setTimeout(function () { timerTimeout = null; if (isUndef(factory.resolved)) { reject( "timeout (" + (res.timeout) + "ms)" ); } }, res.timeout); } } } sync = false; // return in case resolved synchronously return factory.loading ? factory.loadingComp : factory.resolved } } /* */ function isAsyncPlaceholder (node) { return node.isComment && node.asyncFactory } /* */ function getFirstComponentChild (children) { if (Array.isArray(children)) { for (var i = 0; i < children.length; i++) { var c = children[i]; if (isDef(c) && (isDef(c.componentOptions) || isAsyncPlaceholder(c))) { return c } } } } /* */ /* */ function initEvents (vm) { vm._events = Object.create(null); vm._hasHookEvent = false; // init parent attached events var listeners = vm.$options._parentListeners; if (listeners) { updateComponentListeners(vm, listeners); } } var target; function add (event, fn) { target.$on(event, fn); } function remove$1 (event, fn) { target.$off(event, fn); } function createOnceHandler (event, fn) { var _target = target; return function onceHandler () { var res = fn.apply(null, arguments); if (res !== null) { _target.$off(event, onceHandler); } } } function updateComponentListeners ( vm, listeners, oldListeners ) { target = vm; updateListeners(listeners, oldListeners || {}, add, remove$1, createOnceHandler, vm); target = undefined; } function eventsMixin (Vue) { var hookRE = /^hook:/; Vue.prototype.$on = function (event, fn) { var vm = this; if (Array.isArray(event)) { for (var i = 0, l = event.length; i < l; i++) { vm.$on(event[i], fn); } } else { (vm._events[event] || (vm._events[event] = [])).push(fn); // optimize hook:event cost by using a boolean flag marked at registration // instead of a hash lookup if (hookRE.test(event)) { vm._hasHookEvent = true; } } return vm }; Vue.prototype.$once = function (event, fn) { var vm = this; function on () { vm.$off(event, on); fn.apply(vm, arguments); } on.fn = fn; vm.$on(event, on); return vm }; Vue.prototype.$off = function (event, fn) { var vm = this; // all if (!arguments.length) { vm._events = Object.create(null); return vm } // array of events if (Array.isArray(event)) { for (var i$1 = 0, l = event.length; i$1 < l; i$1++) { vm.$off(event[i$1], fn); } return vm } // specific event var cbs = vm._events[event]; if (!cbs) { return vm } if (!fn) { vm._events[event] = null; return vm } // specific handler var cb; var i = cbs.length; while (i--) { cb = cbs[i]; if (cb === fn || cb.fn === fn) { cbs.splice(i, 1); break } } return vm }; Vue.prototype.$emit = function (event) { var vm = this; { var lowerCaseEvent = event.toLowerCase(); if (lowerCaseEvent !== event && vm._events[lowerCaseEvent]) { tip( "Event \"" + lowerCaseEvent + "\" is emitted in component " + (formatComponentName(vm)) + " but the handler is registered for \"" + event + "\". " + "Note that HTML attributes are case-insensitive and you cannot use " + "v-on to listen to camelCase events when using in-DOM templates. " + "You should probably use \"" + (hyphenate(event)) + "\" instead of \"" + event + "\"." ); } } var cbs = vm._events[event]; if (cbs) { cbs = cbs.length > 1 ? toArray(cbs) : cbs; var args = toArray(arguments, 1); var info = "event handler for \"" + event + "\""; for (var i = 0, l = cbs.length; i < l; i++) { invokeWithErrorHandling(cbs[i], vm, args, vm, info); } } return vm }; } /* */ var activeInstance = null; var isUpdatingChildComponent = false; function setActiveInstance(vm) { var prevActiveInstance = activeInstance; activeInstance = vm; return function () { activeInstance = prevActiveInstance; } } function initLifecycle (vm) { var options = vm.$options; // locate first non-abstract parent var parent = options.parent; if (parent && !options.abstract) { while (parent.$options.abstract && parent.$parent) { parent = parent.$parent; } parent.$children.push(vm); } vm.$parent = parent; vm.$root = parent ? parent.$root : vm; vm.$children = []; vm.$refs = {}; vm._watcher = null; vm._inactive = null; vm._directInactive = false; vm._isMounted = false; vm._isDestroyed = false; vm._isBeingDestroyed = false; } function lifecycleMixin (Vue) { Vue.prototype._update = function (vnode, hydrating) { var vm = this; var prevEl = vm.$el; var prevVnode = vm._vnode; var restoreActiveInstance = setActiveInstance(vm); vm._vnode = vnode; // Vue.prototype.__patch__ is injected in entry points // based on the rendering backend used. if (!prevVnode) { // initial render vm.$el = vm.__patch__(vm.$el, vnode, hydrating, false /* removeOnly */); } else { // updates vm.$el = vm.__patch__(prevVnode, vnode); } restoreActiveInstance(); // update __vue__ reference if (prevEl) { prevEl.__vue__ = null; } if (vm.$el) { vm.$el.__vue__ = vm; } // if parent is an HOC, update its $el as well if (vm.$vnode && vm.$parent && vm.$vnode === vm.$parent._vnode) { vm.$parent.$el = vm.$el; } // updated hook is called by the scheduler to ensure that children are // updated in a parent's updated hook. }; Vue.prototype.$forceUpdate = function () { var vm = this; if (vm._watcher) { vm._watcher.update(); } }; Vue.prototype.$destroy = function () { var vm = this; if (vm._isBeingDestroyed) { return } callHook(vm, 'beforeDestroy'); vm._isBeingDestroyed = true; // remove self from parent var parent = vm.$parent; if (parent && !parent._isBeingDestroyed && !vm.$options.abstract) { remove(parent.$children, vm); } // teardown watchers if (vm._watcher) { vm._watcher.teardown(); } var i = vm._watchers.length; while (i--) { vm._watchers[i].teardown(); } // remove reference from data ob // frozen object may not have observer. if (vm._data.__ob__) { vm._data.__ob__.vmCount--; } // call the last hook... vm._isDestroyed = true; // invoke destroy hooks on current rendered tree vm.__patch__(vm._vnode, null); // fire destroyed hook callHook(vm, 'destroyed'); // turn off all instance listeners. vm.$off(); // remove __vue__ reference if (vm.$el) { vm.$el.__vue__ = null; } // release circular reference (#6759) if (vm.$vnode) { vm.$vnode.parent = null; } }; } function mountComponent ( vm, el, hydrating ) { vm.$el = el; if (!vm.$options.render) { vm.$options.render = createEmptyVNode; { /* istanbul ignore if */ if ((vm.$options.template && vm.$options.template.charAt(0) !== '#') || vm.$options.el || el) { warn( 'You are using the runtime-only build of Vue where the template ' + 'compiler is not available. Either pre-compile the templates into ' + 'render functions, or use the compiler-included build.', vm ); } else { warn( 'Failed to mount component: template or render function not defined.', vm ); } } } callHook(vm, 'beforeMount'); var updateComponent; /* istanbul ignore if */ if (config.performance && mark) { updateComponent = function () { var name = vm._name; var id = vm._uid; var startTag = "vue-perf-start:" + id; var endTag = "vue-perf-end:" + id; mark(startTag); var vnode = vm._render(); mark(endTag); measure(("vue " + name + " render"), startTag, endTag); mark(startTag); vm._update(vnode, hydrating); mark(endTag); measure(("vue " + name + " patch"), startTag, endTag); }; } else { updateComponent = function () { vm._update(vm._render(), hydrating); }; } // we set this to vm._watcher inside the watcher's constructor // since the watcher's initial patch may call $forceUpdate (e.g. inside child // component's mounted hook), which relies on vm._watcher being already defined new Watcher(vm, updateComponent, noop, { before: function before () { if (vm._isMounted && !vm._isDestroyed) { callHook(vm, 'beforeUpdate'); } } }, true /* isRenderWatcher */); hydrating = false; // manually mounted instance, call mounted on self // mounted is called for render-created child components in its inserted hook if (vm.$vnode == null) { vm._isMounted = true; callHook(vm, 'mounted'); } return vm } function updateChildComponent ( vm, propsData, listeners, parentVnode, renderChildren ) { { isUpdatingChildComponent = true; } // determine whether component has slot children // we need to do this before overwriting $options._renderChildren. // check if there are dynamic scopedSlots (hand-written or compiled but with // dynamic slot names). Static scoped slots compiled from template has the // "$stable" marker. var newScopedSlots = parentVnode.data.scopedSlots; var oldScopedSlots = vm.$scopedSlots; var hasDynamicScopedSlot = !!( (newScopedSlots && !newScopedSlots.$stable) || (oldScopedSlots !== emptyObject && !oldScopedSlots.$stable) || (newScopedSlots && vm.$scopedSlots.$key !== newScopedSlots.$key) ); // Any static slot children from the parent may have changed during parent's // update. Dynamic scoped slots may also have changed. In such cases, a forced // update is necessary to ensure correctness. var needsForceUpdate = !!( renderChildren || // has new static slots vm.$options._renderChildren || // has old static slots hasDynamicScopedSlot ); vm.$options._parentVnode = parentVnode; vm.$vnode = parentVnode; // update vm's placeholder node without re-render if (vm._vnode) { // update child tree's parent vm._vnode.parent = parentVnode; } vm.$options._renderChildren = renderChildren; // update $attrs and $listeners hash // these are also reactive so they may trigger child update if the child // used them during render vm.$attrs = parentVnode.data.attrs || emptyObject; vm.$listeners = listeners || emptyObject; // update props if (propsData && vm.$options.props) { toggleObserving(false); var props = vm._props; var propKeys = vm.$options._propKeys || []; for (var i = 0; i < propKeys.length; i++) { var key = propKeys[i]; var propOptions = vm.$options.props; // wtf flow? props[key] = validateProp(key, propOptions, propsData, vm); } toggleObserving(true); // keep a copy of raw propsData vm.$options.propsData = propsData; } // update listeners listeners = listeners || emptyObject; var oldListeners = vm.$options._parentListeners; vm.$options._parentListeners = listeners; updateComponentListeners(vm, listeners, oldListeners); // resolve slots + force update if has children if (needsForceUpdate) { vm.$slots = resolveSlots(renderChildren, parentVnode.context); vm.$forceUpdate(); } { isUpdatingChildComponent = false; } } function isInInactiveTree (vm) { while (vm && (vm = vm.$parent)) { if (vm._inactive) { return true } } return false } function activateChildComponent (vm, direct) { if (direct) { vm._directInactive = false; if (isInInactiveTree(vm)) { return } } else if (vm._directInactive) { return } if (vm._inactive || vm._inactive === null) { vm._inactive = false; for (var i = 0; i < vm.$children.length; i++) { activateChildComponent(vm.$children[i]); } callHook(vm, 'activated'); } } function deactivateChildComponent (vm, direct) { if (direct) { vm._directInactive = true; if (isInInactiveTree(vm)) { return } } if (!vm._inactive) { vm._inactive = true; for (var i = 0; i < vm.$children.length; i++) { deactivateChildComponent(vm.$children[i]); } callHook(vm, 'deactivated'); } } function callHook (vm, hook) { // #7573 disable dep collection when invoking lifecycle hooks pushTarget(); var handlers = vm.$options[hook]; var info = hook + " hook"; if (handlers) { for (var i = 0, j = handlers.length; i < j; i++) { invokeWithErrorHandling(handlers[i], vm, null, vm, info); } } if (vm._hasHookEvent) { vm.$emit('hook:' + hook); } popTarget(); } /* */ var MAX_UPDATE_COUNT = 100; var queue = []; var activatedChildren = []; var has = {}; var circular = {}; var waiting = false; var flushing = false; var index = 0; /** * Reset the scheduler's state. */ function resetSchedulerState () { index = queue.length = activatedChildren.length = 0; has = {}; { circular = {}; } waiting = flushing = false; } // Async edge case #6566 requires saving the timestamp when event listeners are // attached. However, calling performance.now() has a perf overhead especially // if the page has thousands of event listeners. Instead, we take a timestamp // every time the scheduler flushes and use that for all event listeners // attached during that flush. var currentFlushTimestamp = 0; // Async edge case fix requires storing an event listener's attach timestamp. var getNow = Date.now; // Determine what event timestamp the browser is using. Annoyingly, the // timestamp can either be hi-res (relative to page load) or low-res // (relative to UNIX epoch), so in order to compare time we have to use the // same timestamp type when saving the flush timestamp. // All IE versions use low-res event timestamps, and have problematic clock // implementations (#9632) if (inBrowser && !isIE) { var performance = window.performance; if ( performance && typeof performance.now === 'function' && getNow() > document.createEvent('Event').timeStamp ) { // if the event timestamp, although evaluated AFTER the Date.now(), is // smaller than it, it means the event is using a hi-res timestamp, // and we need to use the hi-res version for event listener timestamps as // well. getNow = function () { return performance.now(); }; } } /** * Flush both queues and run the watchers. */ function flushSchedulerQueue () { currentFlushTimestamp = getNow(); flushing = true; var watcher, id; // Sort queue before flush. // This ensures that: // 1. Components are updated from parent to child. (because parent is always // created before the child) // 2. A component's user watchers are run before its render watcher (because // user watchers are created before the render watcher) // 3. If a component is destroyed during a parent component's watcher run, // its watchers can be skipped. queue.sort(function (a, b) { return a.id - b.id; }); // do not cache length because more watchers might be pushed // as we run existing watchers for (index = 0; index < queue.length; index++) { watcher = queue[index]; if (watcher.before) { watcher.before(); } id = watcher.id; has[id] = null; watcher.run(); // in dev build, check and stop circular updates. if (has[id] != null) { circular[id] = (circular[id] || 0) + 1; if (circular[id] > MAX_UPDATE_COUNT) { warn( 'You may have an infinite update loop ' + ( watcher.user ? ("in watcher with expression \"" + (watcher.expression) + "\"") : "in a component render function." ), watcher.vm ); break } } } // keep copies of post queues before resetting state var activatedQueue = activatedChildren.slice(); var updatedQueue = queue.slice(); resetSchedulerState(); // call component updated and activated hooks callActivatedHooks(activatedQueue); callUpdatedHooks(updatedQueue); // devtool hook /* istanbul ignore if */ if (devtools && config.devtools) { devtools.emit('flush'); } } function callUpdatedHooks (queue) { var i = queue.length; while (i--) { var watcher = queue[i]; var vm = watcher.vm; if (vm._watcher === watcher && vm._isMounted && !vm._isDestroyed) { callHook(vm, 'updated'); } } } /** * Queue a kept-alive component that was activated during patch. * The queue will be processed after the entire tree has been patched. */ function queueActivatedComponent (vm) { // setting _inactive to false here so that a render function can // rely on checking whether it's in an inactive tree (e.g. router-view) vm._inactive = false; activatedChildren.push(vm); } function callActivatedHooks (queue) { for (var i = 0; i < queue.length; i++) { queue[i]._inactive = true; activateChildComponent(queue[i], true /* true */); } } /** * Push a watcher into the watcher queue. * Jobs with duplicate IDs will be skipped unless it's * pushed when the queue is being flushed. */ function queueWatcher (watcher) { var id = watcher.id; if (has[id] == null) { has[id] = true; if (!flushing) { queue.push(watcher); } else { // if already flushing, splice the watcher based on its id // if already past its id, it will be run next immediately. var i = queue.length - 1; while (i > index && queue[i].id > watcher.id) { i--; } queue.splice(i + 1, 0, watcher); } // queue the flush if (!waiting) { waiting = true; if (!config.async) { flushSchedulerQueue(); return } nextTick(flushSchedulerQueue); } } } /* */ var uid$2 = 0; /** * A watcher parses an expression, collects dependencies, * and fires callback when the expression value changes. * This is used for both the $watch() api and directives. */ var Watcher = function Watcher ( vm, expOrFn, cb, options, isRenderWatcher ) { this.vm = vm; if (isRenderWatcher) { vm._watcher = this; } vm._watchers.push(this); // options if (options) { this.deep = !!options.deep; this.user = !!options.user; this.lazy = !!options.lazy; this.sync = !!options.sync; this.before = options.before; } else { this.deep = this.user = this.lazy = this.sync = false; } this.cb = cb; this.id = ++uid$2; // uid for batching this.active = true; this.dirty = this.lazy; // for lazy watchers this.deps = []; this.newDeps = []; this.depIds = new _Set(); this.newDepIds = new _Set(); this.expression = expOrFn.toString(); // parse expression for getter if (typeof expOrFn === 'function') { this.getter = expOrFn; } else { this.getter = parsePath(expOrFn); if (!this.getter) { this.getter = noop; warn( "Failed watching path: \"" + expOrFn + "\" " + 'Watcher only accepts simple dot-delimited paths. ' + 'For full control, use a function instead.', vm ); } } this.value = this.lazy ? undefined : this.get(); }; /** * Evaluate the getter, and re-collect dependencies. */ Watcher.prototype.get = function get () { pushTarget(this); var value; var vm = this.vm; try { value = this.getter.call(vm, vm); } catch (e) { if (this.user) { handleError(e, vm, ("getter for watcher \"" + (this.expression) + "\"")); } else { throw e } } finally { // "touch" every property so they are all tracked as // dependencies for deep watching if (this.deep) { traverse(value); } popTarget(); this.cleanupDeps(); } return value }; /** * Add a dependency to this directive. */ Watcher.prototype.addDep = function addDep (dep) { var id = dep.id; if (!this.newDepIds.has(id)) { this.newDepIds.add(id); this.newDeps.push(dep); if (!this.depIds.has(id)) { dep.addSub(this); } } }; /** * Clean up for dependency collection. */ Watcher.prototype.cleanupDeps = function cleanupDeps () { var i = this.deps.length; while (i--) { var dep = this.deps[i]; if (!this.newDepIds.has(dep.id)) { dep.removeSub(this); } } var tmp = this.depIds; this.depIds = this.newDepIds; this.newDepIds = tmp; this.newDepIds.clear(); tmp = this.deps; this.deps = this.newDeps; this.newDeps = tmp; this.newDeps.length = 0; }; /** * Subscriber interface. * Will be called when a dependency changes. */ Watcher.prototype.update = function update () { /* istanbul ignore else */ if (this.lazy) { this.dirty = true; } else if (this.sync) { this.run(); } else { queueWatcher(this); } }; /** * Scheduler job interface. * Will be called by the scheduler. */ Watcher.prototype.run = function run () { if (this.active) { var value = this.get(); if ( value !== this.value || // Deep watchers and watchers on Object/Arrays should fire even // when the value is the same, because the value may // have mutated. isObject(value) || this.deep ) { // set new value var oldValue = this.value; this.value = value; if (this.user) { try { this.cb.call(this.vm, value, oldValue); } catch (e) { handleError(e, this.vm, ("callback for watcher \"" + (this.expression) + "\"")); } } else { this.cb.call(this.vm, value, oldValue); } } } }; /** * Evaluate the value of the watcher. * This only gets called for lazy watchers. */ Watcher.prototype.evaluate = function evaluate () { this.value = this.get(); this.dirty = false; }; /** * Depend on all deps collected by this watcher. */ Watcher.prototype.depend = function depend () { var i = this.deps.length; while (i--) { this.deps[i].depend(); } }; /** * Remove self from all dependencies' subscriber list. */ Watcher.prototype.teardown = function teardown () { if (this.active) { // remove self from vm's watcher list // this is a somewhat expensive operation so we skip it // if the vm is being destroyed. if (!this.vm._isBeingDestroyed) { remove(this.vm._watchers, this); } var i = this.deps.length; while (i--) { this.deps[i].removeSub(this); } this.active = false; } }; /* */ var sharedPropertyDefinition = { enumerable: true, configurable: true, get: noop, set: noop }; function proxy (target, sourceKey, key) { sharedPropertyDefinition.get = function proxyGetter () { return this[sourceKey][key] }; sharedPropertyDefinition.set = function proxySetter (val) { this[sourceKey][key] = val; }; Object.defineProperty(target, key, sharedPropertyDefinition); } function initState (vm) { vm._watchers = []; var opts = vm.$options; if (opts.props) { initProps(vm, opts.props); } if (opts.methods) { initMethods(vm, opts.methods); } if (opts.data) { initData(vm); } else { observe(vm._data = {}, true /* asRootData */); } if (opts.computed) { initComputed(vm, opts.computed); } if (opts.watch && opts.watch !== nativeWatch) { initWatch(vm, opts.watch); } } function initProps (vm, propsOptions) { var propsData = vm.$options.propsData || {}; var props = vm._props = {}; // cache prop keys so that future props updates can iterate using Array // instead of dynamic object key enumeration. var keys = vm.$options._propKeys = []; var isRoot = !vm.$parent; // root instance props should be converted if (!isRoot) { toggleObserving(false); } var loop = function ( key ) { keys.push(key); var value = validateProp(key, propsOptions, propsData, vm); /* istanbul ignore else */ { var hyphenatedKey = hyphenate(key); if (isReservedAttribute(hyphenatedKey) || config.isReservedAttr(hyphenatedKey)) { warn( ("\"" + hyphenatedKey + "\" is a reserved attribute and cannot be used as component prop."), vm ); } defineReactive$$1(props, key, value, function () { if (!isRoot && !isUpdatingChildComponent) { warn( "Avoid mutating a prop directly since the value will be " + "overwritten whenever the parent component re-renders. " + "Instead, use a data or computed property based on the prop's " + "value. Prop being mutated: \"" + key + "\"", vm ); } }); } // static props are already proxied on the component's prototype // during Vue.extend(). We only need to proxy props defined at // instantiation here. if (!(key in vm)) { proxy(vm, "_props", key); } }; for (var key in propsOptions) loop( key ); toggleObserving(true); } function initData (vm) { var data = vm.$options.data; data = vm._data = typeof data === 'function' ? getData(data, vm) : data || {}; if (!isPlainObject(data)) { data = {}; warn( 'data functions should return an object:\n' + 'https://vuejs.org/v2/guide/components.html#data-Must-Be-a-Function', vm ); } // proxy data on instance var keys = Object.keys(data); var props = vm.$options.props; var methods = vm.$options.methods; var i = keys.length; while (i--) { var key = keys[i]; { if (methods && hasOwn(methods, key)) { warn( ("Method \"" + key + "\" has already been defined as a data property."), vm ); } } if (props && hasOwn(props, key)) { warn( "The data property \"" + key + "\" is already declared as a prop. " + "Use prop default value instead.", vm ); } else if (!isReserved(key)) { proxy(vm, "_data", key); } } // observe data observe(data, true /* asRootData */); } function getData (data, vm) { // #7573 disable dep collection when invoking data getters pushTarget(); try { return data.call(vm, vm) } catch (e) { handleError(e, vm, "data()"); return {} } finally { popTarget(); } } var computedWatcherOptions = { lazy: true }; function initComputed (vm, computed) { // $flow-disable-line var watchers = vm._computedWatchers = Object.create(null); // computed properties are just getters during SSR var isSSR = isServerRendering(); for (var key in computed) { var userDef = computed[key]; var getter = typeof userDef === 'function' ? userDef : userDef.get; if (getter == null) { warn( ("Getter is missing for computed property \"" + key + "\"."), vm ); } if (!isSSR) { // create internal watcher for the computed property. watchers[key] = new Watcher( vm, getter || noop, noop, computedWatcherOptions ); } // component-defined computed properties are already defined on the // component prototype. We only need to define computed properties defined // at instantiation here. if (!(key in vm)) { defineComputed(vm, key, userDef); } else { if (key in vm.$data) { warn(("The computed property \"" + key + "\" is already defined in data."), vm); } else if (vm.$options.props && key in vm.$options.props) { warn(("The computed property \"" + key + "\" is already defined as a prop."), vm); } } } } function defineComputed ( target, key, userDef ) { var shouldCache = !isServerRendering(); if (typeof userDef === 'function') { sharedPropertyDefinition.get = shouldCache ? createComputedGetter(key) : createGetterInvoker(userDef); sharedPropertyDefinition.set = noop; } else { sharedPropertyDefinition.get = userDef.get ? shouldCache && userDef.cache !== false ? createComputedGetter(key) : createGetterInvoker(userDef.get) : noop; sharedPropertyDefinition.set = userDef.set || noop; } if (sharedPropertyDefinition.set === noop) { sharedPropertyDefinition.set = function () { warn( ("Computed property \"" + key + "\" was assigned to but it has no setter."), this ); }; } Object.defineProperty(target, key, sharedPropertyDefinition); } function createComputedGetter (key) { return function computedGetter () { var watcher = this._computedWatchers && this._computedWatchers[key]; if (watcher) { if (watcher.dirty) { watcher.evaluate(); } if (Dep.target) { watcher.depend(); } return watcher.value } } } function createGetterInvoker(fn) { return function computedGetter () { return fn.call(this, this) } } function initMethods (vm, methods) { var props = vm.$options.props; for (var key in methods) { { if (typeof methods[key] !== 'function') { warn( "Method \"" + key + "\" has type \"" + (typeof methods[key]) + "\" in the component definition. " + "Did you reference the function correctly?", vm ); } if (props && hasOwn(props, key)) { warn( ("Method \"" + key + "\" has already been defined as a prop."), vm ); } if ((key in vm) && isReserved(key)) { warn( "Method \"" + key + "\" conflicts with an existing Vue instance method. " + "Avoid defining component methods that start with _ or $." ); } } vm[key] = typeof methods[key] !== 'function' ? noop : bind(methods[key], vm); } } function initWatch (vm, watch) { for (var key in watch) { var handler = watch[key]; if (Array.isArray(handler)) { for (var i = 0; i < handler.length; i++) { createWatcher(vm, key, handler[i]); } } else { createWatcher(vm, key, handler); } } } function createWatcher ( vm, expOrFn, handler, options ) { if (isPlainObject(handler)) { options = handler; handler = handler.handler; } if (typeof handler === 'string') { handler = vm[handler]; } return vm.$watch(expOrFn, handler, options) } function stateMixin (Vue) { // flow somehow has problems with directly declared definition object // when using Object.defineProperty, so we have to procedurally build up // the object here. var dataDef = {}; dataDef.get = function () { return this._data }; var propsDef = {}; propsDef.get = function () { return this._props }; { dataDef.set = function () { warn( 'Avoid replacing instance root $data. ' + 'Use nested data properties instead.', this ); }; propsDef.set = function () { warn("$props is readonly.", this); }; } Object.defineProperty(Vue.prototype, '$data', dataDef); Object.defineProperty(Vue.prototype, '$props', propsDef); Vue.prototype.$set = set; Vue.prototype.$delete = del; Vue.prototype.$watch = function ( expOrFn, cb, options ) { var vm = this; if (isPlainObject(cb)) { return createWatcher(vm, expOrFn, cb, options) } options = options || {}; options.user = true; var watcher = new Watcher(vm, expOrFn, cb, options); if (options.immediate) { try { cb.call(vm, watcher.value); } catch (error) { handleError(error, vm, ("callback for immediate watcher \"" + (watcher.expression) + "\"")); } } return function unwatchFn () { watcher.teardown(); } }; } /* */ var uid$3 = 0; function initMixin (Vue) { Vue.prototype._init = function (options) { var vm = this; // a uid vm._uid = uid$3++; var startTag, endTag; /* istanbul ignore if */ if (config.performance && mark) { startTag = "vue-perf-start:" + (vm._uid); endTag = "vue-perf-end:" + (vm._uid); mark(startTag); } // a flag to avoid this being observed vm._isVue = true; // merge options if (options && options._isComponent) { // optimize internal component instantiation // since dynamic options merging is pretty slow, and none of the // internal component options needs special treatment. initInternalComponent(vm, options); } else { vm.$options = mergeOptions( resolveConstructorOptions(vm.constructor), options || {}, vm ); } /* istanbul ignore else */ { initProxy(vm); } // expose real self vm._self = vm; initLifecycle(vm); initEvents(vm); initRender(vm); callHook(vm, 'beforeCreate'); initInjections(vm); // resolve injections before data/props initState(vm); initProvide(vm); // resolve provide after data/props callHook(vm, 'created'); /* istanbul ignore if */ if (config.performance && mark) { vm._name = formatComponentName(vm, false); mark(endTag); measure(("vue " + (vm._name) + " init"), startTag, endTag); } if (vm.$options.el) { vm.$mount(vm.$options.el); } }; } function initInternalComponent (vm, options) { var opts = vm.$options = Object.create(vm.constructor.options); // doing this because it's faster than dynamic enumeration. var parentVnode = options._parentVnode; opts.parent = options.parent; opts._parentVnode = parentVnode; var vnodeComponentOptions = parentVnode.componentOptions; opts.propsData = vnodeComponentOptions.propsData; opts._parentListeners = vnodeComponentOptions.listeners; opts._renderChildren = vnodeComponentOptions.children; opts._componentTag = vnodeComponentOptions.tag; if (options.render) { opts.render = options.render; opts.staticRenderFns = options.staticRenderFns; } } function resolveConstructorOptions (Ctor) { var options = Ctor.options; if (Ctor.super) { var superOptions = resolveConstructorOptions(Ctor.super); var cachedSuperOptions = Ctor.superOptions; if (superOptions !== cachedSuperOptions) { // super option changed, // need to resolve new options. Ctor.superOptions = superOptions; // check if there are any late-modified/attached options (#4976) var modifiedOptions = resolveModifiedOptions(Ctor); // update base extend options if (modifiedOptions) { extend(Ctor.extendOptions, modifiedOptions); } options = Ctor.options = mergeOptions(superOptions, Ctor.extendOptions); if (options.name) { options.components[options.name] = Ctor; } } } return options } function resolveModifiedOptions (Ctor) { var modified; var latest = Ctor.options; var sealed = Ctor.sealedOptions; for (var key in latest) { if (latest[key] !== sealed[key]) { if (!modified) { modified = {}; } modified[key] = latest[key]; } } return modified } function Vue (options) { if (!(this instanceof Vue) ) { warn('Vue is a constructor and should be called with the `new` keyword'); } this._init(options); } initMixin(Vue); stateMixin(Vue); eventsMixin(Vue); lifecycleMixin(Vue); renderMixin(Vue); /* */ function initUse (Vue) { Vue.use = function (plugin) { var installedPlugins = (this._installedPlugins || (this._installedPlugins = [])); if (installedPlugins.indexOf(plugin) > -1) { return this } // additional parameters var args = toArray(arguments, 1); args.unshift(this); if (typeof plugin.install === 'function') { plugin.install.apply(plugin, args); } else if (typeof plugin === 'function') { plugin.apply(null, args); } installedPlugins.push(plugin); return this }; } /* */ function initMixin$1 (Vue) { Vue.mixin = function (mixin) { this.options = mergeOptions(this.options, mixin); return this }; } /* */ function initExtend (Vue) { /** * Each instance constructor, including Vue, has a unique * cid. This enables us to create wrapped "child * constructors" for prototypal inheritance and cache them. */ Vue.cid = 0; var cid = 1; /** * Class inheritance */ Vue.extend = function (extendOptions) { extendOptions = extendOptions || {}; var Super = this; var SuperId = Super.cid; var cachedCtors = extendOptions._Ctor || (extendOptions._Ctor = {}); if (cachedCtors[SuperId]) { return cachedCtors[SuperId] } var name = extendOptions.name || Super.options.name; if (name) { validateComponentName(name); } var Sub = function VueComponent (options) { this._init(options); }; Sub.prototype = Object.create(Super.prototype); Sub.prototype.constructor = Sub; Sub.cid = cid++; Sub.options = mergeOptions( Super.options, extendOptions ); Sub['super'] = Super; // For props and computed properties, we define the proxy getters on // the Vue instances at extension time, on the extended prototype. This // avoids Object.defineProperty calls for each instance created. if (Sub.options.props) { initProps$1(Sub); } if (Sub.options.computed) { initComputed$1(Sub); } // allow further extension/mixin/plugin usage Sub.extend = Super.extend; Sub.mixin = Super.mixin; Sub.use = Super.use; // create asset registers, so extended classes // can have their private assets too. ASSET_TYPES.forEach(function (type) { Sub[type] = Super[type]; }); // enable recursive self-lookup if (name) { Sub.options.components[name] = Sub; } // keep a reference to the super options at extension time. // later at instantiation we can check if Super's options have // been updated. Sub.superOptions = Super.options; Sub.extendOptions = extendOptions; Sub.sealedOptions = extend({}, Sub.options); // cache constructor cachedCtors[SuperId] = Sub; return Sub }; } function initProps$1 (Comp) { var props = Comp.options.props; for (var key in props) { proxy(Comp.prototype, "_props", key); } } function initComputed$1 (Comp) { var computed = Comp.options.computed; for (var key in computed) { defineComputed(Comp.prototype, key, computed[key]); } } /* */ function initAssetRegisters (Vue) { /** * Create asset registration methods. */ ASSET_TYPES.forEach(function (type) { Vue[type] = function ( id, definition ) { if (!definition) { return this.options[type + 's'][id] } else { /* istanbul ignore if */ if (type === 'component') { validateComponentName(id); } if (type === 'component' && isPlainObject(definition)) { definition.name = definition.name || id; definition = this.options._base.extend(definition); } if (type === 'directive' && typeof definition === 'function') { definition = { bind: definition, update: definition }; } this.options[type + 's'][id] = definition; return definition } }; }); } /* */ function getComponentName (opts) { return opts && (opts.Ctor.options.name || opts.tag) } function matches (pattern, name) { if (Array.isArray(pattern)) { return pattern.indexOf(name) > -1 } else if (typeof pattern === 'string') { return pattern.split(',').indexOf(name) > -1 } else if (isRegExp(pattern)) { return pattern.test(name) } /* istanbul ignore next */ return false } function pruneCache (keepAliveInstance, filter) { var cache = keepAliveInstance.cache; var keys = keepAliveInstance.keys; var _vnode = keepAliveInstance._vnode; for (var key in cache) { var cachedNode = cache[key]; if (cachedNode) { var name = getComponentName(cachedNode.componentOptions); if (name && !filter(name)) { pruneCacheEntry(cache, key, keys, _vnode); } } } } function pruneCacheEntry ( cache, key, keys, current ) { var cached$$1 = cache[key]; if (cached$$1 && (!current || cached$$1.tag !== current.tag)) { cached$$1.componentInstance.$destroy(); } cache[key] = null; remove(keys, key); } var patternTypes = [String, RegExp, Array]; var KeepAlive = { name: 'keep-alive', abstract: true, props: { include: patternTypes, exclude: patternTypes, max: [String, Number] }, created: function created () { this.cache = Object.create(null); this.keys = []; }, destroyed: function destroyed () { for (var key in this.cache) { pruneCacheEntry(this.cache, key, this.keys); } }, mounted: function mounted () { var this$1 = this; this.$watch('include', function (val) { pruneCache(this$1, function (name) { return matches(val, name); }); }); this.$watch('exclude', function (val) { pruneCache(this$1, function (name) { return !matches(val, name); }); }); }, render: function render () { var slot = this.$slots.default; var vnode = getFirstComponentChild(slot); var componentOptions = vnode && vnode.componentOptions; if (componentOptions) { // check pattern var name = getComponentName(componentOptions); var ref = this; var include = ref.include; var exclude = ref.exclude; if ( // not included (include && (!name || !matches(include, name))) || // excluded (exclude && name && matches(exclude, name)) ) { return vnode } var ref$1 = this; var cache = ref$1.cache; var keys = ref$1.keys; var key = vnode.key == null // same constructor may get registered as different local components // so cid alone is not enough (#3269) ? componentOptions.Ctor.cid + (componentOptions.tag ? ("::" + (componentOptions.tag)) : '') : vnode.key; if (cache[key]) { vnode.componentInstance = cache[key].componentInstance; // make current key freshest remove(keys, key); keys.push(key); } else { cache[key] = vnode; keys.push(key); // prune oldest entry if (this.max && keys.length > parseInt(this.max)) { pruneCacheEntry(cache, keys[0], keys, this._vnode); } } vnode.data.keepAlive = true; } return vnode || (slot && slot[0]) } }; var builtInComponents = { KeepAlive: KeepAlive }; /* */ function initGlobalAPI (Vue) { // config var configDef = {}; configDef.get = function () { return config; }; { configDef.set = function () { warn( 'Do not replace the Vue.config object, set individual fields instead.' ); }; } Object.defineProperty(Vue, 'config', configDef); // exposed util methods. // NOTE: these are not considered part of the public API - avoid relying on // them unless you are aware of the risk. Vue.util = { warn: warn, extend: extend, mergeOptions: mergeOptions, defineReactive: defineReactive$$1 }; Vue.set = set; Vue.delete = del; Vue.nextTick = nextTick; // 2.6 explicit observable API Vue.observable = function (obj) { observe(obj); return obj }; Vue.options = Object.create(null); ASSET_TYPES.forEach(function (type) { Vue.options[type + 's'] = Object.create(null); }); // this is used to identify the "base" constructor to extend all plain-object // components with in Weex's multi-instance scenarios. Vue.options._base = Vue; extend(Vue.options.components, builtInComponents); initUse(Vue); initMixin$1(Vue); initExtend(Vue); initAssetRegisters(Vue); } initGlobalAPI(Vue); Object.defineProperty(Vue.prototype, '$isServer', { get: isServerRendering }); Object.defineProperty(Vue.prototype, '$ssrContext', { get: function get () { /* istanbul ignore next */ return this.$vnode && this.$vnode.ssrContext } }); // expose FunctionalRenderContext for ssr runtime helper installation Object.defineProperty(Vue, 'FunctionalRenderContext', { value: FunctionalRenderContext }); Vue.version = '2.6.10'; /* */ // these are reserved for web because they are directly compiled away // during template compilation var isReservedAttr = makeMap('style,class'); // attributes that should be using props for binding var acceptValue = makeMap('input,textarea,option,select,progress'); var mustUseProp = function (tag, type, attr) { return ( (attr === 'value' && acceptValue(tag)) && type !== 'button' || (attr === 'selected' && tag === 'option') || (attr === 'checked' && tag === 'input') || (attr === 'muted' && tag === 'video') ) }; var isEnumeratedAttr = makeMap('contenteditable,draggable,spellcheck'); var isValidContentEditableValue = makeMap('events,caret,typing,plaintext-only'); var convertEnumeratedValue = function (key, value) { return isFalsyAttrValue(value) || value === 'false' ? 'false' // allow arbitrary string value for contenteditable : key === 'contenteditable' && isValidContentEditableValue(value) ? value : 'true' }; var isBooleanAttr = makeMap( 'allowfullscreen,async,autofocus,autoplay,checked,compact,controls,declare,' + 'default,defaultchecked,defaultmuted,defaultselected,defer,disabled,' + 'enabled,formnovalidate,hidden,indeterminate,inert,ismap,itemscope,loop,multiple,' + 'muted,nohref,noresize,noshade,novalidate,nowrap,open,pauseonexit,readonly,' + 'required,reversed,scoped,seamless,selected,sortable,translate,' + 'truespeed,typemustmatch,visible' ); var xlinkNS = 'http://www.w3.org/1999/xlink'; var isXlink = function (name) { return name.charAt(5) === ':' && name.slice(0, 5) === 'xlink' }; var getXlinkProp = function (name) { return isXlink(name) ? name.slice(6, name.length) : '' }; var isFalsyAttrValue = function (val) { return val == null || val === false }; /* */ function genClassForVnode (vnode) { var data = vnode.data; var parentNode = vnode; var childNode = vnode; while (isDef(childNode.componentInstance)) { childNode = childNode.componentInstance._vnode; if (childNode && childNode.data) { data = mergeClassData(childNode.data, data); } } while (isDef(parentNode = parentNode.parent)) { if (parentNode && parentNode.data) { data = mergeClassData(data, parentNode.data); } } return renderClass(data.staticClass, data.class) } function mergeClassData (child, parent) { return { staticClass: concat(child.staticClass, parent.staticClass), class: isDef(child.class) ? [child.class, parent.class] : parent.class } } function renderClass ( staticClass, dynamicClass ) { if (isDef(staticClass) || isDef(dynamicClass)) { return concat(staticClass, stringifyClass(dynamicClass)) } /* istanbul ignore next */ return '' } function concat (a, b) { return a ? b ? (a + ' ' + b) : a : (b || '') } function stringifyClass (value) { if (Array.isArray(value)) { return stringifyArray(value) } if (isObject(value)) { return stringifyObject(value) } if (typeof value === 'string') { return value } /* istanbul ignore next */ return '' } function stringifyArray (value) { var res = ''; var stringified; for (var i = 0, l = value.length; i < l; i++) { if (isDef(stringified = stringifyClass(value[i])) && stringified !== '') { if (res) { res += ' '; } res += stringified; } } return res } function stringifyObject (value) { var res = ''; for (var key in value) { if (value[key]) { if (res) { res += ' '; } res += key; } } return res } /* */ var namespaceMap = { svg: 'http://www.w3.org/2000/svg', math: 'http://www.w3.org/1998/Math/MathML' }; var isHTMLTag = makeMap( 'html,body,base,head,link,meta,style,title,' + 'address,article,aside,footer,header,h1,h2,h3,h4,h5,h6,hgroup,nav,section,' + 'div,dd,dl,dt,figcaption,figure,picture,hr,img,li,main,ol,p,pre,ul,' + 'a,b,abbr,bdi,bdo,br,cite,code,data,dfn,em,i,kbd,mark,q,rp,rt,rtc,ruby,' + 's,samp,small,span,strong,sub,sup,time,u,var,wbr,area,audio,map,track,video,' + 'embed,object,param,source,canvas,script,noscript,del,ins,' + 'caption,col,colgroup,table,thead,tbody,td,th,tr,' + 'button,datalist,fieldset,form,input,label,legend,meter,optgroup,option,' + 'output,progress,select,textarea,' + 'details,dialog,menu,menuitem,summary,' + 'content,element,shadow,template,blockquote,iframe,tfoot' ); // this map is intentionally selective, only covering SVG elements that may // contain child elements. var isSVG = makeMap( 'svg,animate,circle,clippath,cursor,defs,desc,ellipse,filter,font-face,' + 'foreignObject,g,glyph,image,line,marker,mask,missing-glyph,path,pattern,' + 'polygon,polyline,rect,switch,symbol,text,textpath,tspan,use,view', true ); var isPreTag = function (tag) { return tag === 'pre'; }; var isReservedTag = function (tag) { return isHTMLTag(tag) || isSVG(tag) }; function getTagNamespace (tag) { if (isSVG(tag)) { return 'svg' } // basic support for MathML // note it doesn't support other MathML elements being component roots if (tag === 'math') { return 'math' } } var unknownElementCache = Object.create(null); function isUnknownElement (tag) { /* istanbul ignore if */ if (!inBrowser) { return true } if (isReservedTag(tag)) { return false } tag = tag.toLowerCase(); /* istanbul ignore if */ if (unknownElementCache[tag] != null) { return unknownElementCache[tag] } var el = document.createElement(tag); if (tag.indexOf('-') > -1) { // http://stackoverflow.com/a/28210364/1070244 return (unknownElementCache[tag] = ( el.constructor === window.HTMLUnknownElement || el.constructor === window.HTMLElement )) } else { return (unknownElementCache[tag] = /HTMLUnknownElement/.test(el.toString())) } } var isTextInputType = makeMap('text,number,password,search,email,tel,url'); /* */ /** * Query an element selector if it's not an element already. */ function query (el) { if (typeof el === 'string') { var selected = document.querySelector(el); if (!selected) { warn( 'Cannot find element: ' + el ); return document.createElement('div') } return selected } else { return el } } /* */ function createElement$1 (tagName, vnode) { var elm = document.createElement(tagName); if (tagName !== 'select') { return elm } // false or null will remove the attribute but undefined will not if (vnode.data && vnode.data.attrs && vnode.data.attrs.multiple !== undefined) { elm.setAttribute('multiple', 'multiple'); } return elm } function createElementNS (namespace, tagName) { return document.createElementNS(namespaceMap[namespace], tagName) } function createTextNode (text) { return document.createTextNode(text) } function createComment (text) { return document.createComment(text) } function insertBefore (parentNode, newNode, referenceNode) { parentNode.insertBefore(newNode, referenceNode); } function removeChild (node, child) { node.removeChild(child); } function appendChild (node, child) { node.appendChild(child); } function parentNode (node) { return node.parentNode } function nextSibling (node) { return node.nextSibling } function tagName (node) { return node.tagName } function setTextContent (node, text) { node.textContent = text; } function setStyleScope (node, scopeId) { node.setAttribute(scopeId, ''); } var nodeOps = /*#__PURE__*/Object.freeze({ createElement: createElement$1, createElementNS: createElementNS, createTextNode: createTextNode, createComment: createComment, insertBefore: insertBefore, removeChild: removeChild, appendChild: appendChild, parentNode: parentNode, nextSibling: nextSibling, tagName: tagName, setTextContent: setTextContent, setStyleScope: setStyleScope }); /* */ var ref = { create: function create (_, vnode) { registerRef(vnode); }, update: function update (oldVnode, vnode) { if (oldVnode.data.ref !== vnode.data.ref) { registerRef(oldVnode, true); registerRef(vnode); } }, destroy: function destroy (vnode) { registerRef(vnode, true); } }; function registerRef (vnode, isRemoval) { var key = vnode.data.ref; if (!isDef(key)) { return } var vm = vnode.context; var ref = vnode.componentInstance || vnode.elm; var refs = vm.$refs; if (isRemoval) { if (Array.isArray(refs[key])) { remove(refs[key], ref); } else if (refs[key] === ref) { refs[key] = undefined; } } else { if (vnode.data.refInFor) { if (!Array.isArray(refs[key])) { refs[key] = [ref]; } else if (refs[key].indexOf(ref) < 0) { // $flow-disable-line refs[key].push(ref); } } else { refs[key] = ref; } } } /** * Virtual DOM patching algorithm based on Snabbdom by * Simon Friis Vindum (@paldepind) * Licensed under the MIT License * https://github.com/paldepind/snabbdom/blob/master/LICENSE * * modified by Evan You (@yyx990803) * * Not type-checking this because this file is perf-critical and the cost * of making flow understand it is not worth it. */ var emptyNode = new VNode('', {}, []); var hooks = ['create', 'activate', 'update', 'remove', 'destroy']; function sameVnode (a, b) { return ( a.key === b.key && ( ( a.tag === b.tag && a.isComment === b.isComment && isDef(a.data) === isDef(b.data) && sameInputType(a, b) ) || ( isTrue(a.isAsyncPlaceholder) && a.asyncFactory === b.asyncFactory && isUndef(b.asyncFactory.error) ) ) ) } function sameInputType (a, b) { if (a.tag !== 'input') { return true } var i; var typeA = isDef(i = a.data) && isDef(i = i.attrs) && i.type; var typeB = isDef(i = b.data) && isDef(i = i.attrs) && i.type; return typeA === typeB || isTextInputType(typeA) && isTextInputType(typeB) } function createKeyToOldIdx (children, beginIdx, endIdx) { var i, key; var map = {}; for (i = beginIdx; i <= endIdx; ++i) { key = children[i].key; if (isDef(key)) { map[key] = i; } } return map } function createPatchFunction (backend) { var i, j; var cbs = {}; var modules = backend.modules; var nodeOps = backend.nodeOps; for (i = 0; i < hooks.length; ++i) { cbs[hooks[i]] = []; for (j = 0; j < modules.length; ++j) { if (isDef(modules[j][hooks[i]])) { cbs[hooks[i]].push(modules[j][hooks[i]]); } } } function emptyNodeAt (elm) { return new VNode(nodeOps.tagName(elm).toLowerCase(), {}, [], undefined, elm) } function createRmCb (childElm, listeners) { function remove$$1 () { if (--remove$$1.listeners === 0) { removeNode(childElm); } } remove$$1.listeners = listeners; return remove$$1 } function removeNode (el) { var parent = nodeOps.parentNode(el); // element may have already been removed due to v-html / v-text if (isDef(parent)) { nodeOps.removeChild(parent, el); } } function isUnknownElement$$1 (vnode, inVPre) { return ( !inVPre && !vnode.ns && !( config.ignoredElements.length && config.ignoredElements.some(function (ignore) { return isRegExp(ignore) ? ignore.test(vnode.tag) : ignore === vnode.tag }) ) && config.isUnknownElement(vnode.tag) ) } var creatingElmInVPre = 0; function createElm ( vnode, insertedVnodeQueue, parentElm, refElm, nested, ownerArray, index ) { if (isDef(vnode.elm) && isDef(ownerArray)) { // This vnode was used in a previous render! // now it's used as a new node, overwriting its elm would cause // potential patch errors down the road when it's used as an insertion // reference node. Instead, we clone the node on-demand before creating // associated DOM element for it. vnode = ownerArray[index] = cloneVNode(vnode); } vnode.isRootInsert = !nested; // for transition enter check if (createComponent(vnode, insertedVnodeQueue, parentElm, refElm)) { return } var data = vnode.data; var children = vnode.children; var tag = vnode.tag; if (isDef(tag)) { { if (data && data.pre) { creatingElmInVPre++; } if (isUnknownElement$$1(vnode, creatingElmInVPre)) { warn( 'Unknown custom element: <' + tag + '> - did you ' + 'register the component correctly? For recursive components, ' + 'make sure to provide the "name" option.', vnode.context ); } } vnode.elm = vnode.ns ? nodeOps.createElementNS(vnode.ns, tag) : nodeOps.createElement(tag, vnode); setScope(vnode); /* istanbul ignore if */ { createChildren(vnode, children, insertedVnodeQueue); if (isDef(data)) { invokeCreateHooks(vnode, insertedVnodeQueue); } insert(parentElm, vnode.elm, refElm); } if (data && data.pre) { creatingElmInVPre--; } } else if (isTrue(vnode.isComment)) { vnode.elm = nodeOps.createComment(vnode.text); insert(parentElm, vnode.elm, refElm); } else { vnode.elm = nodeOps.createTextNode(vnode.text); insert(parentElm, vnode.elm, refElm); } } function createComponent (vnode, insertedVnodeQueue, parentElm, refElm) { var i = vnode.data; if (isDef(i)) { var isReactivated = isDef(vnode.componentInstance) && i.keepAlive; if (isDef(i = i.hook) && isDef(i = i.init)) { i(vnode, false /* hydrating */); } // after calling the init hook, if the vnode is a child component // it should've created a child instance and mounted it. the child // component also has set the placeholder vnode's elm. // in that case we can just return the element and be done. if (isDef(vnode.componentInstance)) { initComponent(vnode, insertedVnodeQueue); insert(parentElm, vnode.elm, refElm); if (isTrue(isReactivated)) { reactivateComponent(vnode, insertedVnodeQueue, parentElm, refElm); } return true } } } function initComponent (vnode, insertedVnodeQueue) { if (isDef(vnode.data.pendingInsert)) { insertedVnodeQueue.push.apply(insertedVnodeQueue, vnode.data.pendingInsert); vnode.data.pendingInsert = null; } vnode.elm = vnode.componentInstance.$el; if (isPatchable(vnode)) { invokeCreateHooks(vnode, insertedVnodeQueue); setScope(vnode); } else { // empty component root. // skip all element-related modules except for ref (#3455) registerRef(vnode); // make sure to invoke the insert hook insertedVnodeQueue.push(vnode); } } function reactivateComponent (vnode, insertedVnodeQueue, parentElm, refElm) { var i; // hack for #4339: a reactivated component with inner transition // does not trigger because the inner node's created hooks are not called // again. It's not ideal to involve module-specific logic in here but // there doesn't seem to be a better way to do it. var innerNode = vnode; while (innerNode.componentInstance) { innerNode = innerNode.componentInstance._vnode; if (isDef(i = innerNode.data) && isDef(i = i.transition)) { for (i = 0; i < cbs.activate.length; ++i) { cbs.activate[i](emptyNode, innerNode); } insertedVnodeQueue.push(innerNode); break } } // unlike a newly created component, // a reactivated keep-alive component doesn't insert itself insert(parentElm, vnode.elm, refElm); } function insert (parent, elm, ref$$1) { if (isDef(parent)) { if (isDef(ref$$1)) { if (nodeOps.parentNode(ref$$1) === parent) { nodeOps.insertBefore(parent, elm, ref$$1); } } else { nodeOps.appendChild(parent, elm); } } } function createChildren (vnode, children, insertedVnodeQueue) { if (Array.isArray(children)) { { checkDuplicateKeys(children); } for (var i = 0; i < children.length; ++i) { createElm(children[i], insertedVnodeQueue, vnode.elm, null, true, children, i); } } else if (isPrimitive(vnode.text)) { nodeOps.appendChild(vnode.elm, nodeOps.createTextNode(String(vnode.text))); } } function isPatchable (vnode) { while (vnode.componentInstance) { vnode = vnode.componentInstance._vnode; } return isDef(vnode.tag) } function invokeCreateHooks (vnode, insertedVnodeQueue) { for (var i$1 = 0; i$1 < cbs.create.length; ++i$1) { cbs.create[i$1](emptyNode, vnode); } i = vnode.data.hook; // Reuse variable if (isDef(i)) { if (isDef(i.create)) { i.create(emptyNode, vnode); } if (isDef(i.insert)) { insertedVnodeQueue.push(vnode); } } } // set scope id attribute for scoped CSS. // this is implemented as a special case to avoid the overhead // of going through the normal attribute patching process. function setScope (vnode) { var i; if (isDef(i = vnode.fnScopeId)) { nodeOps.setStyleScope(vnode.elm, i); } else { var ancestor = vnode; while (ancestor) { if (isDef(i = ancestor.context) && isDef(i = i.$options._scopeId)) { nodeOps.setStyleScope(vnode.elm, i); } ancestor = ancestor.parent; } } // for slot content they should also get the scopeId from the host instance. if (isDef(i = activeInstance) && i !== vnode.context && i !== vnode.fnContext && isDef(i = i.$options._scopeId) ) { nodeOps.setStyleScope(vnode.elm, i); } } function addVnodes (parentElm, refElm, vnodes, startIdx, endIdx, insertedVnodeQueue) { for (; startIdx <= endIdx; ++startIdx) { createElm(vnodes[startIdx], insertedVnodeQueue, parentElm, refElm, false, vnodes, startIdx); } } function invokeDestroyHook (vnode) { var i, j; var data = vnode.data; if (isDef(data)) { if (isDef(i = data.hook) && isDef(i = i.destroy)) { i(vnode); } for (i = 0; i < cbs.destroy.length; ++i) { cbs.destroy[i](vnode); } } if (isDef(i = vnode.children)) { for (j = 0; j < vnode.children.length; ++j) { invokeDestroyHook(vnode.children[j]); } } } function removeVnodes (parentElm, vnodes, startIdx, endIdx) { for (; startIdx <= endIdx; ++startIdx) { var ch = vnodes[startIdx]; if (isDef(ch)) { if (isDef(ch.tag)) { removeAndInvokeRemoveHook(ch); invokeDestroyHook(ch); } else { // Text node removeNode(ch.elm); } } } } function removeAndInvokeRemoveHook (vnode, rm) { if (isDef(rm) || isDef(vnode.data)) { var i; var listeners = cbs.remove.length + 1; if (isDef(rm)) { // we have a recursively passed down rm callback // increase the listeners count rm.listeners += listeners; } else { // directly removing rm = createRmCb(vnode.elm, listeners); } // recursively invoke hooks on child component root node if (isDef(i = vnode.componentInstance) && isDef(i = i._vnode) && isDef(i.data)) { removeAndInvokeRemoveHook(i, rm); } for (i = 0; i < cbs.remove.length; ++i) { cbs.remove[i](vnode, rm); } if (isDef(i = vnode.data.hook) && isDef(i = i.remove)) { i(vnode, rm); } else { rm(); } } else { removeNode(vnode.elm); } } function updateChildren (parentElm, oldCh, newCh, insertedVnodeQueue, removeOnly) { var oldStartIdx = 0; var newStartIdx = 0; var oldEndIdx = oldCh.length - 1; var oldStartVnode = oldCh[0]; var oldEndVnode = oldCh[oldEndIdx]; var newEndIdx = newCh.length - 1; var newStartVnode = newCh[0]; var newEndVnode = newCh[newEndIdx]; var oldKeyToIdx, idxInOld, vnodeToMove, refElm; // removeOnly is a special flag used only by <transition-group> // to ensure removed elements stay in correct relative positions // during leaving transitions var canMove = !removeOnly; { checkDuplicateKeys(newCh); } while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) { if (isUndef(oldStartVnode)) { oldStartVnode = oldCh[++oldStartIdx]; // Vnode has been moved left } else if (isUndef(oldEndVnode)) { oldEndVnode = oldCh[--oldEndIdx]; } else if (sameVnode(oldStartVnode, newStartVnode)) { patchVnode(oldStartVnode, newStartVnode, insertedVnodeQueue, newCh, newStartIdx); oldStartVnode = oldCh[++oldStartIdx]; newStartVnode = newCh[++newStartIdx]; } else if (sameVnode(oldEndVnode, newEndVnode)) { patchVnode(oldEndVnode, newEndVnode, insertedVnodeQueue, newCh, newEndIdx); oldEndVnode = oldCh[--oldEndIdx]; newEndVnode = newCh[--newEndIdx]; } else if (sameVnode(oldStartVnode, newEndVnode)) { // Vnode moved right patchVnode(oldStartVnode, newEndVnode, insertedVnodeQueue, newCh, newEndIdx); canMove && nodeOps.insertBefore(parentElm, oldStartVnode.elm, nodeOps.nextSibling(oldEndVnode.elm)); oldStartVnode = oldCh[++oldStartIdx]; newEndVnode = newCh[--newEndIdx]; } else if (sameVnode(oldEndVnode, newStartVnode)) { // Vnode moved left patchVnode(oldEndVnode, newStartVnode, insertedVnodeQueue, newCh, newStartIdx); canMove && nodeOps.insertBefore(parentElm, oldEndVnode.elm, oldStartVnode.elm); oldEndVnode = oldCh[--oldEndIdx]; newStartVnode = newCh[++newStartIdx]; } else { if (isUndef(oldKeyToIdx)) { oldKeyToIdx = createKeyToOldIdx(oldCh, oldStartIdx, oldEndIdx); } idxInOld = isDef(newStartVnode.key) ? oldKeyToIdx[newStartVnode.key] : findIdxInOld(newStartVnode, oldCh, oldStartIdx, oldEndIdx); if (isUndef(idxInOld)) { // New element createElm(newStartVnode, insertedVnodeQueue, parentElm, oldStartVnode.elm, false, newCh, newStartIdx); } else { vnodeToMove = oldCh[idxInOld]; if (sameVnode(vnodeToMove, newStartVnode)) { patchVnode(vnodeToMove, newStartVnode, insertedVnodeQueue, newCh, newStartIdx); oldCh[idxInOld] = undefined; canMove && nodeOps.insertBefore(parentElm, vnodeToMove.elm, oldStartVnode.elm); } else { // same key but different element. treat as new element createElm(newStartVnode, insertedVnodeQueue, parentElm, oldStartVnode.elm, false, newCh, newStartIdx); } } newStartVnode = newCh[++newStartIdx]; } } if (oldStartIdx > oldEndIdx) { refElm = isUndef(newCh[newEndIdx + 1]) ? null : newCh[newEndIdx + 1].elm; addVnodes(parentElm, refElm, newCh, newStartIdx, newEndIdx, insertedVnodeQueue); } else if (newStartIdx > newEndIdx) { removeVnodes(parentElm, oldCh, oldStartIdx, oldEndIdx); } } function checkDuplicateKeys (children) { var seenKeys = {}; for (var i = 0; i < children.length; i++) { var vnode = children[i]; var key = vnode.key; if (isDef(key)) { if (seenKeys[key]) { warn( ("Duplicate keys detected: '" + key + "'. This may cause an update error."), vnode.context ); } else { seenKeys[key] = true; } } } } function findIdxInOld (node, oldCh, start, end) { for (var i = start; i < end; i++) { var c = oldCh[i]; if (isDef(c) && sameVnode(node, c)) { return i } } } function patchVnode ( oldVnode, vnode, insertedVnodeQueue, ownerArray, index, removeOnly ) { if (oldVnode === vnode) { return } if (isDef(vnode.elm) && isDef(ownerArray)) { // clone reused vnode vnode = ownerArray[index] = cloneVNode(vnode); } var elm = vnode.elm = oldVnode.elm; if (isTrue(oldVnode.isAsyncPlaceholder)) { if (isDef(vnode.asyncFactory.resolved)) { hydrate(oldVnode.elm, vnode, insertedVnodeQueue); } else { vnode.isAsyncPlaceholder = true; } return } // reuse element for static trees. // note we only do this if the vnode is cloned - // if the new node is not cloned it means the render functions have been // reset by the hot-reload-api and we need to do a proper re-render. if (isTrue(vnode.isStatic) && isTrue(oldVnode.isStatic) && vnode.key === oldVnode.key && (isTrue(vnode.isCloned) || isTrue(vnode.isOnce)) ) { vnode.componentInstance = oldVnode.componentInstance; return } var i; var data = vnode.data; if (isDef(data) && isDef(i = data.hook) && isDef(i = i.prepatch)) { i(oldVnode, vnode); } var oldCh = oldVnode.children; var ch = vnode.children; if (isDef(data) && isPatchable(vnode)) { for (i = 0; i < cbs.update.length; ++i) { cbs.update[i](oldVnode, vnode); } if (isDef(i = data.hook) && isDef(i = i.update)) { i(oldVnode, vnode); } } if (isUndef(vnode.text)) { if (isDef(oldCh) && isDef(ch)) { if (oldCh !== ch) { updateChildren(elm, oldCh, ch, insertedVnodeQueue, removeOnly); } } else if (isDef(ch)) { { checkDuplicateKeys(ch); } if (isDef(oldVnode.text)) { nodeOps.setTextContent(elm, ''); } addVnodes(elm, null, ch, 0, ch.length - 1, insertedVnodeQueue); } else if (isDef(oldCh)) { removeVnodes(elm, oldCh, 0, oldCh.length - 1); } else if (isDef(oldVnode.text)) { nodeOps.setTextContent(elm, ''); } } else if (oldVnode.text !== vnode.text) { nodeOps.setTextContent(elm, vnode.text); } if (isDef(data)) { if (isDef(i = data.hook) && isDef(i = i.postpatch)) { i(oldVnode, vnode); } } } function invokeInsertHook (vnode, queue, initial) { // delay insert hooks for component root nodes, invoke them after the // element is really inserted if (isTrue(initial) && isDef(vnode.parent)) { vnode.parent.data.pendingInsert = queue; } else { for (var i = 0; i < queue.length; ++i) { queue[i].data.hook.insert(queue[i]); } } } var hydrationBailed = false; // list of modules that can skip create hook during hydration because they // are already rendered on the client or has no need for initialization // Note: style is excluded because it relies on initial clone for future // deep updates (#7063). var isRenderedModule = makeMap('attrs,class,staticClass,staticStyle,key'); // Note: this is a browser-only function so we can assume elms are DOM nodes. function hydrate (elm, vnode, insertedVnodeQueue, inVPre) { var i; var tag = vnode.tag; var data = vnode.data; var children = vnode.children; inVPre = inVPre || (data && data.pre); vnode.elm = elm; if (isTrue(vnode.isComment) && isDef(vnode.asyncFactory)) { vnode.isAsyncPlaceholder = true; return true } // assert node match { if (!assertNodeMatch(elm, vnode, inVPre)) { return false } } if (isDef(data)) { if (isDef(i = data.hook) && isDef(i = i.init)) { i(vnode, true /* hydrating */); } if (isDef(i = vnode.componentInstance)) { // child component. it should have hydrated its own tree. initComponent(vnode, insertedVnodeQueue); return true } } if (isDef(tag)) { if (isDef(children)) { // empty element, allow client to pick up and populate children if (!elm.hasChildNodes()) { createChildren(vnode, children, insertedVnodeQueue); } else { // v-html and domProps: innerHTML if (isDef(i = data) && isDef(i = i.domProps) && isDef(i = i.innerHTML)) { if (i !== elm.innerHTML) { /* istanbul ignore if */ if (typeof console !== 'undefined' && !hydrationBailed ) { hydrationBailed = true; console.warn('Parent: ', elm); console.warn('server innerHTML: ', i); console.warn('client innerHTML: ', elm.innerHTML); } return false } } else { // iterate and compare children lists var childrenMatch = true; var childNode = elm.firstChild; for (var i$1 = 0; i$1 < children.length; i$1++) { if (!childNode || !hydrate(childNode, children[i$1], insertedVnodeQueue, inVPre)) { childrenMatch = false; break } childNode = childNode.nextSibling; } // if childNode is not null, it means the actual childNodes list is // longer than the virtual children list. if (!childrenMatch || childNode) { /* istanbul ignore if */ if (typeof console !== 'undefined' && !hydrationBailed ) { hydrationBailed = true; console.warn('Parent: ', elm); console.warn('Mismatching childNodes vs. VNodes: ', elm.childNodes, children); } return false } } } } if (isDef(data)) { var fullInvoke = false; for (var key in data) { if (!isRenderedModule(key)) { fullInvoke = true; invokeCreateHooks(vnode, insertedVnodeQueue); break } } if (!fullInvoke && data['class']) { // ensure collecting deps for deep class bindings for future updates traverse(data['class']); } } } else if (elm.data !== vnode.text) { elm.data = vnode.text; } return true } function assertNodeMatch (node, vnode, inVPre) { if (isDef(vnode.tag)) { return vnode.tag.indexOf('vue-component') === 0 || ( !isUnknownElement$$1(vnode, inVPre) && vnode.tag.toLowerCase() === (node.tagName && node.tagName.toLowerCase()) ) } else { return node.nodeType === (vnode.isComment ? 8 : 3) } } return function patch (oldVnode, vnode, hydrating, removeOnly) { if (isUndef(vnode)) { if (isDef(oldVnode)) { invokeDestroyHook(oldVnode); } return } var isInitialPatch = false; var insertedVnodeQueue = []; if (isUndef(oldVnode)) { // empty mount (likely as component), create new root element isInitialPatch = true; createElm(vnode, insertedVnodeQueue); } else { var isRealElement = isDef(oldVnode.nodeType); if (!isRealElement && sameVnode(oldVnode, vnode)) { // patch existing root node patchVnode(oldVnode, vnode, insertedVnodeQueue, null, null, removeOnly); } else { if (isRealElement) { // mounting to a real element // check if this is server-rendered content and if we can perform // a successful hydration. if (oldVnode.nodeType === 1 && oldVnode.hasAttribute(SSR_ATTR)) { oldVnode.removeAttribute(SSR_ATTR); hydrating = true; } if (isTrue(hydrating)) { if (hydrate(oldVnode, vnode, insertedVnodeQueue)) { invokeInsertHook(vnode, insertedVnodeQueue, true); return oldVnode } else { warn( 'The client-side rendered virtual DOM tree is not matching ' + 'server-rendered content. This is likely caused by incorrect ' + 'HTML markup, for example nesting block-level elements inside ' + '<p>, or missing <tbody>. Bailing hydration and performing ' + 'full client-side render.' ); } } // either not server-rendered, or hydration failed. // create an empty node and replace it oldVnode = emptyNodeAt(oldVnode); } // replacing existing element var oldElm = oldVnode.elm; var parentElm = nodeOps.parentNode(oldElm); // create new node createElm( vnode, insertedVnodeQueue, // extremely rare edge case: do not insert if old element is in a // leaving transition. Only happens when combining transition + // keep-alive + HOCs. (#4590) oldElm._leaveCb ? null : parentElm, nodeOps.nextSibling(oldElm) ); // update parent placeholder node element, recursively if (isDef(vnode.parent)) { var ancestor = vnode.parent; var patchable = isPatchable(vnode); while (ancestor) { for (var i = 0; i < cbs.destroy.length; ++i) { cbs.destroy[i](ancestor); } ancestor.elm = vnode.elm; if (patchable) { for (var i$1 = 0; i$1 < cbs.create.length; ++i$1) { cbs.create[i$1](emptyNode, ancestor); } // #6513 // invoke insert hooks that may have been merged by create hooks. // e.g. for directives that uses the "inserted" hook. var insert = ancestor.data.hook.insert; if (insert.merged) { // start at index 1 to avoid re-invoking component mounted hook for (var i$2 = 1; i$2 < insert.fns.length; i$2++) { insert.fns[i$2](); } } } else { registerRef(ancestor); } ancestor = ancestor.parent; } } // destroy old node if (isDef(parentElm)) { removeVnodes(parentElm, [oldVnode], 0, 0); } else if (isDef(oldVnode.tag)) { invokeDestroyHook(oldVnode); } } } invokeInsertHook(vnode, insertedVnodeQueue, isInitialPatch); return vnode.elm } } /* */ var directives = { create: updateDirectives, update: updateDirectives, destroy: function unbindDirectives (vnode) { updateDirectives(vnode, emptyNode); } }; function updateDirectives (oldVnode, vnode) { if (oldVnode.data.directives || vnode.data.directives) { _update(oldVnode, vnode); } } function _update (oldVnode, vnode) { var isCreate = oldVnode === emptyNode; var isDestroy = vnode === emptyNode; var oldDirs = normalizeDirectives$1(oldVnode.data.directives, oldVnode.context); var newDirs = normalizeDirectives$1(vnode.data.directives, vnode.context); var dirsWithInsert = []; var dirsWithPostpatch = []; var key, oldDir, dir; for (key in newDirs) { oldDir = oldDirs[key]; dir = newDirs[key]; if (!oldDir) { // new directive, bind callHook$1(dir, 'bind', vnode, oldVnode); if (dir.def && dir.def.inserted) { dirsWithInsert.push(dir); } } else { // existing directive, update dir.oldValue = oldDir.value; dir.oldArg = oldDir.arg; callHook$1(dir, 'update', vnode, oldVnode); if (dir.def && dir.def.componentUpdated) { dirsWithPostpatch.push(dir); } } } if (dirsWithInsert.length) { var callInsert = function () { for (var i = 0; i < dirsWithInsert.length; i++) { callHook$1(dirsWithInsert[i], 'inserted', vnode, oldVnode); } }; if (isCreate) { mergeVNodeHook(vnode, 'insert', callInsert); } else { callInsert(); } } if (dirsWithPostpatch.length) { mergeVNodeHook(vnode, 'postpatch', function () { for (var i = 0; i < dirsWithPostpatch.length; i++) { callHook$1(dirsWithPostpatch[i], 'componentUpdated', vnode, oldVnode); } }); } if (!isCreate) { for (key in oldDirs) { if (!newDirs[key]) { // no longer present, unbind callHook$1(oldDirs[key], 'unbind', oldVnode, oldVnode, isDestroy); } } } } var emptyModifiers = Object.create(null); function normalizeDirectives$1 ( dirs, vm ) { var res = Object.create(null); if (!dirs) { // $flow-disable-line return res } var i, dir; for (i = 0; i < dirs.length; i++) { dir = dirs[i]; if (!dir.modifiers) { // $flow-disable-line dir.modifiers = emptyModifiers; } res[getRawDirName(dir)] = dir; dir.def = resolveAsset(vm.$options, 'directives', dir.name, true); } // $flow-disable-line return res } function getRawDirName (dir) { return dir.rawName || ((dir.name) + "." + (Object.keys(dir.modifiers || {}).join('.'))) } function callHook$1 (dir, hook, vnode, oldVnode, isDestroy) { var fn = dir.def && dir.def[hook]; if (fn) { try { fn(vnode.elm, dir, vnode, oldVnode, isDestroy); } catch (e) { handleError(e, vnode.context, ("directive " + (dir.name) + " " + hook + " hook")); } } } var baseModules = [ ref, directives ]; /* */ function updateAttrs (oldVnode, vnode) { var opts = vnode.componentOptions; if (isDef(opts) && opts.Ctor.options.inheritAttrs === false) { return } if (isUndef(oldVnode.data.attrs) && isUndef(vnode.data.attrs)) { return } var key, cur, old; var elm = vnode.elm; var oldAttrs = oldVnode.data.attrs || {}; var attrs = vnode.data.attrs || {}; // clone observed objects, as the user probably wants to mutate it if (isDef(attrs.__ob__)) { attrs = vnode.data.attrs = extend({}, attrs); } for (key in attrs) { cur = attrs[key]; old = oldAttrs[key]; if (old !== cur) { setAttr(elm, key, cur); } } // #4391: in IE9, setting type can reset value for input[type=radio] // #6666: IE/Edge forces progress value down to 1 before setting a max /* istanbul ignore if */ if ((isIE || isEdge) && attrs.value !== oldAttrs.value) { setAttr(elm, 'value', attrs.value); } for (key in oldAttrs) { if (isUndef(attrs[key])) { if (isXlink(key)) { elm.removeAttributeNS(xlinkNS, getXlinkProp(key)); } else if (!isEnumeratedAttr(key)) { elm.removeAttribute(key); } } } } function setAttr (el, key, value) { if (el.tagName.indexOf('-') > -1) { baseSetAttr(el, key, value); } else if (isBooleanAttr(key)) { // set attribute for blank value // e.g. <option disabled>Select one</option> if (isFalsyAttrValue(value)) { el.removeAttribute(key); } else { // technically allowfullscreen is a boolean attribute for <iframe>, // but Flash expects a value of "true" when used on <embed> tag value = key === 'allowfullscreen' && el.tagName === 'EMBED' ? 'true' : key; el.setAttribute(key, value); } } else if (isEnumeratedAttr(key)) { el.setAttribute(key, convertEnumeratedValue(key, value)); } else if (isXlink(key)) { if (isFalsyAttrValue(value)) { el.removeAttributeNS(xlinkNS, getXlinkProp(key)); } else { el.setAttributeNS(xlinkNS, key, value); } } else { baseSetAttr(el, key, value); } } function baseSetAttr (el, key, value) { if (isFalsyAttrValue(value)) { el.removeAttribute(key); } else { // #7138: IE10 & 11 fires input event when setting placeholder on // <textarea>... block the first input event and remove the blocker // immediately. /* istanbul ignore if */ if ( isIE && !isIE9 && el.tagName === 'TEXTAREA' && key === 'placeholder' && value !== '' && !el.__ieph ) { var blocker = function (e) { e.stopImmediatePropagation(); el.removeEventListener('input', blocker); }; el.addEventListener('input', blocker); // $flow-disable-line el.__ieph = true; /* IE placeholder patched */ } el.setAttribute(key, value); } } var attrs = { create: updateAttrs, update: updateAttrs }; /* */ function updateClass (oldVnode, vnode) { var el = vnode.elm; var data = vnode.data; var oldData = oldVnode.data; if ( isUndef(data.staticClass) && isUndef(data.class) && ( isUndef(oldData) || ( isUndef(oldData.staticClass) && isUndef(oldData.class) ) ) ) { return } var cls = genClassForVnode(vnode); // handle transition classes var transitionClass = el._transitionClasses; if (isDef(transitionClass)) { cls = concat(cls, stringifyClass(transitionClass)); } // set the class if (cls !== el._prevClass) { el.setAttribute('class', cls); el._prevClass = cls; } } var klass = { create: updateClass, update: updateClass }; /* */ var validDivisionCharRE = /[\w).+\-_$\]]/; function parseFilters (exp) { var inSingle = false; var inDouble = false; var inTemplateString = false; var inRegex = false; var curly = 0; var square = 0; var paren = 0; var lastFilterIndex = 0; var c, prev, i, expression, filters; for (i = 0; i < exp.length; i++) { prev = c; c = exp.charCodeAt(i); if (inSingle) { if (c === 0x27 && prev !== 0x5C) { inSingle = false; } } else if (inDouble) { if (c === 0x22 && prev !== 0x5C) { inDouble = false; } } else if (inTemplateString) { if (c === 0x60 && prev !== 0x5C) { inTemplateString = false; } } else if (inRegex) { if (c === 0x2f && prev !== 0x5C) { inRegex = false; } } else if ( c === 0x7C && // pipe exp.charCodeAt(i + 1) !== 0x7C && exp.charCodeAt(i - 1) !== 0x7C && !curly && !square && !paren ) { if (expression === undefined) { // first filter, end of expression lastFilterIndex = i + 1; expression = exp.slice(0, i).trim(); } else { pushFilter(); } } else { switch (c) { case 0x22: inDouble = true; break // " case 0x27: inSingle = true; break // ' case 0x60: inTemplateString = true; break // ` case 0x28: paren++; break // ( case 0x29: paren--; break // ) case 0x5B: square++; break // [ case 0x5D: square--; break // ] case 0x7B: curly++; break // { case 0x7D: curly--; break // } } if (c === 0x2f) { // / var j = i - 1; var p = (void 0); // find first non-whitespace prev char for (; j >= 0; j--) { p = exp.charAt(j); if (p !== ' ') { break } } if (!p || !validDivisionCharRE.test(p)) { inRegex = true; } } } } if (expression === undefined) { expression = exp.slice(0, i).trim(); } else if (lastFilterIndex !== 0) { pushFilter(); } function pushFilter () { (filters || (filters = [])).push(exp.slice(lastFilterIndex, i).trim()); lastFilterIndex = i + 1; } if (filters) { for (i = 0; i < filters.length; i++) { expression = wrapFilter(expression, filters[i]); } } return expression } function wrapFilter (exp, filter) { var i = filter.indexOf('('); if (i < 0) { // _f: resolveFilter return ("_f(\"" + filter + "\")(" + exp + ")") } else { var name = filter.slice(0, i); var args = filter.slice(i + 1); return ("_f(\"" + name + "\")(" + exp + (args !== ')' ? ',' + args : args)) } } /* */ /* eslint-disable no-unused-vars */ function baseWarn (msg, range) { console.error(("[Vue compiler]: " + msg)); } /* eslint-enable no-unused-vars */ function pluckModuleFunction ( modules, key ) { return modules ? modules.map(function (m) { return m[key]; }).filter(function (_) { return _; }) : [] } function addProp (el, name, value, range, dynamic) { (el.props || (el.props = [])).push(rangeSetItem({ name: name, value: value, dynamic: dynamic }, range)); el.plain = false; } function addAttr (el, name, value, range, dynamic) { var attrs = dynamic ? (el.dynamicAttrs || (el.dynamicAttrs = [])) : (el.attrs || (el.attrs = [])); attrs.push(rangeSetItem({ name: name, value: value, dynamic: dynamic }, range)); el.plain = false; } // add a raw attr (use this in preTransforms) function addRawAttr (el, name, value, range) { el.attrsMap[name] = value; el.attrsList.push(rangeSetItem({ name: name, value: value }, range)); } function addDirective ( el, name, rawName, value, arg, isDynamicArg, modifiers, range ) { (el.directives || (el.directives = [])).push(rangeSetItem({ name: name, rawName: rawName, value: value, arg: arg, isDynamicArg: isDynamicArg, modifiers: modifiers }, range)); el.plain = false; } function prependModifierMarker (symbol, name, dynamic) { return dynamic ? ("_p(" + name + ",\"" + symbol + "\")") : symbol + name // mark the event as captured } function addHandler ( el, name, value, modifiers, important, warn, range, dynamic ) { modifiers = modifiers || emptyObject; // warn prevent and passive modifier /* istanbul ignore if */ if ( warn && modifiers.prevent && modifiers.passive ) { warn( 'passive and prevent can\'t be used together. ' + 'Passive handler can\'t prevent default event.', range ); } // normalize click.right and click.middle since they don't actually fire // this is technically browser-specific, but at least for now browsers are // the only target envs that have right/middle clicks. if (modifiers.right) { if (dynamic) { name = "(" + name + ")==='click'?'contextmenu':(" + name + ")"; } else if (name === 'click') { name = 'contextmenu'; delete modifiers.right; } } else if (modifiers.middle) { if (dynamic) { name = "(" + name + ")==='click'?'mouseup':(" + name + ")"; } else if (name === 'click') { name = 'mouseup'; } } // check capture modifier if (modifiers.capture) { delete modifiers.capture; name = prependModifierMarker('!', name, dynamic); } if (modifiers.once) { delete modifiers.once; name = prependModifierMarker('~', name, dynamic); } /* istanbul ignore if */ if (modifiers.passive) { delete modifiers.passive; name = prependModifierMarker('&', name, dynamic); } var events; if (modifiers.native) { delete modifiers.native; events = el.nativeEvents || (el.nativeEvents = {}); } else { events = el.events || (el.events = {}); } var newHandler = rangeSetItem({ value: value.trim(), dynamic: dynamic }, range); if (modifiers !== emptyObject) { newHandler.modifiers = modifiers; } var handlers = events[name]; /* istanbul ignore if */ if (Array.isArray(handlers)) { important ? handlers.unshift(newHandler) : handlers.push(newHandler); } else if (handlers) { events[name] = important ? [newHandler, handlers] : [handlers, newHandler]; } else { events[name] = newHandler; } el.plain = false; } function getRawBindingAttr ( el, name ) { return el.rawAttrsMap[':' + name] || el.rawAttrsMap['v-bind:' + name] || el.rawAttrsMap[name] } function getBindingAttr ( el, name, getStatic ) { var dynamicValue = getAndRemoveAttr(el, ':' + name) || getAndRemoveAttr(el, 'v-bind:' + name); if (dynamicValue != null) { return parseFilters(dynamicValue) } else if (getStatic !== false) { var staticValue = getAndRemoveAttr(el, name); if (staticValue != null) { return JSON.stringify(staticValue) } } } // note: this only removes the attr from the Array (attrsList) so that it // doesn't get processed by processAttrs. // By default it does NOT remove it from the map (attrsMap) because the map is // needed during codegen. function getAndRemoveAttr ( el, name, removeFromMap ) { var val; if ((val = el.attrsMap[name]) != null) { var list = el.attrsList; for (var i = 0, l = list.length; i < l; i++) { if (list[i].name === name) { list.splice(i, 1); break } } } if (removeFromMap) { delete el.attrsMap[name]; } return val } function getAndRemoveAttrByRegex ( el, name ) { var list = el.attrsList; for (var i = 0, l = list.length; i < l; i++) { var attr = list[i]; if (name.test(attr.name)) { list.splice(i, 1); return attr } } } function rangeSetItem ( item, range ) { if (range) { if (range.start != null) { item.start = range.start; } if (range.end != null) { item.end = range.end; } } return item } /* */ /** * Cross-platform code generation for component v-model */ function genComponentModel ( el, value, modifiers ) { var ref = modifiers || {}; var number = ref.number; var trim = ref.trim; var baseValueExpression = '$$v'; var valueExpression = baseValueExpression; if (trim) { valueExpression = "(typeof " + baseValueExpression + " === 'string'" + "? " + baseValueExpression + ".trim()" + ": " + baseValueExpression + ")"; } if (number) { valueExpression = "_n(" + valueExpression + ")"; } var assignment = genAssignmentCode(value, valueExpression); el.model = { value: ("(" + value + ")"), expression: JSON.stringify(value), callback: ("function (" + baseValueExpression + ") {" + assignment + "}") }; } /** * Cross-platform codegen helper for generating v-model value assignment code. */ function genAssignmentCode ( value, assignment ) { var res = parseModel(value); if (res.key === null) { return (value + "=" + assignment) } else { return ("$set(" + (res.exp) + ", " + (res.key) + ", " + assignment + ")") } } /** * Parse a v-model expression into a base path and a final key segment. * Handles both dot-path and possible square brackets. * * Possible cases: * * - test * - test[key] * - test[test1[key]] * - test["a"][key] * - xxx.test[a[a].test1[key]] * - test.xxx.a["asa"][test1[key]] * */ var len, str, chr, index$1, expressionPos, expressionEndPos; function parseModel (val) { // Fix https://github.com/vuejs/vue/pull/7730 // allow v-model="obj.val " (trailing whitespace) val = val.trim(); len = val.length; if (val.indexOf('[') < 0 || val.lastIndexOf(']') < len - 1) { index$1 = val.lastIndexOf('.'); if (index$1 > -1) { return { exp: val.slice(0, index$1), key: '"' + val.slice(index$1 + 1) + '"' } } else { return { exp: val, key: null } } } str = val; index$1 = expressionPos = expressionEndPos = 0; while (!eof()) { chr = next(); /* istanbul ignore if */ if (isStringStart(chr)) { parseString(chr); } else if (chr === 0x5B) { parseBracket(chr); } } return { exp: val.slice(0, expressionPos), key: val.slice(expressionPos + 1, expressionEndPos) } } function next () { return str.charCodeAt(++index$1) } function eof () { return index$1 >= len } function isStringStart (chr) { return chr === 0x22 || chr === 0x27 } function parseBracket (chr) { var inBracket = 1; expressionPos = index$1; while (!eof()) { chr = next(); if (isStringStart(chr)) { parseString(chr); continue } if (chr === 0x5B) { inBracket++; } if (chr === 0x5D) { inBracket--; } if (inBracket === 0) { expressionEndPos = index$1; break } } } function parseString (chr) { var stringQuote = chr; while (!eof()) { chr = next(); if (chr === stringQuote) { break } } } /* */ var warn$1; // in some cases, the event used has to be determined at runtime // so we used some reserved tokens during compile. var RANGE_TOKEN = '__r'; var CHECKBOX_RADIO_TOKEN = '__c'; function model ( el, dir, _warn ) { warn$1 = _warn; var value = dir.value; var modifiers = dir.modifiers; var tag = el.tag; var type = el.attrsMap.type; { // inputs with type="file" are read only and setting the input's // value will throw an error. if (tag === 'input' && type === 'file') { warn$1( "<" + (el.tag) + " v-model=\"" + value + "\" type=\"file\">:\n" + "File inputs are read only. Use a v-on:change listener instead.", el.rawAttrsMap['v-model'] ); } } if (el.component) { genComponentModel(el, value, modifiers); // component v-model doesn't need extra runtime return false } else if (tag === 'select') { genSelect(el, value, modifiers); } else if (tag === 'input' && type === 'checkbox') { genCheckboxModel(el, value, modifiers); } else if (tag === 'input' && type === 'radio') { genRadioModel(el, value, modifiers); } else if (tag === 'input' || tag === 'textarea') { genDefaultModel(el, value, modifiers); } else if (!config.isReservedTag(tag)) { genComponentModel(el, value, modifiers); // component v-model doesn't need extra runtime return false } else { warn$1( "<" + (el.tag) + " v-model=\"" + value + "\">: " + "v-model is not supported on this element type. " + 'If you are working with contenteditable, it\'s recommended to ' + 'wrap a library dedicated for that purpose inside a custom component.', el.rawAttrsMap['v-model'] ); } // ensure runtime directive metadata return true } function genCheckboxModel ( el, value, modifiers ) { var number = modifiers && modifiers.number; var valueBinding = getBindingAttr(el, 'value') || 'null'; var trueValueBinding = getBindingAttr(el, 'true-value') || 'true'; var falseValueBinding = getBindingAttr(el, 'false-value') || 'false'; addProp(el, 'checked', "Array.isArray(" + value + ")" + "?_i(" + value + "," + valueBinding + ")>-1" + ( trueValueBinding === 'true' ? (":(" + value + ")") : (":_q(" + value + "," + trueValueBinding + ")") ) ); addHandler(el, 'change', "var $$a=" + value + "," + '$$el=$event.target,' + "$$c=$$el.checked?(" + trueValueBinding + "):(" + falseValueBinding + ");" + 'if(Array.isArray($$a)){' + "var $$v=" + (number ? '_n(' + valueBinding + ')' : valueBinding) + "," + '$$i=_i($$a,$$v);' + "if($$el.checked){$$i<0&&(" + (genAssignmentCode(value, '$$a.concat([$$v])')) + ")}" + "else{$$i>-1&&(" + (genAssignmentCode(value, '$$a.slice(0,$$i).concat($$a.slice($$i+1))')) + ")}" + "}else{" + (genAssignmentCode(value, '$$c')) + "}", null, true ); } function genRadioModel ( el, value, modifiers ) { var number = modifiers && modifiers.number; var valueBinding = getBindingAttr(el, 'value') || 'null'; valueBinding = number ? ("_n(" + valueBinding + ")") : valueBinding; addProp(el, 'checked', ("_q(" + value + "," + valueBinding + ")")); addHandler(el, 'change', genAssignmentCode(value, valueBinding), null, true); } function genSelect ( el, value, modifiers ) { var number = modifiers && modifiers.number; var selectedVal = "Array.prototype.filter" + ".call($event.target.options,function(o){return o.selected})" + ".map(function(o){var val = \"_value\" in o ? o._value : o.value;" + "return " + (number ? '_n(val)' : 'val') + "})"; var assignment = '$event.target.multiple ? $$selectedVal : $$selectedVal[0]'; var code = "var $$selectedVal = " + selectedVal + ";"; code = code + " " + (genAssignmentCode(value, assignment)); addHandler(el, 'change', code, null, true); } function genDefaultModel ( el, value, modifiers ) { var type = el.attrsMap.type; // warn if v-bind:value conflicts with v-model // except for inputs with v-bind:type { var value$1 = el.attrsMap['v-bind:value'] || el.attrsMap[':value']; var typeBinding = el.attrsMap['v-bind:type'] || el.attrsMap[':type']; if (value$1 && !typeBinding) { var binding = el.attrsMap['v-bind:value'] ? 'v-bind:value' : ':value'; warn$1( binding + "=\"" + value$1 + "\" conflicts with v-model on the same element " + 'because the latter already expands to a value binding internally', el.rawAttrsMap[binding] ); } } var ref = modifiers || {}; var lazy = ref.lazy; var number = ref.number; var trim = ref.trim; var needCompositionGuard = !lazy && type !== 'range'; var event = lazy ? 'change' : type === 'range' ? RANGE_TOKEN : 'input'; var valueExpression = '$event.target.value'; if (trim) { valueExpression = "$event.target.value.trim()"; } if (number) { valueExpression = "_n(" + valueExpression + ")"; } var code = genAssignmentCode(value, valueExpression); if (needCompositionGuard) { code = "if($event.target.composing)return;" + code; } addProp(el, 'value', ("(" + value + ")")); addHandler(el, event, code, null, true); if (trim || number) { addHandler(el, 'blur', '$forceUpdate()'); } } /* */ // normalize v-model event tokens that can only be determined at runtime. // it's important to place the event as the first in the array because // the whole point is ensuring the v-model callback gets called before // user-attached handlers. function normalizeEvents (on) { /* istanbul ignore if */ if (isDef(on[RANGE_TOKEN])) { // IE input[type=range] only supports `change` event var event = isIE ? 'change' : 'input'; on[event] = [].concat(on[RANGE_TOKEN], on[event] || []); delete on[RANGE_TOKEN]; } // This was originally intended to fix #4521 but no longer necessary // after 2.5. Keeping it for backwards compat with generated code from < 2.4 /* istanbul ignore if */ if (isDef(on[CHECKBOX_RADIO_TOKEN])) { on.change = [].concat(on[CHECKBOX_RADIO_TOKEN], on.change || []); delete on[CHECKBOX_RADIO_TOKEN]; } } var target$1; function createOnceHandler$1 (event, handler, capture) { var _target = target$1; // save current target element in closure return function onceHandler () { var res = handler.apply(null, arguments); if (res !== null) { remove$2(event, onceHandler, capture, _target); } } } // #9446: Firefox <= 53 (in particular, ESR 52) has incorrect Event.timeStamp // implementation and does not fire microtasks in between event propagation, so // safe to exclude. var useMicrotaskFix = isUsingMicroTask && !(isFF && Number(isFF[1]) <= 53); function add$1 ( name, handler, capture, passive ) { // async edge case #6566: inner click event triggers patch, event handler // attached to outer element during patch, and triggered again. This // happens because browsers fire microtask ticks between event propagation. // the solution is simple: we save the timestamp when a handler is attached, // and the handler would only fire if the event passed to it was fired // AFTER it was attached. if (useMicrotaskFix) { var attachedTimestamp = currentFlushTimestamp; var original = handler; handler = original._wrapper = function (e) { if ( // no bubbling, should always fire. // this is just a safety net in case event.timeStamp is unreliable in // certain weird environments... e.target === e.currentTarget || // event is fired after handler attachment e.timeStamp >= attachedTimestamp || // bail for environments that have buggy event.timeStamp implementations // #9462 iOS 9 bug: event.timeStamp is 0 after history.pushState // #9681 QtWebEngine event.timeStamp is negative value e.timeStamp <= 0 || // #9448 bail if event is fired in another document in a multi-page // electron/nw.js app, since event.timeStamp will be using a different // starting reference e.target.ownerDocument !== document ) { return original.apply(this, arguments) } }; } target$1.addEventListener( name, handler, supportsPassive ? { capture: capture, passive: passive } : capture ); } function remove$2 ( name, handler, capture, _target ) { (_target || target$1).removeEventListener( name, handler._wrapper || handler, capture ); } function updateDOMListeners (oldVnode, vnode) { if (isUndef(oldVnode.data.on) && isUndef(vnode.data.on)) { return } var on = vnode.data.on || {}; var oldOn = oldVnode.data.on || {}; target$1 = vnode.elm; normalizeEvents(on); updateListeners(on, oldOn, add$1, remove$2, createOnceHandler$1, vnode.context); target$1 = undefined; } var events = { create: updateDOMListeners, update: updateDOMListeners }; /* */ var svgContainer; function updateDOMProps (oldVnode, vnode) { if (isUndef(oldVnode.data.domProps) && isUndef(vnode.data.domProps)) { return } var key, cur; var elm = vnode.elm; var oldProps = oldVnode.data.domProps || {}; var props = vnode.data.domProps || {}; // clone observed objects, as the user probably wants to mutate it if (isDef(props.__ob__)) { props = vnode.data.domProps = extend({}, props); } for (key in oldProps) { if (!(key in props)) { elm[key] = ''; } } for (key in props) { cur = props[key]; // ignore children if the node has textContent or innerHTML, // as these will throw away existing DOM nodes and cause removal errors // on subsequent patches (#3360) if (key === 'textContent' || key === 'innerHTML') { if (vnode.children) { vnode.children.length = 0; } if (cur === oldProps[key]) { continue } // #6601 work around Chrome version <= 55 bug where single textNode // replaced by innerHTML/textContent retains its parentNode property if (elm.childNodes.length === 1) { elm.removeChild(elm.childNodes[0]); } } if (key === 'value' && elm.tagName !== 'PROGRESS') { // store value as _value as well since // non-string values will be stringified elm._value = cur; // avoid resetting cursor position when value is the same var strCur = isUndef(cur) ? '' : String(cur); if (shouldUpdateValue(elm, strCur)) { elm.value = strCur; } } else if (key === 'innerHTML' && isSVG(elm.tagName) && isUndef(elm.innerHTML)) { // IE doesn't support innerHTML for SVG elements svgContainer = svgContainer || document.createElement('div'); svgContainer.innerHTML = "<svg>" + cur + "</svg>"; var svg = svgContainer.firstChild; while (elm.firstChild) { elm.removeChild(elm.firstChild); } while (svg.firstChild) { elm.appendChild(svg.firstChild); } } else if ( // skip the update if old and new VDOM state is the same. // `value` is handled separately because the DOM value may be temporarily // out of sync with VDOM state due to focus, composition and modifiers. // This #4521 by skipping the unnecesarry `checked` update. cur !== oldProps[key] ) { // some property updates can throw // e.g. `value` on <progress> w/ non-finite value try { elm[key] = cur; } catch (e) {} } } } // check platforms/web/util/attrs.js acceptValue function shouldUpdateValue (elm, checkVal) { return (!elm.composing && ( elm.tagName === 'OPTION' || isNotInFocusAndDirty(elm, checkVal) || isDirtyWithModifiers(elm, checkVal) )) } function isNotInFocusAndDirty (elm, checkVal) { // return true when textbox (.number and .trim) loses focus and its value is // not equal to the updated value var notInFocus = true; // #6157 // work around IE bug when accessing document.activeElement in an iframe try { notInFocus = document.activeElement !== elm; } catch (e) {} return notInFocus && elm.value !== checkVal } function isDirtyWithModifiers (elm, newVal) { var value = elm.value; var modifiers = elm._vModifiers; // injected by v-model runtime if (isDef(modifiers)) { if (modifiers.number) { return toNumber(value) !== toNumber(newVal) } if (modifiers.trim) { return value.trim() !== newVal.trim() } } return value !== newVal } var domProps = { create: updateDOMProps, update: updateDOMProps }; /* */ var parseStyleText = cached(function (cssText) { var res = {}; var listDelimiter = /;(?![^(]*\))/g; var propertyDelimiter = /:(.+)/; cssText.split(listDelimiter).forEach(function (item) { if (item) { var tmp = item.split(propertyDelimiter); tmp.length > 1 && (res[tmp[0].trim()] = tmp[1].trim()); } }); return res }); // merge static and dynamic style data on the same vnode function normalizeStyleData (data) { var style = normalizeStyleBinding(data.style); // static style is pre-processed into an object during compilation // and is always a fresh object, so it's safe to merge into it return data.staticStyle ? extend(data.staticStyle, style) : style } // normalize possible array / string values into Object function normalizeStyleBinding (bindingStyle) { if (Array.isArray(bindingStyle)) { return toObject(bindingStyle) } if (typeof bindingStyle === 'string') { return parseStyleText(bindingStyle) } return bindingStyle } /** * parent component style should be after child's * so that parent component's style could override it */ function getStyle (vnode, checkChild) { var res = {}; var styleData; if (checkChild) { var childNode = vnode; while (childNode.componentInstance) { childNode = childNode.componentInstance._vnode; if ( childNode && childNode.data && (styleData = normalizeStyleData(childNode.data)) ) { extend(res, styleData); } } } if ((styleData = normalizeStyleData(vnode.data))) { extend(res, styleData); } var parentNode = vnode; while ((parentNode = parentNode.parent)) { if (parentNode.data && (styleData = normalizeStyleData(parentNode.data))) { extend(res, styleData); } } return res } /* */ var cssVarRE = /^--/; var importantRE = /\s*!important$/; var setProp = function (el, name, val) { /* istanbul ignore if */ if (cssVarRE.test(name)) { el.style.setProperty(name, val); } else if (importantRE.test(val)) { el.style.setProperty(hyphenate(name), val.replace(importantRE, ''), 'important'); } else { var normalizedName = normalize(name); if (Array.isArray(val)) { // Support values array created by autoprefixer, e.g. // {display: ["-webkit-box", "-ms-flexbox", "flex"]} // Set them one by one, and the browser will only set those it can recognize for (var i = 0, len = val.length; i < len; i++) { el.style[normalizedName] = val[i]; } } else { el.style[normalizedName] = val; } } }; var vendorNames = ['Webkit', 'Moz', 'ms']; var emptyStyle; var normalize = cached(function (prop) { emptyStyle = emptyStyle || document.createElement('div').style; prop = camelize(prop); if (prop !== 'filter' && (prop in emptyStyle)) { return prop } var capName = prop.charAt(0).toUpperCase() + prop.slice(1); for (var i = 0; i < vendorNames.length; i++) { var name = vendorNames[i] + capName; if (name in emptyStyle) { return name } } }); function updateStyle (oldVnode, vnode) { var data = vnode.data; var oldData = oldVnode.data; if (isUndef(data.staticStyle) && isUndef(data.style) && isUndef(oldData.staticStyle) && isUndef(oldData.style) ) { return } var cur, name; var el = vnode.elm; var oldStaticStyle = oldData.staticStyle; var oldStyleBinding = oldData.normalizedStyle || oldData.style || {}; // if static style exists, stylebinding already merged into it when doing normalizeStyleData var oldStyle = oldStaticStyle || oldStyleBinding; var style = normalizeStyleBinding(vnode.data.style) || {}; // store normalized style under a different key for next diff // make sure to clone it if it's reactive, since the user likely wants // to mutate it. vnode.data.normalizedStyle = isDef(style.__ob__) ? extend({}, style) : style; var newStyle = getStyle(vnode, true); for (name in oldStyle) { if (isUndef(newStyle[name])) { setProp(el, name, ''); } } for (name in newStyle) { cur = newStyle[name]; if (cur !== oldStyle[name]) { // ie9 setting to null has no effect, must use empty string setProp(el, name, cur == null ? '' : cur); } } } var style = { create: updateStyle, update: updateStyle }; /* */ var whitespaceRE = /\s+/; /** * Add class with compatibility for SVG since classList is not supported on * SVG elements in IE */ function addClass (el, cls) { /* istanbul ignore if */ if (!cls || !(cls = cls.trim())) { return } /* istanbul ignore else */ if (el.classList) { if (cls.indexOf(' ') > -1) { cls.split(whitespaceRE).forEach(function (c) { return el.classList.add(c); }); } else { el.classList.add(cls); } } else { var cur = " " + (el.getAttribute('class') || '') + " "; if (cur.indexOf(' ' + cls + ' ') < 0) { el.setAttribute('class', (cur + cls).trim()); } } } /** * Remove class with compatibility for SVG since classList is not supported on * SVG elements in IE */ function removeClass (el, cls) { /* istanbul ignore if */ if (!cls || !(cls = cls.trim())) { return } /* istanbul ignore else */ if (el.classList) { if (cls.indexOf(' ') > -1) { cls.split(whitespaceRE).forEach(function (c) { return el.classList.remove(c); }); } else { el.classList.remove(cls); } if (!el.classList.length) { el.removeAttribute('class'); } } else { var cur = " " + (el.getAttribute('class') || '') + " "; var tar = ' ' + cls + ' '; while (cur.indexOf(tar) >= 0) { cur = cur.replace(tar, ' '); } cur = cur.trim(); if (cur) { el.setAttribute('class', cur); } else { el.removeAttribute('class'); } } } /* */ function resolveTransition (def$$1) { if (!def$$1) { return } /* istanbul ignore else */ if (typeof def$$1 === 'object') { var res = {}; if (def$$1.css !== false) { extend(res, autoCssTransition(def$$1.name || 'v')); } extend(res, def$$1); return res } else if (typeof def$$1 === 'string') { return autoCssTransition(def$$1) } } var autoCssTransition = cached(function (name) { return { enterClass: (name + "-enter"), enterToClass: (name + "-enter-to"), enterActiveClass: (name + "-enter-active"), leaveClass: (name + "-leave"), leaveToClass: (name + "-leave-to"), leaveActiveClass: (name + "-leave-active") } }); var hasTransition = inBrowser && !isIE9; var TRANSITION = 'transition'; var ANIMATION = 'animation'; // Transition property/event sniffing var transitionProp = 'transition'; var transitionEndEvent = 'transitionend'; var animationProp = 'animation'; var animationEndEvent = 'animationend'; if (hasTransition) { /* istanbul ignore if */ if (window.ontransitionend === undefined && window.onwebkittransitionend !== undefined ) { transitionProp = 'WebkitTransition'; transitionEndEvent = 'webkitTransitionEnd'; } if (window.onanimationend === undefined && window.onwebkitanimationend !== undefined ) { animationProp = 'WebkitAnimation'; animationEndEvent = 'webkitAnimationEnd'; } } // binding to window is necessary to make hot reload work in IE in strict mode var raf = inBrowser ? window.requestAnimationFrame ? window.requestAnimationFrame.bind(window) : setTimeout : /* istanbul ignore next */ function (fn) { return fn(); }; function nextFrame (fn) { raf(function () { raf(fn); }); } function addTransitionClass (el, cls) { var transitionClasses = el._transitionClasses || (el._transitionClasses = []); if (transitionClasses.indexOf(cls) < 0) { transitionClasses.push(cls); addClass(el, cls); } } function removeTransitionClass (el, cls) { if (el._transitionClasses) { remove(el._transitionClasses, cls); } removeClass(el, cls); } function whenTransitionEnds ( el, expectedType, cb ) { var ref = getTransitionInfo(el, expectedType); var type = ref.type; var timeout = ref.timeout; var propCount = ref.propCount; if (!type) { return cb() } var event = type === TRANSITION ? transitionEndEvent : animationEndEvent; var ended = 0; var end = function () { el.removeEventListener(event, onEnd); cb(); }; var onEnd = function (e) { if (e.target === el) { if (++ended >= propCount) { end(); } } }; setTimeout(function () { if (ended < propCount) { end(); } }, timeout + 1); el.addEventListener(event, onEnd); } var transformRE = /\b(transform|all)(,|$)/; function getTransitionInfo (el, expectedType) { var styles = window.getComputedStyle(el); // JSDOM may return undefined for transition properties var transitionDelays = (styles[transitionProp + 'Delay'] || '').split(', '); var transitionDurations = (styles[transitionProp + 'Duration'] || '').split(', '); var transitionTimeout = getTimeout(transitionDelays, transitionDurations); var animationDelays = (styles[animationProp + 'Delay'] || '').split(', '); var animationDurations = (styles[animationProp + 'Duration'] || '').split(', '); var animationTimeout = getTimeout(animationDelays, animationDurations); var type; var timeout = 0; var propCount = 0; /* istanbul ignore if */ if (expectedType === TRANSITION) { if (transitionTimeout > 0) { type = TRANSITION; timeout = transitionTimeout; propCount = transitionDurations.length; } } else if (expectedType === ANIMATION) { if (animationTimeout > 0) { type = ANIMATION; timeout = animationTimeout; propCount = animationDurations.length; } } else { timeout = Math.max(transitionTimeout, animationTimeout); type = timeout > 0 ? transitionTimeout > animationTimeout ? TRANSITION : ANIMATION : null; propCount = type ? type === TRANSITION ? transitionDurations.length : animationDurations.length : 0; } var hasTransform = type === TRANSITION && transformRE.test(styles[transitionProp + 'Property']); return { type: type, timeout: timeout, propCount: propCount, hasTransform: hasTransform } } function getTimeout (delays, durations) { /* istanbul ignore next */ while (delays.length < durations.length) { delays = delays.concat(delays); } return Math.max.apply(null, durations.map(function (d, i) { return toMs(d) + toMs(delays[i]) })) } // Old versions of Chromium (below 61.0.3163.100) formats floating pointer numbers // in a locale-dependent way, using a comma instead of a dot. // If comma is not replaced with a dot, the input will be rounded down (i.e. acting // as a floor function) causing unexpected behaviors function toMs (s) { return Number(s.slice(0, -1).replace(',', '.')) * 1000 } /* */ function enter (vnode, toggleDisplay) { var el = vnode.elm; // call leave callback now if (isDef(el._leaveCb)) { el._leaveCb.cancelled = true; el._leaveCb(); } var data = resolveTransition(vnode.data.transition); if (isUndef(data)) { return } /* istanbul ignore if */ if (isDef(el._enterCb) || el.nodeType !== 1) { return } var css = data.css; var type = data.type; var enterClass = data.enterClass; var enterToClass = data.enterToClass; var enterActiveClass = data.enterActiveClass; var appearClass = data.appearClass; var appearToClass = data.appearToClass; var appearActiveClass = data.appearActiveClass; var beforeEnter = data.beforeEnter; var enter = data.enter; var afterEnter = data.afterEnter; var enterCancelled = data.enterCancelled; var beforeAppear = data.beforeAppear; var appear = data.appear; var afterAppear = data.afterAppear; var appearCancelled = data.appearCancelled; var duration = data.duration; // activeInstance will always be the <transition> component managing this // transition. One edge case to check is when the <transition> is placed // as the root node of a child component. In that case we need to check // <transition>'s parent for appear check. var context = activeInstance; var transitionNode = activeInstance.$vnode; while (transitionNode && transitionNode.parent) { context = transitionNode.context; transitionNode = transitionNode.parent; } var isAppear = !context._isMounted || !vnode.isRootInsert; if (isAppear && !appear && appear !== '') { return } var startClass = isAppear && appearClass ? appearClass : enterClass; var activeClass = isAppear && appearActiveClass ? appearActiveClass : enterActiveClass; var toClass = isAppear && appearToClass ? appearToClass : enterToClass; var beforeEnterHook = isAppear ? (beforeAppear || beforeEnter) : beforeEnter; var enterHook = isAppear ? (typeof appear === 'function' ? appear : enter) : enter; var afterEnterHook = isAppear ? (afterAppear || afterEnter) : afterEnter; var enterCancelledHook = isAppear ? (appearCancelled || enterCancelled) : enterCancelled; var explicitEnterDuration = toNumber( isObject(duration) ? duration.enter : duration ); if (explicitEnterDuration != null) { checkDuration(explicitEnterDuration, 'enter', vnode); } var expectsCSS = css !== false && !isIE9; var userWantsControl = getHookArgumentsLength(enterHook); var cb = el._enterCb = once(function () { if (expectsCSS) { removeTransitionClass(el, toClass); removeTransitionClass(el, activeClass); } if (cb.cancelled) { if (expectsCSS) { removeTransitionClass(el, startClass); } enterCancelledHook && enterCancelledHook(el); } else { afterEnterHook && afterEnterHook(el); } el._enterCb = null; }); if (!vnode.data.show) { // remove pending leave element on enter by injecting an insert hook mergeVNodeHook(vnode, 'insert', function () { var parent = el.parentNode; var pendingNode = parent && parent._pending && parent._pending[vnode.key]; if (pendingNode && pendingNode.tag === vnode.tag && pendingNode.elm._leaveCb ) { pendingNode.elm._leaveCb(); } enterHook && enterHook(el, cb); }); } // start enter transition beforeEnterHook && beforeEnterHook(el); if (expectsCSS) { addTransitionClass(el, startClass); addTransitionClass(el, activeClass); nextFrame(function () { removeTransitionClass(el, startClass); if (!cb.cancelled) { addTransitionClass(el, toClass); if (!userWantsControl) { if (isValidDuration(explicitEnterDuration)) { setTimeout(cb, explicitEnterDuration); } else { whenTransitionEnds(el, type, cb); } } } }); } if (vnode.data.show) { toggleDisplay && toggleDisplay(); enterHook && enterHook(el, cb); } if (!expectsCSS && !userWantsControl) { cb(); } } function leave (vnode, rm) { var el = vnode.elm; // call enter callback now if (isDef(el._enterCb)) { el._enterCb.cancelled = true; el._enterCb(); } var data = resolveTransition(vnode.data.transition); if (isUndef(data) || el.nodeType !== 1) { return rm() } /* istanbul ignore if */ if (isDef(el._leaveCb)) { return } var css = data.css; var type = data.type; var leaveClass = data.leaveClass; var leaveToClass = data.leaveToClass; var leaveActiveClass = data.leaveActiveClass; var beforeLeave = data.beforeLeave; var leave = data.leave; var afterLeave = data.afterLeave; var leaveCancelled = data.leaveCancelled; var delayLeave = data.delayLeave; var duration = data.duration; var expectsCSS = css !== false && !isIE9; var userWantsControl = getHookArgumentsLength(leave); var explicitLeaveDuration = toNumber( isObject(duration) ? duration.leave : duration ); if (isDef(explicitLeaveDuration)) { checkDuration(explicitLeaveDuration, 'leave', vnode); } var cb = el._leaveCb = once(function () { if (el.parentNode && el.parentNode._pending) { el.parentNode._pending[vnode.key] = null; } if (expectsCSS) { removeTransitionClass(el, leaveToClass); removeTransitionClass(el, leaveActiveClass); } if (cb.cancelled) { if (expectsCSS) { removeTransitionClass(el, leaveClass); } leaveCancelled && leaveCancelled(el); } else { rm(); afterLeave && afterLeave(el); } el._leaveCb = null; }); if (delayLeave) { delayLeave(performLeave); } else { performLeave(); } function performLeave () { // the delayed leave may have already been cancelled if (cb.cancelled) { return } // record leaving element if (!vnode.data.show && el.parentNode) { (el.parentNode._pending || (el.parentNode._pending = {}))[(vnode.key)] = vnode; } beforeLeave && beforeLeave(el); if (expectsCSS) { addTransitionClass(el, leaveClass); addTransitionClass(el, leaveActiveClass); nextFrame(function () { removeTransitionClass(el, leaveClass); if (!cb.cancelled) { addTransitionClass(el, leaveToClass); if (!userWantsControl) { if (isValidDuration(explicitLeaveDuration)) { setTimeout(cb, explicitLeaveDuration); } else { whenTransitionEnds(el, type, cb); } } } }); } leave && leave(el, cb); if (!expectsCSS && !userWantsControl) { cb(); } } } // only used in dev mode function checkDuration (val, name, vnode) { if (typeof val !== 'number') { warn( "<transition> explicit " + name + " duration is not a valid number - " + "got " + (JSON.stringify(val)) + ".", vnode.context ); } else if (isNaN(val)) { warn( "<transition> explicit " + name + " duration is NaN - " + 'the duration expression might be incorrect.', vnode.context ); } } function isValidDuration (val) { return typeof val === 'number' && !isNaN(val) } /** * Normalize a transition hook's argument length. The hook may be: * - a merged hook (invoker) with the original in .fns * - a wrapped component method (check ._length) * - a plain function (.length) */ function getHookArgumentsLength (fn) { if (isUndef(fn)) { return false } var invokerFns = fn.fns; if (isDef(invokerFns)) { // invoker return getHookArgumentsLength( Array.isArray(invokerFns) ? invokerFns[0] : invokerFns ) } else { return (fn._length || fn.length) > 1 } } function _enter (_, vnode) { if (vnode.data.show !== true) { enter(vnode); } } var transition = inBrowser ? { create: _enter, activate: _enter, remove: function remove$$1 (vnode, rm) { /* istanbul ignore else */ if (vnode.data.show !== true) { leave(vnode, rm); } else { rm(); } } } : {}; var platformModules = [ attrs, klass, events, domProps, style, transition ]; /* */ // the directive module should be applied last, after all // built-in modules have been applied. var modules = platformModules.concat(baseModules); var patch = createPatchFunction({ nodeOps: nodeOps, modules: modules }); /** * Not type checking this file because flow doesn't like attaching * properties to Elements. */ /* istanbul ignore if */ if (isIE9) { // http://www.matts411.com/post/internet-explorer-9-oninput/ document.addEventListener('selectionchange', function () { var el = document.activeElement; if (el && el.vmodel) { trigger(el, 'input'); } }); } var directive = { inserted: function inserted (el, binding, vnode, oldVnode) { if (vnode.tag === 'select') { // #6903 if (oldVnode.elm && !oldVnode.elm._vOptions) { mergeVNodeHook(vnode, 'postpatch', function () { directive.componentUpdated(el, binding, vnode); }); } else { setSelected(el, binding, vnode.context); } el._vOptions = [].map.call(el.options, getValue); } else if (vnode.tag === 'textarea' || isTextInputType(el.type)) { el._vModifiers = binding.modifiers; if (!binding.modifiers.lazy) { el.addEventListener('compositionstart', onCompositionStart); el.addEventListener('compositionend', onCompositionEnd); // Safari < 10.2 & UIWebView doesn't fire compositionend when // switching focus before confirming composition choice // this also fixes the issue where some browsers e.g. iOS Chrome // fires "change" instead of "input" on autocomplete. el.addEventListener('change', onCompositionEnd); /* istanbul ignore if */ if (isIE9) { el.vmodel = true; } } } }, componentUpdated: function componentUpdated (el, binding, vnode) { if (vnode.tag === 'select') { setSelected(el, binding, vnode.context); // in case the options rendered by v-for have changed, // it's possible that the value is out-of-sync with the rendered options. // detect such cases and filter out values that no longer has a matching // option in the DOM. var prevOptions = el._vOptions; var curOptions = el._vOptions = [].map.call(el.options, getValue); if (curOptions.some(function (o, i) { return !looseEqual(o, prevOptions[i]); })) { // trigger change event if // no matching option found for at least one value var needReset = el.multiple ? binding.value.some(function (v) { return hasNoMatchingOption(v, curOptions); }) : binding.value !== binding.oldValue && hasNoMatchingOption(binding.value, curOptions); if (needReset) { trigger(el, 'change'); } } } } }; function setSelected (el, binding, vm) { actuallySetSelected(el, binding, vm); /* istanbul ignore if */ if (isIE || isEdge) { setTimeout(function () { actuallySetSelected(el, binding, vm); }, 0); } } function actuallySetSelected (el, binding, vm) { var value = binding.value; var isMultiple = el.multiple; if (isMultiple && !Array.isArray(value)) { warn( "<select multiple v-model=\"" + (binding.expression) + "\"> " + "expects an Array value for its binding, but got " + (Object.prototype.toString.call(value).slice(8, -1)), vm ); return } var selected, option; for (var i = 0, l = el.options.length; i < l; i++) { option = el.options[i]; if (isMultiple) { selected = looseIndexOf(value, getValue(option)) > -1; if (option.selected !== selected) { option.selected = selected; } } else { if (looseEqual(getValue(option), value)) { if (el.selectedIndex !== i) { el.selectedIndex = i; } return } } } if (!isMultiple) { el.selectedIndex = -1; } } function hasNoMatchingOption (value, options) { return options.every(function (o) { return !looseEqual(o, value); }) } function getValue (option) { return '_value' in option ? option._value : option.value } function onCompositionStart (e) { e.target.composing = true; } function onCompositionEnd (e) { // prevent triggering an input event for no reason if (!e.target.composing) { return } e.target.composing = false; trigger(e.target, 'input'); } function trigger (el, type) { var e = document.createEvent('HTMLEvents'); e.initEvent(type, true, true); el.dispatchEvent(e); } /* */ // recursively search for possible transition defined inside the component root function locateNode (vnode) { return vnode.componentInstance && (!vnode.data || !vnode.data.transition) ? locateNode(vnode.componentInstance._vnode) : vnode } var show = { bind: function bind (el, ref, vnode) { var value = ref.value; vnode = locateNode(vnode); var transition$$1 = vnode.data && vnode.data.transition; var originalDisplay = el.__vOriginalDisplay = el.style.display === 'none' ? '' : el.style.display; if (value && transition$$1) { vnode.data.show = true; enter(vnode, function () { el.style.display = originalDisplay; }); } else { el.style.display = value ? originalDisplay : 'none'; } }, update: function update (el, ref, vnode) { var value = ref.value; var oldValue = ref.oldValue; /* istanbul ignore if */ if (!value === !oldValue) { return } vnode = locateNode(vnode); var transition$$1 = vnode.data && vnode.data.transition; if (transition$$1) { vnode.data.show = true; if (value) { enter(vnode, function () { el.style.display = el.__vOriginalDisplay; }); } else { leave(vnode, function () { el.style.display = 'none'; }); } } else { el.style.display = value ? el.__vOriginalDisplay : 'none'; } }, unbind: function unbind ( el, binding, vnode, oldVnode, isDestroy ) { if (!isDestroy) { el.style.display = el.__vOriginalDisplay; } } }; var platformDirectives = { model: directive, show: show }; /* */ var transitionProps = { name: String, appear: Boolean, css: Boolean, mode: String, type: String, enterClass: String, leaveClass: String, enterToClass: String, leaveToClass: String, enterActiveClass: String, leaveActiveClass: String, appearClass: String, appearActiveClass: String, appearToClass: String, duration: [Number, String, Object] }; // in case the child is also an abstract component, e.g. <keep-alive> // we want to recursively retrieve the real component to be rendered function getRealChild (vnode) { var compOptions = vnode && vnode.componentOptions; if (compOptions && compOptions.Ctor.options.abstract) { return getRealChild(getFirstComponentChild(compOptions.children)) } else { return vnode } } function extractTransitionData (comp) { var data = {}; var options = comp.$options; // props for (var key in options.propsData) { data[key] = comp[key]; } // events. // extract listeners and pass them directly to the transition methods var listeners = options._parentListeners; for (var key$1 in listeners) { data[camelize(key$1)] = listeners[key$1]; } return data } function placeholder (h, rawChild) { if (/\d-keep-alive$/.test(rawChild.tag)) { return h('keep-alive', { props: rawChild.componentOptions.propsData }) } } function hasParentTransition (vnode) { while ((vnode = vnode.parent)) { if (vnode.data.transition) { return true } } } function isSameChild (child, oldChild) { return oldChild.key === child.key && oldChild.tag === child.tag } var isNotTextNode = function (c) { return c.tag || isAsyncPlaceholder(c); }; var isVShowDirective = function (d) { return d.name === 'show'; }; var Transition = { name: 'transition', props: transitionProps, abstract: true, render: function render (h) { var this$1 = this; var children = this.$slots.default; if (!children) { return } // filter out text nodes (possible whitespaces) children = children.filter(isNotTextNode); /* istanbul ignore if */ if (!children.length) { return } // warn multiple elements if (children.length > 1) { warn( '<transition> can only be used on a single element. Use ' + '<transition-group> for lists.', this.$parent ); } var mode = this.mode; // warn invalid mode if (mode && mode !== 'in-out' && mode !== 'out-in' ) { warn( 'invalid <transition> mode: ' + mode, this.$parent ); } var rawChild = children[0]; // if this is a component root node and the component's // parent container node also has transition, skip. if (hasParentTransition(this.$vnode)) { return rawChild } // apply transition data to child // use getRealChild() to ignore abstract components e.g. keep-alive var child = getRealChild(rawChild); /* istanbul ignore if */ if (!child) { return rawChild } if (this._leaving) { return placeholder(h, rawChild) } // ensure a key that is unique to the vnode type and to this transition // component instance. This key will be used to remove pending leaving nodes // during entering. var id = "__transition-" + (this._uid) + "-"; child.key = child.key == null ? child.isComment ? id + 'comment' : id + child.tag : isPrimitive(child.key) ? (String(child.key).indexOf(id) === 0 ? child.key : id + child.key) : child.key; var data = (child.data || (child.data = {})).transition = extractTransitionData(this); var oldRawChild = this._vnode; var oldChild = getRealChild(oldRawChild); // mark v-show // so that the transition module can hand over the control to the directive if (child.data.directives && child.data.directives.some(isVShowDirective)) { child.data.show = true; } if ( oldChild && oldChild.data && !isSameChild(child, oldChild) && !isAsyncPlaceholder(oldChild) && // #6687 component root is a comment node !(oldChild.componentInstance && oldChild.componentInstance._vnode.isComment) ) { // replace old child transition data with fresh one // important for dynamic transitions! var oldData = oldChild.data.transition = extend({}, data); // handle transition mode if (mode === 'out-in') { // return placeholder node and queue update when leave finishes this._leaving = true; mergeVNodeHook(oldData, 'afterLeave', function () { this$1._leaving = false; this$1.$forceUpdate(); }); return placeholder(h, rawChild) } else if (mode === 'in-out') { if (isAsyncPlaceholder(child)) { return oldRawChild } var delayedLeave; var performLeave = function () { delayedLeave(); }; mergeVNodeHook(data, 'afterEnter', performLeave); mergeVNodeHook(data, 'enterCancelled', performLeave); mergeVNodeHook(oldData, 'delayLeave', function (leave) { delayedLeave = leave; }); } } return rawChild } }; /* */ var props = extend({ tag: String, moveClass: String }, transitionProps); delete props.mode; var TransitionGroup = { props: props, beforeMount: function beforeMount () { var this$1 = this; var update = this._update; this._update = function (vnode, hydrating) { var restoreActiveInstance = setActiveInstance(this$1); // force removing pass this$1.__patch__( this$1._vnode, this$1.kept, false, // hydrating true // removeOnly (!important, avoids unnecessary moves) ); this$1._vnode = this$1.kept; restoreActiveInstance(); update.call(this$1, vnode, hydrating); }; }, render: function render (h) { var tag = this.tag || this.$vnode.data.tag || 'span'; var map = Object.create(null); var prevChildren = this.prevChildren = this.children; var rawChildren = this.$slots.default || []; var children = this.children = []; var transitionData = extractTransitionData(this); for (var i = 0; i < rawChildren.length; i++) { var c = rawChildren[i]; if (c.tag) { if (c.key != null && String(c.key).indexOf('__vlist') !== 0) { children.push(c); map[c.key] = c ;(c.data || (c.data = {})).transition = transitionData; } else { var opts = c.componentOptions; var name = opts ? (opts.Ctor.options.name || opts.tag || '') : c.tag; warn(("<transition-group> children must be keyed: <" + name + ">")); } } } if (prevChildren) { var kept = []; var removed = []; for (var i$1 = 0; i$1 < prevChildren.length; i$1++) { var c$1 = prevChildren[i$1]; c$1.data.transition = transitionData; c$1.data.pos = c$1.elm.getBoundingClientRect(); if (map[c$1.key]) { kept.push(c$1); } else { removed.push(c$1); } } this.kept = h(tag, null, kept); this.removed = removed; } return h(tag, null, children) }, updated: function updated () { var children = this.prevChildren; var moveClass = this.moveClass || ((this.name || 'v') + '-move'); if (!children.length || !this.hasMove(children[0].elm, moveClass)) { return } // we divide the work into three loops to avoid mixing DOM reads and writes // in each iteration - which helps prevent layout thrashing. children.forEach(callPendingCbs); children.forEach(recordPosition); children.forEach(applyTranslation); // force reflow to put everything in position // assign to this to avoid being removed in tree-shaking // $flow-disable-line this._reflow = document.body.offsetHeight; children.forEach(function (c) { if (c.data.moved) { var el = c.elm; var s = el.style; addTransitionClass(el, moveClass); s.transform = s.WebkitTransform = s.transitionDuration = ''; el.addEventListener(transitionEndEvent, el._moveCb = function cb (e) { if (e && e.target !== el) { return } if (!e || /transform$/.test(e.propertyName)) { el.removeEventListener(transitionEndEvent, cb); el._moveCb = null; removeTransitionClass(el, moveClass); } }); } }); }, methods: { hasMove: function hasMove (el, moveClass) { /* istanbul ignore if */ if (!hasTransition) { return false } /* istanbul ignore if */ if (this._hasMove) { return this._hasMove } // Detect whether an element with the move class applied has // CSS transitions. Since the element may be inside an entering // transition at this very moment, we make a clone of it and remove // all other transition classes applied to ensure only the move class // is applied. var clone = el.cloneNode(); if (el._transitionClasses) { el._transitionClasses.forEach(function (cls) { removeClass(clone, cls); }); } addClass(clone, moveClass); clone.style.display = 'none'; this.$el.appendChild(clone); var info = getTransitionInfo(clone); this.$el.removeChild(clone); return (this._hasMove = info.hasTransform) } } }; function callPendingCbs (c) { /* istanbul ignore if */ if (c.elm._moveCb) { c.elm._moveCb(); } /* istanbul ignore if */ if (c.elm._enterCb) { c.elm._enterCb(); } } function recordPosition (c) { c.data.newPos = c.elm.getBoundingClientRect(); } function applyTranslation (c) { var oldPos = c.data.pos; var newPos = c.data.newPos; var dx = oldPos.left - newPos.left; var dy = oldPos.top - newPos.top; if (dx || dy) { c.data.moved = true; var s = c.elm.style; s.transform = s.WebkitTransform = "translate(" + dx + "px," + dy + "px)"; s.transitionDuration = '0s'; } } var platformComponents = { Transition: Transition, TransitionGroup: TransitionGroup }; /* */ // install platform specific utils Vue.config.mustUseProp = mustUseProp; Vue.config.isReservedTag = isReservedTag; Vue.config.isReservedAttr = isReservedAttr; Vue.config.getTagNamespace = getTagNamespace; Vue.config.isUnknownElement = isUnknownElement; // install platform runtime directives & components extend(Vue.options.directives, platformDirectives); extend(Vue.options.components, platformComponents); // install platform patch function Vue.prototype.__patch__ = inBrowser ? patch : noop; // public mount method Vue.prototype.$mount = function ( el, hydrating ) { el = el && inBrowser ? query(el) : undefined; return mountComponent(this, el, hydrating) }; // devtools global hook /* istanbul ignore next */ if (inBrowser) { setTimeout(function () { if (config.devtools) { if (devtools) { devtools.emit('init', Vue); } else { console[console.info ? 'info' : 'log']( 'Download the Vue Devtools extension for a better development experience:\n' + 'https://github.com/vuejs/vue-devtools' ); } } if (config.productionTip !== false && typeof console !== 'undefined' ) { console[console.info ? 'info' : 'log']( "You are running Vue in development mode.\n" + "Make sure to turn on production mode when deploying for production.\n" + "See more tips at https://vuejs.org/guide/deployment.html" ); } }, 0); } /* */ var defaultTagRE = /\{\{((?:.|\r?\n)+?)\}\}/g; var regexEscapeRE = /[-.*+?^${}()|[\]\/\\]/g; var buildRegex = cached(function (delimiters) { var open = delimiters[0].replace(regexEscapeRE, '\\$&'); var close = delimiters[1].replace(regexEscapeRE, '\\$&'); return new RegExp(open + '((?:.|\\n)+?)' + close, 'g') }); function parseText ( text, delimiters ) { var tagRE = delimiters ? buildRegex(delimiters) : defaultTagRE; if (!tagRE.test(text)) { return } var tokens = []; var rawTokens = []; var lastIndex = tagRE.lastIndex = 0; var match, index, tokenValue; while ((match = tagRE.exec(text))) { index = match.index; // push text token if (index > lastIndex) { rawTokens.push(tokenValue = text.slice(lastIndex, index)); tokens.push(JSON.stringify(tokenValue)); } // tag token var exp = parseFilters(match[1].trim()); tokens.push(("_s(" + exp + ")")); rawTokens.push({ '@binding': exp }); lastIndex = index + match[0].length; } if (lastIndex < text.length) { rawTokens.push(tokenValue = text.slice(lastIndex)); tokens.push(JSON.stringify(tokenValue)); } return { expression: tokens.join('+'), tokens: rawTokens } } /* */ function transformNode (el, options) { var warn = options.warn || baseWarn; var staticClass = getAndRemoveAttr(el, 'class'); if (staticClass) { var res = parseText(staticClass, options.delimiters); if (res) { warn( "class=\"" + staticClass + "\": " + 'Interpolation inside attributes has been removed. ' + 'Use v-bind or the colon shorthand instead. For example, ' + 'instead of <div class="{{ val }}">, use <div :class="val">.', el.rawAttrsMap['class'] ); } } if (staticClass) { el.staticClass = JSON.stringify(staticClass); } var classBinding = getBindingAttr(el, 'class', false /* getStatic */); if (classBinding) { el.classBinding = classBinding; } } function genData (el) { var data = ''; if (el.staticClass) { data += "staticClass:" + (el.staticClass) + ","; } if (el.classBinding) { data += "class:" + (el.classBinding) + ","; } return data } var klass$1 = { staticKeys: ['staticClass'], transformNode: transformNode, genData: genData }; /* */ function transformNode$1 (el, options) { var warn = options.warn || baseWarn; var staticStyle = getAndRemoveAttr(el, 'style'); if (staticStyle) { /* istanbul ignore if */ { var res = parseText(staticStyle, options.delimiters); if (res) { warn( "style=\"" + staticStyle + "\": " + 'Interpolation inside attributes has been removed. ' + 'Use v-bind or the colon shorthand instead. For example, ' + 'instead of <div style="{{ val }}">, use <div :style="val">.', el.rawAttrsMap['style'] ); } } el.staticStyle = JSON.stringify(parseStyleText(staticStyle)); } var styleBinding = getBindingAttr(el, 'style', false /* getStatic */); if (styleBinding) { el.styleBinding = styleBinding; } } function genData$1 (el) { var data = ''; if (el.staticStyle) { data += "staticStyle:" + (el.staticStyle) + ","; } if (el.styleBinding) { data += "style:(" + (el.styleBinding) + "),"; } return data } var style$1 = { staticKeys: ['staticStyle'], transformNode: transformNode$1, genData: genData$1 }; /* */ var decoder; var he = { decode: function decode (html) { decoder = decoder || document.createElement('div'); decoder.innerHTML = html; return decoder.textContent } }; /* */ var isUnaryTag = makeMap( 'area,base,br,col,embed,frame,hr,img,input,isindex,keygen,' + 'link,meta,param,source,track,wbr' ); // Elements that you can, intentionally, leave open // (and which close themselves) var canBeLeftOpenTag = makeMap( 'colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr,source' ); // HTML5 tags https://html.spec.whatwg.org/multipage/indices.html#elements-3 // Phrasing Content https://html.spec.whatwg.org/multipage/dom.html#phrasing-content var isNonPhrasingTag = makeMap( 'address,article,aside,base,blockquote,body,caption,col,colgroup,dd,' + 'details,dialog,div,dl,dt,fieldset,figcaption,figure,footer,form,' + 'h1,h2,h3,h4,h5,h6,head,header,hgroup,hr,html,legend,li,menuitem,meta,' + 'optgroup,option,param,rp,rt,source,style,summary,tbody,td,tfoot,th,thead,' + 'title,tr,track' ); /** * Not type-checking this file because it's mostly vendor code. */ // Regular Expressions for parsing tags and attributes var attribute = /^\s*([^\s"'<>\/=]+)(?:\s*(=)\s*(?:"([^"]*)"+|'([^']*)'+|([^\s"'=<>`]+)))?/; var dynamicArgAttribute = /^\s*((?:v-[\w-]+:|@|:|#)\[[^=]+\][^\s"'<>\/=]*)(?:\s*(=)\s*(?:"([^"]*)"+|'([^']*)'+|([^\s"'=<>`]+)))?/; var ncname = "[a-zA-Z_][\\-\\.0-9_a-zA-Z" + (unicodeRegExp.source) + "]*"; var qnameCapture = "((?:" + ncname + "\\:)?" + ncname + ")"; var startTagOpen = new RegExp(("^<" + qnameCapture)); var startTagClose = /^\s*(\/?)>/; var endTag = new RegExp(("^<\\/" + qnameCapture + "[^>]*>")); var doctype = /^<!DOCTYPE [^>]+>/i; // #7298: escape - to avoid being pased as HTML comment when inlined in page var comment = /^<!\--/; var conditionalComment = /^<!\[/; // Special Elements (can contain anything) var isPlainTextElement = makeMap('script,style,textarea', true); var reCache = {}; var decodingMap = { '&lt;': '<', '&gt;': '>', '&quot;': '"', '&amp;': '&', '&#10;': '\n', '&#9;': '\t', '&#39;': "'" }; var encodedAttr = /&(?:lt|gt|quot|amp|#39);/g; var encodedAttrWithNewLines = /&(?:lt|gt|quot|amp|#39|#10|#9);/g; // #5992 var isIgnoreNewlineTag = makeMap('pre,textarea', true); var shouldIgnoreFirstNewline = function (tag, html) { return tag && isIgnoreNewlineTag(tag) && html[0] === '\n'; }; function decodeAttr (value, shouldDecodeNewlines) { var re = shouldDecodeNewlines ? encodedAttrWithNewLines : encodedAttr; return value.replace(re, function (match) { return decodingMap[match]; }) } function parseHTML (html, options) { var stack = []; var expectHTML = options.expectHTML; var isUnaryTag$$1 = options.isUnaryTag || no; var canBeLeftOpenTag$$1 = options.canBeLeftOpenTag || no; var index = 0; var last, lastTag; while (html) { last = html; // Make sure we're not in a plaintext content element like script/style if (!lastTag || !isPlainTextElement(lastTag)) { var textEnd = html.indexOf('<'); if (textEnd === 0) { // Comment: if (comment.test(html)) { var commentEnd = html.indexOf('-->'); if (commentEnd >= 0) { if (options.shouldKeepComment) { options.comment(html.substring(4, commentEnd), index, index + commentEnd + 3); } advance(commentEnd + 3); continue } } // http://en.wikipedia.org/wiki/Conditional_comment#Downlevel-revealed_conditional_comment if (conditionalComment.test(html)) { var conditionalEnd = html.indexOf(']>'); if (conditionalEnd >= 0) { advance(conditionalEnd + 2); continue } } // Doctype: var doctypeMatch = html.match(doctype); if (doctypeMatch) { advance(doctypeMatch[0].length); continue } // End tag: var endTagMatch = html.match(endTag); if (endTagMatch) { var curIndex = index; advance(endTagMatch[0].length); parseEndTag(endTagMatch[1], curIndex, index); continue } // Start tag: var startTagMatch = parseStartTag(); if (startTagMatch) { handleStartTag(startTagMatch); if (shouldIgnoreFirstNewline(startTagMatch.tagName, html)) { advance(1); } continue } } var text = (void 0), rest = (void 0), next = (void 0); if (textEnd >= 0) { rest = html.slice(textEnd); while ( !endTag.test(rest) && !startTagOpen.test(rest) && !comment.test(rest) && !conditionalComment.test(rest) ) { // < in plain text, be forgiving and treat it as text next = rest.indexOf('<', 1); if (next < 0) { break } textEnd += next; rest = html.slice(textEnd); } text = html.substring(0, textEnd); } if (textEnd < 0) { text = html; } if (text) { advance(text.length); } if (options.chars && text) { options.chars(text, index - text.length, index); } } else { var endTagLength = 0; var stackedTag = lastTag.toLowerCase(); var reStackedTag = reCache[stackedTag] || (reCache[stackedTag] = new RegExp('([\\s\\S]*?)(</' + stackedTag + '[^>]*>)', 'i')); var rest$1 = html.replace(reStackedTag, function (all, text, endTag) { endTagLength = endTag.length; if (!isPlainTextElement(stackedTag) && stackedTag !== 'noscript') { text = text .replace(/<!\--([\s\S]*?)-->/g, '$1') // #7298 .replace(/<!\[CDATA\[([\s\S]*?)]]>/g, '$1'); } if (shouldIgnoreFirstNewline(stackedTag, text)) { text = text.slice(1); } if (options.chars) { options.chars(text); } return '' }); index += html.length - rest$1.length; html = rest$1; parseEndTag(stackedTag, index - endTagLength, index); } if (html === last) { options.chars && options.chars(html); if (!stack.length && options.warn) { options.warn(("Mal-formatted tag at end of template: \"" + html + "\""), { start: index + html.length }); } break } } // Clean up any remaining tags parseEndTag(); function advance (n) { index += n; html = html.substring(n); } function parseStartTag () { var start = html.match(startTagOpen); if (start) { var match = { tagName: start[1], attrs: [], start: index }; advance(start[0].length); var end, attr; while (!(end = html.match(startTagClose)) && (attr = html.match(dynamicArgAttribute) || html.match(attribute))) { attr.start = index; advance(attr[0].length); attr.end = index; match.attrs.push(attr); } if (end) { match.unarySlash = end[1]; advance(end[0].length); match.end = index; return match } } } function handleStartTag (match) { var tagName = match.tagName; var unarySlash = match.unarySlash; if (expectHTML) { if (lastTag === 'p' && isNonPhrasingTag(tagName)) { parseEndTag(lastTag); } if (canBeLeftOpenTag$$1(tagName) && lastTag === tagName) { parseEndTag(tagName); } } var unary = isUnaryTag$$1(tagName) || !!unarySlash; var l = match.attrs.length; var attrs = new Array(l); for (var i = 0; i < l; i++) { var args = match.attrs[i]; var value = args[3] || args[4] || args[5] || ''; var shouldDecodeNewlines = tagName === 'a' && args[1] === 'href' ? options.shouldDecodeNewlinesForHref : options.shouldDecodeNewlines; attrs[i] = { name: args[1], value: decodeAttr(value, shouldDecodeNewlines) }; if (options.outputSourceRange) { attrs[i].start = args.start + args[0].match(/^\s*/).length; attrs[i].end = args.end; } } if (!unary) { stack.push({ tag: tagName, lowerCasedTag: tagName.toLowerCase(), attrs: attrs, start: match.start, end: match.end }); lastTag = tagName; } if (options.start) { options.start(tagName, attrs, unary, match.start, match.end); } } function parseEndTag (tagName, start, end) { var pos, lowerCasedTagName; if (start == null) { start = index; } if (end == null) { end = index; } // Find the closest opened tag of the same type if (tagName) { lowerCasedTagName = tagName.toLowerCase(); for (pos = stack.length - 1; pos >= 0; pos--) { if (stack[pos].lowerCasedTag === lowerCasedTagName) { break } } } else { // If no tag name is provided, clean shop pos = 0; } if (pos >= 0) { // Close all the open elements, up the stack for (var i = stack.length - 1; i >= pos; i--) { if (i > pos || !tagName && options.warn ) { options.warn( ("tag <" + (stack[i].tag) + "> has no matching end tag."), { start: stack[i].start, end: stack[i].end } ); } if (options.end) { options.end(stack[i].tag, start, end); } } // Remove the open elements from the stack stack.length = pos; lastTag = pos && stack[pos - 1].tag; } else if (lowerCasedTagName === 'br') { if (options.start) { options.start(tagName, [], true, start, end); } } else if (lowerCasedTagName === 'p') { if (options.start) { options.start(tagName, [], false, start, end); } if (options.end) { options.end(tagName, start, end); } } } } /* */ var onRE = /^@|^v-on:/; var dirRE = /^v-|^@|^:/; var forAliasRE = /([\s\S]*?)\s+(?:in|of)\s+([\s\S]*)/; var forIteratorRE = /,([^,\}\]]*)(?:,([^,\}\]]*))?$/; var stripParensRE = /^\(|\)$/g; var dynamicArgRE = /^\[.*\]$/; var argRE = /:(.*)$/; var bindRE = /^:|^\.|^v-bind:/; var modifierRE = /\.[^.\]]+(?=[^\]]*$)/g; var slotRE = /^v-slot(:|$)|^#/; var lineBreakRE = /[\r\n]/; var whitespaceRE$1 = /\s+/g; var invalidAttributeRE = /[\s"'<>\/=]/; var decodeHTMLCached = cached(he.decode); var emptySlotScopeToken = "_empty_"; // configurable state var warn$2; var delimiters; var transforms; var preTransforms; var postTransforms; var platformIsPreTag; var platformMustUseProp; var platformGetTagNamespace; var maybeComponent; function createASTElement ( tag, attrs, parent ) { return { type: 1, tag: tag, attrsList: attrs, attrsMap: makeAttrsMap(attrs), rawAttrsMap: {}, parent: parent, children: [] } } /** * Convert HTML string to AST. */ function parse ( template, options ) { warn$2 = options.warn || baseWarn; platformIsPreTag = options.isPreTag || no; platformMustUseProp = options.mustUseProp || no; platformGetTagNamespace = options.getTagNamespace || no; var isReservedTag = options.isReservedTag || no; maybeComponent = function (el) { return !!el.component || !isReservedTag(el.tag); }; transforms = pluckModuleFunction(options.modules, 'transformNode'); preTransforms = pluckModuleFunction(options.modules, 'preTransformNode'); postTransforms = pluckModuleFunction(options.modules, 'postTransformNode'); delimiters = options.delimiters; var stack = []; var preserveWhitespace = options.preserveWhitespace !== false; var whitespaceOption = options.whitespace; var root; var currentParent; var inVPre = false; var inPre = false; var warned = false; function warnOnce (msg, range) { if (!warned) { warned = true; warn$2(msg, range); } } function closeElement (element) { trimEndingWhitespace(element); if (!inVPre && !element.processed) { element = processElement(element, options); } // tree management if (!stack.length && element !== root) { // allow root elements with v-if, v-else-if and v-else if (root.if && (element.elseif || element.else)) { { checkRootConstraints(element); } addIfCondition(root, { exp: element.elseif, block: element }); } else { warnOnce( "Component template should contain exactly one root element. " + "If you are using v-if on multiple elements, " + "use v-else-if to chain them instead.", { start: element.start } ); } } if (currentParent && !element.forbidden) { if (element.elseif || element.else) { processIfConditions(element, currentParent); } else { if (element.slotScope) { // scoped slot // keep it in the children list so that v-else(-if) conditions can // find it as the prev node. var name = element.slotTarget || '"default"' ;(currentParent.scopedSlots || (currentParent.scopedSlots = {}))[name] = element; } currentParent.children.push(element); element.parent = currentParent; } } // final children cleanup // filter out scoped slots element.children = element.children.filter(function (c) { return !(c).slotScope; }); // remove trailing whitespace node again trimEndingWhitespace(element); // check pre state if (element.pre) { inVPre = false; } if (platformIsPreTag(element.tag)) { inPre = false; } // apply post-transforms for (var i = 0; i < postTransforms.length; i++) { postTransforms[i](element, options); } } function trimEndingWhitespace (el) { // remove trailing whitespace node if (!inPre) { var lastNode; while ( (lastNode = el.children[el.children.length - 1]) && lastNode.type === 3 && lastNode.text === ' ' ) { el.children.pop(); } } } function checkRootConstraints (el) { if (el.tag === 'slot' || el.tag === 'template') { warnOnce( "Cannot use <" + (el.tag) + "> as component root element because it may " + 'contain multiple nodes.', { start: el.start } ); } if (el.attrsMap.hasOwnProperty('v-for')) { warnOnce( 'Cannot use v-for on stateful component root element because ' + 'it renders multiple elements.', el.rawAttrsMap['v-for'] ); } } parseHTML(template, { warn: warn$2, expectHTML: options.expectHTML, isUnaryTag: options.isUnaryTag, canBeLeftOpenTag: options.canBeLeftOpenTag, shouldDecodeNewlines: options.shouldDecodeNewlines, shouldDecodeNewlinesForHref: options.shouldDecodeNewlinesForHref, shouldKeepComment: options.comments, outputSourceRange: options.outputSourceRange, start: function start (tag, attrs, unary, start$1, end) { // check namespace. // inherit parent ns if there is one var ns = (currentParent && currentParent.ns) || platformGetTagNamespace(tag); // handle IE svg bug /* istanbul ignore if */ if (isIE && ns === 'svg') { attrs = guardIESVGBug(attrs); } var element = createASTElement(tag, attrs, currentParent); if (ns) { element.ns = ns; } { if (options.outputSourceRange) { element.start = start$1; element.end = end; element.rawAttrsMap = element.attrsList.reduce(function (cumulated, attr) { cumulated[attr.name] = attr; return cumulated }, {}); } attrs.forEach(function (attr) { if (invalidAttributeRE.test(attr.name)) { warn$2( "Invalid dynamic argument expression: attribute names cannot contain " + "spaces, quotes, <, >, / or =.", { start: attr.start + attr.name.indexOf("["), end: attr.start + attr.name.length } ); } }); } if (isForbiddenTag(element) && !isServerRendering()) { element.forbidden = true; warn$2( 'Templates should only be responsible for mapping the state to the ' + 'UI. Avoid placing tags with side-effects in your templates, such as ' + "<" + tag + ">" + ', as they will not be parsed.', { start: element.start } ); } // apply pre-transforms for (var i = 0; i < preTransforms.length; i++) { element = preTransforms[i](element, options) || element; } if (!inVPre) { processPre(element); if (element.pre) { inVPre = true; } } if (platformIsPreTag(element.tag)) { inPre = true; } if (inVPre) { processRawAttrs(element); } else if (!element.processed) { // structural directives processFor(element); processIf(element); processOnce(element); } if (!root) { root = element; { checkRootConstraints(root); } } if (!unary) { currentParent = element; stack.push(element); } else { closeElement(element); } }, end: function end (tag, start, end$1) { var element = stack[stack.length - 1]; // pop stack stack.length -= 1; currentParent = stack[stack.length - 1]; if (options.outputSourceRange) { element.end = end$1; } closeElement(element); }, chars: function chars (text, start, end) { if (!currentParent) { { if (text === template) { warnOnce( 'Component template requires a root element, rather than just text.', { start: start } ); } else if ((text = text.trim())) { warnOnce( ("text \"" + text + "\" outside root element will be ignored."), { start: start } ); } } return } // IE textarea placeholder bug /* istanbul ignore if */ if (isIE && currentParent.tag === 'textarea' && currentParent.attrsMap.placeholder === text ) { return } var children = currentParent.children; if (inPre || text.trim()) { text = isTextTag(currentParent) ? text : decodeHTMLCached(text); } else if (!children.length) { // remove the whitespace-only node right after an opening tag text = ''; } else if (whitespaceOption) { if (whitespaceOption === 'condense') { // in condense mode, remove the whitespace node if it contains // line break, otherwise condense to a single space text = lineBreakRE.test(text) ? '' : ' '; } else { text = ' '; } } else { text = preserveWhitespace ? ' ' : ''; } if (text) { if (!inPre && whitespaceOption === 'condense') { // condense consecutive whitespaces into single space text = text.replace(whitespaceRE$1, ' '); } var res; var child; if (!inVPre && text !== ' ' && (res = parseText(text, delimiters))) { child = { type: 2, expression: res.expression, tokens: res.tokens, text: text }; } else if (text !== ' ' || !children.length || children[children.length - 1].text !== ' ') { child = { type: 3, text: text }; } if (child) { if (options.outputSourceRange) { child.start = start; child.end = end; } children.push(child); } } }, comment: function comment (text, start, end) { // adding anyting as a sibling to the root node is forbidden // comments should still be allowed, but ignored if (currentParent) { var child = { type: 3, text: text, isComment: true }; if (options.outputSourceRange) { child.start = start; child.end = end; } currentParent.children.push(child); } } }); return root } function processPre (el) { if (getAndRemoveAttr(el, 'v-pre') != null) { el.pre = true; } } function processRawAttrs (el) { var list = el.attrsList; var len = list.length; if (len) { var attrs = el.attrs = new Array(len); for (var i = 0; i < len; i++) { attrs[i] = { name: list[i].name, value: JSON.stringify(list[i].value) }; if (list[i].start != null) { attrs[i].start = list[i].start; attrs[i].end = list[i].end; } } } else if (!el.pre) { // non root node in pre blocks with no attributes el.plain = true; } } function processElement ( element, options ) { processKey(element); // determine whether this is a plain element after // removing structural attributes element.plain = ( !element.key && !element.scopedSlots && !element.attrsList.length ); processRef(element); processSlotContent(element); processSlotOutlet(element); processComponent(element); for (var i = 0; i < transforms.length; i++) { element = transforms[i](element, options) || element; } processAttrs(element); return element } function processKey (el) { var exp = getBindingAttr(el, 'key'); if (exp) { { if (el.tag === 'template') { warn$2( "<template> cannot be keyed. Place the key on real elements instead.", getRawBindingAttr(el, 'key') ); } if (el.for) { var iterator = el.iterator2 || el.iterator1; var parent = el.parent; if (iterator && iterator === exp && parent && parent.tag === 'transition-group') { warn$2( "Do not use v-for index as key on <transition-group> children, " + "this is the same as not using keys.", getRawBindingAttr(el, 'key'), true /* tip */ ); } } } el.key = exp; } } function processRef (el) { var ref = getBindingAttr(el, 'ref'); if (ref) { el.ref = ref; el.refInFor = checkInFor(el); } } function processFor (el) { var exp; if ((exp = getAndRemoveAttr(el, 'v-for'))) { var res = parseFor(exp); if (res) { extend(el, res); } else { warn$2( ("Invalid v-for expression: " + exp), el.rawAttrsMap['v-for'] ); } } } function parseFor (exp) { var inMatch = exp.match(forAliasRE); if (!inMatch) { return } var res = {}; res.for = inMatch[2].trim(); var alias = inMatch[1].trim().replace(stripParensRE, ''); var iteratorMatch = alias.match(forIteratorRE); if (iteratorMatch) { res.alias = alias.replace(forIteratorRE, '').trim(); res.iterator1 = iteratorMatch[1].trim(); if (iteratorMatch[2]) { res.iterator2 = iteratorMatch[2].trim(); } } else { res.alias = alias; } return res } function processIf (el) { var exp = getAndRemoveAttr(el, 'v-if'); if (exp) { el.if = exp; addIfCondition(el, { exp: exp, block: el }); } else { if (getAndRemoveAttr(el, 'v-else') != null) { el.else = true; } var elseif = getAndRemoveAttr(el, 'v-else-if'); if (elseif) { el.elseif = elseif; } } } function processIfConditions (el, parent) { var prev = findPrevElement(parent.children); if (prev && prev.if) { addIfCondition(prev, { exp: el.elseif, block: el }); } else { warn$2( "v-" + (el.elseif ? ('else-if="' + el.elseif + '"') : 'else') + " " + "used on element <" + (el.tag) + "> without corresponding v-if.", el.rawAttrsMap[el.elseif ? 'v-else-if' : 'v-else'] ); } } function findPrevElement (children) { var i = children.length; while (i--) { if (children[i].type === 1) { return children[i] } else { if (children[i].text !== ' ') { warn$2( "text \"" + (children[i].text.trim()) + "\" between v-if and v-else(-if) " + "will be ignored.", children[i] ); } children.pop(); } } } function addIfCondition (el, condition) { if (!el.ifConditions) { el.ifConditions = []; } el.ifConditions.push(condition); } function processOnce (el) { var once$$1 = getAndRemoveAttr(el, 'v-once'); if (once$$1 != null) { el.once = true; } } // handle content being passed to a component as slot, // e.g. <template slot="xxx">, <div slot-scope="xxx"> function processSlotContent (el) { var slotScope; if (el.tag === 'template') { slotScope = getAndRemoveAttr(el, 'scope'); /* istanbul ignore if */ if (slotScope) { warn$2( "the \"scope\" attribute for scoped slots have been deprecated and " + "replaced by \"slot-scope\" since 2.5. The new \"slot-scope\" attribute " + "can also be used on plain elements in addition to <template> to " + "denote scoped slots.", el.rawAttrsMap['scope'], true ); } el.slotScope = slotScope || getAndRemoveAttr(el, 'slot-scope'); } else if ((slotScope = getAndRemoveAttr(el, 'slot-scope'))) { /* istanbul ignore if */ if (el.attrsMap['v-for']) { warn$2( "Ambiguous combined usage of slot-scope and v-for on <" + (el.tag) + "> " + "(v-for takes higher priority). Use a wrapper <template> for the " + "scoped slot to make it clearer.", el.rawAttrsMap['slot-scope'], true ); } el.slotScope = slotScope; } // slot="xxx" var slotTarget = getBindingAttr(el, 'slot'); if (slotTarget) { el.slotTarget = slotTarget === '""' ? '"default"' : slotTarget; el.slotTargetDynamic = !!(el.attrsMap[':slot'] || el.attrsMap['v-bind:slot']); // preserve slot as an attribute for native shadow DOM compat // only for non-scoped slots. if (el.tag !== 'template' && !el.slotScope) { addAttr(el, 'slot', slotTarget, getRawBindingAttr(el, 'slot')); } } // 2.6 v-slot syntax { if (el.tag === 'template') { // v-slot on <template> var slotBinding = getAndRemoveAttrByRegex(el, slotRE); if (slotBinding) { { if (el.slotTarget || el.slotScope) { warn$2( "Unexpected mixed usage of different slot syntaxes.", el ); } if (el.parent && !maybeComponent(el.parent)) { warn$2( "<template v-slot> can only appear at the root level inside " + "the receiving the component", el ); } } var ref = getSlotName(slotBinding); var name = ref.name; var dynamic = ref.dynamic; el.slotTarget = name; el.slotTargetDynamic = dynamic; el.slotScope = slotBinding.value || emptySlotScopeToken; // force it into a scoped slot for perf } } else { // v-slot on component, denotes default slot var slotBinding$1 = getAndRemoveAttrByRegex(el, slotRE); if (slotBinding$1) { { if (!maybeComponent(el)) { warn$2( "v-slot can only be used on components or <template>.", slotBinding$1 ); } if (el.slotScope || el.slotTarget) { warn$2( "Unexpected mixed usage of different slot syntaxes.", el ); } if (el.scopedSlots) { warn$2( "To avoid scope ambiguity, the default slot should also use " + "<template> syntax when there are other named slots.", slotBinding$1 ); } } // add the component's children to its default slot var slots = el.scopedSlots || (el.scopedSlots = {}); var ref$1 = getSlotName(slotBinding$1); var name$1 = ref$1.name; var dynamic$1 = ref$1.dynamic; var slotContainer = slots[name$1] = createASTElement('template', [], el); slotContainer.slotTarget = name$1; slotContainer.slotTargetDynamic = dynamic$1; slotContainer.children = el.children.filter(function (c) { if (!c.slotScope) { c.parent = slotContainer; return true } }); slotContainer.slotScope = slotBinding$1.value || emptySlotScopeToken; // remove children as they are returned from scopedSlots now el.children = []; // mark el non-plain so data gets generated el.plain = false; } } } } function getSlotName (binding) { var name = binding.name.replace(slotRE, ''); if (!name) { if (binding.name[0] !== '#') { name = 'default'; } else { warn$2( "v-slot shorthand syntax requires a slot name.", binding ); } } return dynamicArgRE.test(name) // dynamic [name] ? { name: name.slice(1, -1), dynamic: true } // static name : { name: ("\"" + name + "\""), dynamic: false } } // handle <slot/> outlets function processSlotOutlet (el) { if (el.tag === 'slot') { el.slotName = getBindingAttr(el, 'name'); if (el.key) { warn$2( "`key` does not work on <slot> because slots are abstract outlets " + "and can possibly expand into multiple elements. " + "Use the key on a wrapping element instead.", getRawBindingAttr(el, 'key') ); } } } function processComponent (el) { var binding; if ((binding = getBindingAttr(el, 'is'))) { el.component = binding; } if (getAndRemoveAttr(el, 'inline-template') != null) { el.inlineTemplate = true; } } function processAttrs (el) { var list = el.attrsList; var i, l, name, rawName, value, modifiers, syncGen, isDynamic; for (i = 0, l = list.length; i < l; i++) { name = rawName = list[i].name; value = list[i].value; if (dirRE.test(name)) { // mark element as dynamic el.hasBindings = true; // modifiers modifiers = parseModifiers(name.replace(dirRE, '')); // support .foo shorthand syntax for the .prop modifier if (modifiers) { name = name.replace(modifierRE, ''); } if (bindRE.test(name)) { // v-bind name = name.replace(bindRE, ''); value = parseFilters(value); isDynamic = dynamicArgRE.test(name); if (isDynamic) { name = name.slice(1, -1); } if ( value.trim().length === 0 ) { warn$2( ("The value for a v-bind expression cannot be empty. Found in \"v-bind:" + name + "\"") ); } if (modifiers) { if (modifiers.prop && !isDynamic) { name = camelize(name); if (name === 'innerHtml') { name = 'innerHTML'; } } if (modifiers.camel && !isDynamic) { name = camelize(name); } if (modifiers.sync) { syncGen = genAssignmentCode(value, "$event"); if (!isDynamic) { addHandler( el, ("update:" + (camelize(name))), syncGen, null, false, warn$2, list[i] ); if (hyphenate(name) !== camelize(name)) { addHandler( el, ("update:" + (hyphenate(name))), syncGen, null, false, warn$2, list[i] ); } } else { // handler w/ dynamic event name addHandler( el, ("\"update:\"+(" + name + ")"), syncGen, null, false, warn$2, list[i], true // dynamic ); } } } if ((modifiers && modifiers.prop) || ( !el.component && platformMustUseProp(el.tag, el.attrsMap.type, name) )) { addProp(el, name, value, list[i], isDynamic); } else { addAttr(el, name, value, list[i], isDynamic); } } else if (onRE.test(name)) { // v-on name = name.replace(onRE, ''); isDynamic = dynamicArgRE.test(name); if (isDynamic) { name = name.slice(1, -1); } addHandler(el, name, value, modifiers, false, warn$2, list[i], isDynamic); } else { // normal directives name = name.replace(dirRE, ''); // parse arg var argMatch = name.match(argRE); var arg = argMatch && argMatch[1]; isDynamic = false; if (arg) { name = name.slice(0, -(arg.length + 1)); if (dynamicArgRE.test(arg)) { arg = arg.slice(1, -1); isDynamic = true; } } addDirective(el, name, rawName, value, arg, isDynamic, modifiers, list[i]); if (name === 'model') { checkForAliasModel(el, value); } } } else { // literal attribute { var res = parseText(value, delimiters); if (res) { warn$2( name + "=\"" + value + "\": " + 'Interpolation inside attributes has been removed. ' + 'Use v-bind or the colon shorthand instead. For example, ' + 'instead of <div id="{{ val }}">, use <div :id="val">.', list[i] ); } } addAttr(el, name, JSON.stringify(value), list[i]); // #6887 firefox doesn't update muted state if set via attribute // even immediately after element creation if (!el.component && name === 'muted' && platformMustUseProp(el.tag, el.attrsMap.type, name)) { addProp(el, name, 'true', list[i]); } } } } function checkInFor (el) { var parent = el; while (parent) { if (parent.for !== undefined) { return true } parent = parent.parent; } return false } function parseModifiers (name) { var match = name.match(modifierRE); if (match) { var ret = {}; match.forEach(function (m) { ret[m.slice(1)] = true; }); return ret } } function makeAttrsMap (attrs) { var map = {}; for (var i = 0, l = attrs.length; i < l; i++) { if ( map[attrs[i].name] && !isIE && !isEdge ) { warn$2('duplicate attribute: ' + attrs[i].name, attrs[i]); } map[attrs[i].name] = attrs[i].value; } return map } // for script (e.g. type="x/template") or style, do not decode content function isTextTag (el) { return el.tag === 'script' || el.tag === 'style' } function isForbiddenTag (el) { return ( el.tag === 'style' || (el.tag === 'script' && ( !el.attrsMap.type || el.attrsMap.type === 'text/javascript' )) ) } var ieNSBug = /^xmlns:NS\d+/; var ieNSPrefix = /^NS\d+:/; /* istanbul ignore next */ function guardIESVGBug (attrs) { var res = []; for (var i = 0; i < attrs.length; i++) { var attr = attrs[i]; if (!ieNSBug.test(attr.name)) { attr.name = attr.name.replace(ieNSPrefix, ''); res.push(attr); } } return res } function checkForAliasModel (el, value) { var _el = el; while (_el) { if (_el.for && _el.alias === value) { warn$2( "<" + (el.tag) + " v-model=\"" + value + "\">: " + "You are binding v-model directly to a v-for iteration alias. " + "This will not be able to modify the v-for source array because " + "writing to the alias is like modifying a function local variable. " + "Consider using an array of objects and use v-model on an object property instead.", el.rawAttrsMap['v-model'] ); } _el = _el.parent; } } /* */ function preTransformNode (el, options) { if (el.tag === 'input') { var map = el.attrsMap; if (!map['v-model']) { return } var typeBinding; if (map[':type'] || map['v-bind:type']) { typeBinding = getBindingAttr(el, 'type'); } if (!map.type && !typeBinding && map['v-bind']) { typeBinding = "(" + (map['v-bind']) + ").type"; } if (typeBinding) { var ifCondition = getAndRemoveAttr(el, 'v-if', true); var ifConditionExtra = ifCondition ? ("&&(" + ifCondition + ")") : ""; var hasElse = getAndRemoveAttr(el, 'v-else', true) != null; var elseIfCondition = getAndRemoveAttr(el, 'v-else-if', true); // 1. checkbox var branch0 = cloneASTElement(el); // process for on the main node processFor(branch0); addRawAttr(branch0, 'type', 'checkbox'); processElement(branch0, options); branch0.processed = true; // prevent it from double-processed branch0.if = "(" + typeBinding + ")==='checkbox'" + ifConditionExtra; addIfCondition(branch0, { exp: branch0.if, block: branch0 }); // 2. add radio else-if condition var branch1 = cloneASTElement(el); getAndRemoveAttr(branch1, 'v-for', true); addRawAttr(branch1, 'type', 'radio'); processElement(branch1, options); addIfCondition(branch0, { exp: "(" + typeBinding + ")==='radio'" + ifConditionExtra, block: branch1 }); // 3. other var branch2 = cloneASTElement(el); getAndRemoveAttr(branch2, 'v-for', true); addRawAttr(branch2, ':type', typeBinding); processElement(branch2, options); addIfCondition(branch0, { exp: ifCondition, block: branch2 }); if (hasElse) { branch0.else = true; } else if (elseIfCondition) { branch0.elseif = elseIfCondition; } return branch0 } } } function cloneASTElement (el) { return createASTElement(el.tag, el.attrsList.slice(), el.parent) } var model$1 = { preTransformNode: preTransformNode }; var modules$1 = [ klass$1, style$1, model$1 ]; /* */ function text (el, dir) { if (dir.value) { addProp(el, 'textContent', ("_s(" + (dir.value) + ")"), dir); } } /* */ function html (el, dir) { if (dir.value) { addProp(el, 'innerHTML', ("_s(" + (dir.value) + ")"), dir); } } var directives$1 = { model: model, text: text, html: html }; /* */ var baseOptions = { expectHTML: true, modules: modules$1, directives: directives$1, isPreTag: isPreTag, isUnaryTag: isUnaryTag, mustUseProp: mustUseProp, canBeLeftOpenTag: canBeLeftOpenTag, isReservedTag: isReservedTag, getTagNamespace: getTagNamespace, staticKeys: genStaticKeys(modules$1) }; /* */ var isStaticKey; var isPlatformReservedTag; var genStaticKeysCached = cached(genStaticKeys$1); /** * Goal of the optimizer: walk the generated template AST tree * and detect sub-trees that are purely static, i.e. parts of * the DOM that never needs to change. * * Once we detect these sub-trees, we can: * * 1. Hoist them into constants, so that we no longer need to * create fresh nodes for them on each re-render; * 2. Completely skip them in the patching process. */ function optimize (root, options) { if (!root) { return } isStaticKey = genStaticKeysCached(options.staticKeys || ''); isPlatformReservedTag = options.isReservedTag || no; // first pass: mark all non-static nodes. markStatic$1(root); // second pass: mark static roots. markStaticRoots(root, false); } function genStaticKeys$1 (keys) { return makeMap( 'type,tag,attrsList,attrsMap,plain,parent,children,attrs,start,end,rawAttrsMap' + (keys ? ',' + keys : '') ) } function markStatic$1 (node) { node.static = isStatic(node); if (node.type === 1) { // do not make component slot content static. this avoids // 1. components not able to mutate slot nodes // 2. static slot content fails for hot-reloading if ( !isPlatformReservedTag(node.tag) && node.tag !== 'slot' && node.attrsMap['inline-template'] == null ) { return } for (var i = 0, l = node.children.length; i < l; i++) { var child = node.children[i]; markStatic$1(child); if (!child.static) { node.static = false; } } if (node.ifConditions) { for (var i$1 = 1, l$1 = node.ifConditions.length; i$1 < l$1; i$1++) { var block = node.ifConditions[i$1].block; markStatic$1(block); if (!block.static) { node.static = false; } } } } } function markStaticRoots (node, isInFor) { if (node.type === 1) { if (node.static || node.once) { node.staticInFor = isInFor; } // For a node to qualify as a static root, it should have children that // are not just static text. Otherwise the cost of hoisting out will // outweigh the benefits and it's better off to just always render it fresh. if (node.static && node.children.length && !( node.children.length === 1 && node.children[0].type === 3 )) { node.staticRoot = true; return } else { node.staticRoot = false; } if (node.children) { for (var i = 0, l = node.children.length; i < l; i++) { markStaticRoots(node.children[i], isInFor || !!node.for); } } if (node.ifConditions) { for (var i$1 = 1, l$1 = node.ifConditions.length; i$1 < l$1; i$1++) { markStaticRoots(node.ifConditions[i$1].block, isInFor); } } } } function isStatic (node) { if (node.type === 2) { // expression return false } if (node.type === 3) { // text return true } return !!(node.pre || ( !node.hasBindings && // no dynamic bindings !node.if && !node.for && // not v-if or v-for or v-else !isBuiltInTag(node.tag) && // not a built-in isPlatformReservedTag(node.tag) && // not a component !isDirectChildOfTemplateFor(node) && Object.keys(node).every(isStaticKey) )) } function isDirectChildOfTemplateFor (node) { while (node.parent) { node = node.parent; if (node.tag !== 'template') { return false } if (node.for) { return true } } return false } /* */ var fnExpRE = /^([\w$_]+|\([^)]*?\))\s*=>|^function\s*(?:[\w$]+)?\s*\(/; var fnInvokeRE = /\([^)]*?\);*$/; var simplePathRE = /^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\['[^']*?']|\["[^"]*?"]|\[\d+]|\[[A-Za-z_$][\w$]*])*$/; // KeyboardEvent.keyCode aliases var keyCodes = { esc: 27, tab: 9, enter: 13, space: 32, up: 38, left: 37, right: 39, down: 40, 'delete': [8, 46] }; // KeyboardEvent.key aliases var keyNames = { // #7880: IE11 and Edge use `Esc` for Escape key name. esc: ['Esc', 'Escape'], tab: 'Tab', enter: 'Enter', // #9112: IE11 uses `Spacebar` for Space key name. space: [' ', 'Spacebar'], // #7806: IE11 uses key names without `Arrow` prefix for arrow keys. up: ['Up', 'ArrowUp'], left: ['Left', 'ArrowLeft'], right: ['Right', 'ArrowRight'], down: ['Down', 'ArrowDown'], // #9112: IE11 uses `Del` for Delete key name. 'delete': ['Backspace', 'Delete', 'Del'] }; // #4868: modifiers that prevent the execution of the listener // need to explicitly return null so that we can determine whether to remove // the listener for .once var genGuard = function (condition) { return ("if(" + condition + ")return null;"); }; var modifierCode = { stop: '$event.stopPropagation();', prevent: '$event.preventDefault();', self: genGuard("$event.target !== $event.currentTarget"), ctrl: genGuard("!$event.ctrlKey"), shift: genGuard("!$event.shiftKey"), alt: genGuard("!$event.altKey"), meta: genGuard("!$event.metaKey"), left: genGuard("'button' in $event && $event.button !== 0"), middle: genGuard("'button' in $event && $event.button !== 1"), right: genGuard("'button' in $event && $event.button !== 2") }; function genHandlers ( events, isNative ) { var prefix = isNative ? 'nativeOn:' : 'on:'; var staticHandlers = ""; var dynamicHandlers = ""; for (var name in events) { var handlerCode = genHandler(events[name]); if (events[name] && events[name].dynamic) { dynamicHandlers += name + "," + handlerCode + ","; } else { staticHandlers += "\"" + name + "\":" + handlerCode + ","; } } staticHandlers = "{" + (staticHandlers.slice(0, -1)) + "}"; if (dynamicHandlers) { return prefix + "_d(" + staticHandlers + ",[" + (dynamicHandlers.slice(0, -1)) + "])" } else { return prefix + staticHandlers } } function genHandler (handler) { if (!handler) { return 'function(){}' } if (Array.isArray(handler)) { return ("[" + (handler.map(function (handler) { return genHandler(handler); }).join(',')) + "]") } var isMethodPath = simplePathRE.test(handler.value); var isFunctionExpression = fnExpRE.test(handler.value); var isFunctionInvocation = simplePathRE.test(handler.value.replace(fnInvokeRE, '')); if (!handler.modifiers) { if (isMethodPath || isFunctionExpression) { return handler.value } return ("function($event){" + (isFunctionInvocation ? ("return " + (handler.value)) : handler.value) + "}") // inline statement } else { var code = ''; var genModifierCode = ''; var keys = []; for (var key in handler.modifiers) { if (modifierCode[key]) { genModifierCode += modifierCode[key]; // left/right if (keyCodes[key]) { keys.push(key); } } else if (key === 'exact') { var modifiers = (handler.modifiers); genModifierCode += genGuard( ['ctrl', 'shift', 'alt', 'meta'] .filter(function (keyModifier) { return !modifiers[keyModifier]; }) .map(function (keyModifier) { return ("$event." + keyModifier + "Key"); }) .join('||') ); } else { keys.push(key); } } if (keys.length) { code += genKeyFilter(keys); } // Make sure modifiers like prevent and stop get executed after key filtering if (genModifierCode) { code += genModifierCode; } var handlerCode = isMethodPath ? ("return " + (handler.value) + "($event)") : isFunctionExpression ? ("return (" + (handler.value) + ")($event)") : isFunctionInvocation ? ("return " + (handler.value)) : handler.value; return ("function($event){" + code + handlerCode + "}") } } function genKeyFilter (keys) { return ( // make sure the key filters only apply to KeyboardEvents // #9441: can't use 'keyCode' in $event because Chrome autofill fires fake // key events that do not have keyCode property... "if(!$event.type.indexOf('key')&&" + (keys.map(genFilterCode).join('&&')) + ")return null;" ) } function genFilterCode (key) { var keyVal = parseInt(key, 10); if (keyVal) { return ("$event.keyCode!==" + keyVal) } var keyCode = keyCodes[key]; var keyName = keyNames[key]; return ( "_k($event.keyCode," + (JSON.stringify(key)) + "," + (JSON.stringify(keyCode)) + "," + "$event.key," + "" + (JSON.stringify(keyName)) + ")" ) } /* */ function on (el, dir) { if (dir.modifiers) { warn("v-on without argument does not support modifiers."); } el.wrapListeners = function (code) { return ("_g(" + code + "," + (dir.value) + ")"); }; } /* */ function bind$1 (el, dir) { el.wrapData = function (code) { return ("_b(" + code + ",'" + (el.tag) + "'," + (dir.value) + "," + (dir.modifiers && dir.modifiers.prop ? 'true' : 'false') + (dir.modifiers && dir.modifiers.sync ? ',true' : '') + ")") }; } /* */ var baseDirectives = { on: on, bind: bind$1, cloak: noop }; /* */ var CodegenState = function CodegenState (options) { this.options = options; this.warn = options.warn || baseWarn; this.transforms = pluckModuleFunction(options.modules, 'transformCode'); this.dataGenFns = pluckModuleFunction(options.modules, 'genData'); this.directives = extend(extend({}, baseDirectives), options.directives); var isReservedTag = options.isReservedTag || no; this.maybeComponent = function (el) { return !!el.component || !isReservedTag(el.tag); }; this.onceId = 0; this.staticRenderFns = []; this.pre = false; }; function generate ( ast, options ) { var state = new CodegenState(options); var code = ast ? genElement(ast, state) : '_c("div")'; return { render: ("with(this){return " + code + "}"), staticRenderFns: state.staticRenderFns } } function genElement (el, state) { if (el.parent) { el.pre = el.pre || el.parent.pre; } if (el.staticRoot && !el.staticProcessed) { return genStatic(el, state) } else if (el.once && !el.onceProcessed) { return genOnce(el, state) } else if (el.for && !el.forProcessed) { return genFor(el, state) } else if (el.if && !el.ifProcessed) { return genIf(el, state) } else if (el.tag === 'template' && !el.slotTarget && !state.pre) { return genChildren(el, state) || 'void 0' } else if (el.tag === 'slot') { return genSlot(el, state) } else { // component or element var code; if (el.component) { code = genComponent(el.component, el, state); } else { var data; if (!el.plain || (el.pre && state.maybeComponent(el))) { data = genData$2(el, state); } var children = el.inlineTemplate ? null : genChildren(el, state, true); code = "_c('" + (el.tag) + "'" + (data ? ("," + data) : '') + (children ? ("," + children) : '') + ")"; } // module transforms for (var i = 0; i < state.transforms.length; i++) { code = state.transforms[i](el, code); } return code } } // hoist static sub-trees out function genStatic (el, state) { el.staticProcessed = true; // Some elements (templates) need to behave differently inside of a v-pre // node. All pre nodes are static roots, so we can use this as a location to // wrap a state change and reset it upon exiting the pre node. var originalPreState = state.pre; if (el.pre) { state.pre = el.pre; } state.staticRenderFns.push(("with(this){return " + (genElement(el, state)) + "}")); state.pre = originalPreState; return ("_m(" + (state.staticRenderFns.length - 1) + (el.staticInFor ? ',true' : '') + ")") } // v-once function genOnce (el, state) { el.onceProcessed = true; if (el.if && !el.ifProcessed) { return genIf(el, state) } else if (el.staticInFor) { var key = ''; var parent = el.parent; while (parent) { if (parent.for) { key = parent.key; break } parent = parent.parent; } if (!key) { state.warn( "v-once can only be used inside v-for that is keyed. ", el.rawAttrsMap['v-once'] ); return genElement(el, state) } return ("_o(" + (genElement(el, state)) + "," + (state.onceId++) + "," + key + ")") } else { return genStatic(el, state) } } function genIf ( el, state, altGen, altEmpty ) { el.ifProcessed = true; // avoid recursion return genIfConditions(el.ifConditions.slice(), state, altGen, altEmpty) } function genIfConditions ( conditions, state, altGen, altEmpty ) { if (!conditions.length) { return altEmpty || '_e()' } var condition = conditions.shift(); if (condition.exp) { return ("(" + (condition.exp) + ")?" + (genTernaryExp(condition.block)) + ":" + (genIfConditions(conditions, state, altGen, altEmpty))) } else { return ("" + (genTernaryExp(condition.block))) } // v-if with v-once should generate code like (a)?_m(0):_m(1) function genTernaryExp (el) { return altGen ? altGen(el, state) : el.once ? genOnce(el, state) : genElement(el, state) } } function genFor ( el, state, altGen, altHelper ) { var exp = el.for; var alias = el.alias; var iterator1 = el.iterator1 ? ("," + (el.iterator1)) : ''; var iterator2 = el.iterator2 ? ("," + (el.iterator2)) : ''; if (state.maybeComponent(el) && el.tag !== 'slot' && el.tag !== 'template' && !el.key ) { state.warn( "<" + (el.tag) + " v-for=\"" + alias + " in " + exp + "\">: component lists rendered with " + "v-for should have explicit keys. " + "See https://vuejs.org/guide/list.html#key for more info.", el.rawAttrsMap['v-for'], true /* tip */ ); } el.forProcessed = true; // avoid recursion return (altHelper || '_l') + "((" + exp + ")," + "function(" + alias + iterator1 + iterator2 + "){" + "return " + ((altGen || genElement)(el, state)) + '})' } function genData$2 (el, state) { var data = '{'; // directives first. // directives may mutate the el's other properties before they are generated. var dirs = genDirectives(el, state); if (dirs) { data += dirs + ','; } // key if (el.key) { data += "key:" + (el.key) + ","; } // ref if (el.ref) { data += "ref:" + (el.ref) + ","; } if (el.refInFor) { data += "refInFor:true,"; } // pre if (el.pre) { data += "pre:true,"; } // record original tag name for components using "is" attribute if (el.component) { data += "tag:\"" + (el.tag) + "\","; } // module data generation functions for (var i = 0; i < state.dataGenFns.length; i++) { data += state.dataGenFns[i](el); } // attributes if (el.attrs) { data += "attrs:" + (genProps(el.attrs)) + ","; } // DOM props if (el.props) { data += "domProps:" + (genProps(el.props)) + ","; } // event handlers if (el.events) { data += (genHandlers(el.events, false)) + ","; } if (el.nativeEvents) { data += (genHandlers(el.nativeEvents, true)) + ","; } // slot target // only for non-scoped slots if (el.slotTarget && !el.slotScope) { data += "slot:" + (el.slotTarget) + ","; } // scoped slots if (el.scopedSlots) { data += (genScopedSlots(el, el.scopedSlots, state)) + ","; } // component v-model if (el.model) { data += "model:{value:" + (el.model.value) + ",callback:" + (el.model.callback) + ",expression:" + (el.model.expression) + "},"; } // inline-template if (el.inlineTemplate) { var inlineTemplate = genInlineTemplate(el, state); if (inlineTemplate) { data += inlineTemplate + ","; } } data = data.replace(/,$/, '') + '}'; // v-bind dynamic argument wrap // v-bind with dynamic arguments must be applied using the same v-bind object // merge helper so that class/style/mustUseProp attrs are handled correctly. if (el.dynamicAttrs) { data = "_b(" + data + ",\"" + (el.tag) + "\"," + (genProps(el.dynamicAttrs)) + ")"; } // v-bind data wrap if (el.wrapData) { data = el.wrapData(data); } // v-on data wrap if (el.wrapListeners) { data = el.wrapListeners(data); } return data } function genDirectives (el, state) { var dirs = el.directives; if (!dirs) { return } var res = 'directives:['; var hasRuntime = false; var i, l, dir, needRuntime; for (i = 0, l = dirs.length; i < l; i++) { dir = dirs[i]; needRuntime = true; var gen = state.directives[dir.name]; if (gen) { // compile-time directive that manipulates AST. // returns true if it also needs a runtime counterpart. needRuntime = !!gen(el, dir, state.warn); } if (needRuntime) { hasRuntime = true; res += "{name:\"" + (dir.name) + "\",rawName:\"" + (dir.rawName) + "\"" + (dir.value ? (",value:(" + (dir.value) + "),expression:" + (JSON.stringify(dir.value))) : '') + (dir.arg ? (",arg:" + (dir.isDynamicArg ? dir.arg : ("\"" + (dir.arg) + "\""))) : '') + (dir.modifiers ? (",modifiers:" + (JSON.stringify(dir.modifiers))) : '') + "},"; } } if (hasRuntime) { return res.slice(0, -1) + ']' } } function genInlineTemplate (el, state) { var ast = el.children[0]; if (el.children.length !== 1 || ast.type !== 1) { state.warn( 'Inline-template components must have exactly one child element.', { start: el.start } ); } if (ast && ast.type === 1) { var inlineRenderFns = generate(ast, state.options); return ("inlineTemplate:{render:function(){" + (inlineRenderFns.render) + "},staticRenderFns:[" + (inlineRenderFns.staticRenderFns.map(function (code) { return ("function(){" + code + "}"); }).join(',')) + "]}") } } function genScopedSlots ( el, slots, state ) { // by default scoped slots are considered "stable", this allows child // components with only scoped slots to skip forced updates from parent. // but in some cases we have to bail-out of this optimization // for example if the slot contains dynamic names, has v-if or v-for on them... var needsForceUpdate = el.for || Object.keys(slots).some(function (key) { var slot = slots[key]; return ( slot.slotTargetDynamic || slot.if || slot.for || containsSlotChild(slot) // is passing down slot from parent which may be dynamic ) }); // #9534: if a component with scoped slots is inside a conditional branch, // it's possible for the same component to be reused but with different // compiled slot content. To avoid that, we generate a unique key based on // the generated code of all the slot contents. var needsKey = !!el.if; // OR when it is inside another scoped slot or v-for (the reactivity may be // disconnected due to the intermediate scope variable) // #9438, #9506 // TODO: this can be further optimized by properly analyzing in-scope bindings // and skip force updating ones that do not actually use scope variables. if (!needsForceUpdate) { var parent = el.parent; while (parent) { if ( (parent.slotScope && parent.slotScope !== emptySlotScopeToken) || parent.for ) { needsForceUpdate = true; break } if (parent.if) { needsKey = true; } parent = parent.parent; } } var generatedSlots = Object.keys(slots) .map(function (key) { return genScopedSlot(slots[key], state); }) .join(','); return ("scopedSlots:_u([" + generatedSlots + "]" + (needsForceUpdate ? ",null,true" : "") + (!needsForceUpdate && needsKey ? (",null,false," + (hash(generatedSlots))) : "") + ")") } function hash(str) { var hash = 5381; var i = str.length; while(i) { hash = (hash * 33) ^ str.charCodeAt(--i); } return hash >>> 0 } function containsSlotChild (el) { if (el.type === 1) { if (el.tag === 'slot') { return true } return el.children.some(containsSlotChild) } return false } function genScopedSlot ( el, state ) { var isLegacySyntax = el.attrsMap['slot-scope']; if (el.if && !el.ifProcessed && !isLegacySyntax) { return genIf(el, state, genScopedSlot, "null") } if (el.for && !el.forProcessed) { return genFor(el, state, genScopedSlot) } var slotScope = el.slotScope === emptySlotScopeToken ? "" : String(el.slotScope); var fn = "function(" + slotScope + "){" + "return " + (el.tag === 'template' ? el.if && isLegacySyntax ? ("(" + (el.if) + ")?" + (genChildren(el, state) || 'undefined') + ":undefined") : genChildren(el, state) || 'undefined' : genElement(el, state)) + "}"; // reverse proxy v-slot without scope on this.$slots var reverseProxy = slotScope ? "" : ",proxy:true"; return ("{key:" + (el.slotTarget || "\"default\"") + ",fn:" + fn + reverseProxy + "}") } function genChildren ( el, state, checkSkip, altGenElement, altGenNode ) { var children = el.children; if (children.length) { var el$1 = children[0]; // optimize single v-for if (children.length === 1 && el$1.for && el$1.tag !== 'template' && el$1.tag !== 'slot' ) { var normalizationType = checkSkip ? state.maybeComponent(el$1) ? ",1" : ",0" : ""; return ("" + ((altGenElement || genElement)(el$1, state)) + normalizationType) } var normalizationType$1 = checkSkip ? getNormalizationType(children, state.maybeComponent) : 0; var gen = altGenNode || genNode; return ("[" + (children.map(function (c) { return gen(c, state); }).join(',')) + "]" + (normalizationType$1 ? ("," + normalizationType$1) : '')) } } // determine the normalization needed for the children array. // 0: no normalization needed // 1: simple normalization needed (possible 1-level deep nested array) // 2: full normalization needed function getNormalizationType ( children, maybeComponent ) { var res = 0; for (var i = 0; i < children.length; i++) { var el = children[i]; if (el.type !== 1) { continue } if (needsNormalization(el) || (el.ifConditions && el.ifConditions.some(function (c) { return needsNormalization(c.block); }))) { res = 2; break } if (maybeComponent(el) || (el.ifConditions && el.ifConditions.some(function (c) { return maybeComponent(c.block); }))) { res = 1; } } return res } function needsNormalization (el) { return el.for !== undefined || el.tag === 'template' || el.tag === 'slot' } function genNode (node, state) { if (node.type === 1) { return genElement(node, state) } else if (node.type === 3 && node.isComment) { return genComment(node) } else { return genText(node) } } function genText (text) { return ("_v(" + (text.type === 2 ? text.expression // no need for () because already wrapped in _s() : transformSpecialNewlines(JSON.stringify(text.text))) + ")") } function genComment (comment) { return ("_e(" + (JSON.stringify(comment.text)) + ")") } function genSlot (el, state) { var slotName = el.slotName || '"default"'; var children = genChildren(el, state); var res = "_t(" + slotName + (children ? ("," + children) : ''); var attrs = el.attrs || el.dynamicAttrs ? genProps((el.attrs || []).concat(el.dynamicAttrs || []).map(function (attr) { return ({ // slot props are camelized name: camelize(attr.name), value: attr.value, dynamic: attr.dynamic }); })) : null; var bind$$1 = el.attrsMap['v-bind']; if ((attrs || bind$$1) && !children) { res += ",null"; } if (attrs) { res += "," + attrs; } if (bind$$1) { res += (attrs ? '' : ',null') + "," + bind$$1; } return res + ')' } // componentName is el.component, take it as argument to shun flow's pessimistic refinement function genComponent ( componentName, el, state ) { var children = el.inlineTemplate ? null : genChildren(el, state, true); return ("_c(" + componentName + "," + (genData$2(el, state)) + (children ? ("," + children) : '') + ")") } function genProps (props) { var staticProps = ""; var dynamicProps = ""; for (var i = 0; i < props.length; i++) { var prop = props[i]; var value = transformSpecialNewlines(prop.value); if (prop.dynamic) { dynamicProps += (prop.name) + "," + value + ","; } else { staticProps += "\"" + (prop.name) + "\":" + value + ","; } } staticProps = "{" + (staticProps.slice(0, -1)) + "}"; if (dynamicProps) { return ("_d(" + staticProps + ",[" + (dynamicProps.slice(0, -1)) + "])") } else { return staticProps } } // #3895, #4268 function transformSpecialNewlines (text) { return text .replace(/\u2028/g, '\\u2028') .replace(/\u2029/g, '\\u2029') } /* */ // these keywords should not appear inside expressions, but operators like // typeof, instanceof and in are allowed var prohibitedKeywordRE = new RegExp('\\b' + ( 'do,if,for,let,new,try,var,case,else,with,await,break,catch,class,const,' + 'super,throw,while,yield,delete,export,import,return,switch,default,' + 'extends,finally,continue,debugger,function,arguments' ).split(',').join('\\b|\\b') + '\\b'); // these unary operators should not be used as property/method names var unaryOperatorsRE = new RegExp('\\b' + ( 'delete,typeof,void' ).split(',').join('\\s*\\([^\\)]*\\)|\\b') + '\\s*\\([^\\)]*\\)'); // strip strings in expressions var stripStringRE = /'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*\$\{|\}(?:[^`\\]|\\.)*`|`(?:[^`\\]|\\.)*`/g; // detect problematic expressions in a template function detectErrors (ast, warn) { if (ast) { checkNode(ast, warn); } } function checkNode (node, warn) { if (node.type === 1) { for (var name in node.attrsMap) { if (dirRE.test(name)) { var value = node.attrsMap[name]; if (value) { var range = node.rawAttrsMap[name]; if (name === 'v-for') { checkFor(node, ("v-for=\"" + value + "\""), warn, range); } else if (onRE.test(name)) { checkEvent(value, (name + "=\"" + value + "\""), warn, range); } else { checkExpression(value, (name + "=\"" + value + "\""), warn, range); } } } } if (node.children) { for (var i = 0; i < node.children.length; i++) { checkNode(node.children[i], warn); } } } else if (node.type === 2) { checkExpression(node.expression, node.text, warn, node); } } function checkEvent (exp, text, warn, range) { var stipped = exp.replace(stripStringRE, ''); var keywordMatch = stipped.match(unaryOperatorsRE); if (keywordMatch && stipped.charAt(keywordMatch.index - 1) !== '$') { warn( "avoid using JavaScript unary operator as property name: " + "\"" + (keywordMatch[0]) + "\" in expression " + (text.trim()), range ); } checkExpression(exp, text, warn, range); } function checkFor (node, text, warn, range) { checkExpression(node.for || '', text, warn, range); checkIdentifier(node.alias, 'v-for alias', text, warn, range); checkIdentifier(node.iterator1, 'v-for iterator', text, warn, range); checkIdentifier(node.iterator2, 'v-for iterator', text, warn, range); } function checkIdentifier ( ident, type, text, warn, range ) { if (typeof ident === 'string') { try { new Function(("var " + ident + "=_")); } catch (e) { warn(("invalid " + type + " \"" + ident + "\" in expression: " + (text.trim())), range); } } } function checkExpression (exp, text, warn, range) { try { new Function(("return " + exp)); } catch (e) { var keywordMatch = exp.replace(stripStringRE, '').match(prohibitedKeywordRE); if (keywordMatch) { warn( "avoid using JavaScript keyword as property name: " + "\"" + (keywordMatch[0]) + "\"\n Raw expression: " + (text.trim()), range ); } else { warn( "invalid expression: " + (e.message) + " in\n\n" + " " + exp + "\n\n" + " Raw expression: " + (text.trim()) + "\n", range ); } } } /* */ var range = 2; function generateCodeFrame ( source, start, end ) { if ( start === void 0 ) start = 0; if ( end === void 0 ) end = source.length; var lines = source.split(/\r?\n/); var count = 0; var res = []; for (var i = 0; i < lines.length; i++) { count += lines[i].length + 1; if (count >= start) { for (var j = i - range; j <= i + range || end > count; j++) { if (j < 0 || j >= lines.length) { continue } res.push(("" + (j + 1) + (repeat$1(" ", 3 - String(j + 1).length)) + "| " + (lines[j]))); var lineLength = lines[j].length; if (j === i) { // push underline var pad = start - (count - lineLength) + 1; var length = end > count ? lineLength - pad : end - start; res.push(" | " + repeat$1(" ", pad) + repeat$1("^", length)); } else if (j > i) { if (end > count) { var length$1 = Math.min(end - count, lineLength); res.push(" | " + repeat$1("^", length$1)); } count += lineLength + 1; } } break } } return res.join('\n') } function repeat$1 (str, n) { var result = ''; if (n > 0) { while (true) { // eslint-disable-line if (n & 1) { result += str; } n >>>= 1; if (n <= 0) { break } str += str; } } return result } /* */ function createFunction (code, errors) { try { return new Function(code) } catch (err) { errors.push({ err: err, code: code }); return noop } } function createCompileToFunctionFn (compile) { var cache = Object.create(null); return function compileToFunctions ( template, options, vm ) { options = extend({}, options); var warn$$1 = options.warn || warn; delete options.warn; /* istanbul ignore if */ { // detect possible CSP restriction try { new Function('return 1'); } catch (e) { if (e.toString().match(/unsafe-eval|CSP/)) { warn$$1( 'It seems you are using the standalone build of Vue.js in an ' + 'environment with Content Security Policy that prohibits unsafe-eval. ' + 'The template compiler cannot work in this environment. Consider ' + 'relaxing the policy to allow unsafe-eval or pre-compiling your ' + 'templates into render functions.' ); } } } // check cache var key = options.delimiters ? String(options.delimiters) + template : template; if (cache[key]) { return cache[key] } // compile var compiled = compile(template, options); // check compilation errors/tips { if (compiled.errors && compiled.errors.length) { if (options.outputSourceRange) { compiled.errors.forEach(function (e) { warn$$1( "Error compiling template:\n\n" + (e.msg) + "\n\n" + generateCodeFrame(template, e.start, e.end), vm ); }); } else { warn$$1( "Error compiling template:\n\n" + template + "\n\n" + compiled.errors.map(function (e) { return ("- " + e); }).join('\n') + '\n', vm ); } } if (compiled.tips && compiled.tips.length) { if (options.outputSourceRange) { compiled.tips.forEach(function (e) { return tip(e.msg, vm); }); } else { compiled.tips.forEach(function (msg) { return tip(msg, vm); }); } } } // turn code into functions var res = {}; var fnGenErrors = []; res.render = createFunction(compiled.render, fnGenErrors); res.staticRenderFns = compiled.staticRenderFns.map(function (code) { return createFunction(code, fnGenErrors) }); // check function generation errors. // this should only happen if there is a bug in the compiler itself. // mostly for codegen development use /* istanbul ignore if */ { if ((!compiled.errors || !compiled.errors.length) && fnGenErrors.length) { warn$$1( "Failed to generate render function:\n\n" + fnGenErrors.map(function (ref) { var err = ref.err; var code = ref.code; return ((err.toString()) + " in\n\n" + code + "\n"); }).join('\n'), vm ); } } return (cache[key] = res) } } /* */ function createCompilerCreator (baseCompile) { return function createCompiler (baseOptions) { function compile ( template, options ) { var finalOptions = Object.create(baseOptions); var errors = []; var tips = []; var warn = function (msg, range, tip) { (tip ? tips : errors).push(msg); }; if (options) { if (options.outputSourceRange) { // $flow-disable-line var leadingSpaceLength = template.match(/^\s*/)[0].length; warn = function (msg, range, tip) { var data = { msg: msg }; if (range) { if (range.start != null) { data.start = range.start + leadingSpaceLength; } if (range.end != null) { data.end = range.end + leadingSpaceLength; } } (tip ? tips : errors).push(data); }; } // merge custom modules if (options.modules) { finalOptions.modules = (baseOptions.modules || []).concat(options.modules); } // merge custom directives if (options.directives) { finalOptions.directives = extend( Object.create(baseOptions.directives || null), options.directives ); } // copy other options for (var key in options) { if (key !== 'modules' && key !== 'directives') { finalOptions[key] = options[key]; } } } finalOptions.warn = warn; var compiled = baseCompile(template.trim(), finalOptions); { detectErrors(compiled.ast, warn); } compiled.errors = errors; compiled.tips = tips; return compiled } return { compile: compile, compileToFunctions: createCompileToFunctionFn(compile) } } } /* */ // `createCompilerCreator` allows creating compilers that use alternative // parser/optimizer/codegen, e.g the SSR optimizing compiler. // Here we just export a default compiler using the default parts. var createCompiler = createCompilerCreator(function baseCompile ( template, options ) { var ast = parse(template.trim(), options); if (options.optimize !== false) { optimize(ast, options); } var code = generate(ast, options); return { ast: ast, render: code.render, staticRenderFns: code.staticRenderFns } }); /* */ var ref$1 = createCompiler(baseOptions); var compile = ref$1.compile; var compileToFunctions = ref$1.compileToFunctions; /* */ // check whether current browser encodes a char inside attribute values var div; function getShouldDecode (href) { div = div || document.createElement('div'); div.innerHTML = href ? "<a href=\"\n\"/>" : "<div a=\"\n\"/>"; return div.innerHTML.indexOf('&#10;') > 0 } // #3663: IE encodes newlines inside attribute values while other browsers don't var shouldDecodeNewlines = inBrowser ? getShouldDecode(false) : false; // #6828: chrome encodes content in a[href] var shouldDecodeNewlinesForHref = inBrowser ? getShouldDecode(true) : false; /* */ var idToTemplate = cached(function (id) { var el = query(id); return el && el.innerHTML }); var mount = Vue.prototype.$mount; Vue.prototype.$mount = function ( el, hydrating ) { el = el && query(el); /* istanbul ignore if */ if (el === document.body || el === document.documentElement) { warn( "Do not mount Vue to <html> or <body> - mount to normal elements instead." ); return this } var options = this.$options; // resolve template/el and convert to render function if (!options.render) { var template = options.template; if (template) { if (typeof template === 'string') { if (template.charAt(0) === '#') { template = idToTemplate(template); /* istanbul ignore if */ if (!template) { warn( ("Template element not found or is empty: " + (options.template)), this ); } } } else if (template.nodeType) { template = template.innerHTML; } else { { warn('invalid template option:' + template, this); } return this } } else if (el) { template = getOuterHTML(el); } if (template) { /* istanbul ignore if */ if (config.performance && mark) { mark('compile'); } var ref = compileToFunctions(template, { outputSourceRange: "development" !== 'production', shouldDecodeNewlines: shouldDecodeNewlines, shouldDecodeNewlinesForHref: shouldDecodeNewlinesForHref, delimiters: options.delimiters, comments: options.comments }, this); var render = ref.render; var staticRenderFns = ref.staticRenderFns; options.render = render; options.staticRenderFns = staticRenderFns; /* istanbul ignore if */ if (config.performance && mark) { mark('compile end'); measure(("vue " + (this._name) + " compile"), 'compile', 'compile end'); } } } return mount.call(this, el, hydrating) }; /** * Get outerHTML of elements, taking care * of SVG elements in IE as well. */ function getOuterHTML (el) { if (el.outerHTML) { return el.outerHTML } else { var container = document.createElement('div'); container.appendChild(el.cloneNode(true)); return container.innerHTML } } Vue.compile = compileToFunctions; module.exports = Vue; /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../webpack/buildin/global.js */ "./node_modules/webpack/buildin/global.js"), __webpack_require__(/*! ./../../timers-browserify/main.js */ "./node_modules/timers-browserify/main.js").setImmediate)) /***/ }), /***/ "./node_modules/vue/dist/vue.common.js": /*!*********************************************!*\ !*** ./node_modules/vue/dist/vue.common.js ***! \*********************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { if (false) {} else { module.exports = __webpack_require__(/*! ./vue.common.dev.js */ "./node_modules/vue/dist/vue.common.dev.js") } /***/ }), /***/ "./node_modules/webpack/buildin/global.js": /*!***********************************!*\ !*** (webpack)/buildin/global.js ***! \***********************************/ /*! no static exports found */ /***/ (function(module, exports) { var g; // This works in non-strict mode g = (function() { return this; })(); try { // This works if eval is allowed (see CSP) g = g || new Function("return this")(); } catch (e) { // This works if the window reference is available if (typeof window === "object") g = window; } // g can still be undefined, but nothing to do about it... // We return undefined, instead of nothing here, so it's // easier to handle this case. if(!global) { ...} module.exports = g; /***/ }), /***/ "./resources/assets/js/app.js": /*!************************************!*\ !*** ./resources/assets/js/app.js ***! \************************************/ /*! no exports provided */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var vue__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! vue */ "./node_modules/vue/dist/vue.common.js"); /* harmony import */ var vue__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(vue__WEBPACK_IMPORTED_MODULE_0__); /* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! axios */ "./node_modules/axios/index.js"); /* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(axios__WEBPACK_IMPORTED_MODULE_1__); new vue__WEBPACK_IMPORTED_MODULE_0___default.a({ delimiters: ['{(', ')}'], data: { ideas: [], lastIdeaDate: '', categories: [], lastCategoryDate: '', form: { categories: [] }, success: false, error: false }, methods: { checkIdeas: function checkIdeas() { var _t = this; axios__WEBPACK_IMPORTED_MODULE_1___default.a.post('api/last-idea-date', this.form.lastIdeaDate).then(function (res) { // If Changes! if (res.data != _t.lastIdeaDate) _t.getIdeas(); // Set Date _t.lastIdeaDate = res.data; }); }, checkCategories: function checkCategories() { var _t = this; axios__WEBPACK_IMPORTED_MODULE_1___default.a.post('api/last-category-date', this.form.lastCategoryDate).then(function (res) { // If Changes! if (res.data != _t.lastCategoryDate) _t.getCategories(); // Set Date _t.lastCategoryDate = res.data; }); }, getIdeas: function getIdeas() { var _t = this; axios__WEBPACK_IMPORTED_MODULE_1___default.a.get('api/ideas').then(function (res) { _t.ideas = res.data; }); }, getCategories: function getCategories() { var _t = this; axios__WEBPACK_IMPORTED_MODULE_1___default.a.get('api/categories').then(function (res) { _t.categories = res.data; }); }, resetForm: function resetForm() { this.form = { categories: [] }; }, setSuccess: function setSuccess() { this.success = true; this.error = false; }, setError: function setError() { this.error = true; this.success = false; }, submitForm: function submitForm() { var _t = this; axios__WEBPACK_IMPORTED_MODULE_1___default.a.post('api/create-idea', this.form).then(function (res) { // Success _t.setSuccess(); _t.resetForm(); _t.ideas = res.data; _t.getIdeas(); })["catch"](function (res) { // Error _t.setError(); }); }, loop: function loop() { var _t = this; this.checkIdeas(); this.checkCategories(); setTimeout(function () { _t.loop(); }, 5000); } }, mounted: function mounted() { this.getIdeas(); this.getCategories(); this.loop(); } }).$mount('#app'); /***/ }), /***/ "./resources/assets/scss/app.scss": /*!****************************************!*\ !*** ./resources/assets/scss/app.scss ***! \****************************************/ /*! no static exports found */ /***/ (function(module, exports) { // removed by extract-text-webpack-plugin /***/ }), /***/ 0: /*!***************************************************************************!*\ !*** multi ./resources/assets/js/app.js ./resources/assets/scss/app.scss ***! \***************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(/*! /Users/baffi/public_html/corporate-happiness/sites/anonyme-ideen/anonyme-ideen/resources/assets/js/app.js */"./resources/assets/js/app.js"); module.exports = __webpack_require__(/*! /Users/baffi/public_html/corporate-happiness/sites/anonyme-ideen/anonyme-ideen/resources/assets/scss/app.scss */"./resources/assets/scss/app.scss"); /***/ }) /******/ });
const handleDomo = (e) => { e.preventDefault(); $("#domoMessage").animate({width:'hide'}, 350); if ($("#domoName").val() == '' || $("#domoAge").val() == '') { handleError("RAWR! All fields are required"); return false; } sendAjax('POST', $("domoForm").attr("action"), $("#domoForm").serializeArray(), function() { loadDomosFromServer(); }); return false; } const DomoForm = (props) => { return ( <form id="domoForm" onSubmit={handleDomo} name="domoForm" action="/maker" method="POST" className="domoForm" > <label htmlFor="name">Name: </label> <input id="domoName" type="text" name="name" placeHolder="Domo Name"/> <label htmlFor="age">Age: </label> <input id="domoAge" type="text" name="age" placeHolder="Domo Age"/> <input type="hidden" name="_csrf" value={props.csrf}/> <input type="hidden" name="domoId" value={props._id}/> <input className="makeDomoSubmit" type="submit" value="Make Domo"/> </form> ) } const handleEditDomo = (e, domoId) => { e.preventDefault(); $("#domoMessage").animate({width:'hide'}, 350); if ($(`${"#editDomoForm_" + domoId} #domoName`).val() == '' || $(`${"#editDomoForm_" + domoId} #domoAge`).val() == '') { handleError("RAWR! All fields are required"); return false; } let test = $(`${"#editDomoForm_" + domoId}`); let testg = test.serializeArray(); sendAjax('POST', $(`${"#editDomoForm_" + domoId}`).attr("action"), $(`${"#editDomoForm_" + domoId}`).serializeArray(), loadDomosFromServer); return false; } const EditDomoForm = (props) => { return ( <form id={"editDomoForm_" + props.domoId} // with help from https://stackoverflow.com/questions/44917513/passing-an-additional-parameter-with-an-onchange-event onSubmit={(e) => handleEditDomo(e, props.domoId)} name="editDomoForm" action="/editDomo" method="POST" className="domoForm" > <label htmlFor="name">New Name: </label> <input id="domoName" type="text" name="name" placeHolder="Domo Name"/> <label htmlFor="age">New Age: </label> <input id="domoAge" type="text" name="age" placeHolder="Domo Age"/> <input type="hidden" name="_csrf" value={props.csrf}/> <input type="hidden" name="_id" value={props.domoId}/> <input className="makeDomoSubmit" type="submit" value="Make Domo"/> </form> ) } class DomoList extends React.Component { constructor(props) { super(props); this.state = {isBeingEdited: false}; } render() { if (this.props.domos.length === 0) { return ( <div className="domoList"> <h3 className="emptyDomo">No Domos yet</h3> </div> ); } const domoNodes = this.props.domos.map(function(domo) { return ( // <div key={domo._id} className="domo"> // <img src = "/assets/img/domoface.jpeg" alt = "Domo face" className="domoFace" /> // <h3 className="domoName">Name: {domo.name}</h3> // <h3 className="domoAge">Age: {domo.age}</h3> // <button onClick = {this.toggleIsBeingEdited}>Edit</button> // </div> <DomoItem _id={domo._id} name={domo.name} age={domo.age}/> ); }, this); return ( <div className="domoList"> {domoNodes} </div> ) } }; class DomoItem extends React.Component { constructor(props) { super(props); this.state = {isBeingEdited: false}; this.toggleIsBeingEdited = this.toggleIsBeingEdited.bind(this); } toggleIsBeingEdited() { this.setState((state, props) =>( { isBeingEdited: !state.isBeingEdited })); } render() { return( <div> <div key={this.props._id} className="domo"> <img src = "/assets/img/domoface.jpeg" alt = "Domo face" className="domoFace" /> <h3 className="domoName">Name: {this.props.name}</h3> <h3 className="domoAge">Age: {this.props.age}</h3> <button onClick = {this.toggleIsBeingEdited}>Edit</button> </div> {this.state.isBeingEdited ? <EditDomoForm csrf={DomoItem.csrf || ''} domoId = {this.props._id}/> : ''} </div> ) } } const loadDomosFromServer = () => { sendAjax('GET', '/getDomos', null, (data) => { ReactDOM.render( <DomoList domos = {data.domos} />, document.querySelector("#domos") ); }); }; const setup = function(csrf) { DomoItem.csrf = csrf; ReactDOM.render( <DomoForm csrf={csrf} />, document.querySelector("#makeDomo") ); ReactDOM.render( <DomoList domos={[]} />, document.querySelector("#domos") ); loadDomosFromServer(); }; const getToken = () => { sendAjax('GET', '/getToken', null, (result) => { setup(result.csrfToken); }); }; $(document).ready(function() { getToken(); });
module.exports = { siteMetadata: { title: `Gatsby Default Starter`, description: `Kick off your next, great Gatsby project with this default starter. This barebones starter ships with the main Gatsby configuration files you might need.`, author: `@gatsbyjs`, }, plugins: [ { resolve: `gatsby-source-strapi`, options: { apiURL: `http://127.0.0.1:2337`, queryLimit: 1000, // Default to 100 contentTypes: ["school", "category"], // Possibility to login with a strapi user, when content types are not publically available (optional). loginData: { identifier: "gatsby-admin", password: "123456", }, }, }, `gatsby-plugin-react-helmet`, { resolve: `gatsby-source-filesystem`, options: { name: `images`, path: `${__dirname}/src/images`, }, }, `gatsby-transformer-sharp`, `gatsby-plugin-sharp`, { resolve: `gatsby-plugin-manifest`, options: { name: `gatsby-starter-default`, short_name: `starter`, start_url: `/`, background_color: `#663399`, theme_color: `#663399`, display: `minimal-ui`, icon: `src/images/gatsby-icon.png`, // This path is relative to the root of the site. }, }, // custom "gatsby-plugin-material-ui", { resolve: `gatsby-plugin-sass`, options: { includePaths: [], }, }, // this (optional) plugin enables Progressive Web App + Offline functionality // To learn more, visit: https://gatsby.dev/offline // `gatsby-plugin-offline`, ], }
import React, { Component } from "react"; import Header from "./views/Header"; import AppRouter from "./components/shared/routers/AppRouter"; /** * Happy coding! * React Template by Lucas Pelloni */ class App extends Component { render() { return ( <div> <Header height={"100"} /> <AppRouter /> </div> ); } } export default App;
Microsoft.WebPortal.Views.List.TablePageRenderer = function (list) { /// <summary> /// Renders a paged list. The footer will contain links used to navigate to pages. /// </summary> /// <param name="list">The list to render.</param> this.base.constructor.call(this, list, "tablePageListBody-template", "tablePageListFooter-template"); // the current page index will start at zero this.pageIndex = ko.observable(0); // this will hold the current page rows as we do not want to render the entire list rows this.rowsToRender = ko.observable(); // controls the enabled state of the next page link this.disableNext = ko.observable(false); // computes the index of the last page this.lastPageIndex = ko.computed(function () { return Math.ceil(this.rows().length / this.pageSize()) - 1; }, this); // determines whether the next link is rendered or not this.renderNext = ko.computed(function () { // render only if the data is not complete or we are not in the last page index in case it was complete return !this.isComplete() || this.pageIndex() < this.lastPageIndex(); }, this); // determines if a row is in the current page or not this.inCurrentPage = function (index) { return index >= this.pageIndex() * this.pageSize() && index < (this.pageIndex() + 1) * this.pageSize(); }; this.pageSizeSubscription = this.pageSize.subscribe(function () { // page size changed, go to first page this.goToPage(0); // clear select all this.list._silentClearSelectAll(); }, this); this.pageIndexSubscription = this.pageIndex.subscribe(function () { // page index changed, clear select all as only the previous page rows were selected (if so) this.list._silentClearSelectAll(); }, this); this.rowsSubscription = this.rows.subscribe(function () { // refresh the page any time the rows update this.refreshPage(); }, this); // render the first page this.refreshPage(); }; // inherit ListRenderer $WebPortal.Helpers.inherit(Microsoft.WebPortal.Views.List.TablePageRenderer, Microsoft.WebPortal.Views.List.ListRenderer); Microsoft.WebPortal.Views.List.TablePageRenderer.prototype.onDataRequestStarted = function () { /// <summary> /// Called before a request for additional data is made. /// </summary> // disable the next button this.disableNext(true); }; Microsoft.WebPortal.Views.List.TablePageRenderer.prototype.onDataArrived = function () { /// <summary> /// Called when the additional data is received. /// </summary> // enable the next button this.disableNext(false); // we do not want the page to unnecessarily refresh when the rows are added as we are going to manually trigger it by moving to the new page this.supressPageRefresh = true; }; Microsoft.WebPortal.Views.List.TablePageRenderer.prototype.onDataRequestFinished = function (pageIndex) { /// <summary> /// Called when requesting data is finished whether in success or in failure. /// </summary> /// <param name="pageIndex">The page index.</param> // navigate to the page index and reenable back page refresh this.supressPageRefresh = false; this.goToPage(pageIndex); }; Microsoft.WebPortal.Views.List.TablePageRenderer.prototype.performSelectAll = function (allSelected) { /// <summary> /// Called to perform select all logic. Override default behavior and only select the current page rows. /// </summary> /// <param name="allSelected">True to select all, false to deselect all.</param> var startIndex = this.pageIndex() * this.pageSize(); // we normally want to loop through the page size but there is a possibility that the total rows we have are less, account for this case var rowCountToSelect = Math.min(this.pageSize(), this.rows().length - this.pageIndex() * this.pageSize()); for (var i = 0; i < rowCountToSelect; ++i) { if (this.rows()[startIndex + i].isSelected) { this.rows()[startIndex + i].isSelected(allSelected); } } }; Microsoft.WebPortal.Views.List.TablePageRenderer.prototype.goToPage = function (pageIndex) { /// <summary> /// Navigates to a list page. /// </summary> /// <param name="pageIndex">The page index to go to.</param> pageIndex = Math.max(0, pageIndex); this.disableNext(false); if (this.isComplete()) { // if we have all the data, ensure we do not run past the last page index pageIndex = Math.min(this.lastPageIndex(), pageIndex); } else { // make sure we do not run too far ahead of the last page index pageIndex = Math.min(this.lastPageIndex() + 1, pageIndex); if (pageIndex > this.lastPageIndex()) { // we do not have rows for this page, get them this.requestMoreRows(pageIndex * this.pageSize(), this.pageSize(), pageIndex); return; } else if ((pageIndex + 1) * this.pageSize() > this.rows().length) { // we have partial data for this row, get the rest to fill up the page this.requestMoreRows(this.rows().length, (pageIndex + 1) * this.pageSize() - this.rows().length, pageIndex); return; } } // if we reach here, then we have all the rows for the requested page, update the page index and refresh the list page to show the // new rows this.pageIndex(pageIndex); this.refreshPage(); }; Microsoft.WebPortal.Views.List.TablePageRenderer.prototype.refreshPage = function () { /// <summary> /// Refreshes the rows that will get rendered as a result of them being in the current page. /// </summary> if (this.supressPageRefresh === true) { return; } var startIndex = this.pageIndex() * this.pageSize(); this.rowsToRender(this.rows.slice(startIndex, startIndex + this.pageSize())); }; Microsoft.WebPortal.Views.List.TablePageRenderer.prototype.destroy = function () { /// <summary> /// Destorys the renderer. /// </summary> // stop listening to page size changes if (this.pageSizeSubscription) { this.pageSizeSubscription.dispose(); this.pageSizeSubscription = null; } // stop listening to page index changes if (this.pageIndexSubscription) { this.pageIndexSubscription.dispose(); this.pageIndexSubscription = null; } // stop listening to row changes if (this.rowsSubscription) { this.rowsSubscription.dispose(); this.rowsSubscription = null; } }; //@ sourceURL=TablePageRenderer.js
const { networkInterfaces, NetworkInterfaceInfo } = require('os'); const ora = require('ora'); const chalk = require('chalk'); const inquirer = require('inquirer'); const spinner = ora(); /** * @description: success tip * @Date: 2020-03-16 13:06:12 */ function successTip(msg) { spinner.succeed( console.log( chalk.blue.bold('**************** ') + chalk.green.bold(msg) + chalk.blue.bold(' ****************') + '. 🎉 🎉 🎉 🎉\n' ) ); } /** * @description: error tip * @Date: 2020-03-16 13:06:12 */ function errorTip(msg, err) { spinner.fail( console.error('\n') + console.error(msg + '\n') + console.error(chalk.magenta('The specific error message is as follows \n')) + chalk.red(err) + '. 😭\n' ); process.exit(1); } function inquirerPrompt(question) { return inquirer.prompt(question); } /** * @description: get env * @Date: 2020-06-07 22:32:25 */ function getEnvFn() { return process.env; } /** * @description: get mode * @Date: 2020-06-07 22:32:56 */ function getModeFn() { return getEnvFn().NODE_ENV; } /** * @description: Whether it is a production mode * @Date: 2020-06-07 22:33:35 */ function isProductionFn() { return getModeFn() === 'production'; } /** * @description: Whether to develop mode * @Date: 2020-06-07 22:34:11 */ function isDevFn() { return getModeFn() === 'development'; } /** * @description: Whether to support ie * * @Date: 2020-06-15 11:06:12 */ function supportIeFn() { return process.env.VUE_APP_SUPPORT_IE === 'TRUE'; } /** * @description: Whether it is report mode * @Date: 2020-06-15 11:06:18 */ function isReportModeFn() { return !!process.env.REPORT; } function isSiteModeFn() { return !!process.env.SITE; } /** * @description: Get local ip * @Date: 2020-06-15 11:06:35 */ function getIPAddress() { let interfaces = networkInterfaces(); for (let devName in interfaces) { let iFace = interfaces[devName]; for (let i = 0; i < iFace.length; i++) { let alias = iFace[i]; if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) { return alias.address; } } } return ''; } module.exports = { getEnvFn, getModeFn, isProductionFn, isDevFn, errorTip, successTip, inquirerPrompt, supportIeFn, isReportModeFn, getIPAddress, isSiteModeFn, };
import esbuildServe from 'esbuild-serve'; esbuildServe( { entryPoints: ['./src/app.tsx'], bundle: true, // minify: true, sourcemap: true, // target: ['chrome58', 'firefox57', 'safari11', 'edge16'], tsconfig: 'tsconfig.json', outfile: './public/bundle.js', // splitting: true, // chunkNames: "", define: { 'process.env.NODE_ENV': '"development"', }, loader: { '.png': 'dataurl', '.eot': 'dataurl', '.svg': 'dataurl', '.ttf': 'dataurl', '.woff': 'dataurl', }, watch: { onRebuild(error, result) { if (error) console.error('Watch build failed:', error) else console.log('Watch build succeeded.') }, }, }, { port: 8081, root: './public' } );
"use strict"; class MakeCards extends BaseComponent { static async pInit () { MakeCards._ = new MakeCards(); await MakeCards.utils.pLoadReducedData(); await MakeCards._.pInit(); window.dispatchEvent(new Event("toolsLoaded")); } constructor () { super(); this._list = null; this._modalFilterItems = new ModalFilterItems("makecards.items"); this._modalFilterBestiary = new ModalFilterBestiary("makecards.bestiary"); this._modalFilterSpells = new ModalFilterSpells("makecards.spells"); this._doSaveStateDebounced = MiscUtil.debounce(() => this._pDoSaveState(), 50); } async pInit () { await SearchUiUtil.pDoGlobalInit(); // Do this asynchronously, to avoid blocking the load SearchWidget.pDoGlobalInit(); await this._pDoLoadState(); this.render(); } render () { this._addHookAll("state", () => this._doSaveStateDebounced()); this._render_configSection(); this._render_cardList(); } _render_configSection () { const $wrpConfig = $(`#wrp_config`).empty(); $(`<h5>New Card Defaults</h5>`).appendTo($wrpConfig); $(`<div class="flex-v-center bold"> <div class="col-4 text-center pr-2">Type</div> <div class="col-4 text-center p-2">Color</div> <div class="col-4 text-center pl-2">Icon</div> </div>`).appendTo($wrpConfig); const $getColorIconConfigRow = (entityType) => { const entityMeta = MakeCards._AVAILABLE_TYPES[entityType]; const kColor = `color_${entityType}`; const kIcon = `icon_${entityType}`; const $iptColor = ComponentUiUtil.$getIptColor(this, kColor).addClass("cards-cfg__ipt-color"); const $dispIcon = $(`<div class="cards__disp-btn-icon"/>`); const $btnChooseIcon = $$`<button class="btn btn-xs btn-default cards__btn-choose-icon">${$dispIcon}</button>` .click(async () => { const icon = await MakeCards._pGetUserIcon(this._state[kIcon]); if (icon) this._state[kIcon] = icon; }); const hkIcon = () => $dispIcon.css("background-image", `url('${MakeCards._getIconPath(this._state[kIcon])}')`); this._addHookBase(kIcon, hkIcon); hkIcon(); return $$`<div class="flex-v-center stripe-even m-1"> <div class="col-4 flex-vh-center pr-2">${entityMeta.searchTitle}</div> <div class="col-4 flex-vh-center p-2">${$iptColor}</div> <div class="col-4 flex-vh-center pl-2">${$btnChooseIcon}</div> </div>`; }; Object.keys(MakeCards._AVAILABLE_TYPES).forEach(it => $getColorIconConfigRow(it).appendTo($wrpConfig)) } _render_cardList () { const $wrpContainer = $(`#wrp_main`).empty(); // region Search bar/add button const contextIdSearch = ContextUtil.getNextGenericMenuId(); const _CONTEXT_OPTIONS = this._render_getContextMenuOptions(); ContextUtil.doInitActionContextMenu(contextIdSearch, _CONTEXT_OPTIONS); const $iptSearch = $(`<input type="search" class="form-control mr-2" placeholder="Search cards...">`); const $btnAdd = $(`<button class="btn btn-primary mr-2"><span class="glyphicon glyphicon-plus"/> Add</button>`) .click(evt => ContextUtil.handleOpenContextMenu(evt, $btnAdd, contextIdSearch)); const $btnReset = $(`<button class="btn btn-danger mr-2"><span class="glyphicon glyphicon-trash"/> Reset</button>`) .click(() => { if (!confirm("Are you sure?")) return; this._list.removeAllItems(); this._list.update(); this._doSaveStateDebounced(); }); const $btnExport = $(`<button class="btn btn-default"><span class="glyphicon glyphicon-download"/> Export JSON</button>`) .click(() => { const toDownload = this._list.items.map(it => { const entityMeta = MakeCards._AVAILABLE_TYPES[it.values.entityType]; return { count: it.values.count, color: it.values.color, title: it.name, icon: it.values.icon, icon_back: it.values.icon, contents: entityMeta.fnGetContents(it.values.entity), tags: entityMeta.fnGetTags(it.values.entity) } }); DataUtil.userDownload("rpg-cards", toDownload); }); $$`<div class="w-100 no-shrink flex-v-center mb-3">${$iptSearch}${$btnAdd}${$btnReset}${$btnExport}</div>`.appendTo($wrpContainer); // endregion // region Mass operations bar const getSelCards = () => { const out = this._list.visibleItems.filter(it => it.data.$cbSel.prop("checked")); if (!out.length) { JqueryUtil.doToast({content: "Please select some cards first!", type: "warning"}); return null; } return out; }; const contextIdMass = ContextUtil.getNextGenericMenuId(); const _CONTEXT_OPTIONS_MASS = [ new ContextUtil.Action( "Set Color", async () => { const sel = getSelCards(); if (!sel) return; const rgb = await InputUiUtil.pGetUserColor({default: MiscUtil.randomColor()}); if (rgb) sel.forEach(it => it.data.setColor(rgb)); } ), new ContextUtil.Action( "Set Icon", async () => { const sel = getSelCards(); if (!sel) return; const icon = await MakeCards._pGetUserIcon(); if (icon) sel.forEach(it => it.data.setIcon(icon)); } ), new ContextUtil.Action( "Remove", async () => { const sel = getSelCards(); if (!sel) return; sel.forEach(it => this._list.removeItem(it.ix)); this._list.update(); this._doSaveStateDebounced(); } ) ]; ContextUtil.doInitActionContextMenu(contextIdMass, _CONTEXT_OPTIONS_MASS); const $btnMass = $(`<button class="btn btn-xs btn-default" title="Carry out actions on selected cards">Mass...</button>`) .click(evt => ContextUtil.handleOpenContextMenu(evt, $btnMass, contextIdMass)); $$`<div class="w-100 no-shrink flex-v-center mb-2">${$btnMass}</div>`.appendTo($wrpContainer); // endregion // region Main content // Headers const $cbSelAll = $(`<input type="checkbox" title="Select All">`) .click(() => { const isSel = $cbSelAll.prop("checked"); this._list.visibleItems.forEach(it => it.data.$cbSel.prop("checked", isSel)); }); $$`<div class="w-100 no-shrink flex-v-center bold"> <div class="col-1 mr-2 flex-vh-center">${$cbSelAll}</div> <div class="col-3 mr-2 flex-vh-center">Name</div> <div class="col-1-5 mr-2 flex-vh-center">Source</div> <div class="col-1-5 mr-2 flex-vh-center">Type</div> <div class="col-1-1 mr-2 flex-vh-center">Color</div> <div class="col-1-1 mr-2 flex-vh-center">Icon</div> <div class="col-1 mr-2 flex-vh-center">Count</div> <div class="col-1-1 flex-v-center flex-h-right"/> </div>`.appendTo($wrpContainer); const $wrpList = $(`<div class="w-100 h-100"/>`); $$`<div class="flex-col h-100 w-100 overflow-y-auto mt-2 overflow-x-hidden">${$wrpList}</div>`.appendTo($wrpContainer); this._list = new List({$iptSearch, $wrpList, isUseJquery: true}); this._list.init(); // endregion } _render_getContextMenuOptions () { return [ ...this._render_getContextMenuOptionsSearch(), null, ...this._render_getContextMenuOptionsFilter(), null, ...this._render_getContextMenuOptionsSublist() ]; } _render_getContextMenuOptionsSearch () { return Object.entries(MakeCards._AVAILABLE_TYPES).map(([entityType, it]) => new ContextUtil.Action( `Search for ${it.searchTitle}`, async () => { const fromSearch = await it.pFnSearch(); if (!fromSearch) return; const existing = this._list.items.find(it => it.values.page === fromSearch.page && it.values.source === fromSearch.source && it.values.hash === fromSearch.hash); if (existing) { existing.values.count++; existing.data.$iptCount.val(existing.values.count); return this._doSaveStateDebounced(); } const listItem = await this._pGetListItem({page: fromSearch.page, source: fromSearch.source, hash: fromSearch.hash, entityType}, true); this._list.addItem(listItem); this._list.update(); this._doSaveStateDebounced(); } )); } _render_getContextMenuOptionsFilter () { return Object.entries(MakeCards._AVAILABLE_TYPES).map(([entityType, type]) => new ContextUtil.Action( `Filter for ${type.searchTitle}`, async () => { const modalFilter = (() => { switch (entityType) { case "creature": return this._modalFilterBestiary; case "item": return this._modalFilterItems; case "spell": return this._modalFilterSpells; default: throw new Error(`Unhandled branch!`); } })(); const selected = await modalFilter.pGetUserSelection(); if (selected == null || !selected.length) return; // do this in serial to avoid bombarding the hover cache const len = selected.length; for (let i = 0; i < len; ++i) { const filterListItem = selected[i]; const listItem = await this._pGetListItem({page: type.page, source: filterListItem.values.sourceJson, hash: filterListItem.values.hash, entityType}, true); this._list.addItem(listItem); } this._list.update(); this._doSaveStateDebounced(); } )); } _render_getContextMenuOptionsSublist () { return Object.entries(MakeCards._AVAILABLE_TYPES).map(([entityType, type]) => new ContextUtil.Action( `Load from ${type.pageTitle}${type.isPageTitleSkipSuffix ? "" : " Page"} Pinned List`, async () => { const storageKey = StorageUtil.getPageKey("sublist", type.page); const pinnedList = await StorageUtil.pGet(storageKey); if (!(pinnedList && pinnedList.items && pinnedList.items.length)) { return JqueryUtil.doToast({content: "Nothing to add! Please visit the page and add/pin some data first.", type: "warning"}); } const listItems = await Promise.all(pinnedList.items.map(it => { const [_, source] = it.h.split(HASH_PART_SEP)[0].split(HASH_LIST_SEP); return this._pGetListItem({page: type.page, source, hash: it.h, entityType}, true); })); listItems.forEach(it => this._list.addItem(it)); this._list.update(); this._doSaveStateDebounced(); } )) } _getStateForType (entityType) { const kColor = `color_${entityType}`; const kIcon = `icon_${entityType}`; const color = this._state[kColor]; const icon = this._state[kIcon]; return {color, icon}; } async _pGetListItem (cardMeta, isNewCard) { const uid = CryptUtil.uid(); if (isNewCard) { const {color, icon} = this._getStateForType(cardMeta.entityType); cardMeta.color = cardMeta.color || color; cardMeta.icon = cardMeta.icon || icon; } cardMeta.count = cardMeta.count || 1; const loaded = await Renderer.hover.pCacheAndGet(cardMeta.page, cardMeta.source, cardMeta.hash); const $cbSel = $(`<input type="checkbox">`); const $iptRgb = $(`<input type="color" class="form-control input-xs form-control--minimal">`) .val(cardMeta.color) .change(() => setColor($iptRgb.val())); const setColor = (rgb) => { $iptRgb.val(rgb); listItem.values.color = rgb; this._doSaveStateDebounced(); }; const $dispIcon = $(`<div class="cards__disp-btn-icon"/>`) .css("background-image", `url('${MakeCards._getIconPath(cardMeta.icon)}')`); const $btnIcon = $$`<button class="btn btn-default btn-xs cards__btn-choose-icon">${$dispIcon}</button>` .click(async () => { const icon = await MakeCards._pGetUserIcon(); if (icon) setIcon(icon); }); const setIcon = (icon) => { listItem.values.icon = icon; $dispIcon.css("background-image", `url('${MakeCards._getIconPath(icon)}')`); this._doSaveStateDebounced(); }; const $iptCount = $(`<input class="form-control form-control--minimal input-xs text-center">`) .change(() => { const asNum = UiUtil.strToInt($iptCount.val(), 1, {min: 1, fallbackOnNaN: 1}); listItem.values.count = asNum; $iptCount.val(asNum); this._doSaveStateDebounced(); }) .val(cardMeta.count); const $btnCopy = $(`<button class="btn btn-default btn-xs mr-2" title="Copy JSON (SHIFT to view JSON)"><span class="glyphicon glyphicon-copy"/></button>`) .click(async evt => { const entityMeta = MakeCards._AVAILABLE_TYPES[listItem.values.entityType]; const toCopy = { count: listItem.values.count, color: listItem.values.color, title: listItem.name, icon: listItem.values.icon, icon_back: listItem.values.icon, contents: entityMeta.fnGetContents(listItem.values.entity), tags: entityMeta.fnGetTags(listItem.values.entity) }; if (evt.shiftKey) { const $content = Renderer.hover.$getHoverContent_statsCode(toCopy); Renderer.hover.getShowWindow( $content, Renderer.hover.getWindowPositionFromEvent(evt), { title: `Card Data \u2014 ${listItem.name}`, isPermanent: true, isBookContent: true } ); } else { await MiscUtil.pCopyTextToClipboard(JSON.stringify(toCopy, null, 2)); JqueryUtil.showCopiedEffect($btnCopy, "Copied JSON!"); } }); const $btnDelete = $(`<button class="btn btn-danger btn-xs" title="Remove"><span class="glyphicon glyphicon-trash"/></button>`) .click(() => { this._list.removeItem(uid); this._list.update(); this._doSaveStateDebounced(); }); const $ele = $$`<label class="flex-v-center my-1 w-100 lst--border"> <div class="col-1 mr-2 flex-vh-center">${$cbSel}</div> <div class="col-3 mr-2 flex-v-center">${loaded.name}</div> <div class="col-1-5 mr-2 flex-vh-center ${Parser.sourceJsonToColor(loaded.source)}" title="${Parser.sourceJsonToFull(loaded.source)}" ${BrewUtil.sourceJsonToStyle(loaded.source)}>${Parser.sourceJsonToAbv(loaded.source)}</div> <div class="col-1-5 mr-2 flex-vh-center">${cardMeta.entityType.toTitleCase()}</div> <div class="col-1-1 mr-2 flex-vh-center">${$iptRgb}</div> <div class="col-1-1 mr-2 flex-vh-center">${$btnIcon}</div> <div class="col-1 mr-2 flex-vh-center">${$iptCount}</div> <div class="col-1-1 flex-v-center flex-h-right">${$btnCopy}${$btnDelete}</div> </label>`; const listItem = new ListItem( uid, $ele, loaded.name, { page: cardMeta.page, hash: cardMeta.hash, source: cardMeta.source, color: cardMeta.color, icon: cardMeta.icon, count: cardMeta.count, entityType: cardMeta.entityType, entity: loaded }, { $cbSel, $iptCount, setColor, setIcon } ); return listItem; } // region contents static _ct_subtitle (val) { return `subtitle | ${val}`; } static _ct_rule () { return `rule`; } static _ct_property (title, val) { return `property | ${title} | ${val}`; } static _ct_fill (size) { return `fill ${size}`; } static _ct_text (val) { return `text | ${val}`; } static _ct_section (val) { return `section | ${val}`; } static _ct_description (title, val) { return `description | ${title} | ${val}`; } static _ct_bullet (val) { return `bullet | ${val}`; } static _ct_boxes (count, size = 1.2) { return `boxes | ${count} | ${size}`; } static _ct_dndstats (...attrs) { return `dndstats | ${attrs.join(" | ")}`; } static _ct_htmlToText (html) { return $(`<div>${html}</div>`).text().trim(); } static _ct_renderEntries (entries, depth = 0) { if (!entries || !entries.length) return []; return entries.map(ent => { const rendSub = ent.rendered || RendererCard.get().render(ent, depth); return rendSub.split("\n").filter(Boolean); }).flat(); } static _getCardContents_creature (mon) { const renderer = RendererCard.get(); const allTraits = Renderer.monster.getOrderedTraits(mon, renderer); return [ this._ct_subtitle(Renderer.monster.getTypeAlignmentPart(mon)), this._ct_rule(), this._ct_property("Armor class", this._ct_htmlToText(Parser.acToFull(mon.ac))), this._ct_property("Hit points", this._ct_htmlToText(Renderer.monster.getRenderedHp(mon.hp))), this._ct_property("Speed", this._ct_htmlToText(Parser.getSpeedString(mon))), this._ct_rule(), this._ct_dndstats(...Parser.ABIL_ABVS.map(it => mon[it])), this._ct_rule(), mon.save ? this._ct_property("Saving Throws", this._ct_htmlToText(Renderer.monster.getSavesPart(mon))) : null, mon.skill ? this._ct_property("Skills", this._ct_htmlToText(Renderer.monster.getSkillsString(Renderer.get(), mon))) : null, mon.vulnerable ? this._ct_property("Damage Vulnerabilities", this._ct_htmlToText(Parser.monImmResToFull(mon.vulnerable))) : null, mon.resist ? this._ct_property("Damage Resistances", this._ct_htmlToText(Parser.monImmResToFull(mon.resist))) : null, mon.immune ? this._ct_property("Damage Immunities", this._ct_htmlToText(Parser.monImmResToFull(mon.immune))) : null, mon.conditionImmune ? this._ct_property("Condition Immunities", this._ct_htmlToText(Parser.monCondImmToFull(mon.conditionImmune))) : null, this._ct_property("Senses", this._ct_htmlToText(Renderer.monster.getSensesPart(mon))), this._ct_property("Languages", this._ct_htmlToText(Renderer.monster.getRenderedLanguages(mon.languages))), this._ct_property("Challenge", this._ct_htmlToText(Parser.monCrToFull(mon.cr))), this._ct_rule(), ...(allTraits ? this._ct_renderEntries(allTraits, 2) : []), mon.action ? this._ct_section("Actions") : null, ...(mon.action ? this._ct_renderEntries(mon.action, 2) : []), mon.reaction ? this._ct_section("Reactions") : null, ...(mon.reaction ? this._ct_renderEntries(mon.reaction, 2) : []), mon.legendary ? this._ct_section("Legendary Actions") : null, mon.legendary ? this._ct_text(this._ct_htmlToText(Renderer.monster.getLegendaryActionIntro(mon))) : null, ...(mon.legendary ? this._ct_renderEntries(mon.legendary, 2) : []) ].filter(Boolean) } static _getCardContents_spell (sp) { const higherLevel = sp.entriesHigherLevel ? (() => { const ents = sp.entriesHigherLevel.length === 1 && sp.entriesHigherLevel[0].name && sp.entriesHigherLevel[0].name.toLowerCase() === "at higher levels" ? sp.entriesHigherLevel[0].entries : sp.entriesHigherLevel; return [ this._ct_section("At higher levels"), ...this._ct_renderEntries(ents, 2) ] })() : null; return [ this._ct_subtitle(Parser.spLevelSchoolMetaToFull(sp.level, sp.school, sp.meta, sp.subschools)), this._ct_rule(), this._ct_property("Casting Time", Parser.spTimeListToFull(sp.time)), this._ct_property("Range", Parser.spRangeToFull(sp.range)), this._ct_property("Components", Parser.spComponentsToFull(sp.components, sp.level)), this._ct_property("Duration", Parser.spDurationToFull(sp.duration)), this._ct_rule(), ...this._ct_renderEntries(sp.entries, 2), ...(higherLevel || []) ].filter(Boolean); } static _getCardContents_item (item) { MakeCards.utils.enhanceItemAlt(item); const [damage, damageType, propertiesTxt] = Renderer.item.getDamageAndPropertiesText(item); const ptValueWeight = [Parser.itemValueToFull(item), Parser.itemWeightToFull(item)].filter(Boolean).join(", ").uppercaseFirst(); const ptDamageProperties = this._ct_htmlToText([damage, damageType, propertiesTxt].filter(Boolean).join(" ")); const itemEntries = []; if (item._fullEntries || (item.entries && item.entries.length)) { itemEntries.push(...(item._fullEntries || item.entries)); } if (item._fullAdditionalEntries || item.additionalEntries) { itemEntries.push(...(item._fullAdditionalEntries || item.additionalEntries)); } return [ this._ct_subtitle(Renderer.item.getTypeRarityAndAttunementText(item).uppercaseFirst()), ptValueWeight || ptDamageProperties ? this._ct_rule() : null, ptValueWeight ? this._ct_text(ptValueWeight) : null, ptDamageProperties ? this._ct_text(ptDamageProperties) : null, itemEntries.length ? this._ct_rule() : null, ...this._ct_renderEntries(itemEntries, 2), item.charges ? this._ct_boxes(item.charges) : null ].filter(Boolean); } // endregion static _getIconPath (iconName) { if (class_icon_names.includes(iconName)) { return `https://raw.githubusercontent.com/crobi/rpg-cards/master/generator/img/classes/${iconName.split("-")[1]}.png` } return `https://raw.githubusercontent.com/crobi/rpg-cards/master/generator/img/${iconName}.png` } static _pGetUserIcon (initialVal) { return new Promise(resolve => { const $iptStr = $(`<input class="form-control mb-2">`) .keydown(async evt => { // prevent double-binding the return key if we have autocomplete enabled await MiscUtil.pDelay(17); // arbitrary delay to allow dropdown to render (~1000/60, i.e. 1 60 FPS frame) if ($modalInner.find(`.typeahead.dropdown-menu`).is(":visible")) return; // return key if (evt.which === 13) doClose(true); evt.stopPropagation(); }); if (initialVal) $iptStr.val(initialVal); $iptStr.typeahead({ source: icon_names, items: "16", fnGetItemPrefix: (iconName) => { return `<span class="cards__disp-typeahead-icon mr-2" style="background-image: url('${MakeCards._getIconPath(iconName)}')"/> `; } }); const $btnOk = $(`<button class="btn btn-default">Confirm</button>`) .click(() => doClose(true)); const {$modalInner, doClose} = UiUtil.getShowModal({ title: "Enter Icon", isMinHeight0: true, cbClose: (isDataEntered) => { if (!isDataEntered) return resolve(null); const raw = $iptStr.val(); if (!raw.trim()) return resolve(null); else return resolve(raw); } }); $iptStr.appendTo($modalInner); $$`<div class="flex-vh-center">${$btnOk}</div>`.appendTo($modalInner); $iptStr.focus(); $iptStr.select(); }); } // region persistence async _pDoSaveState () { const toSave = this.getSaveableState(); await StorageUtil.pSetForPage(MakeCards._STORAGE_KEY, toSave); } async _pDoLoadState () { const toLoad = await StorageUtil.pGetForPage(MakeCards._STORAGE_KEY); if (toLoad != null) this.setStateFrom(toLoad); } getSaveableState () { return { state: this.getBaseSaveableState(), listItems: this._list.items.map(it => ({ page: it.values.page, source: it.values.source, hash: it.values.hash, color: it.values.color, icon: it.values.icon, count: it.values.count, entityType: it.values.entityType })) }; } setStateFrom (toLoad) { this.setBaseSaveableStateFrom(toLoad.state); Promise.all(toLoad.listItems.map(async toLoad => this._pGetListItem(toLoad))) .then(initialListItems => { if (initialListItems.length) { initialListItems.sort((a, b) => SortUtil.ascSortLower(a.name, b.name)).forEach(it => this._list.addItem(it)); this._list.update(); } }); } // endregion _getDefaultState () { const cpy = MiscUtil.copy(MakeCards._DEFAULT_STATE); Object.entries(MakeCards._AVAILABLE_TYPES).forEach(([k, v]) => { const kColor = `color_${k}`; const kIcon = `icon_${k}`; cpy[kColor] = v.colorDefault || MakeCards._DEFAULT_STATE; cpy[kIcon] = v.iconDefault || MakeCards._ICON_DEFAULT; }); return cpy; } } MakeCards._DEFAULT_STATE = { }; MakeCards._COLOR_DEFAULT = "#333333"; MakeCards._ICON_DEFAULT = "perspective-dice-six-faces-random"; MakeCards._STORAGE_KEY = "cardState"; MakeCards._AVAILABLE_TYPES = { creature: { searchTitle: "Creature", pageTitle: "Bestiary", isPageTitleSkipSuffix: true, page: UrlUtil.PG_BESTIARY, colorDefault: "#008000", iconDefault: "imp-laugh", pFnSearch: SearchWidget.pGetUserCreatureSearch, fnGetContents: MakeCards._getCardContents_creature.bind(MakeCards), fnGetTags: (mon) => { const types = Parser.monTypeToFullObj(mon.type); const cr = mon.cr == null ? "unknown CR" : `CR ${(mon.cr.cr || mon.cr)}`; return ["creature", Parser.sourceJsonToAbv(mon.source), types.type, cr, Parser.sizeAbvToFull(mon.size)] } }, item: { searchTitle: "Item", pageTitle: "Items", page: UrlUtil.PG_ITEMS, colorDefault: "#696969", iconDefault: "mixed-swords", pFnSearch: SearchWidget.pGetUserItemSearch, fnGetContents: MakeCards._getCardContents_item.bind(MakeCards), fnGetTags: (item) => { const [typeListText] = Renderer.item.getHtmlAndTextTypes(item); return ["item", Parser.sourceJsonToAbv(item.source), ...typeListText] } }, spell: { searchTitle: "Spell", pageTitle: "Spells", page: UrlUtil.PG_SPELLS, colorDefault: "#4a6898", iconDefault: "magic-swirl", pFnSearch: SearchWidget.pGetUserSpellSearch, fnGetContents: MakeCards._getCardContents_spell.bind(MakeCards), fnGetTags: (spell) => { const out = ["spell", Parser.sourceJsonToAbv(spell.source), Parser.spLevelToFullLevelText(spell.level), Parser.spSchoolAbvToFull(spell.school)]; if (spell.duration.filter(d => d.concentration).length) out.push("concentration"); return out; } } // TODO add more entities }; MakeCards._ = null; window.addEventListener("load", () => MakeCards.pInit()); MakeCards.utils = class { static async pLoadReducedData () { const data = await DataUtil.loadJSON(`${Renderer.get().baseUrl}data/makecards.json`); data.reducedItemProperty.forEach(p => MakeCards.utils._addItemProperty(p)); data.reducedItemType.forEach(t => { if (t.abbreviation === "SHP") { const cpy = MiscUtil.copy(t); cpy.abbreviation = "AIR"; MakeCards.utils._addItemType(cpy); } MakeCards.utils._addItemType(t); }); } // region items static _addItemProperty (p) { if (MakeCards.utils.itemPropertyMap[p.abbreviation]) return; if (p.entries) { MakeCards.utils.itemPropertyMap[p.abbreviation] = p.name ? MiscUtil.copy(p) : { name: p.entries[0].name.toLowerCase(), entries: p.entries }; } else MakeCards.utils.itemPropertyMap[p.abbreviation] = {}; } static _addItemType (t) { if (MakeCards.utils.itemTypeMap[t.abbreviation]) return; MakeCards.utils.itemTypeMap[t.abbreviation] = t.name ? MiscUtil.copy(t) : { name: t.entries[0].name.toLowerCase(), entries: t.entries }; } static enhanceItemAlt (item) { delete item._fullEntries; if (item.type && (MakeCards.utils.itemPropertyMap[item.type] || Renderer.item.typeMap[item.type])) { Renderer.item._initFullEntries(item); (((MakeCards.utils.itemTypeMap[item.type] || Renderer.item.typeMap[item.type]) || {}).entries || []).forEach(e => item._fullEntries.push(e)); } if (item.property) { item.property.forEach(p => { if (MakeCards.utils.itemPropertyMap[p]) { if (MakeCards.utils.itemPropertyMap[p].entries) { Renderer.item._initFullEntries(item); MakeCards.utils.itemPropertyMap[p].entries.forEach(e => item._fullEntries.push(e)); } } else if (Renderer.item.propertyMap[p].entries) { Renderer.item._initFullEntries(item); Renderer.item.propertyMap[p].entries.forEach(e => item._fullEntries.push(e)); } }); } if (item.type === "LA" || item.type === "MA" || item.type === "HA") { if (item.resist) { Renderer.item._initFullEntries(item); item._fullEntries.push(`Resistance to ${item.resist} damage.`); } if (item.stealth) { Renderer.item._initFullEntries(item); item._fullEntries.push("Disadvantage on Stealth (Dexterity) checks."); } if (item.type === "HA" && item.strength) { Renderer.item._initFullEntries(item); item._fullEntries.push(`Speed reduced by 10 feet if Strength score less than ${item.strength}.`); } } else if (item.resist) { if (item.type === "P") { Renderer.item._initFullEntries(item); item._fullEntries.push(`Resistance to ${item.resist} damage for 1 hour.`); } if (item.type === "RG") { Renderer.item._initFullEntries(item); item._fullEntries.push(`Resistance to ${item.resist} damage.`); } } if (item.type === "SCF") { if (item.scfType === "arcane") { Renderer.item._initFullEntries(item); item._fullEntries.push("A sorcerer, warlock, or wizard can use this item as a spellcasting focus."); } if (item.scfType === "druid") { Renderer.item._initFullEntries(item); item._fullEntries.push("A druid can use this item as a spellcasting focus."); } if (item.scfType === "holy") { Renderer.item._initFullEntries(item); item._fullEntries.push("A cleric or paladin can use this item as a spellcasting focus."); } } } // endregion }; MakeCards.utils.itemTypeMap = {}; MakeCards.utils.itemPropertyMap = {};
import CollectionBrowsePage from '@/pages/CollectionBrowsePage' import render from '../../test-utils/render' describe('CollectionBrowsePage', () => { const options = { propsData: { query: { provider: 'foo', }, }, mocks: { $store: { state: { query: { q: 'foo', provider: 'foo', }, }, dispatch: jest.fn(), }, }, } it('should render correct contents', () => { const wrapper = render(CollectionBrowsePage) expect(wrapper.find({ name: 'header-section' }).vm).toBeDefined() expect(wrapper.find({ name: 'footer-section' }).vm).toBeDefined() }) it('should dispatch FETCH_COLLECTION_IMAGES', () => { const params = { foo: 'bar' } const wrapper = render(CollectionBrowsePage, options) wrapper.vm.getImages(params) expect(options.mocks.$store.dispatch).toHaveBeenCalledWith( 'FETCH_COLLECTION_IMAGES', params ) }) })
/*------------------------------------------------------------------------------- # Copyright © 2019 by California Community Colleges Chancellor's Office # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy # of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. #------------------------------------------------------------------------------*/ (function () { angular.module('CCC.AsmtPlayer').service('ToolsPermissionService', [ '$rootScope', function ($rootScope) { var ToolsPermissionService; /*============== PRIVATE VARIABLES ==============*/ var permissions = { allowCalculator: false, allowDictionary: false, allowThesaurus: false }; var clearAllPermissions = function () { for (var key in permissions) { if (permissions.hasOwnProperty(key)) { permissions[key] = false; } } }; var setPermissionsForTaskSet = function (task) { clearAllPermissions(); _.each(task.itemSessions, function (itemSession) { var tools = itemSession.assessmentItem.tools ? itemSession.assessmentItem.tools : {}; _.each(tools, function (toolValue, toolKey) { permissions[toolKey] = permissions[toolKey] || (typeof toolValue === 'string' ? (toolValue.toLowerCase() === 'yes') : false); }); }); }; /*============== SERVICE DEFINITION ==============*/ ToolsPermissionService = { getPermissions: function () { // for a little extra security just send a copy of the object so nobody can change it return $.extend({}, permissions); }, setPermissionsForTaskSet: function (task) { setPermissionsForTaskSet(task); } }; return ToolsPermissionService; } ]); })();
/*! ========================================================= * Argon Dashboard React - v1.1.0 ========================================================= * Product Page: https://www.creative-tim.com/product/argon-dashboard-react * Copyright 2019 Creative Tim (https://www.creative-tim.com) * Licensed under MIT (https://github.com/creativetimofficial/argon-dashboard-react/blob/master/LICENSE.md) * Coded by Creative Tim ========================================================= * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. */ import Signup from "containers/auth/signup"; import Signin from "containers/auth/signin"; const routes = [ { path: "/login", name: "Signin", icon: "ni ni-key-25 text-info", component: Signin, layout: "/auth" }, { path: "/signup", name: "Signup", icon: "ni ni-circle-08 text-pink", component: Signup, layout: "/auth" } ]; export default routes;
module.exports = function(config) { config.set({ frameworks: ["mocha", "chai"], files: ["js/todos.js", "test/todo.test.js"], browsers: ["PhantomJS"], singleRun: true }); };
var iTunes = require('../') , conn = null , t1 , t2 iTunes.createConnection(onConn); function onConn (err, c) { if (err) throw err; conn = c; conn.selection( onSelection ); conn.selection(0, onFirstSelection); } function onSelection (err, selection) { if (err) throw err; if (selection.length > 0) { console.log("%d Selected Tracks:", selection.length); t1 = selection[0]; selection.forEach(function (track, i) { console.log('Track %d:', i); console.log(' ', track); console.log(' ', track.constructor.name); }); } else { console.log('There are no tracks currently selected...'); } } function onFirstSelection (err, track) { if (err) throw err; t2 = track; if (!track) console.log('There is no track currently selected...'); console.log(track); } process.on('exit', function() { console.error("Referential Equality Test:", t1 === t2); });
/** * Created by Raphael Karanja on 2019-01-04. */ import React, {Component} from 'react'; import AuthorStore from '../../../../Flux/stores/AuthorStores'; import AuthorActions from '../../../../Flux/actions/AuthorActions' export default class extends Component { constructor(props) { super(props); this.state = { author: {}, authorId: this.props.match.params.id }; this._onChange = this._onChange.bind(this); this.deleteAuthor = this.deleteAuthor.bind(this); this.redirect = this.redirect.bind(this); } componentDidMount() { this.getAuthor(); AuthorStore.addChangeListener(this._onChange); } componentWillUnmount() { AuthorStore.removeChangeListener(this._onChange); }; _onChange() { this.getAuthor(); this.redirect(); } redirect(){ if(!this.author) { this.props.history.push('/authors'); } } getAuthor(){ let {authorId} =this.state; if (authorId) { let author = AuthorStore.getAuthorById(authorId); this.setState({author}); } } deleteAuthor(){ let {authorId} =this.state; if(authorId){ AuthorActions.deleteAuthor(authorId) } } render() { const {author} = this.state; return( <div> <table className="table table-bordered"> <thead> <tr> <th>ID</th> <th>Name</th> <th>eMail</th> <th>Action</th> </tr> </thead> <tbody> <tr> <td>{author.firstname}</td> <td>{author.lastname}</td> <td>{author.email}</td> <td> <button type="button" className="btn btn-outline-info btn-sm ">Edit</button> <button type="button" className="btn btn-outline-danger btn-sm " onClick={this.deleteAuthor}>Delete</button> </td> </tr> </tbody> </table> </div> ); } }
import _sliced_to_array from "@swc/helpers/src/_sliced_to_array.mjs"; var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined; try { //@target: ES6 for(var _iterator = X[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){ var _value = _sliced_to_array(_step.value, 2), a = _value[0], b = _value[1]; } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally{ try { if (!_iteratorNormalCompletion && _iterator.return != null) { _iterator.return(); } } finally{ if (_didIteratorError) { throw _iteratorError; } } }
'use strict'; import galleryItemsData from './gallery-items.js'; const gallery = document.querySelector('.js-gallery'); const test = createGallery(galleryItemsData); function createGallery(galleryItemsData) { galleryItemsData.forEach(function(galleryItemData, i) { const galleryItem = document.createElement('li'); galleryItem.classList.add('gallery__item'); gallery.appendChild(galleryItem); const previewLink = document.createElement('a'); previewLink.classList.add('gallery__link'); previewLink.setAttribute('href', galleryItemsData[i].original); galleryItem.appendChild(previewLink); const galleryImg = document.createElement('img'); galleryImg.classList.add('gallery__image'); galleryImg.setAttribute('src', galleryItemsData[i].preview); galleryImg.setAttribute('data-source', galleryItemsData[i].original); galleryImg.setAttribute('alt', galleryItemsData[i].description); previewLink.appendChild(galleryImg); const galleryIcon = document.createElement('span'); galleryIcon.classList.add('gallery__icon'); galleryItem.appendChild(galleryIcon); const icons = document.createElement('i'); icons.classList.add('material-icons'); icons.textContent = 'zoom_out_map'; galleryIcon.appendChild(icons); }); } gallery.addEventListener('click', openModal); const overlay = document.querySelector('.overlay'); const overlayImg = document.querySelector('.overlay-img'); function openModal(e) { e.preventDefault(); if (e.target === e.currentTarget) { return; } overlay.classList.add('is-visible'); overlayImg.setAttribute('src', e.target.dataset.source); window.addEventListener('keydown', handleKeyPress); } /// Закрыть модальное окно const closeModalBTN = document.querySelector( 'button[data-action="close-modal"]', ); closeModalBTN.addEventListener('click', closeModal); overlay.addEventListener('click', handleBackDropClick); function closeModal() { overlay.classList.remove('is-visible'); window.removeEventListener('keydown', handleKeyPress); overlayImg.removeAttribute('src'); } // Escape function handleKeyPress(e) { if (e.code !== 'Escape') { return; } closeModal(); } function handleBackDropClick(e) { if (e.target !== e.currentTarget) { return; } closeModal(); }
/* eslint-disable max-len */ const { allValues, edgeGap, edgeSiteMax, gapSiteMax, edgeOnly, gapOnly, siteMaxOnly, columnsOnly, customProperties, } = require('./sharedConfigs'); const Columns = require('../Columns'); /** * Test a method of the Columns class. * * @param {Object} testConfig { * @param {String} testConfig.description The test suite description. * @param {Array} testConfig.tests An array of Test Objects * } */ const testColumnsMethod = (testConfig) => { describe(testConfig.description, () => { /** * Run each test. * * @param {Object} unitTest { * @param {String} unitTest.description The test description. * @param {String} unitTest.actual The test's plugin output. * @param {String} unitTest.expected The expected plugin output. * } */ const reducedTests = testConfig.tests.reduce((acc, test) => { // TODO: Use Object.values(test) once Node v6 support is dropped. const testValues = Object.keys(test).map(key => test[key]); return [...acc, testValues]; }, []); test.each(reducedTests)( '%s', (theTest) => { expect(theTest.actual).toEqual(theTest.expected); }, ); }); }; /** * Separate a CSS length value's number from its units. */ testColumnsMethod({ description: "Separate a CSS length value's number from its units", tests: [ { description: 'Separates a `px` value from its units', actual: Columns.splitCssUnit('10px'), expected: [10, 'px'], }, { description: 'Separates a `rem` value from its units', actual: Columns.splitCssUnit('0.625rem'), expected: [0.625, 'rem'], }, { description: 'Separates a `em` value from its units', actual: Columns.splitCssUnit('2em'), expected: [2, 'em'], }, { description: 'Ignores a unitless value', actual: Columns.splitCssUnit(12), expected: 12, }, ], }); /** * Calculate the shared gap amount to be removed from each column. */ testColumnsMethod({ description: 'Calculate the shared gap amount to be removed from each column', tests: [ { description: 'Calculates a shared gap with `rem` value', actual: new Columns(allValues).getSharedGap(), expected: '0.5859rem', }, { description: 'Calculates a shared gap with `px` value', actual: new Columns(edgeGap).getSharedGap(), expected: '9.1667px', }, { description: 'Calculates a `0` shared gap if a gap option is not declared', actual: new Columns(edgeSiteMax).getSharedGap(), expected: 0, }, { description: 'Builds the shared gap calculation when `gap` is a CSS Custom Property', actual: new Columns(customProperties).getSharedGap(), expected: `(${customProperties.gap} / ${customProperties.columns} * (${customProperties.columns} - 1))`, }, ], }); /** * Round the given number to the specified number of decimal places. */ testColumnsMethod({ description: 'Round the given number to the specified number of decimal places', tests: [ { description: 'Rounds to a single decimal place', actual: Columns.roundToPrecision(1.2345, 1), expected: 1.2, }, { description: 'Rounds to two decimal places', actual: Columns.roundToPrecision(1.2345, 2), expected: 1.23, }, { description: 'Rounds to three decimal places', actual: Columns.roundToPrecision(1.2345, 3), expected: 1.235, }, { description: 'Rounds to four decimal places', actual: Columns.roundToPrecision(1.2345, 4), expected: 1.2345, }, { description: 'Ignores rounding a number shorter than the precision', actual: Columns.roundToPrecision(1.2, 4), expected: 1.2, }, { description: 'Ignores a whole number', actual: Columns.roundToPrecision(1, 3), expected: 1, }, { description: 'Rounds to zero decimal places', actual: Columns.roundToPrecision(1.234, 0), expected: 1, }, { description: 'Ignores rounding a `0`', actual: Columns.roundToPrecision(0, 4), expected: 0, }, { description: 'Rounds a negative number as expected', actual: Columns.roundToPrecision(-1.2345, 2), expected: -1.23, }, ], }); /** * Create the column `calc()` function declaration for each siteMax. */ testColumnsMethod({ description: 'Create the column `calc()` function declaration for each siteMax', tests: [ // ---------- All options { description: 'All options: single column', actual: new Columns(allValues).spanCalc(1), expected: { fluid: 'calc((100vw - 32px * 2) / 16 - 0.5859rem)', full: 'calc((75rem - 32px * 2) / 16 - 0.5859rem)', }, }, { description: 'All options: two columns', actual: new Columns(allValues).spanCalc(2), expected: { fluid: 'calc((((100vw - 32px * 2) / 16 - 0.5859rem) * 2) + 0.625rem)', full: 'calc((((75rem - 32px * 2) / 16 - 0.5859rem) * 2) + 0.625rem)', }, }, { description: 'All options: three columns', actual: new Columns(allValues).spanCalc(4), expected: { fluid: 'calc((((100vw - 32px * 2) / 16 - 0.5859rem) * 4) + 0.625rem * 3)', full: 'calc((((75rem - 32px * 2) / 16 - 0.5859rem) * 4) + 0.625rem * 3)', }, }, { description: 'All options: negative columns', actual: new Columns(allValues).spanCalc(-4), expected: { fluid: 'calc((((100vw - 32px * 2) / 16 - 0.5859rem) * -4) + 0.625rem * -3)', full: 'calc((((75rem - 32px * 2) / 16 - 0.5859rem) * -4) + 0.625rem * -3)', }, }, { description: 'All options: fractional columns (less than 1)', actual: new Columns(allValues).spanCalc(0.5), expected: { fluid: 'calc(((100vw - 32px * 2) / 16 - 0.5859rem) * 0.5)', full: 'calc(((75rem - 32px * 2) / 16 - 0.5859rem) * 0.5)', }, }, { description: 'All options: fractional columns (greater than 1)', actual: new Columns(allValues).spanCalc(1.75), expected: { fluid: 'calc((((100vw - 32px * 2) / 16 - 0.5859rem) * 1.75) + 0.625rem)', full: 'calc((((75rem - 32px * 2) / 16 - 0.5859rem) * 1.75) + 0.625rem)', }, }, { description: 'All options: fractional columns (greater than 2)', actual: new Columns(allValues).spanCalc(2.5), expected: { fluid: 'calc((((100vw - 32px * 2) / 16 - 0.5859rem) * 2.5) + 0.625rem * 2)', full: 'calc((((75rem - 32px * 2) / 16 - 0.5859rem) * 2.5) + 0.625rem * 2)', }, }, // ---------- No siteMax { description: 'Omits a `full` value with no `siteMax` option', actual: new Columns(edgeGap).spanCalc(1), expected: { fluid: 'calc((100vw - 1rem * 2) / 12 - 9.1667px)', }, }, // ---------- No gap { description: 'Omits shared gap for single column with no `gap` option', actual: new Columns(edgeSiteMax).spanCalc(1), expected: { fluid: 'calc((100vw - 1.25rem * 2) / 16)', full: 'calc((1024px - 1.25rem * 2) / 16)', }, }, { description: 'Omits the gap addition wtih no `gap` option', actual: new Columns(edgeSiteMax).spanCalc(2), expected: { fluid: 'calc(((100vw - 1.25rem * 2) / 16) * 2)', full: 'calc(((1024px - 1.25rem * 2) / 16) * 2)', }, }, // ---------- No edge { description: 'Omits the edge subtraction with no `edge` option', actual: new Columns(gapSiteMax).spanCalc(1), expected: { fluid: 'calc(100vw / 16 - 14.0625px)', full: 'calc(60rem / 16 - 14.0625px)', }, }, // ---------- Edges only { description: 'Omits undeclared values from span ouput: `edge` only', actual: new Columns(edgeOnly).spanCalc(1), expected: { fluid: 'calc((100vw - 20px * 2) / 12)', }, }, // ---------- Gap only { description: 'Omits undeclared values from span ouput: `gap` only', actual: new Columns(gapOnly).spanCalc(1), expected: { fluid: 'calc(100vw / 12 - 0.8594rem)', }, }, // ---------- siteMax only { description: 'Omits undeclared values from span ouput: `siteMax` only', actual: new Columns(siteMaxOnly).spanCalc(1), expected: { fluid: 'calc(100vw / 16)', full: 'calc(1200px / 16)', }, }, { description: 'Omits undeclared values from span ouput: `edge` only (multiple columns)', actual: new Columns(siteMaxOnly).spanCalc(5), expected: { fluid: 'calc((100vw / 16) * 5)', full: 'calc((1200px / 16) * 5)', }, }, // ---------- Columns only { description: 'Omits undeclared values from span ouput: `columns` only', actual: new Columns(columnsOnly).spanCalc(1), expected: { fluid: 'calc(100vw / 12)', }, }, { description: 'Omits undeclared values from span ouput: `columns` only (multiple columns)', actual: new Columns(columnsOnly).spanCalc(3), expected: { fluid: 'calc((100vw / 12) * 3)', }, }, // ---------- Custom Properties { description: 'Custom properties used in option values', actual: new Columns(customProperties).spanCalc(3), expected: { fluid: 'calc((((100vw - var(--edge) * 2) / var(--columns) - (var(--gap) / var(--columns) * (var(--columns) - 1))) * 3) + var(--gap) * 2)', full: 'calc((((90rem - var(--edge) * 2) / var(--columns) - (var(--gap) / var(--columns) * (var(--columns) - 1))) * 3) + var(--gap) * 2)', }, }, ], }); /** * Create the offset `calc()` function declaration for each siteMax. */ testColumnsMethod({ description: 'Create the offset `calc()` function declaration for each siteMax', tests: [ // ---------- All options { description: 'All options: single column', actual: new Columns(allValues).offsetCalc(1), expected: { fluid: 'calc(((100vw - 32px * 2) / 16 - 0.5859rem) + 0.625rem)', full: 'calc(((75rem - 32px * 2) / 16 - 0.5859rem) + 0.625rem)', }, }, { description: 'All options: two columns', actual: new Columns(allValues).offsetCalc(2), expected: { fluid: 'calc((((100vw - 32px * 2) / 16 - 0.5859rem) * 2) + 0.625rem * 2)', full: 'calc((((75rem - 32px * 2) / 16 - 0.5859rem) * 2) + 0.625rem * 2)', }, }, { description: 'All options: three columns', actual: new Columns(allValues).offsetCalc(3), expected: { fluid: 'calc((((100vw - 32px * 2) / 16 - 0.5859rem) * 3) + 0.625rem * 3)', full: 'calc((((75rem - 32px * 2) / 16 - 0.5859rem) * 3) + 0.625rem * 3)', }, }, { description: 'All options: negative columns', actual: new Columns(allValues).offsetCalc(-4), expected: { fluid: 'calc((((100vw - 32px * 2) / 16 - 0.5859rem) * -4) + 0.625rem * -4)', full: 'calc((((75rem - 32px * 2) / 16 - 0.5859rem) * -4) + 0.625rem * -4)', }, }, { description: 'All options: fractional columns (less than 1)', actual: new Columns(allValues).offsetCalc(0.75), expected: { fluid: 'calc(((100vw - 32px * 2) / 16 - 0.5859rem) * 0.75)', full: 'calc(((75rem - 32px * 2) / 16 - 0.5859rem) * 0.75)', }, }, { description: 'All options: fractional columns (greater than 1)', actual: new Columns(allValues).offsetCalc(1.5), expected: { fluid: 'calc((((100vw - 32px * 2) / 16 - 0.5859rem) * 1.5) + 0.625rem)', full: 'calc((((75rem - 32px * 2) / 16 - 0.5859rem) * 1.5) + 0.625rem)', }, }, { description: 'All options: fractional columns (greater than 2)', actual: new Columns(allValues).offsetCalc(2.075), expected: { fluid: 'calc((((100vw - 32px * 2) / 16 - 0.5859rem) * 2.075) + 0.625rem * 2)', full: 'calc((((75rem - 32px * 2) / 16 - 0.5859rem) * 2.075) + 0.625rem * 2)', }, }, // ---------- No siteMax { description: 'Omits a `full` value with no `siteMax` option', actual: new Columns(edgeGap).offsetCalc(1), expected: { fluid: 'calc(((100vw - 1rem * 2) / 12 - 9.1667px) + 10px)', }, }, // ---------- No gap { description: 'Omits shared gap for single column with no `gap` option', actual: new Columns(edgeSiteMax).offsetCalc(1), expected: { fluid: 'calc((100vw - 1.25rem * 2) / 16)', full: 'calc((1024px - 1.25rem * 2) / 16)', }, }, { description: 'Omits the gap addition wtih no `gap` option', actual: new Columns(edgeSiteMax).offsetCalc(2), expected: { fluid: 'calc(((100vw - 1.25rem * 2) / 16) * 2)', full: 'calc(((1024px - 1.25rem * 2) / 16) * 2)', }, }, // ---------- No edge { description: 'Omits the edge subtraction with no `edge` option', actual: new Columns(gapSiteMax).offsetCalc(1), expected: { fluid: 'calc((100vw / 16 - 14.0625px) + 15px)', full: 'calc((60rem / 16 - 14.0625px) + 15px)', }, }, // ---------- Edges only { description: 'Omits undeclared values from span ouput: `edge` only', actual: new Columns(edgeOnly).offsetCalc(1), expected: { fluid: 'calc((100vw - 20px * 2) / 12)', }, }, { description: 'Omits undeclared values from span ouput: `edge` only (multiple columns)', actual: new Columns(edgeOnly).offsetCalc(2), expected: { fluid: 'calc(((100vw - 20px * 2) / 12) * 2)', }, }, // ---------- Gap only { description: 'Omits undeclared values from span ouput: `gap` only', actual: new Columns(gapOnly).offsetCalc(1), expected: { fluid: 'calc((100vw / 12 - 0.8594rem) + 0.9375rem)', }, }, // ---------- siteMax only { description: 'Omits undeclared values from span ouput: `siteMax` only', actual: new Columns(siteMaxOnly).offsetCalc(1), expected: { fluid: 'calc(100vw / 16)', full: 'calc(1200px / 16)', }, }, // ---------- Columns only { description: 'Omits undeclared values from span ouput: `columns` only', actual: new Columns(columnsOnly).offsetCalc(1), expected: { fluid: 'calc(100vw / 12)', }, }, { description: 'Omits undeclared values from span ouput: `columns` only (multiple columns)', actual: new Columns(columnsOnly).offsetCalc(4), expected: { fluid: 'calc((100vw / 12) * 4)', }, }, // ---------- Custom Properties { description: 'Custom properties used in option values', actual: new Columns(customProperties).offsetCalc(3), expected: { fluid: 'calc((((100vw - var(--edge) * 2) / var(--columns) - (var(--gap) / var(--columns) * (var(--columns) - 1))) * 3) + var(--gap) * 3)', full: 'calc((((90rem - var(--edge) * 2) / var(--columns) - (var(--gap) / var(--columns) * (var(--columns) - 1))) * 3) + var(--gap) * 3)', }, }, ], });
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.exploreGlobalApiHeaderMetadata = void 0; const constants_1 = require("../constants"); const exploreGlobalApiHeaderMetadata = (metatype) => { const headers = Reflect.getMetadata(constants_1.DECORATORS.API_HEADERS, metatype); return headers ? { root: { parameters: headers }, depth: 1 } : undefined; }; exports.exploreGlobalApiHeaderMetadata = exploreGlobalApiHeaderMetadata;
module.exports = { plugins: [ // require('postcss-import'), // require('postcss-discard-comments')({ removeAll: true }), require('tailwindcss')('./src/styles/tailwind.config.js'), // require('postcss-preset-env')({ stage: 1 }), // require('@fullhuman/postcss-purgecss')({ // content: ['src/**/*.css', 'src/**/*.xml'], // }), // process.env.NODE_ENV != 'development' && require('autoprefixer'), ], }
import React from 'react' import { useSelector, useDispatch } from 'react-redux' import { CHeader, CToggler, CHeaderBrand, CHeaderNav, CHeaderNavItem, CHeaderNavLink, CSubheader, CBreadcrumbRouter, CLink } from '@coreui/react' import CIcon from '@coreui/icons-react' // routes config import routes from '../routes' import { TheHeaderDropdown, TheHeaderDropdownMssg, TheHeaderDropdownNotif, TheHeaderDropdownTasks } from './index' const TheHeader = () => { const dispatch = useDispatch() const sidebarShow = useSelector(state => state.sidebarShow) const toggleSidebar = () => { const val = [true, 'responsive'].includes(sidebarShow) ? false : 'responsive' dispatch({type: 'set', sidebarShow: val}) } const toggleSidebarMobile = () => { const val = [false, 'responsive'].includes(sidebarShow) ? true : 'responsive' dispatch({type: 'set', sidebarShow: val}) } return ( <CHeader withSubheader> <CToggler inHeader className="ml-md-3 d-lg-none" onClick={toggleSidebarMobile} /> <CToggler inHeader className="ml-3 d-md-down-none" onClick={toggleSidebar} /> <CHeaderBrand className="mx-auto d-lg-none" to="/"> <CIcon name="logo" height="48" alt="Logo"/> </CHeaderBrand> <CHeaderNav className="d-md-down-none mr-auto"> <CHeaderNavItem className="px-3" > <CHeaderNavLink to="/dashboard"></CHeaderNavLink> </CHeaderNavItem> <CHeaderNavItem className="px-3"> <CHeaderNavLink to="/users"></CHeaderNavLink> </CHeaderNavItem> <CHeaderNavItem className="px-3"> <CHeaderNavLink></CHeaderNavLink> </CHeaderNavItem> </CHeaderNav> <CHeaderNav className="px-3"> <TheHeaderDropdownNotif/> <TheHeaderDropdownTasks/> <TheHeaderDropdownMssg/> <TheHeaderDropdown/> </CHeaderNav> <CSubheader className="px-3 justify-content-between"> <CBreadcrumbRouter className="border-0 c-subheader-nav m-0 px-0 px-md-3" routes={routes} /> <div className="d-md-down-none mfe-2 c-subheader-nav"> <CLink className="c-subheader-nav-link"href="#"> {/* <CIcon name="cil-speech" alt="Settings" /> */} </CLink> <CLink className="c-subheader-nav-link" aria-current="page" to="/dashboard" > {/* <CIcon name="cil-graph" alt="Dashboard" />&nbsp;Dashboard */} </CLink> <CLink className="c-subheader-nav-link" href="#"> {/* <CIcon name="cil-settings" alt="Settings" />&nbsp;Settings */} </CLink> </div> </CSubheader> </CHeader> ) } export default TheHeader
var mongoose = require('mongoose'); var Schema = mongoose.Schema; var classifiedCategorySchema = new Schema({ name : String, type : String, disableStatus : String, status : String }, { timestamps: true }); var ClassifiedCategory = mongoose.model('ClassifiedCategory',classifiedCategorySchema); module.exports = ClassifiedCategory; /////////////////////////// ADMIN PANEL ///////////////////////// module.exports.addNewClassifiedCategory = function(params,callback){ var new_classified_category = new ClassifiedCategory(params); new_classified_category.save(callback); } module.exports.getAllClassifiedsCategories = function(callback){ ClassifiedCategory.find({status : 'A'},callback); } module.exports.deleteClassifiedCategory = function(id,callback){ ClassifiedCategory.findByIdAndUpdate(id, {status : 'D'},{new:true} ,callback); } module.exports.editClassifiedCategory = function(params,callback){ ClassifiedCategory.findByIdAndUpdate(params.category_id, {name : params.category_name},{new:true} ,callback); } ////////////////////////////////// APP END //////////////////// module.exports.getClassifiedId = function(callback){ ClassifiedCategory.findOne({type : 'birthnewsforbirthdays'},callback); }
//定时 缓存 var MyLocalStorage ={ Cache : { /** * 总容量5M * 存入缓存,支持字符串类型、json对象的存储 * 页面关闭后依然有效 ie7+都有效 * @param key 缓存key * @param stringVal * @time 数字 缓存有效时间(秒) 默认60s * 注:localStorage 方法存储的数据没有时间限制。第二天、第二周或下一年之后,数据依然可用。不能控制缓存时间,故此扩展 * */ put : function(key,stringVal,time){ try{ if (!localStorage) { return false; } if(!time || isNaN(time)){time=1*24*60*60;} var cacheExpireDate = (new Date()-1)+time*1000; var cacheVal = {val:stringVal,exp:cacheExpireDate}; localStorage.setItem(key,JSON.stringify(cacheVal));//存入缓存值 //console.log(key+":存入缓存,"+new Date(cacheExpireDate)+"到期"); }catch(e){} }, /**获取缓存*/ get : function (key){ try{ if(!localStorage){return false;} var cacheVal = localStorage.getItem(key); var result = JSON.parse(cacheVal); var now = new Date()-1; if(!result){return null;}//缓存不存在 if(now>result.exp){//缓存过期 this.remove(key); return ""; } //console.log("get cache:"+key); return result.val; }catch(e){ this.remove(key); return null; } },/**移除缓存,一般情况不手动调用,缓存过期自动调用*/ remove : function(key){ if(!localStorage){return false;} localStorage.removeItem(key); },/**清空所有缓存*/ clear : function(){ if(!localStorage){return false;} localStorage.clear(); } }//end Cache }; export default MyLocalStorage;
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); const assert = require('chai').assert; const process = require('process'); const pip_services3_commons_nodex_1 = require("pip-services3-commons-nodex"); const MqttConnection_1 = require("../../src/connect/MqttConnection"); suite('MqttConnection', () => { let connection; let brokerHost = process.env['MQTT_SERVICE_HOST'] || 'localhost'; let brokerPort = process.env['MQTT_SERVICE_PORT'] || 1883; if (brokerHost == '' && brokerPort == '') { return; } let brokerTopic = process.env['MQTT_TOPIC'] || 'test'; let brokerUser = process.env['MQTT_USER']; let brokerPass = process.env['MQTT_PASS']; let brokerToken = process.env['MQTT_TOKEN']; setup(() => { let config = pip_services3_commons_nodex_1.ConfigParams.fromTuples('topic', brokerTopic, 'connection.protocol', 'mqtt', 'connection.host', brokerHost, 'connection.port', brokerPort, 'credential.username', brokerUser, 'credential.password', brokerPass, 'credential.token', brokerToken); connection = new MqttConnection_1.MqttConnection(); connection.configure(config); }); test('Open/Close', () => __awaiter(void 0, void 0, void 0, function* () { yield connection.open(null); assert.isTrue(connection.isOpen()); assert.isNotNull(connection.getConnection()); yield connection.close(null); assert.isFalse(connection.isOpen()); assert.isNull(connection.getConnection()); })); }); //# sourceMappingURL=MqttConnection.test.js.map
/******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "/packs/"; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = "./app/javascript/packs/weather.js"); /******/ }) /************************************************************************/ /******/ ({ /***/ "./app/javascript/packs/apiLocation.js": /*!*********************************************!*\ !*** ./app/javascript/packs/apiLocation.js ***! \*********************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return getInfoByLocation; }); /* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js"); /* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__); function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } function getInfoByLocation() { return _getInfoByLocation.apply(this, arguments); } function _getInfoByLocation() { _getInfoByLocation = _asyncToGenerator( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee() { var response; return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: console.log('kkk'); _context.next = 3; return fetch('https://ipapi.co/json/', { mode: 'cors' }).then(function (response) { return response.json(); }); case 3: response = _context.sent; return _context.abrupt("return", response); case 5: case "end": return _context.stop(); } } }, _callee); })); return _getInfoByLocation.apply(this, arguments); } /***/ }), /***/ "./app/javascript/packs/apiWeather.js": /*!********************************************!*\ !*** ./app/javascript/packs/apiWeather.js ***! \********************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return getInfo; }); /* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js"); /* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__); function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } function getInfo() { return _getInfo.apply(this, arguments); } function _getInfo() { _getInfo = _asyncToGenerator( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee() { var cityName, key, url, response, _args = arguments; return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: cityName = _args.length > 0 && _args[0] !== undefined ? _args[0] : 'Ontario,CA'; key = 'b9f735ed2467b45a05dde8fe608efd08'; url = "https://api.openweathermap.org/data/2.5/weather?q=".concat(cityName, "&APPID=").concat(key); _context.next = 5; return fetch(url, { mode: 'cors' }).then(function (response) { return response.json(); }); case 5: response = _context.sent; return _context.abrupt("return", response); case 7: case "end": return _context.stop(); } } }, _callee); })); return _getInfo.apply(this, arguments); } /***/ }), /***/ "./app/javascript/packs/weather.js": /*!*****************************************!*\ !*** ./app/javascript/packs/weather.js ***! \*****************************************/ /*! no exports provided */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js"); /* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__); /* harmony import */ var _apiWeather__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./apiWeather */ "./app/javascript/packs/apiWeather.js"); /* harmony import */ var _apiLocation__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./apiLocation */ "./app/javascript/packs/apiLocation.js"); function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } var loadPage = function loadPage(t) { console.log('llll'); var load = /*#__PURE__*/function () { var _ref = _asyncToGenerator( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee(t) { var locData, data; return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: console.log(t); console.log('sssllll'); _context.next = 4; return Object(_apiLocation__WEBPACK_IMPORTED_MODULE_2__["default"])().then(function (response) { var cityName = response.city; return cityName; }); case 4: locData = _context.sent; cityInput = locData; _context.next = 8; return Object(_apiWeather__WEBPACK_IMPORTED_MODULE_1__["default"])(cityInput); case 8: data = _context.sent; console.log(data.name); case 10: case "end": return _context.stop(); } } }, _callee); })); return function load(_x) { return _ref.apply(this, arguments); }; }(); load(); }; console.log('sssllll'); loadPage('lll'); console.log('sssllll'); /***/ }), /***/ "./node_modules/@babel/runtime/regenerator/index.js": /*!**********************************************************!*\ !*** ./node_modules/@babel/runtime/regenerator/index.js ***! \**********************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__(/*! regenerator-runtime */ "./node_modules/regenerator-runtime/runtime.js"); /***/ }), /***/ "./node_modules/regenerator-runtime/runtime.js": /*!*****************************************************!*\ !*** ./node_modules/regenerator-runtime/runtime.js ***! \*****************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright (c) 2014-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var runtime = (function (exports) { "use strict"; var Op = Object.prototype; var hasOwn = Op.hasOwnProperty; var undefined; // More compressible than void 0. var $Symbol = typeof Symbol === "function" ? Symbol : {}; var iteratorSymbol = $Symbol.iterator || "@@iterator"; var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator"; var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; function define(obj, key, value) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); return obj[key]; } try { // IE 8 has a broken Object.defineProperty that only works on DOM objects. define({}, ""); } catch (err) { define = function(obj, key, value) { return obj[key] = value; }; } function wrap(innerFn, outerFn, self, tryLocsList) { // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator. var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator; var generator = Object.create(protoGenerator.prototype); var context = new Context(tryLocsList || []); // The ._invoke method unifies the implementations of the .next, // .throw, and .return methods. generator._invoke = makeInvokeMethod(innerFn, self, context); return generator; } exports.wrap = wrap; // Try/catch helper to minimize deoptimizations. Returns a completion // record like context.tryEntries[i].completion. This interface could // have been (and was previously) designed to take a closure to be // invoked without arguments, but in all the cases we care about we // already have an existing method we want to call, so there's no need // to create a new function object. We can even get away with assuming // the method takes exactly one argument, since that happens to be true // in every case, so we don't have to touch the arguments object. The // only additional allocation required is the completion record, which // has a stable shape and so hopefully should be cheap to allocate. function tryCatch(fn, obj, arg) { try { return { type: "normal", arg: fn.call(obj, arg) }; } catch (err) { return { type: "throw", arg: err }; } } var GenStateSuspendedStart = "suspendedStart"; var GenStateSuspendedYield = "suspendedYield"; var GenStateExecuting = "executing"; var GenStateCompleted = "completed"; // Returning this object from the innerFn has the same effect as // breaking out of the dispatch switch statement. var ContinueSentinel = {}; // Dummy constructor functions that we use as the .constructor and // .constructor.prototype properties for functions that return Generator // objects. For full spec compliance, you may wish to configure your // minifier not to mangle the names of these two functions. function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} // This is a polyfill for %IteratorPrototype% for environments that // don't natively support it. var IteratorPrototype = {}; IteratorPrototype[iteratorSymbol] = function () { return this; }; var getProto = Object.getPrototypeOf; var NativeIteratorPrototype = getProto && getProto(getProto(values([]))); if (NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) { // This environment has a native %IteratorPrototype%; use it instead // of the polyfill. IteratorPrototype = NativeIteratorPrototype; } var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype; GeneratorFunctionPrototype.constructor = GeneratorFunction; GeneratorFunction.displayName = define( GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction" ); // Helper for defining the .next, .throw, and .return methods of the // Iterator interface in terms of a single ._invoke method. function defineIteratorMethods(prototype) { ["next", "throw", "return"].forEach(function(method) { define(prototype, method, function(arg) { return this._invoke(method, arg); }); }); } exports.isGeneratorFunction = function(genFun) { var ctor = typeof genFun === "function" && genFun.constructor; return ctor ? ctor === GeneratorFunction || // For the native GeneratorFunction constructor, the best we can // do is to check its .name property. (ctor.displayName || ctor.name) === "GeneratorFunction" : false; }; exports.mark = function(genFun) { if (Object.setPrototypeOf) { Object.setPrototypeOf(genFun, GeneratorFunctionPrototype); } else { genFun.__proto__ = GeneratorFunctionPrototype; define(genFun, toStringTagSymbol, "GeneratorFunction"); } genFun.prototype = Object.create(Gp); return genFun; }; // Within the body of any async function, `await x` is transformed to // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test // `hasOwn.call(value, "__await")` to determine if the yielded value is // meant to be awaited. exports.awrap = function(arg) { return { __await: arg }; }; function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if (record.type === "throw") { reject(record.arg); } else { var result = record.arg; var value = result.value; if (value && typeof value === "object" && hasOwn.call(value, "__await")) { return PromiseImpl.resolve(value.__await).then(function(value) { invoke("next", value, resolve, reject); }, function(err) { invoke("throw", err, resolve, reject); }); } return PromiseImpl.resolve(value).then(function(unwrapped) { // When a yielded Promise is resolved, its final value becomes // the .value of the Promise<{value,done}> result for the // current iteration. result.value = unwrapped; resolve(result); }, function(error) { // If a rejected Promise was yielded, throw the rejection back // into the async generator function so it can be handled there. return invoke("throw", error, resolve, reject); }); } } var previousPromise; function enqueue(method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function(resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = // If enqueue has been called before, then we want to wait until // all previous Promises have been resolved before calling invoke, // so that results are always delivered in the correct order. If // enqueue has not been called before, then it is important to // call invoke immediately, without waiting on a callback to fire, // so that the async generator function has the opportunity to do // any necessary setup in a predictable way. This predictability // is why the Promise constructor synchronously invokes its // executor callback, and why async functions synchronously // execute code before the first await. Since we implement simple // async functions in terms of async generators, it is especially // important to get this right, even though it requires care. previousPromise ? previousPromise.then( callInvokeWithMethodAndArg, // Avoid propagating failures to Promises returned by later // invocations of the iterator. callInvokeWithMethodAndArg ) : callInvokeWithMethodAndArg(); } // Define the unified helper method that is used to implement .next, // .throw, and .return (see defineIteratorMethods). this._invoke = enqueue; } defineIteratorMethods(AsyncIterator.prototype); AsyncIterator.prototype[asyncIteratorSymbol] = function () { return this; }; exports.AsyncIterator = AsyncIterator; // Note that simple async functions are implemented on top of // AsyncIterator objects; they just return a Promise for the value of // the final result produced by the iterator. exports.async = function(innerFn, outerFn, self, tryLocsList, PromiseImpl) { if (PromiseImpl === void 0) PromiseImpl = Promise; var iter = new AsyncIterator( wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl ); return exports.isGeneratorFunction(outerFn) ? iter // If outerFn is a generator, return the full iterator. : iter.next().then(function(result) { return result.done ? result.value : iter.next(); }); }; function makeInvokeMethod(innerFn, self, context) { var state = GenStateSuspendedStart; return function invoke(method, arg) { if (state === GenStateExecuting) { throw new Error("Generator is already running"); } if (state === GenStateCompleted) { if (method === "throw") { throw arg; } // Be forgiving, per 25.3.3.3.3 of the spec: // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume return doneResult(); } context.method = method; context.arg = arg; while (true) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if (context.method === "next") { // Setting context._sent for legacy support of Babel's // function.sent implementation. context.sent = context._sent = context.arg; } else if (context.method === "throw") { if (state === GenStateSuspendedStart) { state = GenStateCompleted; throw context.arg; } context.dispatchException(context.arg); } else if (context.method === "return") { context.abrupt("return", context.arg); } state = GenStateExecuting; var record = tryCatch(innerFn, self, context); if (record.type === "normal") { // If an exception is thrown from innerFn, we leave state === // GenStateExecuting and loop back for another invocation. state = context.done ? GenStateCompleted : GenStateSuspendedYield; if (record.arg === ContinueSentinel) { continue; } return { value: record.arg, done: context.done }; } else if (record.type === "throw") { state = GenStateCompleted; // Dispatch the exception by looping back around to the // context.dispatchException(context.arg) call above. context.method = "throw"; context.arg = record.arg; } } }; } // Call delegate.iterator[context.method](context.arg) and handle the // result, either by returning a { value, done } result from the // delegate iterator, or by modifying context.method and context.arg, // setting context.delegate to null, and returning the ContinueSentinel. function maybeInvokeDelegate(delegate, context) { var method = delegate.iterator[context.method]; if (method === undefined) { // A .throw or .return when the delegate iterator has no .throw // method always terminates the yield* loop. context.delegate = null; if (context.method === "throw") { // Note: ["return"] must be used for ES3 parsing compatibility. if (delegate.iterator["return"]) { // If the delegate iterator has a return method, give it a // chance to clean up. context.method = "return"; context.arg = undefined; maybeInvokeDelegate(delegate, context); if (context.method === "throw") { // If maybeInvokeDelegate(context) changed context.method from // "return" to "throw", let that override the TypeError below. return ContinueSentinel; } } context.method = "throw"; context.arg = new TypeError( "The iterator does not provide a 'throw' method"); } return ContinueSentinel; } var record = tryCatch(method, delegate.iterator, context.arg); if (record.type === "throw") { context.method = "throw"; context.arg = record.arg; context.delegate = null; return ContinueSentinel; } var info = record.arg; if (! info) { context.method = "throw"; context.arg = new TypeError("iterator result is not an object"); context.delegate = null; return ContinueSentinel; } if (info.done) { // Assign the result of the finished delegate to the temporary // variable specified by delegate.resultName (see delegateYield). context[delegate.resultName] = info.value; // Resume execution at the desired location (see delegateYield). context.next = delegate.nextLoc; // If context.method was "throw" but the delegate handled the // exception, let the outer generator proceed normally. If // context.method was "next", forget context.arg since it has been // "consumed" by the delegate iterator. If context.method was // "return", allow the original .return call to continue in the // outer generator. if (context.method !== "return") { context.method = "next"; context.arg = undefined; } } else { // Re-yield the result returned by the delegate method. return info; } // The delegate iterator is finished, so forget it and continue with // the outer generator. context.delegate = null; return ContinueSentinel; } // Define Generator.prototype.{next,throw,return} in terms of the // unified ._invoke helper method. defineIteratorMethods(Gp); define(Gp, toStringTagSymbol, "Generator"); // A Generator should always return itself as the iterator object when the // @@iterator function is called on it. Some browsers' implementations of the // iterator prototype chain incorrectly implement this, causing the Generator // object to not be returned from this call. This ensures that doesn't happen. // See https://github.com/facebook/regenerator/issues/274 for more details. Gp[iteratorSymbol] = function() { return this; }; Gp.toString = function() { return "[object Generator]"; }; function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; if (1 in locs) { entry.catchLoc = locs[1]; } if (2 in locs) { entry.finallyLoc = locs[2]; entry.afterLoc = locs[3]; } this.tryEntries.push(entry); } function resetTryEntry(entry) { var record = entry.completion || {}; record.type = "normal"; delete record.arg; entry.completion = record; } function Context(tryLocsList) { // The root entry object (effectively a try statement without a catch // or a finally block) gives us a place to store values thrown from // locations where there is no enclosing try statement. this.tryEntries = [{ tryLoc: "root" }]; tryLocsList.forEach(pushTryEntry, this); this.reset(true); } exports.keys = function(object) { var keys = []; for (var key in object) { keys.push(key); } keys.reverse(); // Rather than returning an object with a next method, we keep // things simple and return the next function itself. return function next() { while (keys.length) { var key = keys.pop(); if (key in object) { next.value = key; next.done = false; return next; } } // To avoid creating an additional object, we just hang the .value // and .done properties off the next function object itself. This // also ensures that the minifier will not anonymize the function. next.done = true; return next; }; }; function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) { return iteratorMethod.call(iterable); } if (typeof iterable.next === "function") { return iterable; } if (!isNaN(iterable.length)) { var i = -1, next = function next() { while (++i < iterable.length) { if (hasOwn.call(iterable, i)) { next.value = iterable[i]; next.done = false; return next; } } next.value = undefined; next.done = true; return next; }; return next.next = next; } } // Return an iterator with no values. return { next: doneResult }; } exports.values = values; function doneResult() { return { value: undefined, done: true }; } Context.prototype = { constructor: Context, reset: function(skipTempReset) { this.prev = 0; this.next = 0; // Resetting context._sent for legacy support of Babel's // function.sent implementation. this.sent = this._sent = undefined; this.done = false; this.delegate = null; this.method = "next"; this.arg = undefined; this.tryEntries.forEach(resetTryEntry); if (!skipTempReset) { for (var name in this) { // Not sure about the optimal order of these conditions: if (name.charAt(0) === "t" && hasOwn.call(this, name) && !isNaN(+name.slice(1))) { this[name] = undefined; } } } }, stop: function() { this.done = true; var rootEntry = this.tryEntries[0]; var rootRecord = rootEntry.completion; if (rootRecord.type === "throw") { throw rootRecord.arg; } return this.rval; }, dispatchException: function(exception) { if (this.done) { throw exception; } var context = this; function handle(loc, caught) { record.type = "throw"; record.arg = exception; context.next = loc; if (caught) { // If the dispatched exception was caught by a catch block, // then let that catch block handle the exception normally. context.method = "next"; context.arg = undefined; } return !! caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; var record = entry.completion; if (entry.tryLoc === "root") { // Exception thrown outside of any try block that could handle // it, so set the completion value of the entire function to // throw the exception. return handle("end"); } if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, "catchLoc"); var hasFinally = hasOwn.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) { return handle(entry.catchLoc, true); } else if (this.prev < entry.finallyLoc) { return handle(entry.finallyLoc); } } else if (hasCatch) { if (this.prev < entry.catchLoc) { return handle(entry.catchLoc, true); } } else if (hasFinally) { if (this.prev < entry.finallyLoc) { return handle(entry.finallyLoc); } } else { throw new Error("try statement without catch or finally"); } } } }, abrupt: function(type, arg) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { var finallyEntry = entry; break; } } if (finallyEntry && (type === "break" || type === "continue") && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc) { // Ignore the finally entry if control is not jumping to a // location outside the try/catch block. finallyEntry = null; } var record = finallyEntry ? finallyEntry.completion : {}; record.type = type; record.arg = arg; if (finallyEntry) { this.method = "next"; this.next = finallyEntry.finallyLoc; return ContinueSentinel; } return this.complete(record); }, complete: function(record, afterLoc) { if (record.type === "throw") { throw record.arg; } if (record.type === "break" || record.type === "continue") { this.next = record.arg; } else if (record.type === "return") { this.rval = this.arg = record.arg; this.method = "return"; this.next = "end"; } else if (record.type === "normal" && afterLoc) { this.next = afterLoc; } return ContinueSentinel; }, finish: function(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) { this.complete(entry.completion, entry.afterLoc); resetTryEntry(entry); return ContinueSentinel; } } }, "catch": function(tryLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc === tryLoc) { var record = entry.completion; if (record.type === "throw") { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } // The context.catch method must only be called with a location // argument that corresponds to a known catch block. throw new Error("illegal catch attempt"); }, delegateYield: function(iterable, resultName, nextLoc) { this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }; if (this.method === "next") { // Deliberately forget the last sent value so that we don't // accidentally pass it on to the delegate. this.arg = undefined; } return ContinueSentinel; } }; // Regardless of whether this script is executing as a CommonJS module // or not, return the runtime object so that we can declare the variable // regeneratorRuntime in the outer scope, which allows this module to be // injected easily by `bin/regenerator --include-runtime script.js`. return exports; }( // If this script is executing as a CommonJS module, use module.exports // as the regeneratorRuntime namespace. Otherwise create a new empty // object. Either way, the resulting object will be used to initialize // the regeneratorRuntime variable at the top of this file. true ? module.exports : undefined )); try { regeneratorRuntime = runtime; } catch (accidentalStrictMode) { // This module should not be running in strict mode, so the above // assignment should always work unless something is misconfigured. Just // in case runtime.js accidentally runs in strict mode, we can escape // strict mode using a global Function call. This could conceivably fail // if a Content Security Policy forbids using Function, but in that case // the proper solution is to fix the accidental strict mode problem. If // you've misconfigured your bundler to force strict mode and applied a // CSP to forbid Function, and you're not willing to fix either of those // problems, please detail your unique predicament in a GitHub issue. Function("r", "regeneratorRuntime = r")(runtime); } /***/ }) /******/ }); //# sourceMappingURL=weather-f4f5e6c985196e7db782.js.map
import { __assign } from "tslib"; import * as React from 'react'; import { StyledIconBase } from '@styled-icons/styled-icon'; export var SadCry = React.forwardRef(function (props, ref) { var attrs = { "fill": "currentColor", "xmlns": "http://www.w3.org/2000/svg", }; return (React.createElement(StyledIconBase, __assign({ iconAttrs: attrs, iconVerticalAlign: "-.125em", iconViewBox: "0 0 496 512" }, props, { ref: ref }), React.createElement("path", { fill: "currentColor", d: "M248 8C111 8 0 119 0 256s111 248 248 248 248-111 248-248S385 8 248 8zm144 386.4V280c0-13.2-10.8-24-24-24s-24 10.8-24 24v151.4C315.5 447 282.8 456 248 456s-67.5-9-96-24.6V280c0-13.2-10.8-24-24-24s-24 10.8-24 24v114.4c-34.6-36-56-84.7-56-138.4 0-110.3 89.7-200 200-200s200 89.7 200 200c0 53.7-21.4 102.5-56 138.4zM205.8 234.5c4.4-2.4 6.9-7.4 6.1-12.4-4-25.2-34.2-42.1-59.8-42.1s-55.9 16.9-59.8 42.1c-.8 5 1.7 10 6.1 12.4 4.4 2.4 9.9 1.8 13.7-1.6l9.5-8.5c14.8-13.2 46.2-13.2 61 0l9.5 8.5c2.5 2.3 7.9 4.8 13.7 1.6zM344 180c-25.7 0-55.9 16.9-59.8 42.1-.8 5 1.7 10 6.1 12.4 4.5 2.4 9.9 1.8 13.7-1.6l9.5-8.5c14.8-13.2 46.2-13.2 61 0l9.5 8.5c2.5 2.2 8 4.7 13.7 1.6 4.4-2.4 6.9-7.4 6.1-12.4-3.9-25.2-34.1-42.1-59.8-42.1zm-96 92c-30.9 0-56 28.7-56 64s25.1 64 56 64 56-28.7 56-64-25.1-64-56-64z", key: "k0" }))); }); SadCry.displayName = 'SadCry'; export var SadCryDimensions = { height: undefined, width: undefined };
'use strict'; process.env.SECRET = "toes"; const dotenv = require('dotenv'); dotenv.config(); const server = require('../src/server.js').server; const supergoose = require('@code-fellows/supergoose'); const mockRequest = supergoose(server); const middleware = require('../src/auth/middleware/bearer.js'); const Users = require('../src/auth/models/users-model.js'); const jwt = require('jsonwebtoken'); let users = { admin: { username: 'admin', password: 'password' }, }; // Pre-load our database with fake users beforeAll(async (done) => { await new Users(users.admin).save(); done(); }); describe('Auth Middleware', () => { // Mock the express req/res/next that we need for each middleware call const req = {}; const res = { status: jest.fn(() => res), send: jest.fn(() => res) } const next = jest.fn(); describe('user authentication', () => { it('fails a login for a user (admin) with an incorrect token', () => { req.headers = { authorization: 'Bearer thisisabadtoken', }; return middleware(req, res, next) .then(() => { expect(next).not.toHaveBeenCalled(); expect(res.status).toHaveBeenCalledWith(403); }); }); it('logs in a user with a proper token', () => { const user = { username: 'admin' }; const token = jwt.sign(user, process.env.SECRET); req.headers = { authorization: `Bearer ${token}`, }; return middleware(req, res, next) .then(() => { expect(next).toHaveBeenCalledWith(); }); }); }); });
const { ImageFragment } = require('../image/index.js'); const ProductsFragment = ` fragment ProductsFragment on WpProduct { id productId nodeType link description galleryImages { nodes { id title altText mediaItemUrl } } image { ...ImageFragment } productCategories { nodes { id name } } ... on WpSimpleProduct { id name price } ... on WpVariableProduct { id name price variations { nodes { id variationId attributes { nodes { attributeId name value } } } } } ... on WpExternalProduct { id name price externalUrl } ... on WpGroupProduct { id name products { nodes { ... on WpSimpleProduct { id name price } } } } } ${ ImageFragment } `; module.exports.ProductsFragment = ProductsFragment;
import * as React from "react"; import PropTypes from "prop-types"; import { v4 } from "uuid"; import { GatsbyImage } from "gatsby-plugin-image"; const Gallery = ({ images }) => ( <div> {images.map((image) => ( <div key={v4()}> {image?.url ? ( <img src={image} objectFit={"cover"} objectPosition={"top left"} style={{ gridArea: "1/1", // You can set a maximum height for the image, if you wish. height: "400px", width: "100%", }} // You can optionally force an aspect ratio for the generated image aspectratio={3 / 1} // This is a presentational image, so the alt should be an empty string alt="" formats={["auto", "webp", "avif"]} /> ) : ( <GatsbyImage image={image} objectFit={"cover"} objectPosition={"top left"} style={{ gridArea: "1/1", // You can set a maximum height for the image, if you wish. maxHeight: "400px", }} layout="fullWidth" // You can optionally force an aspect ratio for the generated image aspectratio={3 / 1} // This is a presentational image, so the alt should be an empty string alt="" formats={["auto", "webp", "avif"]} /> )} </div> ))} </div> ); Gallery.propTypes = { images: PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.object, PropTypes.string])), title: PropTypes.string, discription: PropTypes.string, }; export default Gallery;
/** * @author yamahigashi https://github.com/yamahigashi * * This loader loads FBX file in *ASCII and version 7 format*. * * Support * - mesh * - skinning * - normal / uv * * Not Support * - material * - texture * - morph */ var THREE = require('../three.js'); ( function() { THREE.FBXLoader = function ( showStatus, manager ) { THREE.Loader.call( this, showStatus ); this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; this.textureLoader = null; this.textureBasePath = null; }; THREE.FBXLoader.prototype = Object.create( THREE.Loader.prototype ); THREE.FBXLoader.prototype.constructor = THREE.FBXLoader; THREE.FBXLoader.prototype.load = function ( url, onLoad, onProgress, onError ) { var scope = this; var loader = new THREE.XHRLoader( scope.manager ); // loader.setCrossOrigin( this.crossOrigin ); loader.load( url, function ( text ) { if ( ! scope.isFbxFormatASCII( text ) ) { console.warn( 'FBXLoader: !!! FBX Binary format not supported !!!' ); } else if ( ! scope.isFbxVersionSupported( text ) ) { console.warn( 'FBXLoader: !!! FBX Version below 7 not supported !!!' ); } else { scope.textureBasePath = scope.extractUrlBase( url ); onLoad( scope.parse( text ) ); } }, onProgress, onError ); }; THREE.FBXLoader.prototype.setCrossOrigin = function ( value ) { this.crossOrigin = value; }; THREE.FBXLoader.prototype.isFbxFormatASCII = function ( body ) { CORRECT = [ 'K', 'a', 'y', 'd', 'a', 'r', 'a', '\\', 'F', 'B', 'X', '\\', 'B', 'i', 'n', 'a', 'r', 'y', '\\', '\\' ]; var cursor = 0; var read = function ( offset ) { var result = body[ offset - 1 ]; body = body.slice( cursor + offset ); cursor ++; return result; }; for ( var i = 0; i < CORRECT.length; ++ i ) { num = read( 1 ); if ( num == CORRECT[ i ] ) { return false; } } return true; }; THREE.FBXLoader.prototype.isFbxVersionSupported = function ( body ) { var versionExp = /FBXVersion: (\d+)/; match = body.match( versionExp ); if ( match ) { var version = parseInt( match[ 1 ] ); console.log( 'FBXLoader: FBX version ' + version ); return version >= 7000; } return false; }; THREE.FBXLoader.prototype.parse = function ( text ) { var scope = this; console.time( 'FBXLoader' ); console.time( 'FBXLoader: TextParser' ); var nodes = new FBXParser().parse( text ); console.timeEnd( 'FBXLoader: TextParser' ); console.time( 'FBXLoader: ObjectParser' ); scope.hierarchy = ( new Bones() ).parseHierarchy( nodes ); scope.weights = ( new Weights() ).parse( nodes, scope.hierarchy ); scope.animations = ( new Animation() ).parse( nodes, scope.hierarchy ); scope.textures = ( new Textures() ).parse( nodes, scope.hierarchy ); console.timeEnd( 'FBXLoader: ObjectParser' ); console.time( 'FBXLoader: GeometryParser' ); geometries = this.parseGeometries( nodes ); console.timeEnd( 'FBXLoader: GeometryParser' ); var container = new THREE.Group(); for ( var i = 0; i < geometries.length; ++ i ) { if ( geometries[ i ] === undefined ) { continue; } container.add( geometries[ i ] ); //wireframe = new THREE.WireframeHelper( geometries[i], 0x00ff00 ); //container.add( wireframe ); //vnh = new THREE.VertexNormalsHelper( geometries[i], 0.6 ); //container.add( vnh ); //skh = new THREE.SkeletonHelper( geometries[i] ); //container.add( skh ); // container.add( new THREE.BoxHelper( geometries[i] ) ); } console.timeEnd( 'FBXLoader' ); return container; }; THREE.FBXLoader.prototype.parseGeometries = function ( node ) { // has not geo, return [] if ( ! ( 'Geometry' in node.Objects.subNodes ) ) { return []; } // has many var geoCount = 0; for ( var geo in node.Objects.subNodes.Geometry ) { if ( geo.match( /^\d+$/ ) ) { geoCount ++; } } var res = []; if ( geoCount > 0 ) { for ( geo in node.Objects.subNodes.Geometry ) { if ( node.Objects.subNodes.Geometry[ geo ].attrType === 'Mesh' ) { res.push( this.parseGeometry( node.Objects.subNodes.Geometry[ geo ], node ) ); } } } else { res.push( this.parseGeometry( node.Objects.subNodes.Geometry, node ) ); } return res; }; THREE.FBXLoader.prototype.parseGeometry = function ( node, nodes ) { geo = ( new Geometry() ).parse( node ); geo.addBones( this.hierarchy.hierarchy ); //* var geometry = new THREE.BufferGeometry(); geometry.name = geo.name; geometry.addAttribute( 'position', new THREE.BufferAttribute( new Float32Array( geo.vertices ), 3 ) ); if ( geo.normals !== undefined && geo.normals.length > 0 ) { geometry.addAttribute( 'normal', new THREE.BufferAttribute( new Float32Array( geo.normals ), 3 ) ); } if ( geo.uvs !== undefined && geo.uvs.length > 0 ) { geometry.addAttribute( 'uv', new THREE.BufferAttribute( new Float32Array( geo.uvs ), 2 ) ); } if ( geo.indices !== undefined && geo.indices.length > 65535 ) { geometry.setIndex( new THREE.BufferAttribute( new Uint32Array( geo.indices ), 1 ) ); } else if ( geo.indices !== undefined ) { geometry.setIndex( new THREE.BufferAttribute( new Uint16Array( geo.indices ), 1 ) ); } geometry.verticesNeedUpdate = true; geometry.computeBoundingSphere(); geometry.computeBoundingBox(); // TODO: texture & material support var texture; var texs = this.textures.getById( nodes.searchConnectionParent( geo.id ) ); if ( texs !== undefined && texs.length > 0 ) { if ( this.textureLoader === null ) { this.textureLoader = new THREE.TextureLoader(); } texture = this.textureLoader.load( this.textureBasePath + '/' + texs[ 0 ].fileName ); } var material; if ( texture !== undefined ) { material = new THREE.MeshBasicMaterial( { map: texture } ); } else { material = new THREE.MeshBasicMaterial( { color: 0x3300ff } ); } geometry = new THREE.Geometry().fromBufferGeometry( geometry ); geometry.bones = geo.bones; geometry.skinIndices = this.weights.skinIndices; geometry.skinWeights = this.weights.skinWeights; var mesh = null; if ( geo.bones === undefined || geo.skins === undefined || this.animations === undefined || this.animations.length === 0 ) { mesh = new THREE.Mesh( geometry, material ); } else { material.skinning = true; mesh = new THREE.SkinnedMesh( geometry, material ); this.addAnimation( mesh, this.weights.matrices, this.animations ); } return mesh; }; THREE.FBXLoader.prototype.addAnimation = function ( mesh, matrices, animations ) { var animationdata = { "name": 'animationtest', "fps": 30, "length": animations.length, "hierarchy": [] }; for ( var i = 0; i < mesh.geometry.bones.length; ++ i ) { var name = mesh.geometry.bones[ i ].name; name = name.replace( /.*:/, '' ); animationdata.hierarchy.push( { parent: mesh.geometry.bones[ i ].parent, name: name, keys: [] } ); } var hasCurve = function ( animNode, attr ) { if ( animNode === undefined ) { return false; } var attrNode; switch ( attr ) { case 'S': if ( animNode.S === undefined ) { return false; } attrNode = animNode.S; break; case 'R': if ( animNode.R === undefined ) { return false; } attrNode = animNode.R; break; case 'T': if ( animNode.T === undefined ) { return false; } attrNode = animNode.T; break; } if ( attrNode.curves.x === undefined ) { return false; } if ( attrNode.curves.y === undefined ) { return false; } if ( attrNode.curves.z === undefined ) { return false; } return true; }; var hasKeyOnFrame = function ( attrNode, frame ) { var x = isKeyExistOnFrame( attrNode.curves.x, frame ); var y = isKeyExistOnFrame( attrNode.curves.y, frame ); var z = isKeyExistOnFrame( attrNode.curves.z, frame ); return x && y && z; }; var isKeyExistOnFrame = function ( curve, frame ) { var value = curve.values[ frame ]; return value !== undefined; }; var genKey = function ( animNode, bone ) { // key initialize with its bone's bind pose at first var key = {}; key.time = frame / animations.fps; // TODO: key.pos = bone.pos; key.rot = bone.rotq; key.scl = bone.scl; if ( animNode === undefined ) { return key; } try { if ( hasCurve( animNode, 'T' ) && hasKeyOnFrame( animNode.T, frame ) ) { var pos = new THREE.Vector3( animNode.T.curves.x.values[ frame ], animNode.T.curves.y.values[ frame ], animNode.T.curves.z.values[ frame ] ); key.pos = [ pos.x, pos.y, pos.z ]; } else { delete key.pos; } if ( hasCurve( animNode, 'R' ) && hasKeyOnFrame( animNode.R, frame ) ) { var rx = degToRad( animNode.R.curves.x.values[ frame ] ); var ry = degToRad( animNode.R.curves.y.values[ frame ] ); var rz = degToRad( animNode.R.curves.z.values[ frame ] ); var eul = new THREE.Vector3( rx, ry, rz ); var rot = quatFromVec( eul.x, eul.y, eul.z ); key.rot = [ rot.x, rot.y, rot.z, rot.w ]; } else { delete key.rot; } if ( hasCurve( animNode, 'S' ) && hasKeyOnFrame( animNode.S, frame ) ) { var scl = new THREE.Vector3( animNode.S.curves.x.values[ frame ], animNode.S.curves.y.values[ frame ], animNode.S.curves.z.values[ frame ] ); key.scl = [ scl.x, scl.y, scl.z ]; } else { delete key.scl; } } catch ( e ) { // curve is not full plotted console.log( bone ); console.log( e ); } return key; }; var bones = mesh.geometry.bones; for ( frame = 0; frame < animations.frames; frame ++ ) { for ( i = 0; i < bones.length; i ++ ) { var bone = bones[ i ]; var animNode = animations.curves[ i ]; for ( var j = 0; j < animationdata.hierarchy.length; j ++ ) { if ( animationdata.hierarchy[ j ].name === bone.name ) { animationdata.hierarchy[ j ].keys.push( genKey( animNode, bone ) ); } } } } if ( mesh.geometry.animations === undefined ) { mesh.geometry.animations = []; } mesh.geometry.animations.push( THREE.AnimationClip.parseAnimation( animationdata, mesh.geometry.bones ) ); }; THREE.FBXLoader.prototype.parseMaterials = function ( node ) { // has not mat, return [] if ( ! ( 'Material' in node.subNodes ) ) { return []; } // has many var matCount = 0; for ( var mat in node.subNodes.Materials ) { if ( mat.match( /^\d+$/ ) ) { matCount ++; } } var res = []; if ( matCount > 0 ) { for ( mat in node.subNodes.Material ) { res.push( parseMaterial( node.subNodes.Material[ mat ] ) ); } } else { res.push( parseMaterial( node.subNodes.Material ) ); } return res; }; // TODO THREE.FBXLoader.prototype.parseMaterial = function ( node ) { }; THREE.FBXLoader.prototype.loadFile = function ( url, onLoad, onProgress, onError, responseType ) { var loader = new THREE.XHRLoader( this.manager ); loader.setResponseType( responseType ); var request = loader.load( url, function ( result ) { onLoad( result ); }, onProgress, onError ); return request; }; THREE.FBXLoader.prototype.loadFileAsBuffer = function ( url, onload, onProgress, onError ) { this.loadFile( url, onLoad, onProgress, onError, 'arraybuffer' ); }; THREE.FBXLoader.prototype.loadFileAsText = function ( url, onLoad, onProgress, onError ) { this.loadFile( url, onLoad, onProgress, onError, 'text' ); }; /* ----------------------------------------------------------------- */ function FBXNodes() {} FBXNodes.prototype.add = function ( key, val ) { this[ key ] = val; }; FBXNodes.prototype.searchConnectionParent = function ( id ) { if ( this.__cache_search_connection_parent === undefined ) { this.__cache_search_connection_parent = []; } if ( this.__cache_search_connection_parent[ id ] !== undefined ) { return this.__cache_search_connection_parent[ id ]; } else { this.__cache_search_connection_parent[ id ] = []; } var conns = this.Connections.properties.connections; var results = []; for ( var i = 0; i < conns.length; ++ i ) { if ( conns[ i ][ 0 ] == id ) { // 0 means scene root var res = conns[ i ][ 1 ] === 0 ? - 1 : conns[ i ][ 1 ]; results.push( res ); } } if ( results.length > 0 ) { this.__cache_search_connection_parent[ id ] = this.__cache_search_connection_parent[ id ].concat( results ); return results; } else { this.__cache_search_connection_parent[ id ] = [ - 1 ]; return [ - 1 ]; } }; FBXNodes.prototype.searchConnectionChildren = function ( id ) { if ( this.__cache_search_connection_children === undefined ) { this.__cache_search_connection_children = []; } if ( this.__cache_search_connection_children[ id ] !== undefined ) { return this.__cache_search_connection_children[ id ]; } else { this.__cache_search_connection_children[ id ] = []; } var conns = this.Connections.properties.connections; var res = []; for ( var i = 0; i < conns.length; ++ i ) { if ( conns[ i ][ 1 ] == id ) { // 0 means scene root res.push( conns[ i ][ 0 ] === 0 ? - 1 : conns[ i ][ 0 ] ); // there may more than one kid, then search to the end } } if ( res.length > 0 ) { this.__cache_search_connection_children[ id ] = this.__cache_search_connection_children[ id ].concat( res ); return res; } else { this.__cache_search_connection_children[ id ] = [ - 1 ]; return [ - 1 ]; } }; FBXNodes.prototype.searchConnectionType = function ( id, to ) { var key = id + ',' + to; // TODO: to hash if ( this.__cache_search_connection_type === undefined ) { this.__cache_search_connection_type = ''; } if ( this.__cache_search_connection_type[ key ] !== undefined ) { return this.__cache_search_connection_type[ key ]; } else { this.__cache_search_connection_type[ key ] = ''; } var conns = this.Connections.properties.connections; for ( var i = 0; i < conns.length; ++ i ) { if ( conns[ i ][ 0 ] == id && conns[ i ][ 1 ] == to ) { // 0 means scene root this.__cache_search_connection_type[ key ] = conns[ i ][ 2 ]; return conns[ i ][ 2 ]; } } this.__cache_search_connection_type[ id ] = null; return null; }; function FBXParser() {} FBXParser.prototype = { // constructor: FBXParser, // ------------ node stack manipulations ---------------------------------- getPrevNode: function () { return this.nodeStack[ this.currentIndent - 2 ]; }, getCurrentNode: function () { return this.nodeStack[ this.currentIndent - 1 ]; }, getCurrentProp: function () { return this.currentProp; }, pushStack: function ( node ) { this.nodeStack.push( node ); this.currentIndent += 1; }, popStack: function () { this.nodeStack.pop(); this.currentIndent -= 1; }, setCurrentProp: function ( val, name ) { this.currentProp = val; this.currentPropName = name; }, // ----------parse --------------------------------------------------- parse: function ( text ) { this.currentIndent = 0; this.allNodes = new FBXNodes(); this.nodeStack = []; this.currentProp = []; this.currentPropName = ''; var split = text.split( "\n" ); for ( var line in split ) { var l = split[ line ]; // short cut if ( l.match( /^[\s\t]*;/ ) ) { continue; } // skip comment line if ( l.match( /^[\s\t]*$/ ) ) { continue; } // skip empty line // beginning of node var beginningOfNodeExp = new RegExp( "^\\t{" + this.currentIndent + "}(\\w+):(.*){", '' ); match = l.match( beginningOfNodeExp ); if ( match ) { var nodeName = match[ 1 ].trim().replace( /^"/, '' ).replace( /"$/, "" ); var nodeAttrs = match[ 2 ].split( ',' ).map( function ( element ) { return element.trim().replace( /^"/, '' ).replace( /"$/, '' ); } ); this.parseNodeBegin( l, nodeName, nodeAttrs || null ); continue; } // node's property var propExp = new RegExp( "^\\t{" + ( this.currentIndent ) + "}(\\w+):[\\s\\t\\r\\n](.*)" ); match = l.match( propExp ); if ( match ) { var propName = match[ 1 ].replace( /^"/, '' ).replace( /"$/, "" ).trim(); var propValue = match[ 2 ].replace( /^"/, '' ).replace( /"$/, "" ).trim(); this.parseNodeProperty( l, propName, propValue ); continue; } // end of node var endOfNodeExp = new RegExp( "^\\t{" + ( this.currentIndent - 1 ) + "}}" ); if ( l.match( endOfNodeExp ) ) { this.nodeEnd(); continue; } // for special case, // // Vertices: *8670 { // a: 0.0356229953467846,13.9599733352661,-0.399196773.....(snip) // -0.0612030513584614,13.960485458374,-0.409748703241348,-0.10..... // 0.12490539252758,13.7450733184814,-0.454119384288788,0.09272..... // 0.0836158767342567,13.5432004928589,-0.435397416353226,0.028..... // // these case the lines must contiue with previous line if ( l.match( /^[^\s\t}]/ ) ) { this.parseNodePropertyContinued( l ); } } return this.allNodes; }, parseNodeBegin: function ( line, nodeName, nodeAttrs ) { // var nodeName = match[1]; var node = { 'name': nodeName, properties: {}, 'subNodes': {} }; var attrs = this.parseNodeAttr( nodeAttrs ); var currentNode = this.getCurrentNode(); // a top node if ( this.currentIndent === 0 ) { this.allNodes.add( nodeName, node ); } else { // a subnode // already exists subnode, then append it if ( nodeName in currentNode.subNodes ) { var tmp = currentNode.subNodes[ nodeName ]; // console.log( "duped entry found\nkey: " + nodeName + "\nvalue: " + propValue ); if ( this.isFlattenNode( currentNode.subNodes[ nodeName ] ) ) { if ( attrs.id === '' ) { currentNode.subNodes[ nodeName ] = []; currentNode.subNodes[ nodeName ].push( tmp ); } else { currentNode.subNodes[ nodeName ] = {}; currentNode.subNodes[ nodeName ][ tmp.id ] = tmp; } } if ( attrs.id === '' ) { currentNode.subNodes[ nodeName ].push( node ); } else { currentNode.subNodes[ nodeName ][ attrs.id ] = node; } } else { currentNode.subNodes[ nodeName ] = node; } } // for this ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓ // NodeAttribute: 1001463072, "NodeAttribute::", "LimbNode" { if ( nodeAttrs ) { node.id = attrs.id; node.attrName = attrs.name; node.attrType = attrs.type; } this.pushStack( node ); }, parseNodeAttr: function ( attrs ) { var id = attrs[ 0 ]; if ( attrs[ 0 ] !== "" ) { id = parseInt( attrs[ 0 ] ); if ( isNaN( id ) ) { // PolygonVertexIndex: *16380 { id = attrs[ 0 ]; } } var name; var type; if ( attrs.length > 1 ) { name = attrs[ 1 ].replace( /^(\w+)::/, '' ); type = attrs[ 2 ]; } return { id: id, name: name || '', type: type || '' }; }, parseNodeProperty: function ( line, propName, propValue ) { var currentNode = this.getCurrentNode(); var parentName = currentNode.name; // special case parent node's is like "Properties70" // these chilren nodes must treat with careful if ( parentName !== undefined ) { var propMatch = parentName.match( /Properties(\d)+/ ); if ( propMatch ) { this.parseNodeSpecialProperty( line, propName, propValue ); return; } } // special case Connections if ( propName == 'C' ) { var connProps = propValue.split( ',' ).slice( 1 ); var from = parseInt( connProps[ 0 ] ); var to = parseInt( connProps[ 1 ] ); var rest = propValue.split( ',' ).slice( 3 ); propName = 'connections'; propValue = [ from, to ]; propValue = propValue.concat( rest ); if ( currentNode.properties[ propName ] === undefined ) { currentNode.properties[ propName ] = []; } } // special case Connections if ( propName == 'Node' ) { var id = parseInt( propValue ); currentNode.properties.id = id; currentNode.id = id; } // already exists in properties, then append this if ( propName in currentNode.properties ) { // console.log( "duped entry found\nkey: " + propName + "\nvalue: " + propValue ); if ( Array.isArray( currentNode.properties[ propName ] ) ) { currentNode.properties[ propName ].push( propValue ); } else { currentNode.properties[ propName ] += propValue; } } else { // console.log( propName + ": " + propValue ); if ( Array.isArray( currentNode.properties[ propName ] ) ) { currentNode.properties[ propName ].push( propValue ); } else { currentNode.properties[ propName ] = propValue; } } this.setCurrentProp( currentNode.properties, propName ); }, // TODO: parseNodePropertyContinued: function ( line ) { this.currentProp[ this.currentPropName ] += line; }, parseNodeSpecialProperty: function ( line, propName, propValue ) { // split this // P: "Lcl Scaling", "Lcl Scaling", "", "A",1,1,1 // into array like below // ["Lcl Scaling", "Lcl Scaling", "", "A", "1,1,1" ] var props = propValue.split( '",' ).map( function ( element ) { return element.trim().replace( /^\"/, '' ).replace( /\s/, '_' ); } ); var innerPropName = props[ 0 ]; var innerPropType1 = props[ 1 ]; var innerPropType2 = props[ 2 ]; var innerPropFlag = props[ 3 ]; var innerPropValue = props[ 4 ]; /* if ( innerPropValue === undefined ) { innerPropValue = props[3]; } */ // cast value in its type switch ( innerPropType1 ) { case "int": innerPropValue = parseInt( innerPropValue ); break; case "double": innerPropValue = parseFloat( innerPropValue ); break; case "ColorRGB": case "Vector3D": var tmp = innerPropValue.split( ',' ); innerPropValue = new THREE.Vector3( tmp[ 0 ], tmp[ 1 ], tmp[ 2 ] ); break; } // CAUTION: these props must append to parent's parent this.getPrevNode().properties[ innerPropName ] = { 'type': innerPropType1, 'type2': innerPropType2, 'flag': innerPropFlag, 'value': innerPropValue }; this.setCurrentProp( this.getPrevNode().properties, innerPropName ); }, nodeEnd: function ( line ) { this.popStack(); }, /* ---------------------------------------------------------------- */ /* util */ isFlattenNode: function ( node ) { return ( 'subNodes' in node && 'properties' in node ) ? true : false; } }; function FBXAnalyzer() {} FBXAnalyzer.prototype = { }; // generate skinIndices, skinWeights // @skinIndices: per vertex data, this represents the bone indexes affects that vertex // @skinWeights: per vertex data, this represents the Weight Values affects that vertex // @matrices: per `bones` data function Weights() { this.skinIndices = []; this.skinWeights = []; this.matrices = []; } Weights.prototype.parseCluster = function ( node, id, entry ) { var _p = node.searchConnectionParent( id ); var _indices = toInt( entry.subNodes.Indexes.properties.a.split( ',' ) ); var _weights = toFloat( entry.subNodes.Weights.properties.a.split( ',' ) ); var _transform = toMat44( toFloat( entry.subNodes.Transform.properties.a.split( ',' ) ) ); var _link = toMat44( toFloat( entry.subNodes.TransformLink.properties.a.split( ',' ) ) ); return { 'parent': _p, 'id': parseInt( id ), 'indices': _indices, 'weights': _weights, 'transform': _transform, 'transformlink': _link, 'linkMode': entry.properties.Mode }; }; Weights.prototype.parse = function ( node, bones ) { this.skinIndices = []; this.skinWeights = []; this.matrices = []; var deformers = node.Objects.subNodes.Deformer; var clusters = {}; for ( var id in deformers ) { if ( deformers[ id ].attrType === 'Cluster' ) { if ( ! ( 'Indexes' in deformers[ id ].subNodes ) ) { continue; } //clusters.push( this.parseCluster( node, id, deformers[id] ) ); var cluster = this.parseCluster( node, id, deformers[ id ] ); var boneId = node.searchConnectionChildren( cluster.id )[ 0 ]; clusters[ boneId ] = cluster; } } // this clusters is per Bone data, thus we make this into per vertex data var weights = []; var hi = bones.hierarchy; for ( var b = 0; b < hi.length; ++ b ) { var bid = hi[ b ].internalId; if ( clusters[ bid ] === undefined ) { //console.log( bid ); this.matrices.push( new THREE.Matrix4() ); continue; } var clst = clusters[ bid ]; // store transform matrix per bones this.matrices.push( clst.transform ); //this.matrices.push( clst.transformlink ); for ( var v = 0; v < clst.indices.length; ++ v ) { if ( weights[ clst.indices[ v ] ] === undefined ) { weights[ clst.indices[ v ] ] = {}; weights[ clst.indices[ v ] ].joint = []; weights[ clst.indices[ v ] ].weight = []; } // indices var affect = node.searchConnectionChildren( clst.id ); if ( affect.length > 1 ) { console.warn( "FBXLoader: node " + clst.id + " have many weight kids: " + affect ); } weights[ clst.indices[ v ] ].joint.push( bones.getBoneIdfromInternalId( node, affect[ 0 ] ) ); // weight value weights[ clst.indices[ v ] ].weight.push( clst.weights[ v ] ); } } // normalize the skin weights // TODO - this might be a good place to choose greatest 4 weights for ( var i = 0; i < weights.length; i ++ ) { var indicies = new THREE.Vector4( weights[ i ].joint[ 0 ] ? weights[ i ].joint[ 0 ] : 0, weights[ i ].joint[ 1 ] ? weights[ i ].joint[ 1 ] : 0, weights[ i ].joint[ 2 ] ? weights[ i ].joint[ 2 ] : 0, weights[ i ].joint[ 3 ] ? weights[ i ].joint[ 3 ] : 0 ); var weight = new THREE.Vector4( weights[ i ].weight[ 0 ] ? weights[ i ].weight[ 0 ] : 0, weights[ i ].weight[ 1 ] ? weights[ i ].weight[ 1 ] : 0, weights[ i ].weight[ 2 ] ? weights[ i ].weight[ 2 ] : 0, weights[ i ].weight[ 3 ] ? weights[ i ].weight[ 3 ] : 0 ); this.skinIndices.push( indicies ); this.skinWeights.push( weight ); } //console.log( this ); return this; }; function Bones() { // returns bones hierarchy tree. // [ // { // "parent": id, // "name": name, // "pos": pos, // "rotq": quat // }, // ... // {}, // ... // ] // /* sample response "bones" : [ {"parent":-1, "name":"Fbx01", "pos":[-0.002, 98.739, 1.6e-05], "rotq":[0, 0, 0, 1]}, {"parent":0, "name":"Fbx01_Pelvis", "pos":[0.00015963, 0, 7.33107e-08], "rotq":[0, 0, 0, 1]}, {"parent":1, "name":"Fbx01_Spine", "pos":[6.577e-06, 10.216, 0.0106811], "rotq":[0, 0, 0, 1]}, {"parent":2, "name":"Fbx01_R_Thigh", "pos":[14.6537, -10.216, -0.00918758], "rotq":[0, 0, 0, 1]}, {"parent":3, "name":"Fbx01_R_Calf", "pos":[-3.70047, -42.9681, -7.78158], "rotq":[0, 0, 0, 1]}, {"parent":4, "name":"Fbx01_R_Foot", "pos":[-2.0696, -46.0488, 9.42052], "rotq":[0, 0, 0, 1]}, {"parent":5, "name":"Fbx01_R_Toe0", "pos":[-0.0234785, -9.46233, -15.3187], "rotq":[0, 0, 0, 1]}, {"parent":2, "name":"Fbx01_L_Thigh", "pos":[-14.6537, -10.216, -0.00918314], "rotq":[0, 0, 0, 1]}, {"parent":7, "name":"Fbx01_L_Calf", "pos":[3.70037, -42.968, -7.78155], "rotq":[0, 0, 0, 1]}, {"parent":8, "name":"Fbx01_L_Foot", "pos":[2.06954, -46.0488, 9.42052], "rotq":[0, 0, 0, 1]}, {"parent":9, "name":"Fbx01_L_Toe0", "pos":[0.0234566, -9.46235, -15.3187], "rotq":[0, 0, 0, 1]}, {"parent":2, "name":"Fbx01_Spine1", "pos":[-2.97523e-05, 11.5892, -9.81027e-05], "rotq":[0, 0, 0, 1]}, {"parent":11, "name":"Fbx01_Spine2", "pos":[-2.91292e-05, 11.4685, 8.27126e-05], "rotq":[0, 0, 0, 1]}, {"parent":12, "name":"Fbx01_Spine3", "pos":[-4.48857e-05, 11.5783, 8.35108e-05], "rotq":[0, 0, 0, 1]}, {"parent":13, "name":"Fbx01_Neck", "pos":[1.22987e-05, 11.5582, -0.0044775], "rotq":[0, 0, 0, 1]}, {"parent":14, "name":"Fbx01_Head", "pos":[-3.50709e-05, 6.62915, -0.00523254], "rotq":[0, 0, 0, 1]}, {"parent":15, "name":"Fbx01_R_Eye", "pos":[3.31681, 12.739, -10.5267], "rotq":[0, 0, 0, 1]}, {"parent":15, "name":"Fbx01_L_Eye", "pos":[-3.32038, 12.7391, -10.5267], "rotq":[0, 0, 0, 1]}, {"parent":15, "name":"Jaw", "pos":[-0.0017738, 7.43481, -4.08114], "rotq":[0, 0, 0, 1]}, {"parent":14, "name":"Fbx01_R_Clavicle", "pos":[3.10919, 2.46577, -0.0115284], "rotq":[0, 0, 0, 1]}, {"parent":19, "name":"Fbx01_R_UpperArm", "pos":[16.014, 4.57764e-05, 3.10405], "rotq":[0, 0, 0, 1]}, {"parent":20, "name":"Fbx01_R_Forearm", "pos":[22.7068, -1.66322, -2.13803], "rotq":[0, 0, 0, 1]}, {"parent":21, "name":"Fbx01_R_Hand", "pos":[25.5881, -0.80249, -6.37307], "rotq":[0, 0, 0, 1]}, ... {"parent":27, "name":"Fbx01_R_Finger32", "pos":[2.15572, -0.548737, -0.539604], "rotq":[0, 0, 0, 1]}, {"parent":22, "name":"Fbx01_R_Finger2", "pos":[9.79318, 0.132553, -2.97845], "rotq":[0, 0, 0, 1]}, {"parent":29, "name":"Fbx01_R_Finger21", "pos":[2.74037, 0.0483093, -0.650531], "rotq":[0, 0, 0, 1]}, {"parent":55, "name":"Fbx01_L_Finger02", "pos":[-1.65308, -1.43208, -1.82885], "rotq":[0, 0, 0, 1]} ] */ this.hierarchy = []; } Bones.prototype.parseHierarchy = function ( node ) { var objects = node.Objects; var models = objects.subNodes.Model; var bones = []; for ( var id in models ) { if ( models[ id ].attrType === undefined ) { continue; } bones.push( models[ id ] ); } this.hierarchy = []; for ( var i = 0; i < bones.length; ++ i ) { var bone = bones[ i ]; var p = node.searchConnectionParent( bone.id )[ 0 ]; var t = [ 0.0, 0.0, 0.0 ]; var r = [ 0.0, 0.0, 0.0, 1.0 ]; var s = [ 1.0, 1.0, 1.0 ]; if ( 'Lcl_Translation' in bone.properties ) { t = toFloat( bone.properties.Lcl_Translation.value.split( ',' ) ); } if ( 'Lcl_Rotation' in bone.properties ) { r = toRad( toFloat( bone.properties.Lcl_Rotation.value.split( ',' ) ) ); var q = new THREE.Quaternion(); q.setFromEuler( new THREE.Euler( r[ 0 ], r[ 1 ], r[ 2 ], 'ZYX' ) ); r = [ q.x, q.y, q.z, q.w ]; } if ( 'Lcl_Scaling' in bone.properties ) { s = toFloat( bone.properties.Lcl_Scaling.value.split( ',' ) ); } // replace unsafe character var name = bone.attrName; name = name.replace( /:/, '' ); name = name.replace( /_/, '' ); name = name.replace( /-/, '' ); this.hierarchy.push( { "parent": p, "name": name, "pos": t, "rotq": r, "scl": s, "internalId": bone.id } ); } this.reindexParentId(); this.restoreBindPose( node ); return this; }; Bones.prototype.reindexParentId = function () { for ( var h = 0; h < this.hierarchy.length; h ++ ) { for ( var ii = 0; ii < this.hierarchy.length; ++ ii ) { if ( this.hierarchy[ h ].parent == this.hierarchy[ ii ].internalId ) { this.hierarchy[ h ].parent = ii; break; } } } }; Bones.prototype.restoreBindPose = function ( node ) { var bindPoseNode = node.Objects.subNodes.Pose; if ( bindPoseNode === undefined ) { return; } var poseNode = bindPoseNode.subNodes.PoseNode; var localMatrices = {}; // store local matrices, modified later( initialy world space ) var worldMatrices = {}; // store world matrices for ( var i = 0; i < poseNode.length; ++ i ) { var rawMatLcl = toMat44( poseNode[ i ].subNodes.Matrix.properties.a.split( ',' ) ); var rawMatWrd = toMat44( poseNode[ i ].subNodes.Matrix.properties.a.split( ',' ) ); localMatrices[ poseNode[ i ].id ] = rawMatLcl; worldMatrices[ poseNode[ i ].id ] = rawMatWrd; } for ( var h = 0; h < this.hierarchy.length; ++ h ) { var bone = this.hierarchy[ h ]; var inId = bone.internalId; if ( worldMatrices[ inId ] === undefined ) { // has no bind pose node, possibly be mesh // console.log( bone ); continue; } var t = new THREE.Vector3( 0, 0, 0 ); var r = new THREE.Quaternion(); var s = new THREE.Vector3( 1, 1, 1 ); var parentId; var parentNodes = node.searchConnectionParent( inId ); for ( var pn = 0; pn < parentNodes.length; ++ pn ) { if ( this.isBoneNode( parentNodes[ pn ] ) ) { parentId = parentNodes[ pn ]; break; } } if ( parentId !== undefined && localMatrices[ parentId ] !== undefined ) { // convert world space matrix into local space var inv = new THREE.Matrix4(); inv.getInverse( worldMatrices[ parentId ] ); inv.multiply( localMatrices[ inId ] ); localMatrices[ inId ] = inv; } else { //console.log( bone ); } localMatrices[ inId ].decompose( t, r, s ); bone.pos = [ t.x, t.y, t.z ]; bone.rotq = [ r.x, r.y, r.z, r.w ]; bone.scl = [ s.x, s.y, s.z ]; } }; Bones.prototype.searchRealId = function ( internalId ) { for ( var h = 0; h < this.hierarchy.length; h ++ ) { if ( internalId == this.hierarchy[ h ].internalId ) { return h; } } // console.warn( 'FBXLoader: notfound internalId in bones: ' + internalId); return - 1; }; Bones.prototype.getByInternalId = function ( internalId ) { for ( var h = 0; h < this.hierarchy.length; h ++ ) { if ( internalId == this.hierarchy[ h ].internalId ) { return this.hierarchy[ h ]; } } return null; }; Bones.prototype.isBoneNode = function ( id ) { for ( var i = 0; i < this.hierarchy.length; ++ i ) { if ( id === this.hierarchy[ i ].internalId ) { return true; } } return false; }; Bones.prototype.getBoneIdfromInternalId = function ( node, id ) { if ( node.__cache_get_boneid_from_internalid === undefined ) { node.__cache_get_boneid_from_internalid = []; } if ( node.__cache_get_boneid_from_internalid[ id ] !== undefined ) { return node.__cache_get_boneid_from_internalid[ id ]; } for ( var i = 0; i < this.hierarchy.length; ++ i ) { if ( this.hierarchy[ i ].internalId == id ) { var res = i; node.__cache_get_boneid_from_internalid[ id ] = i; return i; } } // console.warn( 'FBXLoader: bone internalId(' + id + ') not found in bone hierarchy' ); return - 1; }; function Geometry() { this.node = null; this.name = null; this.id = null; this.vertices = []; this.indices = []; this.normals = []; this.uvs = []; this.bones = []; this.skins = null; } Geometry.prototype.parse = function ( geoNode ) { this.node = geoNode; this.name = geoNode.attrName; this.id = geoNode.id; this.vertices = this.getVertices(); if ( this.vertices === undefined ) { console.log( 'FBXLoader: Geometry.parse(): pass' + this.node.id ); return; } this.indices = this.getPolygonVertexIndices(); this.uvs = ( new UV() ).parse( this.node, this ); this.normals = ( new Normal() ).parse( this.node, this ); if ( this.getPolygonTopologyMax() > 3 ) { this.indices = this.convertPolyIndicesToTri( this.indices, this.getPolygonTopologyArray() ); } return this; }; Geometry.prototype.getVertices = function () { if ( this.node.__cache_vertices ) { return this.node.__cache_vertices; } if ( this.node.subNodes.Vertices === undefined ) { console.warn( 'this.node: ' + this.node.attrName + "(" + this.node.id + ") does not have Vertices" ); this.node.__cache_vertices = undefined; return null; } var rawTextVert = this.node.subNodes.Vertices.properties.a; var vertices = rawTextVert.split( ',' ).map( function ( element ) { return parseFloat( element ); } ); this.node.__cache_vertices = vertices; return this.node.__cache_vertices; }; Geometry.prototype.getPolygonVertexIndices = function () { if ( this.node.__cache_indices && this.node.__cache_poly_topology_max ) { return this.node.__cache_indices; } if ( this.node.subNodes === undefined ) { console.error( 'this.node.subNodes undefined' ); console.log( this.node ); return; } if ( this.node.subNodes.PolygonVertexIndex === undefined ) { console.warn( 'this.node: ' + this.node.attrName + "(" + this.node.id + ") does not have PolygonVertexIndex " ); this.node.__cache_indices = undefined; return; } var rawTextIndices = this.node.subNodes.PolygonVertexIndex.properties.a; var indices = rawTextIndices.split( ',' ); var currentTopo = 1; var topologyN = null; var topologyArr = []; // The indices that make up the polygon are in order and a negative index // means that it’s the last index of the polygon. That index needs // to be made positive and then you have to subtract 1 from it! for ( var i = 0; i < indices.length; ++ i ) { var tmpI = parseInt( indices[ i ] ); // found n if ( tmpI < 0 ) { if ( currentTopo > topologyN ) { topologyN = currentTopo; } indices[ i ] = tmpI ^ - 1; topologyArr.push( currentTopo ); currentTopo = 1; } else { indices[ i ] = tmpI; currentTopo ++; } } if ( topologyN === null ) { console.warn( "FBXLoader: topology N not found: " + this.node.attrName ); console.warn( this.node ); topologyN = 3; } this.node.__cache_poly_topology_max = topologyN; this.node.__cache_poly_topology_arr = topologyArr; this.node.__cache_indices = indices; return this.node.__cache_indices; }; Geometry.prototype.getPolygonTopologyMax = function () { if ( this.node.__cache_indices && this.node.__cache_poly_topology_max ) { return this.node.__cache_poly_topology_max; } this.getPolygonVertexIndices( this.node ); return this.node.__cache_poly_topology_max; }; Geometry.prototype.getPolygonTopologyArray = function () { if ( this.node.__cache_indices && this.node.__cache_poly_topology_max ) { return this.node.__cache_poly_topology_arr; } this.getPolygonVertexIndices( this.node ); return this.node.__cache_poly_topology_arr; }; // a - d // | | // b - c // // [( a, b, c, d ) ........... // [( a, b, c ), (a, c, d ).... Geometry.prototype.convertPolyIndicesToTri = function ( indices, strides ) { var res = []; var i = 0; var tmp = []; var currentPolyNum = 0; var currentStride = 0; while ( i < indices.length ) { currentStride = strides[ currentPolyNum ]; // CAUTIN: NG over 6gon for ( var j = 0; j <= ( currentStride - 3 ); j ++ ) { res.push( indices[ i ] ); res.push( indices[ i + ( currentStride - 2 - j ) ] ); res.push( indices[ i + ( currentStride - 1 - j ) ] ); } currentPolyNum ++; i += currentStride; } return res; }; Geometry.prototype.addBones = function ( bones ) { this.bones = bones; }; function UV() { this.uv = null; this.map = null; this.ref = null; this.node = null; this.index = null; } UV.prototype.getUV = function ( node ) { if ( this.node && this.uv && this.map && this.ref ) { return this.uv; } else { return this._parseText( node ); } }; UV.prototype.getMap = function ( node ) { if ( this.node && this.uv && this.map && this.ref ) { return this.map; } else { this._parseText( node ); return this.map; } }; UV.prototype.getRef = function ( node ) { if ( this.node && this.uv && this.map && this.ref ) { return this.ref; } else { this._parseText( node ); return this.ref; } }; UV.prototype.getIndex = function ( node ) { if ( this.node && this.uv && this.map && this.ref ) { return this.index; } else { this._parseText( node ); return this.index; } }; UV.prototype.getNode = function ( topnode ) { if ( this.node !== null ) { return this.node; } this.node = topnode.subNodes.LayerElementUV; return this.node; }; UV.prototype._parseText = function ( node ) { var uvNode = this.getNode( node ); if ( uvNode === undefined ) { // console.log( node.attrName + "(" + node.id + ")" + " has no LayerElementUV." ); return []; } var count = 0; var x = ''; for ( var n in uvNode ) { if ( n.match( /^\d+$/ ) ) { count ++; x = n; } } if ( count > 0 ) { console.warn( 'multi uv not supported' ); uvNode = uvNode[ n ]; } var uvIndex = uvNode.subNodes.UVIndex.properties.a; var uvs = uvNode.subNodes.UV.properties.a; var uvMap = uvNode.properties.MappingInformationType; var uvRef = uvNode.properties.ReferenceInformationType; this.uv = toFloat( uvs.split( ',' ) ); this.index = toInt( uvIndex.split( ',' ) ); this.map = uvMap; // TODO: normalize notation shaking... FOR BLENDER this.ref = uvRef; return this.uv; }; UV.prototype.parse = function ( node, geo ) { this.uvNode = this.getNode( node ); this.uv = this.getUV( node ); var mappingType = this.getMap( node ); var refType = this.getRef( node ); var indices = this.getIndex( node ); var strides = geo.getPolygonTopologyArray(); // it means that there is a normal for every vertex of every polygon of the model. // For example, if the models has 8 vertices that make up four quads, then there // will be 16 normals (one normal * 4 polygons * 4 vertices of the polygon). Note // that generally a game engine needs the vertices to have only one normal defined. // So, if you find a vertex has more tha one normal, you can either ignore the normals // you find after the first, or calculate the mean from all of them (normal smoothing). //if ( mappingType == "ByPolygonVertex" ){ switch ( mappingType ) { case "ByPolygonVertex": switch ( refType ) { // Direct // The this.uv are in order. case "Direct": this.uv = this.parseUV_ByPolygonVertex_Direct( this.uv, indices, strides, 2 ); break; // IndexToDirect // The order of the this.uv is given by the uvsIndex property. case "IndexToDirect": this.uv = this.parseUV_ByPolygonVertex_IndexToDirect( this.uv, indices ); break; } // convert from by polygon(vert) data into by verts data this.uv = mapByPolygonVertexToByVertex( this.uv, geo.getPolygonVertexIndices( node ), 2 ); break; case "ByPolygon": switch ( refType ) { // Direct // The this.uv are in order. case "Direct": this.uv = this.parseUV_ByPolygon_Direct(); break; // IndexToDirect // The order of the this.uv is given by the uvsIndex property. case "IndexToDirect": this.uv = this.parseUV_ByPolygon_IndexToDirect(); break; } break; } return this.uv; }; UV.prototype.parseUV_ByPolygonVertex_Direct = function ( node, indices, strides, itemSize ) { return parse_Data_ByPolygonVertex_Direct( node, indices, strides, itemSize ); }; UV.prototype.parseUV_ByPolygonVertex_IndexToDirect = function ( node, indices ) { return parse_Data_ByPolygonVertex_IndexToDirect( node, indices, 2 ); }; UV.prototype.parseUV_ByPolygon_Direct = function ( node ) { console.warn( "not implemented" ); return node; }; UV.prototype.parseUV_ByPolygon_IndexToDirect = function ( node ) { console.warn( "not implemented" ); return node; }; UV.prototype.parseUV_ByVertex_Direct = function ( node ) { console.warn( "not implemented" ); return node; }; function Normal() { this.normal = null; this.map = null; this.ref = null; this.node = null; this.index = null; } Normal.prototype.getNormal = function ( node ) { if ( this.node && this.normal && this.map && this.ref ) { return this.normal; } else { this._parseText( node ); return this.normal; } }; // mappingType: possible variant // ByPolygon // ByPolygonVertex // ByVertex (or also ByVertice, as the Blender exporter writes) // ByEdge // AllSame // var mappingType = node.properties.MappingInformationType; Normal.prototype.getMap = function ( node ) { if ( this.node && this.normal && this.map && this.ref ) { return this.map; } else { this._parseText( node ); return this.map; } }; // refType: possible variants // Direct // IndexToDirect (or Index for older versions) // var refType = node.properties.ReferenceInformationType; Normal.prototype.getRef = function ( node ) { if ( this.node && this.normal && this.map && this.ref ) { return this.ref; } else { this._parseText( node ); return this.ref; } }; Normal.prototype.getNode = function ( node ) { if ( this.node ) { return this.node; } this.node = node.subNodes.LayerElementNormal; return this.node; }; Normal.prototype._parseText = function ( node ) { var normalNode = this.getNode( node ); if ( normalNode === undefined ) { console.warn( 'node: ' + node.attrName + "(" + node.id + ") does not have LayerElementNormal" ); return; } var mappingType = normalNode.properties.MappingInformationType; var refType = normalNode.properties.ReferenceInformationType; var rawTextNormals = normalNode.subNodes.Normals.properties.a; this.normal = toFloat( rawTextNormals.split( ',' ) ); // TODO: normalize notation shaking, vertex / vertice... blender... this.map = mappingType; this.ref = refType; }; Normal.prototype.parse = function ( topnode, geo ) { var normals = this.getNormal( topnode ); var normalNode = this.getNode( topnode ); var mappingType = this.getMap( topnode ); var refType = this.getRef( topnode ); var indices = geo.getPolygonVertexIndices( topnode ); var strides = geo.getPolygonTopologyArray( topnode ); // it means that there is a normal for every vertex of every polygon of the model. // For example, if the models has 8 vertices that make up four quads, then there // will be 16 normals (one normal * 4 polygons * 4 vertices of the polygon). Note // that generally a game engine needs the vertices to have only one normal defined. // So, if you find a vertex has more tha one normal, you can either ignore the normals // you find after the first, or calculate the mean from all of them (normal smoothing). //if ( mappingType == "ByPolygonVertex" ){ switch ( mappingType ) { case "ByPolygonVertex": switch ( refType ) { // Direct // The normals are in order. case "Direct": normals = this.parseNormal_ByPolygonVertex_Direct( normals, indices, strides, 3 ); break; // IndexToDirect // The order of the normals is given by the NormalsIndex property. case "IndexToDirect": normals = this.parseNormal_ByPolygonVertex_IndexToDirect(); break; } break; case "ByPolygon": switch ( refType ) { // Direct // The normals are in order. case "Direct": normals = this.parseNormal_ByPolygon_Direct(); break; // IndexToDirect // The order of the normals is given by the NormalsIndex property. case "IndexToDirect": normals = this.parseNormal_ByPolygon_IndexToDirect(); break; } break; } return normals; }; Normal.prototype.parseNormal_ByPolygonVertex_Direct = function ( node, indices, strides, itemSize ) { return parse_Data_ByPolygonVertex_Direct( node, indices, strides, itemSize ); }; Normal.prototype.parseNormal_ByPolygonVertex_IndexToDirect = function ( node ) { console.warn( "not implemented" ); return node; }; Normal.prototype.parseNormal_ByPolygon_Direct = function ( node ) { console.warn( "not implemented" ); return node; }; Normal.prototype.parseNormal_ByPolygon_IndexToDirect = function ( node ) { console.warn( "not implemented" ); return node; }; Normal.prototype.parseNormal_ByVertex_Direct = function ( node ) { console.warn( "not implemented" ); return node; }; function AnimationCurve() { this.version = null; this.id = null; this.internalId = null; this.times = null; this.values = null; this.attrFlag = null; // tangeant this.attrData = null; // slope, weight } AnimationCurve.prototype.fromNode = function ( curveNode ) { this.id = curveNode.id; this.internalId = curveNode.id; this.times = curveNode.subNodes.KeyTime.properties.a; this.values = curveNode.subNodes.KeyValueFloat.properties.a; this.attrFlag = curveNode.subNodes.KeyAttrFlags.properties.a; this.attrData = curveNode.subNodes.KeyAttrDataFloat.properties.a; this.times = toFloat( this.times.split( ',' ) ); this.values = toFloat( this.values.split( ',' ) ); this.attrData = toFloat( this.attrData.split( ',' ) ); this.attrFlag = toInt( this.attrFlag.split( ',' ) ); this.times = this.times.map( function ( element ) { return FBXTimeToSeconds( element ); } ); return this; }; AnimationCurve.prototype.getLength = function () { return this.times[ this.times.length - 1 ]; }; function AnimationNode() { this.id = null; this.attr = null; // S, R, T this.attrX = false; this.attrY = false; this.attrZ = false; this.internalId = null; this.containerInternalId = null; // bone, null etc Id this.containerBoneId = null; // bone, null etc Id this.curveIdx = null; // AnimationCurve's indices this.curves = []; // AnimationCurve refs } AnimationNode.prototype.fromNode = function ( allNodes, node, bones ) { this.id = node.id; this.attr = node.attrName; this.internalId = node.id; if ( this.attr.match( /S|R|T/ ) ) { for ( var attrKey in node.properties ) { if ( attrKey.match( /X/ ) ) { this.attrX = true; } if ( attrKey.match( /Y/ ) ) { this.attrY = true; } if ( attrKey.match( /Z/ ) ) { this.attrZ = true; } } } else { // may be deform percent nodes return null; } this.containerIndices = allNodes.searchConnectionParent( this.id ); this.curveIdx = allNodes.searchConnectionChildren( this.id ); for ( var i = this.containerIndices.length - 1; i >= 0; -- i ) { var boneId = bones.searchRealId( this.containerIndices[ i ] ); if ( boneId >= 0 ) { this.containerBoneId = boneId; this.containerId = this.containerIndices [ i ]; } if ( boneId >= 0 ) { break; } } // this.containerBoneId = bones.searchRealId( this.containerIndices ); return this; }; AnimationNode.prototype.setCurve = function ( curve ) { this.curves.push( curve ); }; function Animation() { this.curves = {}; this.length = 0.0; this.fps = 30.0; this.frames = 0.0; } Animation.prototype.parse = function ( node, bones ) { var rawNodes = node.Objects.subNodes.AnimationCurveNode; var rawCurves = node.Objects.subNodes.AnimationCurve; // first: expand AnimationCurveNode into curve nodes var curveNodes = []; for ( var key in rawNodes ) { if ( key.match( /\d+/ ) ) { var a = ( new AnimationNode() ).fromNode( node, rawNodes[ key ], bones ); curveNodes.push( a ); } } // second: gen dict, mapped by internalId var tmp = {}; for ( var i = 0; i < curveNodes.length; ++ i ) { if ( curveNodes[ i ] === null ) { continue; } tmp[ curveNodes[ i ].id ] = curveNodes[ i ]; } // third: insert curves into the dict var ac = []; var max = 0.0; for ( key in rawCurves ) { if ( key.match( /\d+/ ) ) { var c = ( new AnimationCurve() ).fromNode( rawCurves[ key ] ); ac.push( c ); max = c.getLength() ? c.getLength() : max; var parentId = node.searchConnectionParent( c.id )[ 0 ]; var axis = node.searchConnectionType( c.id, parentId ); if ( axis.match( /X/ ) ) { axis = 'x'; } if ( axis.match( /Y/ ) ) { axis = 'y'; } if ( axis.match( /Z/ ) ) { axis = 'z'; } tmp[ parentId ].curves[ axis ] = c; } } // forth: for ( var t in tmp ) { var id = tmp[ t ].containerBoneId; if ( this.curves[ id ] === undefined ) { this.curves[ id ] = {}; } this.curves[ id ][ tmp[ t ].attr ] = tmp[ t ]; } this.length = max; this.frames = this.length * this.fps; return this; }; function Textures() { this.textures = []; this.perGeoMap = {}; } Textures.prototype.add = function ( tex ) { if ( this.textures === undefined ) { this.textures = []; } this.textures.push( tex ); for ( var i = 0; i < tex.parentIds.length; ++ i ) { if ( this.perGeoMap[ tex.parentIds[ i ] ] === undefined ) { this.perGeoMap[ tex.parentIds[ i ] ] = []; } this.perGeoMap[ tex.parentIds[ i ] ].push( this.textures[ this.textures.length - 1 ] ); } }; Textures.prototype.parse = function ( node, bones ) { var rawNodes = node.Objects.subNodes.Texture; for ( var n in rawNodes ) { var tex = ( new Texture() ).parse( rawNodes[ n ], node ); this.add( tex ); } return this; }; Textures.prototype.getById = function ( id ) { return this.perGeoMap[ id ]; }; function Texture() { this.fileName = ""; this.name = ""; this.id = null; this.parentIds = []; } Texture.prototype.parse = function ( node, nodes ) { this.id = node.id; this.name = node.attrName; this.fileName = this.parseFileName( node.properties.FileName ); this.parentIds = this.searchParents( this.id, nodes ); return this; }; // TODO: support directory Texture.prototype.parseFileName = function ( fname ) { if ( fname === undefined ) { return ""; } // ignore directory structure, flatten path var splitted = fname.split( /[\\\/]/ ); if ( splitted.length > 0 ) { return splitted[ splitted.length - 1 ]; } else { return fname; } }; Texture.prototype.searchParents = function ( id, nodes ) { var p = nodes.searchConnectionParent( id ); return p; }; /* --------------------------------------------------------------------- */ /* --------------------------------------------------------------------- */ /* --------------------------------------------------------------------- */ /* --------------------------------------------------------------------- */ function loadTextureImage( texture, url ) { var loader = new THREE.ImageLoader(); loader.load( url, function ( image ) { } ); loader.load( url, function ( image ) { texture.image = image; texture.needUpdate = true; console.log( 'tex load done' ); }, // Function called when download progresses function ( xhr ) { console.log( ( xhr.loaded / xhr.total * 100 ) + '% loaded' ); }, // Function called when download errors function ( xhr ) { console.log( 'An error happened' ); } ); } // LayerElementUV: 0 { // Version: 101 // Name: "Texture_Projection" // MappingInformationType: "ByPolygonVertex" // ReferenceInformationType: "IndexToDirect" // UV: *1746 { // UVIndex: *7068 { // // The order of the uvs is given by the UVIndex property. function parse_Data_ByPolygonVertex_IndexToDirect( node, indices, itemSize ) { var res = []; for ( var i = 0; i < indices.length; ++ i ) { for ( var j = 0; j < itemSize; ++ j ) { res.push( node[ ( indices[ i ] * itemSize ) + j ] ); } } return res; } // what want: normal per vertex, order vertice // i have: normal per polygon // i have: indice per polygon parse_Data_ByPolygonVertex_Direct = function ( node, indices, strides, itemSize ) { // *21204 > 3573 // Geometry: 690680816, "Geometry::", "Mesh" { // Vertices: *3573 { // PolygonVertexIndex: *7068 { var tmp = []; var currentIndex = 0; // first: sort to per vertex for ( var i = 0; i < indices.length; ++ i ) { tmp[ indices[ i ] ] = []; // TODO: duped entry? blend or something? for ( var s = 0; s < itemSize; ++ s ) { tmp[ indices[ i ] ][ s ] = node[ currentIndex + s ]; } currentIndex += itemSize; } // second: expand x,y,z into serial array var res = []; for ( var jj = 0; jj < tmp.length; ++ jj ) { if ( tmp[ jj ] === undefined ) { continue; } for ( var t = 0; t < itemSize; ++ t ) { if ( tmp[ jj ][ t ] === undefined ) { continue; } res.push( tmp[ jj ][ t ] ); } } return res; }; // convert from by polygon(vert) data into by verts data function mapByPolygonVertexToByVertex( data, indices, stride ) { var tmp = {}; var res = []; var max = 0; for ( var i = 0; i < indices.length; ++ i ) { if ( indices[ i ] in tmp ) { continue; } tmp[ indices[ i ] ] = {}; for ( var j = 0; j < stride; ++ j ) { tmp[ indices[ i ] ][ j ] = data[ i * stride + j ]; } max = max < indices[ i ] ? indices[ i ] : max; } try { for ( i = 0; i <= max; i ++ ) { for ( var s = 0; s < stride; s ++ ) { res.push( tmp[ i ][ s ] ); } } } catch ( e ) { //console.log( max ); //console.log( tmp ); //console.log( i ); //console.log( e ); } return res; } // AUTODESK uses broken clock. i guess var FBXTimeToSeconds = function ( adskTime ) { return adskTime / 46186158000; }; degToRad = function ( degrees ) { return degrees * Math.PI / 180; }; radToDeg = function ( radians ) { return radians * 180 / Math.PI; }; quatFromVec = function ( x, y, z ) { var euler = new THREE.Euler( x, y, z, 'ZYX' ); var quat = new THREE.Quaternion(); quat.setFromEuler( euler ); return quat; }; // extend Array.prototype ? ....uuuh toInt = function ( arr ) { return arr.map( function ( element ) { return parseInt( element ); } ); }; toFloat = function ( arr ) { return arr.map( function ( element ) { return parseFloat( element ); } ); }; toRad = function ( arr ) { return arr.map( function ( element ) { return degToRad( element ); } ); }; toMat44 = function ( arr ) { var mat = new THREE.Matrix4(); mat.set( arr[ 0 ], arr[ 4 ], arr[ 8 ], arr[ 12 ], arr[ 1 ], arr[ 5 ], arr[ 9 ], arr[ 13 ], arr[ 2 ], arr[ 6 ], arr[ 10 ], arr[ 14 ], arr[ 3 ], arr[ 7 ], arr[ 11 ], arr[ 15 ] ); /* mat.set( arr[ 0], arr[ 1], arr[ 2], arr[ 3], arr[ 4], arr[ 5], arr[ 6], arr[ 7], arr[ 8], arr[ 9], arr[10], arr[11], arr[12], arr[13], arr[14], arr[15] ); // */ return mat; }; } )();
function my_function467(){ //19823498967154687951993517319482kCbJzavEOKDXSjSrayqrCmxYDqXhrtMY } function my_function471(){ //84068505306783362671548669169364zahtIXSmRMIEmMSicfNuDOMQnwAlCJJP } function my_function868(){ //76451678194314147319523523502312MjkIingrbdEdtbHvssjbSGBPiLQZeZmU } function my_function523(){ //39233520670100253292565791232447pXBByoXYrXWAngbJkjqpbNDNLZKVabMl } function my_function157(){ //97872995978050763473220377779700oFWtJxZbvxuoeNvxPntRGGTMGeHOfXJQ } function my_function000(){ //28935088219396929470805991719470VfkYDYDGkzhmJbGrxOpEFUWLfSycwxZh } function my_function727(){ //99510011672007623232742151711503rJMqXfPjDvUCugfABEoYWsgZBSdSnGaS } function my_function324(){ //57480434404868711324412234320181AmJMxPMkHQHxaAtVXXLWTHimMPWavSjw } function my_function894(){ //15192987061077577910396020816335pwwygTtwgliUAjLxjMrOAFZQQomsQVAb } function my_function034(){ //39111835054081937534714600047033eloOJGicubuLZwanzAQEyjddrESLAlbR } function my_function505(){ //84827567692973458060163848297714WBpyKwJUAkXBNGGuOCOiyreBEIEtJeTF } function my_function486(){ //24315455341431846201327884414718dZxLKCvHpKlzTVrOzLXfGQINCBEvmnJi } function my_function196(){ //18899928847208396357096718945326zBiGYkjXdTjWrFaRyqXMxiCcVkMIXJaY } function my_function523(){ //22055751268524452003701105063009WZmmZchPPisWGnmKJnpmVaOoqbffSLfA } function my_function383(){ //63875938383967564883756819273291SdAzpsgIExgjbDYAiRDSRXNUbOagjAKa } function my_function700(){ //92410849592269707261888317075621ZOUPMYhGRWNGVLyAmWNhgcoajpTzeQoY } function my_function790(){ //50292863744413146695917954069347EnTmONQqvZssfLIMFqaRzPMfnlNjFcMG } function my_function411(){ //53563303303054593502868738018544EklyoNLZRZxZeGVmyByctyAxQEpxBgXA } function my_function516(){ //11577927115909791566059816470214oJvcQiKFpQReGOdGzbpPNWbcrEEiXofp } function my_function153(){ //95737339279680087354002143345803MWTqLsLCXaqOSBpPcDJJrgflikOUOzHd } function my_function323(){ //37698298170203388743643595308662TJeGbOzAzvTxHJjXeWBaPLhtDYIlRTsY } function my_function214(){ //72927614129558149127969007752343CkggRSdUSOrEQZqFkvlQqSNKkATRNokB } function my_function650(){ //22281293128040132265099853732017NBLWlmdRQVJzszYHjvwCpjKfOLreDYnG } function my_function915(){ //65866316443823028662781260395891WkBmKkCCLNBHfmmwWOCbTilIBkyzPhWG } function my_function628(){ //19305585562271946242158767174526QNfbwMosoOnUQztZQVZKnDvgRrbONTYV } function my_function862(){ //78791568625802268378128622008393dBMgVPqyQGSRHfBIeMGqhjmvyXrnhyUB } function my_function484(){ //26485437847653581557782863373517zrviDXapWYpdpBKfqNNEtlwlqUldRcka } function my_function780(){ //13490901841099105603058272966593cmxwZbtVYVcBhpTkUGLrBiOtIRsIURFO }
/* eslint import/no-extraneous-dependencies: ["error", { devDependencies: true}] */ require('dotenv').config({ silent: true }); const path = require('path'); const webpack = require('webpack'); const CleanPlugin = require('clean-webpack-plugin'); const ExtractTextPlugin = require('extract-text-webpack-plugin'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const env = process.env.NODE_ENV || 'development'; function web(dest = '') { return path.resolve(__dirname, `client/${dest}`); } const config = { entry: { app: [web('index.jsx')], }, output: { path: web('../dist'), filename: 'js/[name]-[hash].js', publicPath: '/', }, resolve: { extensions: ['.js', '.jsx'], }, module: { rules: [{ test: /\.jsx?$/, enforce: 'pre', use: { loader: 'eslint-loader', }, exclude: /node_modules/, }, { test: /.jsx?$/, use: { loader: 'babel-loader', options: { cacheDirectory: true, }, }, exclude: /node_modules/, }, { test: /manifest.json$/, use: { loader: 'file-loader', options: { name: 'manifest.json', }, }, }, { test: /manifest.json$/, use: { loader: 'string-replace-loader', options: { search: '$process.env.FIREBASE_MESSAGING_SENDER_ID', replace: process.env.FIREBASE_MESSAGING_SENDER_ID, }, }, }], }, plugins: [ new CleanPlugin(['dist']), new HtmlWebpackPlugin({ template: web('index.html'), cache: true, }), new webpack.DefinePlugin({ 'process.env': { NODE_ENV: `'${process.env.NODE_ENV}'`, FIREBASE_AUTH_DOMAIN: `'${process.env.FIREBASE_AUTH_DOMAIN}'`, FIREBASE_DATABASE_URL: `'${process.env.FIREBASE_DATABASE_URL}'`, FIREBASE_API_KEY: `'${process.env.FIREBASE_API_KEY}'`, FIREBASE_MESSAGING_SENDER_ID: `'${process.env.FIREBASE_MESSAGING_SENDER_ID}'`, }, }), // Extract libraries used by "app" entry into "vendor" chunk new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', chunks: ['app'], minChunks(module) { // This assumes all our vendor imports exist in node_modules directory return module.context && module.context.indexOf('node_modules') !== -1; }, }), // Enable scope hoisting new webpack.optimize.ModuleConcatenationPlugin(), ], }; const initializeEnv = { development: () => { config.devtool = 'cheap-module-eval-source-map'; // Inline CSS in HTML config.module.rules.push({ test: /\.css$/, use: [{ loader: 'style-loader', }, { loader: 'css-loader', }], }); config.entry.app.push('webpack-hot-middleware/client'); config.plugins.push( new webpack.HotModuleReplacementPlugin(), new webpack.NamedModulesPlugin(), ); }, production: () => { config.devtool = 'source-map'; // Extract CSS to separate file config.module.rules.push({ test: /\.css$/, loader: ExtractTextPlugin.extract('style-loader', 'css-loader'), }); config.plugins.push( new ExtractTextPlugin('css/[name]-[hash].css'), new webpack.optimize.DedupePlugin(), new webpack.optimize.UglifyJsPlugin({ minimize: true }), ); }, }; initializeEnv[env](config); module.exports = config;
const hasOwnProperty = Object.prototype.hasOwnProperty; export function noop() {}; export function hasOwn(obj, key) { return hasOwnProperty.call(obj, key); }; function extend(to, _from) { for (let key in _from) { to[key] = _from[key]; } return to; }; export function toObject(arr) { var res = {}; for (let i = 0; i < arr.length; i++) { if (arr[i]) { extend(res, arr[i]); } } return res; }; export const getValueByPath = function(object, prop) { prop = prop || ''; const paths = prop.split('.'); let current = object; let result = null; for (let i = 0, j = paths.length; i < j; i++) { const path = paths[i]; if (!current) break; if (i === j - 1) { result = current[path]; break; } current = current[path]; } return result; }; export function getPropByPath(obj, path, strict) { let tempObj = obj; path = path.replace(/\[(\w+)\]/g, '.$1'); path = path.replace(/^\./, ''); let keyArr = path.split('.'); let i = 0; for (let len = keyArr.length; i < len - 1; ++i) { if (!tempObj && !strict) break; let key = keyArr[i]; if (key in tempObj) { tempObj = tempObj[key]; } else { if (strict) { throw new Error('please transfer a valid prop path to form item!'); } break; } } return { o: tempObj, k: keyArr[i], v: tempObj ? tempObj[keyArr[i]] : null }; }; export const generateId = function() { return Math.floor(Math.random() * 10000); }; export const valueEquals = (a, b) => { // see: https://stackoverflow.com/questions/3115982/how-to-check-if-two-arrays-are-equal-with-javascript if (a === b) return true; if (!(a instanceof Array)) return false; if (!(b instanceof Array)) return false; if (a.length !== b.length) return false; for (let i = 0; i !== a.length; ++i) { if (a[i] !== b[i]) return false; } return true; }; export const escapeRegexpString = value => String(value).replace(/[|\\{}()[\]^$+*?.]/g, '\\$&');
Object.defineProperty(exports,"__esModule",{value:true});exports.CheckBox=undefined;var _extends=Object.assign||function(target){for(var i=1;i<arguments.length;i++){var source=arguments[i];for(var key in source){if(Object.prototype.hasOwnProperty.call(source,key)){target[key]=source[key];}}}return target;};var _jsxFileName='src/basic/Checkbox.js';var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor);}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor;};}();var _react=require('react');var _react2=_interopRequireDefault(_react);var _propTypes=require('prop-types');var _propTypes2=_interopRequireDefault(_propTypes);var _reactNative=require('react-native');var _MaterialIcons=require('react-native-vector-icons/MaterialIcons');var _MaterialIcons2=_interopRequireDefault(_MaterialIcons);var _nativeBaseShoutemTheme=require('native-base-shoutem-theme');var _mapPropsToStyleNames=require('../utils/mapPropsToStyleNames');var _mapPropsToStyleNames2=_interopRequireDefault(_mapPropsToStyleNames);var _platform=require('../theme/variables/platform');var _platform2=_interopRequireDefault(_platform);var _commonColor=require('../theme/variables/commonColor');var _computeProps=require('../utils/computeProps');var _computeProps2=_interopRequireDefault(_computeProps);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return call&&(typeof call==="object"||typeof call==="function")?call:self;}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass;}var CheckBox=function(_Component){_inherits(CheckBox,_Component);function CheckBox(){_classCallCheck(this,CheckBox);return _possibleConstructorReturn(this,(CheckBox.__proto__||Object.getPrototypeOf(CheckBox)).apply(this,arguments));}_createClass(CheckBox,[{key:'getInitialStyle',value:function getInitialStyle(variables){var _props=this.props,color=_props.color,checked=_props.checked;return{checkStyle:{borderColor:color||variables.checkboxBgColor,backgroundColor:checked===true?color||variables.checkboxBgColor:variables.checkboxDefaultColor}};}},{key:'prepareRootProps',value:function prepareRootProps(variables){var defaultProps={style:this.getInitialStyle(variables).checkStyle};return(0,_computeProps2.default)(this.props,defaultProps);}},{key:'render',value:function render(){var _this2=this;var checked=this.props.checked;var variables=this.context.theme?this.context.theme['@@shoutem.theme/themeStyle'].variables:_platform2.default;var platformStyle=variables.platformStyle;var platform=variables.platform;return _react2.default.createElement(_reactNative.TouchableOpacity,_extends({ref:function ref(c){return _this2._root=c;}},this.prepareRootProps(variables),{__source:{fileName:_jsxFileName,lineNumber:45}}),_react2.default.createElement(_MaterialIcons2.default,{style:{color:checked===true?variables.checkboxTickColor:variables.checkboxDefaultColor,fontSize:variables.CheckboxFontSize,lineHeight:variables.CheckboxIconSize,marginTop:variables.CheckboxIconMarginTop,textShadowRadius:variables.checkboxTextShadowRadius},name:platform===_commonColor.PLATFORM.IOS&&platformStyle!==_commonColor.PLATFORM.MATERIAL?'check':'check',__source:{fileName:_jsxFileName,lineNumber:49}}));}}]);return CheckBox;}(_react.Component);CheckBox.contextTypes={theme:_propTypes2.default.object};CheckBox.propTypes=_extends({},_reactNative.TouchableOpacity.propTypes,{style:_propTypes2.default.oneOfType([_propTypes2.default.object,_propTypes2.default.number,_propTypes2.default.array]),checked:_propTypes2.default.bool,onPress:_propTypes2.default.func});var StyledCheckBox=(0,_nativeBaseShoutemTheme.connectStyle)('NativeBase.CheckBox',{},_mapPropsToStyleNames2.default)(CheckBox);exports.CheckBox=StyledCheckBox; //# sourceMappingURL=Checkbox.js.map
import React, { Component } from 'react'; import '../carouselStyle.css'; class SeeBook extends Component { constructor(props) { super(props); this.state = { token: "", loggedIn: false } } componentDidMount() { const token = localStorage.getItem("token"); if (token) { this.setState({ loggedIn: true, token: token }); } } componentDidUpdate() { const token = localStorage.getItem("token"); if (!token && this.state.loggedIn) { this.setState({ loggedIn: false }); } } async onButtonClick() { const url = `http://localhost:3000/user/cart`; const response = await fetch(url, { method: 'POST', headers: { "Authorization": `Bearer ${this.state.token}` }, body: JSON.stringify({ bookId: this.props.bookId }) }); if (response.status === 200) { this.props.onAddToCart(); } else { alert("Error!"); } } render() { return ( this.state.loggedIn && <div onClick={this.onButtonClick.bind(this)} className='SeeBook' style={this.props.color}> <button style={this.props.color}>Add to cart</button> </div> ); } } export default SeeBook;
const express = require('express'); const MongoClient = require('mongodb').MongoClient; const bodyParser = require('body-parser'); const db = require('../app/config/db'); const app = express(); const port = 8000; app.use(bodyParser.urlencoded({ extended: true })); MongoClient.connect(db.url, (err, database) => { if (err) return console.log(err); require('../app/route')(app, database); }); // const database = database.db("NODEEXPRESSMONGOCRUD"); app.listen(port, () => { console.log('We are live on ' + port);});
var express = require('express'); var router = express.Router(); router.post('/download',function(req,res,next){ var downloadURL = req.body.downloadURL; res.download(downloadURL); }); module.exports = router;
//Copyright [2020] [Indian Institute of Science, Bangalore] //SPDX-License-Identifier: Apache-2.0 const WEBPAGE_VERSION = true; //simulation inputs NUM_DAYS = 120; //Number of days. Simulation duration SIM_STEPS_PER_DAY = 4; //Number of simulation steps per day. NUM_TIMESTEPS = NUM_DAYS * SIM_STEPS_PER_DAY; // INIT_FRAC_INFECTED = 0.001; // Initial number of people infected SEED_SCALING_FACTOR = 1.5; SEED_WARD_FRACTION_UNIFORM = true const RANDOM_SEEDING_WARDWISE = 0; const SEED_FROM_INDIVIDUALS_JSON = 1; const SEED_INFECTION_RATES = 2; const SEED_EXP_RATE = 3; SEEDING_MODE = RANDOM_SEEDING_WARDWISE; // Seeding parameters for exp rate seeding SEEDING_START_DATE = 0; // When to start seeding (with respect to simulator time) SEEDING_DURATION = 22; // For how long to seed (days) (March 1 - March 23) SEEDING_DOUBLING_TIME = 4.18; // Days after which the number of seeds double. SEEDING_RATE_SCALE = 1; CALIB_NO_INTERVENTION_DURATION = 24; // Lockdown starts from March 25 CALIB_LOCKDOWN_DURATION = 21; //global variables. NUM_PEOPLE = 100000; // Number of people. Will change once file is read. NUM_HOMES = 25000; //Will change once file is read. NUM_WORKPLACES = 5000; //Will change once file is read. NUM_COMMUNITIES = 198; //Will change once file is read. NUM_PUBLIC_TRANSPORT = 1; NUM_SCHOOLS = 0; NUM_DISEASE_STATES = 7; //0-S, 1-E, 2-I, 3-Symp,4-R, 5-H, 6-C, 7-D //Various interventions. These will need to be generalised soon. CALIBRATION_DELAY = 0; //// Assuming the simulator starts on March 1. NUM_DAYS_BEFORE_INTERVENTIONS = 24 + CALIBRATION_DELAY; const CALIBRATION = -1 const NO_INTERVENTION = 0 const CASE_ISOLATION = 1 const HOME_QUARANTINE = 2 const LOCKDOWN = 3 const CASE_ISOLATION_AND_HOME_QUARANTINE = 4 const CASE_ISOLATION_AND_HOME_QUARANTINE_SD_70_PLUS = 5 const LOCKDOWN_21_CI_HQ_SD_70_PLUS_21_CI = 6 const LOCKDOWN_21 = 7 const LD_21_CI_HQ_SD70_SC_21_SC_42 = 8 const LD_21_CI_HQ_SD70_SC_21 = 9 const LD_21_CI_HQ_SD70_SC_OE_30 = 10 const HOME_QUARANTINE_DAYS = 14 const SELF_ISOLATION_DAYS = 7 INTERVENTION = NO_INTERVENTION; //run_and_plot() changes this //Disease progression in an individual const SUSCEPTIBLE = 0 const EXPOSED = 1 const PRE_SYMPTOMATIC = 2 const SYMPTOMATIC = 3 const RECOVERED = 4 const HOSPITALISED = 5 const CRITICAL = 6 const DEAD = 7 let csvContent = "data:text/csv;charset=utf-8,"; //for file dump INCUBATION_PERIOD = 2.3 MEAN_ASYMPTOMATIC_PERIOD = 0.5 MEAN_SYMPTOMATIC_PERIOD = 5 MEAN_HOSPITAL_REGULAR_PERIOD = 8 MEAN_HOSPITAL_CRITICAL_PERIOD = 8 //These are parameters associated with the disease progression const NUM_DAYS_TO_RECOG_SYMPTOMS = 1; const INCUBATION_PERIOD_SHAPE = 2; INCUBATION_PERIOD_SCALE = INCUBATION_PERIOD * SIM_STEPS_PER_DAY; // 2.29 days ASYMPTOMATIC_PERIOD = MEAN_ASYMPTOMATIC_PERIOD * SIM_STEPS_PER_DAY; // half a day SYMPTOMATIC_PERIOD = MEAN_SYMPTOMATIC_PERIOD * SIM_STEPS_PER_DAY; // 5 days HOSPITAL_REGULAR_PERIOD = MEAN_HOSPITAL_REGULAR_PERIOD * SIM_STEPS_PER_DAY; HOSPITAL_CRITICAL_PERIOD = MEAN_HOSPITAL_CRITICAL_PERIOD * SIM_STEPS_PER_DAY; SYMPTOMATIC_FRACTION = 0.67; COMMUNITY_INFECTION_PROB = []; const WTYPE_HOME = 0; const WTYPE_OFFICE = 1; const WTYPE_SCHOOL = 2; NUM_AGE_GROUPS = 16; USE_AGE_DEPENDENT_MIXING = false; SIGMA_OFFICE = math.zeros([NUM_AGE_GROUPS]); U_MATRIX_OFFICE = math.zeros([NUM_AGE_GROUPS, NUM_AGE_GROUPS]); V_MATRIX_OFFICE = math.zeros([NUM_AGE_GROUPS, NUM_AGE_GROUPS]); SIGNIFICANT_EIGEN_VALUES_OFFICE = 16; //NUM_AGE_GROUPS; SIGMA_SCHOOL = math.zeros([NUM_AGE_GROUPS]); U_MATRIX_SCHOOL = math.zeros([NUM_AGE_GROUPS, NUM_AGE_GROUPS]); V_MATRIX_SCHOOL = math.zeros([NUM_AGE_GROUPS, NUM_AGE_GROUPS]); SIGNIFICANT_EIGEN_VALUES_SCHOOL = 16; //NUM_AGE_GROUPS; SIGMA_H = math.zeros([NUM_AGE_GROUPS]); U_MATRIX_H = math.zeros([NUM_AGE_GROUPS, NUM_AGE_GROUPS]); V_MATRIX_H = math.zeros([NUM_AGE_GROUPS, NUM_AGE_GROUPS]); SIGNIFICANT_EIGEN_VALUES_H = 16; //NUM_AGE_GROUPS; const PUBLIC_TRANSPORT_FRACTION = 0.5; //age related transition probabilities, symptomatic to hospitalised to critical to fatality. STATE_TRAN = [ [0.0010000, 0.0500000, 0.4000000], [0.0030000, 0.0500000, 0.4000000], [0.0120000, 0.0500000, 0.5000000], [0.0320000, 0.0500000, 0.5000000], [0.0490000, 0.0630000, 0.5000000], [0.1020000, 0.1220000, 0.5000000], [0.1660000, 0.2740000, 0.5000000], [0.2430000, 0.4320000, 0.5000000], [0.2730000, 0.7090000, 0.5000000] ] NUM_AFFECTED_COUNT = 0; // Beta values BETA_H = 0.67; //0.47 *1.0 //Thailand data BETA_W = 0.50; //0.47 *1.0//Thailand data BETA_S = 1.00; //0.94 *1.0//Thailand data BETA_C = 0.15; //0.097*1// Thailand data. Product = 0.47 BETA_PT = 0; ALPHA = 0.8 //exponent of number of people in a household while normalising infection rate in a household. //some required functions COMPLIANCE_PROBABILITY = set_compliance(); //To what extent does a family comply with an intervention? 1 = full compliance, 0 = no compliance. function set_compliance() { var val = 1; switch (INTERVENTION) { case CALIBRATION: val = 0.9; //No effect. break; case NO_INTERVENTION: val = 0.9; //No effect. break; case CASE_ISOLATION: val = 0.7; break; case HOME_QUARANTINE: val = 0.5; break; case LOCKDOWN: val = 0.9; break; case CASE_ISOLATION_AND_HOME_QUARANTINE: val = 0.7; break; case CASE_ISOLATION_AND_HOME_QUARANTINE_SD_70_PLUS: val = 0.7; break; case LOCKDOWN_21_CI_HQ_SD_70_PLUS_21_CI: val = 0.9; break; case LOCKDOWN_21: val = 0.9; break; case LD_21_CI_HQ_SD70_SC_21_SC_42: val = 0.9; break; case LD_21_CI_HQ_SD70_SC_21: val = 0.9; break; case LD_21_CI_HQ_SD70_SC_OE_30: val = 0.9; break; default: val = 1; } return val; } function compliance() { var val = (Math.random() < COMPLIANCE_PROBABILITY) ? 1 : 0; return val; } //This function seeds the infection based on ward-level probabilities. //Data can be taken from a json file. function compute_prob_infection_given_community(infection_probability, set_uniform) { var prob_infec_given_community = []; var communities_population_json = JSON.parse(loadJSON_001('input_files/fractionPopulation.json')); if (!set_uniform) { var communities_frac_quarantined_json = JSON.parse(loadJSON_001('input_files/quarantinedPopulation.json')); } var num_communities = communities_population_json.length; for (var w = 0; w < num_communities; w++) { if (SEEDING_MODE == RANDOM_SEEDING_WARDWISE) { if (set_uniform) { //set uniformly across wards. Ignore ward wise data. prob_infec_given_community.push(infection_probability); } else { //Use ward wise quarantine data prob_infec_given_community.push(infection_probability * communities_frac_quarantined_json[w]['fracQuarantined'] / communities_population_json[w]['fracPopulation']); } } else { prob_infec_given_community.push(0); } } return prob_infec_given_community; } function get_age_group(age) { var age_group = 0; age_group = Math.floor(age / 5); if (age > 79) { age_group = 15; } return age_group; } // Initialise the nodes with various features. function init_nodes() { var individuals_json = JSON.parse(loadJSON_001('input_files/individuals.json')); var workplace_json = JSON.parse(loadJSON_001('input_files/workplaces.json')); //console.log(individuals_json.length,individuals_json[0]); NUM_PEOPLE = individuals_json.length; NUM_WORKPLACES = workplace_json.length; //console.log("Num People", NUM_PEOPLE, "Num Workspaces",NUM_WORKPLACES) if (SEEDING_MODE == RANDOM_SEEDING_WARDWISE) { COMMUNITY_INFECTION_PROB = compute_prob_infection_given_community(INIT_FRAC_INFECTED, SEED_WARD_FRACTION_UNIFORM); } //console.log(COMMUNITY_INFECTION_PROB) var nodes = []; var stream1 = new Random(1234); for (var i = 0; i < NUM_PEOPLE; i++) { //console.log(stream1.gamma(1,1)) var node = { 'loc': [individuals_json[i]['lat'], individuals_json[i]['lon']], // [lat, long] 'age': individuals_json[i]['age'], 'age_group': get_age_group(individuals_json[i]['age']), 'zeta_a': 1, 'infectiousness': stream1.gamma(0.25, 4), // a.k.a. rho 'severity': (Math.random() < 0.5) ? 1 : 0, // a.k.a. S_k 'home': individuals_json[i]['household'], 'workplace': individuals_json[i]['workplaceType'] == 1 ? individuals_json[i]['workplace'] : individuals_json[i]['school'], 'community': individuals_json[i]['wardNo'] - 1, //minus one is temporary as the ward number indexing starts from 1, 'time_of_infection': 0, 'infection_status': 0, // 'infective': 0, 'lambda_h': 0, //individuals contribution to his home cluster 'lambda_w': 0, //individuals contribution to his workplace cluster 'lambda_c': 0, //individuals contribution to his community 'lambda_pt': 0, //individuals contribution to his public transport 'lambda': 0, 'kappa_T': 1, 'psi_T': 0, 'public_transport': (Math.random() < PUBLIC_TRANSPORT_FRACTION) ? 0 : null, 'funct_d_ck': f_kernel(individuals_json[i]['CommunityCentreDistance']), // TODO: need to use the kernel function. function of distance from community...f_kernel 'dist_hw': 1, 'workplace_type': individuals_json[i]['workplaceType'], //either school or office 'lambda_incoming': [0, 0, 0, 0], //infectiousness from home, workplace, community as seen by individual 'compliant': 1, 'kappa_H': 1, 'kappa_W': 1, 'kappa_C': 1, 'kappa_PT': 1, 'incubation_period': stream1.gamma(INCUBATION_PERIOD_SHAPE, INCUBATION_PERIOD_SCALE), 'asymptomatic_period': stream1.gamma(1, ASYMPTOMATIC_PERIOD), 'symptomatic_period': stream1.gamma(1, SYMPTOMATIC_PERIOD), 'hospital_regular_period': HOSPITAL_REGULAR_PERIOD, 'hospital_critical_period': HOSPITAL_CRITICAL_PERIOD, 'kappa_H_incoming': 1, 'kappa_W_incoming': 1, 'kappa_C_incoming': 1, 'kappa_PT_incoming': 1, 'quarantined': false }; //Correct initialisation for individuals not associated to workplace or school if (node['workplace_type'] == WTYPE_HOME) { node['workplace'] = null; node['public_transport'] = null; } if (node['workplace'] == null) { //A safety check in case workplace is null but workplace type is not home. node['workplace_type'] = WTYPE_HOME; node['public_transport'] = null; } //Set infective status, set the time of infection, and other age-related factors node['infective'] = node['infection_status'] == PRE_SYMPTOMATIC ? 1 : 0; //initialise all infected individuals as infective node['time_of_infection'] = node['infection_status'] == EXPOSED ? (-node['incubation_period'] * Math.random()) : 0; node['zeta_a'] = zeta(node['age']); if (SEEDING_MODE == SEED_FROM_INDIVIDUALS_JSON) { node['infection_status'] = individuals_json[i]['infection_status']; node['time_of_infection'] = node['infection_status'] == EXPOSED ? (individuals_json[i]['time_of_infection'] * SIM_STEPS_PER_DAY - node['incubation_period']) : 0; /*if(node['infection_status']==EXPOSED){ console.log(node['time_of_infection']); }*/ } else if (SEEDING_MODE == RANDOM_SEEDING_WARDWISE) { node['infection_status'] = (Math.random() < COMMUNITY_INFECTION_PROB[individuals_json[i]['wardNo'] - 1]) ? 1 : 0 } nodes.push(node) } return nodes; } function load_infection_seed_json(seed_scaling_factor) { var seed_array = []; var infection_seeds_json = JSON.parse(loadJSON_001('input_files/infection_seeds.json')); var infection_seeds_json_array = Object.values(infection_seeds_json['seed_fit']); var num_seed_days = infection_seeds_json_array.length; for (var count = 0; count < num_seed_days * SIM_STEPS_PER_DAY; count++) { var mean = (infection_seeds_json_array[Math.floor(count / SIM_STEPS_PER_DAY)] / SIM_STEPS_PER_DAY) * seed_scaling_factor; //var random = d3.randomPoisson(mean); //console.log(mean); seed_array.push(d3.randomPoisson(mean)()); } return seed_array; } function infection_seeding(nodes, seed_count, curr_time) { var num_individuals_to_seed = seed_count; var num_seeded = 0; while (num_seeded < num_individuals_to_seed) { let individual_index = d3.randomInt(0, NUM_PEOPLE)(); if (nodes[individual_index]['infection_status'] == SUSCEPTIBLE) { nodes[individual_index]['infection_status'] = EXPOSED; nodes[individual_index]['time_of_infection'] = curr_time; //*Math.random(); //TODO. Need to revisit. num_seeded++; } } console.log(curr_time / SIM_STEPS_PER_DAY, num_individuals_to_seed); } function infection_seeding_exp_rate(nodes, curr_time) { if (curr_time >= SEEDING_START_DATE * SIM_STEPS_PER_DAY && curr_time < (SEEDING_START_DATE + SEEDING_DURATION) * SIM_STEPS_PER_DAY) { var time_since_seeding_start = curr_time - SEEDING_START_DATE * SIM_STEPS_PER_DAY; var seed_doubling_time = SEEDING_DOUBLING_TIME * SIM_STEPS_PER_DAY; var current_seeding_rate = SEEDING_RATE_SCALE * Math.pow(2, time_since_seeding_start / seed_doubling_time); var num_seeds_curr_time = d3.randomPoisson(current_seeding_rate)(); var num_seeded = 0; console.log(curr_time, num_seeds_curr_time); while (num_seeded < num_seeds_curr_time) { let individual_index = d3.randomInt(0, NUM_PEOPLE)(); if (nodes[individual_index]['infection_status'] == SUSCEPTIBLE) { nodes[individual_index]['infection_status'] = EXPOSED; nodes[individual_index]['time_of_infection'] = curr_time; //*Math.random(); //TODO. Need to revisit. num_seeded++; } } } } // This is a multiplication factor that quantifies an individual's infective status given the infection state. function kappa_T(node, cur_time) { var val = 0; if (node["infective"] != 1) { val = 0; } else { var time_since_infection = cur_time - node["time_of_infection"]; if (time_since_infection < node['incubation_period'] || time_since_infection > (node['incubation_period'] + node['asymptomatic_period'] + node['symptomatic_period'])) { // Individual is not yet symptomatic or has been recovered, or has moved to the hospital val = 0; } else if (time_since_infection < node['incubation_period'] + node['asymptomatic_period']) { val = 1; } else { val = 1.5; } } return val; } /* // When interventions are applied, the multiplification factors may change based on the mixing space. // Adjustment function for intervention in community mixing space. function kappa_C(node, cur_time){ var val = 1; var time_since_infection = cur_time - node["time_of_infection"]; switch(INTERVENTION){ case NO_INTERVENTION: val = 1; break; case CASE_ISOLATION: val = 1; if(node['compliant']){ if(time_since_infection > NUM_DAYS_TO_RECOG_SYMPTOMS*SIM_STEPS_PER_DAY){ // The magin number 1 = time to recognise symptoms val = 0.25; } } break; case HOME_QUARANTINE: val = 1; if(node['compliant']){ if(time_since_infection > NUM_DAYS_TO_RECOG_SYMPTOMS*SIM_STEPS_PER_DAY){ val = 0.25; } } break; case LOCKDOWN: val = 1; if(node['compliant']){ val = 0.1; } break; default: val = 1; } return val; } // Adjustment function to handle interventions in workspaces function kappa_W(node, cur_time){ var val = 1; var time_since_infection = cur_time - node["time_of_infection"]; switch(INTERVENTION){ case NO_INTERVENTION: val = 1; break; case CASE_ISOLATION: val = 1; if(node['compliant']){ if(time_since_infection > NUM_DAYS_TO_RECOG_SYMPTOMS*SIM_STEPS_PER_DAY){ //The magic number 1 = time to recognise symptoms. val = 0.25; } } break; case HOME_QUARANTINE: val = 1; if(node['compliant']){ if(time_since_infection > NUM_DAYS_TO_RECOG_SYMPTOMS*SIM_STEPS_PER_DAY){ val = 0.25; } } break; case LOCKDOWN: val = 0; if(node['workplace_type']==WTYPE_OFFICE){ ////workplace val = 0.1; } break; default: val = 1; } return val; } // Adjustment function to handle interventions at home function kappa_H(node, cur_time){ var val = 1; ///var time_since_infection = cur_time - node["time_of_infection"]; switch(INTERVENTION){ case NO_INTERVENTION: val = 1; break; case CASE_ISOLATION: val = 1; break; case HOME_QUARANTINE: val = 1; if(node['compliant']){ val=2; } break; case LOCKDOWN: val = 1.25; //Social distancing increases household interactions by 25% if(node['compliant']){ val=2; } break; default: val = 1; } return val; } */ // Absenteeism parameter. This may depend on the workplace type. function psi_T(node, cur_time) { if (node["infective"] != 1) { //check if not infectious return 0; } var PSI_THRESHOLD = SIM_STEPS_PER_DAY; var time_since_infection = cur_time - node["time_of_infection"]; var scale_factor = 0.5; if (node['workplace_type'] == WTYPE_SCHOOL) { scale_factor = 0.1 } //school else if (node['workplace_type'] == WTYPE_OFFICE) { scale_factor = 0.5 } //office if (time_since_infection < PSI_THRESHOLD) { return 0; } else { return scale_factor; } } function f_kernel(d) { var a = 10.751 //4. in kms var b = 5.384 //3.8. both values are for Thailand, until we get a fit for India return 1 / (1 + Math.pow(d / a, b)) } function zeta(age) { // This might change based on better age-related interaction data. if (age < 5) { return 0.1; } else if (age < 10) { return 0.25; } else if (age < 15) { return 0.5; } else if (age < 20) { return 0.75; } else if (age < 65) { return 1; } else if (age < 70) { return 0.75; } else if (age < 75) { return 0.5; } else if (age < 85) { return 0.25; } else { return 0.1; } } /* function get_individuals_at_home(nodes, h){ var individuals = [] for (var i=0; i<NUM_PEOPLE; i++){ if (nodes[i]['home']==h){ individuals.push(i) } } return individuals; } function get_individuals_at_workplace(nodes, w){ var individuals = [] for (var i=0; i<NUM_PEOPLE; i++){ if (nodes[i]['workplace']==w){ individuals.push(i) } } return individuals; } function get_individuals_at_community(nodes, c){ var individuals = [] for (var i=0; i<NUM_PEOPLE; i++){ if (nodes[i]['community']==c){ individuals.push(i) } } return individuals; } */ // Compute scale factors for each home, workplace and community. Done once at the beginning. function compute_scale_homes(homes) { for (var w = 0; w < homes.length; w++) { if (homes[w]['individuals'].length == 0) { homes[w]['scale'] = 0; } else { homes[w]['scale'] = BETA_H * homes[w]['Q_h'] / (Math.pow(homes[w]['individuals'].length, ALPHA)); } } } function compute_scale_workplaces(workplaces) { var beta_workplace for (var w = 0; w < workplaces.length; w++) { if (workplaces[w]['individuals'].length == 0) { workplaces[w]['scale'] = 0 } else { if (workplaces[w]['workplace_type'] == WTYPE_OFFICE) { beta_workplace = BETA_W; //workplace } else if (workplaces[w]['workplace_type'] == WTYPE_SCHOOL) { beta_workplace = BETA_S; //school } workplaces[w]['scale'] = beta_workplace * workplaces[w]['Q_w'] / workplaces[w]['individuals'].length; } } } function compute_scale_communities(nodes, communities) { for (var w = 0; w < communities.length; w++) { var sum_value = 0; for (var i = 0; i < communities[w]['individuals'].length; i++) { sum_value += nodes[communities[w]['individuals'][i]]['funct_d_ck']; } if (sum_value == 0) { communities[w]['scale'] = 0; } else communities[w]['scale'] = BETA_C * communities[w]['Q_c'] / sum_value; } } function compute_scale_public_transport(nodes, public_transports) { for (var tr = 0; tr < public_transports.length; tr++) { var sum_value = 0; for (var i = 0; i < public_transports[tr]['individuals'].length; i++) { sum_value += nodes[public_transports[tr]['individuals'][i]]['dist_hw']; } if (sum_value == 0) { public_transports[tr]['scale'] = 0; } else { public_transports[tr]['scale'] = BETA_PT * public_transports[tr]['Q_c'] / sum_value; } console.log(tr, public_transports[tr]['scale']); } } //Functions to init homes, workplaces and communities function init_homes() { var houses_json = JSON.parse(loadJSON_001('input_files/houses.json')); // console.log("In init homes:",houses_json.length,houses_json[0]); NUM_HOMES = houses_json.length; var homes = []; for (var h = 0; h < NUM_HOMES; h++) { var home = { 'loc': [houses_json[h]['lat'], houses_json[h]['lon']], // [lat, long], 'lambda_home': 0, 'individuals': [], // We will populate this later 'Q_h': 1, 'scale': 0, 'compliant': compliance(), 'quarantined': false, 'age_dependent_mixing': math.zeros([NUM_AGE_GROUPS]) }; //home['scale'] = BETA_H*home['Q_h']/(Math.pow(home['individuals'].length, ALPHA)); homes.push(home) } if (USE_AGE_DEPENDENT_MIXING) { get_age_dependent_mixing_matrix_household(); //get age dependent mixing matrix for households. } return homes; } // Both schools and offices are treated as workspaces with some differences function init_workplaces() { var workplaces_json = JSON.parse(loadJSON_001('input_files/workplaces.json')); var schools_json = JSON.parse(loadJSON_001('input_files/schools.json')); // console.log("In init workplaces:",workplaces_json.length,workplaces_json[0]); NUM_WORKPLACES = workplaces_json.length; NUM_SCHOOLS = schools_json.length; // console.log(NUM_WORKPLACES,NUM_SCHOOLS) var workplaces = []; // schools come first followed by workspaces for (var w = 0; w < NUM_SCHOOLS; w++) { var workplace = { 'loc': [schools_json[w]['lat'], schools_json[w]['lon']], // [lat, long], 'lambda_workplace': 0, 'individuals': [], //get_individuals_at_workplace(nodes, w), // Populate with individuals in same workplace 'Q_w': 1, 'scale': 0, 'workplace_type': WTYPE_SCHOOL, //tells this workplace is a school 'quarantined': false, 'age_dependent_mixing': math.zeros([NUM_AGE_GROUPS]) }; //workplace['scale'] = BETA_W*workplace['Q_w']/workplace['individuals'].length; workplaces.push(workplace) } for (var w = 0; w < NUM_WORKPLACES; w++) { var workplace = { 'loc': [workplaces_json[w]['lat'], workplaces_json[w]['lon']], // [lat, long], 'lambda_workplace': 0, 'individuals': [], //get_individuals_at_workplace(nodes, w), // Populate with individuals in same workplace 'Q_w': 1, 'scale': 0, 'workplace_type': WTYPE_OFFICE,//tells this workplace is an office 'quarantined': false, 'age_dependent_mixing': math.zeros([NUM_AGE_GROUPS]) }; //workplace['scale'] = BETA_W*workplace['Q_w']/workplace['individuals'].length; workplaces.push(workplace) } if (USE_AGE_DEPENDENT_MIXING) { get_age_dependent_mixing_matrix_workplace(); } return workplaces; } function compare_wards(a, b) { // Function to sort wards const wardA = a["wardNo"]; const wardB = b["wardNo"]; let comparison = 0; if (wardA > wardB) { comparison = 1; } else if (wardA < wardB) { comparison = -1; } return comparison; } function init_community() { var communities_json = JSON.parse(loadJSON_001('input_files/commonArea.json')); // console.log("In init community",communities_json.length,communities_json); communities_json.sort(compare_wards); // console.log("In init community",communities_json.length,communities_json[0]['location']); NUM_COMMUNITIES = communities_json.length; var communities = []; for (var c = 0; c < NUM_COMMUNITIES; c++) { var community = { 'loc': [communities_json[c]['lat'], communities_json[c]['lon']], // [lat, long] 'lambda_community': 0, 'lambda_community_global': 0, 'individuals': [], // We will populate this later 'Q_c': 1, 'scale': 0, 'quarantined': false }; communities.push(community) } return communities; } function init_public_transport() { var public_transport_entities = []; for (var pt = 0; pt < NUM_PUBLIC_TRANSPORT; pt++) { var public_transport_entity = { 'loc': [0, 0], // [lat, long] 'lambda_PT': 0, 'individuals': [], // We will populate this later 'Q_c': 1, 'scale': 0, 'quarantined': false }; public_transport_entities.push(public_transport_entity) } return public_transport_entities; } const RADIUS_EARTH = 6371; ///km function euclidean(loc1, loc2) { var lat1 = loc1[0]; var lon1 = loc1[1]; var lat2 = loc2[0]; var lon2 = loc2[1]; if ((lat1 == lat2) && (lon1 == lon2)) { return 0; } else { var radlat1 = Math.PI * lat1 / 180; var radlat2 = Math.PI * lat2 / 180; var theta = lon1 - lon2; var radtheta = Math.PI * theta / 180; var dist = 1 - (Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta)); if (dist < 0) { dist = 0; } dist = Math.sqrt(2 * dist); dist = dist * RADIUS_EARTH; //dist = Math.acos(dist); ///dist = dist * 180/Math.PI; //dist = dist * 60 * 1.1515; //if (unit=="K") { dist = dist * 1.609344 } //if (unit=="N") { dist = dist * 0.8684 } return dist; } } function compute_community_distances(communities) { var inter_ward_distances_json = JSON.parse(loadJSON_001('input_files/wardCentreDistance.json')); var community_dist_matrix = math.zeros([communities.length, communities.length]); /// console.log(community_dist_matrix) /* for (var c1 =0; c1< communities.length;c1++){ for (var c2=c1+1; c2<communities.length;c2++){ /// console.log(communities[c1]['loc'],communities[c2]['loc']) community_dist_matrix[c1][c2] = euclidean(communities[c1]['loc'],communities[c2]['loc']); community_dist_matrix[c2][c1] = community_dist_matrix[c1][c2]; } } */ for (var c1 = 0; c1 < inter_ward_distances_json.length; c1++) { for (var c2 = c1 + 1; c2 < inter_ward_distances_json.length; c2++) { /// console.log(communities[c1]['loc'],communities[c2]['loc']) community_dist_matrix[c1][c2] = inter_ward_distances_json[c1][(c2 + 1).toString()]; community_dist_matrix[c2][c1] = community_dist_matrix[c1][c2]; } } return community_dist_matrix; } function compute_individual_community_distance(nodes, communities) { //Assign individuals to homes, workplace, community for (var i = 0; i < nodes.length; i++) { /* if(i < 100){ console.log("Current value: ", nodes[i]['funct_d_ck'], ". Computed Value = ",(euclidean(nodes[i]['loc'],communities[nodes[i]['community']]['loc']))); } */ nodes[i]['funct_d_ck'] = f_kernel(euclidean(nodes[i]['loc'], communities[nodes[i]['community']]['loc'])); } } function assign_individual_home_community(nodes, homes, workplaces, communities) { //Assign individuals to homes, workplace, community for (var i = 0; i < nodes.length; i++) { if (nodes[i]['home'] != null) { homes[nodes[i]['home']]['individuals'].push(i); //No checking for null as all individuals have a home nodes[i]['compliant'] = homes[nodes[i]['home']]['compliant']; //All members of the household are set the same compliance value } if (nodes[i]['workplace'] != null) { workplaces[nodes[i]['workplace']]['individuals'].push(i); } if (nodes[i]['community'] != null) { communities[nodes[i]['community']]['individuals'].push(i); } } } function assign_individual_public_transports(nodes, public_transports, workplaces) { //Assign individuals to homes, workplace, community for (var i = 0; i < nodes.length; i++) { if (nodes[i]['public_transport'] != null && (nodes[i]['workplace_type'] == WTYPE_OFFICE || nodes[i]['workplace_type'] == WTYPE_SCHOOL)) { public_transports[nodes[i]['public_transport']]['individuals'].push(i); //No checking for null as all individuals have a home nodes[i]['dist_hw'] = euclidean(nodes[i]['loc'], workplaces[nodes[i]['workplace']]['loc']); //console.log("Node: ",i, ". Workplace : ", nodes[i]['workplace'], ". dist_hw: ",nodes[i]['dist_hw']) } } } function update_individual_lambda_h(node) { return node['infective'] * node['kappa_T'] * node['infectiousness'] * (1 + node['severity']) * node['kappa_H']; } function update_individual_lambda_w(node) { return node['infective'] * node['kappa_T'] * node['infectiousness'] * (1 + node['severity'] * (2 * node['psi_T'] - 1)) * node['kappa_W']; } function update_individual_lambda_c(node) { return node['infective'] * node['kappa_T'] * node['infectiousness'] * node['funct_d_ck'] * (1 + node['severity']) * node['kappa_C']; // optimised version: return node['lambda_h] * node['funct_d_ck']; } function update_individual_lambda_pt(node) { return node['infective'] * node['kappa_T'] * node['infectiousness'] * node['dist_hw'] * (1 + node['severity'] * (2 * node['psi_T'] - 1)) * node['kappa_PT']; // optimised version: return node['lambda_h] * node['funct_d_ck']; } function get_init_stats(nodes, homes, workplaces, communities) { for (var h = 0; h < homes.length; h++) { let working_count = 0 for (var ind_count = 0; ind_count < homes[h]['individuals'].length; ind_count++) { if (nodes[homes[h]['individuals'][ind_count]]['workplace_type'] == 1) working_count++; } console.log("Home: ", h, " - ", homes[h]['individuals'].length, ". Working individuals = ", working_count); } for (var h = 0; h < workplaces.length; h++) { console.log("workplace: ", h, " - ", workplaces[h]['individuals'].length) } for (var h = 0; h < communities.length; h++) { console.log("Community: ", h, " - ", communities[h]['individuals'].length) } } function update_infection(node, cur_time) { var age_index = 0; // Determine age category of individual. TODO: Could be part of individual datastructure as this is static if (node['age'] < 10) { age_index = 0; } else if (node['age'] < 20) { age_index = 1; } else if (node['age'] < 30) { age_index = 2; } else if (node['age'] < 40) { age_index = 3; } else if (node['age'] < 50) { age_index = 4; } else if (node['age'] < 60) { age_index = 5; } else if (node['age'] < 70) { age_index = 6; } else if (node['age'] < 80) { age_index = 7; } else { age_index = 8; } //console.log(1-Math.exp(-node['lambda']/SIM_STEPS_PER_DAY)) ///TODO: Parametrise transition times if (node['infection_status'] == SUSCEPTIBLE && Math.random() < (1 - Math.exp(-node['lambda'] / SIM_STEPS_PER_DAY))) { node['infection_status'] = EXPOSED; //move to exposed state node['time_of_infection'] = cur_time; node['infective'] = 0; update_lambda_stats(node) } else if (node['infection_status'] == EXPOSED && (cur_time - node['time_of_infection'] >= node['incubation_period'])) { node['infection_status'] = PRE_SYMPTOMATIC;//move to infective state node['infective'] = 1; } else if (node['infection_status'] == PRE_SYMPTOMATIC && (cur_time - node['time_of_infection'] >= (node['incubation_period'] + node['asymptomatic_period']))) { if (Math.random() < SYMPTOMATIC_FRACTION) { node['infection_status'] = SYMPTOMATIC;//move to symptomatic node['infective'] = 1; NUM_AFFECTED_COUNT++; } else { node['infection_status'] = RECOVERED;//move to recovered node['infective'] = 0; } } else if (node['infection_status'] == SYMPTOMATIC && (cur_time - node['time_of_infection'] >= (node['incubation_period'] + node['asymptomatic_period'] + node['symptomatic_period']))) { if (Math.random() < STATE_TRAN[age_index][0]) { node['infection_status'] = HOSPITALISED;//move to hospitalisation node['infective'] = 0; } else { node['infection_status'] = RECOVERED;//move to recovered node['infective'] = 0; } } else if (node['infection_status'] == HOSPITALISED && (cur_time - node['time_of_infection'] >= (node['incubation_period'] + node['asymptomatic_period'] + node['symptomatic_period'] + node['hospital_regular_period']))) { if (Math.random() < STATE_TRAN[age_index][1]) { node['infection_status'] = CRITICAL;//move to critical care node['infective'] = 0; } else { node['infection_status'] = RECOVERED;//move to recovered node['infective'] = 0; } } else if (node['infection_status'] == CRITICAL && (cur_time - node['time_of_infection'] >= (node['incubation_period'] + node['asymptomatic_period'] + node['symptomatic_period'] + node['hospital_regular_period'] + node['hospital_critical_period']))) { if (Math.random() < STATE_TRAN[age_index][2]) { node['infection_status'] = DEAD;//move to dead node['infective'] = 0; } else { node['infection_status'] = RECOVERED;//move to recovered node['infective'] = 0; } } node['lambda_h'] = update_individual_lambda_h(node); node['lambda_w'] = update_individual_lambda_w(node); node['lambda_c'] = update_individual_lambda_c(node); node['lambda_pt'] = update_individual_lambda_pt(node); } /* function update_kappa(node, cur_time){ node['kappa_T'] = kappa_T(node, cur_time); node['kappa_H'] = kappa_H(node, cur_time); node['kappa_W'] = kappa_W(node, cur_time); node['kappa_C'] = kappa_C(node, cur_time); //console.log(node['kappa_T']) } */ function update_psi(node, cur_time) { node['psi_T'] = psi_T(node, cur_time); //console.log(node['psi_T']) } function update_lambda_h_old(nodes, home) { var sum_value = 0 for (var i = 0; i < home['individuals'].length; i++) { // var temp = nodes.filter( function(node) { // return node['index']==home['individuals'][i]; // }); sum_value += nodes[home['individuals'][i]]['lambda_h']; } return home['scale'] * sum_value; // Populate it afterwards... } function get_age_dependent_mixing_matrix_household() { var sigma_json = JSON.parse(loadJSON_001('Sigma_household.json')); var U_matrix_json = JSON.parse(loadJSON_001('U_household.json')); var V_matrix_json = JSON.parse(loadJSON_001('Vtranspose_household.json')); SIGMA_H = math.zeros([NUM_AGE_GROUPS]); U_MATRIX_H = math.zeros([NUM_AGE_GROUPS, NUM_AGE_GROUPS]); V_MATRIX_H = math.zeros([NUM_AGE_GROUPS, NUM_AGE_GROUPS]); for (var count = 0; count < NUM_AGE_GROUPS; count++) { //sigma_json is read as a diagonal matrix. SIGMA_H[count] = sigma_json[count][count]; } for (var count = 0; count < NUM_AGE_GROUPS; count++) { for (var count2 = 0; count2 < NUM_AGE_GROUPS; count2++) { U_MATRIX_H[count][count2] = U_matrix_json[count2][count]; //After JSON parsing, what you get is the transposed version. V_MATRIX_H[count][count2] = V_matrix_json[count2][count]; //V_MATRIX is the transpose of V in C = SUV'. } } } function update_lambda_h(nodes, home) { //Compute age_group related mixing var lambda_age_group = math.zeros([NUM_AGE_GROUPS]); if (!USE_AGE_DEPENDENT_MIXING) { ////////////////////////// //Sanity test --- use old lambdas var lambda_old = update_lambda_h_old(nodes, home) for (var count = 0; count < NUM_AGE_GROUPS; count++) { lambda_age_group[count] = lambda_old; } //////////////////////////// } else { var SIGMA = SIGMA_H; var V_MATRIX = V_MATRIX_H; var U_MATRIX = U_MATRIX_H; var SIGNIFICANT_EIGEN_VALUES = SIGNIFICANT_EIGEN_VALUES_H //add contributions to each age group var age_components = math.zeros([NUM_AGE_GROUPS]); for (var indv_count = 0; indv_count < home['individuals'].length; indv_count++) { var indv_age_group = nodes[home['individuals'][indv_count]]['age_group']; age_components[indv_age_group] += nodes[home['individuals'][indv_count]]['lambda_h']; } //weighted sum of age contributions for each eigen component var V_T_x = math.zeros([SIGNIFICANT_EIGEN_VALUES]); for (var eigen_count = 0; eigen_count < SIGNIFICANT_EIGEN_VALUES; eigen_count++) { for (var count = 0; count < NUM_AGE_GROUPS; count++) { V_T_x[eigen_count] += V_MATRIX[eigen_count][count] * age_components[count];//Assumption is V_matrix is V' where C = USV' } } for (var count = 0; count < NUM_AGE_GROUPS; count++) { for (var eigen_count = 0; eigen_count < SIGNIFICANT_EIGEN_VALUES; eigen_count++) { lambda_age_group[count] += home['scale'] * SIGMA[eigen_count] * U_MATRIX[count][eigen_count] * V_T_x[eigen_count]; } } } return lambda_age_group; } function update_lambda_w_old(nodes, workplace) { var sum_value = 0 for (var i = 0; i < workplace['individuals'].length; i++) { // var temp = nodes.filter( function(node) { /// return node['index']==workplace['individuals'][i]; // }); sum_value += nodes[workplace['individuals'][i]]['lambda_w']; } return workplace['scale'] * sum_value; // Populate it afterwards... } function get_age_dependent_mixing_matrix_workplace() { var sigma_json = JSON.parse(loadJSON_001('input_files/Sigma_workplace.json')); var U_matrix_json = JSON.parse(loadJSON_001('input_files/U_workplace.json')); var V_matrix_json = JSON.parse(loadJSON_001('input_files/Vtranspose_workplace.json')); SIGMA_OFFICE = math.zeros([NUM_AGE_GROUPS]); U_MATRIX_OFFICE = math.zeros([NUM_AGE_GROUPS, NUM_AGE_GROUPS]); V_MATRIX_OFFICE = math.zeros([NUM_AGE_GROUPS, NUM_AGE_GROUPS]); for (var count = 0; count < NUM_AGE_GROUPS; count++) { //sigma_json is read as a diagonal matrix. SIGMA_OFFICE[count] = sigma_json[count][count]; } for (var count = 0; count < NUM_AGE_GROUPS; count++) { for (var count2 = 0; count2 < NUM_AGE_GROUPS; count2++) { U_MATRIX_OFFICE[count][count2] = U_matrix_json[count2][count]; //After JSON parsing, what you get is the transposed version. V_MATRIX_OFFICE[count][count2] = V_matrix_json[count2][count]; //V_MATRIX is the transpose of V in C = SUV'. } } var sigma_json = JSON.parse(loadJSON_001('input_files/Sigma_school.json')); var U_matrix_json = JSON.parse(loadJSON_001('input_files/U_school.json')); var V_matrix_json = JSON.parse(loadJSON_001('input_files/Vtranspose_school.json')); SIGMA_SCHOOL = math.zeros([NUM_AGE_GROUPS]); U_MATRIX_SCHOOL = math.zeros([NUM_AGE_GROUPS, NUM_AGE_GROUPS]); V_MATRIX_SCHOOL = math.zeros([NUM_AGE_GROUPS, NUM_AGE_GROUPS]); for (var count = 0; count < NUM_AGE_GROUPS; count++) { //TODO:Change loop max to NUM_AGE_GROUPS SIGMA_SCHOOL[count] = sigma_json[count][count]; } for (var count = 0; count < NUM_AGE_GROUPS; count++) { for (var count2 = 0; count2 < NUM_AGE_GROUPS; count2++) { U_MATRIX_SCHOOL[count][count2] = U_matrix_json[count2][count]; V_MATRIX_SCHOOL[count][count2] = V_matrix_json[count2][count]; } } } function update_lambda_w(nodes, workplace) { //Compute age_group related mixing var lambda_age_group = math.zeros([NUM_AGE_GROUPS]); if (!USE_AGE_DEPENDENT_MIXING) { ////////////////////////// //Sanity test --- use old lambdas var lambda_old = update_lambda_w_old(nodes, workplace) for (var count = 0; count < NUM_AGE_GROUPS; count++) { lambda_age_group[count] = lambda_old; } //////////////////////////// } else { var SIGMA = SIGMA_OFFICE; var V_MATRIX = V_MATRIX_OFFICE; var U_MATRIX = U_MATRIX_OFFICE; var SIGNIFICANT_EIGEN_VALUES = SIGNIFICANT_EIGEN_VALUES_OFFICE if (workplace['workplace_type'] == WTYPE_SCHOOL) { SIGMA = SIGMA_SCHOOL; V_MATRIX = V_MATRIX_SCHOOL; U_MATRIX = U_MATRIX_SCHOOL; SIGNIFICANT_EIGEN_VALUES = SIGNIFICANT_EIGEN_VALUES_SCHOOL } //add contributions to each age group var age_components = math.zeros([NUM_AGE_GROUPS]); for (var student_count = 0; student_count < workplace['individuals'].length; student_count++) { var student_age_group = nodes[workplace['individuals'][student_count]]['age_group']; age_components[student_age_group] += nodes[workplace['individuals'][student_count]]['lambda_w']; } //weighted sum of age contributions for each eigen component var V_T_x = math.zeros([SIGNIFICANT_EIGEN_VALUES]); for (var eigen_count = 0; eigen_count < SIGNIFICANT_EIGEN_VALUES; eigen_count++) { for (var count = 0; count < NUM_AGE_GROUPS; count++) { V_T_x[eigen_count] += V_MATRIX[eigen_count][count] * age_components[count];//Assumption is V_matrix is V' where C = USV' } } for (var count = 0; count < NUM_AGE_GROUPS; count++) { for (var eigen_count = 0; eigen_count < SIGNIFICANT_EIGEN_VALUES; eigen_count++) { lambda_age_group[count] += workplace['scale'] * SIGMA[eigen_count] * U_MATRIX[count][eigen_count] * V_T_x[eigen_count]; } } } return lambda_age_group; } function update_lambda_public_transport(nodes, public_transport) { var sum_value = 0 for (var i = 0; i < public_transport['individuals'].length; i++) { // var temp = nodes.filter( function(node) { // return node['index']==community['individuals'][i]; // }); sum_value += nodes[public_transport['individuals'][i]]['lambda_pt']; } return public_transport['scale'] * sum_value; // Populate it afterwards... } function update_lambda_c_local(nodes, community) { var sum_value = 0 for (var i = 0; i < community['individuals'].length; i++) { // var temp = nodes.filter( function(node) { // return node['index']==community['individuals'][i]; // }); sum_value += nodes[community['individuals'][i]]['lambda_c']; } return community['scale'] * sum_value; // Populate it afterwards... } function update_lambda_c_global(communities, community_distance_matrix) { for (var c1 = 0; c1 < communities.length; c1++) { var temp = 0; var temp2 = 0; for (var c2 = 0; c2 < communities.length; c2++) { temp += f_kernel(community_distance_matrix[c1][c2]) * communities[c2]['lambda_community']; temp2 += f_kernel(community_distance_matrix[c1][c2]); //console.log(c1,c2,f_kernel(community_distance_matrix[c1][c2])*communities[c2]['lambda_community']) } communities[c1]['lambda_community_global'] = temp / temp2; } } function get_infected_community(nodes, community) { var affected_stat = 0 var infected_stat = 0 var exposed_stat = 0 var hospitalised_stat = 0 var critical_stat = 0 var dead_stat = 0 var recovered_stat = 0 var exposed_stat = 0 for (var i = 0; i < community['individuals'].length; i++) { // var temp = nodes.filter( function(node) { // return node['index']==community['individuals'][i]; // }); if (nodes[community['individuals'][i]]['infection_status'] == EXPOSED) { exposed_stat += 1 } if (nodes[community['individuals'][i]]['infection_status'] == RECOVERED) { recovered_stat += 1 } if (nodes[community['individuals'][i]]['infection_status'] == HOSPITALISED) { hospitalised_stat += 1 } if (nodes[community['individuals'][i]]['infection_status'] == CRITICAL) { critical_stat += 1 } if (nodes[community['individuals'][i]]['infection_status'] == DEAD) { dead_stat += 1 } if (nodes[community['individuals'][i]]['infection_status'] == PRE_SYMPTOMATIC || nodes[community['individuals'][i]]['infection_status'] == SYMPTOMATIC || nodes[community['individuals'][i]]['infection_status'] == HOSPITALISED || nodes[community['individuals'][i]]['infection_status'] == CRITICAL) { infected_stat += 1 } } affected_stat = exposed_stat + infected_stat + recovered_stat + dead_stat; return [infected_stat, affected_stat, hospitalised_stat, critical_stat, dead_stat]; // Populate it afterwards... } function update_lambdas(node, homes, workplaces, communities, public_transports, nodes, cur_time) { /* ///////TODO: See if this can be made as a function var node_home_quarantined = false; if(INTERVENTION == HOME_QUARANTINE && node['compliant']){ var house_members = homes[node['home']]['individuals']; for (var l = 0; l < house_members.length; l++){ var time_since_symptoms = cur_time - nodes[house_members[l]]['time_since_infection'] - nodes[house_members[l]]['incubation_period'] - nodes[house_members[l]]['asymptomatic_period']; node_home_quarantined = node_home_quarantined || ( (nodes[house_members[l]]['infection_status']!=SUSCEPTIBLE) && (nodes[house_members[l]]['infection_status']!=EXPOSED) && (time_since_symptoms > NUM_DAYS_TO_RECOG_SYMPTOMS*SIM_STEPS_PER_DAY) && (time_since_symptoms <= (NUM_DAYS_TO_RECOG_SYMPTOMS+HOME_QUARANTINE_DAYS)*SIM_STEPS_PER_DAY) ); } } */ node['lambda_incoming'] = [0, 0, 0, 0]; if (node['home'] != null && node['home'] != undefined) { var age_group = node['age_group']; node['lambda_incoming'][0] = node['kappa_H_incoming'] * homes[node['home']]['age_dependent_mixing'][age_group]; } if (node['workplace'] != null && node['workplace'] != undefined) { var age_group = node['age_group']; node['lambda_incoming'][1] = node['kappa_W_incoming'] * workplaces[node['workplace']]['age_dependent_mixing'][age_group]; } if (node['community'] != null && node['community'] != undefined) { //for all communities //add the community lambda with a distance related scaling factor node['lambda_incoming'][2] = node['kappa_C_incoming'] * node['zeta_a'] * node['funct_d_ck'] * communities[node['community']]['lambda_community_global']; } if (node['public_transport'] != null && node['public_transport'] != undefined) { //for all public transport //add the community lambda with a distance related scaling factor //console.log("In lambda incoming.") node['lambda_incoming'][3] = node['kappa_PT_incoming'] * node['dist_hw'] * public_transports[node['public_transport']]['lambda_PT']; } node['lambda'] = node['lambda_incoming'][0] + node['lambda_incoming'][1] + node['lambda_incoming'][2] + node['lambda_incoming'][3]; } /* function get_lambda_stats(time,node,lambda_stats_variable){ var temp = [time,node,0,0,0,0]; if(node['home']!=null) {temp[2]=homes[node['home']]['lambda_home'];} if(node['workplace']!=null ) {temp[3] = workplaces[node['workplace']]['lambda_workplace'];} if(node['community']!=null) {temp[4] = node['zeta_a']*node['funct_d_ck']*communities[node['community']]['lambda_community'];} temp[5] = temp[2]+temp[3]+temp[4] lambda_stats_variable.push(temp) } */ function update_lambda_stats(node) { var sum_inv = 1 / math.sum(node['lambda_incoming']); var lambda_vector = []; for (var i = 0; i < node['lambda_incoming'].length; i++) { lambda_vector.push(node['lambda_incoming'][i] * sum_inv); LAMBDA_INFECTION_MEAN[i] = (LAMBDA_INFECTION_MEAN[i] * LAMBDA_INFECTION_STATS.length + lambda_vector[i]) / (LAMBDA_INFECTION_STATS.length + 1); } LAMBDA_INFECTION_STATS.push(lambda_vector) } let csvContent_alltogether = "data:text/csv;charset=utf-8,"; function update_all_kappa(nodes, homes, workplaces, communities, cur_time) { var current_time = cur_time; if (current_time < NUM_DAYS_BEFORE_INTERVENTIONS * SIM_STEPS_PER_DAY) { get_kappa_no_intervention(nodes, homes, workplaces, communities, current_time); } else { //current_time = current_time - NUM_DAYS_BEFORE_INTERVENTIONS*SIM_STEPS_PER_DAY; switch (INTERVENTION) { case CALIBRATION: get_kappa_CALIBRATION(nodes, homes, workplaces, communities, current_time); break; case NO_INTERVENTION: get_kappa_no_intervention(nodes, homes, workplaces, communities, current_time); break; case CASE_ISOLATION: get_kappa_case_isolation(nodes, homes, workplaces, communities, current_time); break; case HOME_QUARANTINE: get_kappa_home_quarantine(nodes, homes, workplaces, communities, current_time); break; case LOCKDOWN: get_kappa_lockdown(nodes, homes, workplaces, communities, current_time); break; case CASE_ISOLATION_AND_HOME_QUARANTINE: get_kappa_CI_HQ(nodes, homes, workplaces, communities, current_time); break; case CASE_ISOLATION_AND_HOME_QUARANTINE_SD_70_PLUS: get_kappa_CI_HQ_70P(nodes, homes, workplaces, communities, current_time); break; case LOCKDOWN_21_CI_HQ_SD_70_PLUS_21_CI: get_kappa_LOCKDOWN_21_CI_HQ_SD_70_PLUS_21_CI(nodes, homes, workplaces, communities, current_time); break; case LOCKDOWN_21: get_kappa_LOCKDOWN_21(nodes, homes, workplaces, communities, current_time); break; case LD_21_CI_HQ_SD70_SC_21_SC_42: get_kappa_LD_21_CI_HQ_SD70_SC_21_SC_42(nodes, homes, workplaces, communities, current_time); break; case LD_21_CI_HQ_SD70_SC_21: get_kappa_LD_21_CI_HQ_SD70_SC_21(nodes, homes, workplaces, communities, current_time); break; case LD_21_CI_HQ_SD70_SC_OE_30: get_kappa_LD_21_CI_HQ_SD70_SC_OE_30(nodes, homes, workplaces, communities, current_time); break; default: break; } } } function run_simday(time_step, homes, workplaces, communities, public_transports, nodes, community_distance_matrix, seed_array, days_num_affected, days_num_critical, days_num_exposed, days_num_fatalities, days_num_hospitalised, days_num_infected, days_num_recovered, lambda_evolution) { console.log("time_step = " + time_step + "time_step / SIM_STEPS_PER_DAY" + time_step / SIM_STEPS_PER_DAY); //seeding strategies if (SEEDING_MODE == SEED_INFECTION_RATES && time_step < seed_array.length) { infection_seeding(nodes, seed_array[time_step], time_step); } else if (SEEDING_MODE == SEED_EXP_RATE) { infection_seeding_exp_rate(nodes, time_step); } for (var j = 0; j < NUM_PEOPLE; j++) { update_infection(nodes[j], time_step); //update_kappa(nodes[j], time_step); update_psi(nodes[j], time_step); } update_all_kappa(nodes, homes, workplaces, communities, time_step); for (var h = 0; h < NUM_HOMES; h++) { homes[h]['age_dependent_mixing'] = update_lambda_h(nodes, homes[h]); } for (var w = 0; w < NUM_SCHOOLS + NUM_WORKPLACES; w++) { workplaces[w]['age_dependent_mixing'] = update_lambda_w(nodes, workplaces[w]); } for (var c = 0; c < NUM_COMMUNITIES; c++) { communities[c]['lambda_community'] = update_lambda_c_local(nodes, communities[c]); ///console.log("lambda_community:",c,communities[c]['lambda_community']) var temp_stats = get_infected_community(nodes, communities[c]); //infection_status_community.push([]); let row = [time_step / SIM_STEPS_PER_DAY, c, temp_stats[0], temp_stats[1], temp_stats[2], temp_stats[3], temp_stats[4]].join(","); csvContent += row + "\r\n"; } for (var pt = 0; pt < NUM_PUBLIC_TRANSPORT; pt++) { public_transports[pt]['lambda_PT'] = update_lambda_public_transport(nodes, public_transports[pt]); } update_lambda_c_global(communities, community_distance_matrix); for (var j = 0; j < NUM_PEOPLE; j++) { var lambda_current_stats = []; update_lambdas(nodes[j], homes, workplaces, communities, public_transports, nodes, time_step); //get_lambda_stats(i,j,lambda_current_stats); } //lambda_current_stats_avg = math.mean(math.mean(lambda_current_stats, 0)); //lambda_evolution.push([i/SIM_STEPS_PER_DAY,lambda_current_stats_avg[2],lambda_current_stats_avg[3],lambda_current_stats_avg[4],lambda_current_stats_avg[5]]); var n_infected_wardwise = nodes.reduce(function (partial_sum, node) { return partial_sum + ((node['infection_status'] == PRE_SYMPTOMATIC || node['infection_status'] == SYMPTOMATIC || node['infection_status'] == HOSPITALISED || node['infection_status'] == CRITICAL) ? 1 : 0); }, 0); //I don't know what to do with this. It is not an initialized variable at start. Thus i'm commenting out // days_num_infected.push([time_step / SIM_STEPS_PER_DAY, n_infected]); csvContent_ninfected = [time_step / SIM_STEPS_PER_DAY, n_infected].join(',') + "\r\n" var n_infected = nodes.reduce(function (partial_sum, node) { return partial_sum + ((node['infection_status'] == PRE_SYMPTOMATIC || node['infection_status'] == SYMPTOMATIC || node['infection_status'] == HOSPITALISED || node['infection_status'] == CRITICAL) ? 1 : 0); }, 0); //PLEASE CHECK BELOW LINE AS n_infected_wardwise returns same thing days_num_infected[time_step] = [time_step / SIM_STEPS_PER_DAY, n_infected]; var n_exposed = nodes.reduce(function (partial_sum, node) { return partial_sum + ((node['infection_status'] == EXPOSED) ? 1 : 0); }, 0); days_num_exposed[time_step] = [time_step / SIM_STEPS_PER_DAY, n_exposed]; var n_hospitalised = nodes.reduce(function (partial_sum, node) { return partial_sum + ((node['infection_status'] == HOSPITALISED) ? 1 : 0); }, 0); days_num_hospitalised[time_step] = [time_step / SIM_STEPS_PER_DAY, n_hospitalised]; var n_critical = nodes.reduce(function (partial_sum, node) { return partial_sum + ((node['infection_status'] == CRITICAL) ? 1 : 0); }, 0); days_num_critical[time_step] = [time_step / SIM_STEPS_PER_DAY, n_critical]; var n_fatalities = nodes.reduce(function (partial_sum, node) { return partial_sum + ((node['infection_status'] == DEAD) ? 1 : 0); }, 0); days_num_fatalities[time_step] = [time_step / SIM_STEPS_PER_DAY, (n_fatalities)]; var n_recovered = nodes.reduce(function (partial_sum, node) { return partial_sum + ((node['infection_status'] == RECOVERED) ? 1 : 0); }, 0); days_num_recovered[time_step] = [time_step / SIM_STEPS_PER_DAY, n_recovered]; //var n_affected = nodes.reduce(function(partial_sum, node) {return partial_sum + ((node['infection_status']) ? 1 : 0);}, 0); days_num_affected[time_step] = [time_step / SIM_STEPS_PER_DAY, (NUM_AFFECTED_COUNT)]; let row = [time_step / SIM_STEPS_PER_DAY, NUM_AFFECTED_COUNT, n_recovered, n_infected, n_exposed, n_hospitalised, n_critical, n_fatalities, LAMBDA_INFECTION_MEAN[0], LAMBDA_INFECTION_MEAN[1], LAMBDA_INFECTION_MEAN[2]].join(","); csvContent_alltogether += row + "\r\n"; if (LAMBDA_INFECTION_STATS.length > 0) { lambda_evolution.push([time_step / SIM_STEPS_PER_DAY, [LAMBDA_INFECTION_MEAN[0], LAMBDA_INFECTION_MEAN[1], LAMBDA_INFECTION_MEAN[2], LAMBDA_INFECTION_MEAN[3]]]) } ///update_sim_progress_status(time_step,NUM_TIMESTEPS); // } if (LAMBDA_INFECTION_STATS.length > 0) { console.log(math.mean(LAMBDA_INFECTION_STATS, 0)); } if (time_step % SIM_STEPS_PER_DAY == 0 && time_step > 0) { document.getElementById("status").innerHTML = "Simulation Complete for " + time_step / SIM_STEPS_PER_DAY + " Days"; return time_step; // return [time_step, days_num_infected, days_num_exposed, days_num_hospitalised, days_num_critical, days_num_fatalities, days_num_recovered, days_num_affected, lambda_evolution]; } else { return run_simday(time_step + 1, homes, workplaces, communities, public_transports, nodes, community_distance_matrix, seed_array, days_num_affected, days_num_critical, days_num_exposed, days_num_fatalities, days_num_hospitalised, days_num_infected, days_num_recovered, lambda_evolution); } } function newFilledArray(len, val) { var rv = new Array(len); while (--len >= 0) { rv[len] = val; } return rv; } function initialize_simulation() { document.getElementById("status").innerHTML = "Initializing Simulation..."; const homes = init_homes(); const workplaces = init_workplaces(); const communities = init_community(); const public_transports = init_public_transport(); const nodes = init_nodes(); const community_distance_matrix = compute_community_distances(communities); let seed_array = []; if (SEEDING_MODE == SEED_INFECTION_RATES) { seed_array = load_infection_seed_json(SEED_SCALING_FACTOR); } //console.log(community_distance_matrix) console.log(NUM_PEOPLE, NUM_HOMES, NUM_WORKPLACES, NUM_SCHOOLS, NUM_COMMUNITIES) assign_individual_home_community(nodes, homes, workplaces, communities); assign_individual_public_transports(nodes, public_transports, workplaces); //compute_individual_community_distance(nodes,communities); //TODO: remove once distance to community center is provided in json. compute_scale_homes(homes); compute_scale_workplaces(workplaces); compute_scale_communities(nodes, communities); compute_scale_public_transport(nodes, public_transports); //get_init_stats(nodes,homes,workplaces,communities); const array_len = NUM_TIMESTEPS; const array_default = 0; const days_num_affected = newFilledArray(array_len, array_default); const days_num_critical = newFilledArray(array_len, array_default); const days_num_exposed = newFilledArray(array_len, array_default); const days_num_fatalities = newFilledArray(array_len, array_default); const days_num_hospitalised = newFilledArray(array_len, array_default); const days_num_infected = newFilledArray(array_len, array_default); const days_num_recovered = newFilledArray(array_len, array_default); let lambda_evolution = [] LAMBDA_INFECTION_STATS = [] //global variable to track lambda evolution when a person gets infected LAMBDA_INFECTION_MEAN = [0, 0, 0, 0]; NUM_AFFECTED_COUNT = 0; document.getElementById("status").innerHTML = "Initialization Done..."; return [homes, workplaces, communities, public_transports, nodes, community_distance_matrix, seed_array, days_num_affected, days_num_critical, days_num_exposed, days_num_fatalities, days_num_hospitalised, days_num_infected, days_num_recovered, lambda_evolution]; } SIMULATION_STOP = false; function stop_sim() { SIMULATION_STOP = true; } function run_simulation() { document.getElementById("run_button").style.display = "none"; document.getElementById("sim_stop").style.display = "inline"; const [homes, workplaces, communities, public_transports, nodes, community_distance_matrix, seed_array, days_num_affected, days_num_critical, days_num_exposed, days_num_fatalities, days_num_hospitalised, days_num_infected, days_num_recovered, lambda_evolution] = initialize_simulation(); document.getElementById("status").innerHTML = "Starting to run Simulation..."; let time_step = 0; time_step = run_simday(time_step, homes, workplaces, communities, public_transports, nodes, community_distance_matrix, seed_array, days_num_affected, days_num_critical, days_num_exposed, days_num_fatalities, days_num_hospitalised, days_num_infected, days_num_recovered, lambda_evolution); let plot_tuple = [days_num_infected, days_num_exposed, days_num_hospitalised, days_num_critical, days_num_fatalities, days_num_recovered, days_num_affected, lambda_evolution]; call_plotly(plot_tuple); const interval = setInterval(function () { // console.log("inside the interval stuff. time_step = ", time_step); document.getElementById("status").innerHTML = "Calculating Simulation for Day: " + time_step / SIM_STEPS_PER_DAY; const last_time_step = time_step; time_step = run_simday(time_step + 1, homes, workplaces, communities, public_transports, nodes, community_distance_matrix, seed_array, days_num_affected, days_num_critical, days_num_exposed, days_num_fatalities, days_num_hospitalised, days_num_infected, days_num_recovered, lambda_evolution); extend_plotlyDay(last_time_step,time_step,plot_tuple); // call_plotly(plot_tuple); // Plotly.extendTraces('graph', { // x: [[cnt], [cnt]], // y: [[rand()], [rand()]] // }, [0, 1]) if (time_step >= NUM_TIMESTEPS || SIMULATION_STOP) { // console.log("time_step = ", time_step); clearInterval(interval); //Get Run working again document.getElementById("run_button").style.display = "inline"; document.getElementById("sim_stop").style.display = "none"; SIMULATION_STOP = false; //Ensure last data point plotted extend_plotlyLast(time_step, plot_tuple); //Do some TASKS for output var encodedUri = encodeURI(csvContent); var link = document.createElement("a"); link.setAttribute("href", encodedUri); link.setAttribute("download", "my_data.csv"); document.body.appendChild(link); // Required for FF if (!WEBPAGE_VERSION) { link.click(); //TODO: Instead of click link, add link for download on page. } encodedUri = encodeURI(csvContent_alltogether); link = document.createElement("a"); link.setAttribute("href", encodedUri); link.setAttribute("download", "my_data_all_together.csv"); document.body.appendChild(link); // Required for FF document.getElementById("status").innerHTML = "Numbers plotted are per " + String(NUM_PEOPLE) + "."; if (!WEBPAGE_VERSION) { link.click(); //TODO: Instead of click link, add link for download on page. } } }, 50); if (LAMBDA_INFECTION_STATS.length > 0) { console.log(math.mean(LAMBDA_INFECTION_STATS, 0)); } } function plot_lambda_evolution(data, plot_position, title_text, legends) { if (data[0] == undefined || data[0][0] == undefined) { //If there is no data to plot, return. return; } var trace = []; for (var count = 0; count < data.length; count++) { for (var lambda_length_count = 0; lambda_length_count < data[0][0][1].length; lambda_length_count++) { //iterate over lambda_h, lambda_w,lambda_c var trace1 = { x: [], y: [], mode: 'bar', name: legends[lambda_length_count] }; for (var count2 = 0; count2 < data[count].length; count2++) { trace1.x.push(data[count][count2][0]); trace1.y.push(data[count][count2][1][lambda_length_count]); } trace.push(trace1) } } var data_plot = trace; var layout = { barmode: 'stack', title: { text: title_text, font: { family: 'Courier New, monospace', size: 24 }, xref: 'paper', x: 0.05, }, xaxis: { title: { text: 'Days', font: { family: 'Courier New, monospace', size: 18, color: '#7f7f7f' } }, }, yaxis: { title: { text: title_text, font: { family: 'Courier New, monospace', size: 18, color: '#7f7f7f' } }, range: [0, 1] }, showlegend: true, legend: { x: 1, xanchor: 'right', y: 1 } }; Plotly.newPlot(plot_position, data_plot, layout); } function call_plotly(data_tuple) { var plot_values = data_tuple; plot_plotly_SingleLine([plot_values[0]], 'num_infected_plot_2', 'Number Infectious (daily)', 'Evolution of Infected Population'); //plot_plotly_SingleLine([plot_values[1]],'num_exposed_plot_2','Number Exposed (daily)','Evolution of Exposed Population'); plot_plotly_SingleLine([plot_values[2]], 'num_hospitalised_plot_2', 'Number Hospitalised (daily)', 'Evolution of Hospitalised Population'); plot_plotly_SingleLine([plot_values[3]], 'num_critical_plot_2', 'Number Critical (daily)', 'Evolution of Critical Population'); plot_plotly_SingleLine([plot_values[4]], 'num_fatalities_plot_2', 'Number Fatalities (cum.)', 'Evolution of Fatalities Population'); //plot_plotly_SingleLine([plot_values[5]],'num_recovered_plot_2','Number Recovered (cum.)','Evolution of Recovered Population'); plot_plotly_SingleLine([plot_values[6]], 'num_affected_plot_2', 'Number Affected (cum.)', 'Evolution of Affected Population'); plot_lambda_evolution([plot_values[7]], 'lambda_evolution', 'Source of infection', ['Home', 'School/Workplace', 'Community', 'Public Transport']); } function run_and_plot(intervention) { var returned_values; returned_values = run_simulation(); call_plotly(returned_values); } function plotly_extend(div_id, x_value, y_value) { Plotly.extendTraces(div_id, { x: [[x_value]], y: [[y_value]] }, [0]); } function plotly_PlotExtend(div_id, x_value, y_value) { Plotly.extendTraces(div_id, { x: [[x_value]], y: [[y_value]] }, [0]); } function plotly_PlotExtendMulti(div_id, x_values, y_values) { Plotly.extendTraces(div_id, { x: [x_values], y: [y_values] }, [0]); } function extend_plotlyDay(last_timestep, current_timestep, data_tuple) { // console.log("data_tuple[0] = ",data_tuple[0]); const data_len = data_tuple[0].length; const num_updates = current_timestep-last_timestep; // const infected = data_tuple[0].slice(Math.max(data_len - num_updates, 0)); const infected = data_tuple[0].slice(last_timestep,current_timestep); plotly_PlotExtendMulti("num_infected_plot_2",infected.flatMap(x=>x[0]),infected.flatMap(x=>x[1])); // const hospitalized = data_tuple[2].slice(Math.max(data_len - num_updates, 0)); const hospitalized = data_tuple[2].slice(last_timestep,current_timestep); plotly_PlotExtendMulti("num_hospitalised_plot_2",hospitalized.flatMap(x=>x[0]),hospitalized.flatMap(x=>x[1])); // const critical = data_tuple[3].slice(Math.max(data_len - num_updates, 0)); const critical = data_tuple[3].slice(last_timestep,current_timestep); plotly_PlotExtendMulti("num_critical_plot_2",critical.flatMap(x=>x[0]),critical.flatMap(x=>x[1])); // const fatalities = data_tuple[4].slice(Math.max(data_len - num_updates, 0)); const fatalities = data_tuple[4].slice(last_timestep,current_timestep); plotly_PlotExtendMulti("num_fatalities_plot_2",fatalities.flatMap(x=>x[0]),fatalities.flatMap(x=>x[1])); // const affected = data_tuple[6].slice(Math.max(data_len - num_updates, 0)); const affected = data_tuple[6].slice(last_timestep,current_timestep); plotly_PlotExtendMulti("num_affected_plot_2",affected.flatMap(x=>x[0]),affected.flatMap(x=>x[1])); // EXTENDING ONE BY ONE: ABOVE IS FASTER // for(let i = 0;i < num_updates;i++){ plotly_PlotExtend("num_infected_plot_2",infected,data_tuple[0][data_len-num_updates+i][1]); } // for(let i = 0;i < num_updates;i++){ plotly_PlotExtend("num_hospitalised_plot_2",(last_timestep+i)/SIM_STEPS_PER_DAY,data_tuple[2][data_len-num_updates+i][1]); } // for(let i = 0;i < num_updates;i++){ plotly_PlotExtend("num_critical_plot_2",(last_timestep+i)/SIM_STEPS_PER_DAY,data_tuple[3][data_len-num_updates+i][1]); } // for(let i = 0;i < num_updates;i++){ plotly_PlotExtend("num_fatalities_plot_2",(last_timestep+i)/SIM_STEPS_PER_DAY,data_tuple[4][data_len-num_updates+i][1]); } // for(let i = 0;i < num_updates;i++){ plotly_PlotExtend("num_affected_plot_2",(last_timestep+i)/SIM_STEPS_PER_DAY,data_tuple[6][data_len-num_updates+i][1]); } plot_lambda_evolution([data_tuple[7]], 'lambda_evolution', 'Source of infection', ['Home', 'School/Workplace', 'Community', 'Public Transport']); } function extend_plotlyLast(time_step, data_tuple) { plotly_PlotExtend("num_infected_plot_2",data_tuple[0][time_step][0],data_tuple[0][time_step][1]); plotly_PlotExtend("num_hospitalised_plot_2",data_tuple[2][time_step][0],data_tuple[0][time_step][1]); plotly_PlotExtend("num_critical_plot_2",data_tuple[3][time_step][0],data_tuple[0][time_step][1]); plotly_PlotExtend("num_fatalities_plot_2",data_tuple[4][time_step][0],data_tuple[0][time_step][1]); plotly_PlotExtend("num_affected_plot_2",data_tuple[5][time_step][0],data_tuple[0][time_step][1]); plot_lambda_evolution([data_tuple[7]], 'lambda_evolution', 'Source of infection', ['Home', 'School/Workplace', 'Community', 'Public Transport']); } function plot_plotly_SingleLine(data, plot_position, title_text, legends) { var trace = []; for(var count = 0; count < data.length; count++) { var trace1 = { x: [], y: [], mode: 'lines', name: legends[count], line: { //color: 'rgb(219, 64, 82)', width: 3 } }; for (var count2 = 0; count2 < data[count].length; count2++) { trace1.x.push(data[count][count2][0]); trace1.y.push(data[count][count2][1]); } trace.push(trace1) } var data_plot = trace; var layout = { xaxis: { title: { text: 'Days', font: { family: 'Courier New, monospace', size: 18, color: '#7f7f7f' } }, }, yaxis: { title: { text: title_text, font: { family: 'Courier New, monospace', size: 18, color: '#7f7f7f' } } } }; Plotly.newPlot(plot_position, data_plot, layout); } function plot_plotly(data, plot_position, title_text, legends) { const trace = []; for (let columnNo = 0; columnNo < data.length; columnNo++) { let trace1 = { x: [], y: [], mode: 'lines', name: legends[columnNo], line: { // color: 'rgb(219, 64, 82)', width: 3 } }; for (let rowNo = 0; rowNo < data[columnNo].length; rowNo++) { trace1.x.push(data[columnNo][rowNo][0]); trace1.y.push(data[columnNo][rowNo][1]); } trace.push(trace1) } const data_plot = trace; const layout = { xaxis: { title: { text: 'Days', font: { family: 'Courier New, monospace', size: 18, color: '#7f7f7f' } }, }, yaxis: { title: { text: title_text, font: { family: 'Courier New, monospace', size: 18, color: '#7f7f7f' } } } }; Plotly.newPlot(plot_position, data_plot, layout); } //Main function function runSimulations() { //clear_plots(); //get the inputs from the HTML page NUM_DAYS = document.getElementById("numDays").value; // == 0 ? NUM_DAYS : document.getElementById("numDays").value; NUM_TIMESTEPS = NUM_DAYS * SIM_STEPS_PER_DAY; INIT_FRAC_INFECTED = document.getElementById("initFrac").value; // COMPLIANCE_PROBABILITY = document.getElementById("compliance").value; INCUBATION_PERIOD = parseFloat(document.getElementById("Incubation").value) / 2; INCUBATION_PERIOD_SCALE = INCUBATION_PERIOD * SIM_STEPS_PER_DAY; // 2.29 days MEAN_ASYMPTOMATIC_PERIOD = document.getElementById("asymptomaticMean").value; MEAN_SYMPTOMATIC_PERIOD = document.getElementById("symptomaticMean").value; SYMPTOMATIC_FRACTION = document.getElementById("symtomaticFraction").value; MEAN_HOSPITAL_REGULAR_PERIOD = document.getElementById("meanHospitalPeriod").value; MEAN_HOSPITAL_CRITICAL_PERIOD = document.getElementById("meanICUPeriod").value; COMPLIANCE_PROBABILITY = document.getElementById("compliance").value; ASYMPTOMATIC_PERIOD = MEAN_ASYMPTOMATIC_PERIOD * SIM_STEPS_PER_DAY; SYMPTOMATIC_PERIOD = MEAN_SYMPTOMATIC_PERIOD * SIM_STEPS_PER_DAY; HOSPITAL_REGULAR_PERIOD = MEAN_HOSPITAL_REGULAR_PERIOD * SIM_STEPS_PER_DAY; HOSPITAL_CRITICAL_PERIOD = MEAN_HOSPITAL_CRITICAL_PERIOD * SIM_STEPS_PER_DAY; BETA_H = document.getElementById("betaHouse").value; BETA_W = document.getElementById("betaWork").value; BETA_C = document.getElementById("betaCommunity").value; BETA_S = document.getElementById("betaSchools").value; BETA_PT = document.getElementById("betaPT").value; INTERVENTION = parseInt(document.getElementById("interventions").value); console.log(NUM_DAYS, INIT_FRAC_INFECTED, INTERVENTION); console.log("INTERVENTION = ", INTERVENTION); //where simulation starts run_simulation(); } function clear_plots() { //clear previous plots document.getElementById("status").innerHTML = "Simulation in Progress...."; document.getElementById("num_affected_plot_2").innerHTML = ""; document.getElementById("num_infected_plot_2").innerHTML = ""; document.getElementById("num_exposed_plot_2").innerHTML = ""; document.getElementById("num_hospitalised_plot_2").innerHTML = ""; document.getElementById("num_critical_plot_2").innerHTML = ""; document.getElementById("num_fatalities_plot_2").innerHTML = ""; document.getElementById("num_recovered_plot_2").innerHTML = ""; document.getElementById("lambda_evolution").innerHTML = ""; runSimulations(); } function set_default_values_html() { document.getElementById("numDays").value = NUM_DAYS; document.getElementById("initFrac").value = INIT_FRAC_INFECTED; document.getElementById("Incubation").value = 2 * INCUBATION_PERIOD; document.getElementById("asymptomaticMean").value = MEAN_ASYMPTOMATIC_PERIOD; document.getElementById("symptomaticMean").value = MEAN_SYMPTOMATIC_PERIOD; document.getElementById("symtomaticFraction").value = SYMPTOMATIC_FRACTION; document.getElementById("meanHospitalPeriod").value = MEAN_HOSPITAL_REGULAR_PERIOD; document.getElementById("meanICUPeriod").value = MEAN_HOSPITAL_CRITICAL_PERIOD; document.getElementById("compliance").value = COMPLIANCE_PROBABILITY; document.getElementById("betaHouse").value = BETA_H; document.getElementById("betaWork").value = BETA_W; document.getElementById("betaCommunity").value = BETA_C; document.getElementById("betaSchools").value = BETA_S; document.getElementById("betaPT").value = BETA_PT; document.getElementById("interventions").value = "0"; } function clear_variables() { } set_default_values_html();
'use strict'; const { COLOR } = require('@data/config'); const { Command, SimplicityEmbed } = require('@structures'); const moment = require('moment'); class ServerInfo extends Command { constructor(client) { super(client, 'serverinfo', { aliases: ['si', 'server', 'svinfo', 'sv', 'guild', 'serverinformation', 'svinformation'], category: 'guild', }); } async run({ author, channel, emoji, guild, send, t, language }) { if (guild.memberCount !== guild.members.cache.size) await guild.members.fetch(); moment.locale(language); const totalMembers = guild.memberCount; const members = guild.members.cache; const onlineMembers = members.filter((m) => m.presence.status !== 'offline').size; const offlineMembers = members.filter((m) => m.presence.status === 'offline').size; const channels = guild.channels.cache; let textChannels = 0, totalChannels = 0, voiceChannels = 0; for (let { type } of channels.values()) { totalChannels++; if (type === 'voice') voiceChannels++; else if (type === 'category') totalChannels--; else textChannels++; } const totalRoles = guild.roles && guild.roles.cache.filter((r) => r.id !== guild.id).size; const roles = guild.roles && guild.roles.cache.sort((a, b) => b.position - a.position).map((r) => r).slice(0, -1); const rolesClean = roles && roles.map((r) => r.name || `${r}`); const emojis = guild.emojis && guild.emojis.cache.size; const owner = (guild.owner && guild.owner.user.tag) || t('commands:serverinfo.unknown'); const date = moment(guild.createdAt); const boostTier = guild.premiumTier; const boosters = guild.premiumSubscriptionCount; const embed = new SimplicityEmbed({ author, guild, t }) .addField('» $$commands:serverinfo.name', guild.name, true) .addField('» $$commands:serverinfo.id', guild.id, true) .addField('» $$commands:serverinfo.owner', owner, true) .addField('» $$commands:serverinfo.emotes', emojis, true); const guildIcon = embed.resolveImage(guild); embed.setThumbnail(guildIcon); if (roles.length <= 5) embed.addField('» $$commands:serverinfo.roles', rolesClean.join(', '), true, { totalRoles }); else embed.addField('» $$commands:serverinfo.totalRoles', totalRoles, true); if (boostTier && boosters) { embed.addField('» $$commands:serverinfo.boostTier', '$$commands:serverinfo.tier', true, {}, { boostTier }); } embed .addFields( { inline: true, name: '» $$commands:serverinfo.members', options: { totalMembers }, value: '$$commands:serverinfo.onlineOffline', valueOptions: { offlineMembers, onlineMembers }, }, { inline: true, name: '» $$commands:serverinfo.channels', options: { totalChannels }, value: '$$commands:serverinfo.textVoice', valueOptions: { textChannels, voiceChannels }, }, { name: '» $$commands:serverinfo.created', value: `${date.format('LLL')} (${date.fromNow()})`, }, { inline: true, name: '» $$commands:serverinfo.verificationLevel', options: { level: guild.verificationLevel }, value: `$$commands:serverinfo.verificationDetails.${guild.verificationLevel}`, }, ); const message = await send(embed); const permissions = channel.permissionsFor(guild.me); const roleRestriction = rolesClean && rolesClean.length > 5; if (permissions.has('ADD_REACTIONS') && roleRestriction) { const role = { embed: createEmbedRoles(roles, guildIcon, { author, t }), emoji: emoji('ROLES', { id: true }), }; await message.react(role.emoji); const serverinfoEmoji = emoji('BACK', { id: true }); await message.react(serverinfoEmoji); const filter = (r, u) => r.me && author.id === u.id; const collector = await message.createReactionCollector(filter, { errors: ['time'], time: 30000 }); collector.on('collect', async ({ emoji: emote, users, message: collectorMessage }) => { const name = emote.id || emote.name; const checkEmbed = (e) => e.author.name === collectorMessage.embeds[0].author.name; if (permissions.has('MANAGE_MESSAGES')) await users.remove(author.id); if (name === serverinfoEmoji && !checkEmbed(embed)) await collectorMessage.edit(embed); if (role && name === role.emoji && !checkEmbed(role.embed)) await collectorMessage.edit(role.embed); }); collector.on('end', async () => { if (message && permissions.has('MANAGE_MESSAGES')) await message.reactions.removeAll().catch(() => null); }); } } } function createEmbedRoles(roles, guildIcon, embedOptions = {}) { const clean = (a) => a.slice(0, 25).join('\n') + (a.length > 25 ? '\n...' : ''); return new SimplicityEmbed(embedOptions) .setThumbnail(guildIcon) .setAuthor('$$commands:serverinfo.roles', null, '', { totalRoles: roles.length }) .setDescription(clean(roles)) .setColor(COLOR); } module.exports = ServerInfo;
import xs from 'xstream'; import {run} from '@cycle/run'; import {div, button, h1, h4, a, makeDOMDriver, DOMSource} from '@cycle/dom'; import {makeHTTPDriver, Response, HTTPSource} from '@cycle/http'; function main(sources) { const requests$ = intent(sources) const {user$, todo$} = model(sources) const vdom$ = view({user$, todo$}) return { DOM: vdom$, HTTP: requests$, }; } run(main, { DOM: makeDOMDriver('#app'), HTTP: makeHTTPDriver(), }); function intent(sources) { const getRandomUser$ = xs.of( { url: 'https://jsonplaceholder.typicode.com/users/1', category: 'users', method: 'GET', } ) const getTodo$ = xs.of( { url: 'https://jsonplaceholder.typicode.com/todos/1', category: 'todos', method: 'GET', } ) return xs.merge(getRandomUser$, getTodo$) } function model(sources) { const user$ = sources.HTTP.select('users') .flatten() .map(res => res.body ) .startWith(null) const todo$ = sources.HTTP.select('todos') .flatten() .map(res => res.body) .startWith(null) return {user$, todo$} } function view(state) { const {user$, todo$} = state const userVdom$ = user$.map( user => div('.users', [ user === null ? null : div('.user-details', [ h1('.user-name', user.name), a('.user-website', {attrs: {href: user.website}}, user.website), ]), ]) ) const todoVdom$ = todo$.map( todo => div('.todos', [ todo === null ? null : div('.todo-details', [ h1('.todo-title', todo.title), ]), ]) ) const vdom$ = xs.combine( userVdom$, todoVdom$, ) .map( ([user, todo]) => div([ user, todo, ]) ) return vdom$ }
import reducer, { initialState } from '../reducer'; import * as types from '../types'; describe('Series relations reducer', () => { it('should have initial state', () => { expect(reducer(undefined, {})).toEqual(initialState); }); it('should change loading state on loading action', () => { const action = { type: types.IS_LOADING, }; expect(reducer(initialState, action)).toEqual({ ...initialState, isLoading: true, }); }); it('should change data state on success action', () => { const relatedRecords = { serial: [ { pid: '1', pid_type: 'serid', volume: '1', }, ], }; const action = { type: types.SUCCESS, payload: relatedRecords, }; expect(reducer(initialState, action)).toEqual({ ...initialState, isLoading: false, data: relatedRecords, hasError: false, }); }); it('should change error state on error action', () => { const action = { type: types.HAS_ERROR, payload: 'Error', }; expect(reducer(initialState, action)).toEqual({ ...initialState, isLoading: false, error: 'Error', hasError: true, }); }); });
/* global notFramework */ var CommonNetwork = { addHost: function (uri) { return this.get('host') + uri; }, addProtocol: function (uri) { return this.get('protocol') + uri; }, preloadImages: function (dataArray, fields) { for (var i in dataArray) { for (var f in fields) { if (dataArray[i].hasOwnProperty(fields[f])) { var image = new Image(); image.setAttribute('crossOrigin', 'anonymous'); image.src = dataArray[i][fields[f]].indexOf('//') === 0 ? this.addProtocol(dataArray[i][fields[f]]) : dataArray[i][fields[f]]; } } } }, putFile(upload /* object(file, onProgress, url)*/ ) { return new Promise((resolve, reject) => { var xhr = new XMLHttpRequest(); if (xhr.upload) { // progress bar if (upload.onProgress) { xhr.upload.addEventListener('progress', upload.onProgress, false); } // file received/failed xhr.responseType = 'json'; xhr.onreadystatechange = function ( /*e*/ ) { if (xhr.readyState == 4) { if (xhr.status == 200) { resolve(xhr.response); } else { reject(xhr.response); } } }; // start upload xhr.withCredentials = true; xhr.open('PUT', upload.url, true); xhr.setRequestHeader('SessionID', this.getSessionID()); xhr.setRequestHeader('Content-Type', upload.file.type); xhr.setRequestHeader('X-FILENAME', encodeURIComponent(upload.file.name)); try { xhr.send(upload.file); } catch (e) { reject(e); } } else { reject(); } }); }, requestJSON: function (method, url, data) { return new Promise((resolve, reject) => { let xhr = new XMLHttpRequest(); xhr.open(method, url, true); xhr.setRequestHeader('SessionID', this.getSessionID()); xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8'); xhr.responseType = 'json'; xhr.withCredentials = true; notFramework.notCommon.registerRequest(xhr); xhr.onload = () => { let status = xhr.status; if (status == 200) { notFramework.notCommon.onSuccessRequest(xhr); resolve(xhr.response); } else { notFramework.notCommon.onFailedRequest(xhr); reject(xhr.response); } }; let t = () => { notFramework.notCommon.onFailedRequest(xhr); reject(xhr.status); }; xhr.onerror = t; xhr.ontimeout = t; try { xhr.send(data); } catch (e) { reject(e); } }); }, registerRequest: (xhr) => { let con = notFramework.notCommon.getAPI ? notFramework.notCommon.getAPI() : false; if (con && xhr) { con.markStart(xhr); } }, onSuccessRequest: (xhr) => { let con = notFramework.notCommon.getAPI ? notFramework.notCommon.getAPI() : false; if (con && xhr) { //con.markEnd(xhr); } }, onFailedRequest: (xhr) => { let con = notFramework.notCommon.getAPI ? notFramework.notCommon.getAPI() : false; if (con && xhr) { con.markFailed(xhr); } }, getJSON: function (url, data) { return new Promise((resolve, reject) => { var xhr = new XMLHttpRequest(); xhr.open('get', url, true); xhr.setRequestHeader('SessionID', this.getSessionID()); xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8'); xhr.responseType = 'json'; xhr.withCredentials = true; xhr.onload = function () { var status = xhr.status; if (status == 200) { resolve(xhr.response); } else { reject(xhr.response); } }; let t = () => reject(xhr.status); xhr.onerror = t; xhr.ontimeout = t; try { xhr.send(data); } catch (e) { reject(e); } }); }, postJSON: function (url, data) { return new Promise((resolve, reject) => { var xhr = new XMLHttpRequest(); // new HttpRequest instance xhr.open('POST', url); xhr.setRequestHeader('SessionID', this.getSessionID()); xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8'); xhr.responseType = 'json'; xhr.withCredentials = true; xhr.onload = function () { var status = xhr.status; if (status == 200) { resolve(xhr.response); } else { reject(xhr.response); } }; let t = () => reject(xhr.status); xhr.onerror = t; xhr.ontimeout = t; try { xhr.send(data); } catch (e) { reject(e); } }); }, putJSON: function (url, data) { return new Promise((resolve, reject) => { var xhr = new XMLHttpRequest(); // new HttpRequest instance xhr.open('PUT', url); xhr.setRequestHeader('SessionID', this.getSessionID()); xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8'); xhr.responseType = 'json'; xhr.withCredentials = true; xhr.onload = function () { var status = xhr.status; if (status == 200) { resolve(xhr.response); } else { reject(xhr.response); } }; let t = () => reject(xhr.status); xhr.onerror = t; xhr.ontimeout = t; try { xhr.send(data); } catch (e) { reject(e); } }); }, deleteJSON: function (url, data) { return new Promise((resolve, reject) => { var xhr = new XMLHttpRequest(); // new HttpRequest instance xhr.open('DELETE', url); xhr.setRequestHeader('SessionID', this.getSessionID()); xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8'); xhr.responseType = 'json'; xhr.withCredentials = true; xhr.onload = function () { var status = xhr.status; if (status == 200) { resolve(xhr.response); } else { reject(xhr.response); } }; let t = () => reject(xhr.status); xhr.onerror = t; xhr.ontimeout = t; xhr.send(data); }); }, getHTML: function (url, data) { return new Promise((resolve, reject) => { var xhr = new XMLHttpRequest(); xhr.open('get', url, true); xhr.setRequestHeader('SessionID', this.getSessionID()); xhr.responseType = 'text'; xhr.withCredentials = true; xhr.onload = () => { var status = xhr.status; if (parseInt(status) === 200) { resolve(xhr.responseText); } else { reject(xhr.responseText); } }; let t = (e) => reject(e); xhr.onerror = t; xhr.ontimeout = t; try { xhr.send(data); } catch (e) { reject(e); } }); }, getSessionID: function (name = 'SessionID') { return this.getCookie(name); }, getCookie: (name) => { let value = '; ' + document.cookie, parts = value.split('; ' + name + '='); if (parts.length == 2) { return parts.pop().split(';').shift(); } else { return null; } } }; export default CommonNetwork;
"use strict"; // 'npm run prepare' must be run for this to work during testing const WebsocketClient = require("../../../client/clients/WebsocketClient"); window.expectedClient = WebsocketClient; // eslint-disable-next-line camelcase, no-undef window.injectedClient = __webpack_dev_server_client__;
/* Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang('a11yhelp', 'fi', { accessibilityHelp: { title: 'Saavutettavuus ohjeet', contents: 'Ohjeen sisällöt. Sulkeaksesi tämän dialogin paina ESC.', legend: [ { name: 'Yleinen', items: [ { name: 'Editorin työkalupalkki', legend: 'Paina ${toolbarFocus} siirtyäksesi työkalupalkkiin. Siirry seuraavaan ja edelliseen työkalupalkin ryhmään TAB ja SHIFT-TAB näppäimillä. Siirry seuraavaan ja edelliseen työkalupainikkeeseen käyttämällä NUOLI OIKEALLE tai NUOLI VASEMMALLE näppäimillä. Paina VÄLILYÖNTI tai ENTER näppäintä aktivoidaksesi työkalupainikkeen.' }, { name: 'Editorin dialogi', legend: 'Dialogin sisällä, painamalla TAB siirryt seuraavaan dialogin kenttään, painamalla SHIFT+TAB siirryt aiempaan kenttään, painamalla ENTER lähetät dialogin, painamalla ESC peruutat dialogin. Dialogeille joissa on useita välilehtiä, paina ALT+F10 siirtyäksesi välillehtilistaan. Siirtyäksesi seuraavaan välilehteen paina TAB tai NUOLI OIKEALLE. Siirry edelliseen välilehteen painamalla SHIFT+TAB tai nuoli vasemmalle. Paina VÄLILYÖNTI tai ENTER valitaksesi välilehden.' }, { name: 'Editorin oheisvalikko', legend: 'Paina ${contextMenu} tai SOVELLUSPAINIKETTA avataksesi oheisvalikon. Liiku seuraavaan valikon vaihtoehtoon TAB tai NUOLI ALAS näppäimillä. Siirry edelliseen vaihtoehtoon SHIFT+TAB tai NUOLI YLÖS näppäimillä. Paina VÄLILYÖNTI tai ENTER valitaksesi valikon kohdan. Avataksesi nykyisen kohdan alivalikon paina VÄLILYÖNTI tai ENTER tai NUOLI OIKEALLE painiketta. Siirtyäksesi takaisin valikon ylemmälle tasolle paina ESC tai NUOLI vasemmalle. Oheisvalikko suljetaan ESC painikkeella.' }, { name: 'Editorin listalaatikko', legend: 'Listalaatikon sisällä siirry seuraavaan listan kohtaan TAB tai NUOLI ALAS painikkeilla. Siirry edelliseen listan kohtaan SHIFT+TAB tai NUOLI YLÖS painikkeilla. Paina VÄLILYÖNTI tai ENTER valitaksesi listan vaihtoehdon. Paina ESC sulkeaksesi listalaatikon.' }, { name: 'Editorin elementtipolun palkki', legend: 'Paina ${elementsPathFocus} siirtyäksesi elementtipolun palkkiin. Siirry seuraavaan elementtipainikkeeseen TAB tai NUOLI OIKEALLE painikkeilla. Siirry aiempaan painikkeeseen SHIFT+TAB tai NUOLI VASEMMALLE painikkeilla. Paina VÄLILYÖNTI tai ENTER valitaksesi elementin editorissa.' } ] }, { name: 'Komennot', items: [ { name: 'Peruuta komento', legend: 'Paina ${undo}' }, { name: 'Tee uudelleen komento', legend: 'Paina ${redo}' }, { name: 'Lihavoi komento', legend: 'Paina ${bold}' }, { name: 'Kursivoi komento', legend: 'Paina ${italic}' }, { name: 'Alleviivaa komento', legend: 'Paina ${underline}' }, { name: 'Linkki komento', legend: 'Paina ${link}' }, { name: 'Pienennä työkalupalkki komento', legend: 'Paina ${toolbarCollapse}' }, { name: 'Saavutettavuus ohjeet', legend: 'Paina ${a11yHelp}' } ] } ] } });
function asyncGeneratorStep(t,i,e,n,o,r,s){try{var a=t[r](s),l=a.value}catch(d){return void e(d)}a.done?i(l):Promise.resolve(l).then(n,o)}function _asyncToGenerator(t){return function(){var i=this,e=arguments;return new Promise((function(n,o){var r=t.apply(i,e);function s(t){asyncGeneratorStep(r,n,o,s,a,"next",t)}function a(t){asyncGeneratorStep(r,n,o,s,a,"throw",t)}s(void 0)}))}}function _defineProperty(t,i,e){return i in t?Object.defineProperty(t,i,{value:e,enumerable:!0,configurable:!0,writable:!0}):t[i]=e,t}function _classCallCheck(t,i){if(!(t instanceof i))throw new TypeError("Cannot call a class as a function")}function _defineProperties(t,i){for(var e=0;e<i.length;e++){var n=i[e];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}function _createClass(t,i,e){return i&&_defineProperties(t.prototype,i),e&&_defineProperties(t,e),t}(window.webpackJsonp=window.webpackJsonp||[]).push([[51],{KTnd:function(t,i,e){"use strict";e.r(i),e.d(i,"ion_item_option",(function(){return a})),e.d(i,"ion_item_options",(function(){return l})),e.d(i,"ion_item_sliding",(function(){return d}));var n,o=e("imtE"),r=(e("AfW+"),e("aiEM")),s=e("Dl6n"),a=function(){function t(i){_classCallCheck(this,t),Object(o.k)(this,i),this.disabled=!1,this.expandable=!1,this.type="button",this.onClick=function(t){t.target.closest("ion-item-option")&&t.preventDefault()}}return _createClass(t,[{key:"render",value:function(){var t,i=this.disabled,e=this.expandable,n=void 0===this.href?"button":"a",r=Object(o.d)(this),a="button"===n?{type:this.type}:{download:this.download,href:this.href,target:this.target};return Object(o.i)(o.a,{onClick:this.onClick,class:Object.assign(Object.assign({},Object(s.a)(this.color)),(t={},_defineProperty(t,r,!0),_defineProperty(t,"item-option-disabled",i),_defineProperty(t,"item-option-expandable",e),_defineProperty(t,"ion-activatable",!0),t))},Object(o.i)(n,Object.assign({},a,{class:"button-native",disabled:i}),Object(o.i)("span",{class:"button-inner"},Object(o.i)("slot",{name:"top"}),Object(o.i)("div",{class:"horizontal-wrapper"},Object(o.i)("slot",{name:"start"}),Object(o.i)("slot",{name:"icon-only"}),Object(o.i)("slot",null),Object(o.i)("slot",{name:"end"})),Object(o.i)("slot",{name:"bottom"})),"md"===r&&Object(o.i)("ion-ripple-effect",null)))}},{key:"el",get:function(){return Object(o.f)(this)}}],[{key:"style",get:function(){return":host{--background:var(--ion-color-primary,#3880ff);--color:var(--ion-color-primary-contrast,#fff);background:var(--background);color:var(--color);font-family:var(--ion-font-family,inherit)}:host(.in-list.item-options-end:last-child){padding-right:calc(.7em + var(--ion-safe-area-right))}@supports ((-webkit-margin-start:0) or (margin-inline-start:0)) or (-webkit-margin-start:0){:host(.in-list.item-options-end:last-child){padding-right:unset;-webkit-padding-end:calc(.7em + var(--ion-safe-area-right));padding-inline-end:calc(.7em + var(--ion-safe-area-right))}}:host(.in-list.item-options-start:first-child){padding-left:calc(.7em + var(--ion-safe-area-left))}@supports ((-webkit-margin-start:0) or (margin-inline-start:0)) or (-webkit-margin-start:0){:host(.in-list.item-options-start:first-child){padding-left:unset;-webkit-padding-start:calc(.7em + var(--ion-safe-area-left));padding-inline-start:calc(.7em + var(--ion-safe-area-left))}}:host(.ion-color){background:var(--ion-color-base);color:var(--ion-color-contrast)}.button-native{font-family:inherit;font-size:inherit;font-style:inherit;font-weight:inherit;letter-spacing:inherit;text-decoration:inherit;text-indent:inherit;text-overflow:inherit;text-transform:inherit;text-align:inherit;white-space:inherit;color:inherit;padding-left:.7em;padding-right:.7em;padding-top:0;padding-bottom:0;display:inline-block;position:relative;width:100%;height:100%;border:0;outline:none;background:transparent;cursor:pointer;-webkit-appearance:none;-moz-appearance:none;appearance:none;-webkit-box-sizing:border-box;box-sizing:border-box}@supports ((-webkit-margin-start:0) or (margin-inline-start:0)) or (-webkit-margin-start:0){.button-native{padding-left:unset;padding-right:unset;-webkit-padding-start:.7em;padding-inline-start:.7em;-webkit-padding-end:.7em;padding-inline-end:.7em}}.button-inner{-ms-flex-flow:column nowrap;flex-flow:column nowrap;height:100%}.button-inner,.horizontal-wrapper{display:-ms-flexbox;display:flex;-ms-flex-negative:0;flex-shrink:0;-ms-flex-align:center;align-items:center;-ms-flex-pack:center;justify-content:center;width:100%}.horizontal-wrapper{-ms-flex-flow:row nowrap;flex-flow:row nowrap}::slotted(*){-ms-flex-negative:0;flex-shrink:0}::slotted([slot=start]){margin-left:0;margin-right:5px;margin-top:0;margin-bottom:0}@supports ((-webkit-margin-start:0) or (margin-inline-start:0)) or (-webkit-margin-start:0){::slotted([slot=start]){margin-left:unset;margin-right:unset;-webkit-margin-start:0;margin-inline-start:0;-webkit-margin-end:5px;margin-inline-end:5px}}::slotted([slot=end]){margin-left:5px;margin-right:0;margin-top:0;margin-bottom:0}@supports ((-webkit-margin-start:0) or (margin-inline-start:0)) or (-webkit-margin-start:0){::slotted([slot=end]){margin-left:unset;margin-right:unset;-webkit-margin-start:5px;margin-inline-start:5px;-webkit-margin-end:0;margin-inline-end:0}}::slotted([slot=icon-only]){padding-left:0;padding-right:0;padding-top:0;padding-bottom:0;margin-left:10px;margin-right:10px;margin-top:0;margin-bottom:0;min-width:.9em;font-size:1.8em}@supports ((-webkit-margin-start:0) or (margin-inline-start:0)) or (-webkit-margin-start:0){::slotted([slot=icon-only]){margin-left:unset;margin-right:unset;-webkit-margin-start:10px;margin-inline-start:10px;-webkit-margin-end:10px;margin-inline-end:10px}}:host(.item-option-expandable){-ms-flex-negative:0;flex-shrink:0;-webkit-transition-duration:0;transition-duration:0;-webkit-transition-property:none;transition-property:none;-webkit-transition-timing-function:cubic-bezier(.65,.05,.36,1);transition-timing-function:cubic-bezier(.65,.05,.36,1)}:host(.item-option-disabled){pointer-events:none}:host(.item-option-disabled) .button-native{cursor:default;opacity:.5;pointer-events:none}:host{font-size:14px;font-weight:500;text-transform:uppercase}"}}]),t}(),l=function(){function t(i){_classCallCheck(this,t),Object(o.k)(this,i),this.side="end",this.ionSwipe=Object(o.e)(this,"ionSwipe",7)}var i;return _createClass(t,[{key:"fireSwipeEvent",value:(i=_asyncToGenerator(regeneratorRuntime.mark((function t(){return regeneratorRuntime.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:this.ionSwipe.emit({side:this.side});case 1:case"end":return t.stop()}}),t,this)}))),function(){return i.apply(this,arguments)})},{key:"render",value:function(){var t,i=Object(o.d)(this),e=Object(r.h)(this.side);return Object(o.i)(o.a,{class:(t={},_defineProperty(t,i,!0),_defineProperty(t,"item-options-".concat(i),!0),_defineProperty(t,"item-options-start",!e),_defineProperty(t,"item-options-end",e),t)})}},{key:"el",get:function(){return Object(o.f)(this)}}],[{key:"style",get:function(){return"ion-item-options{top:0;right:0;-ms-flex-pack:end;justify-content:flex-end;display:none;position:absolute;height:100%;font-size:14px;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;z-index:1}:host-context([dir=rtl]) ion-item-options,[dir=rtl] ion-item-options{-ms-flex-pack:start;justify-content:flex-start}:host-context([dir=rtl]) ion-item-options:not(.item-options-end),[dir=rtl] ion-item-options:not(.item-options-end){right:auto;left:0;-ms-flex-pack:end;justify-content:flex-end}.item-options-start{right:auto;left:0;-ms-flex-pack:start;justify-content:flex-start}:host-context([dir=rtl]) .item-options-start,[dir=rtl] .item-options-start{-ms-flex-pack:end;justify-content:flex-end}.item-options-start ion-item-option:first-child{padding-right:var(--ion-safe-area-left)}@supports ((-webkit-margin-start:0) or (margin-inline-start:0)) or (-webkit-margin-start:0){.item-options-start ion-item-option:first-child{padding-right:unset;-webkit-padding-end:var(--ion-safe-area-left);padding-inline-end:var(--ion-safe-area-left)}}.item-options-end ion-item-option:last-child{padding-right:var(--ion-safe-area-right)}@supports ((-webkit-margin-start:0) or (margin-inline-start:0)) or (-webkit-margin-start:0){.item-options-end ion-item-option:last-child{padding-right:unset;-webkit-padding-end:var(--ion-safe-area-right);padding-inline-end:var(--ion-safe-area-right)}}:host-context([dir=rtl]) .item-sliding-active-slide.item-sliding-active-options-start ion-item-options:not(.item-options-end),[dir=rtl] .item-sliding-active-slide.item-sliding-active-options-start ion-item-options:not(.item-options-end){width:100%;visibility:visible}.item-sliding-active-slide ion-item-options{display:-ms-flexbox;display:flex;visibility:hidden}.item-sliding-active-slide.item-sliding-active-options-end ion-item-options:not(.item-options-start),.item-sliding-active-slide.item-sliding-active-options-start .item-options-start{width:100%;visibility:visible}.item-options-md{border-bottom-style:solid;border-bottom-color:var(--ion-item-border-color,var(--ion-border-color,var(--ion-color-step-150,rgba(0,0,0,.13))))}.item-options-md,.list-md-lines-none .item-options-md{border-bottom-width:0}.list-md-lines-full .item-options-md,.list-md-lines-inset .item-options-md.item-options-end{border-bottom-width:1px}"}}]),t}(),d=function(){function t(i){_classCallCheck(this,t),Object(o.k)(this,i),this.item=null,this.openAmount=0,this.initialOpenAmount=0,this.optsWidthRightSide=0,this.optsWidthLeftSide=0,this.sides=0,this.optsDirty=!0,this.state=2,this.disabled=!1,this.ionDrag=Object(o.e)(this,"ionDrag",7)}var i,s,a,l,d;return _createClass(t,[{key:"disabledChanged",value:function(){this.gesture&&this.gesture.enable(!this.disabled)}},{key:"connectedCallback",value:(d=_asyncToGenerator(regeneratorRuntime.mark((function t(){var i=this;return regeneratorRuntime.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return this.item=this.el.querySelector("ion-item"),t.next=3,this.updateOptions();case 3:return t.next=5,Promise.resolve().then(e.bind(null,"AzGJ"));case 5:t.t0={el:this.el,gestureName:"item-swipe",gesturePriority:100,threshold:5,canStart:function(){return i.canStart()},onStart:function(){return i.onStart()},onMove:function(t){return i.onMove(t)},onEnd:function(t){return i.onEnd(t)}},this.gesture=t.sent.createGesture(t.t0),this.disabledChanged();case 8:case"end":return t.stop()}}),t,this)}))),function(){return d.apply(this,arguments)})},{key:"disconnectedCallback",value:function(){this.gesture&&(this.gesture.destroy(),this.gesture=void 0),this.item=null,this.leftOptions=this.rightOptions=void 0,n===this.el&&(n=void 0)}},{key:"getOpenAmount",value:function(){return Promise.resolve(this.openAmount)}},{key:"getSlidingRatio",value:function(){return Promise.resolve(this.getSlidingRatioSync())}},{key:"open",value:(l=_asyncToGenerator(regeneratorRuntime.mark((function t(i){var e,o=this;return regeneratorRuntime.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(null!==this.item){t.next=2;break}return t.abrupt("return");case 2:(e=this.getOptions(i))&&(void 0===i&&(i=e===this.leftOptions?"start":"end"),i=Object(r.h)(i)?"end":"start",this.openAmount<0&&e===this.leftOptions||this.openAmount>0&&e===this.rightOptions||(this.closeOpened(),this.state=4,requestAnimationFrame((function(){o.calculateOptsWidth(),n=o.el,o.setOpenAmount("end"===i?o.optsWidthRightSide:-o.optsWidthLeftSide,!1),o.state="end"===i?8:16}))));case 4:case"end":return t.stop()}}),t,this)}))),function(t){return l.apply(this,arguments)})},{key:"close",value:(a=_asyncToGenerator(regeneratorRuntime.mark((function t(){return regeneratorRuntime.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:this.setOpenAmount(0,!0);case 1:case"end":return t.stop()}}),t,this)}))),function(){return a.apply(this,arguments)})},{key:"closeOpened",value:(s=_asyncToGenerator(regeneratorRuntime.mark((function t(){return regeneratorRuntime.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.abrupt("return",void 0!==n&&(n.close(),n=void 0,!0));case 1:case"end":return t.stop()}}),t)}))),function(){return s.apply(this,arguments)})},{key:"getOptions",value:function(t){return void 0===t?this.leftOptions||this.rightOptions:"start"===t?this.leftOptions:this.rightOptions}},{key:"updateOptions",value:(i=_asyncToGenerator(regeneratorRuntime.mark((function t(){var i,e,n,o;return regeneratorRuntime.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:i=this.el.querySelectorAll("ion-item-options"),e=0,this.leftOptions=this.rightOptions=void 0,n=0;case 4:if(!(n<i.length)){t.next=12;break}return t.next=7,i.item(n).componentOnReady();case 7:o=t.sent,"start"==(Object(r.h)(o.side)?"end":"start")?(this.leftOptions=o,e|=1):(this.rightOptions=o,e|=2);case 9:n++,t.next=4;break;case 12:this.optsDirty=!0,this.sides=e;case 13:case"end":return t.stop()}}),t,this)}))),function(){return i.apply(this,arguments)})},{key:"canStart",value:function(){return n&&n!==this.el?(this.closeOpened(),!1):!(!this.rightOptions&&!this.leftOptions)}},{key:"onStart",value:function(){n=this.el,void 0!==this.tmr&&(clearTimeout(this.tmr),this.tmr=void 0),0===this.openAmount&&(this.optsDirty=!0,this.state=4),this.initialOpenAmount=this.openAmount,this.item&&(this.item.style.transition="none")}},{key:"onMove",value:function(t){this.optsDirty&&this.calculateOptsWidth();var i,e=this.initialOpenAmount-t.deltaX;switch(this.sides){case 2:e=Math.max(0,e);break;case 1:e=Math.min(0,e);break;case 3:break;case 0:return;default:console.warn("invalid ItemSideFlags value",this.sides)}e>this.optsWidthRightSide?e=(i=this.optsWidthRightSide)+.55*(e-i):e<-this.optsWidthLeftSide&&(e=(i=-this.optsWidthLeftSide)+.55*(e-i)),this.setOpenAmount(e,!1)}},{key:"onEnd",value:function(t){var i=t.velocityX,e=this.openAmount>0?this.optsWidthRightSide:-this.optsWidthLeftSide,n=this.openAmount>0==!(i<0),o=Math.abs(i)>.3,r=Math.abs(this.openAmount)<Math.abs(e/2);p(n,o,r)&&(e=0);var s=this.state;this.setOpenAmount(e,!0),0!=(32&s)&&this.rightOptions?this.rightOptions.fireSwipeEvent():0!=(64&s)&&this.leftOptions&&this.leftOptions.fireSwipeEvent()}},{key:"calculateOptsWidth",value:function(){this.optsWidthRightSide=0,this.rightOptions&&(this.rightOptions.style.display="flex",this.optsWidthRightSide=this.rightOptions.offsetWidth,this.rightOptions.style.display=""),this.optsWidthLeftSide=0,this.leftOptions&&(this.leftOptions.style.display="flex",this.optsWidthLeftSide=this.leftOptions.offsetWidth,this.leftOptions.style.display=""),this.optsDirty=!1}},{key:"setOpenAmount",value:function(t,i){var e=this;if(void 0!==this.tmr&&(clearTimeout(this.tmr),this.tmr=void 0),this.item){var o=this.item.style;if(this.openAmount=t,i&&(o.transition=""),t>0)this.state=t>=this.optsWidthRightSide+30?40:8;else{if(!(t<0))return this.tmr=setTimeout((function(){e.state=2,e.tmr=void 0}),600),n=void 0,void(o.transform="");this.state=t<=-this.optsWidthLeftSide-30?80:16}o.transform="translate3d(".concat(-t,"px,0,0)"),this.ionDrag.emit({amount:t,ratio:this.getSlidingRatioSync()})}}},{key:"getSlidingRatioSync",value:function(){return this.openAmount>0?this.openAmount/this.optsWidthRightSide:this.openAmount<0?this.openAmount/this.optsWidthLeftSide:0}},{key:"render",value:function(){var t,i=Object(o.d)(this);return Object(o.i)(o.a,{class:(t={},_defineProperty(t,i,!0),_defineProperty(t,"item-sliding-active-slide",2!==this.state),_defineProperty(t,"item-sliding-active-options-end",0!=(8&this.state)),_defineProperty(t,"item-sliding-active-options-start",0!=(16&this.state)),_defineProperty(t,"item-sliding-active-swipe-end",0!=(32&this.state)),_defineProperty(t,"item-sliding-active-swipe-start",0!=(64&this.state)),t)})}},{key:"el",get:function(){return Object(o.f)(this)}}],[{key:"watchers",get:function(){return{disabled:["disabledChanged"]}}},{key:"style",get:function(){return"ion-item-sliding{display:block;position:relative;width:100%;overflow:hidden}ion-item-sliding,ion-item-sliding .item{-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.item-sliding-active-slide .item{position:relative;-webkit-transition:-webkit-transform .5s cubic-bezier(.36,.66,.04,1);transition:-webkit-transform .5s cubic-bezier(.36,.66,.04,1);transition:transform .5s cubic-bezier(.36,.66,.04,1);transition:transform .5s cubic-bezier(.36,.66,.04,1),-webkit-transform .5s cubic-bezier(.36,.66,.04,1);opacity:1;z-index:2;pointer-events:none;will-change:transform}.item-sliding-active-swipe-end .item-options-end .item-option-expandable{padding-left:100%;-ms-flex-order:1;order:1;-webkit-transition-duration:.6s;transition-duration:.6s;-webkit-transition-property:padding-left;transition-property:padding-left}:host-context([dir=rtl]) .item-sliding-active-swipe-end .item-options-end .item-option-expandable,[dir=rtl] .item-sliding-active-swipe-end .item-options-end .item-option-expandable{-ms-flex-order:-1;order:-1}.item-sliding-active-swipe-start .item-options-start .item-option-expandable{padding-right:100%;-ms-flex-order:-1;order:-1;-webkit-transition-duration:.6s;transition-duration:.6s;-webkit-transition-property:padding-right;transition-property:padding-right}:host-context([dir=rtl]) .item-sliding-active-swipe-start .item-options-start .item-option-expandable,[dir=rtl] .item-sliding-active-swipe-start .item-options-start .item-option-expandable{-ms-flex-order:1;order:1}"}}]),t}(),p=function(t,i,e){return!i&&e||t&&i}}}]);
// Important modules this config uses const path = require('path') const HtmlWebpackPlugin = require('html-webpack-plugin') const WebpackPwaManifest = require('webpack-pwa-manifest') const OfflinePlugin = require('offline-plugin') const { HashedModuleIdsPlugin } = require('webpack') const TerserPlugin = require('terser-webpack-plugin') const CompressionPlugin = require('compression-webpack-plugin') module.exports = require('./webpack.base.babel')({ mode: 'production', // In production, we skip all hot-reloading stuff entry: [ require.resolve('react-app-polyfill/ie11'), path.join(process.cwd(), 'app/app.js'), ], // Utilize long-term caching by adding content hashes (not compilation hashes) to compiled assets output: { filename: '[name].[chunkhash].js', chunkFilename: '[name].[chunkhash].chunk.js', }, optimization: { minimize: true, minimizer: [ new TerserPlugin({ terserOptions: { warnings: false, compress: { comparisons: false, }, parse: {}, mangle: true, output: { comments: false, ascii_only: true, }, }, parallel: true, cache: true, sourceMap: true, }), ], nodeEnv: 'production', sideEffects: true, concatenateModules: true, runtimeChunk: 'single', splitChunks: { chunks: 'all', maxInitialRequests: 10, minSize: 0, cacheGroups: { vendor: { test: /[\\/]node_modules[\\/]/, name(module) { const packageName = module.context.match( /[\\/]node_modules[\\/](.*?)([\\/]|$)/, )[1] return `npm.${packageName.replace('@', '')}` }, }, }, }, }, plugins: [ // Minify and optimize the index.html new HtmlWebpackPlugin({ template: 'app/index.html', minify: { removeComments: true, collapseWhitespace: true, removeRedundantAttributes: true, useShortDoctype: true, removeEmptyAttributes: true, removeStyleLinkTypeAttributes: true, keepClosingSlash: true, minifyJS: true, minifyCSS: true, minifyURLs: true, }, inject: true, }), // Put it in the end to capture all the HtmlWebpackPlugin's // assets manipulations and do leak its manipulations to HtmlWebpackPlugin new OfflinePlugin({ relativePaths: false, publicPath: '/', appShell: '/', // No need to cache .htaccess. See http://mxs.is/googmp, // this is applied before any match in `caches` section excludes: ['.htaccess'], caches: { main: [':rest:'], // All chunks marked as `additional`, loaded after main section // and do not prevent SW to install. Change to `optional` if // do not want them to be preloaded at all (cached only when first loaded) additional: ['*.chunk.js'], }, // Removes warning for about `additional` section usage safeToUseOptionalCaches: true, }), new CompressionPlugin({ algorithm: 'gzip', test: /\.js$|\.css$|\.html$/, threshold: 10240, minRatio: 0.8, }), new WebpackPwaManifest({ name: 'React Boilerplate', short_name: 'React BP', description: 'My React Boilerplate-based project!', background_color: '#fafafa', theme_color: '#b1624d', inject: true, ios: true, icons: [ { src: path.resolve('app/medias/images/icon-512x512.png'), sizes: [72, 96, 128, 144, 192, 384, 512], }, { src: path.resolve('app/medias/images/icon-512x512.png'), sizes: [120, 152, 167, 180], ios: true, }, ], }), new HashedModuleIdsPlugin({ hashFunction: 'sha256', hashDigest: 'hex', hashDigestLength: 20, }), ], performance: { assetFilter: assetFilename => !/(\.map$)|(^(main\.|favicon\.))/.test(assetFilename), }, })
 CKEDITOR.lang['gu']={"editor":"રીચ ટેક્ષ્ત્ એડીટર","editorPanel":"Rich Text Editor panel","common":{"editorHelp":"પ્રેસ ALT 0 મદદ માટ","browseServer":"સર્વર બ્રાઉઝ કરો","url":"URL","protocol":"પ્રોટોકૉલ","upload":"અપલોડ","uploadSubmit":"આ સર્વરને મોકલવું","image":"ચિત્ર","flash":"ફ્લૅશ","form":"ફૉર્મ/પત્રક","checkbox":"ચેક બોક્સ","radio":"રેડિઓ બટન","textField":"ટેક્સ્ટ ફીલ્ડ, શબ્દ ક્ષેત્ર","textarea":"ટેક્સ્ટ એરિઆ, શબ્દ વિસ્તાર","hiddenField":"ગુપ્ત ક્ષેત્ર","button":"બટન","select":"પસંદગી ક્ષેત્ર","imageButton":"ચિત્ર બટન","notSet":"<સેટ નથી>","id":"Id","name":"નામ","langDir":"ભાષા લેખવાની પદ્ધતિ","langDirLtr":"ડાબે થી જમણે (LTR)","langDirRtl":"જમણે થી ડાબે (RTL)","langCode":"ભાષા કોડ","longDescr":"વધારે માહિતી માટે URL","cssClass":"સ્ટાઇલ-શીટ ક્લાસ","advisoryTitle":"મુખ્ય મથાળું","cssStyle":"સ્ટાઇલ","ok":"ઠીક છે","cancel":"રદ કરવું","close":"બંધ કરવું","preview":"જોવું","resize":"ખેંચી ને યોગ્ય કરવું","generalTab":"જનરલ","advancedTab":"અડ્વાન્સડ","validateNumberFailed":"આ રકમ આકડો નથી.","confirmNewPage":"સવે કાર્ય વગરનું ફકરો ખોવાઈ જશે. તમને ખાતરી છે કે તમને નવું પાનું ખોલવું છે?","confirmCancel":"ઘણા વિકલ્પો બદલાયા છે. તમારે આ બોક્ષ્ બંધ કરવું છે?","options":"વિકલ્પો","target":"લક્ષ્ય","targetNew":"નવી વિન્ડો (_blank)","targetTop":"ઉપરની વિન્ડો (_top)","targetSelf":"એજ વિન્ડો (_self)","targetParent":"પેરનટ વિન્ડો (_parent)","langDirLTR":"ડાબે થી જમણે (LTR)","langDirRTL":"જમણે થી ડાબે (RTL)","styles":"શૈલી","cssClasses":"શૈલી કલાસીસ","width":"પહોળાઈ","height":"ઊંચાઈ","align":"લાઇનદોરીમાં ગોઠવવું","alignLeft":"ડાબી બાજુ ગોઠવવું","alignRight":"જમણી","alignCenter":"મધ્ય સેન્ટર","alignJustify":"બ્લૉક, અંતરાય જસ્ટિફાઇ","alignTop":"ઉપર","alignMiddle":"વચ્ચે","alignBottom":"નીચે","alignNone":"None","invalidValue":"Invalid value.","invalidHeight":"ઉંચાઈ એક આંકડો હોવો જોઈએ.","invalidWidth":"પોહળ ઈ એક આંકડો હોવો જોઈએ.","invalidCssLength":"\"%1\" ની વેલ્યુ એક પોસીટીવ આંકડો હોવો જોઈએ અથવા CSS measurement unit (px, %, in, cm, mm, em, ex, pt, or pc) વગર.","invalidHtmlLength":"\"%1\" ની વેલ્યુ એક પોસીટીવ આંકડો હોવો જોઈએ અથવા HTML measurement unit (px or %) વગર.","invalidInlineStyle":"ઈનલાઈન સ્ટાઈલ ની વેલ્યુ \"name : value\" ના ફોર્મેટ માં હોવી જોઈએ, વચ્ચે સેમી-કોલોન જોઈએ.","cssLengthTooltip":"પિક્ષ્લ્ નો આંકડો CSS unit (px, %, in, cm, mm, em, ex, pt, or pc) માં નાખો.","unavailable":"%1<span class=\"cke_accessibility\">, નથી મળતું</span>"},"about":{"copy":"કોપીરાઈટ &copy; $1. ઓલ રાઈટ્સ ","dlgTitle":"CKEditor વિષે","help":"મદદ માટે $1 તપાસો","moreInfo":"લાયસનસની માહિતી માટે અમારી વેબ સાઈટ","title":"CKEditor વિષે","userGuide":"CKEditor યુઝર્સ ગાઈડ"},"basicstyles":{"bold":"બોલ્ડ/સ્પષ્ટ","italic":"ઇટેલિક, ત્રાંસા","strike":"છેકી નાખવું","subscript":"એક ચિહ્નની નીચે કરેલું બીજું ચિહ્ન","superscript":"એક ચિહ્ન ઉપર કરેલું બીજું ચિહ્ન.","underline":"અન્ડર્લાઇન, નીચે લીટી"},"blockquote":{"toolbar":"બ્લૉક-કોટ, અવતરણચિહ્નો"},"clipboard":{"copy":"નકલ","copyError":"તમારા બ્રાઉઝર ની સુરક્ષિત સેટિંગસ કોપી કરવાની પરવાનગી નથી આપતી. (Ctrl/Cmd+C) का प्रयोग करें।","cut":"કાપવું","cutError":"તમારા બ્રાઉઝર ની સુરક્ષિત સેટિંગસ કટ કરવાની પરવાનગી નથી આપતી. (Ctrl/Cmd+X) નો ઉપયોગ કરો.","paste":"પેસ્ટ","pasteArea":"પેસ્ટ કરવાની જગ્યા","pasteMsg":"Ctrl/Cmd+V નો પ્રયોગ કરી પેસ્ટ કરો","securityMsg":"તમારા બ્રાઉઝર ની સુરક્ષિત સેટિંગસના કારણે,એડિટર તમારા કિલ્પબોર્ડ ડેટા ને કોપી નથી કરી શકતો. તમારે આ વિન્ડોમાં ફરીથી પેસ્ટ કરવું પડશે.","title":"પેસ્ટ"},"contextmenu":{"options":"કોન્તેક્ષ્ત્ મેનુના વિકલ્પો"},"button":{"selectedLabel":"%1 (Selected)"},"toolbar":{"toolbarCollapse":"ટૂલબાર નાનું કરવું","toolbarExpand":"ટૂલબાર મોટું કરવું","toolbarGroups":{"document":"દસ્તાવેજ","clipboard":"ક્લિપબોર્ડ/અન","editing":"એડીટ કરવું","forms":"ફોર્મ","basicstyles":"બેસિક્ સ્ટાઇલ","paragraph":"ફકરો","links":"લીંક","insert":"ઉમેરવું","styles":"સ્ટાઇલ","colors":"રંગ","tools":"ટૂલ્સ"},"toolbars":"એડીટર ટૂલ બાર"},"elementspath":{"eleLabel":"એલીમેન્ટ્સ નો ","eleTitle":"એલીમેન્ટ %1"},"format":{"label":"ફૉન્ટ ફૉર્મટ, રચનાની શૈલી","panelTitle":"ફૉન્ટ ફૉર્મટ, રચનાની શૈલી","tag_address":"સરનામું","tag_div":"શીર્ષક (DIV)","tag_h1":"શીર્ષક 1","tag_h2":"શીર્ષક 2","tag_h3":"શીર્ષક 3","tag_h4":"શીર્ષક 4","tag_h5":"શીર્ષક 5","tag_h6":"શીર્ષક 6","tag_p":"સામાન્ય","tag_pre":"ફૉર્મટેડ"},"horizontalrule":{"toolbar":"સમસ્તરીય રેખા ઇન્સર્ટ/દાખલ કરવી"},"image":{"alt":"ઑલ્ટર્નટ ટેક્સ્ટ","border":"બોર્ડર","btnUpload":"આ સર્વરને મોકલવું","button2Img":"તમારે ઈમેજ બટનને સાદી ઈમેજમાં બદલવું છે.","hSpace":"સમસ્તરીય જગ્યા","img2Button":"તમારે સાદી ઈમેજને ઈમેજ બટનમાં બદલવું છે.","infoTab":"ચિત્ર ની જાણકારી","linkTab":"લિંક","lockRatio":"લૉક ગુણોત્તર","menu":"ચિત્રના ગુણ","resetSize":"રીસેટ સાઇઝ","title":"ચિત્રના ગુણ","titleButton":"ચિત્ર બટનના ગુણ","upload":"અપલોડ","urlMissing":"ઈમેજની મૂળ URL છે નહી.","vSpace":"લંબરૂપ જગ્યા","validateBorder":"બોર્ડેર આંકડો હોવો જોઈએ.","validateHSpace":"HSpaceઆંકડો હોવો જોઈએ.","validateVSpace":"VSpace આંકડો હોવો જોઈએ. "},"indent":{"indent":"ઇન્ડેન્ટ, લીટીના આરંભમાં જગ્યા વધારવી","outdent":"ઇન્ડેન્ટ લીટીના આરંભમાં જગ્યા ઘટાડવી"},"fakeobjects":{"anchor":"અનકર","flash":"ફ્લેશ ","hiddenfield":"હિડન ","iframe":"IFrame","unknown":"અનનોન ઓબ્જેક્ટ"},"link":{"acccessKey":"ઍક્સેસ કી","advanced":"અડ્વાન્સડ","advisoryContentType":"મુખ્ય કન્ટેન્ટ પ્રકાર","advisoryTitle":"મુખ્ય મથાળું","anchor":{"toolbar":"ઍંકર ઇન્સર્ટ/દાખલ કરવી","menu":"ઍંકરના ગુણ","title":"ઍંકરના ગુણ","name":"ઍંકરનું નામ","errorName":"ઍંકરનું નામ ટાઈપ કરો","remove":"સ્થિર નકરવું"},"anchorId":"ઍંકર એલિમન્ટ Id થી પસંદ કરો","anchorName":"ઍંકર નામથી પસંદ કરો","charset":"લિંક રિસૉર્સ કૅરિક્ટર સેટ","cssClasses":"સ્ટાઇલ-શીટ ક્લાસ","emailAddress":"ઈ-મેલ સરનામું","emailBody":"સંદેશ","emailSubject":"ઈ-મેલ વિષય","id":"Id","info":"લિંક ઇન્ફૉ ટૅબ","langCode":"ભાષા લેખવાની પદ્ધતિ","langDir":"ભાષા લેખવાની પદ્ધતિ","langDirLTR":"ડાબે થી જમણે (LTR)","langDirRTL":"જમણે થી ડાબે (RTL)","menu":" લિંક એડિટ/માં ફેરફાર કરવો","name":"નામ","noAnchors":"(ડૉક્યુમન્ટમાં ઍંકરની સંખ્યા)","noEmail":"ઈ-મેલ સરનામું ટાઇપ કરો","noUrl":"લિંક URL ટાઇપ કરો","other":"<other> <અન્ય>","popupDependent":"ડિપેન્ડન્ટ (Netscape)","popupFeatures":"પૉપ-અપ વિન્ડો ફીચરસૅ","popupFullScreen":"ફુલ સ્ક્રીન (IE)","popupLeft":"ડાબી બાજુ","popupLocationBar":"લોકેશન બાર","popupMenuBar":"મેન્યૂ બાર","popupResizable":"રીસાઈઝએબલ","popupScrollBars":"સ્ક્રોલ બાર","popupStatusBar":"સ્ટૅટસ બાર","popupToolbar":"ટૂલ બાર","popupTop":"જમણી બાજુ","rel":"સંબંધની સ્થિતિ","selectAnchor":"ઍંકર પસંદ કરો","styles":"સ્ટાઇલ","tabIndex":"ટૅબ ઇન્ડેક્સ","target":"ટાર્ગેટ/લક્ષ્ય","targetFrame":"<ફ્રેમ>","targetFrameName":"ટાર્ગેટ ફ્રેમ નું નામ","targetPopup":"<પૉપ-અપ વિન્ડો>","targetPopupName":"પૉપ-અપ વિન્ડો નું નામ","title":"લિંક","toAnchor":"આ પેજનો ઍંકર","toEmail":"ઈ-મેલ","toUrl":"URL","toolbar":"લિંક ઇન્સર્ટ/દાખલ કરવી","type":"લિંક પ્રકાર","unlink":"લિંક કાઢવી","upload":"અપલોડ"},"list":{"bulletedlist":"બુલેટ સૂચિ","numberedlist":"સંખ્યાંકન સૂચિ"},"magicline":{"title":"Insert paragraph here"},"maximize":{"maximize":"મોટું કરવું","minimize":"નાનું કરવું"},"pastetext":{"button":"પેસ્ટ (ટેક્સ્ટ)","title":"પેસ્ટ (ટેક્સ્ટ)"},"pastefromword":{"confirmCleanup":"તમે જે ટેક્ષ્ત્ કોપી કરી રહ્યા છો ટે વર્ડ ની છે. કોપી કરતા પેહલા સાફ કરવી છે?","error":"પેસ્ટ કરેલો ડેટા ઇન્ટરનલ એરર ના લીથે સાફ કરી શકાયો નથી.","title":"પેસ્ટ (વડૅ ટેક્સ્ટ)","toolbar":"પેસ્ટ (વડૅ ટેક્સ્ટ)"},"removeformat":{"toolbar":"ફૉર્મટ કાઢવું"},"sourcearea":{"toolbar":"મૂળ કે પ્રાથમિક દસ્તાવેજ"},"specialchar":{"options":"સ્પેશિઅલ કરેક્ટરના વિકલ્પો","title":"સ્પેશિઅલ વિશિષ્ટ અક્ષર પસંદ કરો","toolbar":"વિશિષ્ટ અક્ષર ઇન્સર્ટ/દાખલ કરવું"},"scayt":{"btn_about":"SCAYT વિષે","btn_dictionaries":"શબ્દકોશ","btn_disable":"SCAYT ડિસેબલ કરવું","btn_enable":"SCAYT એનેબલ કરવું","btn_langs":"ભાષાઓ","btn_options":"વિકલ્પો","text_title":"ટાઈપ કરતા સ્પેલ તપાસો"},"stylescombo":{"label":"શૈલી/રીત","panelTitle":"ફોર્મેટ ","panelTitle1":"બ્લોક ","panelTitle2":"ઈનલાઈન ","panelTitle3":"ઓબ્જેક્ટ પદ્ધતિ"},"table":{"border":"કોઠાની બાજુ(બોર્ડર) સાઇઝ","caption":"મથાળું/કૅપ્શન ","cell":{"menu":"કોષના ખાના","insertBefore":"પહેલાં કોષ ઉમેરવો","insertAfter":"પછી કોષ ઉમેરવો","deleteCell":"કોષ ડિલીટ/કાઢી નાખવો","merge":"કોષ ભેગા કરવા","mergeRight":"જમણી બાજુ ભેગા કરવા","mergeDown":"નીચે ભેગા કરવા","splitHorizontal":"કોષને સમસ્તરીય વિભાજન કરવું","splitVertical":"કોષને સીધું ને ઊભું વિભાજન કરવું","title":"સેલના ગુણ","cellType":"સેલનો પ્રકાર","rowSpan":"આડી કટારની જગ્યા","colSpan":"ઊભી કતારની જગ્યા","wordWrap":"વર્ડ રેપ","hAlign":"સપાટ લાઈનદોરી","vAlign":"ઊભી લાઈનદોરી","alignBaseline":"બસે લાઈન","bgColor":"પાછાળનો રંગ","borderColor":"બોર્ડેર રંગ","data":"સ્વીકૃત માહિતી","header":"મથાળું","yes":"હા","no":"ના","invalidWidth":"સેલની પોહલાઈ આંકડો હોવો જોઈએ.","invalidHeight":"સેલની ઊંચાઈ આંકડો હોવો જોઈએ.","invalidRowSpan":"રો સ્પાન આંકડો હોવો જોઈએ.","invalidColSpan":"કોલમ સ્પાન આંકડો હોવો જોઈએ.","chooseColor":"પસંદ કરવું"},"cellPad":"સેલ પૅડિંગ","cellSpace":"સેલ અંતર","column":{"menu":"કૉલમ/ઊભી કટાર","insertBefore":"પહેલાં કૉલમ/ઊભી કટાર ઉમેરવી","insertAfter":"પછી કૉલમ/ઊભી કટાર ઉમેરવી","deleteColumn":"કૉલમ/ઊભી કટાર ડિલીટ/કાઢી નાખવી"},"columns":"કૉલમ/ઊભી કટાર","deleteTable":"કોઠો ડિલીટ/કાઢી નાખવું","headers":"મથાળા","headersBoth":"બેવું","headersColumn":"પહેલી ઊભી કટાર","headersNone":"નથી ","headersRow":"પહેલી કટાર","invalidBorder":"બોર્ડર એક આંકડો હોવો જોઈએ","invalidCellPadding":"સેલની અંદરની જગ્યા સુન્ય કરતા વધારે હોવી જોઈએ.","invalidCellSpacing":"સેલ વચ્ચેની જગ્યા સુન્ય કરતા વધારે હોવી જોઈએ.","invalidCols":"ઉભી કટાર, 0 કરતા વધારે હોવી જોઈએ.","invalidHeight":"ટેબલની ઊંચાઈ આંકડો હોવો જોઈએ.","invalidRows":"આડી કટાર, 0 કરતા વધારે હોવી જોઈએ.","invalidWidth":"ટેબલની પોહલાઈ આંકડો હોવો જોઈએ.","menu":"ટેબલ, કોઠાનું મથાળું","row":{"menu":"પંક્તિના ખાના","insertBefore":"પહેલાં પંક્તિ ઉમેરવી","insertAfter":"પછી પંક્તિ ઉમેરવી","deleteRow":"પંક્તિઓ ડિલીટ/કાઢી નાખવી"},"rows":"પંક્તિના ખાના","summary":"ટૂંકો એહેવાલ","title":"ટેબલ, કોઠાનું મથાળું","toolbar":"ટેબલ, કોઠો","widthPc":"પ્રતિશત","widthPx":"પિકસલ","widthUnit":"પોહાલાઈ એકમ"},"undo":{"redo":"રિડૂ; પછી હતી એવી સ્થિતિ પાછી લાવવી","undo":"રદ કરવું; પહેલાં હતી એવી સ્થિતિ પાછી લાવવી"},"wsc":{"btnIgnore":"ઇગ્નોર/અવગણના કરવી","btnIgnoreAll":"બધાની ઇગ્નોર/અવગણના કરવી","btnReplace":"બદલવું","btnReplaceAll":"બધા બદલી કરો","btnUndo":"અન્ડૂ","changeTo":"આનાથી બદલવું","errorLoading":"સર્વિસ એપ્લીકેશન લોડ નથી થ: %s.","ieSpellDownload":"સ્પેલ-ચેકર ઇન્સ્ટોલ નથી. શું તમે ડાઉનલોડ કરવા માંગો છો?","manyChanges":"શબ્દની જોડણી/સ્પેલ ચેક પૂર્ણ: %1 શબ્દ બદલયા છે","noChanges":"શબ્દની જોડણી/સ્પેલ ચેક પૂર્ણ: એકપણ શબ્દ બદલયો નથી","noMispell":"શબ્દની જોડણી/સ્પેલ ચેક પૂર્ણ: ખોટી જોડણી મળી નથી","noSuggestions":"- કઇ સજેશન નથી -","notAvailable":"માફ કરશો, આ સુવિધા ઉપલબ્ધ નથી","notInDic":"શબ્દકોશમાં નથી","oneChange":"શબ્દની જોડણી/સ્પેલ ચેક પૂર્ણ: એક શબ્દ બદલયો છે","progress":"શબ્દની જોડણી/સ્પેલ ચેક ચાલુ છે...","title":"સ્પેલ ","toolbar":"જોડણી (સ્પેલિંગ) તપાસવી"}};
const RopeSequence = require("rope-sequence") const {Mapping} = require("prosemirror-transform") const {Selection, Plugin, PluginKey} = require("prosemirror-state") // ProseMirror's history isn't simply a way to roll back to a previous // state, because ProseMirror supports applying changes without adding // them to the history (for example during collaboration). // // To this end, each 'Branch' (one for the undo history and one for // the redo history) keeps an array of 'Items', which can optionally // hold a step (an actual undoable change), and always hold a position // map (which is needed to move changes below them to apply to the // current document). // // An item that has both a step and a selection JSON representation is // the start of an 'event' — a group of changes that will be undone // or redone at once. (It stores only the JSON, since that way we don't // have to provide a document until the selection is actually applied, // which is useful when compressing.) // Used to schedule history compression const max_empty_items = 500 class Branch { constructor(items, eventCount) { this.items = items this.eventCount = eventCount } // : (Node, bool, ?Item) → ?{transform: Transform, selection: Object} // Pop the latest event off the branch's history and apply it // to a document transform. popEvent(state, preserveItems) { if (this.eventCount == 0) return null let end = this.items.length for (;; end--) { let next = this.items.get(end - 1) if (next.selection) { --end; break } } let remap, mapFrom if (preserveItems) { remap = this.remapping(end, this.items.length) mapFrom = remap.maps.length } let transform = state.tr let selection, remaining let addAfter = [], addBefore = [] this.items.forEach((item, i) => { if (!item.step) { if (!remap) { remap = this.remapping(end, i + 1) mapFrom = remap.maps.length } mapFrom-- addBefore.push(item) return } if (remap) { addBefore.push(new Item(item.map)) let step = item.step.map(remap.slice(mapFrom)), map if (step && transform.maybeStep(step).doc) { map = transform.mapping.maps[transform.mapping.maps.length - 1] addAfter.push(new Item(map, null, null, addAfter.length + addBefore.length)) } mapFrom-- if (map) remap.appendMap(map, mapFrom) } else { transform.maybeStep(item.step) } if (item.selection) { selection = remap ? Selection.mapJSON(item.selection, remap.slice(mapFrom)) : item.selection remaining = new Branch(this.items.slice(0, end).append(addBefore.reverse().concat(addAfter)), this.eventCount - 1) return false } }, this.items.length, 0) return {remaining, transform, selection} } // : (Transform, Selection, Object) // Create a new branch with the given transform added. addTransform(transform, selection, histOptions) { let newItems = [], eventCount = this.eventCount + (selection ? 1 : 0) let oldItems = this.items, lastItem = !histOptions.preserveItems && oldItems.length ? oldItems.get(oldItems.length - 1) : null for (let i = 0; i < transform.steps.length; i++) { let step = transform.steps[i].invert(transform.docs[i]) let item = new Item(transform.mapping.maps[i], step, selection), merged if (merged = lastItem && lastItem.merge(item)) { item = merged if (i) newItems.pop() else oldItems = oldItems.slice(0, oldItems.length - 1) } newItems.push(item) selection = null if (!histOptions.preserveItems) lastItem = item } let overflow = this.eventCount - histOptions.depth if (overflow > DEPTH_OVERFLOW) oldItems = cutOffEvents(oldItems, overflow) return new Branch(oldItems.append(newItems), eventCount) } remapping(from, to) { let maps = [], mirrors = [] this.items.forEach((item, i) => { if (item.mirrorOffset != null) { let mirrorPos = i - item.mirrorOffset if (mirrorPos >= from) mirrors.push(maps.length - item.mirrorOffset, maps.length) } maps.push(item.map) }, from, to) return new Mapping(maps, mirrors) } addMaps(array) { if (this.eventCount == 0) return this return new Branch(this.items.append(array.map(map => new Item(map))), this.eventCount) } // : ([StepMap], Transform, [number]) // When the collab module receives remote changes, the history has // to know about those, so that it can adjust the steps that were // rebased on top of the remote changes, and include the position // maps for the remote changes in its array of items. rebased(rebasedTransform, rebasedCount) { if (!this.eventCount) return this let rebasedItems = [], start = this.items.length - rebasedCount, startPos = 0 if (start < 0) { startPos = -start start = 0 } let mapping = rebasedTransform.mapping let newUntil = rebasedTransform.steps.length let iRebased = startPos this.items.forEach(item => { let pos = mapping.getMirror(iRebased++) if (pos == null) return newUntil = Math.min(newUntil, pos) let map = mapping.maps[pos] if (item.step) { let step = rebasedTransform.steps[pos].invert(rebasedTransform.docs[pos]) let selection = item.selection && Selection.mapJSON(item.selection, mapping.slice(iRebased - 1, pos)) rebasedItems.push(new Item(map, step, selection)) } else { rebasedItems.push(new Item(map)) } }, start) let newMaps = [] for (let i = rebasedCount; i < newUntil; i++) newMaps.push(new Item(mapping.maps[i])) let items = this.items.slice(0, start).append(newMaps).append(rebasedItems) let branch = new Branch(items, this.eventCount) // FIXME might update event count if (branch.emptyItemCount() > max_empty_items) branch = branch.compress(this.items.length - rebasedItems.length) return branch } emptyItemCount() { let count = 0 this.items.forEach(item => { if (!item.step) count++ }) return count } // Compressing a branch means rewriting it to push the air (map-only // items) out. During collaboration, these naturally accumulate // because each remote change adds one. The `upto` argument is used // to ensure that only the items below a given level are compressed, // because `rebased` relies on a clean, untouched set of items in // order to associate old items with rebased steps. compress(upto = this.items.length) { let remap = this.remapping(0, upto), mapFrom = remap.maps.length let items = [], events = 0 this.items.forEach((item, i) => { if (i >= upto) { items.push(item) } else if (item.step) { let step = item.step.map(remap.slice(mapFrom)), map = step && step.getMap() mapFrom-- if (map) remap.appendMap(map, mapFrom) if (step) { let selection = item.selection && Selection.mapJSON(item.selection, remap.slice(mapFrom)) if (selection) events++ let newItem = new Item(map.invert(), step, selection), merged, last = items.length - 1 if (merged = items.length && items[last].merge(newItem)) items[last] = merged else items.push(newItem) } } else if (item.map) { mapFrom-- } }, this.items.length, 0) return new Branch(RopeSequence.from(items.reverse()), events) } } Branch.empty = new Branch(RopeSequence.empty, 0) function cutOffEvents(items, n) { let cutPoint items.forEach((item, i) => { if (item.selection && (--n == 0)) { cutPoint = i return false } }) return items.slice(cutPoint) } class Item { constructor(map, step, selection, mirrorOffset) { this.map = map this.step = step this.selection = selection this.mirrorOffset = mirrorOffset } merge(other) { if (this.step && other.step && !other.selection) { let step = other.step.merge(this.step) if (step) return new Item(step.getMap().invert(), step, this.selection) } } } // The value of the state field that tracks undo/redo history for that // state. Will be stored in the plugin state when the history plugin // is active. class HistoryState { constructor(done, undone, prevMap, prevTime) { this.done = done this.undone = undone this.prevMap = prevMap this.prevTime = prevTime } } exports.HistoryState = HistoryState const DEPTH_OVERFLOW = 20 // : (EditorState, Transform, Selection, Object) // Record a transformation in undo history. function recordTransform(history, selection, action, options) { let transform = action.transform if (action.historyState) { return action.historyState } else if (transform.steps.length == 0) { return history } else if (action.addToHistory !== false) { // Group transforms that occur in quick succession into one event. let newGroup = history.prevTime < (action.time || 0) - options.newGroupDelay || !isAdjacentToLastStep(transform, history.prevMap, history.done) return new HistoryState(history.done.addTransform(transform, newGroup ? selection.toJSON() : null, options), Branch.empty, transform.mapping.maps[transform.steps.length - 1], action.time) } else if (action.rebased) { // Used by the collab module to tell the history that some of its // content has been rebased. return new HistoryState(history.done.rebased(transform, action.rebased), history.undone.rebased(transform, action.rebased), history.prevMap && transform.mapping.maps[transform.steps.length - 1], history.prevTime) } else { return new HistoryState(history.done.addMaps(transform.mapping.maps), history.undone.addMaps(transform.mapping.maps), history.prevMap, history.prevTime) } } function isAdjacentToLastStep(transform, prevMap, done) { if (!prevMap) return false let firstMap = transform.mapping.maps[0], adjacent = false if (!firstMap) return true firstMap.forEach((start, end) => { done.items.forEach(item => { if (item.step) { prevMap.forEach((_start, _end, rStart, rEnd) => { if (start <= rEnd && end >= rStart) adjacent = true }) return false } else { start = item.map.invert().map(start, -1) end = item.map.invert().map(end, 1) } }, done.items.length, 0) }) return adjacent } // : (EditorState, bool, Object) → Object // Apply the latest event from one branch to the document and optionally // shift the event onto the other branch. Returns true when an event could // be shifted. function histAction(history, state, onAction, redo) { let histOptions = historyKey.get(state).options.config let pop = (redo ? history.undone : history.done).popEvent(state, histOptions.preserveItems) if (!pop) return let selectionBefore = state.selection let selection = Selection.fromJSON(pop.transform.doc, pop.selection) let added = (redo ? history.done : history.undone).addTransform(pop.transform, selectionBefore.toJSON(), histOptions) let newHist = new HistoryState(redo ? added : pop.remaining, redo ? pop.remaining : added, null, 0) onAction(pop.transform.action({selection, historyState: newHist, scrollIntoView: true, sealed: true})) } const historyKey = new PluginKey("history") // :: (?Object) → Plugin // Returns a plugin that enables the undo history for an editor. // // config::- // Supports the following configuration options: // // depth:: ?number // The amount of history events that are collected before the // oldest events are discarded. Defaults to 100. // // newGroupDelay:: number // The delay between changes after which a new group should be // started. Defaults to 500 (milliseconds). Note that when changes // aren't adjacent, a new group is always started. // // preserveItems:: ?bool // Whether to preserve the steps exactly as they came in. **Must** // be true when using the history together with the collaborative // editing plugin, to allow syncing the history when concurrent // changes come in. Defaults to false. function history(config) { config = {depth: config && config.depth || 100, preserveItems: !!(config && config.preserveItems), newGroupDelay: config && config.newGroupDelay || 500} return new Plugin({ key: historyKey, state: { init() { return new HistoryState(Branch.empty, Branch.empty, null, 0) }, applyAction(action, hist, state) { if (action.type == "transform") return recordTransform(hist, state.selection, action, config) if (action.type == "historyClose") return new HistoryState(hist.done, hist.undone, null, 0) return hist } }, config }) } exports.history = history // :: (state: EditorState, onAction: ?(action: Action)) → bool // A command function that undoes the last change, if any. function undo(state, onAction) { let hist = historyKey.getState(state) if (!hist || hist.done.eventCount == 0) return false if (onAction) histAction(hist, state, onAction, false) return true } exports.undo = undo // :: (state: EditorState, onAction: ?(action: Action)) → bool // A command function that redoes the last undone change, if any. function redo(state, onAction) { let hist = historyKey.getState(state) if (!hist || hist.undone.eventCount == 0) return false if (onAction) histAction(hist, state, onAction, true) return true } exports.redo = redo // :: (EditorState) → number // The amount of undoable events available in a given state. function undoDepth(state) { let hist = historyKey.getState(state) return hist ? hist.done.eventCount : 0 } exports.undoDepth = undoDepth // :: (EditorState) → number // The amount of redoable events available in a given editor state. function redoDepth(state) { let hist = historyKey.getState(state) return hist ? hist.undone.eventCount : 0 } exports.redoDepth = redoDepth
"use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var base_1 = require('./base'); var Response = (function (_super) { __extends(Response, _super); function Response(options) { _super.call(this, options); this.body = options.body; this.status = options.status; this.statusText = options.statusText; } Response.prototype.statusType = function () { return ~~(this.status / 100); }; Response.prototype.toJSON = function () { return { url: this.url, headers: this.headers, body: this.body, status: this.status, statusText: this.statusText }; }; return Response; }(base_1.default)); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = Response; //# sourceMappingURL=response.js.map
import React from "react"; import ReactDOM from "react-dom"; import App from "next/app"; import Head from "next/head"; import Router from "next/router"; import PageChange from "components/PageChange/PageChange.js"; import "assets/plugins/nucleo/css/nucleo.css"; import "@fortawesome/fontawesome-free/css/all.min.css"; import "assets/scss/nextjs-argon-dashboard.scss"; Router.events.on("routeChangeStart", (url) => { console.log(`Loading: ${url}`); document.body.classList.add("body-page-transition"); ReactDOM.render( <PageChange path={url} />, document.getElementById("page-transition") ); }); Router.events.on("routeChangeComplete", () => { ReactDOM.unmountComponentAtNode(document.getElementById("page-transition")); document.body.classList.remove("body-page-transition"); }); Router.events.on("routeChangeError", () => { ReactDOM.unmountComponentAtNode(document.getElementById("page-transition")); document.body.classList.remove("body-page-transition"); }); export default class MyApp extends App { componentDidMount() { let comment = document.createComment(` ========================================================= * * NextJS Argon Dashboard v1.1.0 based on Argon Dashboard React v1.1.0 ========================================================= * Product Page: https://www.creative-tim.com/product/nextjs-argon-dashboard * Copyright 2021 Creative Tim (https://www.creative-tim.com) * Licensed under MIT (https://github.com/creativetimofficial/nextjs-argon-dashboard/blob/master/LICENSE.md) * Coded by Creative Tim ========================================================= * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. `); document.insertBefore(comment, document.documentElement); } static async getInitialProps({ Component, router, ctx }) { let pageProps = {}; if (Component.getInitialProps) { pageProps = await Component.getInitialProps(ctx); } return { pageProps }; } render() { const { Component, pageProps } = this.props; const Layout = Component.layout || (({ children }) => <>{children}</>); return ( <React.Fragment> <Head> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" /> <title>Franchise POS</title> {/* <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_KEY_HERE"></script> */} </Head> <Layout> <Component {...pageProps} /> </Layout> </React.Fragment> ); } }
// All symbols with the `Diacritic` property as per Unicode v5.0.0: [ '\x5E', '\x60', '\xA8', '\xAF', '\xB4', '\xB7', '\xB8', '\u02B0', '\u02B1', '\u02B2', '\u02B3', '\u02B4', '\u02B5', '\u02B6', '\u02B7', '\u02B8', '\u02B9', '\u02BA', '\u02BB', '\u02BC', '\u02BD', '\u02BE', '\u02BF', '\u02C0', '\u02C1', '\u02C2', '\u02C3', '\u02C4', '\u02C5', '\u02C6', '\u02C7', '\u02C8', '\u02C9', '\u02CA', '\u02CB', '\u02CC', '\u02CD', '\u02CE', '\u02CF', '\u02D0', '\u02D1', '\u02D2', '\u02D3', '\u02D4', '\u02D5', '\u02D6', '\u02D7', '\u02D8', '\u02D9', '\u02DA', '\u02DB', '\u02DC', '\u02DD', '\u02DE', '\u02DF', '\u02E0', '\u02E1', '\u02E2', '\u02E3', '\u02E4', '\u02E5', '\u02E6', '\u02E7', '\u02E8', '\u02E9', '\u02EA', '\u02EB', '\u02EC', '\u02ED', '\u02EE', '\u02EF', '\u02F0', '\u02F1', '\u02F2', '\u02F3', '\u02F4', '\u02F5', '\u02F6', '\u02F7', '\u02F8', '\u02F9', '\u02FA', '\u02FB', '\u02FC', '\u02FD', '\u02FE', '\u02FF', '\u0300', '\u0301', '\u0302', '\u0303', '\u0304', '\u0305', '\u0306', '\u0307', '\u0308', '\u0309', '\u030A', '\u030B', '\u030C', '\u030D', '\u030E', '\u030F', '\u0310', '\u0311', '\u0312', '\u0313', '\u0314', '\u0315', '\u0316', '\u0317', '\u0318', '\u0319', '\u031A', '\u031B', '\u031C', '\u031D', '\u031E', '\u031F', '\u0320', '\u0321', '\u0322', '\u0323', '\u0324', '\u0325', '\u0326', '\u0327', '\u0328', '\u0329', '\u032A', '\u032B', '\u032C', '\u032D', '\u032E', '\u032F', '\u0330', '\u0331', '\u0332', '\u0333', '\u0334', '\u0335', '\u0336', '\u0337', '\u0338', '\u0339', '\u033A', '\u033B', '\u033C', '\u033D', '\u033E', '\u033F', '\u0340', '\u0341', '\u0342', '\u0343', '\u0344', '\u0345', '\u0346', '\u0347', '\u0348', '\u0349', '\u034A', '\u034B', '\u034C', '\u034D', '\u034E', '\u0350', '\u0351', '\u0352', '\u0353', '\u0354', '\u0355', '\u0356', '\u0357', '\u035D', '\u035E', '\u035F', '\u0360', '\u0361', '\u0362', '\u0374', '\u0375', '\u037A', '\u0384', '\u0385', '\u0483', '\u0484', '\u0485', '\u0486', '\u0559', '\u0591', '\u0592', '\u0593', '\u0594', '\u0595', '\u0596', '\u0597', '\u0598', '\u0599', '\u059A', '\u059B', '\u059C', '\u059D', '\u059E', '\u059F', '\u05A0', '\u05A1', '\u05A3', '\u05A4', '\u05A5', '\u05A6', '\u05A7', '\u05A8', '\u05A9', '\u05AA', '\u05AB', '\u05AC', '\u05AD', '\u05AE', '\u05AF', '\u05B0', '\u05B1', '\u05B2', '\u05B3', '\u05B4', '\u05B5', '\u05B6', '\u05B7', '\u05B8', '\u05B9', '\u05BA', '\u05BB', '\u05BC', '\u05BD', '\u05BF', '\u05C1', '\u05C2', '\u05C4', '\u064B', '\u064C', '\u064D', '\u064E', '\u064F', '\u0650', '\u0651', '\u0652', '\u0657', '\u0658', '\u06DF', '\u06E0', '\u06E5', '\u06E6', '\u06EA', '\u06EB', '\u06EC', '\u0730', '\u0731', '\u0732', '\u0733', '\u0734', '\u0735', '\u0736', '\u0737', '\u0738', '\u0739', '\u073A', '\u073B', '\u073C', '\u073D', '\u073E', '\u073F', '\u0740', '\u0741', '\u0742', '\u0743', '\u0744', '\u0745', '\u0746', '\u0747', '\u0748', '\u0749', '\u074A', '\u07A6', '\u07A7', '\u07A8', '\u07A9', '\u07AA', '\u07AB', '\u07AC', '\u07AD', '\u07AE', '\u07AF', '\u07B0', '\u07EB', '\u07EC', '\u07ED', '\u07EE', '\u07EF', '\u07F0', '\u07F1', '\u07F2', '\u07F3', '\u07F4', '\u07F5', '\u093C', '\u094D', '\u0951', '\u0952', '\u0953', '\u0954', '\u09BC', '\u09CD', '\u0A3C', '\u0A4D', '\u0ABC', '\u0ACD', '\u0B3C', '\u0B4D', '\u0BCD', '\u0C4D', '\u0CBC', '\u0CCD', '\u0D4D', '\u0DCA', '\u0E47', '\u0E48', '\u0E49', '\u0E4A', '\u0E4B', '\u0E4C', '\u0E4E', '\u0EC8', '\u0EC9', '\u0ECA', '\u0ECB', '\u0ECC', '\u0F18', '\u0F19', '\u0F35', '\u0F37', '\u0F39', '\u0F3E', '\u0F3F', '\u0F82', '\u0F83', '\u0F84', '\u0F86', '\u0F87', '\u0FC6', '\u1037', '\u1039', '\u17C9', '\u17CA', '\u17CB', '\u17CC', '\u17CD', '\u17CE', '\u17CF', '\u17D0', '\u17D1', '\u17D2', '\u17D3', '\u17DD', '\u1939', '\u193A', '\u193B', '\u1B34', '\u1B44', '\u1B6B', '\u1B6C', '\u1B6D', '\u1B6E', '\u1B6F', '\u1B70', '\u1B71', '\u1B72', '\u1B73', '\u1D2C', '\u1D2D', '\u1D2E', '\u1D2F', '\u1D30', '\u1D31', '\u1D32', '\u1D33', '\u1D34', '\u1D35', '\u1D36', '\u1D37', '\u1D38', '\u1D39', '\u1D3A', '\u1D3B', '\u1D3C', '\u1D3D', '\u1D3E', '\u1D3F', '\u1D40', '\u1D41', '\u1D42', '\u1D43', '\u1D44', '\u1D45', '\u1D46', '\u1D47', '\u1D48', '\u1D49', '\u1D4A', '\u1D4B', '\u1D4C', '\u1D4D', '\u1D4E', '\u1D4F', '\u1D50', '\u1D51', '\u1D52', '\u1D53', '\u1D54', '\u1D55', '\u1D56', '\u1D57', '\u1D58', '\u1D59', '\u1D5A', '\u1D5B', '\u1D5C', '\u1D5D', '\u1D5E', '\u1D5F', '\u1D60', '\u1D61', '\u1D62', '\u1D63', '\u1D64', '\u1D65', '\u1D66', '\u1D67', '\u1D68', '\u1D69', '\u1D6A', '\u1DC4', '\u1DC5', '\u1DC6', '\u1DC7', '\u1DC8', '\u1DC9', '\u1DCA', '\u1DFE', '\u1DFF', '\u1FBD', '\u1FBF', '\u1FC0', '\u1FC1', '\u1FCD', '\u1FCE', '\u1FCF', '\u1FDD', '\u1FDE', '\u1FDF', '\u1FED', '\u1FEE', '\u1FEF', '\u1FFD', '\u1FFE', '\u302A', '\u302B', '\u302C', '\u302D', '\u302E', '\u302F', '\u3099', '\u309A', '\u309B', '\u309C', '\u30FC', '\uA717', '\uA718', '\uA719', '\uA71A', '\uA720', '\uA721', '\uFB1E', '\uFE20', '\uFE21', '\uFE22', '\uFE23', '\uFF3E', '\uFF40', '\uFF70', '\uFF9E', '\uFF9F', '\uFFE3', '\uD834\uDD67', '\uD834\uDD68', '\uD834\uDD69', '\uD834\uDD6D', '\uD834\uDD6E', '\uD834\uDD6F', '\uD834\uDD70', '\uD834\uDD71', '\uD834\uDD72', '\uD834\uDD7B', '\uD834\uDD7C', '\uD834\uDD7D', '\uD834\uDD7E', '\uD834\uDD7F', '\uD834\uDD80', '\uD834\uDD81', '\uD834\uDD82', '\uD834\uDD85', '\uD834\uDD86', '\uD834\uDD87', '\uD834\uDD88', '\uD834\uDD89', '\uD834\uDD8A', '\uD834\uDD8B', '\uD834\uDDAA', '\uD834\uDDAB', '\uD834\uDDAC', '\uD834\uDDAD' ];
test("IFrame", function() { var iframe = document.createElement("iframe"); assert( !!iframe, "iframe supported" ); }); // test("IFrame Seamless", function() { // var iframe = document.createElement("iframe"); // assert( "seamless" in iframe ); // }); test("IFrame Sandbox", function() { var iframe = document.createElement("iframe"); assert( "sandbox" in iframe, "Sandbox iframe supported" ); }); asyncTest("IFrame Sandbox Sanity", function( async ) { var regular = document.getElementById("regular"), sandbox = document.getElementById("sandbox"), iframe = document.createElement("iframe"); if ( !("sandbox" in iframe) ) { assert( false, "Sandbox iframe not support, skipping tests" ); async.done(); } else { assert( !!regular.contentWindow, "regular iframe is accessible" ); assert( !sandbox.contentWindow, "sandbox iframe is blocked" ); async.done(); } }); asyncTest("IFrame Sandbox allow-scripts", function( async ) { var fixture = document.getElementById("iframe"), iframe = document.createElement("iframe"), isDead = false; function allowScripts( event ) { if ( !isDead && event.data.type === "allow-scripts" ) { async.step(function() { assert( event.data.result === "?allow-scripts", "allowScripts allowed JS to execute in iframe" ); H.off( window, "message", allowScripts ); isDead = true; async.done(); }); } } if ( !("sandbox" in iframe) ) { assert( false, "Sandbox iframe not support, skipping tests" ); async.done(); } else { H.on( window, "message", allowScripts ); iframe.sandbox = "allow-scripts"; iframe.src = "/tests/iframe/allow-scripts.html?allow-scripts"; fixture.appendChild( iframe ); // Bailout setTimeout(function() { if ( !isDead ) { async.step(function() { assert( false, "allowScripts failed" ); H.off( window, "message", allowScripts ); isDead = true; async.done(); }); } }, 1000); } }); asyncTest("IFrame Sandbox allow-scripts allow-forms", function( async ) { var fixture = document.getElementById("iframe"), iframe = document.createElement("iframe"), isDead = false; function allowScriptsForms( event ) { async.step(function() { if ( !isDead && event.data.type === "allow-scripts-forms" ) { assert( true, "allowScripts allowed JS to execute in iframe and submit a form" ); H.off( window, "message", allowScriptsForms ); isDead = true; async.done(); } }); } if ( !("sandbox" in iframe) ) { assert( false, "Sandbox iframe not support, skipping tests" ); async.done(); } else { H.on( window, "message", allowScriptsForms ); iframe.sandbox = "allow-scripts allow-forms"; iframe.src = "/tests/iframe/allow-scripts-forms.html?allow-scripts-forms"; fixture.appendChild( iframe ); // Bailout setTimeout(function() { if ( !isDead ) { async.step(function() { assert( false, "allowScriptsForms failed" ); H.off( window, "message", allowScriptsForms ); isDead = true; async.done(); }); } }, 1000); } }); // allow-forms, allow-same-origin, allow-scripts, and allow-top-navigation // // allow-same-origin keyword allows the content to be // treated as being from the same origin instead of // forcing it into a unique origin, // // allow-top-navigation keyword allows the content to // navigate its top-level browsing context. // // allow-forms and allow-scripts keywords re-enable // forms and scripts respectively // (though scripts are still prevented from creating popups).
export * from './urls.constants'; export * from './form.constants';
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.random = random; /** * @param {String|Number|null} value * @returns {Number} */ function customParseInt(value) { var intVal = parseInt(value, 10); return isNaN(intVal) ? 0 : intVal; } exports.parseInt = customParseInt; /** * @param {String|Number|null} value * @returns {Number} */ function customParseFloat(value) { var floatVal = parseFloat(value); return isNaN(floatVal) ? 0 : floatVal; } exports.parseFloat = customParseFloat; /** * @param {Number} min * @param {Number} max * @returns {Number} */ function random(min, max) { return Math.floor(Math.random() * (max - min + 1) + min); }
/* * Copyright (c) AXA Group Operations Spain S.A. * * 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. */ const { tokenizer } = require('../examples/03-tokenization-normalized'); // const { TokenizerUk } = require('@nlpjs/lang-uk'); const input = "Це ще не токенізовано"; test(input + ' => [ \'це\', \'ще\', \'не\', \'токенізовано\' ]', () => { expect(tokenizer.tokenize(input, true)).toEqual([ 'це', 'ще', 'не', 'токенізовано' ]) })
// |jit-test| error:TypeError // Binary: cache/js-dbg-64-ff51ddfdf5d1-linux // Flags: // var a = []; for (var i = 0; i < 200; ++i) a.push({}); var p = Proxy.create({fix: function() { return a; }}); Object.preventExtensions(p);
import FaceTime from "../components/apps/FaceTime"; import Terminal from "../components/apps/Terminal"; import Safari from "../components/apps/Safari"; import Bear from "../components/apps/Bear"; import VSCode from "../components/apps/VSCode"; const apps = [ { id: "launchpad", title: "Launchpad", desktop: false, img: "img/icons/launchpad.png" }, { id: "akbar", title: "Notes", desktop: true, show: true, width: 860, height: 500, img: "img/icons/bear.png", content: <Bear /> }, { id: "safari", title: "Safari", desktop: true, show: false, width: 1024, minWidth: 375, minHeight: 200, img: "img/icons/safari.png", content: <Safari /> }, { id: "vscode", title: "VSCode", desktop: true, show: false, img: "img/icons/vscode.png", content: <VSCode /> }, { id: "facetime", title: "FaceTime", desktop: true, show: false, img: "img/icons/facetime.png", height: 530, content: <FaceTime /> }, { id: "terminal", title: "Terminal", desktop: true, show: false, img: "img/icons/terminal.png", content: <Terminal /> }, { id: "email", title: "Mail", desktop: false, img: "img/icons/mail.png", link: "mailto:umair@tesla.com.ai" }, { id: "github", title: "Github", desktop: false, img: "img/icons/github.png", link: "https://github.com/uakbr/macos-portfolio" } ]; export default apps;
/** * * @title 垂直排列的按钮组 * @description 通过`vertical`属性设置按钮组垂直排列 * */ import React, { Component } from 'react'; import ButtonGroup from '../../src'; import Button from 'bee-button'; import Icon from 'bee-icon'; class Demo2 extends Component { render () { return ( <ButtonGroup vertical> <Button colors="primary"><Icon type='uf-navmenu' /></Button> <Button colors="info"><Icon type='uf-file' /></Button> <Button colors="warning"><Icon type='uf-del' /></Button> </ButtonGroup> ) } } export default Demo2;
import "../App.css"; import React, { useState, useEffect } from "react"; import Nav from "./Nav.js"; import projectData from "../projects.json"; function Projects() { return ( <div className="App"> <Nav /> <div style={{ color: "white", paddingTop: "50px" }}> <h1>My Projects </h1> <div class="container"> {projectData.map((project) => ( <div class="row mt-4" style={{ textAlign: "left" }}> <div class="col-lg-4 col-12-sm"> <a target="_blank" href={project.liveUrl} className="project-link" > <img // style={{ height: "250px", width: "400px" }} className="project-img" alt="project" src={project.imgSrc} onMouseOver={(e) => { e.currentTarget.src = project.gifSrc; e.currentTarget.classList.add("fade-in-image"); }} onMouseOut={(e) => { e.currentTarget.src = project.imgSrc; e.currentTarget.classList.remove("fade-in-image"); }} ></img> </a> </div> <div class="col-lg-8 col-12-sm"> <h4>{project.title}</h4> <h6>{project.meta}</h6> <p dangerouslySetInnerHTML={{ __html: project.description }} /> <p> <a href={project.liveUrl}>Github</a> <br /> <a href={project.liveUrlApp}>Live App</a> </p> </div> </div> ))} </div> </div> </div> ); } export default Projects;
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><path d="M12 3c-.55 0-1 .45-1 1v8c0 .55.45 1 1 1s1-.45 1-1V4c0-.55-.45-1-1-1zm5.14 2.86c-.39.39-.38 1-.01 1.39 1.13 1.2 1.83 2.8 1.87 4.57.09 3.83-3.08 7.13-6.91 7.17C8.18 19.05 5 15.9 5 12c0-1.84.71-3.51 1.87-4.76.37-.39.37-1-.01-1.38-.4-.4-1.05-.39-1.43.02C3.98 7.42 3.07 9.47 3 11.74c-.14 4.88 3.83 9.1 8.71 9.25 5.1.16 9.29-3.93 9.29-9 0-2.37-.92-4.51-2.42-6.11-.38-.41-1.04-.42-1.44-.02z" /></React.Fragment> , 'PowerSettingsNewRounded');
let data = { "body": "<path d=\"M6.5 2.27L20 10.14L6.5 18l-1-1.73l10.53-6.13L5.5 4l1-1.73M20 20v2H5v-2h15z\" fill=\"currentColor\"/>", "width": 24, "height": 24 }; export default data;
const utils = require('../../../utils'); /** * TODO: descricao * */ module.exports = class MegaSenaInterpreter { constructor() {} static interpret(user, questionPhrase, mentions) { return questionPhrase.match(/(mega ?sena|loteria)/i); } static get priority() { return 100 }; static phrases(user, questionPhrase, mentions) { const today = new Date(); const seed = today.getDate() + today.getMonth() + today.getFullYear(); let numeros = utils.shuffle([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], seed); numeros = numeros.splice(0, 6).join(' '); return [numeros]; } };
import { createContext, useContext } from 'react' import { makeAutoObservable } from 'mobx' import { find, compact, isEqual, isNull, isNil, isUndefined, has, some, chunk, get, uniq, } from 'lodash' import toast from 'react-hot-toast' import { createClient } from '@supabase/supabase-js' import { STORAGE_VIEWS, STORAGE_ROW_TYPES, STORAGE_ROW_STATUS, STORAGE_SORT_BY, } from 'components/to-be-cleaned/Storage/Storage.constants.ts' import { timeout, copyToClipboard } from 'lib/helpers' /** * This is a preferred method rather than React Context and useStorageExplorerStore(). * If we can switch to this method, we can remove the implementation below, and we don't need compose() within the react components */ let store = null export function useStorageStore() { if (store === null) store = new StorageExplorerStore(null) return store } /** * Deprecated - it's preferable to use the useStorageStore() function above */ export const StorageExplorerContext = createContext(null) export const useStorageExplorerStore = () => { return useContext(StorageExplorerContext) } const LIMIT = 100000 const OFFSET = 0 const DEFAULT_EXPIRY = 10 * 365 * 24 * 60 * 60 // in seconds, default to 1 year const PREVIEW_SIZE_LIMIT = 10000000 // 10MB const BATCH_SIZE = 100 const EMPTY_FOLDER_PLACEHOLDER_FILE_NAME = '.emptyFolderPlaceholder' class StorageExplorerStore { projectRef = '' loaded = false view = STORAGE_VIEWS.COLUMNS sortBy = STORAGE_SORT_BY.NAME buckets = [] selectedBucket = {} selectedBucketToEdit = {} columns = [] openedFolders = [] selectedItems = [] selectedItemsToDelete = [] selectedItemsToMove = [] selectedFilePreview = {} DEFAULT_OPTIONS = { limit: LIMIT, offset: OFFSET, sortBy: { column: this.sortBy, order: 'asc' } } /* Supabase client */ supabaseClient = null /* FE to toggle page level modals */ showCreateBucketModal = false showDeleteBucketModal = false showToggleBucketPublicModal = false /* FE Cacheing for file previews */ filePreviewCache = [] /* For file uploads, from 0 to 1 */ uploadProgress = 0 /* Controllers to abort API calls */ abortController = null constructor(projectRef) { makeAutoObservable(this, { supabaseClient: false }) this.projectRef = projectRef this.abortController = new AbortController() } initStore(projectRef, url, serviceKey) { this.projectRef = projectRef this.initializeSupabaseClient(serviceKey, url) } /* Methods which are commonly used + For better readability */ initializeSupabaseClient = (serviceKey, serviceEndpoint) => { this.supabaseClient = createClient(`https://${serviceEndpoint}`, serviceKey, { localStorage: { getItem: (key) => { return undefined }, setItem: (key, value) => {}, removeItem: (key) => {}, }, }) } updateFileInPreviewCache = (fileCache) => { const updatedFilePreviewCache = this.filePreviewCache.map((file) => { if (file.id === fileCache.id) return fileCache return file }) this.filePreviewCache = updatedFilePreviewCache } addFileToPreviewCache = (fileCache) => { const updatedFilePreviewCache = this.filePreviewCache.concat([fileCache]) this.filePreviewCache = updatedFilePreviewCache } clearFilePreviewCache = () => { this.filePreviewCache = [] } getLocalStorageKey = () => { return `supabase-storage-${this.projectRef}` } getLatestColumnIndex = () => { return this.columns.length - 1 } getCurrentlySelectedBucket = () => { return this.columns.length > 1 ? this.columns[1] : null } // Probably refactor this to ignore bucket by default getPathAlongOpenedFolders = (includeBucket = true) => { if (includeBucket) { return this.openedFolders.length > 0 ? `${this.selectedBucket.name}/${this.openedFolders.map((folder) => folder.name).join('/')}` : this.selectedBucket.name } return this.openedFolders.map((folder) => folder.name).join('/') } abortApiCalls = () => { this.abortController.abort() this.abortController = new AbortController() } get currentBucketName() { return this.selectedBucket.name } /* UI specific methods */ setLoaded = (val) => { this.loaded = val } openCreateBucketModal = () => { this.showCreateBucketModal = true } closeCreateBucketModal = () => { this.showCreateBucketModal = false } openDeleteBucketModal = (bucket) => { this.selectedBucketToEdit = bucket this.showDeleteBucketModal = true } closeDeleteBucketModal = () => { this.showDeleteBucketModal = false } openToggleBucketPublicModal = (bucket) => { this.selectedBucketToEdit = bucket this.showToggleBucketPublicModal = true } closeToggleBucketPublicModal = () => { this.showToggleBucketPublicModal = false } setSelectedBucket = (bucket) => { this.selectedBucket = bucket this.clearOpenedFolders() this.closeFilePreview() this.clearSelectedItems() } setView = (view) => { this.view = view this.closeFilePreview() this.updateExplorerPreferences() } setSortBy = async (sortBy) => { this.sortBy = sortBy this.closeFilePreview() this.updateExplorerPreferences() await this.refetchAllOpenedFolders() } clearColumns = () => { this.columns = [] } pushColumnAtIndex = (column, index) => { this.columns = this.columns.slice(0, index + 1).concat([column]) } popColumn = () => { this.abortApiCalls() this.columns = this.columns.slice(0, this.getLatestColumnIndex()) } popColumnAtIndex = (index) => { this.columns = this.columns.slice(0, index + 1) } pushOpenedFolderAtIndex = (folder, index) => { this.openedFolders = this.openedFolders.slice(0, index).concat(folder) } popOpenedFolders = () => { this.openedFolders = this.openedFolders.slice(0, this.openedFolders.length - 1) } popOpenedFoldersAtIndex = (index) => { this.openedFolders = this.openedFolders.slice(0, index + 1) } clearOpenedFolders = () => { this.openedFolders = [] } setSelectedItems = (items) => { this.selectedItems = items } clearSelectedItems = () => { this.selectedItems = [] } setSelectedItemsToDelete = (items) => { this.selectedItemsToDelete = items } clearSelectedItemsToDelete = () => { this.selectedItemsToDelete = [] } setSelectedItemsToMove = (items) => { this.selectedItemsToMove = items } clearSelectedItemsToMove = () => { this.selectedItemsToMove = [] } addNewFolderPlaceholder = (columnIndex) => { const folderName = 'Untitled folder' const folderType = STORAGE_ROW_TYPES.FOLDER const columnIdx = columnIndex === -1 ? this.getLatestColumnIndex() : columnIndex this.addTempRow(folderType, folderName, STORAGE_ROW_STATUS.EDITING, columnIdx) } addNewFolder = async (folderName, columnIndex) => { const autofix = false const formattedName = this.sanitizeNameForDuplicateInColumn(folderName, autofix, columnIndex) if (isNull(formattedName)) { return } if (formattedName.length === 0) { return this.removeTempRows(columnIndex) } this.updateFolderAfterEdit(formattedName, columnIndex) const emptyPlaceholderFile = `${formattedName}/${EMPTY_FOLDER_PLACEHOLDER_FILE_NAME}` const pathToFolder = this.openedFolders .slice(0, columnIndex) .map((folder) => folder.name) .join('/') const formattedPathToEmptyPlaceholderFile = pathToFolder.length > 0 ? `${pathToFolder}/${emptyPlaceholderFile}` : emptyPlaceholderFile await this.supabaseClient.storage .from(this.selectedBucket.name) .upload(formattedPathToEmptyPlaceholderFile, new File([], EMPTY_FOLDER_PLACEHOLDER_FILE_NAME)) if (pathToFolder.length > 0) { await this.supabaseClient.storage .from(this.selectedBucket.name) .remove([`${pathToFolder}/${EMPTY_FOLDER_PLACEHOLDER_FILE_NAME}`]) } } setFilePreview = async (file) => { const size = file.metadata?.size const mimeType = file.metadata?.mimetype if (mimeType && size && this.selectedFilePreview.id !== file.id) { // Skip fetching of file preview if file is too big if (size > PREVIEW_SIZE_LIMIT) { this.selectedFilePreview = { ...file, previewUrl: 'skipped' } return } // Either retrieve file preview from FE cache or retrieve signed url this.selectedFilePreview = { ...file, previewUrl: 'loading' } const cachedPreview = find(this.filePreviewCache, { id: file.id }) const fetchedAt = get(cachedPreview, ['fetchedAt'], null) const expiresIn = get(cachedPreview, ['expiresIn'], null) const existsInCache = !isNull(fetchedAt) && !isNull(expiresIn) const isExpired = existsInCache ? fetchedAt + expiresIn * 1000 < Date.now() : true if (!isExpired) { this.selectedFilePreview = { ...file, previewUrl: cachedPreview.url } } else { const previewUrl = await this.fetchFilePreview(file.name) const formattedPreviewUrl = this.selectedBucket.public ? `${previewUrl}?t=${new Date().toISOString()}` : previewUrl this.selectedFilePreview = { ...file, previewUrl: formattedPreviewUrl } const fileCache = { id: file.id, url: previewUrl, expiresIn: DEFAULT_EXPIRY, fetchedAt: Date.now(), } if (!existsInCache) { this.addFileToPreviewCache(fileCache) } else { this.updateFileInPreviewCache(fileCache) } } } else { this.selectedFilePreview = { ...file, previewUrl: null } } } closeFilePreview = () => { this.selectedFilePreview = {} } copyFileURLToClipboard = async (file) => { const filePreview = find(this.filePreviewCache, { id: file.id }) if (filePreview) { // Already generated signed URL copyToClipboard(filePreview.url, () => { toast(`Copied URL for ${file.name} to clipboard.`) }) } else { // Need to generate signed URL, and might as well save it to cache as well const signedUrl = await this.fetchFilePreview(file.name) copyToClipboard(signedUrl, () => { toast(`Copied URL for ${file.name} to clipboard.`) }) const fileCache = { id: file.id, url: signedUrl, expiresIn: DEFAULT_EXPIRY, fetchedAt: Date.now(), } this.addFileToPreviewCache(fileCache) } } /* Methods that involve the storage client library */ /* Bucket CRUD */ createBucket = async (bucketName, isPublic = false) => { if (isNil(this.supabaseClient)) { return toast.error('Failed to initialize supabase client, try refreshing your browser.') } const { error } = await this.supabaseClient.storage.createBucket(bucketName, { public: isPublic, }) if (error) { toast.error(error.message) return this.closeCreateBucketModal() } await this.fetchBuckets() this.closeCreateBucketModal() } openBucket = async (bucket) => { const { id, name } = bucket const columnIndex = -1 if (!isEqual(this.selectedBucket, bucket)) { this.setSelectedBucket(bucket) await this.fetchFolderContents(id, name, columnIndex) } } fetchBuckets = async () => { const { data: buckets, error } = await this.supabaseClient.storage.listBuckets() if (error) return toast(error.message) const formattedBuckets = buckets.map((bucket) => { return { ...bucket, type: STORAGE_ROW_TYPES.BUCKET, status: STORAGE_ROW_STATUS.READY } }) this.buckets = formattedBuckets return formattedBuckets } deleteBucket = async (bucket) => { // Deleting a bucket requires the bucket to be empty first // hence delete bucket and empty bucket are coupled tightly here const { id, name: bucketName } = bucket const { error: emptyBucketError } = await this.supabaseClient.storage.emptyBucket(id) if (emptyBucketError) { toast(emptyBucketError.message) return false } const { error: deleteBucketError } = await this.supabaseClient.storage.deleteBucket(id) if (deleteBucketError) { toast(deleteBucketError.message) return false } await this.fetchBuckets() if (bucketName === this.selectedBucket.name) { this.setSelectedBucket({}) this.clearColumns() this.clearOpenedFolders() } this.clearSelectedItemsToDelete() this.closeDeleteBucketModal() return true } toggleBucketPublic = async (bucket) => { const { name: bucketName } = bucket const { data, error } = await this.supabaseClient.storage.updateBucket(bucketName, { public: !bucket.public, }) if (error) { toast(error.message) return this.closeToggleBucketPublicModal() } await this.fetchBuckets() this.clearFilePreviewCache() this.closeToggleBucketPublicModal() await this.openBucket({ ...bucket, public: !bucket.public }) } /* Files CRUD */ getFile = async (fileEntry) => { try { return await new Promise((resolve, reject) => fileEntry.file(resolve, reject)) } catch (err) { console.error('getFile error:', err) return undefined } } // https://stackoverflow.com/a/53058574 getFilesDataTransferItems = async (items) => { const toastId = toast.loading('Retrieving items to upload...') const files = [] const queue = [] for (const item of items) { queue.push(item.webkitGetAsEntry()) } while (queue.length > 0) { const entry = queue.shift() || {} if (entry.isFile) { const file = await this.getFile(entry) if (!isUndefined(file)) { file.path = entry.fullPath.slice(1) files.push(file) } } else if (entry.isDirectory) { queue.push(...(await this.readAllDirectoryEntries(entry.createReader()))) } } toast.dismiss(toastId) return files } // Get all the entries (files or sub-directories) in a directory // by calling readEntries until it returns empty array readAllDirectoryEntries = async (directoryReader) => { const entries = [] let readEntries = await this.readEntriesPromise(directoryReader) while (readEntries.length > 0) { entries.push(...readEntries) readEntries = await this.readEntriesPromise(directoryReader) } return entries } // Wrap readEntries in a promise to make working with readEntries easier // readEntries will return only some of the entries in a directory // e.g. Chrome returns at most 100 entries at a time readEntriesPromise = async (directoryReader) => { try { return await new Promise((resolve, reject) => { directoryReader.readEntries(resolve, reject) }) } catch (err) { console.error('readEntriesPromise error:', err) } } uploadFiles = async (files, columnIndex, isDrop = false) => { const t1 = new Date() const autofix = true // We filter out any folders which are just '#' until we can properly encode such characters in the URL const filesToUpload = isDrop ? (await this.getFilesDataTransferItems(files)).filter((file) => !file.path.includes('#/')) : Array.from(files) const derivedColumnIndex = columnIndex === -1 ? this.getLatestColumnIndex() : columnIndex // If we're uploading a folder which name already exists in the same folder that we're uploading to // We sanitize the folder name and let all file uploads through. (This is only via drag drop) const topLevelFolders = get(this.columns, [derivedColumnIndex, 'items'], []) .filter((item) => !item.id) .map((item) => item.name) const formattedFilesToUpload = filesToUpload.map((file) => { // If the files are from clicking "Upload button", just take them as they are since users cannot // upload folders from clicking that button, only via drag drop if (!file.path) return file const path = file.path.split('/') const topLevelFolder = path.length > 1 ? path[0] : null if (topLevelFolders.includes(topLevelFolder)) { const newTopLevelFolder = this.sanitizeNameForDuplicateInColumn( topLevelFolder, autofix, columnIndex ) path[0] = newTopLevelFolder file.path = path.join('/') } return file }) const uploadedTopLevelFolders = [] this.uploadProgress = 0 let numberOfFilesToUpload = formattedFilesToUpload.length let numberOfFilesUploadedSuccess = 0 let numberOfFilesUploadedFail = 0 const pathToFile = this.openedFolders .slice(0, derivedColumnIndex) .map((folder) => folder.name) .join('/') const toastId = toast.loading( `Uploading ${formattedFilesToUpload.length} file${ formattedFilesToUpload.length > 1 ? 's' : '' }...` ) // Upload files in batches const promises = formattedFilesToUpload.map((file) => { const fileOptions = { cacheControl: 3600 } const metadata = { mimetype: file.type, size: file.size } const isWithinFolder = get(file, ['path'], '').split('/').length > 1 const fileName = !isWithinFolder ? this.sanitizeNameForDuplicateInColumn(file.name, autofix) : file.name const formattedFileName = has(file, ['path']) && isWithinFolder ? file.path : fileName const formattedPathToFile = pathToFile.length > 0 ? `${pathToFile}/${formattedFileName}` : formattedFileName if (isWithinFolder) { const topLevelFolder = file.path.split('/')[0] if (!uploadedTopLevelFolders.includes(topLevelFolder)) { this.addTempRow( STORAGE_ROW_TYPES.FOLDER, topLevelFolder, STORAGE_ROW_STATUS.LOADING, derivedColumnIndex, metadata ) uploadedTopLevelFolders.push(topLevelFolder) } } else { this.addTempRow( STORAGE_ROW_TYPES.FILE, fileName, STORAGE_ROW_STATUS.LOADING, derivedColumnIndex, metadata ) } return () => { return Promise.race([ new Promise(async (resolve) => { const { error } = await this.supabaseClient.storage .from(this.selectedBucket.name) .upload(formattedPathToFile, file, fileOptions) this.uploadProgress = this.uploadProgress + 1 / formattedFilesToUpload.length if (error) { numberOfFilesUploadedFail += 1 toast.error(`Failed to upload ${file.name}: ${error.message}`) resolve() } else { numberOfFilesUploadedSuccess += 1 resolve() } }), timeout(30000), ]) } }) // For file uploads specifically, we have to lower the batch size for now as the client side // is just unable to handle such volumes of transfer // [Joshen] I realised this can be simplified with just a vanilla for loop, no need for reduce // Just take note, but if it's working fine, then it's okay const batchedPromises = chunk(promises, 10) try { await batchedPromises.reduce(async (previousPromise, nextBatch) => { await previousPromise await Promise.allSettled(nextBatch.map((batch) => batch())) toast.loading( `Uploading ${formattedFilesToUpload.length} file${ formattedFilesToUpload.length > 1 ? 's' : '' }... (${(this.uploadProgress * 100).toFixed(2)}%)`, { id: toastId } ) }, Promise.resolve()) if (numberOfFilesUploadedSuccess > 0) { await this.supabaseClient.storage .from(this.selectedBucket.name) .remove([`${pathToFile}/${EMPTY_FOLDER_PLACEHOLDER_FILE_NAME}`]) } await this.refetchAllOpenedFolders() if (numberOfFilesToUpload === 0) { toast.dismiss(toastId) } else if (numberOfFilesUploadedFail === numberOfFilesToUpload) { toast.error( `Failed to upload ${numberOfFilesToUpload} file${numberOfFilesToUpload > 1 ? 's' : ''}!`, { id: toastId } ) } else if (numberOfFilesUploadedSuccess === numberOfFilesToUpload) { toast.success( `Successfully uploaded ${numberOfFilesToUpload} file${ numberOfFilesToUpload > 1 ? 's' : '' }!`, { id: toastId } ) } else { toast.success( `Successfully uploaded ${numberOfFilesUploadedSuccess} out of ${numberOfFilesToUpload} file${ numberOfFilesToUpload > 1 ? 's' : '' }!`, { id: toastId } ) } } catch (e) { console.error(e) toast.error(`Failed to upload files`) } const t2 = new Date() console.log( `Total time taken for ${formattedFilesToUpload.length} files: ${(t2 - t1) / 1000} seconds` ) } moveFiles = async (newPathToFile) => { const newPaths = compact(newPathToFile.split('/')) const formattedNewPathToFile = newPaths.join('/') let numberOfFilesMovedFail = 0 this.clearSelectedItems() await Promise.all( this.selectedItemsToMove.map(async (item) => { const pathToFile = this.openedFolders .slice(0, item.columnIndex) .map((folder) => folder.name) .join('/') const fromPath = pathToFile.length > 0 ? `${pathToFile}/${item.name}` : item.name const toPath = newPathToFile.length > 0 ? `${formattedNewPathToFile}/${item.name}` : item.name const { error } = await this.supabaseClient.storage .from(this.selectedBucket.name) .move(fromPath, toPath) if (error) { numberOfFilesMovedFail += 1 toast.error(error.message) } }) ) if (numberOfFilesMovedFail === this.selectedItemsToMove.length) { toast.error(`Failed to move files`) } else { toast.success( `Successfully moved ${ this.selectedItemsToMove.length - numberOfFilesMovedFail } to ${formattedNewPathToFile}` ) } // Clear file preview cache if moved files exist in cache const idsOfItemsToMove = this.selectedItemsToMove.map((item) => item.id) const updatedFilePreviewCache = this.filePreviewCache.filter( (file) => !idsOfItemsToMove.includes(file.id) ) this.filePreviewCache = updatedFilePreviewCache await this.refetchAllOpenedFolders() this.clearSelectedItemsToMove() } fetchFilePreview = async (fileName) => { const includeBucket = false const pathToFile = this.getPathAlongOpenedFolders(includeBucket) const formattedPathToFile = pathToFile.length > 0 ? `${pathToFile}/${fileName}` : fileName if (this.selectedBucket.public) { const { data, error } = await this.supabaseClient.storage .from(this.selectedBucket.name) .getPublicUrl(formattedPathToFile) if (!error) { return data.publicURL } } const { data, error } = await this.supabaseClient.storage .from(this.selectedBucket.name) .createSignedUrl(formattedPathToFile, DEFAULT_EXPIRY) if (!error) { return data.signedURL } return null } deleteFiles = async (files, isDeleteFolder = false) => { this.closeFilePreview() // If every file has the 'prefix' property, then just construct the prefix // directly (from delete folder). Otherwise go by the opened folders. const prefixes = !some(files, 'prefix') ? files.map((file) => { const { name, columnIndex } = file const pathToFile = this.openedFolders .slice(0, columnIndex) .map((folder) => folder.name) .join('/') this.updateRowStatus(name, STORAGE_ROW_STATUS.LOADING, columnIndex) return pathToFile.length > 0 ? `${pathToFile}/${name}` : name }) : files.map((file) => `${file.prefix}/${file.name}`) this.clearSelectedItems() const batches = chunk(prefixes, BATCH_SIZE) await Promise.all( batches.map( async (batchedPrefixes) => await this.supabaseClient.storage.from(this.selectedBucket.name).remove(batchedPrefixes) ) ) // Clear file preview cache if deleted files exist in cache const idsOfFilesDeleted = files.map((file) => file.id) const updatedFilePreviewCache = this.filePreviewCache.filter( (file) => !idsOfFilesDeleted.includes(file.id) ) this.filePreviewCache = updatedFilePreviewCache if (!isDeleteFolder) { // If parent folders are empty, reinstate .emptyFolderPlaceholder to persist them const parentFolderPrefixes = uniq( prefixes.map((prefix) => { const segments = prefix.split('/') return segments.slice(0, segments.length - 1).join('/') }) ) await Promise.all( parentFolderPrefixes.map((prefix) => this.validateParentFolderEmpty(prefix)) ) toast.success(`Successfully deleted ${prefixes.length} file(s)`) await this.refetchAllOpenedFolders() this.clearSelectedItemsToDelete() } } downloadSelectedFiles = async () => { const showIndividualToast = false const toastId = toast(`Retrieving ${this.selectedItems.length} files...`, { autoClose: false, hideProgressBar: true, }) const res = await Promise.all( this.selectedItems.map(async (item) => await this.downloadFile(item, showIndividualToast)) ) const numberOfSuccessfullyDownloadedFiles = res.filter((x) => x === true).length toast.success(`Downloaded ${numberOfSuccessfullyDownloadedFiles} files`, { id: toastId, }) } downloadFile = async (file, showToast = true) => { let toastId const fileName = file.name const fileMimeType = get(file, ['metadata', 'mimetype'], null) if (showToast) { toastId = toast.loading(`Retrieving ${fileName}...`, { autoClose: false, }) } const pathToFile = this.openedFolders .slice(0, file.columnIndex) .map((folder) => folder.name) .join('/') const formattedPathToFile = pathToFile.length > 0 ? `${pathToFile}/${fileName}` : fileName const { data, error } = await this.supabaseClient.storage .from(this.selectedBucket.name) .download(formattedPathToFile) if (!error) { const blob = data const newBlob = new Blob([blob], { type: fileMimeType }) const blobUrl = window.URL.createObjectURL(newBlob) const link = document.createElement('a') link.href = blobUrl link.setAttribute('download', `${fileName}`) document.body.appendChild(link) link.click() link.parentNode.removeChild(link) window.URL.revokeObjectURL(blob) if (toastId) { toast.success(`Downloading ${fileName}`, { id: toastId, }) } return true } else { console.error('Failed to download:', fileName) if (toastId) { toast.error(`Failed to download ${fileName}`, { id: toastId, }) } return false } } renameFile = async (file, newName, columnIndex) => { const originalName = file.name if (originalName === newName) { this.updateRowStatus(originalName, STORAGE_ROW_STATUS.READY, columnIndex) } else { this.updateRowStatus(originalName, STORAGE_ROW_STATUS.LOADING, columnIndex, newName) const includeBucket = false const pathToFile = this.getPathAlongOpenedFolders(includeBucket) const fromPath = pathToFile.length > 0 ? `${pathToFile}/${originalName}` : originalName const toPath = pathToFile.length > 0 ? `${pathToFile}/${newName}` : newName const { error } = await this.supabaseClient.storage .from(this.selectedBucket.name) .move(fromPath, toPath) if (error) { toast.error(error.message) } await this.refetchAllOpenedFolders() // Clear file preview cache if the renamed file exists in the cache const updatedFilePreviewCache = this.filePreviewCache.filter( (fileCache) => fileCache.id !== file.id ) this.filePreviewCache = updatedFilePreviewCache } } /* Folders CRUD */ fetchFolderContents = async (folderId, folderName, index, showLoading = true) => { this.abortApiCalls() if (showLoading) { this.updateRowStatus(folderName, STORAGE_ROW_STATUS.LOADING, index) this.pushColumnAtIndex( { id: folderId, name: folderName, status: STORAGE_ROW_STATUS.LOADING, items: [] }, index ) } const prefix = this.openedFolders.map((folder) => folder.name).join('/') const options = { limit: LIMIT, offset: OFFSET, sortBy: { column: this.sortBy, order: 'asc' } } const parameters = { signal: this.abortController.signal } const { data: items, error } = await this.supabaseClient.storage .from(this.selectedBucket.name) .list(prefix, options, parameters) if (showLoading) { this.updateRowStatus(folderName, STORAGE_ROW_STATUS.READY, index) } if (!error) { const formattedItems = this.formatFolderItems(items) this.pushColumnAtIndex( { id: folderId || folderName, name: folderName, items: formattedItems }, index ) } } refetchAllOpenedFolders = async () => { const paths = this.openedFolders.map((folder) => folder.name) await this.fetchFoldersByPath(paths) } fetchFoldersByPath = async (paths) => { const pathsWithEmptyPrefix = [''].concat(paths) const foldersItems = await Promise.all( pathsWithEmptyPrefix.map(async (path, idx) => { const prefix = paths.slice(0, idx).join('/') const options = { limit: LIMIT, offset: OFFSET, sortBy: { column: this.sortBy, order: 'asc' }, } const { data: items, error } = await this.supabaseClient.storage .from(this.selectedBucket.name) .list(prefix, options) if (error) { console.error('Error at fetchFoldersByPath:', error) } return items }) ) const formattedFolders = foldersItems.map((folderItems, idx) => { const formattedItems = this.formatFolderItems(folderItems) return { id: null, name: idx === 0 ? this.selectedBucket.name : pathsWithEmptyPrefix[idx], items: formattedItems, } }) // Package into columns and update this.columns this.columns = formattedFolders // Update openedFolders as well const updatedOpenedFolders = paths.map((path, idx) => { const folderInfo = find(formattedFolders[idx].items, { name: path }) // Folder doesnt exist, FE just scaffolds a "fake" folder if (!folderInfo) { return { id: null, name: path, type: STORAGE_ROW_TYPES.FOLDER, status: STORAGE_ROW_STATUS.READY, } } return folderInfo }) this.openedFolders = updatedOpenedFolders } // Check parent folder if its empty, if yes, reinstate .emptyFolderPlaceholder // Used when deleting folder or deleting files validateParentFolderEmpty = async (parentFolderPrefix) => { const { data: items, error } = await this.supabaseClient.storage .from(this.selectedBucket.name) .list(parentFolderPrefix, this.DEFAULT_OPTIONS) if (!error && items.length === 0) { const prefixToPlaceholder = `${parentFolderPrefix}/${EMPTY_FOLDER_PLACEHOLDER_FILE_NAME}` await this.supabaseClient.storage .from(this.selectedBucket.name) .upload(prefixToPlaceholder, new File([], EMPTY_FOLDER_PLACEHOLDER_FILE_NAME)) } } deleteFolder = async (folder) => { const isDeleteFolder = true const files = await this.getAllItemsAlongFolder(folder) await this.deleteFiles(files, isDeleteFolder) const parentFolderPrefix = this.openedFolders.map((folder) => folder.name).join('/') if (parentFolderPrefix.length > 0) { await this.validateParentFolderEmpty(parentFolderPrefix) } await this.refetchAllOpenedFolders() this.clearSelectedItemsToDelete() toast.success(`Successfully deleted ${folder.name}`) } renameFolder = async (folder, newName, columnIndex) => { const originalName = folder.name if (originalName === newName) { this.updateRowStatus(originalName, STORAGE_ROW_STATUS.READY, columnIndex) } else { this.updateRowStatus(originalName, STORAGE_ROW_STATUS.LOADING, columnIndex, newName) const files = await this.getAllItemsAlongFolder(folder) // Make this batched promises into a reusable function for storage, i think this will be super helpful const promises = files.map((file) => { const fromPath = `${file.prefix}/${file.name}` const pathSegments = fromPath.split('/') const toPath = pathSegments .slice(0, columnIndex) .concat(newName) .concat(pathSegments.slice(columnIndex + 1)) .join('/') return () => { return new Promise(async (resolve, reject) => { const { error } = await this.supabaseClient.storage .from(this.selectedBucket.name) .move(fromPath, toPath) if (error) reject() resolve() }) } }) const batchedPromises = chunk(promises, BATCH_SIZE) // [Joshen] I realised this can be simplified with just a vanilla for loop, no need for reduce // Just take note, but if it's working fine, then it's okay try { await batchedPromises.reduce(async (previousPromise, nextBatch) => { await previousPromise await Promise.all(nextBatch.map((batch) => batch())) }, Promise.resolve()) toast.success(`Successfully renamed folder to ${newName}`) await this.refetchAllOpenedFolders() // Clear file preview cache if the moved file exists in the cache const fileIds = files.map((file) => file.id) const updatedFilePreviewCache = this.filePreviewCache.filter( (fileCache) => !fileIds.includes(fileCache.id) ) this.filePreviewCache = updatedFilePreviewCache } catch (e) { toast.error(`Failed to rename folder to ${newName}`) } } } /* Recursively returns a list of items along every directory within the specified base folder Each item has an extra property 'prefix' which has the prefix that leads to the item Used specifically for any operation that deals with every file along the folder e.g Delete folder, rename folder */ getAllItemsAlongFolder = async (folder) => { const items = [] let formattedPathToFolder = '' const { name, columnIndex, prefix } = folder if (isUndefined(prefix)) { const pathToFolder = this.openedFolders .slice(0, columnIndex) .map((folder) => folder.name) .join('/') formattedPathToFolder = pathToFolder.length > 0 ? `${pathToFolder}/${name}` : name } else { formattedPathToFolder = `${prefix}/${name}` } const options = { limit: LIMIT, offset: OFFSET, sortBy: { column: this.sortBy, order: 'asc' } } const { data: folderContents } = await this.supabaseClient.storage .from(this.selectedBucket.name) .list(formattedPathToFolder, options) const subfolders = folderContents?.filter((item) => isNull(item.id)) ?? [] const folderItems = folderContents?.filter((item) => !isNull(item.id)) ?? [] folderItems.forEach((item) => items.push({ ...item, prefix: formattedPathToFolder })) const subFolderContents = await Promise.all( subfolders.map((folder) => this.getAllItemsAlongFolder({ ...folder, prefix: formattedPathToFolder }) ) ) subFolderContents.map((subfolderContent) => { subfolderContent.map((item) => items.push(item)) }) return items } /* UI Helper functions */ sanitizeNameForDuplicateInColumn = ( name, autofix = false, columnIndex = this.getLatestColumnIndex() ) => { const currentColumn = this.columns[columnIndex] const currentColumnItems = currentColumn.items.filter( (item) => item.status !== STORAGE_ROW_STATUS.EDITING ) const hasSameNameInColumn = currentColumnItems.filter((item) => item.name === name).length > 0 if (hasSameNameInColumn) { if (autofix) { const [fileName, fileExt] = name.split('.') const dupeNameRegex = new RegExp( `${fileName} \\([-0-9]+\\)${fileExt ? '.' + fileExt : ''}$` ) const itemsWithSameNameInColumn = currentColumnItems.filter((item) => item.name.match(dupeNameRegex) ) const updatedFileName = fileName + ` (${itemsWithSameNameInColumn.length + 1})` return fileExt ? `${updatedFileName}.${fileExt}` : updatedFileName } else { toast( `The name ${name} already exists in the current directory. Please use a different name.` ) return null } } return name } formatFolderItems = (items = []) => { const formattedItems = items ?.filter((item) => item.name !== EMPTY_FOLDER_PLACEHOLDER_FILE_NAME) .map((item) => { const itemObj = { ...item, type: item.id ? STORAGE_ROW_TYPES.FILE : STORAGE_ROW_TYPES.FOLDER, status: STORAGE_ROW_STATUS.READY, } return itemObj }) ?? [] return formattedItems } addTempRow = (type, name, status, columnIndex, metadata = {}) => { const updatedColumns = this.columns.map((column, idx) => { if (idx === columnIndex) { const tempRow = { type, name, status, metadata } const updatedItems = column.items.concat([tempRow]) return { ...column, items: updatedItems } } return column }) this.columns = updatedColumns } removeTempRows = (columnIndex) => { const updatedColumns = this.columns.map((column, idx) => { if (idx === columnIndex) { const updatedItems = column.items.filter((item) => has(item, 'id')) return { ...column, items: updatedItems } } return column }) this.columns = updatedColumns } setSelectedItemToRename = (file) => { this.updateRowStatus(file.name, STORAGE_ROW_STATUS.EDITING, file.columnIndex) } updateRowStatus = ( name, status, columnIndex = this.getLatestColumnIndex(), updatedName = null ) => { const updatedColumns = this.columns.map((column, idx) => { if (idx === columnIndex) { const updatedColumnItems = column.items.map((item) => { if (item.name === name) { return { ...item, status, ...(updatedName && { name: updatedName }), } } return item }) return { ...column, items: updatedColumnItems } } return column }) this.columns = updatedColumns } updateFolderAfterEdit = ( folderName, columnIndex = this.getLatestColumnIndex(), status = STORAGE_ROW_STATUS.READY ) => { const updatedColumns = this.columns.map((column, idx) => { if (idx === columnIndex) { const updatedItems = column.items.map((item) => { if (item.status === STORAGE_ROW_STATUS.EDITING) { const currentTime = new Date().toISOString() return { ...item, status, name: folderName, createdAt: currentTime, lastAccessedAt: currentTime, updatedAt: currentTime, metadata: null, id: null, } } return item }) return { ...column, items: updatedItems } } return column }) this.columns = updatedColumns } /* User Preferences */ updateExplorerPreferences = () => { const localStorageKey = this.getLocalStorageKey() const preferences = { view: this.view, sortBy: this.sortBy, } localStorage.setItem(localStorageKey, JSON.stringify(preferences)) return preferences } loadExplorerPreferences = () => { const localStorageKey = this.getLocalStorageKey() const preferences = localStorage.getItem(localStorageKey) if (preferences) { const { view, sortBy } = JSON.parse(preferences) this.view = view this.sortBy = sortBy } else { const { view, sortBy } = this.updateExplorerPreferences() this.view = view this.sortBy = sortBy } } } export default StorageExplorerStore
/** * ueditor完整配置项 * 可以在这里配置整个编辑器的特性 */ /**************************提示******************************** * 所有被注释的配置项均为UEditor默认值。 * 修改默认配置请首先确保已经完全明确该参数的真实用途。 * 主要有两种修改方案,一种是取消此处注释,然后修改成对应参数;另一种是在实例化编辑器时传入对应参数。 * 当升级编辑器时,可直接使用旧版配置文件替换新版配置文件,不用担心旧版配置文件中因缺少新功能所需的参数而导致脚本报错。 **************************提示********************************/ (function () { /** * 编辑器资源文件根路径。它所表示的含义是:以编辑器实例化页面为当前路径,指向编辑器资源文件(即dialog等文件夹)的路径。 * 鉴于很多同学在使用编辑器的时候出现的种种路径问题,此处强烈建议大家使用"相对于网站根目录的相对路径"进行配置。 * "相对于网站根目录的相对路径"也就是以斜杠开头的形如"/myProject/ueditor/"这样的路径。 * 如果站点中有多个不在同一层级的页面需要实例化编辑器,且引用了同一UEditor的时候,此处的URL可能不适用于每个页面的编辑器。 * 因此,UEditor提供了针对不同页面的编辑器可单独配置的根路径,具体来说,在需要实例化编辑器的页面最顶部写上如下代码即可。当然,需要令此处的URL等于对应的配置。 * window.UEDITOR_HOME_URL = "/xxxx/xxxx/"; */ //var URL = window.UEDITOR_HOME_URL || getUEBasePath(); var URL = window.UEDITOR_HOME_URL || getUEBasePath(); /** * 配置项主体。注意,此处所有涉及到路径的配置别遗漏URL变量。 */ window.UEDITOR_CONFIG = { //为编辑器实例添加一个路径,这个不能被注释 UEDITOR_HOME_URL: URL // 服务器统一请求接口路径 , serverUrl: "php/controller.php" //工具栏上的所有的功能按钮和下拉框,可以在new编辑器的实例时选择自己需要的重新定义 , toolbars: [[ 'bold', 'italic', 'underline','strikethrough','|','forecolor', 'backcolor','|','fontsize','|','justifyleft', 'justifycenter', 'justifyright', 'justifyjustify','simpleupload', 'insertimage','insertorderedlist', 'insertunorderedlist','source' /*'fullscreen', 'source', '|', 'undo', 'redo', '|', 'bold', 'italic', 'underline', 'fontborder', 'strikethrough', 'superscript', 'subscript', 'removeformat', 'formatmatch', 'autotypeset', 'blockquote', 'pasteplain', '|', 'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist', 'selectall', 'cleardoc', '|', 'rowspacingtop', 'rowspacingbottom', 'lineheight', '|', 'customstyle', 'paragraph', 'fontfamily', 'fontsize', '|', 'directionalityltr', 'directionalityrtl', 'indent', '|', 'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|', 'touppercase', 'tolowercase', '|', 'link', 'unlink', 'anchor', '|', 'imagenone', 'imageleft', 'imageright', 'imagecenter', '|', 'simpleupload', 'insertimage', 'emotion', 'scrawl', 'insertvideo', 'music', 'attachment', 'map', 'gmap', 'insertframe', 'insertcode', 'webapp', 'pagebreak', 'template', 'background', '|', 'horizontal', 'date', 'time', 'spechars', 'snapscreen', 'wordimage', '|', 'inserttable', 'deletetable', 'insertparagraphbeforetable', 'insertrow', 'deleterow', 'insertcol', 'deletecol', 'mergecells', 'mergeright', 'mergedown', 'splittocells', 'splittorows', 'splittocols', 'charts', '|', 'print', 'preview', 'searchreplace', 'drafts', 'help'*/ ]] //当鼠标放在工具栏上时显示的tooltip提示,留空支持自动多语言配置,否则以配置值为准 //,labelMap:{ // 'anchor':'', 'undo':'' //} //语言配置项,默认是zh-cn。有需要的话也可以使用如下这样的方式来自动多语言切换,当然,前提条件是lang文件夹下存在对应的语言文件: //lang值也可以通过自动获取 (navigator.language||navigator.browserLanguage ||navigator.userLanguage).toLowerCase() //,lang:"zh-cn" //,langPath:URL +"lang/" //主题配置项,默认是default。有需要的话也可以使用如下这样的方式来自动多主题切换,当然,前提条件是themes文件夹下存在对应的主题文件: //现有如下皮肤:default //,theme:'default' //,themePath:URL +"themes/" //,zIndex : 900 //编辑器层级的基数,默认是900 //针对getAllHtml方法,会在对应的head标签中增加该编码设置。 //,charset:"utf-8" //若实例化编辑器的页面手动修改的domain,此处需要设置为true //,customDomain:false //常用配置项目 //,isShow : true //默认显示编辑器 //,textarea:'editorValue' // 提交表单时,服务器获取编辑器提交内容的所用的参数,多实例时可以给容器name属性,会将name给定的值最为每个实例的键值,不用每次实例化的时候都设置这个值 //,initialContent:'欢迎使用ueditor!' //初始化编辑器的内容,也可以通过textarea/script给值,看官网例子 //,autoClearinitialContent:true //是否自动清除编辑器初始内容,注意:如果focus属性设置为true,这个也为真,那么编辑器一上来就会触发导致初始化的内容看不到了 //,focus:false //初始化时,是否让编辑器获得焦点true或false //如果自定义,最好给p标签如下的行高,要不输入中文时,会有跳动感 //,initialStyle:'p{line-height:1em}'//编辑器层级的基数,可以用来改变字体等 //,iframeCssUrl: URL + '/themes/iframe.css' //给编辑区域的iframe引入一个css文件 //indentValue //首行缩进距离,默认是2em //,indentValue:'2em' //,initialFrameWidth:1000 //初始化编辑器宽度,默认1000 //,initialFrameHeight:320 //初始化编辑器高度,默认320 //,readonly : false //编辑器初始化结束后,编辑区域是否是只读的,默认是false //,autoClearEmptyNode : true //getContent时,是否删除空的inlineElement节点(包括嵌套的情况) //启用自动保存 //,enableAutoSave: true //自动保存间隔时间, 单位ms //,saveInterval: 500 //,fullscreen : false //是否开启初始化时即全屏,默认关闭 //,imagePopup:true //图片操作的浮层开关,默认打开 //,autoSyncData:true //自动同步编辑器要提交的数据 //,emotionLocalization:false //是否开启表情本地化,默认关闭。若要开启请确保emotion文件夹下包含官网提供的images表情文件夹 //粘贴只保留标签,去除标签所有属性 //,retainOnlyLabelPasted: false //,pasteplain:false //是否默认为纯文本粘贴。false为不使用纯文本粘贴,true为使用纯文本粘贴 //纯文本粘贴模式下的过滤规则 //'filterTxtRules' : function(){ // function transP(node){ // node.tagName = 'p'; // node.setStyle(); // } // return { // //直接删除及其字节点内容 // '-' : 'script style object iframe embed input select', // 'p': {$:{}}, // 'br':{$:{}}, // 'div':{'$':{}}, // 'li':{'$':{}}, // 'caption':transP, // 'th':transP, // 'tr':transP, // 'h1':transP,'h2':transP,'h3':transP,'h4':transP,'h5':transP,'h6':transP, // 'td':function(node){ // //没有内容的td直接删掉 // var txt = !!node.innerText(); // if(txt){ // node.parentNode.insertAfter(UE.uNode.createText(' &nbsp; &nbsp;'),node); // } // node.parentNode.removeChild(node,node.innerText()) // } // } //}() //,allHtmlEnabled:false //提交到后台的数据是否包含整个html字符串 //insertorderedlist //有序列表的下拉配置,值留空时支持多语言自动识别,若配置值,则以此值为准 //,'insertorderedlist':{ // //自定的样式 // 'num':'1,2,3...', // 'num1':'1),2),3)...', // 'num2':'(1),(2),(3)...', // 'cn':'一,二,三....', // 'cn1':'一),二),三)....', // 'cn2':'(一),(二),(三)....', // //系统自带 // 'decimal' : '' , //'1,2,3...' // 'lower-alpha' : '' , // 'a,b,c...' // 'lower-roman' : '' , //'i,ii,iii...' // 'upper-alpha' : '' , lang //'A,B,C' // 'upper-roman' : '' //'I,II,III...' //} //insertunorderedlist //无序列表的下拉配置,值留空时支持多语言自动识别,若配置值,则以此值为准 //,insertunorderedlist : { //自定的样式 // 'dash' :'— 破折号', //-破折号 // 'dot':' 。 小圆圈', //系统自带 // 'circle' : '', // '○ 小圆圈' // 'disc' : '', // '● 小圆点' // 'square' : '' //'■ 小方块' //} //,listDefaultPaddingLeft : '30'//默认的左边缩进的基数倍 //,listiconpath : 'http://bs.baidu.com/listicon/'//自定义标号的路径 //,maxListLevel : 3 //限制可以tab的级数, 设置-1为不限制 //,autoTransWordToList:false //禁止word中粘贴进来的列表自动变成列表标签 //fontfamily //字体设置 label留空支持多语言自动切换,若配置,则以配置值为准 //,'fontfamily':[ // { label:'',name:'songti',val:'宋体,SimSun'}, // { label:'',name:'kaiti',val:'楷体,楷体_GB2312, SimKai'}, // { label:'',name:'yahei',val:'微软雅黑,Microsoft YaHei'}, // { label:'',name:'heiti',val:'黑体, SimHei'}, // { label:'',name:'lishu',val:'隶书, SimLi'}, // { label:'',name:'andaleMono',val:'andale mono'}, // { label:'',name:'arial',val:'arial, helvetica,sans-serif'}, // { label:'',name:'arialBlack',val:'arial black,avant garde'}, // { label:'',name:'comicSansMs',val:'comic sans ms'}, // { label:'',name:'impact',val:'impact,chicago'}, // { label:'',name:'timesNewRoman',val:'times new roman'} //] //fontsize //字号 //,'fontsize':[10, 11, 12, 14, 16, 18, 20, 24, 36] //paragraph //段落格式 值留空时支持多语言自动识别,若配置,则以配置值为准 //,'paragraph':{'p':'', 'h1':'', 'h2':'', 'h3':'', 'h4':'', 'h5':'', 'h6':''} //rowspacingtop //段间距 值和显示的名字相同 //,'rowspacingtop':['5', '10', '15', '20', '25'] //rowspacingBottom //段间距 值和显示的名字相同 //,'rowspacingbottom':['5', '10', '15', '20', '25'] //lineheight //行内间距 值和显示的名字相同 //,'lineheight':['1', '1.5','1.75','2', '3', '4', '5'] //customstyle //自定义样式,不支持国际化,此处配置值即可最后显示值 //block的元素是依据设置段落的逻辑设置的,inline的元素依据BIU的逻辑设置 //尽量使用一些常用的标签 //参数说明 //tag 使用的标签名字 //label 显示的名字也是用来标识不同类型的标识符,注意这个值每个要不同, //style 添加的样式 //每一个对象就是一个自定义的样式 //,'customstyle':[ // {tag:'h1', name:'tc', label:'', style:'border-bottom:#ccc 2px solid;padding:0 4px 0 0;text-align:center;margin:0 0 20px 0;'}, // {tag:'h1', name:'tl',label:'', style:'border-bottom:#ccc 2px solid;padding:0 4px 0 0;margin:0 0 10px 0;'}, // {tag:'span',name:'im', label:'', style:'font-style:italic;font-weight:bold'}, // {tag:'span',name:'hi', label:'', style:'font-style:italic;font-weight:bold;color:rgb(51, 153, 204)'} //] //打开右键菜单功能 //,enableContextMenu: true //右键菜单的内容,可以参考plugins/contextmenu.js里边的默认菜单的例子,label留空支持国际化,否则以此配置为准 //,contextMenu:[ // { // label:'', //显示的名称 // cmdName:'selectall',//执行的command命令,当点击这个右键菜单时 // //exec可选,有了exec就会在点击时执行这个function,优先级高于cmdName // exec:function () { // //this是当前编辑器的实例 // //this.ui._dialogs['inserttableDialog'].open(); // } // } //] //快捷菜单 //,shortcutMenu:["fontfamily", "fontsize", "bold", "italic", "underline", "forecolor", "backcolor", "insertorderedlist", "insertunorderedlist"] //elementPathEnabled //是否启用元素路径,默认是显示 //,elementPathEnabled : true //wordCount //,wordCount:true //是否开启字数统计 //,maximumWords:10000 //允许的最大字符数 //字数统计提示,{#count}代表当前字数,{#leave}代表还可以输入多少字符数,留空支持多语言自动切换,否则按此配置显示 //,wordCountMsg:'' //当前已输入 {#count} 个字符,您还可以输入{#leave} 个字符 //超出字数限制提示 留空支持多语言自动切换,否则按此配置显示 //,wordOverFlowMsg:'' //<span style="color:red;">你输入的字符个数已经超出最大允许值,服务器可能会拒绝保存!</span> //tab //点击tab键时移动的距离,tabSize倍数,tabNode什么字符做为单位 //,tabSize:4 //,tabNode:'&nbsp;' //removeFormat //清除格式时可以删除的标签和属性 //removeForamtTags标签 //,removeFormatTags:'b,big,code,del,dfn,em,font,i,ins,kbd,q,samp,small,span,strike,strong,sub,sup,tt,u,var' //removeFormatAttributes属性 //,removeFormatAttributes:'class,style,lang,width,height,align,hspace,valign' //undo //可以最多回退的次数,默认20 //,maxUndoCount:20 //当输入的字符数超过该值时,保存一次现场 //,maxInputCount:1 //autoHeightEnabled // 是否自动长高,默认true //,autoHeightEnabled:true //scaleEnabled //是否可以拉伸长高,默认true(当开启时,自动长高失效) //,scaleEnabled:false //,minFrameWidth:800 //编辑器拖动时最小宽度,默认800 //,minFrameHeight:220 //编辑器拖动时最小高度,默认220 //autoFloatEnabled //是否保持toolbar的位置不动,默认true //,autoFloatEnabled:true //浮动时工具栏距离浏览器顶部的高度,用于某些具有固定头部的页面 //,topOffset:30 //编辑器底部距离工具栏高度(如果参数大于等于编辑器高度,则设置无效) //,toolbarTopOffset:400 //设置远程图片是否抓取到本地保存 //,catchRemoteImageEnable: true //设置是否抓取远程图片 //pageBreakTag //分页标识符,默认是_ueditor_page_break_tag_ //,pageBreakTag:'_ueditor_page_break_tag_' //autotypeset //自动排版参数 //,autotypeset: { // mergeEmptyline: true, //合并空行 // removeClass: true, //去掉冗余的class // removeEmptyline: false, //去掉空行 // textAlign:"left", //段落的排版方式,可以是 left,right,center,justify 去掉这个属性表示不执行排版 // imageBlockLine: 'center', //图片的浮动方式,独占一行剧中,左右浮动,默认: center,left,right,none 去掉这个属性表示不执行排版 // pasteFilter: false, //根据规则过滤没事粘贴进来的内容 // clearFontSize: false, //去掉所有的内嵌字号,使用编辑器默认的字号 // clearFontFamily: false, //去掉所有的内嵌字体,使用编辑器默认的字体 // removeEmptyNode: false, // 去掉空节点 // //可以去掉的标签 // removeTagNames: {标签名字:1}, // indent: false, // 行首缩进 // indentValue : '2em', //行首缩进的大小 // bdc2sb: false, // tobdc: false //} //tableDragable //表格是否可以拖拽 //,tableDragable: true //sourceEditor //源码的查看方式,codemirror 是代码高亮,textarea是文本框,默认是codemirror //注意默认codemirror只能在ie8+和非ie中使用 //,sourceEditor:"codemirror" //如果sourceEditor是codemirror,还用配置一下两个参数 //codeMirrorJsUrl js加载的路径,默认是 URL + "third-party/codemirror/codemirror.js" //,codeMirrorJsUrl:URL + "third-party/codemirror/codemirror.js" //codeMirrorCssUrl css加载的路径,默认是 URL + "third-party/codemirror/codemirror.css" //,codeMirrorCssUrl:URL + "third-party/codemirror/codemirror.css" //编辑器初始化完成后是否进入源码模式,默认为否。 //,sourceEditorFirst:false //iframeUrlMap //dialog内容的路径 ~会被替换成URL,垓属性一旦打开,将覆盖所有的dialog的默认路径 //,iframeUrlMap:{ // 'anchor':'~/dialogs/anchor/anchor.html', //} //allowLinkProtocol 允许的链接地址,有这些前缀的链接地址不会自动添加http //, allowLinkProtocols: ['http:', 'https:', '#', '/', 'ftp:', 'mailto:', 'tel:', 'git:', 'svn:'] //webAppKey 百度应用的APIkey,每个站长必须首先去百度官网注册一个key后方能正常使用app功能,注册介绍,http://app.baidu.com/static/cms/getapikey.html //, webAppKey: "" //默认过滤规则相关配置项目 //,disabledTableInTable:true //禁止表格嵌套 //,allowDivTransToP:true //允许进入编辑器的div标签自动变成p标签 //,rgb2Hex:true //默认产出的数据中的color自动从rgb格式变成16进制格式 // xss 过滤是否开启,inserthtml等操作 ,xssFilterRules: true //input xss过滤 ,inputXssFilter: true //output xss过滤 ,outputXssFilter: true // xss过滤白名单 名单来源: https://raw.githubusercontent.com/leizongmin/js-xss/master/lib/default.js ,whitList: { a: ['target', 'href', 'title', 'class', 'style'], abbr: ['title', 'class', 'style'], address: ['class', 'style'], area: ['shape', 'coords', 'href', 'alt'], article: [], aside: [], audio: ['autoplay', 'controls', 'loop', 'preload', 'src', 'class', 'style'], b: ['class', 'style'], bdi: ['dir'], bdo: ['dir'], big: [], blockquote: ['cite', 'class', 'style'], br: [], caption: ['class', 'style'], center: [], cite: [], code: ['class', 'style'], col: ['align', 'valign', 'span', 'width', 'class', 'style'], colgroup: ['align', 'valign', 'span', 'width', 'class', 'style'], dd: ['class', 'style'], del: ['datetime'], details: ['open'], div: ['class', 'style'], dl: ['class', 'style'], dt: ['class', 'style'], em: ['class', 'style'], font: ['color', 'size', 'face'], footer: [], h1: ['class', 'style'], h2: ['class', 'style'], h3: ['class', 'style'], h4: ['class', 'style'], h5: ['class', 'style'], h6: ['class', 'style'], header: [], hr: [], i: ['class', 'style'], img: ['src', 'alt', 'title', 'width', 'height', 'id', '_src', 'loadingclass', 'class', 'data-latex'], ins: ['datetime'], li: ['class', 'style'], mark: [], nav: [], ol: ['class', 'style'], p: ['class', 'style'], pre: ['class', 'style'], s: [], section:[], small: [], span: ['class', 'style'], sub: ['class', 'style'], sup: ['class', 'style'], strong: ['class', 'style'], table: ['width', 'border', 'align', 'valign', 'class', 'style'], tbody: ['align', 'valign', 'class', 'style'], td: ['width', 'rowspan', 'colspan', 'align', 'valign', 'class', 'style'], tfoot: ['align', 'valign', 'class', 'style'], th: ['width', 'rowspan', 'colspan', 'align', 'valign', 'class', 'style'], thead: ['align', 'valign', 'class', 'style'], tr: ['rowspan', 'align', 'valign', 'class', 'style'], tt: [], u: [], ul: ['class', 'style'], video: ['autoplay', 'controls', 'loop', 'preload', 'src', 'height', 'width', 'class', 'style'] } }; function getUEBasePath(docUrl, confUrl) { return getBasePath(docUrl || self.document.URL || self.location.href, confUrl || getConfigFilePath()); } function getConfigFilePath() { var configPath = document.getElementsByTagName('script'); return configPath[ configPath.length - 1 ].src; } function getBasePath(docUrl, confUrl) { var basePath = confUrl; if (/^(\/|\\\\)/.test(confUrl)) { basePath = /^.+?\w(\/|\\\\)/.exec(docUrl)[0] + confUrl.replace(/^(\/|\\\\)/, ''); } else if (!/^[a-z]+:/i.test(confUrl)) { docUrl = docUrl.split("#")[0].split("?")[0].replace(/[^\\\/]+$/, ''); basePath = docUrl + "" + confUrl; } return optimizationPath(basePath); } function optimizationPath(path) { var protocol = /^[a-z]+:\/\//.exec(path)[ 0 ], tmp = null, res = []; path = path.replace(protocol, "").split("?")[0].split("#")[0]; path = path.replace(/\\/g, '/').split(/\//); path[ path.length - 1 ] = ""; while (path.length) { if (( tmp = path.shift() ) === "..") { res.pop(); } else if (tmp !== ".") { res.push(tmp); } } return protocol + res.join("/"); } window.UE = { getUEBasePath: getUEBasePath }; })();
import { Color, Mesh, Plane, Program } from 'ogl' import fragment from 'shaders/background-fragment.glsl' import vertex from 'shaders/background-vertex.glsl' import { random } from 'utils/math' export default class { constructor ({ gl, scene, viewport }) { this.gl = gl this.scene = scene this.viewport = viewport const geometry = new Plane(this.gl) const program = new Program(this.gl, { vertex, fragment, uniforms: { uColor: { value: new Color('#0D0D0F') } }, transparent: true }) this.meshes = [] for (let i = 0; i < 50; i++) { let mesh = new Mesh(this.gl, { geometry, program, }) const scale = random(0.75, 1) mesh.scale.x = 1.6 * scale mesh.scale.y = 0.9 * scale mesh.speed = random(0.75, 1) mesh.xExtra = 0 mesh.x = mesh.position.x = random(-this.viewport.width * 0.5, this.viewport.width * 0.5) mesh.y = mesh.position.y = random(-this.viewport.height * 0.5, this.viewport.height * 0.5) this.meshes.push(mesh) this.scene.addChild(mesh) } } update (scroll, direction) { this.meshes.forEach(mesh => { mesh.position.x = mesh.x - scroll.current * mesh.speed - mesh.xExtra const viewportOffset = this.viewport.width * 0.5 const widthTotal = this.viewport.width + mesh.scale.x mesh.isBefore = mesh.position.x < -viewportOffset mesh.isAfter = mesh.position.x > viewportOffset if (direction === 'right' && mesh.isBefore) { mesh.xExtra -= widthTotal mesh.isBefore = false mesh.isAfter = false } if (direction === 'left' && mesh.isAfter) { mesh.xExtra += widthTotal mesh.isBefore = false mesh.isAfter = false } mesh.position.y += 0.05 * mesh.speed if (mesh.position.y > this.viewport.height * 0.5 + mesh.scale.y) { mesh.position.y -= this.viewport.height + mesh.scale.y } }) } }
/*! * Start Bootstrap - New Age v5.0.7 (https://startbootstrap.com/template-overviews/new-age) * Copyright 2013-2020 Start Bootstrap * Licensed under MIT (https://github.com/BlackrockDigital/startbootstrap-new-age/blob/master/LICENSE) */ !function(t){"use strict";t('a.js-scroll-trigger[href*="#"]:not([href="#"])').click(function(){if(location.pathname.replace(/^\//,"")==this.pathname.replace(/^\//,"")&&location.hostname==this.hostname){var e=t(this.hash);if((e=e.length?e:t("[name="+this.hash.slice(1)+"]")).length)return t("html, body").animate({scrollTop:e.offset().top-48},1e3,"easeInOutExpo"),!1}}),t(".js-scroll-trigger").click(function(){t(".navbar-collapse").collapse("hide")}),t("body").scrollspy({target:"#mainNav",offset:54})}(jQuery);
import React, { useState } from 'react' import ClassNames from 'classnames' import PropTypes from 'prop-types' import Scrollbars from '../Scrollbars' import useSize from '../../hooks/useSize' import './style.css' const getTabTitle = (tab) => { // eslint-disable-line const { htmlKey, tabtitle } = tab.props if (typeof tabtitle === 'string') { return tabtitle } if (!htmlKey) console.trace('htmlKey missing') return htmlKey } const getForcedTab = (forcedTab, tabs) => { // eslint-disable-line for (let i = 0; i < tabs.length; i++) { if (tabs[i].props.tabtitle === forcedTab) { return i } } } const Panel = (props) => { const { label, className, onRemove, hideIcons, children, headerComponents, extraIcons, moveable, removeable, modal, footer, settingsOpen, onToggleSettings, darkHeader, dark, showChartMarket, chartMarketSelect, secondaryHeaderComponents, closePanel, preHeaderComponents, dropdown, forcedTab, } = props const tabs = React.Children.toArray(children).filter(c => c && c.props.tabtitle) const initTab = forcedTab.length ? getForcedTab(forcedTab, tabs) : 0 const [selectedTab, setSelectedTab] = useState(initTab) const [panelRef, panelSize] = useSize() const [headerRef, headerSize] = useSize() return ( <div className={ClassNames('hfui-panel', className, { 'dark-header': darkHeader, dark, })} ref={panelRef} > <div ref={headerRef}> <div className={ClassNames('hfui-panel__header', { 'has-secondary-header': !!secondaryHeaderComponents, })} > <div className='hfui-panel__left-container'> {label && <p className='hfui-panel__label'>{label}</p>} {headerComponents && ( <div className='hfui-panel__header-components'> {headerComponents} </div> )} </div> <div className='hfui-panel__buttons-section'> {preHeaderComponents && ( <div className='hfui-panel__preheader'> {preHeaderComponents} </div> )} {closePanel && ( <p className='hfui-panel__close' onClick={closePanel}>&#10005;</p> )} </div> {tabs.length > 0 && ( <ul className='hfui-panel__header-tabs'> {tabs.map((tab, index) => ( <li key={tab.props.htmlKey || tab.props.tabtitle} className={ClassNames({ active: getTabTitle(tab) === getTabTitle(tabs[selectedTab]) })} onClick={() => setSelectedTab(index)} > <p className='hfui-panel__label'> {tab.props.tabtitle} </p> </li> ))} </ul> )} {!hideIcons && ( <div className='hfui-panel__header-icons'> {removeable && ( <i onClick={onRemove} className='icon-cancel' /> )} {moveable && <i className='icon-move' />} {showChartMarket && ( <div className='hfui-panel__chart-market-select'> {chartMarketSelect} </div> )} {onToggleSettings && ( <i onClick={onToggleSettings} className={ClassNames('icon-settings-icon', { yellow: settingsOpen, })} /> )} {extraIcons} {dropdown} </div> )} </div> {secondaryHeaderComponents && ( <div className='hfui-panel__secondaryheader__wrapper'> {secondaryHeaderComponents} </div> )} </div> <div className='hfui-panel__content'> {modal} <Scrollbars style={{ height: panelSize.height - headerSize.height }}> <div className='hfui-panel__inner'> {tabs.length > 0 ? tabs[selectedTab] : children} </div> </Scrollbars> </div> {footer && ( <div className='hfui-panel__footer'>{footer}</div> )} </div> ) } Panel.propTypes = { className: PropTypes.string, label: PropTypes.oneOfType([PropTypes.node, PropTypes.string]), onRemove: PropTypes.func, headerComponents: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.node), PropTypes.node]), secondaryHeaderComponents: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.node), PropTypes.node]), hideIcons: PropTypes.bool, extraIcons: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.node), PropTypes.node]), moveable: PropTypes.bool, removeable: PropTypes.bool, modal: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.node), PropTypes.node]), darkHeader: PropTypes.bool, dark: PropTypes.bool, children: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.node), PropTypes.node]), footer: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.node), PropTypes.node]), settingsOpen: PropTypes.bool, onToggleSettings: PropTypes.func, showChartMarket: PropTypes.bool, chartMarketSelect: PropTypes.node, closePanel: PropTypes.func, preHeaderComponents: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.node), PropTypes.node]), forcedTab: PropTypes.string, dropdown: PropTypes.node, } Panel.defaultProps = { moveable: true, removeable: true, darkHeader: false, dark: false, className: '', label: '', onRemove: () => {}, headerComponents: null, secondaryHeaderComponents: null, hideIcons: false, extraIcons: null, children: [], modal: null, footer: null, settingsOpen: false, onToggleSettings: null, showChartMarket: false, chartMarketSelect: null, closePanel: null, preHeaderComponents: null, forcedTab: '', dropdown: null, } export default Panel
import _extends from "@babel/runtime/helpers/esm/extends"; import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties"; import * as React from 'react'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import { refType } from '@mui-magic/utils'; import InputBase from '../InputBase'; import withStyles from '../styles/withStyles'; export var styles = function styles(theme) { var light = theme.palette.type === 'light'; var bottomLineColor = light ? 'rgba(0, 0, 0, 0.42)' : 'rgba(255, 255, 255, 0.7)'; var backgroundColor = light ? 'rgba(0, 0, 0, 0.09)' : 'rgba(255, 255, 255, 0.09)'; return { /* Styles applied to the root element. */ root: { position: 'relative', backgroundColor: backgroundColor, borderTopLeftRadius: theme.shape.borderRadius, borderTopRightRadius: theme.shape.borderRadius, transition: theme.transitions.create('background-color', { duration: theme.transitions.duration.shorter, easing: theme.transitions.easing.easeOut }), '&:hover': { backgroundColor: light ? 'rgba(0, 0, 0, 0.13)' : 'rgba(255, 255, 255, 0.13)', // Reset on touch devices, it doesn't add specificity '@media (hover: none)': { backgroundColor: backgroundColor } }, '&$focused': { backgroundColor: light ? 'rgba(0, 0, 0, 0.09)' : 'rgba(255, 255, 255, 0.09)' }, '&$disabled': { backgroundColor: light ? 'rgba(0, 0, 0, 0.12)' : 'rgba(255, 255, 255, 0.12)' } }, /* Styles applied to the root element if color secondary. */ colorSecondary: { '&$underline:after': { borderBottomColor: theme.palette.secondary.main } }, /* Styles applied to the root element if `disableUnderline={false}`. */ underline: { '&:after': { borderBottom: "2px solid ".concat(theme.palette.primary.main), left: 0, bottom: 0, // Doing the other way around crash on IE 11 "''" https://github.com/cssinjs/jss/issues/242 content: '""', position: 'absolute', right: 0, transform: 'scaleX(0)', transition: theme.transitions.create('transform', { duration: theme.transitions.duration.shorter, easing: theme.transitions.easing.easeOut }), pointerEvents: 'none' // Transparent to the hover style. }, '&$focused:after': { transform: 'scaleX(1)' }, '&$error:after': { borderBottomColor: theme.palette.error.main, transform: 'scaleX(1)' // error is always underlined in red }, '&:before': { borderBottom: "1px solid ".concat(bottomLineColor), left: 0, bottom: 0, // Doing the other way around crash on IE 11 "''" https://github.com/cssinjs/jss/issues/242 content: '"\\00a0"', position: 'absolute', right: 0, transition: theme.transitions.create('border-bottom-color', { duration: theme.transitions.duration.shorter }), pointerEvents: 'none' // Transparent to the hover style. }, '&:hover:before': { borderBottom: "1px solid ".concat(theme.palette.text.primary) }, '&$disabled:before': { borderBottomStyle: 'dotted' } }, /* Pseudo-class applied to the root element if the component is focused. */ focused: {}, /* Pseudo-class applied to the root element if `disabled={true}`. */ disabled: {}, /* Styles applied to the root element if `startAdornment` is provided. */ adornedStart: { paddingLeft: 12 }, /* Styles applied to the root element if `endAdornment` is provided. */ adornedEnd: { paddingRight: 12 }, /* Pseudo-class applied to the root element if `error={true}`. */ error: {}, /* Styles applied to the `input` element if `margin="dense"`. */ marginDense: {}, /* Styles applied to the root element if `multiline={true}`. */ multiline: { padding: '27px 12px 10px', '&$marginDense': { paddingTop: 23, paddingBottom: 6 } }, /* Styles applied to the `input` element. */ input: { padding: '27px 12px 10px', '&:-webkit-autofill': { WebkitBoxShadow: theme.palette.type === 'light' ? null : '0 0 0 100px #266798 inset', WebkitTextFillColor: theme.palette.type === 'light' ? null : '#fff', caretColor: theme.palette.type === 'light' ? null : '#fff', borderTopLeftRadius: 'inherit', borderTopRightRadius: 'inherit' } }, /* Styles applied to the `input` element if `margin="dense"`. */ inputMarginDense: { paddingTop: 23, paddingBottom: 6 }, /* Styles applied to the `input` if in `<FormControl hiddenLabel />`. */ inputHiddenLabel: { paddingTop: 18, paddingBottom: 19, '&$inputMarginDense': { paddingTop: 10, paddingBottom: 11 } }, /* Styles applied to the `input` element if `multiline={true}`. */ inputMultiline: { padding: 0 }, /* Styles applied to the `input` element if `startAdornment` is provided. */ inputAdornedStart: { paddingLeft: 0 }, /* Styles applied to the `input` element if `endAdornment` is provided. */ inputAdornedEnd: { paddingRight: 0 } }; }; var FilledInput = /*#__PURE__*/React.forwardRef(function FilledInput(props, ref) { var disableUnderline = props.disableUnderline, classes = props.classes, _props$fullWidth = props.fullWidth, fullWidth = _props$fullWidth === void 0 ? false : _props$fullWidth, _props$inputComponent = props.inputComponent, inputComponent = _props$inputComponent === void 0 ? 'input' : _props$inputComponent, _props$multiline = props.multiline, multiline = _props$multiline === void 0 ? false : _props$multiline, _props$type = props.type, type = _props$type === void 0 ? 'text' : _props$type, other = _objectWithoutProperties(props, ["disableUnderline", "classes", "fullWidth", "inputComponent", "multiline", "type"]); return /*#__PURE__*/React.createElement(InputBase, _extends({ classes: _extends({}, classes, { root: clsx(classes.root, !disableUnderline && classes.underline), underline: null }), fullWidth: fullWidth, inputComponent: inputComponent, multiline: multiline, ref: ref, type: type }, other)); }); process.env.NODE_ENV !== "production" ? FilledInput.propTypes = { // ----------------------------- Warning -------------------------------- // | These PropTypes are generated from the TypeScript type definitions | // | To update them edit the d.ts file and run "yarn proptypes" | // ---------------------------------------------------------------------- /** * This prop helps users to fill forms faster, especially on mobile devices. * The name can be confusing, as it's more like an autofill. * You can learn more about it [following the specification](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofill). */ autoComplete: PropTypes.string, /** * If `true`, the `input` element will be focused during the first mount. */ autoFocus: PropTypes.bool, /** * Override or extend the styles applied to the component. * See [CSS API](#css) below for more details. */ classes: PropTypes.object, /** * The color of the component. It supports those theme colors that make sense for this component. */ color: PropTypes.oneOf(['primary', 'secondary']), /** * The default `input` element value. Use when the component is not controlled. */ defaultValue: PropTypes.any, /** * If `true`, the `input` element will be disabled. */ disabled: PropTypes.bool, /** * If `true`, the input will not have an underline. */ disableUnderline: PropTypes.bool, /** * End `InputAdornment` for this component. */ endAdornment: PropTypes.node, /** * If `true`, the input will indicate an error. This is normally obtained via context from * FormControl. */ error: PropTypes.bool, /** * If `true`, the input will take up the full width of its container. */ fullWidth: PropTypes.bool, /** * The id of the `input` element. */ id: PropTypes.string, /** * The component used for the `input` element. * Either a string to use a HTML element or a component. */ inputComponent: PropTypes.elementType, /** * [Attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Attributes) applied to the `input` element. */ inputProps: PropTypes.object, /** * Pass a ref to the `input` element. */ inputRef: refType, /** * If `dense`, will adjust vertical spacing. This is normally obtained via context from * FormControl. */ margin: PropTypes.oneOf(['dense', 'none']), /** * If `true`, a textarea element will be rendered. */ multiline: PropTypes.bool, /** * Name attribute of the `input` element. */ name: PropTypes.string, /** * Callback fired when the value is changed. * * @param {object} event The event source of the callback. * You can pull out the new value by accessing `event.target.value` (string). */ onChange: PropTypes.func, /** * The short hint displayed in the input before the user enters a value. */ placeholder: PropTypes.string, /** * It prevents the user from changing the value of the field * (not from interacting with the field). */ readOnly: PropTypes.bool, /** * If `true`, the `input` element will be required. */ required: PropTypes.bool, /** * Number of rows to display when multiline option is set to true. */ rows: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), /** * Maximum number of rows to display when multiline option is set to true. */ rowsMax: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), /** * Start `InputAdornment` for this component. */ startAdornment: PropTypes.node, /** * Type of the `input` element. It should be [a valid HTML5 input type](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Form_%3Cinput%3E_types). */ type: PropTypes.string, /** * The value of the `input` element, required for a controlled component. */ value: PropTypes.any } : void 0; FilledInput.muiName = 'Input'; export default withStyles(styles, { name: 'MuiFilledInput' })(FilledInput);
/** * Created by Eduardo Luttinger on 05/04/2016. */ angular.module('App') .factory('BusinessLookup', function ($http, $q, CONST_PROXY_URL) { var lookup = {}; var businessIdFound = 0; var businessJson = { business: {}, totalPages: 0, totalRecords: 0 }; /** * * @returns {IPromise<TResult>|*} */ lookup.allBusiness = function (filterCriteria) { var defered = $q.defer(); var promise = defered.promise; $http({ method: 'POST', data: JSON.stringify(filterCriteria), url: CONST_PROXY_URL.PROXY_URL_ALL_BUSINESS_WITH_PAGINATE, }).success(function (response) { businessJson.business = response.ReaxiumResponse.object; businessJson.totalPages = response.ReaxiumResponse.totalPages; businessJson.totalRecords = response.ReaxiumResponse.totalRecords; defered.resolve(businessJson); }).error(function (err) { defered.reject(err); }) return promise; }; /** * search a business by his ID */ lookup.businessById = function (businessId) { var defered = $q.defer(); var promise = defered.promise; $http({ method: 'POST', data: JSON.stringify({'ReaxiumParameters': {'Business': {'business_id': businessId}}}), url: CONST_PROXY_URL.PROXY_URL_BUSINESS_BY_ID, }).success(function (response) { var jsonObj = response.ReaxiumResponse.object; businessIdFound = jsonObj[0].business_id; defered.resolve(response.ReaxiumResponse.object); }).error(function (err) { defered.reject(err); }) return promise; }; /** * Get Business with filter * @param filters * @returns {*} */ lookup.allBusinessWithFilter = function (filters) { var defered = $q.defer(); var promise = defered.promise; $http({ method: 'POST', url: CONST_PROXY_URL.PROXY_URL_ALL_BUSINESS_WITH_FILTER, data: JSON.stringify({ReaxiumParameters: {Business: {filter: filters}}}), headers: {'Content-Type': 'application/json;charset=UTF-8'} }).success(function (response) { defered.resolve(response); }).error(function (err) { defered.reject(err); }); return promise; }; /** * get all status available in system * @returns {*} */ lookup.allStatus = function () { var defered = $q.defer(); var promise = defered.promise; $http({ method: 'GET', url: CONST_PROXY_URL.PROXY_URL_ALL_STATUS_USER }).success(function (response) { defered.resolve(response.ReaxiumResponse.object); }).error(function (err) { defered.reject(err); }); return promise; } /** * create new business * @param obj * @returns {*} */ lookup.newBusiness = function (obj) { var defered = $q.defer(); var promise = defered.promise; $http({ method: 'POST', url: CONST_PROXY_URL.PROXY_URL_CREATE_NEW_BUSINESS, data: JSON.stringify(obj), headers: {'Content-Type': 'application/json;charset=UTF-8'} }).success(function (response) { defered.resolve(response.ReaxiumResponse); }).error(function (err) { defered.reject(err); }); return promise; } lookup.getBusinessIdFound = function () { return businessIdFound; } /** * Delete Business * @param businessId * @returns {d.promise|*|promise} */ lookup.deleteABusiness = function(businessId){ var defered = $q.defer(); var promise = defered.promise; $http({ method: 'POST', url: CONST_PROXY_URL.PROXY_URL_DELETE_BUSINESS_BY_ID, data: JSON.stringify({ReaxiumParameters:{Business:{business_id:businessId}}}), headers: {'Content-Type': 'application/json;charset=UTF-8'} }).success(function (response) { defered.resolve(response); }).error(function (err) { defered.reject(err); }); return promise; } return lookup; }) .service('BusinessService', function (BusinessLookup) { var objModeEdit = { isModeEdit: false, businessId: 0 }; var addressDefault = { latitude: 37.0902, longitude: -95.7129 } var showGrowl = { isShow: false, message: "" }; var objBusinessById = {}; this.cleanGrowl = function(){ this.setShowGrowlMessage({isShow:false,message:""}); } this.cleanModeEdit = function(){ this.setModeEdit({isModeEdit:false,businessId:0}); } this.getObjBusinessById = function () { return objBusinessById; } this.setObjBusinessById = function (obj) { objBusinessById = obj; } this.getAddressDefault = function () { return addressDefault; } this.getModeEdit = function () { return objModeEdit; }; this.setModeEdit = function (mode) { objModeEdit = mode; }; this.getBusiness = function (filter) { return BusinessLookup.allBusiness(filter); }; this.getBusinessById = function (businessId) { return BusinessLookup.businessById(businessId); }; this.getBusinessIdFound = function () { return BusinessLookup.getBusinessIdFound(); }; this.getAllStatus = function () { return BusinessLookup.allStatus(); }; this.createNewBusiness = function (objNewBusiness) { return BusinessLookup.newBusiness(objNewBusiness) } this.getShowGrowlMessage = function () { return showGrowl; } this.setShowGrowlMessage = function (obj) { showGrowl = obj; } this.deleteBusiness = function(businessId){ return BusinessLookup.deleteABusiness(businessId) } this.getBusinessFilter = function(filter){ return BusinessLookup.allBusinessWithFilter(filter); } });
/** * password controller * helps user to reset his password * @author adrienjoly, whyd */ var config = require('../../models/config.js'); var users = require('../../models/user.js'); var md5 = users.md5; var notifEmails = require('../../models/notifEmails.js'); var templateLoader = require('../../templates/templateLoader.js'); exports.checkResetCode = function (request, reqParams, response, okCallback) { if (!reqParams.resetCode || !reqParams.uid) { console.log('resetCode and uid parameters are required'); response.legacyRender( 'Your password reset request is invalid. Please try to login on ' + process.appParams.urlPrefix ); return false; } users.fetchByUid(reqParams.uid, function (user) { if (user && user.pwd == reqParams.resetCode) { if (okCallback) okCallback(user); } else { console.log('invalid password reset request'); response.legacyRender( 'Your password reset request is invalid or expired. Please try to login on ' + process.appParams.urlPrefix ); } }); }; /** * called when a user wants to reset his password */ exports.renderForgotPage = function (request, reqParams, response, error) { reqParams = reqParams || {}; request.logToConsole('password.renderForgotPage', { email: reqParams.email, error: reqParams.error, redirect: reqParams.redirect, }); var vars = { email: reqParams.email, error: error || reqParams.error || '', redirect: reqParams.redirect || '', }; templateLoader.loadTemplate( 'app/templates/passwordForgot.html', function (template) { response.legacyRender(template.render(vars), null, { 'content-type': 'text/html', }); } ); }; /** * called when user follows the password reset URL (/password?uid=xxx&resetCode=yyy), e.g. provided in an email */ exports.renderPasswordPage = function (request, reqParams, response, error) { reqParams = reqParams || {}; request.logToConsole('password.renderPasswordPage', { uid: reqParams.uid, resetCode: reqParams.resetCode, email: reqParams.email, error: reqParams.error, redirect: reqParams.redirect, }); exports.checkResetCode(request, reqParams, response, function (user) { var vars = { resetCode: reqParams.resetCode, uid: user.id, email: user.email, password: reqParams.password || '', password2: reqParams.password2 || '', error: error || reqParams.error || '', redirect: reqParams.redirect || '', }; //var html = Mustache.to_html(htmlTemplate, vars); //response.legacyRender(html, null, {'content-type': 'text/html'}); templateLoader.loadTemplate( 'app/templates/passwordSet.html', function (template) { response.legacyRender(template.render(vars), null, { 'content-type': 'text/html', }); } ); }); }; /** * called when user submits the form from password.html */ exports.resetPassword = function (request, reqParams, response) { request.logToConsole( 'register.resetPassword', reqParams ? { resetCode: reqParams.resetCode, uid: reqParams.uid, email: reqParams.email, redirect: reqParams.redirect, } : null ); reqParams = reqParams || {}; if (!reqParams.resetCode || !reqParams.uid || !reqParams.password) return exports.renderPasswordPage( request, reqParams, response, 'missing required parameters' ); if (reqParams.password == 'password' || reqParams.password.trim() == '') return exports.renderPasswordPage( request, reqParams, response, 'Please enter your new password twice' ); else if (reqParams.password.length < 4 || reqParams.password.length > 32) return exports.renderPasswordPage( request, reqParams, response, 'Your password must be between 4 and 32 characters' ); //else if (!pwdRegex.test(reqParams.password)) // return exports.renderPasswordPage(request, reqParams, response, "Your password contains invalid characters"); exports.checkResetCode(request, reqParams, response, function (user) { users.save( { _id: user._id, pwd: md5(reqParams.password) }, function (storedUser) { if (!storedUser) return exports.renderPasswordPage( request, reqParams, response, 'Oops, your request failed... Please try again!' ); console.log('password reset ok'); notifEmails.sendPasswordUpdated(storedUser._id, storedUser.email); if (reqParams.redirect) return response.redirect(reqParams.redirect); else return response.legacyRender( 'Your password was successfully updated! You can now login there: ' + config.urlPrefix ); //, null, {'content-type': 'text/html'}); } ); }); }; exports.controller = function (request, getParams, response) { request.logToConsole('password.controller', request.method); if (request.method.toLowerCase() === 'post') exports.resetPassword(request, request.body /*postParams*/, response); else exports[ getParams && getParams.uid ? 'renderPasswordPage' : 'renderForgotPage' ](request, getParams, response); };
// THIS FILE IS AUTO GENERATED var GenIcon = require('../lib').GenIcon module.exports.GiOasis = function GiOasis (props) { return GenIcon({"tag":"svg","attr":{"viewBox":"0 0 512 512"},"child":[{"tag":"path","attr":{"d":"M307.4 20.97c-21.7-.15-43.9 3.68-64.9 9.72C296.7 39.1 344.7 55 364.3 80.71c-39.8-9.4-74.5 34.19-75.7 69.09 23.4-24.2 47.8-41.4 87.4-43.7 27.9 56.7 5.1 141.1 7.6 199.7.6 15.3 47.8 24.6 47.2 10.1-.2-51.5-4-145-25.8-208.1 38.8 7.3 74.1 33 74.1 33-1.1-23-26.9-48.99-58.6-53.59 7.7-9.6 27-24.9 71.1-26.71-23.4-18.4-59.9-17.7-88.3 2.31-25.1-30.36-59.8-41.61-95.9-41.84zm-153 35.84c-18.3.1-36.9 6.89-56.35 21.82-25.99-18.58-56.2-25.59-77.61-8.5 40.35 1.68 49.53 21.74 56.57 30.57-29 4.3-50.49 25.9-51.49 47.1 0 0 34.94-13.1 70.44-19.9-19.94 58.5-20.49 91.1-20.68 139 .57 11.5 41.52 17.8 42.22 1.5 2.3-54.5-13.6-79.4 2.4-134.1 11.5-5.9 52.2.5 73.6 23-1.1-32.3-19-64.41-55.4-55.7 9.4-18.03 26.8-21.13 78-20.99-20.7-15.28-41-23.87-61.7-23.8zm50.4 227.69c-22.3-.1-44.3 3.4-65.2 12.2-57.09 24.2-85.37 48.5-90.55 75.7-2.58 13.6 1.58 26.9 9.74 38.2 8.16 11.3 20.17 21.1 34.67 29.9 58.04 35.1 156.94 55.3 222.24 49.6 26.6-2.3 62.7-7 93.7-18.4 15.4-5.8 29.7-13.2 40.8-23.4 11-10.3 18.8-23.7 20-39.7v-.1c1-14.1-4.2-26.7-12.6-36.5-8.4-9.8-19.8-17.4-32.3-23.8-25.1-12.9-55.1-21.3-76.5-29.3-44-16.5-94.8-34.2-144-34.4zm11.2 18.7c12.3.8 24.9 2.6 37.4 5.2-70.8 23.9-127.7 59.7-171.65 101-4.55-4.4-8.4-8.9-11.35-14 39-36.4 87.3-68.4 145.6-92.2zm58.3 10.1c17.4 4.6 34.7 10.3 51.4 16.3-71.7 31.2-138.6 65.8-192.3 110.7-12.8-5.3-24-11.3-34.64-17.7 50.54-45 111.14-79.4 175.54-109.3z"}}]})(props); };
module.exports = exports = joi => (fields = []) => { let fieldsValid; if (fields.length > 0) fieldsValid = joi.string().valid(fields); const rule = joi .array() .items(fieldsValid) .default([]); return rule; };
/** * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Use `npm run webpack` to produce Webpack bundle for this library. const path = require('path'); module.exports = { entry: './index.ts', resolve: { extensions: ['.ts', '.js', '.json'], }, output: { library: 'Spanner', filename: 'spanner.min.js', path: path.resolve(__dirname, 'dist'), }, node: { child_process: 'empty', fs: 'empty', crypto: 'empty', }, module: { rules: [ { test: /node_modules\/google-auth-library\/src\/crypto\/node\/crypto/, use: 'null-loader', }, { test: /node_modules\/https-proxy-agent\//, use: 'null-loader', }, { test: /node_modules\/gcp-metadata\//, use: 'null-loader', }, { test: /node_modules\/gtoken\//, use: 'null-loader', }, { test: /node_modules\/pkginfo\//, use: 'null-loader', }, { test: /node_modules\/semver\//, use: 'null-loader', }, { test: /\.ts$/, use: 'ts-loader', exclude: /node_modules/, }, ], }, mode: 'production', plugins: [], };
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0z" /><circle cx="6.18" cy="17.82" r="2.18" /><path d="M4 4.44v2.83c7.03 0 12.73 5.7 12.73 12.73h2.83c0-8.59-6.97-15.56-15.56-15.56zm0 5.66v2.83c3.9 0 7.07 3.17 7.07 7.07h2.83c0-5.47-4.43-9.9-9.9-9.9z" /></React.Fragment> , 'RssFeed');
(window.webpackJsonp=window.webpackJsonp||[]).push([[7],{TbC0:function(l,n,t){"use strict";t.r(n);var u=t("CcnG"),e=function(){},a=t("t68o"),i=t("zbXB"),r=t("NcP4"),o=t("xYTU"),c=t("pMnS"),s=t("lzlj"),b=t("FVSy"),p=t("21Lb"),f=t("OzfB"),d=t("zh/F"),g=t("coki"),m=t("bujt"),h=t("UodH"),y=t("dWZg"),v=t("lLAP"),Z=t("wFw1"),k=t("ZYCi"),x=t("Ip0R"),R=t("Fzqc"),Q=function(){function l(){}return l.isString=function(l){return"string"==typeof l||l instanceof String},l.caseInsensitiveSort=function(n,t){return l.isString(n)&&l.isString(t)?n.localeCompare(t):l.defaultCompare(n,t)},l.defaultCompare=function(l,n){return l===n?0:null==l?1:null==n?-1:l>n?1:-1},l.parseExpression=function(l){return(l=(l=l.replace(/\[(\w+)\]/g,".$1")).replace(/^\./,"")).split(".")},l.getValue=function(l,n){for(var t=0,u=n.length;t<u;++t){var e=n[t];if(!(e in l))return;l=l[e]}return l},l.setValue=function(l,n,t){var u;for(u=0;u<t.length-1;u++)l=l[t[u]];l[t[u]]=n},l.prototype.transform=function(l,n,t,u,e){return void 0===u&&(u=!1),l?Array.isArray(n)?this.multiExpressionTransform(l,n,t,u,e):Array.isArray(l)?this.sortArray(l.slice(),n,t,u,e):"object"==typeof l?this.transformObject(Object.assign({},l),n,t,u,e):l:l},l.prototype.sortArray=function(n,t,u,e,a){var i,r=t&&-1!==t.indexOf(".");r&&(t=l.parseExpression(t)),i=a&&"function"==typeof a?a:e?l.caseInsensitiveSort:l.defaultCompare;var o=n.sort(function(n,u){return t?r?i(l.getValue(n,t),l.getValue(u,t)):n&&u?i(n[t],u[t]):i(n,u):i(n,u)});return u?o.reverse():o},l.prototype.transformObject=function(n,t,u,e,a){var i=l.parseExpression(t),r=i.pop(),o=l.getValue(n,i);return Array.isArray(o)||(i.push(r),r=null,o=l.getValue(n,i)),o?(l.setValue(n,this.transform(o,r,u,e),i),n):n},l.prototype.multiExpressionTransform=function(l,n,t,u,e){var a=this;return void 0===u&&(u=!1),n.reverse().reduce(function(l,n){return a.transform(l,n,t,u,e)},l)},l}(),S=function(){},L=t("h1+l"),w=t("6W14"),A=function(){function l(l,n){this.employeesService=l,this.editNameService=n}return l.prototype.ngOnInit=function(){},l.prototype.openDialogEditName=function(l){this.editNameService.openDialog(l)},l}(),O=u.Pa({encapsulation:0,styles:[['@charset "UTF-8";.container[_ngcontent-%COMP%]{text-align:center;padding:1em}p[_ngcontent-%COMP%]{margin:2px}q[_ngcontent-%COMP%]{font-style:italic;quotes:"\xab " " \xbb"}button[_ngcontent-%COMP%]{width:100vh;text-align:center}']],data:{}});function I(l){return u.kb(0,[(l()(),u.Ra(0,0,null,null,71,null,null,null,null,null,null,null)),(l()(),u.ib(-1,null,["\n "])),(l()(),u.Ra(2,0,null,null,68,"div",[],null,null,null,null,null)),(l()(),u.ib(-1,null,["\n "])),(l()(),u.Ra(4,0,null,null,65,"mat-card",[["class","mat-card"],["style","width:300px"]],null,null,null,s.b,s.a)),u.Qa(5,49152,null,0,b.a,[],null,null),(l()(),u.ib(-1,0,["\n "])),(l()(),u.Ra(7,0,null,0,15,"mat-card-title",[["class","mat-card-title"],["fxLayout","row wrap"],["fxLayoutAlign","center center"]],null,null,null,null,null)),u.Qa(8,737280,null,0,p.e,[f.g,u.k,f.k],{layout:[0,"layout"]},null),u.Qa(9,737280,null,0,p.d,[f.g,u.k,[6,p.e],f.k],{align:[0,"align"]},null),u.Qa(10,16384,null,0,b.g,[],null,null),(l()(),u.ib(-1,null,[" \n "])),(l()(),u.Ra(12,0,null,null,9,"span",[],null,[[null,"dblclick"]],function(l,n,t){var u=!0;return"dblclick"===n&&(u=!1!==l.component.openDialogEditName(l.parent.parent.context.$implicit.nodeAddress)&&u),u},null,null)),(l()(),u.ib(-1,null,[" \n "])),(l()(),u.Ra(14,0,null,null,1,"span",[],null,null,null,null,null)),(l()(),u.ib(15,null,[" "," "])),(l()(),u.ib(-1,null,[" \xa0\n "])),(l()(),u.Ra(17,0,null,null,3,"svg-icon",[["class","logo"],["src","../../../assets/edit.svg"]],null,[[null,"click"]],function(l,n,t){var u=!0;return"click"===n&&(u=!1!==l.component.openDialogEditName(l.parent.parent.context.$implicit.nodeAddress)&&u),u},d.b,d.a)),u.Qa(18,1032192,null,0,g.c,[u.k,u.t,u.E,g.d],{src:[0,"src"],svgStyle:[1,"svgStyle"]},null),u.eb(19,{"width.px":0,"height.px":1,fill:2}),(l()(),u.ib(-1,0,[" "])),(l()(),u.ib(-1,null,["\n "])),(l()(),u.ib(-1,null,["\n "])),(l()(),u.ib(-1,0,["\n "])),(l()(),u.Ra(24,0,null,0,31,"mat-card-content",[["class","mat-card-content"]],null,null,null,null,null)),u.Qa(25,16384,null,0,b.b,[],null,null),(l()(),u.ib(-1,null,["\n "])),(l()(),u.Ra(27,0,null,null,27,"div",[["fxLayout","colum"],["fxLayoutAlign","center center"]],null,null,null,null,null)),u.Qa(28,737280,null,0,p.e,[f.g,u.k,f.k],{layout:[0,"layout"]},null),u.Qa(29,737280,null,0,p.d,[f.g,u.k,[6,p.e],f.k],{align:[0,"align"]},null),(l()(),u.ib(-1,null,["\n "])),(l()(),u.Ra(31,0,null,null,14,"div",[],null,null,null,null,null)),(l()(),u.ib(-1,null,["\n Temperature "])),(l()(),u.Ra(33,0,null,null,1,"b",[],null,null,null,null,null)),(l()(),u.ib(34,null,["",""])),(l()(),u.ib(-1,null,[" \xb0C "])),(l()(),u.Ra(36,0,null,null,0,"br",[],null,null,null,null,null)),(l()(),u.ib(-1,null,["\n Humidity "])),(l()(),u.Ra(38,0,null,null,1,"b",[],null,null,null,null,null)),(l()(),u.ib(39,null,["",""])),(l()(),u.ib(-1,null,[" % "])),(l()(),u.Ra(41,0,null,null,0,"br",[],null,null,null,null,null)),(l()(),u.ib(-1,null,["\n Heart Rate "])),(l()(),u.Ra(43,0,null,null,1,"b",[],null,null,null,null,null)),(l()(),u.ib(44,null,["",""])),(l()(),u.ib(-1,null,[" BPM \n "])),(l()(),u.ib(-1,null,["\n "])),(l()(),u.Ra(47,0,null,null,6,"div",[],null,null,null,null,null)),(l()(),u.ib(-1,null,["\n \xa0\xa0\xa0\xa0\xa0\xa0\n "])),(l()(),u.Ra(49,0,null,null,3,"svg-icon",[["class","logo"],["src","../../../assets/circle.svg"]],null,null,null,d.b,d.a)),u.Qa(50,1032192,null,0,g.c,[u.k,u.t,u.E,g.d],{src:[0,"src"],svgStyle:[1,"svgStyle"]},null),u.eb(51,{"width.px":0,"height.px":1,fill:2}),(l()(),u.ib(-1,0,[" "])),(l()(),u.ib(-1,null,["\n "])),(l()(),u.ib(-1,null,["\n "])),(l()(),u.ib(-1,null,["\n "])),(l()(),u.ib(-1,0,["\n "])),(l()(),u.Ra(57,0,null,1,11,"mat-card-footer",[["class","mat-card-footer"],["fxLayoutAlign","center center"]],null,null,null,null,null)),u.Qa(58,737280,null,0,p.d,[f.g,u.k,[8,null],f.k],{align:[0,"align"]},null),u.Qa(59,16384,null,0,b.c,[],null,null),(l()(),u.ib(-1,null,["\n "])),(l()(),u.Ra(61,0,null,null,6,"button",[["color","primary"],["mat-raised-button",""],["routerLinkActive","active"]],[[8,"disabled",0],[2,"_mat-animation-noopable",null]],[[null,"click"]],function(l,n,t){var e=!0;return"click"===n&&(e=!1!==u.bb(l,63).onClick()&&e),e},m.d,m.b)),u.Qa(62,180224,null,0,h.b,[u.k,y.a,v.g,[2,Z.a]],{color:[0,"color"]},null),u.Qa(63,16384,[[1,4]],0,k.m,[k.l,k.a,[8,null],u.E,u.k],{routerLink:[0,"routerLink"]},null),u.Qa(64,1720320,null,2,k.n,[k.l,u.k,u.E,u.h],{routerLinkActive:[0,"routerLinkActive"]},null),u.gb(603979776,1,{links:1}),u.gb(603979776,2,{linksWithHrefs:1}),(l()(),u.ib(-1,0,[" Details "])),(l()(),u.ib(-1,null,["\n "])),(l()(),u.ib(-1,0,["\n "])),(l()(),u.ib(-1,null,["\n "])),(l()(),u.ib(-1,null,["\n "]))],function(l,n){l(n,8,0,"row wrap"),l(n,9,0,"center center"),l(n,18,0,"../../../assets/edit.svg",l(n,19,0,15,15,"grey")),l(n,28,0,"colum"),l(n,29,0,"center center"),l(n,50,0,"../../../assets/circle.svg",l(n,51,0,70,70,"green")),l(n,58,0,"center center"),l(n,62,0,"primary"),l(n,63,0,u.Ta(1,"/details/",n.parent.parent.context.$implicit.nodeAddress,"")),l(n,64,0,"active")},function(l,n){l(n,15,0,n.parent.parent.context.$implicit.name),l(n,34,0,n.parent.parent.context.$implicit.getLastTimeserie().temperature),l(n,39,0,n.parent.parent.context.$implicit.getLastTimeserie().humidity),l(n,44,0,n.parent.parent.context.$implicit.getLastTimeserie().heartRate),l(n,61,0,u.bb(n,62).disabled||null,"NoopAnimations"===u.bb(n,62)._animationMode)})}function j(l){return u.kb(0,[(l()(),u.Ra(0,0,null,null,4,null,null,null,null,null,null,null)),(l()(),u.ib(-1,null,["\n "])),(l()(),u.Ia(16777216,null,null,1,null,I)),u.Qa(3,16384,null,0,x.k,[u.Q,u.N],{ngIf:[0,"ngIf"]},null),(l()(),u.ib(-1,null,["\n "]))],function(l,n){l(n,3,0,n.parent.context.$implicit.name)},null)}function C(l){return u.kb(0,[(l()(),u.Ra(0,0,null,null,4,null,null,null,null,null,null,null)),(l()(),u.ib(-1,null,["\n "])),(l()(),u.Ia(16777216,null,null,1,null,j)),u.Qa(3,16384,null,0,x.k,[u.Q,u.N],{ngIf:[0,"ngIf"]},null),(l()(),u.ib(-1,null,[" \n "]))],function(l,n){l(n,3,0,n.context.$implicit)},null)}function E(l){return u.kb(0,[(l()(),u.Ra(0,0,null,null,63,null,null,null,null,null,null,null)),(l()(),u.ib(-1,null,["\n "])),(l()(),u.Ra(2,0,null,null,60,"div",[],null,null,null,null,null)),(l()(),u.ib(-1,null,["\n "])),(l()(),u.Ra(4,0,null,null,57,"mat-card",[["class","mat-card"],["style","width:300px"]],null,null,null,s.b,s.a)),u.Qa(5,49152,null,0,b.a,[],null,null),(l()(),u.ib(-1,0,["\n "])),(l()(),u.Ra(7,0,null,0,7,"mat-card-title",[["class","mat-card-title"],["fxLayout","row wrap"],["fxLayoutAlign","center center"]],null,null,null,null,null)),u.Qa(8,737280,null,0,p.e,[f.g,u.k,f.k],{layout:[0,"layout"]},null),u.Qa(9,737280,null,0,p.d,[f.g,u.k,[6,p.e],f.k],{align:[0,"align"]},null),u.Qa(10,16384,null,0,b.g,[],null,null),(l()(),u.ib(-1,null,[" \n "])),(l()(),u.Ra(12,0,null,null,1,"span",[],null,[[null,"dblclick"]],function(l,n,t){var u=!0;return"dblclick"===n&&(u=!1!==l.component.openDialogEditName(l.parent.parent.context.$implicit.nodeAddress)&&u),u},null,null)),(l()(),u.ib(13,null,[" \n ","\n "])),(l()(),u.ib(-1,null,["\n "])),(l()(),u.ib(-1,0,["\n "])),(l()(),u.Ra(16,0,null,0,31,"mat-card-content",[["class","mat-card-content"]],null,null,null,null,null)),u.Qa(17,16384,null,0,b.b,[],null,null),(l()(),u.ib(-1,null,["\n "])),(l()(),u.Ra(19,0,null,null,27,"div",[["fxLayout","colum"],["fxLayoutAlign","center center"]],null,null,null,null,null)),u.Qa(20,737280,null,0,p.e,[f.g,u.k,f.k],{layout:[0,"layout"]},null),u.Qa(21,737280,null,0,p.d,[f.g,u.k,[6,p.e],f.k],{align:[0,"align"]},null),(l()(),u.ib(-1,null,["\n "])),(l()(),u.Ra(23,0,null,null,14,"div",[],null,null,null,null,null)),(l()(),u.ib(-1,null,["\n Temperature "])),(l()(),u.Ra(25,0,null,null,1,"b",[],null,null,null,null,null)),(l()(),u.ib(26,null,["",""])),(l()(),u.ib(-1,null,[" \xb0C "])),(l()(),u.Ra(28,0,null,null,0,"br",[],null,null,null,null,null)),(l()(),u.ib(-1,null,["\n Humidity "])),(l()(),u.Ra(30,0,null,null,1,"b",[],null,null,null,null,null)),(l()(),u.ib(31,null,["",""])),(l()(),u.ib(-1,null,[" % "])),(l()(),u.Ra(33,0,null,null,0,"br",[],null,null,null,null,null)),(l()(),u.ib(-1,null,["\n Heart Rate "])),(l()(),u.Ra(35,0,null,null,1,"b",[],null,null,null,null,null)),(l()(),u.ib(36,null,["",""])),(l()(),u.ib(-1,null,[" BPM \n "])),(l()(),u.ib(-1,null,["\n "])),(l()(),u.Ra(39,0,null,null,6,"div",[],null,null,null,null,null)),(l()(),u.ib(-1,null,["\n \xa0\xa0\xa0\xa0\xa0\xa0\n "])),(l()(),u.Ra(41,0,null,null,3,"svg-icon",[["class","logo"],["src","assets/circle.svg"]],null,null,null,d.b,d.a)),u.Qa(42,1032192,null,0,g.c,[u.k,u.t,u.E,g.d],{src:[0,"src"],svgStyle:[1,"svgStyle"]},null),u.eb(43,{"width.px":0,"height.px":1,fill:2}),(l()(),u.ib(-1,0,[" "])),(l()(),u.ib(-1,null,["\n "])),(l()(),u.ib(-1,null,["\n "])),(l()(),u.ib(-1,null,["\n "])),(l()(),u.ib(-1,0,["\n "])),(l()(),u.Ra(49,0,null,1,11,"mat-card-footer",[["class","mat-card-footer"],["fxLayoutAlign","center center"]],null,null,null,null,null)),u.Qa(50,737280,null,0,p.d,[f.g,u.k,[8,null],f.k],{align:[0,"align"]},null),u.Qa(51,16384,null,0,b.c,[],null,null),(l()(),u.ib(-1,null,["\n "])),(l()(),u.Ra(53,0,null,null,6,"button",[["color","primary"],["mat-raised-button",""],["routerLinkActive","active"]],[[8,"disabled",0],[2,"_mat-animation-noopable",null]],[[null,"click"]],function(l,n,t){var e=!0;return"click"===n&&(e=!1!==u.bb(l,55).onClick()&&e),e},m.d,m.b)),u.Qa(54,180224,null,0,h.b,[u.k,y.a,v.g,[2,Z.a]],{color:[0,"color"]},null),u.Qa(55,16384,[[3,4]],0,k.m,[k.l,k.a,[8,null],u.E,u.k],{routerLink:[0,"routerLink"]},null),u.Qa(56,1720320,null,2,k.n,[k.l,u.k,u.E,u.h],{routerLinkActive:[0,"routerLinkActive"]},null),u.gb(603979776,3,{links:1}),u.gb(603979776,4,{linksWithHrefs:1}),(l()(),u.ib(-1,0,[" Details "])),(l()(),u.ib(-1,null,["\n "])),(l()(),u.ib(-1,0,["\n "])),(l()(),u.ib(-1,null,["\n "])),(l()(),u.ib(-1,null,["\n "]))],function(l,n){l(n,8,0,"row wrap"),l(n,9,0,"center center"),l(n,20,0,"colum"),l(n,21,0,"center center"),l(n,42,0,"assets/circle.svg",l(n,43,0,70,70,"green")),l(n,50,0,"center center"),l(n,54,0,"primary"),l(n,55,0,u.Ta(1,"/details/",n.parent.parent.context.$implicit.nodeAddress,"")),l(n,56,0,"active")},function(l,n){l(n,13,0,n.parent.parent.context.$implicit.nodeAddress),l(n,26,0,n.parent.parent.context.$implicit.getLastTimeserie().temperature),l(n,31,0,n.parent.parent.context.$implicit.getLastTimeserie().humidity),l(n,36,0,n.parent.parent.context.$implicit.getLastTimeserie().heartRate),l(n,53,0,u.bb(n,54).disabled||null,"NoopAnimations"===u.bb(n,54)._animationMode)})}function N(l){return u.kb(0,[(l()(),u.Ra(0,0,null,null,4,null,null,null,null,null,null,null)),(l()(),u.ib(-1,null,["\n "])),(l()(),u.Ia(16777216,null,null,1,null,E)),u.Qa(3,16384,null,0,x.k,[u.Q,u.N],{ngIf:[0,"ngIf"]},null),(l()(),u.ib(-1,null,["\n "]))],function(l,n){l(n,3,0,!n.parent.context.$implicit.name)},null)}function B(l){return u.kb(0,[(l()(),u.Ra(0,0,null,null,4,null,null,null,null,null,null,null)),(l()(),u.ib(-1,null,["\n "])),(l()(),u.Ia(16777216,null,null,1,null,N)),u.Qa(3,16384,null,0,x.k,[u.Q,u.N],{ngIf:[0,"ngIf"]},null),(l()(),u.ib(-1,null,[" \n "]))],function(l,n){l(n,3,0,n.context.$implicit)},null)}function T(l){return u.kb(0,[(l()(),u.Ra(0,0,null,null,12,"div",[["fxLayout","row wrap"],["fxLayout.xs","column"],["fxLayoutAlign","center center"],["fxLayoutGap","10px grid"]],null,null,null,null,null)),u.Qa(1,737280,null,0,p.e,[f.g,u.k,f.k],{layout:[0,"layout"],layoutXs:[1,"layoutXs"]},null),u.Qa(2,1785856,null,0,p.f,[f.g,u.k,[6,p.e],u.z,R.b,f.k],{gap:[0,"gap"]},null),u.Qa(3,737280,null,0,p.d,[f.g,u.k,[6,p.e],f.k],{align:[0,"align"]},null),(l()(),u.ib(-1,null,["\n\n "])),(l()(),u.Ia(16777216,null,null,2,null,C)),u.Qa(6,278528,null,0,x.j,[u.Q,u.N,u.s],{ngForOf:[0,"ngForOf"]},null),u.db(0,Q,[]),(l()(),u.ib(-1,null,["\n \n "])),(l()(),u.Ia(16777216,null,null,2,null,B)),u.Qa(10,278528,null,0,x.j,[u.Q,u.N,u.s],{ngForOf:[0,"ngForOf"]},null),u.db(0,Q,[]),(l()(),u.ib(-1,null,["\n\n"]))],function(l,n){var t=n.component;l(n,1,0,"row wrap","column"),l(n,2,0,"10px grid"),l(n,3,0,"center center"),l(n,6,0,u.jb(n,6,0,u.bb(n,7).transform(t.employeesService.employees.employees,"name"))),l(n,10,0,u.jb(n,10,0,u.bb(n,11).transform(t.employeesService.employees.employees,"nodeAddress")))},null)}function M(l){return u.kb(0,[(l()(),u.ib(-1,null,["\n"])),(l()(),u.Ia(16777216,null,null,1,null,T)),u.Qa(2,16384,null,0,x.k,[u.Q,u.N],{ngIf:[0,"ngIf"]},null),(l()(),u.ib(-1,null,["\n "]))],function(l,n){l(n,2,0,n.component.employeesService.employees)},null)}var $=u.Na("app-home",A,function(l){return u.kb(0,[(l()(),u.Ra(0,0,null,null,1,"app-home",[],null,null,null,M,O)),u.Qa(1,114688,null,0,A,[L.a,w.a],null,null)],function(l,n){l(n,1,0)},null)},{},{},[]),D=t("eDkP"),U=t("4tE/"),P=t("M2Lx"),V=t("Wf4p"),F=t("o3x0"),H=t("jQLj"),_=t("mVsa"),z=t("uGex"),q=t("v9Dh"),Y=t("4epT"),W=t("ZYjt"),X=t("OkvK"),G=t("wmQ5"),K=t("t/Na"),J=t("gIcY"),ll=t("hUWP"),nl=t("V9q+"),tl=t("4c35"),ul=t("qAlS"),el=t("u7R8"),al=t("de3e"),il=t("/dO6"),rl=t("LC5p"),ol=t("YhbO"),cl=t("jlZm"),sl=t("seP3"),bl=t("r43C"),pl=t("SMsm"),fl=t("/VYK"),dl=t("b716"),gl=t("0/Q6"),ml=t("Z+uX"),hl=t("Blfk"),yl=t("9It4"),vl=t("Nsh5"),Zl=t("kWGw"),kl=t("w+lc"),xl=t("vARd"),Rl=t("Lwpp"),Ql=t("y4qS"),Sl=t("BHnd"),Ll=t("La40"),wl=t("8mMr"),Al=t("vvyD"),Ol=t("PCNd"),Il={title:"Overview"},jl=function(){},Cl=t("YSh2");t.d(n,"HomeModuleNgFactory",function(){return El});var El=u.Oa(e,[],function(l){return u.Ya([u.Za(512,u.j,u.Da,[[8,[a.a,i.b,i.a,r.a,o.a,o.b,c.a,$]],[3,u.j],u.x]),u.Za(4608,x.m,x.l,[u.u,[2,x.w]]),u.Za(4608,f.i,f.h,[f.d,f.f]),u.Za(5120,u.b,function(l,n){return[f.l(l,n)]},[x.d,u.B]),u.Za(4608,D.a,D.a,[D.g,D.c,u.j,D.f,D.d,u.r,u.z,x.d,R.b]),u.Za(5120,D.h,D.i,[D.a]),u.Za(5120,U.a,U.b,[D.a]),u.Za(4608,P.c,P.c,[]),u.Za(4608,V.d,V.d,[]),u.Za(5120,F.c,F.d,[D.a]),u.Za(4608,F.e,F.e,[D.a,u.r,[2,x.g],[2,F.b],F.c,[3,F.e],D.c]),u.Za(4608,H.h,H.h,[]),u.Za(5120,H.a,H.b,[D.a]),u.Za(5120,_.b,_.g,[D.a]),u.Za(4608,V.c,V.z,[[2,V.h],y.a]),u.Za(5120,z.a,z.b,[D.a]),u.Za(5120,q.a,q.b,[D.a]),u.Za(5120,Y.b,Y.a,[[3,Y.b]]),u.Za(4608,W.f,V.e,[[2,V.i],[2,V.n]]),u.Za(5120,X.b,X.a,[[3,X.b]]),u.Za(4608,G.a,G.a,[]),u.Za(5120,g.d,g.b,[[3,g.d],K.c]),u.Za(4608,J.u,J.u,[]),u.Za(4608,J.e,J.e,[]),u.Za(4608,Q,Q,[]),u.Za(1073742336,x.c,x.c,[]),u.Za(1073742336,f.e,f.e,[]),u.Za(1073742336,R.a,R.a,[]),u.Za(1073742336,p.c,p.c,[]),u.Za(1073742336,ll.b,ll.b,[]),u.Za(1073742336,nl.a,nl.a,[[2,f.j],u.B]),u.Za(1073742336,V.n,V.n,[[2,V.f]]),u.Za(1073742336,y.b,y.b,[]),u.Za(1073742336,V.y,V.y,[]),u.Za(1073742336,V.w,V.w,[]),u.Za(1073742336,V.t,V.t,[]),u.Za(1073742336,tl.g,tl.g,[]),u.Za(1073742336,ul.b,ul.b,[]),u.Za(1073742336,D.e,D.e,[]),u.Za(1073742336,U.c,U.c,[]),u.Za(1073742336,h.c,h.c,[]),u.Za(1073742336,el.a,el.a,[]),u.Za(1073742336,b.e,b.e,[]),u.Za(1073742336,P.d,P.d,[]),u.Za(1073742336,al.c,al.c,[]),u.Za(1073742336,il.b,il.b,[]),u.Za(1073742336,F.k,F.k,[]),u.Za(1073742336,v.a,v.a,[]),u.Za(1073742336,H.i,H.i,[]),u.Za(1073742336,rl.b,rl.b,[]),u.Za(1073742336,ol.c,ol.c,[]),u.Za(1073742336,cl.a,cl.a,[]),u.Za(1073742336,sl.e,sl.e,[]),u.Za(1073742336,V.o,V.o,[]),u.Za(1073742336,bl.b,bl.b,[]),u.Za(1073742336,pl.b,pl.b,[]),u.Za(1073742336,fl.c,fl.c,[]),u.Za(1073742336,dl.b,dl.b,[]),u.Za(1073742336,gl.c,gl.c,[]),u.Za(1073742336,_.e,_.e,[]),u.Za(1073742336,V.A,V.A,[]),u.Za(1073742336,V.q,V.q,[]),u.Za(1073742336,z.c,z.c,[]),u.Za(1073742336,q.c,q.c,[]),u.Za(1073742336,Y.c,Y.c,[]),u.Za(1073742336,ml.a,ml.a,[]),u.Za(1073742336,hl.c,hl.c,[]),u.Za(1073742336,yl.a,yl.a,[]),u.Za(1073742336,vl.h,vl.h,[]),u.Za(1073742336,Zl.c,Zl.c,[]),u.Za(1073742336,kl.a,kl.a,[]),u.Za(1073742336,xl.d,xl.d,[]),u.Za(1073742336,X.c,X.c,[]),u.Za(1073742336,Rl.d,Rl.d,[]),u.Za(1073742336,G.b,G.b,[]),u.Za(1073742336,Ql.o,Ql.o,[]),u.Za(1073742336,Sl.a,Sl.a,[]),u.Za(1073742336,Ll.a,Ll.a,[]),u.Za(1073742336,wl.b,wl.b,[]),u.Za(1073742336,Al.a,Al.a,[]),u.Za(1073742336,Ol.a,Ol.a,[]),u.Za(1073742336,k.p,k.p,[[2,k.v],[2,k.l]]),u.Za(1073742336,jl,jl,[]),u.Za(1073742336,g.a,g.a,[]),u.Za(1073742336,J.s,J.s,[]),u.Za(1073742336,J.h,J.h,[]),u.Za(1073742336,J.p,J.p,[]),u.Za(1073742336,S,S,[]),u.Za(1073742336,e,e,[]),u.Za(256,il.a,{separatorKeyCodes:[Cl.f]},[]),u.Za(256,V.g,V.k,[]),u.Za(1024,k.j,function(){return[[{path:"",component:A,data:Il}]]},[])])})},coki:function(l,n,t){"use strict";t.d(n,"a",function(){return g}),t.d(n,"d",function(){return p}),t.d(n,"b",function(){return f}),t.d(n,"c",function(){return d});var u=t("mrSG"),e=t("CcnG"),a=(t("t/Na"),t("F/XL")),i=t("XlPw"),r=t("67Y/"),o=t("xMyE"),c=t("9Z1F"),s=t("2WpN"),b=t("S1nX"),p=function(){function l(l){this.http=l,this.iconsByUrl=new Map,this.iconsLoadingByUrl=new Map}return l.prototype.addSvg=function(l,n){if(!this.iconsByUrl.has(l)){var t=document.createElement("DIV");t.innerHTML=n;var u=t.querySelector("svg");this.iconsByUrl.set(l,u)}},l.prototype.loadSvg=function(l){var n=this;if(this.iconsByUrl.has(l))return Object(a.a)(this.iconsByUrl.get(l));if(this.iconsLoadingByUrl.has(l))return this.iconsLoadingByUrl.get(l);var t=this.http.get(l,{responseType:"text"}).pipe(Object(r.a)(function(l){var n=document.createElement("DIV");return n.innerHTML=l,n.querySelector("svg")}),Object(o.a)(function(t){return n.iconsByUrl.set(l,t)}),Object(c.a)(function(l){return console.error(l),Object(i.a)(l)}),Object(s.a)(function(){return n.iconsLoadingByUrl.delete(l)}),Object(b.a)());return this.iconsLoadingByUrl.set(l,t),t},l.prototype.unloadSvg=function(l){this.iconsByUrl.has(l)&&this.iconsByUrl.delete(l)},l}();function f(l,n){return l||new p(n)}new e.A,new e.K;var d=function(){function l(l,n,t,u){this.element=l,this.differs=n,this.renderer=t,this.iconReg=u,this.stretch=!1}return Object.defineProperty(l.prototype,"svgStyle",{set:function(l){this._svgStyle=l,!this.differ&&l&&(this.differ=this.differs.find(l).create())},enumerable:!0,configurable:!0}),l.prototype.ngOnInit=function(){this.init()},l.prototype.ngOnDestroy=function(){this.destroy()},l.prototype.ngOnChanges=function(l){l.src&&(this.svg&&this.destroy(),this.init()),l.stretch&&this.stylize()},l.prototype.ngDoCheck=function(){if(this.svg&&this.differ){var l=this.differ.diff(this._svgStyle);l&&this.applyChanges(l)}},l.prototype.init=function(){var l=this;this.icnSub=this.iconReg.loadSvg(this.src).subscribe(function(n){l.setSvg(n),l.resetDiffer()})},l.prototype.destroy=function(){this.svg=void 0,this.differ=void 0,this.icnSub&&this.icnSub.unsubscribe()},l.prototype.resetDiffer=function(){this._svgStyle&&!this.differ&&(this.differ=this.differs.find(this._svgStyle).create())},l.prototype.setSvg=function(l){if(l){this.svg=l;var n=l.cloneNode(!0),t=this.element.nativeElement;t.innerHTML="",this.renderer.appendChild(t,n),this.stylize()}},l.prototype.stylize=function(){if(this.svg){var l=this.element.nativeElement.firstChild;!0===this.stretch?this.renderer.setAttribute(l,"preserveAspectRatio","none"):!1===this.stretch&&this.renderer.removeAttribute(l,"preserveAspectRatio")}},l.prototype.applyChanges=function(l){var n=this;l.forEachRemovedItem(function(l){return n.setStyle(l.key,null)}),l.forEachAddedItem(function(l){return n.setStyle(l.key,l.currentValue)}),l.forEachChangedItem(function(l){return n.setStyle(l.key,l.currentValue)})},l.prototype.setStyle=function(l,n){var t=Object(u.c)(l.split("."),2),e=t[0],a=t[1],i=this.element.nativeElement.firstChild;null!==(n=null!==n&&a?""+n+a:n)?this.renderer.setStyle(i,e,n):this.renderer.removeStyle(i,e)},l}(),g=function(){}}}]);
import { ADD, TICK } from '../constants/actionTypes' export const initialState = { lastUpdate: 0, light: false, count: 0 } export default (state = initialState, action) => { const { type, ts, light } = action switch (type) { case TICK: { return Object.assign({}, state, { lastUpdate: ts, light: !!light }) } case ADD: { return Object.assign({}, state, { count: state.count + 1 }) } default: { return state } } }
/* Problem: How to Sum Integers 1 to n Example: Input: [1,2,3,4,5,6,7,8,9,10] Output: 55 */ // Solution 1 - Brute Force function sumNumbers(listOfIntegers) { var result = 0; for (var i = 0; i < listOfIntegers.length; i++) { result += listOfIntegers[i]; } return result; } sumNumbers([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); // Time Complexity: O(N) // Solution 2 - (N * (N + 1)) / 2 function sumNumbers(listOfIntegers) { return (listOfIntegers.length * (listOfIntegers.length + 1)) / 2; } sumNumbers([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); // Time Complexity: O(1), no matter how big the list is, solution will always run in constant time
var Whitespace = require('./whitespace'); var wrap = require('./wrap'); var output = []; var whitespace = null; module.exports = function(node, options) { output.length = 0; whitespace = new Whitespace(options, token); generate(node); whitespace = null; return output.join(''); } var types = { 'root': gen_root, 'type': gen_type, 'preprocessor': gen_preprocessor, 'identifier': gen_identifier, 'operator': gen_operator, 'parameter': gen_parameter, 'function_declaration': gen_function, 'function_call': gen_function_call, 'struct_definition': gen_struct_definition, 'scope': gen_scope, 'declarator': gen_declarator, 'declarator_item': gen_declarator_item, 'expression': gen_expression, 'sequence': gen_sequence, 'binary': gen_binary, 'unary': gen_unary, 'ternary': gen_ternary, 'postfix': gen_postfix, 'field_selector': gen_field_selector, 'precision': gen_precision, 'accessor': gen_accessor, 'if_statement': gen_if_statement, 'for_statement': gen_for_statement, 'while_statement': gen_while_statement, 'do_statement': gen_do_statement, 'continue': gen_continue, 'break': gen_break, 'return': gen_return, 'discard': gen_discard, 'float': gen_float, 'int': gen_int, 'bool': gen_bool, }; var noTerminator = { 'root': true, 'preprocessor': true, 'function_declaration' : true, 'if_statement' : true, 'for_statement' : true, 'while_statement' : true, 'scope': true }; var noParens = { 'identifier': true, 'function_call': true, }; var unaryParens = { 'unary': true, 'binary': true, 'ternary': true }; var binaryParens = { 'binary': true, 'ternary': true }; function token(s) { output.push(s); } function last_token() { if (output.length == 0) return null; return output[output.length - 1]; } function list_parameters(a) { for (var i=0; i<a.length; i++) { generate(a[i]); if (i < a.length-1) whitespace.separator(); } } function list_statements(a) { for (var i=0; i<a.length; i++) { if (a[i].type == 'expression' && !a[i].expression) continue; if (a[i].type != 'preprocessor') whitespace.tab(); generate(a[i]); if (!(a[i].type in noTerminator)) whitespace.terminateLine(); } } function statement_body(node, forceSpace) { if (node.type == 'scope') { whitespace.space(); generate(node); } else { if (forceSpace) whitespace.space(true); if (node.type == 'expression' && node.expression == null) { whitespace.terminator(); } else { whitespace.newline(); whitespace.indent(); generate(wrap(node)); whitespace.dedent(); } } } function generate(node) { if (!node) return; var fn = types[node.type]; if (!fn) { return console.warn('Warning: Encountered an AST node that has no generator:', node.type); } return fn(node); } function gen_root(node) { list_statements(node.statements); } function gen_bool(node) { token(node.value); } function gen_type(node) { if (node.qualifier) { token(node.qualifier); whitespace.space(true); } if (node.precision) { token(node.precision); whitespace.space(true); } token(node.name); } function gen_preprocessor(node) { if (last_token() != null && last_token() != '\n') whitespace.newline(true); switch (node.directive) { case '#define': token(node.directive); whitespace.space(true); token(node.identifier); if (node.parameters && node.parameters.length > 0) { token('('); list_parameters(node.parameters); token(')'); } if (node.token_string && node.token_string.length > 0) { whitespace.space(true); token(node.token_string); } whitespace.newline(true); break; case '#ifdef': case '#ifndef': case '#if': case '#elif': token(node.directive); whitespace.space(true); token(node.value); whitespace.newline(true); list_statements(node.guarded_statements); if ('elseBody' in node) generate(node.elseBody); else { if (last_token() != null && last_token() != '\n') whitespace.newline(true); token('#endif'); whitespace.newline(true); } break; case '#else': token(node.directive); whitespace.newline(true); list_statements(node.guarded_statements); if (last_token() != null && last_token() != '\n') whitespace.newline(true); token('#endif'); whitespace.newline(true); break; case '#version': case '#undef': case '#pragma': case '#extension': case '#line': case '#error': case '#include': token(node.directive); whitespace.space(true); token(node.value); whitespace.newline(true); break; } } function gen_identifier(node) { token(node.name); } function gen_operator(node) { token(node.operator); } function gen_declarator(node) { generate(node.typeAttribute); whitespace.space(true); list_parameters(node.declarators); } function gen_declarator_item(node) { generate(node.name); if ('arraySize' in node) { token('['); generate(node.arraySize); token(']'); } if ('initializer' in node) { whitespace.space(); token('='); whitespace.space(); generate(node.initializer); } } function gen_expression(node) { generate(node.expression); } function gen_sequence(node) { a = node.expressions for (var i=0; i<a.length; i++) { generate(a[i]); if (i < a.length-1) whitespace.separator(); } } function gen_binary(node) { switch (node.operator.operator) { case '=': generate(node.left); whitespace.space(); generate(node.operator); whitespace.space(); generate(node.right); break; default: if (node.left.type in binaryParens) { token('('); generate(node.left); token(')'); } else { generate(node.left); } whitespace.space(); generate(node.operator); whitespace.space(); if (node.right.type in binaryParens) { token('('); generate(node.right); token(')'); } else { generate(node.right); } break; } } function gen_unary(node) { generate(node.operator); if (node.expression.type in unaryParens) { token('('); generate(node.expression); token(')'); } else { generate(node.expression); } } function gen_parameter(node) { if (node.typeQualifier) { token(node.typeQualifier); whitespace.space(true); } if (node.parameterQualifier) { token(node.parameterQualifier); whitespace.space(true); } token(node.type_name); whitespace.space(true); token(node.name); if ('arraySize' in node) { token('['); generate(node.arraySize); token(']'); } } function gen_function(node) { generate(node.returnType); whitespace.space(true); token(node.name); token('('); list_parameters(node.parameters); token(')'); whitespace.space(); generate(node.body); } function gen_function_call(node) { token(node.function_name); token('('); list_parameters(node.parameters); token(')'); } function gen_struct_definition(node) { token('struct'); whitespace.space(true); token(node.name) whitespace.space(); token('{'); whitespace.newline(); whitespace.indent(); list_statements(node.members); whitespace.dedent(); whitespace.tab(); token('}'); if ('declarators' in node && node.declarators.length > 0) { whitespace.space(); list_parameters(node.declarators); } } function gen_scope(node, noNewline) { token('{'); whitespace.newline(); whitespace.indent(); list_statements(node.statements); whitespace.dedent(); whitespace.tab(); token('}'); if (!noNewline) whitespace.newline(); } function gen_postfix(node) { if (node.expression.type in noParens) { generate(node.expression); } else { token('('); generate(node.expression); token(')'); } generate(node.operator); } function gen_field_selector(node) { token('.'); token(node.selection); } function gen_accessor(node) { token('['); generate(node.index); token(']'); } function gen_float(node) { token(node.value); } function gen_int(node) { token(node.value); } function gen_bool(node) { token(node.value); } function gen_precision(node) { token(node.type); whitespace.space(true); token(node.precision); whitespace.space(true); token(node.typeName); } function gen_if_statement(node, isElseIf) { if (isElseIf) { whitespace.tab(); token('else if'); } else token('if'); whitespace.space(); token('('); generate(node.condition); token(')'); statement_body(node.body); if (node.elseBody) { if (node.elseBody.type == 'if_statement') { gen_if_statement(node.elseBody, true); } else { whitespace.tab(); token('else'); // Only force space after statement if newlines are stripped // and we actually have a statement following the 'else'. var forceSpace = false; if (whitespace.options.newline == '') forceSpace = true; if (node.elseBody.type == 'expression' && node.elseBody.expression == null) forceSpace = false; statement_body(node.elseBody, forceSpace); } } } function gen_return(node) { token('return'); whitespace.space(true); generate(node.value); } function gen_ternary(node) { generate(node.condition); whitespace.space(); token('?'); whitespace.space(); generate(node.is_true); whitespace.space(); token(':'); whitespace.space(); generate(node.is_false); } function gen_for_statement(node) { token('for'); whitespace.space(); token('('); generate(node.initializer); whitespace.terminator(); whitespace.space(); generate(node.condition); whitespace.terminator(); whitespace.space(); generate(node.increment); token(')'); statement_body(node.body); } function gen_while_statement(node) { token('while'); whitespace.space(); token('('); generate(node.condition); token(')'); statement_body(node.body); } function gen_do_statement(node) { token('do'); whitespace.space(); gen_scope(node.body, true); whitespace.space(); token('while'); whitespace.space(); token('('); generate(node.condition); token(')'); } function gen_continue(node) { token('continue'); } function gen_break(node) { token('break'); } function gen_discard(node) { token('discard'); }
import React from "react" import PropTypes from "prop-types" export default function HTML(props) { return ( <html {...props.htmlAttributes}> <head> <meta charSet="utf-8" /> <meta httpEquiv="x-ua-compatible" content="ie=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" /> <link rel="stylesheet" href="https://cdn.rawgit.com/konpa/devicon/df6431e323547add1b4cf45992913f15286456d3/devicon.min.css" /> {props.headComponents} </head> <body {...props.bodyAttributes}> {props.preBodyComponents} <noscript key="noscript" id="gatsby-noscript"> WOT M8? </noscript> <div key={`body`} id="___gatsby" dangerouslySetInnerHTML={{ __html: props.body }} /> {props.postBodyComponents} </body> </html> ) } HTML.propTypes = { htmlAttributes: PropTypes.object, headComponents: PropTypes.array, bodyAttributes: PropTypes.object, preBodyComponents: PropTypes.array, body: PropTypes.string, postBodyComponents: PropTypes.array, }
import React from 'react'; import ReactDOM from 'react-dom'; import './scss/main.scss'; import App from './App'; import * as serviceWorker from './serviceWorker'; ReactDOM.render(<App />, document.getElementById('root')); serviceWorker.register();
import { html, css, LitElement } from 'lit-element'; export class LiveSearchInput extends LitElement { static get styles() { return css` :host { display: block; padding: 25px; color: var(--live-search-text-color, #000); } .highlight { font-weight: bold; } `; } static get properties() { return { suggestions: { type: Array }, searchString: { type: String }, }; } constructor() { super(); this.suggestions = []; this.searchString = ''; } render() { return html` <label id="label" >Encuentra profesionales de confianza <input type="text" @keyup=${this.onKeyup} /> </label> <ul role="listbox" aria-labelledby="label"> ${this.suggestions.map((suggestion, index) => { return html` ${LiveSearchInput.renderHighlightSuggestion( suggestion, this.searchString, index )} `; })} </ul> `; } static renderHighlightSuggestion(text, search, index) { if (text.includes(search)) { const [init, match, end] = LiveSearchInput.splitBySearch(text, search); return html`<li id="listbox-${index}" role="option" aria-selected="false"> ${init}<span class="highlight">${match}</span>${end} </li>`; } return html``; } static splitBySearch(text, search) { const index = text.indexOf(search); return [ text.substring(0, index), text.substring(index, index + search.length), text.substring(index + search.length), ]; } onKeyup(detail) { this.searchString = detail?.target?.value; this.trigger('live-search-string', { string: this.searchString }); } trigger(eventName, detail) { this.dispatchEvent( new CustomEvent(eventName, { detail, bubbles: true, composed: true, }) ); } }
const router = require("express").Router(); const db = require("../models"); router.get('/api/workouts', (req, res) => { db.Workout.find({}) .then(workoutData => { console.log(workoutData); workoutData.forEach(workout => { let total = 0; workout.exercises.forEach(ex => { total += ex.duration; }) workout.totalDuration = total; }) res.json(workoutData); }) .catch(err => { res.status(404).json(err); }); }); router.post('/api/workouts', (req, res) => { db.Workout.create(req.body) .then(workoutData => { res.json(workoutData); }) .catch(err => { res.status(400).json(err); }); }) router.put('/api/workouts/:id', (req, res) => { db.Workout.findByIdAndUpdate({ _id: req.params.id }, { $push: { exercises: req.body }, $inc: { totalDuration: req.body.duration } }) .then(workoutData => { res.json(workoutData); }) .catch(err => { res.status(400).json(err); }) }) router.get('/api/workouts/range', (req, res) => { db.Workout.find({}) .then(workoutData => { res.json(workoutData); }) .catch(err => { res.status(400).json(err); }); }) module.exports = router;
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.TreasureChest = void 0; var _react = _interopRequireDefault(require("react")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } 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); } const TreasureChest = props => /*#__PURE__*/_react.default.createElement("svg", _extends({ width: "24", height: "24", viewBox: "0 0 24 24", fill: "none", xmlns: "http://www.w3.org/2000/svg" }, props), /*#__PURE__*/_react.default.createElement("path", { d: "M5 4H19C19.7956 4 20.5587 4.31607 21.1213 4.87868C21.6839 5.44129 22 6.20435 22 7V11H15V10H9V11H2V7C2 6.20435 2.31607 5.44129 2.87868 4.87868C3.44129 4.31607 4.20435 4 5 4V4ZM11 11H13V13H11V11ZM2 12H9V13L11 15H13L15 13V12H22V20H2V12Z" })); exports.TreasureChest = TreasureChest;