.'
);
}
}
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 = {
staticKeys: ['staticStyle'],
transformNode: transformNode$1,
genData: genData$1
};
var modules$1 = [
klass,
style
];
/* */
/**
* 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: ("\"" + value + "\""),
callback: ("function (" + baseValueExpression + ") {" + assignment + "}")
};
}
/**
* Cross-platform codegen helper for generating v-model value assignment code.
*/
function genAssignmentCode (
value,
assignment
) {
var modelRs = parseModel(value);
if (modelRs.idx === null) {
return (value + "=" + assignment)
} else {
return ("$set(" + (modelRs.exp) + ", " + (modelRs.idx) + ", " + assignment + ")")
}
}
/**
* parse directive model to do the array update transform. a[idx] = val => $$a.splice($$idx, 1, val)
*
* for loop possible cases:
*
* - test
* - test[idx]
* - test[test1[idx]]
* - test["a"][idx]
* - xxx.test[a[a].test1[idx]]
* - test.xxx.a["asa"][test1[idx]]
*
*/
var len;
var str;
var chr;
var index;
var expressionPos;
var expressionEndPos;
function parseModel (val) {
str = val;
len = str.length;
index = expressionPos = expressionEndPos = 0;
if (val.indexOf('[') < 0 || val.lastIndexOf(']') < len - 1) {
return {
exp: val,
idx: null
}
}
while (!eof()) {
chr = next();
/* istanbul ignore if */
if (isStringStart(chr)) {
parseString(chr);
} else if (chr === 0x5B) {
parseBracket(chr);
}
}
return {
exp: val.substring(0, expressionPos),
idx: val.substring(expressionPos + 1, expressionEndPos)
}
}
function next () {
return str.charCodeAt(++index)
}
function eof () {
return index >= len
}
function isStringStart (chr) {
return chr === 0x22 || chr === 0x27
}
function parseBracket (chr) {
var inBracket = 1;
expressionPos = index;
while (!eof()) {
chr = next();
if (isStringStart(chr)) {
parseString(chr);
continue
}
if (chr === 0x5B) { inBracket++; }
if (chr === 0x5D) { inBracket--; }
if (inBracket === 0) {
expressionEndPos = index;
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;
{
var dynamicType = el.attrsMap['v-bind:type'] || el.attrsMap[':type'];
if (tag === 'input' && dynamicType) {
warn$1(
"
:\n" +
"v-model does not support dynamic input types. Use v-if branches instead."
);
}
// 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."
);
}
}
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.'
);
}
// 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, CHECKBOX_RADIO_TOKEN,
"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&&(" + value + "=$$a.concat($$v))}" +
"else{$$i>-1&&(" + 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, CHECKBOX_RADIO_TOKEN, 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;
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()');
}
}
/* */
function text (el, dir) {
if (dir.value) {
addProp(el, 'textContent', ("_s(" + (dir.value) + ")"));
}
}
/* */
function html (el, dir) {
if (dir.value) {
addProp(el, 'innerHTML', ("_s(" + (dir.value) + ")"));
}
}
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 commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
function createCommonjsModule(fn, module) {
return module = { exports: {} }, fn(module, module.exports), module.exports;
}
var he = createCommonjsModule(function (module, exports) {
/*! https://mths.be/he v1.1.1 by @mathias | MIT license */
(function(root) {
// Detect free variables `exports`.
var freeExports = 'object' == 'object' && exports;
// Detect free variable `module`.
var freeModule = 'object' == 'object' && module &&
module.exports == freeExports && module;
// Detect free variable `global`, from Node.js or Browserified code,
// and use it as `root`.
var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal;
if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) {
root = freeGlobal;
}
/*--------------------------------------------------------------------------*/
// All astral symbols.
var regexAstralSymbols = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
// All ASCII symbols (not just printable ASCII) except those listed in the
// first column of the overrides table.
// https://html.spec.whatwg.org/multipage/syntax.html#table-charref-overrides
var regexAsciiWhitelist = /[\x01-\x7F]/g;
// All BMP symbols that are not ASCII newlines, printable ASCII symbols, or
// code points listed in the first column of the overrides table on
// https://html.spec.whatwg.org/multipage/syntax.html#table-charref-overrides.
var regexBmpWhitelist = /[\x01-\t\x0B\f\x0E-\x1F\x7F\x81\x8D\x8F\x90\x9D\xA0-\uFFFF]/g;
var regexEncodeNonAscii = /<\u20D2|=\u20E5|>\u20D2|\u205F\u200A|\u219D\u0338|\u2202\u0338|\u2220\u20D2|\u2229\uFE00|\u222A\uFE00|\u223C\u20D2|\u223D\u0331|\u223E\u0333|\u2242\u0338|\u224B\u0338|\u224D\u20D2|\u224E\u0338|\u224F\u0338|\u2250\u0338|\u2261\u20E5|\u2264\u20D2|\u2265\u20D2|\u2266\u0338|\u2267\u0338|\u2268\uFE00|\u2269\uFE00|\u226A\u0338|\u226A\u20D2|\u226B\u0338|\u226B\u20D2|\u227F\u0338|\u2282\u20D2|\u2283\u20D2|\u228A\uFE00|\u228B\uFE00|\u228F\u0338|\u2290\u0338|\u2293\uFE00|\u2294\uFE00|\u22B4\u20D2|\u22B5\u20D2|\u22D8\u0338|\u22D9\u0338|\u22DA\uFE00|\u22DB\uFE00|\u22F5\u0338|\u22F9\u0338|\u2933\u0338|\u29CF\u0338|\u29D0\u0338|\u2A6D\u0338|\u2A70\u0338|\u2A7D\u0338|\u2A7E\u0338|\u2AA1\u0338|\u2AA2\u0338|\u2AAC\uFE00|\u2AAD\uFE00|\u2AAF\u0338|\u2AB0\u0338|\u2AC5\u0338|\u2AC6\u0338|\u2ACB\uFE00|\u2ACC\uFE00|\u2AFD\u20E5|[\xA0-\u0113\u0116-\u0122\u0124-\u012B\u012E-\u014D\u0150-\u017E\u0192\u01B5\u01F5\u0237\u02C6\u02C7\u02D8-\u02DD\u0311\u0391-\u03A1\u03A3-\u03A9\u03B1-\u03C9\u03D1\u03D2\u03D5\u03D6\u03DC\u03DD\u03F0\u03F1\u03F5\u03F6\u0401-\u040C\u040E-\u044F\u0451-\u045C\u045E\u045F\u2002-\u2005\u2007-\u2010\u2013-\u2016\u2018-\u201A\u201C-\u201E\u2020-\u2022\u2025\u2026\u2030-\u2035\u2039\u203A\u203E\u2041\u2043\u2044\u204F\u2057\u205F-\u2063\u20AC\u20DB\u20DC\u2102\u2105\u210A-\u2113\u2115-\u211E\u2122\u2124\u2127-\u2129\u212C\u212D\u212F-\u2131\u2133-\u2138\u2145-\u2148\u2153-\u215E\u2190-\u219B\u219D-\u21A7\u21A9-\u21AE\u21B0-\u21B3\u21B5-\u21B7\u21BA-\u21DB\u21DD\u21E4\u21E5\u21F5\u21FD-\u2205\u2207-\u2209\u220B\u220C\u220F-\u2214\u2216-\u2218\u221A\u221D-\u2238\u223A-\u2257\u2259\u225A\u225C\u225F-\u2262\u2264-\u228B\u228D-\u229B\u229D-\u22A5\u22A7-\u22B0\u22B2-\u22BB\u22BD-\u22DB\u22DE-\u22E3\u22E6-\u22F7\u22F9-\u22FE\u2305\u2306\u2308-\u2310\u2312\u2313\u2315\u2316\u231C-\u231F\u2322\u2323\u232D\u232E\u2336\u233D\u233F\u237C\u23B0\u23B1\u23B4-\u23B6\u23DC-\u23DF\u23E2\u23E7\u2423\u24C8\u2500\u2502\u250C\u2510\u2514\u2518\u251C\u2524\u252C\u2534\u253C\u2550-\u256C\u2580\u2584\u2588\u2591-\u2593\u25A1\u25AA\u25AB\u25AD\u25AE\u25B1\u25B3-\u25B5\u25B8\u25B9\u25BD-\u25BF\u25C2\u25C3\u25CA\u25CB\u25EC\u25EF\u25F8-\u25FC\u2605\u2606\u260E\u2640\u2642\u2660\u2663\u2665\u2666\u266A\u266D-\u266F\u2713\u2717\u2720\u2736\u2758\u2772\u2773\u27C8\u27C9\u27E6-\u27ED\u27F5-\u27FA\u27FC\u27FF\u2902-\u2905\u290C-\u2913\u2916\u2919-\u2920\u2923-\u292A\u2933\u2935-\u2939\u293C\u293D\u2945\u2948-\u294B\u294E-\u2976\u2978\u2979\u297B-\u297F\u2985\u2986\u298B-\u2996\u299A\u299C\u299D\u29A4-\u29B7\u29B9\u29BB\u29BC\u29BE-\u29C5\u29C9\u29CD-\u29D0\u29DC-\u29DE\u29E3-\u29E5\u29EB\u29F4\u29F6\u2A00-\u2A02\u2A04\u2A06\u2A0C\u2A0D\u2A10-\u2A17\u2A22-\u2A27\u2A29\u2A2A\u2A2D-\u2A31\u2A33-\u2A3C\u2A3F\u2A40\u2A42-\u2A4D\u2A50\u2A53-\u2A58\u2A5A-\u2A5D\u2A5F\u2A66\u2A6A\u2A6D-\u2A75\u2A77-\u2A9A\u2A9D-\u2AA2\u2AA4-\u2AB0\u2AB3-\u2AC8\u2ACB\u2ACC\u2ACF-\u2ADB\u2AE4\u2AE6-\u2AE9\u2AEB-\u2AF3\u2AFD\uFB00-\uFB04]|\uD835[\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDCCF\uDD04\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDD6B]/g;
var encodeMap = {'\xAD':'shy','\u200C':'zwnj','\u200D':'zwj','\u200E':'lrm','\u2063':'ic','\u2062':'it','\u2061':'af','\u200F':'rlm','\u200B':'ZeroWidthSpace','\u2060':'NoBreak','\u0311':'DownBreve','\u20DB':'tdot','\u20DC':'DotDot','\t':'Tab','\n':'NewLine','\u2008':'puncsp','\u205F':'MediumSpace','\u2009':'thinsp','\u200A':'hairsp','\u2004':'emsp13','\u2002':'ensp','\u2005':'emsp14','\u2003':'emsp','\u2007':'numsp','\xA0':'nbsp','\u205F\u200A':'ThickSpace','\u203E':'oline','_':'lowbar','\u2010':'dash','\u2013':'ndash','\u2014':'mdash','\u2015':'horbar',',':'comma',';':'semi','\u204F':'bsemi',':':'colon','\u2A74':'Colone','!':'excl','\xA1':'iexcl','?':'quest','\xBF':'iquest','.':'period','\u2025':'nldr','\u2026':'mldr','\xB7':'middot','\'':'apos','\u2018':'lsquo','\u2019':'rsquo','\u201A':'sbquo','\u2039':'lsaquo','\u203A':'rsaquo','"':'quot','\u201C':'ldquo','\u201D':'rdquo','\u201E':'bdquo','\xAB':'laquo','\xBB':'raquo','(':'lpar',')':'rpar','[':'lsqb',']':'rsqb','{':'lcub','}':'rcub','\u2308':'lceil','\u2309':'rceil','\u230A':'lfloor','\u230B':'rfloor','\u2985':'lopar','\u2986':'ropar','\u298B':'lbrke','\u298C':'rbrke','\u298D':'lbrkslu','\u298E':'rbrksld','\u298F':'lbrksld','\u2990':'rbrkslu','\u2991':'langd','\u2992':'rangd','\u2993':'lparlt','\u2994':'rpargt','\u2995':'gtlPar','\u2996':'ltrPar','\u27E6':'lobrk','\u27E7':'robrk','\u27E8':'lang','\u27E9':'rang','\u27EA':'Lang','\u27EB':'Rang','\u27EC':'loang','\u27ED':'roang','\u2772':'lbbrk','\u2773':'rbbrk','\u2016':'Vert','\xA7':'sect','\xB6':'para','@':'commat','*':'ast','/':'sol','undefined':null,'&':'amp','#':'num','%':'percnt','\u2030':'permil','\u2031':'pertenk','\u2020':'dagger','\u2021':'Dagger','\u2022':'bull','\u2043':'hybull','\u2032':'prime','\u2033':'Prime','\u2034':'tprime','\u2057':'qprime','\u2035':'bprime','\u2041':'caret','`':'grave','\xB4':'acute','\u02DC':'tilde','^':'Hat','\xAF':'macr','\u02D8':'breve','\u02D9':'dot','\xA8':'die','\u02DA':'ring','\u02DD':'dblac','\xB8':'cedil','\u02DB':'ogon','\u02C6':'circ','\u02C7':'caron','\xB0':'deg','\xA9':'copy','\xAE':'reg','\u2117':'copysr','\u2118':'wp','\u211E':'rx','\u2127':'mho','\u2129':'iiota','\u2190':'larr','\u219A':'nlarr','\u2192':'rarr','\u219B':'nrarr','\u2191':'uarr','\u2193':'darr','\u2194':'harr','\u21AE':'nharr','\u2195':'varr','\u2196':'nwarr','\u2197':'nearr','\u2198':'searr','\u2199':'swarr','\u219D':'rarrw','\u219D\u0338':'nrarrw','\u219E':'Larr','\u219F':'Uarr','\u21A0':'Rarr','\u21A1':'Darr','\u21A2':'larrtl','\u21A3':'rarrtl','\u21A4':'mapstoleft','\u21A5':'mapstoup','\u21A6':'map','\u21A7':'mapstodown','\u21A9':'larrhk','\u21AA':'rarrhk','\u21AB':'larrlp','\u21AC':'rarrlp','\u21AD':'harrw','\u21B0':'lsh','\u21B1':'rsh','\u21B2':'ldsh','\u21B3':'rdsh','\u21B5':'crarr','\u21B6':'cularr','\u21B7':'curarr','\u21BA':'olarr','\u21BB':'orarr','\u21BC':'lharu','\u21BD':'lhard','\u21BE':'uharr','\u21BF':'uharl','\u21C0':'rharu','\u21C1':'rhard','\u21C2':'dharr','\u21C3':'dharl','\u21C4':'rlarr','\u21C5':'udarr','\u21C6':'lrarr','\u21C7':'llarr','\u21C8':'uuarr','\u21C9':'rrarr','\u21CA':'ddarr','\u21CB':'lrhar','\u21CC':'rlhar','\u21D0':'lArr','\u21CD':'nlArr','\u21D1':'uArr','\u21D2':'rArr','\u21CF':'nrArr','\u21D3':'dArr','\u21D4':'iff','\u21CE':'nhArr','\u21D5':'vArr','\u21D6':'nwArr','\u21D7':'neArr','\u21D8':'seArr','\u21D9':'swArr','\u21DA':'lAarr','\u21DB':'rAarr','\u21DD':'zigrarr','\u21E4':'larrb','\u21E5':'rarrb','\u21F5':'duarr','\u21FD':'loarr','\u21FE':'roarr','\u21FF':'hoarr','\u2200':'forall','\u2201':'comp','\u2202':'part','\u2202\u0338':'npart','\u2203':'exist','\u2204':'nexist','\u2205':'empty','\u2207':'Del','\u2208':'in','\u2209':'notin','\u220B':'ni','\u220C':'notni','\u03F6':'bepsi','\u220F':'prod','\u2210':'coprod','\u2211':'sum','+':'plus','\xB1':'pm','\xF7':'div','\xD7':'times','<':'lt','\u226E':'nlt','<\u20D2':'nvlt','=':'equals','\u2260':'ne','=\u20E5':'bne','\u2A75':'Equal','>':'gt','\u226F':'ngt','>\u20D2':'nvgt','\xAC':'not','|':'vert','\xA6':'brvbar','\u2212':'minus','\u2213':'mp','\u2214':'plusdo','\u2044':'frasl','\u2216':'setmn','\u2217':'lowast','\u2218':'compfn','\u221A':'Sqrt','\u221D':'prop','\u221E':'infin','\u221F':'angrt','\u2220':'ang','\u2220\u20D2':'nang','\u2221':'angmsd','\u2222':'angsph','\u2223':'mid','\u2224':'nmid','\u2225':'par','\u2226':'npar','\u2227':'and','\u2228':'or','\u2229':'cap','\u2229\uFE00':'caps','\u222A':'cup','\u222A\uFE00':'cups','\u222B':'int','\u222C':'Int','\u222D':'tint','\u2A0C':'qint','\u222E':'oint','\u222F':'Conint','\u2230':'Cconint','\u2231':'cwint','\u2232':'cwconint','\u2233':'awconint','\u2234':'there4','\u2235':'becaus','\u2236':'ratio','\u2237':'Colon','\u2238':'minusd','\u223A':'mDDot','\u223B':'homtht','\u223C':'sim','\u2241':'nsim','\u223C\u20D2':'nvsim','\u223D':'bsim','\u223D\u0331':'race','\u223E':'ac','\u223E\u0333':'acE','\u223F':'acd','\u2240':'wr','\u2242':'esim','\u2242\u0338':'nesim','\u2243':'sime','\u2244':'nsime','\u2245':'cong','\u2247':'ncong','\u2246':'simne','\u2248':'ap','\u2249':'nap','\u224A':'ape','\u224B':'apid','\u224B\u0338':'napid','\u224C':'bcong','\u224D':'CupCap','\u226D':'NotCupCap','\u224D\u20D2':'nvap','\u224E':'bump','\u224E\u0338':'nbump','\u224F':'bumpe','\u224F\u0338':'nbumpe','\u2250':'doteq','\u2250\u0338':'nedot','\u2251':'eDot','\u2252':'efDot','\u2253':'erDot','\u2254':'colone','\u2255':'ecolon','\u2256':'ecir','\u2257':'cire','\u2259':'wedgeq','\u225A':'veeeq','\u225C':'trie','\u225F':'equest','\u2261':'equiv','\u2262':'nequiv','\u2261\u20E5':'bnequiv','\u2264':'le','\u2270':'nle','\u2264\u20D2':'nvle','\u2265':'ge','\u2271':'nge','\u2265\u20D2':'nvge','\u2266':'lE','\u2266\u0338':'nlE','\u2267':'gE','\u2267\u0338':'ngE','\u2268\uFE00':'lvnE','\u2268':'lnE','\u2269':'gnE','\u2269\uFE00':'gvnE','\u226A':'ll','\u226A\u0338':'nLtv','\u226A\u20D2':'nLt','\u226B':'gg','\u226B\u0338':'nGtv','\u226B\u20D2':'nGt','\u226C':'twixt','\u2272':'lsim','\u2274':'nlsim','\u2273':'gsim','\u2275':'ngsim','\u2276':'lg','\u2278':'ntlg','\u2277':'gl','\u2279':'ntgl','\u227A':'pr','\u2280':'npr','\u227B':'sc','\u2281':'nsc','\u227C':'prcue','\u22E0':'nprcue','\u227D':'sccue','\u22E1':'nsccue','\u227E':'prsim','\u227F':'scsim','\u227F\u0338':'NotSucceedsTilde','\u2282':'sub','\u2284':'nsub','\u2282\u20D2':'vnsub','\u2283':'sup','\u2285':'nsup','\u2283\u20D2':'vnsup','\u2286':'sube','\u2288':'nsube','\u2287':'supe','\u2289':'nsupe','\u228A\uFE00':'vsubne','\u228A':'subne','\u228B\uFE00':'vsupne','\u228B':'supne','\u228D':'cupdot','\u228E':'uplus','\u228F':'sqsub','\u228F\u0338':'NotSquareSubset','\u2290':'sqsup','\u2290\u0338':'NotSquareSuperset','\u2291':'sqsube','\u22E2':'nsqsube','\u2292':'sqsupe','\u22E3':'nsqsupe','\u2293':'sqcap','\u2293\uFE00':'sqcaps','\u2294':'sqcup','\u2294\uFE00':'sqcups','\u2295':'oplus','\u2296':'ominus','\u2297':'otimes','\u2298':'osol','\u2299':'odot','\u229A':'ocir','\u229B':'oast','\u229D':'odash','\u229E':'plusb','\u229F':'minusb','\u22A0':'timesb','\u22A1':'sdotb','\u22A2':'vdash','\u22AC':'nvdash','\u22A3':'dashv','\u22A4':'top','\u22A5':'bot','\u22A7':'models','\u22A8':'vDash','\u22AD':'nvDash','\u22A9':'Vdash','\u22AE':'nVdash','\u22AA':'Vvdash','\u22AB':'VDash','\u22AF':'nVDash','\u22B0':'prurel','\u22B2':'vltri','\u22EA':'nltri','\u22B3':'vrtri','\u22EB':'nrtri','\u22B4':'ltrie','\u22EC':'nltrie','\u22B4\u20D2':'nvltrie','\u22B5':'rtrie','\u22ED':'nrtrie','\u22B5\u20D2':'nvrtrie','\u22B6':'origof','\u22B7':'imof','\u22B8':'mumap','\u22B9':'hercon','\u22BA':'intcal','\u22BB':'veebar','\u22BD':'barvee','\u22BE':'angrtvb','\u22BF':'lrtri','\u22C0':'Wedge','\u22C1':'Vee','\u22C2':'xcap','\u22C3':'xcup','\u22C4':'diam','\u22C5':'sdot','\u22C6':'Star','\u22C7':'divonx','\u22C8':'bowtie','\u22C9':'ltimes','\u22CA':'rtimes','\u22CB':'lthree','\u22CC':'rthree','\u22CD':'bsime','\u22CE':'cuvee','\u22CF':'cuwed','\u22D0':'Sub','\u22D1':'Sup','\u22D2':'Cap','\u22D3':'Cup','\u22D4':'fork','\u22D5':'epar','\u22D6':'ltdot','\u22D7':'gtdot','\u22D8':'Ll','\u22D8\u0338':'nLl','\u22D9':'Gg','\u22D9\u0338':'nGg','\u22DA\uFE00':'lesg','\u22DA':'leg','\u22DB':'gel','\u22DB\uFE00':'gesl','\u22DE':'cuepr','\u22DF':'cuesc','\u22E6':'lnsim','\u22E7':'gnsim','\u22E8':'prnsim','\u22E9':'scnsim','\u22EE':'vellip','\u22EF':'ctdot','\u22F0':'utdot','\u22F1':'dtdot','\u22F2':'disin','\u22F3':'isinsv','\u22F4':'isins','\u22F5':'isindot','\u22F5\u0338':'notindot','\u22F6':'notinvc','\u22F7':'notinvb','\u22F9':'isinE','\u22F9\u0338':'notinE','\u22FA':'nisd','\u22FB':'xnis','\u22FC':'nis','\u22FD':'notnivc','\u22FE':'notnivb','\u2305':'barwed','\u2306':'Barwed','\u230C':'drcrop','\u230D':'dlcrop','\u230E':'urcrop','\u230F':'ulcrop','\u2310':'bnot','\u2312':'profline','\u2313':'profsurf','\u2315':'telrec','\u2316':'target','\u231C':'ulcorn','\u231D':'urcorn','\u231E':'dlcorn','\u231F':'drcorn','\u2322':'frown','\u2323':'smile','\u232D':'cylcty','\u232E':'profalar','\u2336':'topbot','\u233D':'ovbar','\u233F':'solbar','\u237C':'angzarr','\u23B0':'lmoust','\u23B1':'rmoust','\u23B4':'tbrk','\u23B5':'bbrk','\u23B6':'bbrktbrk','\u23DC':'OverParenthesis','\u23DD':'UnderParenthesis','\u23DE':'OverBrace','\u23DF':'UnderBrace','\u23E2':'trpezium','\u23E7':'elinters','\u2423':'blank','\u2500':'boxh','\u2502':'boxv','\u250C':'boxdr','\u2510':'boxdl','\u2514':'boxur','\u2518':'boxul','\u251C':'boxvr','\u2524':'boxvl','\u252C':'boxhd','\u2534':'boxhu','\u253C':'boxvh','\u2550':'boxH','\u2551':'boxV','\u2552':'boxdR','\u2553':'boxDr','\u2554':'boxDR','\u2555':'boxdL','\u2556':'boxDl','\u2557':'boxDL','\u2558':'boxuR','\u2559':'boxUr','\u255A':'boxUR','\u255B':'boxuL','\u255C':'boxUl','\u255D':'boxUL','\u255E':'boxvR','\u255F':'boxVr','\u2560':'boxVR','\u2561':'boxvL','\u2562':'boxVl','\u2563':'boxVL','\u2564':'boxHd','\u2565':'boxhD','\u2566':'boxHD','\u2567':'boxHu','\u2568':'boxhU','\u2569':'boxHU','\u256A':'boxvH','\u256B':'boxVh','\u256C':'boxVH','\u2580':'uhblk','\u2584':'lhblk','\u2588':'block','\u2591':'blk14','\u2592':'blk12','\u2593':'blk34','\u25A1':'squ','\u25AA':'squf','\u25AB':'EmptyVerySmallSquare','\u25AD':'rect','\u25AE':'marker','\u25B1':'fltns','\u25B3':'xutri','\u25B4':'utrif','\u25B5':'utri','\u25B8':'rtrif','\u25B9':'rtri','\u25BD':'xdtri','\u25BE':'dtrif','\u25BF':'dtri','\u25C2':'ltrif','\u25C3':'ltri','\u25CA':'loz','\u25CB':'cir','\u25EC':'tridot','\u25EF':'xcirc','\u25F8':'ultri','\u25F9':'urtri','\u25FA':'lltri','\u25FB':'EmptySmallSquare','\u25FC':'FilledSmallSquare','\u2605':'starf','\u2606':'star','\u260E':'phone','\u2640':'female','\u2642':'male','\u2660':'spades','\u2663':'clubs','\u2665':'hearts','\u2666':'diams','\u266A':'sung','\u2713':'check','\u2717':'cross','\u2720':'malt','\u2736':'sext','\u2758':'VerticalSeparator','\u27C8':'bsolhsub','\u27C9':'suphsol','\u27F5':'xlarr','\u27F6':'xrarr','\u27F7':'xharr','\u27F8':'xlArr','\u27F9':'xrArr','\u27FA':'xhArr','\u27FC':'xmap','\u27FF':'dzigrarr','\u2902':'nvlArr','\u2903':'nvrArr','\u2904':'nvHarr','\u2905':'Map','\u290C':'lbarr','\u290D':'rbarr','\u290E':'lBarr','\u290F':'rBarr','\u2910':'RBarr','\u2911':'DDotrahd','\u2912':'UpArrowBar','\u2913':'DownArrowBar','\u2916':'Rarrtl','\u2919':'latail','\u291A':'ratail','\u291B':'lAtail','\u291C':'rAtail','\u291D':'larrfs','\u291E':'rarrfs','\u291F':'larrbfs','\u2920':'rarrbfs','\u2923':'nwarhk','\u2924':'nearhk','\u2925':'searhk','\u2926':'swarhk','\u2927':'nwnear','\u2928':'toea','\u2929':'tosa','\u292A':'swnwar','\u2933':'rarrc','\u2933\u0338':'nrarrc','\u2935':'cudarrr','\u2936':'ldca','\u2937':'rdca','\u2938':'cudarrl','\u2939':'larrpl','\u293C':'curarrm','\u293D':'cularrp','\u2945':'rarrpl','\u2948':'harrcir','\u2949':'Uarrocir','\u294A':'lurdshar','\u294B':'ldrushar','\u294E':'LeftRightVector','\u294F':'RightUpDownVector','\u2950':'DownLeftRightVector','\u2951':'LeftUpDownVector','\u2952':'LeftVectorBar','\u2953':'RightVectorBar','\u2954':'RightUpVectorBar','\u2955':'RightDownVectorBar','\u2956':'DownLeftVectorBar','\u2957':'DownRightVectorBar','\u2958':'LeftUpVectorBar','\u2959':'LeftDownVectorBar','\u295A':'LeftTeeVector','\u295B':'RightTeeVector','\u295C':'RightUpTeeVector','\u295D':'RightDownTeeVector','\u295E':'DownLeftTeeVector','\u295F':'DownRightTeeVector','\u2960':'LeftUpTeeVector','\u2961':'LeftDownTeeVector','\u2962':'lHar','\u2963':'uHar','\u2964':'rHar','\u2965':'dHar','\u2966':'luruhar','\u2967':'ldrdhar','\u2968':'ruluhar','\u2969':'rdldhar','\u296A':'lharul','\u296B':'llhard','\u296C':'rharul','\u296D':'lrhard','\u296E':'udhar','\u296F':'duhar','\u2970':'RoundImplies','\u2971':'erarr','\u2972':'simrarr','\u2973':'larrsim','\u2974':'rarrsim','\u2975':'rarrap','\u2976':'ltlarr','\u2978':'gtrarr','\u2979':'subrarr','\u297B':'suplarr','\u297C':'lfisht','\u297D':'rfisht','\u297E':'ufisht','\u297F':'dfisht','\u299A':'vzigzag','\u299C':'vangrt','\u299D':'angrtvbd','\u29A4':'ange','\u29A5':'range','\u29A6':'dwangle','\u29A7':'uwangle','\u29A8':'angmsdaa','\u29A9':'angmsdab','\u29AA':'angmsdac','\u29AB':'angmsdad','\u29AC':'angmsdae','\u29AD':'angmsdaf','\u29AE':'angmsdag','\u29AF':'angmsdah','\u29B0':'bemptyv','\u29B1':'demptyv','\u29B2':'cemptyv','\u29B3':'raemptyv','\u29B4':'laemptyv','\u29B5':'ohbar','\u29B6':'omid','\u29B7':'opar','\u29B9':'operp','\u29BB':'olcross','\u29BC':'odsold','\u29BE':'olcir','\u29BF':'ofcir','\u29C0':'olt','\u29C1':'ogt','\u29C2':'cirscir','\u29C3':'cirE','\u29C4':'solb','\u29C5':'bsolb','\u29C9':'boxbox','\u29CD':'trisb','\u29CE':'rtriltri','\u29CF':'LeftTriangleBar','\u29CF\u0338':'NotLeftTriangleBar','\u29D0':'RightTriangleBar','\u29D0\u0338':'NotRightTriangleBar','\u29DC':'iinfin','\u29DD':'infintie','\u29DE':'nvinfin','\u29E3':'eparsl','\u29E4':'smeparsl','\u29E5':'eqvparsl','\u29EB':'lozf','\u29F4':'RuleDelayed','\u29F6':'dsol','\u2A00':'xodot','\u2A01':'xoplus','\u2A02':'xotime','\u2A04':'xuplus','\u2A06':'xsqcup','\u2A0D':'fpartint','\u2A10':'cirfnint','\u2A11':'awint','\u2A12':'rppolint','\u2A13':'scpolint','\u2A14':'npolint','\u2A15':'pointint','\u2A16':'quatint','\u2A17':'intlarhk','\u2A22':'pluscir','\u2A23':'plusacir','\u2A24':'simplus','\u2A25':'plusdu','\u2A26':'plussim','\u2A27':'plustwo','\u2A29':'mcomma','\u2A2A':'minusdu','\u2A2D':'loplus','\u2A2E':'roplus','\u2A2F':'Cross','\u2A30':'timesd','\u2A31':'timesbar','\u2A33':'smashp','\u2A34':'lotimes','\u2A35':'rotimes','\u2A36':'otimesas','\u2A37':'Otimes','\u2A38':'odiv','\u2A39':'triplus','\u2A3A':'triminus','\u2A3B':'tritime','\u2A3C':'iprod','\u2A3F':'amalg','\u2A40':'capdot','\u2A42':'ncup','\u2A43':'ncap','\u2A44':'capand','\u2A45':'cupor','\u2A46':'cupcap','\u2A47':'capcup','\u2A48':'cupbrcap','\u2A49':'capbrcup','\u2A4A':'cupcup','\u2A4B':'capcap','\u2A4C':'ccups','\u2A4D':'ccaps','\u2A50':'ccupssm','\u2A53':'And','\u2A54':'Or','\u2A55':'andand','\u2A56':'oror','\u2A57':'orslope','\u2A58':'andslope','\u2A5A':'andv','\u2A5B':'orv','\u2A5C':'andd','\u2A5D':'ord','\u2A5F':'wedbar','\u2A66':'sdote','\u2A6A':'simdot','\u2A6D':'congdot','\u2A6D\u0338':'ncongdot','\u2A6E':'easter','\u2A6F':'apacir','\u2A70':'apE','\u2A70\u0338':'napE','\u2A71':'eplus','\u2A72':'pluse','\u2A73':'Esim','\u2A77':'eDDot','\u2A78':'equivDD','\u2A79':'ltcir','\u2A7A':'gtcir','\u2A7B':'ltquest','\u2A7C':'gtquest','\u2A7D':'les','\u2A7D\u0338':'nles','\u2A7E':'ges','\u2A7E\u0338':'nges','\u2A7F':'lesdot','\u2A80':'gesdot','\u2A81':'lesdoto','\u2A82':'gesdoto','\u2A83':'lesdotor','\u2A84':'gesdotol','\u2A85':'lap','\u2A86':'gap','\u2A87':'lne','\u2A88':'gne','\u2A89':'lnap','\u2A8A':'gnap','\u2A8B':'lEg','\u2A8C':'gEl','\u2A8D':'lsime','\u2A8E':'gsime','\u2A8F':'lsimg','\u2A90':'gsiml','\u2A91':'lgE','\u2A92':'glE','\u2A93':'lesges','\u2A94':'gesles','\u2A95':'els','\u2A96':'egs','\u2A97':'elsdot','\u2A98':'egsdot','\u2A99':'el','\u2A9A':'eg','\u2A9D':'siml','\u2A9E':'simg','\u2A9F':'simlE','\u2AA0':'simgE','\u2AA1':'LessLess','\u2AA1\u0338':'NotNestedLessLess','\u2AA2':'GreaterGreater','\u2AA2\u0338':'NotNestedGreaterGreater','\u2AA4':'glj','\u2AA5':'gla','\u2AA6':'ltcc','\u2AA7':'gtcc','\u2AA8':'lescc','\u2AA9':'gescc','\u2AAA':'smt','\u2AAB':'lat','\u2AAC':'smte','\u2AAC\uFE00':'smtes','\u2AAD':'late','\u2AAD\uFE00':'lates','\u2AAE':'bumpE','\u2AAF':'pre','\u2AAF\u0338':'npre','\u2AB0':'sce','\u2AB0\u0338':'nsce','\u2AB3':'prE','\u2AB4':'scE','\u2AB5':'prnE','\u2AB6':'scnE','\u2AB7':'prap','\u2AB8':'scap','\u2AB9':'prnap','\u2ABA':'scnap','\u2ABB':'Pr','\u2ABC':'Sc','\u2ABD':'subdot','\u2ABE':'supdot','\u2ABF':'subplus','\u2AC0':'supplus','\u2AC1':'submult','\u2AC2':'supmult','\u2AC3':'subedot','\u2AC4':'supedot','\u2AC5':'subE','\u2AC5\u0338':'nsubE','\u2AC6':'supE','\u2AC6\u0338':'nsupE','\u2AC7':'subsim','\u2AC8':'supsim','\u2ACB\uFE00':'vsubnE','\u2ACB':'subnE','\u2ACC\uFE00':'vsupnE','\u2ACC':'supnE','\u2ACF':'csub','\u2AD0':'csup','\u2AD1':'csube','\u2AD2':'csupe','\u2AD3':'subsup','\u2AD4':'supsub','\u2AD5':'subsub','\u2AD6':'supsup','\u2AD7':'suphsub','\u2AD8':'supdsub','\u2AD9':'forkv','\u2ADA':'topfork','\u2ADB':'mlcp','\u2AE4':'Dashv','\u2AE6':'Vdashl','\u2AE7':'Barv','\u2AE8':'vBar','\u2AE9':'vBarv','\u2AEB':'Vbar','\u2AEC':'Not','\u2AED':'bNot','\u2AEE':'rnmid','\u2AEF':'cirmid','\u2AF0':'midcir','\u2AF1':'topcir','\u2AF2':'nhpar','\u2AF3':'parsim','\u2AFD':'parsl','\u2AFD\u20E5':'nparsl','\u266D':'flat','\u266E':'natur','\u266F':'sharp','\xA4':'curren','\xA2':'cent','$':'dollar','\xA3':'pound','\xA5':'yen','\u20AC':'euro','\xB9':'sup1','\xBD':'half','\u2153':'frac13','\xBC':'frac14','\u2155':'frac15','\u2159':'frac16','\u215B':'frac18','\xB2':'sup2','\u2154':'frac23','\u2156':'frac25','\xB3':'sup3','\xBE':'frac34','\u2157':'frac35','\u215C':'frac38','\u2158':'frac45','\u215A':'frac56','\u215D':'frac58','\u215E':'frac78','\uD835\uDCB6':'ascr','\uD835\uDD52':'aopf','\uD835\uDD1E':'afr','\uD835\uDD38':'Aopf','\uD835\uDD04':'Afr','\uD835\uDC9C':'Ascr','\xAA':'ordf','\xE1':'aacute','\xC1':'Aacute','\xE0':'agrave','\xC0':'Agrave','\u0103':'abreve','\u0102':'Abreve','\xE2':'acirc','\xC2':'Acirc','\xE5':'aring','\xC5':'angst','\xE4':'auml','\xC4':'Auml','\xE3':'atilde','\xC3':'Atilde','\u0105':'aogon','\u0104':'Aogon','\u0101':'amacr','\u0100':'Amacr','\xE6':'aelig','\xC6':'AElig','\uD835\uDCB7':'bscr','\uD835\uDD53':'bopf','\uD835\uDD1F':'bfr','\uD835\uDD39':'Bopf','\u212C':'Bscr','\uD835\uDD05':'Bfr','\uD835\uDD20':'cfr','\uD835\uDCB8':'cscr','\uD835\uDD54':'copf','\u212D':'Cfr','\uD835\uDC9E':'Cscr','\u2102':'Copf','\u0107':'cacute','\u0106':'Cacute','\u0109':'ccirc','\u0108':'Ccirc','\u010D':'ccaron','\u010C':'Ccaron','\u010B':'cdot','\u010A':'Cdot','\xE7':'ccedil','\xC7':'Ccedil','\u2105':'incare','\uD835\uDD21':'dfr','\u2146':'dd','\uD835\uDD55':'dopf','\uD835\uDCB9':'dscr','\uD835\uDC9F':'Dscr','\uD835\uDD07':'Dfr','\u2145':'DD','\uD835\uDD3B':'Dopf','\u010F':'dcaron','\u010E':'Dcaron','\u0111':'dstrok','\u0110':'Dstrok','\xF0':'eth','\xD0':'ETH','\u2147':'ee','\u212F':'escr','\uD835\uDD22':'efr','\uD835\uDD56':'eopf','\u2130':'Escr','\uD835\uDD08':'Efr','\uD835\uDD3C':'Eopf','\xE9':'eacute','\xC9':'Eacute','\xE8':'egrave','\xC8':'Egrave','\xEA':'ecirc','\xCA':'Ecirc','\u011B':'ecaron','\u011A':'Ecaron','\xEB':'euml','\xCB':'Euml','\u0117':'edot','\u0116':'Edot','\u0119':'eogon','\u0118':'Eogon','\u0113':'emacr','\u0112':'Emacr','\uD835\uDD23':'ffr','\uD835\uDD57':'fopf','\uD835\uDCBB':'fscr','\uD835\uDD09':'Ffr','\uD835\uDD3D':'Fopf','\u2131':'Fscr','\uFB00':'fflig','\uFB03':'ffilig','\uFB04':'ffllig','\uFB01':'filig','fj':'fjlig','\uFB02':'fllig','\u0192':'fnof','\u210A':'gscr','\uD835\uDD58':'gopf','\uD835\uDD24':'gfr','\uD835\uDCA2':'Gscr','\uD835\uDD3E':'Gopf','\uD835\uDD0A':'Gfr','\u01F5':'gacute','\u011F':'gbreve','\u011E':'Gbreve','\u011D':'gcirc','\u011C':'Gcirc','\u0121':'gdot','\u0120':'Gdot','\u0122':'Gcedil','\uD835\uDD25':'hfr','\u210E':'planckh','\uD835\uDCBD':'hscr','\uD835\uDD59':'hopf','\u210B':'Hscr','\u210C':'Hfr','\u210D':'Hopf','\u0125':'hcirc','\u0124':'Hcirc','\u210F':'hbar','\u0127':'hstrok','\u0126':'Hstrok','\uD835\uDD5A':'iopf','\uD835\uDD26':'ifr','\uD835\uDCBE':'iscr','\u2148':'ii','\uD835\uDD40':'Iopf','\u2110':'Iscr','\u2111':'Im','\xED':'iacute','\xCD':'Iacute','\xEC':'igrave','\xCC':'Igrave','\xEE':'icirc','\xCE':'Icirc','\xEF':'iuml','\xCF':'Iuml','\u0129':'itilde','\u0128':'Itilde','\u0130':'Idot','\u012F':'iogon','\u012E':'Iogon','\u012B':'imacr','\u012A':'Imacr','\u0133':'ijlig','\u0132':'IJlig','\u0131':'imath','\uD835\uDCBF':'jscr','\uD835\uDD5B':'jopf','\uD835\uDD27':'jfr','\uD835\uDCA5':'Jscr','\uD835\uDD0D':'Jfr','\uD835\uDD41':'Jopf','\u0135':'jcirc','\u0134':'Jcirc','\u0237':'jmath','\uD835\uDD5C':'kopf','\uD835\uDCC0':'kscr','\uD835\uDD28':'kfr','\uD835\uDCA6':'Kscr','\uD835\uDD42':'Kopf','\uD835\uDD0E':'Kfr','\u0137':'kcedil','\u0136':'Kcedil','\uD835\uDD29':'lfr','\uD835\uDCC1':'lscr','\u2113':'ell','\uD835\uDD5D':'lopf','\u2112':'Lscr','\uD835\uDD0F':'Lfr','\uD835\uDD43':'Lopf','\u013A':'lacute','\u0139':'Lacute','\u013E':'lcaron','\u013D':'Lcaron','\u013C':'lcedil','\u013B':'Lcedil','\u0142':'lstrok','\u0141':'Lstrok','\u0140':'lmidot','\u013F':'Lmidot','\uD835\uDD2A':'mfr','\uD835\uDD5E':'mopf','\uD835\uDCC2':'mscr','\uD835\uDD10':'Mfr','\uD835\uDD44':'Mopf','\u2133':'Mscr','\uD835\uDD2B':'nfr','\uD835\uDD5F':'nopf','\uD835\uDCC3':'nscr','\u2115':'Nopf','\uD835\uDCA9':'Nscr','\uD835\uDD11':'Nfr','\u0144':'nacute','\u0143':'Nacute','\u0148':'ncaron','\u0147':'Ncaron','\xF1':'ntilde','\xD1':'Ntilde','\u0146':'ncedil','\u0145':'Ncedil','\u2116':'numero','\u014B':'eng','\u014A':'ENG','\uD835\uDD60':'oopf','\uD835\uDD2C':'ofr','\u2134':'oscr','\uD835\uDCAA':'Oscr','\uD835\uDD12':'Ofr','\uD835\uDD46':'Oopf','\xBA':'ordm','\xF3':'oacute','\xD3':'Oacute','\xF2':'ograve','\xD2':'Ograve','\xF4':'ocirc','\xD4':'Ocirc','\xF6':'ouml','\xD6':'Ouml','\u0151':'odblac','\u0150':'Odblac','\xF5':'otilde','\xD5':'Otilde','\xF8':'oslash','\xD8':'Oslash','\u014D':'omacr','\u014C':'Omacr','\u0153':'oelig','\u0152':'OElig','\uD835\uDD2D':'pfr','\uD835\uDCC5':'pscr','\uD835\uDD61':'popf','\u2119':'Popf','\uD835\uDD13':'Pfr','\uD835\uDCAB':'Pscr','\uD835\uDD62':'qopf','\uD835\uDD2E':'qfr','\uD835\uDCC6':'qscr','\uD835\uDCAC':'Qscr','\uD835\uDD14':'Qfr','\u211A':'Qopf','\u0138':'kgreen','\uD835\uDD2F':'rfr','\uD835\uDD63':'ropf','\uD835\uDCC7':'rscr','\u211B':'Rscr','\u211C':'Re','\u211D':'Ropf','\u0155':'racute','\u0154':'Racute','\u0159':'rcaron','\u0158':'Rcaron','\u0157':'rcedil','\u0156':'Rcedil','\uD835\uDD64':'sopf','\uD835\uDCC8':'sscr','\uD835\uDD30':'sfr','\uD835\uDD4A':'Sopf','\uD835\uDD16':'Sfr','\uD835\uDCAE':'Sscr','\u24C8':'oS','\u015B':'sacute','\u015A':'Sacute','\u015D':'scirc','\u015C':'Scirc','\u0161':'scaron','\u0160':'Scaron','\u015F':'scedil','\u015E':'Scedil','\xDF':'szlig','\uD835\uDD31':'tfr','\uD835\uDCC9':'tscr','\uD835\uDD65':'topf','\uD835\uDCAF':'Tscr','\uD835\uDD17':'Tfr','\uD835\uDD4B':'Topf','\u0165':'tcaron','\u0164':'Tcaron','\u0163':'tcedil','\u0162':'Tcedil','\u2122':'trade','\u0167':'tstrok','\u0166':'Tstrok','\uD835\uDCCA':'uscr','\uD835\uDD66':'uopf','\uD835\uDD32':'ufr','\uD835\uDD4C':'Uopf','\uD835\uDD18':'Ufr','\uD835\uDCB0':'Uscr','\xFA':'uacute','\xDA':'Uacute','\xF9':'ugrave','\xD9':'Ugrave','\u016D':'ubreve','\u016C':'Ubreve','\xFB':'ucirc','\xDB':'Ucirc','\u016F':'uring','\u016E':'Uring','\xFC':'uuml','\xDC':'Uuml','\u0171':'udblac','\u0170':'Udblac','\u0169':'utilde','\u0168':'Utilde','\u0173':'uogon','\u0172':'Uogon','\u016B':'umacr','\u016A':'Umacr','\uD835\uDD33':'vfr','\uD835\uDD67':'vopf','\uD835\uDCCB':'vscr','\uD835\uDD19':'Vfr','\uD835\uDD4D':'Vopf','\uD835\uDCB1':'Vscr','\uD835\uDD68':'wopf','\uD835\uDCCC':'wscr','\uD835\uDD34':'wfr','\uD835\uDCB2':'Wscr','\uD835\uDD4E':'Wopf','\uD835\uDD1A':'Wfr','\u0175':'wcirc','\u0174':'Wcirc','\uD835\uDD35':'xfr','\uD835\uDCCD':'xscr','\uD835\uDD69':'xopf','\uD835\uDD4F':'Xopf','\uD835\uDD1B':'Xfr','\uD835\uDCB3':'Xscr','\uD835\uDD36':'yfr','\uD835\uDCCE':'yscr','\uD835\uDD6A':'yopf','\uD835\uDCB4':'Yscr','\uD835\uDD1C':'Yfr','\uD835\uDD50':'Yopf','\xFD':'yacute','\xDD':'Yacute','\u0177':'ycirc','\u0176':'Ycirc','\xFF':'yuml','\u0178':'Yuml','\uD835\uDCCF':'zscr','\uD835\uDD37':'zfr','\uD835\uDD6B':'zopf','\u2128':'Zfr','\u2124':'Zopf','\uD835\uDCB5':'Zscr','\u017A':'zacute','\u0179':'Zacute','\u017E':'zcaron','\u017D':'Zcaron','\u017C':'zdot','\u017B':'Zdot','\u01B5':'imped','\xFE':'thorn','\xDE':'THORN','\u0149':'napos','\u03B1':'alpha','\u0391':'Alpha','\u03B2':'beta','\u0392':'Beta','\u03B3':'gamma','\u0393':'Gamma','\u03B4':'delta','\u0394':'Delta','\u03B5':'epsi','\u03F5':'epsiv','\u0395':'Epsilon','\u03DD':'gammad','\u03DC':'Gammad','\u03B6':'zeta','\u0396':'Zeta','\u03B7':'eta','\u0397':'Eta','\u03B8':'theta','\u03D1':'thetav','\u0398':'Theta','\u03B9':'iota','\u0399':'Iota','\u03BA':'kappa','\u03F0':'kappav','\u039A':'Kappa','\u03BB':'lambda','\u039B':'Lambda','\u03BC':'mu','\xB5':'micro','\u039C':'Mu','\u03BD':'nu','\u039D':'Nu','\u03BE':'xi','\u039E':'Xi','\u03BF':'omicron','\u039F':'Omicron','\u03C0':'pi','\u03D6':'piv','\u03A0':'Pi','\u03C1':'rho','\u03F1':'rhov','\u03A1':'Rho','\u03C3':'sigma','\u03A3':'Sigma','\u03C2':'sigmaf','\u03C4':'tau','\u03A4':'Tau','\u03C5':'upsi','\u03A5':'Upsilon','\u03D2':'Upsi','\u03C6':'phi','\u03D5':'phiv','\u03A6':'Phi','\u03C7':'chi','\u03A7':'Chi','\u03C8':'psi','\u03A8':'Psi','\u03C9':'omega','\u03A9':'ohm','\u0430':'acy','\u0410':'Acy','\u0431':'bcy','\u0411':'Bcy','\u0432':'vcy','\u0412':'Vcy','\u0433':'gcy','\u0413':'Gcy','\u0453':'gjcy','\u0403':'GJcy','\u0434':'dcy','\u0414':'Dcy','\u0452':'djcy','\u0402':'DJcy','\u0435':'iecy','\u0415':'IEcy','\u0451':'iocy','\u0401':'IOcy','\u0454':'jukcy','\u0404':'Jukcy','\u0436':'zhcy','\u0416':'ZHcy','\u0437':'zcy','\u0417':'Zcy','\u0455':'dscy','\u0405':'DScy','\u0438':'icy','\u0418':'Icy','\u0456':'iukcy','\u0406':'Iukcy','\u0457':'yicy','\u0407':'YIcy','\u0439':'jcy','\u0419':'Jcy','\u0458':'jsercy','\u0408':'Jsercy','\u043A':'kcy','\u041A':'Kcy','\u045C':'kjcy','\u040C':'KJcy','\u043B':'lcy','\u041B':'Lcy','\u0459':'ljcy','\u0409':'LJcy','\u043C':'mcy','\u041C':'Mcy','\u043D':'ncy','\u041D':'Ncy','\u045A':'njcy','\u040A':'NJcy','\u043E':'ocy','\u041E':'Ocy','\u043F':'pcy','\u041F':'Pcy','\u0440':'rcy','\u0420':'Rcy','\u0441':'scy','\u0421':'Scy','\u0442':'tcy','\u0422':'Tcy','\u045B':'tshcy','\u040B':'TSHcy','\u0443':'ucy','\u0423':'Ucy','\u045E':'ubrcy','\u040E':'Ubrcy','\u0444':'fcy','\u0424':'Fcy','\u0445':'khcy','\u0425':'KHcy','\u0446':'tscy','\u0426':'TScy','\u0447':'chcy','\u0427':'CHcy','\u045F':'dzcy','\u040F':'DZcy','\u0448':'shcy','\u0428':'SHcy','\u0449':'shchcy','\u0429':'SHCHcy','\u044A':'hardcy','\u042A':'HARDcy','\u044B':'ycy','\u042B':'Ycy','\u044C':'softcy','\u042C':'SOFTcy','\u044D':'ecy','\u042D':'Ecy','\u044E':'yucy','\u042E':'YUcy','\u044F':'yacy','\u042F':'YAcy','\u2135':'aleph','\u2136':'beth','\u2137':'gimel','\u2138':'daleth'};
var regexEscape = /["&'<>`]/g;
var escapeMap = {
'"': '"',
'&': '&',
'\'': ''',
'<': '<',
// See https://mathiasbynens.be/notes/ambiguous-ampersands: in HTML, the
// following is not strictly necessary unless it’s part of a tag or an
// unquoted attribute value. We’re only escaping it to support those
// situations, and for XML support.
'>': '>',
// In Internet Explorer ≤ 8, the backtick character can be used
// to break out of (un)quoted attribute values or HTML comments.
// See http://html5sec.org/#102, http://html5sec.org/#108, and
// http://html5sec.org/#133.
'`': '`'
};
var regexInvalidEntity = /&#(?:[xX][^a-fA-F0-9]|[^0-9xX])/;
var regexInvalidRawCodePoint = /[\0-\x08\x0B\x0E-\x1F\x7F-\x9F\uFDD0-\uFDEF\uFFFE\uFFFF]|[\uD83F\uD87F\uD8BF\uD8FF\uD93F\uD97F\uD9BF\uD9FF\uDA3F\uDA7F\uDABF\uDAFF\uDB3F\uDB7F\uDBBF\uDBFF][\uDFFE\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/;
var regexDecode = /&#([0-9]+)(;?)|&#[xX]([a-fA-F0-9]+)(;?)|&([0-9a-zA-Z]+);|&(Aacute|Agrave|Atilde|Ccedil|Eacute|Egrave|Iacute|Igrave|Ntilde|Oacute|Ograve|Oslash|Otilde|Uacute|Ugrave|Yacute|aacute|agrave|atilde|brvbar|ccedil|curren|divide|eacute|egrave|frac12|frac14|frac34|iacute|igrave|iquest|middot|ntilde|oacute|ograve|oslash|otilde|plusmn|uacute|ugrave|yacute|AElig|Acirc|Aring|Ecirc|Icirc|Ocirc|THORN|Ucirc|acirc|acute|aelig|aring|cedil|ecirc|icirc|iexcl|laquo|micro|ocirc|pound|raquo|szlig|thorn|times|ucirc|Auml|COPY|Euml|Iuml|Ouml|QUOT|Uuml|auml|cent|copy|euml|iuml|macr|nbsp|ordf|ordm|ouml|para|quot|sect|sup1|sup2|sup3|uuml|yuml|AMP|ETH|REG|amp|deg|eth|not|reg|shy|uml|yen|GT|LT|gt|lt)([=a-zA-Z0-9])?/g;
var decodeMap = {'aacute':'\xE1','Aacute':'\xC1','abreve':'\u0103','Abreve':'\u0102','ac':'\u223E','acd':'\u223F','acE':'\u223E\u0333','acirc':'\xE2','Acirc':'\xC2','acute':'\xB4','acy':'\u0430','Acy':'\u0410','aelig':'\xE6','AElig':'\xC6','af':'\u2061','afr':'\uD835\uDD1E','Afr':'\uD835\uDD04','agrave':'\xE0','Agrave':'\xC0','alefsym':'\u2135','aleph':'\u2135','alpha':'\u03B1','Alpha':'\u0391','amacr':'\u0101','Amacr':'\u0100','amalg':'\u2A3F','amp':'&','AMP':'&','and':'\u2227','And':'\u2A53','andand':'\u2A55','andd':'\u2A5C','andslope':'\u2A58','andv':'\u2A5A','ang':'\u2220','ange':'\u29A4','angle':'\u2220','angmsd':'\u2221','angmsdaa':'\u29A8','angmsdab':'\u29A9','angmsdac':'\u29AA','angmsdad':'\u29AB','angmsdae':'\u29AC','angmsdaf':'\u29AD','angmsdag':'\u29AE','angmsdah':'\u29AF','angrt':'\u221F','angrtvb':'\u22BE','angrtvbd':'\u299D','angsph':'\u2222','angst':'\xC5','angzarr':'\u237C','aogon':'\u0105','Aogon':'\u0104','aopf':'\uD835\uDD52','Aopf':'\uD835\uDD38','ap':'\u2248','apacir':'\u2A6F','ape':'\u224A','apE':'\u2A70','apid':'\u224B','apos':'\'','ApplyFunction':'\u2061','approx':'\u2248','approxeq':'\u224A','aring':'\xE5','Aring':'\xC5','ascr':'\uD835\uDCB6','Ascr':'\uD835\uDC9C','Assign':'\u2254','ast':'*','asymp':'\u2248','asympeq':'\u224D','atilde':'\xE3','Atilde':'\xC3','auml':'\xE4','Auml':'\xC4','awconint':'\u2233','awint':'\u2A11','backcong':'\u224C','backepsilon':'\u03F6','backprime':'\u2035','backsim':'\u223D','backsimeq':'\u22CD','Backslash':'\u2216','Barv':'\u2AE7','barvee':'\u22BD','barwed':'\u2305','Barwed':'\u2306','barwedge':'\u2305','bbrk':'\u23B5','bbrktbrk':'\u23B6','bcong':'\u224C','bcy':'\u0431','Bcy':'\u0411','bdquo':'\u201E','becaus':'\u2235','because':'\u2235','Because':'\u2235','bemptyv':'\u29B0','bepsi':'\u03F6','bernou':'\u212C','Bernoullis':'\u212C','beta':'\u03B2','Beta':'\u0392','beth':'\u2136','between':'\u226C','bfr':'\uD835\uDD1F','Bfr':'\uD835\uDD05','bigcap':'\u22C2','bigcirc':'\u25EF','bigcup':'\u22C3','bigodot':'\u2A00','bigoplus':'\u2A01','bigotimes':'\u2A02','bigsqcup':'\u2A06','bigstar':'\u2605','bigtriangledown':'\u25BD','bigtriangleup':'\u25B3','biguplus':'\u2A04','bigvee':'\u22C1','bigwedge':'\u22C0','bkarow':'\u290D','blacklozenge':'\u29EB','blacksquare':'\u25AA','blacktriangle':'\u25B4','blacktriangledown':'\u25BE','blacktriangleleft':'\u25C2','blacktriangleright':'\u25B8','blank':'\u2423','blk12':'\u2592','blk14':'\u2591','blk34':'\u2593','block':'\u2588','bne':'=\u20E5','bnequiv':'\u2261\u20E5','bnot':'\u2310','bNot':'\u2AED','bopf':'\uD835\uDD53','Bopf':'\uD835\uDD39','bot':'\u22A5','bottom':'\u22A5','bowtie':'\u22C8','boxbox':'\u29C9','boxdl':'\u2510','boxdL':'\u2555','boxDl':'\u2556','boxDL':'\u2557','boxdr':'\u250C','boxdR':'\u2552','boxDr':'\u2553','boxDR':'\u2554','boxh':'\u2500','boxH':'\u2550','boxhd':'\u252C','boxhD':'\u2565','boxHd':'\u2564','boxHD':'\u2566','boxhu':'\u2534','boxhU':'\u2568','boxHu':'\u2567','boxHU':'\u2569','boxminus':'\u229F','boxplus':'\u229E','boxtimes':'\u22A0','boxul':'\u2518','boxuL':'\u255B','boxUl':'\u255C','boxUL':'\u255D','boxur':'\u2514','boxuR':'\u2558','boxUr':'\u2559','boxUR':'\u255A','boxv':'\u2502','boxV':'\u2551','boxvh':'\u253C','boxvH':'\u256A','boxVh':'\u256B','boxVH':'\u256C','boxvl':'\u2524','boxvL':'\u2561','boxVl':'\u2562','boxVL':'\u2563','boxvr':'\u251C','boxvR':'\u255E','boxVr':'\u255F','boxVR':'\u2560','bprime':'\u2035','breve':'\u02D8','Breve':'\u02D8','brvbar':'\xA6','bscr':'\uD835\uDCB7','Bscr':'\u212C','bsemi':'\u204F','bsim':'\u223D','bsime':'\u22CD','bsol':'\\','bsolb':'\u29C5','bsolhsub':'\u27C8','bull':'\u2022','bullet':'\u2022','bump':'\u224E','bumpe':'\u224F','bumpE':'\u2AAE','bumpeq':'\u224F','Bumpeq':'\u224E','cacute':'\u0107','Cacute':'\u0106','cap':'\u2229','Cap':'\u22D2','capand':'\u2A44','capbrcup':'\u2A49','capcap':'\u2A4B','capcup':'\u2A47','capdot':'\u2A40','CapitalDifferentialD':'\u2145','caps':'\u2229\uFE00','caret':'\u2041','caron':'\u02C7','Cayleys':'\u212D','ccaps':'\u2A4D','ccaron':'\u010D','Ccaron':'\u010C','ccedil':'\xE7','Ccedil':'\xC7','ccirc':'\u0109','Ccirc':'\u0108','Cconint':'\u2230','ccups':'\u2A4C','ccupssm':'\u2A50','cdot':'\u010B','Cdot':'\u010A','cedil':'\xB8','Cedilla':'\xB8','cemptyv':'\u29B2','cent':'\xA2','centerdot':'\xB7','CenterDot':'\xB7','cfr':'\uD835\uDD20','Cfr':'\u212D','chcy':'\u0447','CHcy':'\u0427','check':'\u2713','checkmark':'\u2713','chi':'\u03C7','Chi':'\u03A7','cir':'\u25CB','circ':'\u02C6','circeq':'\u2257','circlearrowleft':'\u21BA','circlearrowright':'\u21BB','circledast':'\u229B','circledcirc':'\u229A','circleddash':'\u229D','CircleDot':'\u2299','circledR':'\xAE','circledS':'\u24C8','CircleMinus':'\u2296','CirclePlus':'\u2295','CircleTimes':'\u2297','cire':'\u2257','cirE':'\u29C3','cirfnint':'\u2A10','cirmid':'\u2AEF','cirscir':'\u29C2','ClockwiseContourIntegral':'\u2232','CloseCurlyDoubleQuote':'\u201D','CloseCurlyQuote':'\u2019','clubs':'\u2663','clubsuit':'\u2663','colon':':','Colon':'\u2237','colone':'\u2254','Colone':'\u2A74','coloneq':'\u2254','comma':',','commat':'@','comp':'\u2201','compfn':'\u2218','complement':'\u2201','complexes':'\u2102','cong':'\u2245','congdot':'\u2A6D','Congruent':'\u2261','conint':'\u222E','Conint':'\u222F','ContourIntegral':'\u222E','copf':'\uD835\uDD54','Copf':'\u2102','coprod':'\u2210','Coproduct':'\u2210','copy':'\xA9','COPY':'\xA9','copysr':'\u2117','CounterClockwiseContourIntegral':'\u2233','crarr':'\u21B5','cross':'\u2717','Cross':'\u2A2F','cscr':'\uD835\uDCB8','Cscr':'\uD835\uDC9E','csub':'\u2ACF','csube':'\u2AD1','csup':'\u2AD0','csupe':'\u2AD2','ctdot':'\u22EF','cudarrl':'\u2938','cudarrr':'\u2935','cuepr':'\u22DE','cuesc':'\u22DF','cularr':'\u21B6','cularrp':'\u293D','cup':'\u222A','Cup':'\u22D3','cupbrcap':'\u2A48','cupcap':'\u2A46','CupCap':'\u224D','cupcup':'\u2A4A','cupdot':'\u228D','cupor':'\u2A45','cups':'\u222A\uFE00','curarr':'\u21B7','curarrm':'\u293C','curlyeqprec':'\u22DE','curlyeqsucc':'\u22DF','curlyvee':'\u22CE','curlywedge':'\u22CF','curren':'\xA4','curvearrowleft':'\u21B6','curvearrowright':'\u21B7','cuvee':'\u22CE','cuwed':'\u22CF','cwconint':'\u2232','cwint':'\u2231','cylcty':'\u232D','dagger':'\u2020','Dagger':'\u2021','daleth':'\u2138','darr':'\u2193','dArr':'\u21D3','Darr':'\u21A1','dash':'\u2010','dashv':'\u22A3','Dashv':'\u2AE4','dbkarow':'\u290F','dblac':'\u02DD','dcaron':'\u010F','Dcaron':'\u010E','dcy':'\u0434','Dcy':'\u0414','dd':'\u2146','DD':'\u2145','ddagger':'\u2021','ddarr':'\u21CA','DDotrahd':'\u2911','ddotseq':'\u2A77','deg':'\xB0','Del':'\u2207','delta':'\u03B4','Delta':'\u0394','demptyv':'\u29B1','dfisht':'\u297F','dfr':'\uD835\uDD21','Dfr':'\uD835\uDD07','dHar':'\u2965','dharl':'\u21C3','dharr':'\u21C2','DiacriticalAcute':'\xB4','DiacriticalDot':'\u02D9','DiacriticalDoubleAcute':'\u02DD','DiacriticalGrave':'`','DiacriticalTilde':'\u02DC','diam':'\u22C4','diamond':'\u22C4','Diamond':'\u22C4','diamondsuit':'\u2666','diams':'\u2666','die':'\xA8','DifferentialD':'\u2146','digamma':'\u03DD','disin':'\u22F2','div':'\xF7','divide':'\xF7','divideontimes':'\u22C7','divonx':'\u22C7','djcy':'\u0452','DJcy':'\u0402','dlcorn':'\u231E','dlcrop':'\u230D','dollar':'$','dopf':'\uD835\uDD55','Dopf':'\uD835\uDD3B','dot':'\u02D9','Dot':'\xA8','DotDot':'\u20DC','doteq':'\u2250','doteqdot':'\u2251','DotEqual':'\u2250','dotminus':'\u2238','dotplus':'\u2214','dotsquare':'\u22A1','doublebarwedge':'\u2306','DoubleContourIntegral':'\u222F','DoubleDot':'\xA8','DoubleDownArrow':'\u21D3','DoubleLeftArrow':'\u21D0','DoubleLeftRightArrow':'\u21D4','DoubleLeftTee':'\u2AE4','DoubleLongLeftArrow':'\u27F8','DoubleLongLeftRightArrow':'\u27FA','DoubleLongRightArrow':'\u27F9','DoubleRightArrow':'\u21D2','DoubleRightTee':'\u22A8','DoubleUpArrow':'\u21D1','DoubleUpDownArrow':'\u21D5','DoubleVerticalBar':'\u2225','downarrow':'\u2193','Downarrow':'\u21D3','DownArrow':'\u2193','DownArrowBar':'\u2913','DownArrowUpArrow':'\u21F5','DownBreve':'\u0311','downdownarrows':'\u21CA','downharpoonleft':'\u21C3','downharpoonright':'\u21C2','DownLeftRightVector':'\u2950','DownLeftTeeVector':'\u295E','DownLeftVector':'\u21BD','DownLeftVectorBar':'\u2956','DownRightTeeVector':'\u295F','DownRightVector':'\u21C1','DownRightVectorBar':'\u2957','DownTee':'\u22A4','DownTeeArrow':'\u21A7','drbkarow':'\u2910','drcorn':'\u231F','drcrop':'\u230C','dscr':'\uD835\uDCB9','Dscr':'\uD835\uDC9F','dscy':'\u0455','DScy':'\u0405','dsol':'\u29F6','dstrok':'\u0111','Dstrok':'\u0110','dtdot':'\u22F1','dtri':'\u25BF','dtrif':'\u25BE','duarr':'\u21F5','duhar':'\u296F','dwangle':'\u29A6','dzcy':'\u045F','DZcy':'\u040F','dzigrarr':'\u27FF','eacute':'\xE9','Eacute':'\xC9','easter':'\u2A6E','ecaron':'\u011B','Ecaron':'\u011A','ecir':'\u2256','ecirc':'\xEA','Ecirc':'\xCA','ecolon':'\u2255','ecy':'\u044D','Ecy':'\u042D','eDDot':'\u2A77','edot':'\u0117','eDot':'\u2251','Edot':'\u0116','ee':'\u2147','efDot':'\u2252','efr':'\uD835\uDD22','Efr':'\uD835\uDD08','eg':'\u2A9A','egrave':'\xE8','Egrave':'\xC8','egs':'\u2A96','egsdot':'\u2A98','el':'\u2A99','Element':'\u2208','elinters':'\u23E7','ell':'\u2113','els':'\u2A95','elsdot':'\u2A97','emacr':'\u0113','Emacr':'\u0112','empty':'\u2205','emptyset':'\u2205','EmptySmallSquare':'\u25FB','emptyv':'\u2205','EmptyVerySmallSquare':'\u25AB','emsp':'\u2003','emsp13':'\u2004','emsp14':'\u2005','eng':'\u014B','ENG':'\u014A','ensp':'\u2002','eogon':'\u0119','Eogon':'\u0118','eopf':'\uD835\uDD56','Eopf':'\uD835\uDD3C','epar':'\u22D5','eparsl':'\u29E3','eplus':'\u2A71','epsi':'\u03B5','epsilon':'\u03B5','Epsilon':'\u0395','epsiv':'\u03F5','eqcirc':'\u2256','eqcolon':'\u2255','eqsim':'\u2242','eqslantgtr':'\u2A96','eqslantless':'\u2A95','Equal':'\u2A75','equals':'=','EqualTilde':'\u2242','equest':'\u225F','Equilibrium':'\u21CC','equiv':'\u2261','equivDD':'\u2A78','eqvparsl':'\u29E5','erarr':'\u2971','erDot':'\u2253','escr':'\u212F','Escr':'\u2130','esdot':'\u2250','esim':'\u2242','Esim':'\u2A73','eta':'\u03B7','Eta':'\u0397','eth':'\xF0','ETH':'\xD0','euml':'\xEB','Euml':'\xCB','euro':'\u20AC','excl':'!','exist':'\u2203','Exists':'\u2203','expectation':'\u2130','exponentiale':'\u2147','ExponentialE':'\u2147','fallingdotseq':'\u2252','fcy':'\u0444','Fcy':'\u0424','female':'\u2640','ffilig':'\uFB03','fflig':'\uFB00','ffllig':'\uFB04','ffr':'\uD835\uDD23','Ffr':'\uD835\uDD09','filig':'\uFB01','FilledSmallSquare':'\u25FC','FilledVerySmallSquare':'\u25AA','fjlig':'fj','flat':'\u266D','fllig':'\uFB02','fltns':'\u25B1','fnof':'\u0192','fopf':'\uD835\uDD57','Fopf':'\uD835\uDD3D','forall':'\u2200','ForAll':'\u2200','fork':'\u22D4','forkv':'\u2AD9','Fouriertrf':'\u2131','fpartint':'\u2A0D','frac12':'\xBD','frac13':'\u2153','frac14':'\xBC','frac15':'\u2155','frac16':'\u2159','frac18':'\u215B','frac23':'\u2154','frac25':'\u2156','frac34':'\xBE','frac35':'\u2157','frac38':'\u215C','frac45':'\u2158','frac56':'\u215A','frac58':'\u215D','frac78':'\u215E','frasl':'\u2044','frown':'\u2322','fscr':'\uD835\uDCBB','Fscr':'\u2131','gacute':'\u01F5','gamma':'\u03B3','Gamma':'\u0393','gammad':'\u03DD','Gammad':'\u03DC','gap':'\u2A86','gbreve':'\u011F','Gbreve':'\u011E','Gcedil':'\u0122','gcirc':'\u011D','Gcirc':'\u011C','gcy':'\u0433','Gcy':'\u0413','gdot':'\u0121','Gdot':'\u0120','ge':'\u2265','gE':'\u2267','gel':'\u22DB','gEl':'\u2A8C','geq':'\u2265','geqq':'\u2267','geqslant':'\u2A7E','ges':'\u2A7E','gescc':'\u2AA9','gesdot':'\u2A80','gesdoto':'\u2A82','gesdotol':'\u2A84','gesl':'\u22DB\uFE00','gesles':'\u2A94','gfr':'\uD835\uDD24','Gfr':'\uD835\uDD0A','gg':'\u226B','Gg':'\u22D9','ggg':'\u22D9','gimel':'\u2137','gjcy':'\u0453','GJcy':'\u0403','gl':'\u2277','gla':'\u2AA5','glE':'\u2A92','glj':'\u2AA4','gnap':'\u2A8A','gnapprox':'\u2A8A','gne':'\u2A88','gnE':'\u2269','gneq':'\u2A88','gneqq':'\u2269','gnsim':'\u22E7','gopf':'\uD835\uDD58','Gopf':'\uD835\uDD3E','grave':'`','GreaterEqual':'\u2265','GreaterEqualLess':'\u22DB','GreaterFullEqual':'\u2267','GreaterGreater':'\u2AA2','GreaterLess':'\u2277','GreaterSlantEqual':'\u2A7E','GreaterTilde':'\u2273','gscr':'\u210A','Gscr':'\uD835\uDCA2','gsim':'\u2273','gsime':'\u2A8E','gsiml':'\u2A90','gt':'>','Gt':'\u226B','GT':'>','gtcc':'\u2AA7','gtcir':'\u2A7A','gtdot':'\u22D7','gtlPar':'\u2995','gtquest':'\u2A7C','gtrapprox':'\u2A86','gtrarr':'\u2978','gtrdot':'\u22D7','gtreqless':'\u22DB','gtreqqless':'\u2A8C','gtrless':'\u2277','gtrsim':'\u2273','gvertneqq':'\u2269\uFE00','gvnE':'\u2269\uFE00','Hacek':'\u02C7','hairsp':'\u200A','half':'\xBD','hamilt':'\u210B','hardcy':'\u044A','HARDcy':'\u042A','harr':'\u2194','hArr':'\u21D4','harrcir':'\u2948','harrw':'\u21AD','Hat':'^','hbar':'\u210F','hcirc':'\u0125','Hcirc':'\u0124','hearts':'\u2665','heartsuit':'\u2665','hellip':'\u2026','hercon':'\u22B9','hfr':'\uD835\uDD25','Hfr':'\u210C','HilbertSpace':'\u210B','hksearow':'\u2925','hkswarow':'\u2926','hoarr':'\u21FF','homtht':'\u223B','hookleftarrow':'\u21A9','hookrightarrow':'\u21AA','hopf':'\uD835\uDD59','Hopf':'\u210D','horbar':'\u2015','HorizontalLine':'\u2500','hscr':'\uD835\uDCBD','Hscr':'\u210B','hslash':'\u210F','hstrok':'\u0127','Hstrok':'\u0126','HumpDownHump':'\u224E','HumpEqual':'\u224F','hybull':'\u2043','hyphen':'\u2010','iacute':'\xED','Iacute':'\xCD','ic':'\u2063','icirc':'\xEE','Icirc':'\xCE','icy':'\u0438','Icy':'\u0418','Idot':'\u0130','iecy':'\u0435','IEcy':'\u0415','iexcl':'\xA1','iff':'\u21D4','ifr':'\uD835\uDD26','Ifr':'\u2111','igrave':'\xEC','Igrave':'\xCC','ii':'\u2148','iiiint':'\u2A0C','iiint':'\u222D','iinfin':'\u29DC','iiota':'\u2129','ijlig':'\u0133','IJlig':'\u0132','Im':'\u2111','imacr':'\u012B','Imacr':'\u012A','image':'\u2111','ImaginaryI':'\u2148','imagline':'\u2110','imagpart':'\u2111','imath':'\u0131','imof':'\u22B7','imped':'\u01B5','Implies':'\u21D2','in':'\u2208','incare':'\u2105','infin':'\u221E','infintie':'\u29DD','inodot':'\u0131','int':'\u222B','Int':'\u222C','intcal':'\u22BA','integers':'\u2124','Integral':'\u222B','intercal':'\u22BA','Intersection':'\u22C2','intlarhk':'\u2A17','intprod':'\u2A3C','InvisibleComma':'\u2063','InvisibleTimes':'\u2062','iocy':'\u0451','IOcy':'\u0401','iogon':'\u012F','Iogon':'\u012E','iopf':'\uD835\uDD5A','Iopf':'\uD835\uDD40','iota':'\u03B9','Iota':'\u0399','iprod':'\u2A3C','iquest':'\xBF','iscr':'\uD835\uDCBE','Iscr':'\u2110','isin':'\u2208','isindot':'\u22F5','isinE':'\u22F9','isins':'\u22F4','isinsv':'\u22F3','isinv':'\u2208','it':'\u2062','itilde':'\u0129','Itilde':'\u0128','iukcy':'\u0456','Iukcy':'\u0406','iuml':'\xEF','Iuml':'\xCF','jcirc':'\u0135','Jcirc':'\u0134','jcy':'\u0439','Jcy':'\u0419','jfr':'\uD835\uDD27','Jfr':'\uD835\uDD0D','jmath':'\u0237','jopf':'\uD835\uDD5B','Jopf':'\uD835\uDD41','jscr':'\uD835\uDCBF','Jscr':'\uD835\uDCA5','jsercy':'\u0458','Jsercy':'\u0408','jukcy':'\u0454','Jukcy':'\u0404','kappa':'\u03BA','Kappa':'\u039A','kappav':'\u03F0','kcedil':'\u0137','Kcedil':'\u0136','kcy':'\u043A','Kcy':'\u041A','kfr':'\uD835\uDD28','Kfr':'\uD835\uDD0E','kgreen':'\u0138','khcy':'\u0445','KHcy':'\u0425','kjcy':'\u045C','KJcy':'\u040C','kopf':'\uD835\uDD5C','Kopf':'\uD835\uDD42','kscr':'\uD835\uDCC0','Kscr':'\uD835\uDCA6','lAarr':'\u21DA','lacute':'\u013A','Lacute':'\u0139','laemptyv':'\u29B4','lagran':'\u2112','lambda':'\u03BB','Lambda':'\u039B','lang':'\u27E8','Lang':'\u27EA','langd':'\u2991','langle':'\u27E8','lap':'\u2A85','Laplacetrf':'\u2112','laquo':'\xAB','larr':'\u2190','lArr':'\u21D0','Larr':'\u219E','larrb':'\u21E4','larrbfs':'\u291F','larrfs':'\u291D','larrhk':'\u21A9','larrlp':'\u21AB','larrpl':'\u2939','larrsim':'\u2973','larrtl':'\u21A2','lat':'\u2AAB','latail':'\u2919','lAtail':'\u291B','late':'\u2AAD','lates':'\u2AAD\uFE00','lbarr':'\u290C','lBarr':'\u290E','lbbrk':'\u2772','lbrace':'{','lbrack':'[','lbrke':'\u298B','lbrksld':'\u298F','lbrkslu':'\u298D','lcaron':'\u013E','Lcaron':'\u013D','lcedil':'\u013C','Lcedil':'\u013B','lceil':'\u2308','lcub':'{','lcy':'\u043B','Lcy':'\u041B','ldca':'\u2936','ldquo':'\u201C','ldquor':'\u201E','ldrdhar':'\u2967','ldrushar':'\u294B','ldsh':'\u21B2','le':'\u2264','lE':'\u2266','LeftAngleBracket':'\u27E8','leftarrow':'\u2190','Leftarrow':'\u21D0','LeftArrow':'\u2190','LeftArrowBar':'\u21E4','LeftArrowRightArrow':'\u21C6','leftarrowtail':'\u21A2','LeftCeiling':'\u2308','LeftDoubleBracket':'\u27E6','LeftDownTeeVector':'\u2961','LeftDownVector':'\u21C3','LeftDownVectorBar':'\u2959','LeftFloor':'\u230A','leftharpoondown':'\u21BD','leftharpoonup':'\u21BC','leftleftarrows':'\u21C7','leftrightarrow':'\u2194','Leftrightarrow':'\u21D4','LeftRightArrow':'\u2194','leftrightarrows':'\u21C6','leftrightharpoons':'\u21CB','leftrightsquigarrow':'\u21AD','LeftRightVector':'\u294E','LeftTee':'\u22A3','LeftTeeArrow':'\u21A4','LeftTeeVector':'\u295A','leftthreetimes':'\u22CB','LeftTriangle':'\u22B2','LeftTriangleBar':'\u29CF','LeftTriangleEqual':'\u22B4','LeftUpDownVector':'\u2951','LeftUpTeeVector':'\u2960','LeftUpVector':'\u21BF','LeftUpVectorBar':'\u2958','LeftVector':'\u21BC','LeftVectorBar':'\u2952','leg':'\u22DA','lEg':'\u2A8B','leq':'\u2264','leqq':'\u2266','leqslant':'\u2A7D','les':'\u2A7D','lescc':'\u2AA8','lesdot':'\u2A7F','lesdoto':'\u2A81','lesdotor':'\u2A83','lesg':'\u22DA\uFE00','lesges':'\u2A93','lessapprox':'\u2A85','lessdot':'\u22D6','lesseqgtr':'\u22DA','lesseqqgtr':'\u2A8B','LessEqualGreater':'\u22DA','LessFullEqual':'\u2266','LessGreater':'\u2276','lessgtr':'\u2276','LessLess':'\u2AA1','lesssim':'\u2272','LessSlantEqual':'\u2A7D','LessTilde':'\u2272','lfisht':'\u297C','lfloor':'\u230A','lfr':'\uD835\uDD29','Lfr':'\uD835\uDD0F','lg':'\u2276','lgE':'\u2A91','lHar':'\u2962','lhard':'\u21BD','lharu':'\u21BC','lharul':'\u296A','lhblk':'\u2584','ljcy':'\u0459','LJcy':'\u0409','ll':'\u226A','Ll':'\u22D8','llarr':'\u21C7','llcorner':'\u231E','Lleftarrow':'\u21DA','llhard':'\u296B','lltri':'\u25FA','lmidot':'\u0140','Lmidot':'\u013F','lmoust':'\u23B0','lmoustache':'\u23B0','lnap':'\u2A89','lnapprox':'\u2A89','lne':'\u2A87','lnE':'\u2268','lneq':'\u2A87','lneqq':'\u2268','lnsim':'\u22E6','loang':'\u27EC','loarr':'\u21FD','lobrk':'\u27E6','longleftarrow':'\u27F5','Longleftarrow':'\u27F8','LongLeftArrow':'\u27F5','longleftrightarrow':'\u27F7','Longleftrightarrow':'\u27FA','LongLeftRightArrow':'\u27F7','longmapsto':'\u27FC','longrightarrow':'\u27F6','Longrightarrow':'\u27F9','LongRightArrow':'\u27F6','looparrowleft':'\u21AB','looparrowright':'\u21AC','lopar':'\u2985','lopf':'\uD835\uDD5D','Lopf':'\uD835\uDD43','loplus':'\u2A2D','lotimes':'\u2A34','lowast':'\u2217','lowbar':'_','LowerLeftArrow':'\u2199','LowerRightArrow':'\u2198','loz':'\u25CA','lozenge':'\u25CA','lozf':'\u29EB','lpar':'(','lparlt':'\u2993','lrarr':'\u21C6','lrcorner':'\u231F','lrhar':'\u21CB','lrhard':'\u296D','lrm':'\u200E','lrtri':'\u22BF','lsaquo':'\u2039','lscr':'\uD835\uDCC1','Lscr':'\u2112','lsh':'\u21B0','Lsh':'\u21B0','lsim':'\u2272','lsime':'\u2A8D','lsimg':'\u2A8F','lsqb':'[','lsquo':'\u2018','lsquor':'\u201A','lstrok':'\u0142','Lstrok':'\u0141','lt':'<','Lt':'\u226A','LT':'<','ltcc':'\u2AA6','ltcir':'\u2A79','ltdot':'\u22D6','lthree':'\u22CB','ltimes':'\u22C9','ltlarr':'\u2976','ltquest':'\u2A7B','ltri':'\u25C3','ltrie':'\u22B4','ltrif':'\u25C2','ltrPar':'\u2996','lurdshar':'\u294A','luruhar':'\u2966','lvertneqq':'\u2268\uFE00','lvnE':'\u2268\uFE00','macr':'\xAF','male':'\u2642','malt':'\u2720','maltese':'\u2720','map':'\u21A6','Map':'\u2905','mapsto':'\u21A6','mapstodown':'\u21A7','mapstoleft':'\u21A4','mapstoup':'\u21A5','marker':'\u25AE','mcomma':'\u2A29','mcy':'\u043C','Mcy':'\u041C','mdash':'\u2014','mDDot':'\u223A','measuredangle':'\u2221','MediumSpace':'\u205F','Mellintrf':'\u2133','mfr':'\uD835\uDD2A','Mfr':'\uD835\uDD10','mho':'\u2127','micro':'\xB5','mid':'\u2223','midast':'*','midcir':'\u2AF0','middot':'\xB7','minus':'\u2212','minusb':'\u229F','minusd':'\u2238','minusdu':'\u2A2A','MinusPlus':'\u2213','mlcp':'\u2ADB','mldr':'\u2026','mnplus':'\u2213','models':'\u22A7','mopf':'\uD835\uDD5E','Mopf':'\uD835\uDD44','mp':'\u2213','mscr':'\uD835\uDCC2','Mscr':'\u2133','mstpos':'\u223E','mu':'\u03BC','Mu':'\u039C','multimap':'\u22B8','mumap':'\u22B8','nabla':'\u2207','nacute':'\u0144','Nacute':'\u0143','nang':'\u2220\u20D2','nap':'\u2249','napE':'\u2A70\u0338','napid':'\u224B\u0338','napos':'\u0149','napprox':'\u2249','natur':'\u266E','natural':'\u266E','naturals':'\u2115','nbsp':'\xA0','nbump':'\u224E\u0338','nbumpe':'\u224F\u0338','ncap':'\u2A43','ncaron':'\u0148','Ncaron':'\u0147','ncedil':'\u0146','Ncedil':'\u0145','ncong':'\u2247','ncongdot':'\u2A6D\u0338','ncup':'\u2A42','ncy':'\u043D','Ncy':'\u041D','ndash':'\u2013','ne':'\u2260','nearhk':'\u2924','nearr':'\u2197','neArr':'\u21D7','nearrow':'\u2197','nedot':'\u2250\u0338','NegativeMediumSpace':'\u200B','NegativeThickSpace':'\u200B','NegativeThinSpace':'\u200B','NegativeVeryThinSpace':'\u200B','nequiv':'\u2262','nesear':'\u2928','nesim':'\u2242\u0338','NestedGreaterGreater':'\u226B','NestedLessLess':'\u226A','NewLine':'\n','nexist':'\u2204','nexists':'\u2204','nfr':'\uD835\uDD2B','Nfr':'\uD835\uDD11','nge':'\u2271','ngE':'\u2267\u0338','ngeq':'\u2271','ngeqq':'\u2267\u0338','ngeqslant':'\u2A7E\u0338','nges':'\u2A7E\u0338','nGg':'\u22D9\u0338','ngsim':'\u2275','ngt':'\u226F','nGt':'\u226B\u20D2','ngtr':'\u226F','nGtv':'\u226B\u0338','nharr':'\u21AE','nhArr':'\u21CE','nhpar':'\u2AF2','ni':'\u220B','nis':'\u22FC','nisd':'\u22FA','niv':'\u220B','njcy':'\u045A','NJcy':'\u040A','nlarr':'\u219A','nlArr':'\u21CD','nldr':'\u2025','nle':'\u2270','nlE':'\u2266\u0338','nleftarrow':'\u219A','nLeftarrow':'\u21CD','nleftrightarrow':'\u21AE','nLeftrightarrow':'\u21CE','nleq':'\u2270','nleqq':'\u2266\u0338','nleqslant':'\u2A7D\u0338','nles':'\u2A7D\u0338','nless':'\u226E','nLl':'\u22D8\u0338','nlsim':'\u2274','nlt':'\u226E','nLt':'\u226A\u20D2','nltri':'\u22EA','nltrie':'\u22EC','nLtv':'\u226A\u0338','nmid':'\u2224','NoBreak':'\u2060','NonBreakingSpace':'\xA0','nopf':'\uD835\uDD5F','Nopf':'\u2115','not':'\xAC','Not':'\u2AEC','NotCongruent':'\u2262','NotCupCap':'\u226D','NotDoubleVerticalBar':'\u2226','NotElement':'\u2209','NotEqual':'\u2260','NotEqualTilde':'\u2242\u0338','NotExists':'\u2204','NotGreater':'\u226F','NotGreaterEqual':'\u2271','NotGreaterFullEqual':'\u2267\u0338','NotGreaterGreater':'\u226B\u0338','NotGreaterLess':'\u2279','NotGreaterSlantEqual':'\u2A7E\u0338','NotGreaterTilde':'\u2275','NotHumpDownHump':'\u224E\u0338','NotHumpEqual':'\u224F\u0338','notin':'\u2209','notindot':'\u22F5\u0338','notinE':'\u22F9\u0338','notinva':'\u2209','notinvb':'\u22F7','notinvc':'\u22F6','NotLeftTriangle':'\u22EA','NotLeftTriangleBar':'\u29CF\u0338','NotLeftTriangleEqual':'\u22EC','NotLess':'\u226E','NotLessEqual':'\u2270','NotLessGreater':'\u2278','NotLessLess':'\u226A\u0338','NotLessSlantEqual':'\u2A7D\u0338','NotLessTilde':'\u2274','NotNestedGreaterGreater':'\u2AA2\u0338','NotNestedLessLess':'\u2AA1\u0338','notni':'\u220C','notniva':'\u220C','notnivb':'\u22FE','notnivc':'\u22FD','NotPrecedes':'\u2280','NotPrecedesEqual':'\u2AAF\u0338','NotPrecedesSlantEqual':'\u22E0','NotReverseElement':'\u220C','NotRightTriangle':'\u22EB','NotRightTriangleBar':'\u29D0\u0338','NotRightTriangleEqual':'\u22ED','NotSquareSubset':'\u228F\u0338','NotSquareSubsetEqual':'\u22E2','NotSquareSuperset':'\u2290\u0338','NotSquareSupersetEqual':'\u22E3','NotSubset':'\u2282\u20D2','NotSubsetEqual':'\u2288','NotSucceeds':'\u2281','NotSucceedsEqual':'\u2AB0\u0338','NotSucceedsSlantEqual':'\u22E1','NotSucceedsTilde':'\u227F\u0338','NotSuperset':'\u2283\u20D2','NotSupersetEqual':'\u2289','NotTilde':'\u2241','NotTildeEqual':'\u2244','NotTildeFullEqual':'\u2247','NotTildeTilde':'\u2249','NotVerticalBar':'\u2224','npar':'\u2226','nparallel':'\u2226','nparsl':'\u2AFD\u20E5','npart':'\u2202\u0338','npolint':'\u2A14','npr':'\u2280','nprcue':'\u22E0','npre':'\u2AAF\u0338','nprec':'\u2280','npreceq':'\u2AAF\u0338','nrarr':'\u219B','nrArr':'\u21CF','nrarrc':'\u2933\u0338','nrarrw':'\u219D\u0338','nrightarrow':'\u219B','nRightarrow':'\u21CF','nrtri':'\u22EB','nrtrie':'\u22ED','nsc':'\u2281','nsccue':'\u22E1','nsce':'\u2AB0\u0338','nscr':'\uD835\uDCC3','Nscr':'\uD835\uDCA9','nshortmid':'\u2224','nshortparallel':'\u2226','nsim':'\u2241','nsime':'\u2244','nsimeq':'\u2244','nsmid':'\u2224','nspar':'\u2226','nsqsube':'\u22E2','nsqsupe':'\u22E3','nsub':'\u2284','nsube':'\u2288','nsubE':'\u2AC5\u0338','nsubset':'\u2282\u20D2','nsubseteq':'\u2288','nsubseteqq':'\u2AC5\u0338','nsucc':'\u2281','nsucceq':'\u2AB0\u0338','nsup':'\u2285','nsupe':'\u2289','nsupE':'\u2AC6\u0338','nsupset':'\u2283\u20D2','nsupseteq':'\u2289','nsupseteqq':'\u2AC6\u0338','ntgl':'\u2279','ntilde':'\xF1','Ntilde':'\xD1','ntlg':'\u2278','ntriangleleft':'\u22EA','ntrianglelefteq':'\u22EC','ntriangleright':'\u22EB','ntrianglerighteq':'\u22ED','nu':'\u03BD','Nu':'\u039D','num':'#','numero':'\u2116','numsp':'\u2007','nvap':'\u224D\u20D2','nvdash':'\u22AC','nvDash':'\u22AD','nVdash':'\u22AE','nVDash':'\u22AF','nvge':'\u2265\u20D2','nvgt':'>\u20D2','nvHarr':'\u2904','nvinfin':'\u29DE','nvlArr':'\u2902','nvle':'\u2264\u20D2','nvlt':'<\u20D2','nvltrie':'\u22B4\u20D2','nvrArr':'\u2903','nvrtrie':'\u22B5\u20D2','nvsim':'\u223C\u20D2','nwarhk':'\u2923','nwarr':'\u2196','nwArr':'\u21D6','nwarrow':'\u2196','nwnear':'\u2927','oacute':'\xF3','Oacute':'\xD3','oast':'\u229B','ocir':'\u229A','ocirc':'\xF4','Ocirc':'\xD4','ocy':'\u043E','Ocy':'\u041E','odash':'\u229D','odblac':'\u0151','Odblac':'\u0150','odiv':'\u2A38','odot':'\u2299','odsold':'\u29BC','oelig':'\u0153','OElig':'\u0152','ofcir':'\u29BF','ofr':'\uD835\uDD2C','Ofr':'\uD835\uDD12','ogon':'\u02DB','ograve':'\xF2','Ograve':'\xD2','ogt':'\u29C1','ohbar':'\u29B5','ohm':'\u03A9','oint':'\u222E','olarr':'\u21BA','olcir':'\u29BE','olcross':'\u29BB','oline':'\u203E','olt':'\u29C0','omacr':'\u014D','Omacr':'\u014C','omega':'\u03C9','Omega':'\u03A9','omicron':'\u03BF','Omicron':'\u039F','omid':'\u29B6','ominus':'\u2296','oopf':'\uD835\uDD60','Oopf':'\uD835\uDD46','opar':'\u29B7','OpenCurlyDoubleQuote':'\u201C','OpenCurlyQuote':'\u2018','operp':'\u29B9','oplus':'\u2295','or':'\u2228','Or':'\u2A54','orarr':'\u21BB','ord':'\u2A5D','order':'\u2134','orderof':'\u2134','ordf':'\xAA','ordm':'\xBA','origof':'\u22B6','oror':'\u2A56','orslope':'\u2A57','orv':'\u2A5B','oS':'\u24C8','oscr':'\u2134','Oscr':'\uD835\uDCAA','oslash':'\xF8','Oslash':'\xD8','osol':'\u2298','otilde':'\xF5','Otilde':'\xD5','otimes':'\u2297','Otimes':'\u2A37','otimesas':'\u2A36','ouml':'\xF6','Ouml':'\xD6','ovbar':'\u233D','OverBar':'\u203E','OverBrace':'\u23DE','OverBracket':'\u23B4','OverParenthesis':'\u23DC','par':'\u2225','para':'\xB6','parallel':'\u2225','parsim':'\u2AF3','parsl':'\u2AFD','part':'\u2202','PartialD':'\u2202','pcy':'\u043F','Pcy':'\u041F','percnt':'%','period':'.','permil':'\u2030','perp':'\u22A5','pertenk':'\u2031','pfr':'\uD835\uDD2D','Pfr':'\uD835\uDD13','phi':'\u03C6','Phi':'\u03A6','phiv':'\u03D5','phmmat':'\u2133','phone':'\u260E','pi':'\u03C0','Pi':'\u03A0','pitchfork':'\u22D4','piv':'\u03D6','planck':'\u210F','planckh':'\u210E','plankv':'\u210F','plus':'+','plusacir':'\u2A23','plusb':'\u229E','pluscir':'\u2A22','plusdo':'\u2214','plusdu':'\u2A25','pluse':'\u2A72','PlusMinus':'\xB1','plusmn':'\xB1','plussim':'\u2A26','plustwo':'\u2A27','pm':'\xB1','Poincareplane':'\u210C','pointint':'\u2A15','popf':'\uD835\uDD61','Popf':'\u2119','pound':'\xA3','pr':'\u227A','Pr':'\u2ABB','prap':'\u2AB7','prcue':'\u227C','pre':'\u2AAF','prE':'\u2AB3','prec':'\u227A','precapprox':'\u2AB7','preccurlyeq':'\u227C','Precedes':'\u227A','PrecedesEqual':'\u2AAF','PrecedesSlantEqual':'\u227C','PrecedesTilde':'\u227E','preceq':'\u2AAF','precnapprox':'\u2AB9','precneqq':'\u2AB5','precnsim':'\u22E8','precsim':'\u227E','prime':'\u2032','Prime':'\u2033','primes':'\u2119','prnap':'\u2AB9','prnE':'\u2AB5','prnsim':'\u22E8','prod':'\u220F','Product':'\u220F','profalar':'\u232E','profline':'\u2312','profsurf':'\u2313','prop':'\u221D','Proportion':'\u2237','Proportional':'\u221D','propto':'\u221D','prsim':'\u227E','prurel':'\u22B0','pscr':'\uD835\uDCC5','Pscr':'\uD835\uDCAB','psi':'\u03C8','Psi':'\u03A8','puncsp':'\u2008','qfr':'\uD835\uDD2E','Qfr':'\uD835\uDD14','qint':'\u2A0C','qopf':'\uD835\uDD62','Qopf':'\u211A','qprime':'\u2057','qscr':'\uD835\uDCC6','Qscr':'\uD835\uDCAC','quaternions':'\u210D','quatint':'\u2A16','quest':'?','questeq':'\u225F','quot':'"','QUOT':'"','rAarr':'\u21DB','race':'\u223D\u0331','racute':'\u0155','Racute':'\u0154','radic':'\u221A','raemptyv':'\u29B3','rang':'\u27E9','Rang':'\u27EB','rangd':'\u2992','range':'\u29A5','rangle':'\u27E9','raquo':'\xBB','rarr':'\u2192','rArr':'\u21D2','Rarr':'\u21A0','rarrap':'\u2975','rarrb':'\u21E5','rarrbfs':'\u2920','rarrc':'\u2933','rarrfs':'\u291E','rarrhk':'\u21AA','rarrlp':'\u21AC','rarrpl':'\u2945','rarrsim':'\u2974','rarrtl':'\u21A3','Rarrtl':'\u2916','rarrw':'\u219D','ratail':'\u291A','rAtail':'\u291C','ratio':'\u2236','rationals':'\u211A','rbarr':'\u290D','rBarr':'\u290F','RBarr':'\u2910','rbbrk':'\u2773','rbrace':'}','rbrack':']','rbrke':'\u298C','rbrksld':'\u298E','rbrkslu':'\u2990','rcaron':'\u0159','Rcaron':'\u0158','rcedil':'\u0157','Rcedil':'\u0156','rceil':'\u2309','rcub':'}','rcy':'\u0440','Rcy':'\u0420','rdca':'\u2937','rdldhar':'\u2969','rdquo':'\u201D','rdquor':'\u201D','rdsh':'\u21B3','Re':'\u211C','real':'\u211C','realine':'\u211B','realpart':'\u211C','reals':'\u211D','rect':'\u25AD','reg':'\xAE','REG':'\xAE','ReverseElement':'\u220B','ReverseEquilibrium':'\u21CB','ReverseUpEquilibrium':'\u296F','rfisht':'\u297D','rfloor':'\u230B','rfr':'\uD835\uDD2F','Rfr':'\u211C','rHar':'\u2964','rhard':'\u21C1','rharu':'\u21C0','rharul':'\u296C','rho':'\u03C1','Rho':'\u03A1','rhov':'\u03F1','RightAngleBracket':'\u27E9','rightarrow':'\u2192','Rightarrow':'\u21D2','RightArrow':'\u2192','RightArrowBar':'\u21E5','RightArrowLeftArrow':'\u21C4','rightarrowtail':'\u21A3','RightCeiling':'\u2309','RightDoubleBracket':'\u27E7','RightDownTeeVector':'\u295D','RightDownVector':'\u21C2','RightDownVectorBar':'\u2955','RightFloor':'\u230B','rightharpoondown':'\u21C1','rightharpoonup':'\u21C0','rightleftarrows':'\u21C4','rightleftharpoons':'\u21CC','rightrightarrows':'\u21C9','rightsquigarrow':'\u219D','RightTee':'\u22A2','RightTeeArrow':'\u21A6','RightTeeVector':'\u295B','rightthreetimes':'\u22CC','RightTriangle':'\u22B3','RightTriangleBar':'\u29D0','RightTriangleEqual':'\u22B5','RightUpDownVector':'\u294F','RightUpTeeVector':'\u295C','RightUpVector':'\u21BE','RightUpVectorBar':'\u2954','RightVector':'\u21C0','RightVectorBar':'\u2953','ring':'\u02DA','risingdotseq':'\u2253','rlarr':'\u21C4','rlhar':'\u21CC','rlm':'\u200F','rmoust':'\u23B1','rmoustache':'\u23B1','rnmid':'\u2AEE','roang':'\u27ED','roarr':'\u21FE','robrk':'\u27E7','ropar':'\u2986','ropf':'\uD835\uDD63','Ropf':'\u211D','roplus':'\u2A2E','rotimes':'\u2A35','RoundImplies':'\u2970','rpar':')','rpargt':'\u2994','rppolint':'\u2A12','rrarr':'\u21C9','Rrightarrow':'\u21DB','rsaquo':'\u203A','rscr':'\uD835\uDCC7','Rscr':'\u211B','rsh':'\u21B1','Rsh':'\u21B1','rsqb':']','rsquo':'\u2019','rsquor':'\u2019','rthree':'\u22CC','rtimes':'\u22CA','rtri':'\u25B9','rtrie':'\u22B5','rtrif':'\u25B8','rtriltri':'\u29CE','RuleDelayed':'\u29F4','ruluhar':'\u2968','rx':'\u211E','sacute':'\u015B','Sacute':'\u015A','sbquo':'\u201A','sc':'\u227B','Sc':'\u2ABC','scap':'\u2AB8','scaron':'\u0161','Scaron':'\u0160','sccue':'\u227D','sce':'\u2AB0','scE':'\u2AB4','scedil':'\u015F','Scedil':'\u015E','scirc':'\u015D','Scirc':'\u015C','scnap':'\u2ABA','scnE':'\u2AB6','scnsim':'\u22E9','scpolint':'\u2A13','scsim':'\u227F','scy':'\u0441','Scy':'\u0421','sdot':'\u22C5','sdotb':'\u22A1','sdote':'\u2A66','searhk':'\u2925','searr':'\u2198','seArr':'\u21D8','searrow':'\u2198','sect':'\xA7','semi':';','seswar':'\u2929','setminus':'\u2216','setmn':'\u2216','sext':'\u2736','sfr':'\uD835\uDD30','Sfr':'\uD835\uDD16','sfrown':'\u2322','sharp':'\u266F','shchcy':'\u0449','SHCHcy':'\u0429','shcy':'\u0448','SHcy':'\u0428','ShortDownArrow':'\u2193','ShortLeftArrow':'\u2190','shortmid':'\u2223','shortparallel':'\u2225','ShortRightArrow':'\u2192','ShortUpArrow':'\u2191','shy':'\xAD','sigma':'\u03C3','Sigma':'\u03A3','sigmaf':'\u03C2','sigmav':'\u03C2','sim':'\u223C','simdot':'\u2A6A','sime':'\u2243','simeq':'\u2243','simg':'\u2A9E','simgE':'\u2AA0','siml':'\u2A9D','simlE':'\u2A9F','simne':'\u2246','simplus':'\u2A24','simrarr':'\u2972','slarr':'\u2190','SmallCircle':'\u2218','smallsetminus':'\u2216','smashp':'\u2A33','smeparsl':'\u29E4','smid':'\u2223','smile':'\u2323','smt':'\u2AAA','smte':'\u2AAC','smtes':'\u2AAC\uFE00','softcy':'\u044C','SOFTcy':'\u042C','sol':'/','solb':'\u29C4','solbar':'\u233F','sopf':'\uD835\uDD64','Sopf':'\uD835\uDD4A','spades':'\u2660','spadesuit':'\u2660','spar':'\u2225','sqcap':'\u2293','sqcaps':'\u2293\uFE00','sqcup':'\u2294','sqcups':'\u2294\uFE00','Sqrt':'\u221A','sqsub':'\u228F','sqsube':'\u2291','sqsubset':'\u228F','sqsubseteq':'\u2291','sqsup':'\u2290','sqsupe':'\u2292','sqsupset':'\u2290','sqsupseteq':'\u2292','squ':'\u25A1','square':'\u25A1','Square':'\u25A1','SquareIntersection':'\u2293','SquareSubset':'\u228F','SquareSubsetEqual':'\u2291','SquareSuperset':'\u2290','SquareSupersetEqual':'\u2292','SquareUnion':'\u2294','squarf':'\u25AA','squf':'\u25AA','srarr':'\u2192','sscr':'\uD835\uDCC8','Sscr':'\uD835\uDCAE','ssetmn':'\u2216','ssmile':'\u2323','sstarf':'\u22C6','star':'\u2606','Star':'\u22C6','starf':'\u2605','straightepsilon':'\u03F5','straightphi':'\u03D5','strns':'\xAF','sub':'\u2282','Sub':'\u22D0','subdot':'\u2ABD','sube':'\u2286','subE':'\u2AC5','subedot':'\u2AC3','submult':'\u2AC1','subne':'\u228A','subnE':'\u2ACB','subplus':'\u2ABF','subrarr':'\u2979','subset':'\u2282','Subset':'\u22D0','subseteq':'\u2286','subseteqq':'\u2AC5','SubsetEqual':'\u2286','subsetneq':'\u228A','subsetneqq':'\u2ACB','subsim':'\u2AC7','subsub':'\u2AD5','subsup':'\u2AD3','succ':'\u227B','succapprox':'\u2AB8','succcurlyeq':'\u227D','Succeeds':'\u227B','SucceedsEqual':'\u2AB0','SucceedsSlantEqual':'\u227D','SucceedsTilde':'\u227F','succeq':'\u2AB0','succnapprox':'\u2ABA','succneqq':'\u2AB6','succnsim':'\u22E9','succsim':'\u227F','SuchThat':'\u220B','sum':'\u2211','Sum':'\u2211','sung':'\u266A','sup':'\u2283','Sup':'\u22D1','sup1':'\xB9','sup2':'\xB2','sup3':'\xB3','supdot':'\u2ABE','supdsub':'\u2AD8','supe':'\u2287','supE':'\u2AC6','supedot':'\u2AC4','Superset':'\u2283','SupersetEqual':'\u2287','suphsol':'\u27C9','suphsub':'\u2AD7','suplarr':'\u297B','supmult':'\u2AC2','supne':'\u228B','supnE':'\u2ACC','supplus':'\u2AC0','supset':'\u2283','Supset':'\u22D1','supseteq':'\u2287','supseteqq':'\u2AC6','supsetneq':'\u228B','supsetneqq':'\u2ACC','supsim':'\u2AC8','supsub':'\u2AD4','supsup':'\u2AD6','swarhk':'\u2926','swarr':'\u2199','swArr':'\u21D9','swarrow':'\u2199','swnwar':'\u292A','szlig':'\xDF','Tab':'\t','target':'\u2316','tau':'\u03C4','Tau':'\u03A4','tbrk':'\u23B4','tcaron':'\u0165','Tcaron':'\u0164','tcedil':'\u0163','Tcedil':'\u0162','tcy':'\u0442','Tcy':'\u0422','tdot':'\u20DB','telrec':'\u2315','tfr':'\uD835\uDD31','Tfr':'\uD835\uDD17','there4':'\u2234','therefore':'\u2234','Therefore':'\u2234','theta':'\u03B8','Theta':'\u0398','thetasym':'\u03D1','thetav':'\u03D1','thickapprox':'\u2248','thicksim':'\u223C','ThickSpace':'\u205F\u200A','thinsp':'\u2009','ThinSpace':'\u2009','thkap':'\u2248','thksim':'\u223C','thorn':'\xFE','THORN':'\xDE','tilde':'\u02DC','Tilde':'\u223C','TildeEqual':'\u2243','TildeFullEqual':'\u2245','TildeTilde':'\u2248','times':'\xD7','timesb':'\u22A0','timesbar':'\u2A31','timesd':'\u2A30','tint':'\u222D','toea':'\u2928','top':'\u22A4','topbot':'\u2336','topcir':'\u2AF1','topf':'\uD835\uDD65','Topf':'\uD835\uDD4B','topfork':'\u2ADA','tosa':'\u2929','tprime':'\u2034','trade':'\u2122','TRADE':'\u2122','triangle':'\u25B5','triangledown':'\u25BF','triangleleft':'\u25C3','trianglelefteq':'\u22B4','triangleq':'\u225C','triangleright':'\u25B9','trianglerighteq':'\u22B5','tridot':'\u25EC','trie':'\u225C','triminus':'\u2A3A','TripleDot':'\u20DB','triplus':'\u2A39','trisb':'\u29CD','tritime':'\u2A3B','trpezium':'\u23E2','tscr':'\uD835\uDCC9','Tscr':'\uD835\uDCAF','tscy':'\u0446','TScy':'\u0426','tshcy':'\u045B','TSHcy':'\u040B','tstrok':'\u0167','Tstrok':'\u0166','twixt':'\u226C','twoheadleftarrow':'\u219E','twoheadrightarrow':'\u21A0','uacute':'\xFA','Uacute':'\xDA','uarr':'\u2191','uArr':'\u21D1','Uarr':'\u219F','Uarrocir':'\u2949','ubrcy':'\u045E','Ubrcy':'\u040E','ubreve':'\u016D','Ubreve':'\u016C','ucirc':'\xFB','Ucirc':'\xDB','ucy':'\u0443','Ucy':'\u0423','udarr':'\u21C5','udblac':'\u0171','Udblac':'\u0170','udhar':'\u296E','ufisht':'\u297E','ufr':'\uD835\uDD32','Ufr':'\uD835\uDD18','ugrave':'\xF9','Ugrave':'\xD9','uHar':'\u2963','uharl':'\u21BF','uharr':'\u21BE','uhblk':'\u2580','ulcorn':'\u231C','ulcorner':'\u231C','ulcrop':'\u230F','ultri':'\u25F8','umacr':'\u016B','Umacr':'\u016A','uml':'\xA8','UnderBar':'_','UnderBrace':'\u23DF','UnderBracket':'\u23B5','UnderParenthesis':'\u23DD','Union':'\u22C3','UnionPlus':'\u228E','uogon':'\u0173','Uogon':'\u0172','uopf':'\uD835\uDD66','Uopf':'\uD835\uDD4C','uparrow':'\u2191','Uparrow':'\u21D1','UpArrow':'\u2191','UpArrowBar':'\u2912','UpArrowDownArrow':'\u21C5','updownarrow':'\u2195','Updownarrow':'\u21D5','UpDownArrow':'\u2195','UpEquilibrium':'\u296E','upharpoonleft':'\u21BF','upharpoonright':'\u21BE','uplus':'\u228E','UpperLeftArrow':'\u2196','UpperRightArrow':'\u2197','upsi':'\u03C5','Upsi':'\u03D2','upsih':'\u03D2','upsilon':'\u03C5','Upsilon':'\u03A5','UpTee':'\u22A5','UpTeeArrow':'\u21A5','upuparrows':'\u21C8','urcorn':'\u231D','urcorner':'\u231D','urcrop':'\u230E','uring':'\u016F','Uring':'\u016E','urtri':'\u25F9','uscr':'\uD835\uDCCA','Uscr':'\uD835\uDCB0','utdot':'\u22F0','utilde':'\u0169','Utilde':'\u0168','utri':'\u25B5','utrif':'\u25B4','uuarr':'\u21C8','uuml':'\xFC','Uuml':'\xDC','uwangle':'\u29A7','vangrt':'\u299C','varepsilon':'\u03F5','varkappa':'\u03F0','varnothing':'\u2205','varphi':'\u03D5','varpi':'\u03D6','varpropto':'\u221D','varr':'\u2195','vArr':'\u21D5','varrho':'\u03F1','varsigma':'\u03C2','varsubsetneq':'\u228A\uFE00','varsubsetneqq':'\u2ACB\uFE00','varsupsetneq':'\u228B\uFE00','varsupsetneqq':'\u2ACC\uFE00','vartheta':'\u03D1','vartriangleleft':'\u22B2','vartriangleright':'\u22B3','vBar':'\u2AE8','Vbar':'\u2AEB','vBarv':'\u2AE9','vcy':'\u0432','Vcy':'\u0412','vdash':'\u22A2','vDash':'\u22A8','Vdash':'\u22A9','VDash':'\u22AB','Vdashl':'\u2AE6','vee':'\u2228','Vee':'\u22C1','veebar':'\u22BB','veeeq':'\u225A','vellip':'\u22EE','verbar':'|','Verbar':'\u2016','vert':'|','Vert':'\u2016','VerticalBar':'\u2223','VerticalLine':'|','VerticalSeparator':'\u2758','VerticalTilde':'\u2240','VeryThinSpace':'\u200A','vfr':'\uD835\uDD33','Vfr':'\uD835\uDD19','vltri':'\u22B2','vnsub':'\u2282\u20D2','vnsup':'\u2283\u20D2','vopf':'\uD835\uDD67','Vopf':'\uD835\uDD4D','vprop':'\u221D','vrtri':'\u22B3','vscr':'\uD835\uDCCB','Vscr':'\uD835\uDCB1','vsubne':'\u228A\uFE00','vsubnE':'\u2ACB\uFE00','vsupne':'\u228B\uFE00','vsupnE':'\u2ACC\uFE00','Vvdash':'\u22AA','vzigzag':'\u299A','wcirc':'\u0175','Wcirc':'\u0174','wedbar':'\u2A5F','wedge':'\u2227','Wedge':'\u22C0','wedgeq':'\u2259','weierp':'\u2118','wfr':'\uD835\uDD34','Wfr':'\uD835\uDD1A','wopf':'\uD835\uDD68','Wopf':'\uD835\uDD4E','wp':'\u2118','wr':'\u2240','wreath':'\u2240','wscr':'\uD835\uDCCC','Wscr':'\uD835\uDCB2','xcap':'\u22C2','xcirc':'\u25EF','xcup':'\u22C3','xdtri':'\u25BD','xfr':'\uD835\uDD35','Xfr':'\uD835\uDD1B','xharr':'\u27F7','xhArr':'\u27FA','xi':'\u03BE','Xi':'\u039E','xlarr':'\u27F5','xlArr':'\u27F8','xmap':'\u27FC','xnis':'\u22FB','xodot':'\u2A00','xopf':'\uD835\uDD69','Xopf':'\uD835\uDD4F','xoplus':'\u2A01','xotime':'\u2A02','xrarr':'\u27F6','xrArr':'\u27F9','xscr':'\uD835\uDCCD','Xscr':'\uD835\uDCB3','xsqcup':'\u2A06','xuplus':'\u2A04','xutri':'\u25B3','xvee':'\u22C1','xwedge':'\u22C0','yacute':'\xFD','Yacute':'\xDD','yacy':'\u044F','YAcy':'\u042F','ycirc':'\u0177','Ycirc':'\u0176','ycy':'\u044B','Ycy':'\u042B','yen':'\xA5','yfr':'\uD835\uDD36','Yfr':'\uD835\uDD1C','yicy':'\u0457','YIcy':'\u0407','yopf':'\uD835\uDD6A','Yopf':'\uD835\uDD50','yscr':'\uD835\uDCCE','Yscr':'\uD835\uDCB4','yucy':'\u044E','YUcy':'\u042E','yuml':'\xFF','Yuml':'\u0178','zacute':'\u017A','Zacute':'\u0179','zcaron':'\u017E','Zcaron':'\u017D','zcy':'\u0437','Zcy':'\u0417','zdot':'\u017C','Zdot':'\u017B','zeetrf':'\u2128','ZeroWidthSpace':'\u200B','zeta':'\u03B6','Zeta':'\u0396','zfr':'\uD835\uDD37','Zfr':'\u2128','zhcy':'\u0436','ZHcy':'\u0416','zigrarr':'\u21DD','zopf':'\uD835\uDD6B','Zopf':'\u2124','zscr':'\uD835\uDCCF','Zscr':'\uD835\uDCB5','zwj':'\u200D','zwnj':'\u200C'};
var decodeMapLegacy = {'aacute':'\xE1','Aacute':'\xC1','acirc':'\xE2','Acirc':'\xC2','acute':'\xB4','aelig':'\xE6','AElig':'\xC6','agrave':'\xE0','Agrave':'\xC0','amp':'&','AMP':'&','aring':'\xE5','Aring':'\xC5','atilde':'\xE3','Atilde':'\xC3','auml':'\xE4','Auml':'\xC4','brvbar':'\xA6','ccedil':'\xE7','Ccedil':'\xC7','cedil':'\xB8','cent':'\xA2','copy':'\xA9','COPY':'\xA9','curren':'\xA4','deg':'\xB0','divide':'\xF7','eacute':'\xE9','Eacute':'\xC9','ecirc':'\xEA','Ecirc':'\xCA','egrave':'\xE8','Egrave':'\xC8','eth':'\xF0','ETH':'\xD0','euml':'\xEB','Euml':'\xCB','frac12':'\xBD','frac14':'\xBC','frac34':'\xBE','gt':'>','GT':'>','iacute':'\xED','Iacute':'\xCD','icirc':'\xEE','Icirc':'\xCE','iexcl':'\xA1','igrave':'\xEC','Igrave':'\xCC','iquest':'\xBF','iuml':'\xEF','Iuml':'\xCF','laquo':'\xAB','lt':'<','LT':'<','macr':'\xAF','micro':'\xB5','middot':'\xB7','nbsp':'\xA0','not':'\xAC','ntilde':'\xF1','Ntilde':'\xD1','oacute':'\xF3','Oacute':'\xD3','ocirc':'\xF4','Ocirc':'\xD4','ograve':'\xF2','Ograve':'\xD2','ordf':'\xAA','ordm':'\xBA','oslash':'\xF8','Oslash':'\xD8','otilde':'\xF5','Otilde':'\xD5','ouml':'\xF6','Ouml':'\xD6','para':'\xB6','plusmn':'\xB1','pound':'\xA3','quot':'"','QUOT':'"','raquo':'\xBB','reg':'\xAE','REG':'\xAE','sect':'\xA7','shy':'\xAD','sup1':'\xB9','sup2':'\xB2','sup3':'\xB3','szlig':'\xDF','thorn':'\xFE','THORN':'\xDE','times':'\xD7','uacute':'\xFA','Uacute':'\xDA','ucirc':'\xFB','Ucirc':'\xDB','ugrave':'\xF9','Ugrave':'\xD9','uml':'\xA8','uuml':'\xFC','Uuml':'\xDC','yacute':'\xFD','Yacute':'\xDD','yen':'\xA5','yuml':'\xFF'};
var decodeMapNumeric = {'0':'\uFFFD','128':'\u20AC','130':'\u201A','131':'\u0192','132':'\u201E','133':'\u2026','134':'\u2020','135':'\u2021','136':'\u02C6','137':'\u2030','138':'\u0160','139':'\u2039','140':'\u0152','142':'\u017D','145':'\u2018','146':'\u2019','147':'\u201C','148':'\u201D','149':'\u2022','150':'\u2013','151':'\u2014','152':'\u02DC','153':'\u2122','154':'\u0161','155':'\u203A','156':'\u0153','158':'\u017E','159':'\u0178'};
var invalidReferenceCodePoints = [1,2,3,4,5,6,7,8,11,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,64976,64977,64978,64979,64980,64981,64982,64983,64984,64985,64986,64987,64988,64989,64990,64991,64992,64993,64994,64995,64996,64997,64998,64999,65000,65001,65002,65003,65004,65005,65006,65007,65534,65535,131070,131071,196606,196607,262142,262143,327678,327679,393214,393215,458750,458751,524286,524287,589822,589823,655358,655359,720894,720895,786430,786431,851966,851967,917502,917503,983038,983039,1048574,1048575,1114110,1114111];
/*--------------------------------------------------------------------------*/
var stringFromCharCode = String.fromCharCode;
var object = {};
var hasOwnProperty = object.hasOwnProperty;
var has = function(object, propertyName) {
return hasOwnProperty.call(object, propertyName);
};
var contains = function(array, value) {
var index = -1;
var length = array.length;
while (++index < length) {
if (array[index] == value) {
return true;
}
}
return false;
};
var merge = function(options, defaults) {
if (!options) {
return defaults;
}
var result = {};
var key;
for (key in defaults) {
// A `hasOwnProperty` check is not needed here, since only recognized
// option names are used anyway. Any others are ignored.
result[key] = has(options, key) ? options[key] : defaults[key];
}
return result;
};
// Modified version of `ucs2encode`; see https://mths.be/punycode.
var codePointToSymbol = function(codePoint, strict) {
var output = '';
if ((codePoint >= 0xD800 && codePoint <= 0xDFFF) || codePoint > 0x10FFFF) {
// See issue #4:
// “Otherwise, if the number is in the range 0xD800 to 0xDFFF or is
// greater than 0x10FFFF, then this is a parse error. Return a U+FFFD
// REPLACEMENT CHARACTER.”
if (strict) {
parseError('character reference outside the permissible Unicode range');
}
return '\uFFFD';
}
if (has(decodeMapNumeric, codePoint)) {
if (strict) {
parseError('disallowed character reference');
}
return decodeMapNumeric[codePoint];
}
if (strict && contains(invalidReferenceCodePoints, codePoint)) {
parseError('disallowed character reference');
}
if (codePoint > 0xFFFF) {
codePoint -= 0x10000;
output += stringFromCharCode(codePoint >>> 10 & 0x3FF | 0xD800);
codePoint = 0xDC00 | codePoint & 0x3FF;
}
output += stringFromCharCode(codePoint);
return output;
};
var hexEscape = function(codePoint) {
return '&#x' + codePoint.toString(16).toUpperCase() + ';';
};
var decEscape = function(codePoint) {
return '&#' + codePoint + ';';
};
var parseError = function(message) {
throw Error('Parse error: ' + message);
};
/*--------------------------------------------------------------------------*/
var encode = function(string, options) {
options = merge(options, encode.options);
var strict = options.strict;
if (strict && regexInvalidRawCodePoint.test(string)) {
parseError('forbidden code point');
}
var encodeEverything = options.encodeEverything;
var useNamedReferences = options.useNamedReferences;
var allowUnsafeSymbols = options.allowUnsafeSymbols;
var escapeCodePoint = options.decimal ? decEscape : hexEscape;
var escapeBmpSymbol = function(symbol) {
return escapeCodePoint(symbol.charCodeAt(0));
};
if (encodeEverything) {
// Encode ASCII symbols.
string = string.replace(regexAsciiWhitelist, function(symbol) {
// Use named references if requested & possible.
if (useNamedReferences && has(encodeMap, symbol)) {
return '&' + encodeMap[symbol] + ';';
}
return escapeBmpSymbol(symbol);
});
// Shorten a few escapes that represent two symbols, of which at least one
// is within the ASCII range.
if (useNamedReferences) {
string = string
.replace(/>\u20D2/g, '>⃒')
.replace(/<\u20D2/g, '<⃒')
.replace(/fj/g, 'fj');
}
// Encode non-ASCII symbols.
if (useNamedReferences) {
// Encode non-ASCII symbols that can be replaced with a named reference.
string = string.replace(regexEncodeNonAscii, function(string) {
// Note: there is no need to check `has(encodeMap, string)` here.
return '&' + encodeMap[string] + ';';
});
}
// Note: any remaining non-ASCII symbols are handled outside of the `if`.
} else if (useNamedReferences) {
// Apply named character references.
// Encode `<>"'&` using named character references.
if (!allowUnsafeSymbols) {
string = string.replace(regexEscape, function(string) {
return '&' + encodeMap[string] + ';'; // no need to check `has()` here
});
}
// Shorten escapes that represent two symbols, of which at least one is
// `<>"'&`.
string = string
.replace(/>\u20D2/g, '>⃒')
.replace(/<\u20D2/g, '<⃒');
// Encode non-ASCII symbols that can be replaced with a named reference.
string = string.replace(regexEncodeNonAscii, function(string) {
// Note: there is no need to check `has(encodeMap, string)` here.
return '&' + encodeMap[string] + ';';
});
} else if (!allowUnsafeSymbols) {
// Encode `<>"'&` using hexadecimal escapes, now that they’re not handled
// using named character references.
string = string.replace(regexEscape, escapeBmpSymbol);
}
return string
// Encode astral symbols.
.replace(regexAstralSymbols, function($0) {
// https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
var high = $0.charCodeAt(0);
var low = $0.charCodeAt(1);
var codePoint = (high - 0xD800) * 0x400 + low - 0xDC00 + 0x10000;
return escapeCodePoint(codePoint);
})
// Encode any remaining BMP symbols that are not printable ASCII symbols
// using a hexadecimal escape.
.replace(regexBmpWhitelist, escapeBmpSymbol);
};
// Expose default options (so they can be overridden globally).
encode.options = {
'allowUnsafeSymbols': false,
'encodeEverything': false,
'strict': false,
'useNamedReferences': false,
'decimal' : false
};
var decode = function(html, options) {
options = merge(options, decode.options);
var strict = options.strict;
if (strict && regexInvalidEntity.test(html)) {
parseError('malformed character reference');
}
return html.replace(regexDecode, function($0, $1, $2, $3, $4, $5, $6, $7) {
var codePoint;
var semicolon;
var decDigits;
var hexDigits;
var reference;
var next;
if ($1) {
// Decode decimal escapes, e.g. `𝌆`.
decDigits = $1;
semicolon = $2;
if (strict && !semicolon) {
parseError('character reference was not terminated by a semicolon');
}
codePoint = parseInt(decDigits, 10);
return codePointToSymbol(codePoint, strict);
}
if ($3) {
// Decode hexadecimal escapes, e.g. `𝌆`.
hexDigits = $3;
semicolon = $4;
if (strict && !semicolon) {
parseError('character reference was not terminated by a semicolon');
}
codePoint = parseInt(hexDigits, 16);
return codePointToSymbol(codePoint, strict);
}
if ($5) {
// Decode named character references with trailing `;`, e.g. `©`.
reference = $5;
if (has(decodeMap, reference)) {
return decodeMap[reference];
} else {
// Ambiguous ampersand. https://mths.be/notes/ambiguous-ampersands
if (strict) {
parseError(
'named character reference was not terminated by a semicolon'
);
}
return $0;
}
}
// If we’re still here, it’s a legacy reference for sure. No need for an
// extra `if` check.
// Decode named character references without trailing `;`, e.g. `&`
// This is only a parse error if it gets converted to `&`, or if it is
// followed by `=` in an attribute context.
reference = $6;
next = $7;
if (next && options.isAttributeValue) {
if (strict && next == '=') {
parseError('`&` did not start a character reference');
}
return $0;
} else {
if (strict) {
parseError(
'named character reference was not terminated by a semicolon'
);
}
// Note: there is no need to check `has(decodeMapLegacy, reference)`.
return decodeMapLegacy[reference] + (next || '');
}
});
};
// Expose default options (so they can be overridden globally).
decode.options = {
'isAttributeValue': false,
'strict': false
};
var escape = function(string) {
return string.replace(regexEscape, function($0) {
// Note: there is no need to check `has(escapeMap, $0)` here.
return escapeMap[$0];
});
};
/*--------------------------------------------------------------------------*/
var he = {
'version': '1.1.1',
'encode': encode,
'decode': decode,
'escape': escape,
'unescape': decode
};
// Some AMD build optimizers, like r.js, check for specific condition patterns
// like the following:
if (
typeof undefined == 'function' &&
typeof undefined.amd == 'object' &&
undefined.amd
) {
undefined(function() {
return he;
});
} else if (freeExports && !freeExports.nodeType) {
if (freeModule) { // in Node.js, io.js, or RingoJS v0.8.0+
freeModule.exports = he;
} else { // in Narwhal or RingoJS v0.7.0-
for (var key in he) {
has(he, key) && (freeExports[key] = he[key]);
}
}
} else { // in Rhino or a web browser
root.he = he;
}
}(commonjsGlobal));
});
/**
* Not type-checking this file because it's mostly vendor code.
*/
/*!
* HTML Parser By John Resig (ejohn.org)
* Modified by Juriy "kangax" Zaytsev
* Original code by Erik Arvidsson, Mozilla Public License
* http://erik.eae.net/simplehtmlparser/simplehtmlparser.js
*/
// Regular Expressions for parsing tags and attributes
var singleAttrIdentifier = /([^\s"'<>/=]+)/;
var singleAttrAssign = /(?:=)/;
var singleAttrValues = [
// attr value double quotes
/"([^"]*)"+/.source,
// attr value, single quotes
/'([^']*)'+/.source,
// attr value, no quotes
/([^\s"'=<>`]+)/.source
];
var attribute = new RegExp(
'^\\s*' + singleAttrIdentifier.source +
'(?:\\s*(' + singleAttrAssign.source + ')' +
'\\s*(?:' + singleAttrValues.join('|') + '))?'
);
// could use https://www.w3.org/TR/1999/REC-xml-names-19990114/#NT-QName
// but for Vue templates we can enforce a simple charset
var ncname = '[a-zA-Z_][\\w\\-\\.]*';
var qnameCapture = '((?:' + ncname + '\\:)?' + ncname + ')';
var startTagOpen = new RegExp('^<' + qnameCapture);
var startTagClose = /^\s*(\/?)>/;
var endTag = new RegExp('^<\\/' + qnameCapture + '[^>]*>');
var doctype = /^]+>/i;
var comment = /^');
if (commentEnd >= 0) {
if (options.shouldKeepComment) {
options.comment(html.substring(4, commentEnd));
}
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(lastTag, 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);
advance(textEnd);
}
if (textEnd < 0) {
text = html;
html = '';
}
if (options.chars && text) {
options.chars(text);
}
} else {
var endTagLength = 0;
var stackedTag = lastTag.toLowerCase();
var reStackedTag = reCache[stackedTag] || (reCache[stackedTag] = new RegExp('([\\s\\S]*?)(]*>)', 'i'));
var rest$1 = html.replace(reStackedTag, function (all, text, endTag) {
endTagLength = endTag.length;
if (!isPlainTextElement(stackedTag) && stackedTag !== 'noscript') {
text = text
.replace(//g, '$1')
.replace(//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 ("development" !== 'production' && !stack.length && options.warn) {
options.warn(("Mal-formatted tag at end of template: \"" + html + "\""));
}
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(attribute))) {
advance(attr[0].length);
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];
// hackish work around FF bug https://bugzilla.mozilla.org/show_bug.cgi?id=369778
if (IS_REGEX_CAPTURING_BROKEN && args[0].indexOf('""') === -1) {
if (args[3] === '') { delete args[3]; }
if (args[4] === '') { delete args[4]; }
if (args[5] === '') { delete args[5]; }
}
var value = args[3] || args[4] || args[5] || '';
attrs[i] = {
name: args[1],
value: decodeAttr(
value,
options.shouldDecodeNewlines
)
};
}
if (!unary) {
stack.push({ tag: tagName, lowerCasedTag: tagName.toLowerCase(), attrs: attrs });
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; }
if (tagName) {
lowerCasedTagName = tagName.toLowerCase();
}
// Find the closest opened tag of the same type
if (tagName) {
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 ("development" !== 'production' &&
(i > pos || !tagName) &&
options.warn
) {
options.warn(
("tag <" + (stack[i].tag) + "> has no matching end tag.")
);
}
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+(?:in|of)\s+(.*)/;
var forIteratorRE = /\((\{[^}]*\}|[^,]*),([^,]*)(?:,([^,]*))?\)/;
var argRE = /:(.*)$/;
var bindRE = /^:|^v-bind:/;
var modifierRE = /\.[^.]+/g;
var decodeHTMLCached = cached(he.decode);
// configurable state
var warn$2;
var delimiters;
var transforms;
var preTransforms;
var postTransforms;
var platformIsPreTag;
var platformMustUseProp;
var platformGetTagNamespace;
/**
* 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;
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 root;
var currentParent;
var inVPre = false;
var inPre = false;
var warned = false;
function warnOnce (msg) {
if (!warned) {
warned = true;
warn$2(msg);
}
}
function endPre (element) {
// check pre state
if (element.pre) {
inVPre = false;
}
if (platformIsPreTag(element.tag)) {
inPre = false;
}
}
parseHTML(template, {
warn: warn$2,
expectHTML: options.expectHTML,
isUnaryTag: options.isUnaryTag,
canBeLeftOpenTag: options.canBeLeftOpenTag,
shouldDecodeNewlines: options.shouldDecodeNewlines,
shouldKeepComment: options.comments,
start: function start (tag, attrs, unary) {
// 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 = {
type: 1,
tag: tag,
attrsList: attrs,
attrsMap: makeAttrsMap(attrs),
parent: currentParent,
children: []
};
if (ns) {
element.ns = ns;
}
if (isForbiddenTag(element) && !isServerRendering()) {
element.forbidden = true;
"development" !== 'production' && 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.'
);
}
// apply pre-transforms
for (var i = 0; i < preTransforms.length; i++) {
preTransforms[i](element, options);
}
if (!inVPre) {
processPre(element);
if (element.pre) {
inVPre = true;
}
}
if (platformIsPreTag(element.tag)) {
inPre = true;
}
if (inVPre) {
processRawAttrs(element);
} else {
processFor(element);
processIf(element);
processOnce(element);
processKey(element);
// determine whether this is a plain element after
// removing structural attributes
element.plain = !element.key && !attrs.length;
processRef(element);
processSlot(element);
processComponent(element);
for (var i$1 = 0; i$1 < transforms.length; i$1++) {
transforms[i$1](element, options);
}
processAttrs(element);
}
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.'
);
}
if (el.attrsMap.hasOwnProperty('v-for')) {
warnOnce(
'Cannot use v-for on stateful component root element because ' +
'it renders multiple elements.'
);
}
}
}
// tree management
if (!root) {
root = element;
checkRootConstraints(root);
} else if (!stack.length) {
// 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."
);
}
}
if (currentParent && !element.forbidden) {
if (element.elseif || element.else) {
processIfConditions(element, currentParent);
} else if (element.slotScope) { // scoped slot
currentParent.plain = false;
var name = element.slotTarget || '"default"';(currentParent.scopedSlots || (currentParent.scopedSlots = {}))[name] = element;
} else {
currentParent.children.push(element);
element.parent = currentParent;
}
}
if (!unary) {
currentParent = element;
stack.push(element);
} else {
endPre(element);
}
// apply post-transforms
for (var i$2 = 0; i$2 < postTransforms.length; i$2++) {
postTransforms[i$2](element, options);
}
},
end: function end () {
// remove trailing whitespace
var element = stack[stack.length - 1];
var lastNode = element.children[element.children.length - 1];
if (lastNode && lastNode.type === 3 && lastNode.text === ' ' && !inPre) {
element.children.pop();
}
// pop stack
stack.length -= 1;
currentParent = stack[stack.length - 1];
endPre(element);
},
chars: function chars (text) {
if (!currentParent) {
{
if (text === template) {
warnOnce(
'Component template requires a root element, rather than just text.'
);
} else if ((text = text.trim())) {
warnOnce(
("text \"" + text + "\" outside root element will be ignored.")
);
}
}
return
}
// IE textarea placeholder bug
/* istanbul ignore if */
if (isIE &&
currentParent.tag === 'textarea' &&
currentParent.attrsMap.placeholder === text
) {
return
}
var children = currentParent.children;
text = inPre || text.trim()
? isTextTag(currentParent) ? text : decodeHTMLCached(text)
// only preserve whitespace if its not right after a starting tag
: preserveWhitespace && children.length ? ' ' : '';
if (text) {
var expression;
if (!inVPre && text !== ' ' && (expression = parseText(text, delimiters))) {
children.push({
type: 2,
expression: expression,
text: text
});
} else if (text !== ' ' || !children.length || children[children.length - 1].text !== ' ') {
children.push({
type: 3,
text: text
});
}
}
},
comment: function comment (text) {
currentParent.children.push({
type: 3,
text: text,
isComment: true
});
}
});
return root
}
function processPre (el) {
if (getAndRemoveAttr(el, 'v-pre') != null) {
el.pre = true;
}
}
function processRawAttrs (el) {
var l = el.attrsList.length;
if (l) {
var attrs = el.attrs = new Array(l);
for (var i = 0; i < l; i++) {
attrs[i] = {
name: el.attrsList[i].name,
value: JSON.stringify(el.attrsList[i].value)
};
}
} else if (!el.pre) {
// non root node in pre blocks with no attributes
el.plain = true;
}
}
function processKey (el) {
var exp = getBindingAttr(el, 'key');
if (exp) {
if ("development" !== 'production' && el.tag === 'template') {
warn$2("
cannot be keyed. Place the key on real elements instead.");
}
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 inMatch = exp.match(forAliasRE);
if (!inMatch) {
"development" !== 'production' && warn$2(
("Invalid v-for expression: " + exp)
);
return
}
el.for = inMatch[2].trim();
var alias = inMatch[1].trim();
var iteratorMatch = alias.match(forIteratorRE);
if (iteratorMatch) {
el.alias = iteratorMatch[1].trim();
el.iterator1 = iteratorMatch[2].trim();
if (iteratorMatch[3]) {
el.iterator2 = iteratorMatch[3].trim();
}
} else {
el.alias = alias;
}
}
}
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."
);
}
}
function findPrevElement (children) {
var i = children.length;
while (i--) {
if (children[i].type === 1) {
return children[i]
} else {
if ("development" !== 'production' && children[i].text !== ' ') {
warn$2(
"text \"" + (children[i].text.trim()) + "\" between v-if and v-else(-if) " +
"will be ignored."
);
}
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;
}
}
function processSlot (el) {
if (el.tag === 'slot') {
el.slotName = getBindingAttr(el, 'name');
if ("development" !== 'production' && el.key) {
warn$2(
"`key` does not work on because slots are abstract outlets " +
"and can possibly expand into multiple elements. " +
"Use the key on a wrapping element instead."
);
}
} else {
var slotTarget = getBindingAttr(el, 'slot');
if (slotTarget) {
el.slotTarget = slotTarget === '""' ? '"default"' : slotTarget;
}
if (el.tag === 'template') {
el.slotScope = getAndRemoveAttr(el, 'scope');
}
}
}
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, isProp;
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);
if (modifiers) {
name = name.replace(modifierRE, '');
}
if (bindRE.test(name)) { // v-bind
name = name.replace(bindRE, '');
value = parseFilters(value);
isProp = false;
if (modifiers) {
if (modifiers.prop) {
isProp = true;
name = camelize(name);
if (name === 'innerHtml') { name = 'innerHTML'; }
}
if (modifiers.camel) {
name = camelize(name);
}
if (modifiers.sync) {
addHandler(
el,
("update:" + (camelize(name))),
genAssignmentCode(value, "$event")
);
}
}
if (isProp || (
!el.component && platformMustUseProp(el.tag, el.attrsMap.type, name)
)) {
addProp(el, name, value);
} else {
addAttr(el, name, value);
}
} else if (onRE.test(name)) { // v-on
name = name.replace(onRE, '');
addHandler(el, name, value, modifiers, false, warn$2);
} else { // normal directives
name = name.replace(dirRE, '');
// parse arg
var argMatch = name.match(argRE);
var arg = argMatch && argMatch[1];
if (arg) {
name = name.slice(0, -(arg.length + 1));
}
addDirective(el, name, rawName, value, arg, modifiers);
if ("development" !== 'production' && name === 'model') {
checkForAliasModel(el, value);
}
}
} else {
// literal attribute
{
var expression = parseText(value, delimiters);
if (expression) {
warn$2(
name + "=\"" + value + "\": " +
'Interpolation inside attributes has been removed. ' +
'Use v-bind or the colon shorthand instead. For example, ' +
'instead of , use
.'
);
}
}
addAttr(el, name, JSON.stringify(value));
}
}
}
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 (
"development" !== 'production' &&
map[attrs[i].name] && !isIE && !isEdge
) {
warn$2('duplicate attribute: ' + attrs[i].name);
}
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 = _el.parent;
}
}
/* */
var fnExpRE = /^\s*([\w$_]+|\([^)]*?\))\s*=>|^function\s*\(/;
var simplePathRE = /^\s*[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\['.*?']|\[".*?"]|\[\d+]|\[[A-Za-z_$][\w$]*])*\s*$/;
// keyCode aliases
var keyCodes = {
esc: 27,
tab: 9,
enter: 13,
space: 32,
up: 38,
left: 37,
right: 39,
down: 40,
'delete': [8, 46]
};
// #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,
warn
) {
var res = isNative ? 'nativeOn:{' : 'on:{';
for (var name in events) {
var handler = events[name];
// #5330: warn click.right, since right clicks do not actually fire click events.
if ("development" !== 'production' &&
name === 'click' &&
handler && handler.modifiers && handler.modifiers.right
) {
warn(
"Use \"contextmenu\" instead of \"click.right\" since right clicks " +
"do not actually fire \"click\" events."
);
}
res += "\"" + name + "\":" + (genHandler(name, handler)) + ",";
}
return res.slice(0, -1) + '}'
}
function genHandler (
name,
handler
) {
if (!handler) {
return 'function(){}'
}
if (Array.isArray(handler)) {
return ("[" + (handler.map(function (handler) { return genHandler(name, handler); }).join(',')) + "]")
}
var isMethodPath = simplePathRE.test(handler.value);
var isFunctionExpression = fnExpRE.test(handler.value);
if (!handler.modifiers) {
return isMethodPath || isFunctionExpression
? handler.value
: ("function($event){" + (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 {
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
? handler.value + '($event)'
: isFunctionExpression
? ("(" + (handler.value) + ")($event)")
: handler.value;
return ("function($event){" + code + handlerCode + "}")
}
}
function genKeyFilter (keys) {
return ("if(!('button' in $event)&&" + (keys.map(genFilterCode).join('&&')) + ")return null;")
}
function genFilterCode (key) {
var keyVal = parseInt(key, 10);
if (keyVal) {
return ("$event.keyCode!==" + keyVal)
}
var alias = keyCodes[key];
return ("_k($event.keyCode," + (JSON.stringify(key)) + (alias ? ',' + JSON.stringify(alias) : '') + ")")
}
/* */
function on (el, dir) {
if ("development" !== 'production' && 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 !isReservedTag(el.tag); };
this.onceId = 0;
this.staticRenderFns = [];
};
function generate$1 (
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.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) {
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 = el.plain ? undefined : 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;
state.staticRenderFns.push(("with(this){return " + (genElement(el, state)) + "}"));
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) {
"development" !== 'production' && state.warn(
"v-once can only be used inside v-for that is keyed. "
);
return genElement(el, state)
}
return ("_o(" + (genElement(el, state)) + "," + (state.onceId++) + (key ? ("," + 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 ("development" !== 'production' &&
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.",
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, state.warn)) + ",";
}
if (el.nativeEvents) {
data += (genHandlers(el.nativeEvents, true, state.warn)) + ",";
}
// slot target
if (el.slotTarget) {
data += "slot:" + (el.slotTarget) + ",";
}
// scoped slots
if (el.scopedSlots) {
data += (genScopedSlots(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 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.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 ("development" !== 'production' && (
el.children.length > 1 || ast.type !== 1
)) {
state.warn('Inline-template components must have exactly one child element.');
}
if (ast.type === 1) {
var inlineRenderFns = generate$1(ast, state.options);
return ("inlineTemplate:{render:function(){" + (inlineRenderFns.render) + "},staticRenderFns:[" + (inlineRenderFns.staticRenderFns.map(function (code) { return ("function(){" + code + "}"); }).join(',')) + "]}")
}
}
function genScopedSlots (
slots,
state
) {
return ("scopedSlots:_u([" + (Object.keys(slots).map(function (key) {
return genScopedSlot(key, slots[key], state)
}).join(',')) + "])")
}
function genScopedSlot (
key,
el,
state
) {
if (el.for && !el.forProcessed) {
return genForScopedSlot(key, el, state)
}
return "{key:" + key + ",fn:function(" + (String(el.attrsMap.scope)) + "){" +
"return " + (el.tag === 'template'
? genChildren(el, state) || 'void 0'
: genElement(el, state)) + "}}"
}
function genForScopedSlot (
key,
el,
state
) {
var exp = el.for;
var alias = el.alias;
var iterator1 = el.iterator1 ? ("," + (el.iterator1)) : '';
var iterator2 = el.iterator2 ? ("," + (el.iterator2)) : '';
el.forProcessed = true; // avoid recursion
return "_l((" + exp + ")," +
"function(" + alias + iterator1 + iterator2 + "){" +
"return " + (genScopedSlot(key, el, state)) +
'})'
}
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'
) {
return (altGenElement || genElement)(el$1, state)
}
var normalizationType = checkSkip
? getNormalizationType(children, state.maybeComponent)
: 0;
var gen = altGenNode || genNode;
return ("[" + (children.map(function (c) { return gen(c, state); }).join(',')) + "]" + (normalizationType ? ("," + normalizationType) : ''))
}
}
// 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)
} 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.attrs.map(function (a) { return ((camelize(a.name)) + ":" + (a.value)); }).join(',')) + "}");
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 res = '';
for (var i = 0; i < props.length; i++) {
var prop = props[i];
res += "\"" + (prop.name) + "\":" + (transformSpecialNewlines(prop.value)) + ",";
}
return res.slice(0, -1)
}
// #3895, #4268
function transformSpecialNewlines (text) {
return text
.replace(/\u2028/g, '\\u2028')
.replace(/\u2029/g, '\\u2029')
}
/* */
var plainStringRE = /^"(?:[^"\\]|\\.)*"$|^'(?:[^'\\]|\\.)*'$/;
// let the model AST transform translate v-model into appropriate
// props bindings
function applyModelTransform (el, state) {
if (el.directives) {
for (var i = 0; i < el.directives.length; i++) {
var dir = el.directives[i];
if (dir.name === 'model') {
state.directives.model(el, dir, state.warn);
break
}
}
}
}
function genAttrSegments (
attrs
) {
return attrs.map(function (ref) {
var name = ref.name;
var value = ref.value;
return genAttrSegment(name, value);
})
}
function genDOMPropSegments (
props,
attrs
) {
var segments = [];
props.forEach(function (ref) {
var name = ref.name;
var value = ref.value;
name = propsToAttrMap[name] || name.toLowerCase();
if (isRenderableAttr(name) &&
!(attrs && attrs.some(function (a) { return a.name === name; }))
) {
segments.push(genAttrSegment(name, value));
}
});
return segments
}
function genAttrSegment (name, value) {
if (plainStringRE.test(value)) {
// force double quote
value = value.replace(/^'|'$/g, '"');
// force enumerated attr to "true"
if (isEnumeratedAttr(name) && value !== "\"false\"") {
value = "\"true\"";
}
return {
type: RAW,
value: isBooleanAttr(name)
? (" " + name + "=\"" + name + "\"")
: value === '""'
? (" " + name)
: (" " + name + "=" + value)
}
} else {
return {
type: EXPRESSION,
value: ("_ssrAttr(" + (JSON.stringify(name)) + "," + value + ")")
}
}
}
function genClassSegments (
staticClass,
classBinding
) {
if (staticClass && !classBinding) {
return [{ type: RAW, value: (" class=" + staticClass) }]
} else {
return [{
type: EXPRESSION,
value: ("_ssrClass(" + (staticClass || 'null') + "," + (classBinding || 'null') + ")")
}]
}
}
function genStyleSegments (
staticStyle,
parsedStaticStyle,
styleBinding,
vShowExpression
) {
if (staticStyle && !styleBinding && !vShowExpression) {
return [{ type: RAW, value: (" style=" + (JSON.stringify(staticStyle))) }]
} else {
return [{
type: EXPRESSION,
value: ("_ssrStyle(" + (parsedStaticStyle || 'null') + "," + (styleBinding || 'null') + ", " + (vShowExpression
? ("{ display: (" + vShowExpression + ") ? '' : 'none' }")
: 'null') + ")")
}]
}
}
/* */
/**
* In SSR, the vdom tree is generated only once and never patched, so
* we can optimize most element / trees into plain string render functions.
* The SSR optimizer walks the AST tree to detect optimizable elements and trees.
*
* The criteria for SSR optimizability is quite a bit looser than static tree
* detection (which is designed for client re-render). In SSR we bail only for
* components/slots/custom directives.
*/
// optimizability constants
var optimizability = {
FALSE: 0, // whole sub tree un-optimizable
FULL: 1, // whole sub tree optimizable
SELF: 2, // self optimizable but has some un-optimizable children
CHILDREN: 3, // self un-optimizable but have fully optimizable children
PARTIAL: 4 // self un-optimizable with some un-optimizable children
};
var isPlatformReservedTag;
function optimize (root, options) {
if (!root) { return }
isPlatformReservedTag = options.isReservedTag || no;
walk(root, true);
}
function walk (node, isRoot) {
if (isUnOptimizableTree(node)) {
node.ssrOptimizability = optimizability.FALSE;
return
}
// root node or nodes with custom directives should always be a VNode
var selfUnoptimizable = isRoot || hasCustomDirective(node);
var check = function (child) {
if (child.ssrOptimizability !== optimizability.FULL) {
node.ssrOptimizability = selfUnoptimizable
? optimizability.PARTIAL
: optimizability.SELF;
}
};
if (selfUnoptimizable) {
node.ssrOptimizability = optimizability.CHILDREN;
}
if (node.type === 1) {
for (var i = 0, l = node.children.length; i < l; i++) {
var child = node.children[i];
walk(child);
check(child);
}
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;
walk(block);
check(block);
}
}
if (node.ssrOptimizability == null ||
(!isRoot && (node.attrsMap['v-html'] || node.attrsMap['v-text']))
) {
node.ssrOptimizability = optimizability.FULL;
} else {
node.children = optimizeSiblings(node);
}
} else {
node.ssrOptimizability = optimizability.FULL;
}
}
function optimizeSiblings (el) {
var children = el.children;
var optimizedChildren = [];
var currentOptimizableGroup = [];
var pushGroup = function () {
if (currentOptimizableGroup.length) {
optimizedChildren.push({
type: 1,
parent: el,
tag: 'template',
attrsList: [],
attrsMap: {},
children: currentOptimizableGroup,
ssrOptimizability: optimizability.FULL
});
}
currentOptimizableGroup = [];
};
for (var i = 0; i < children.length; i++) {
var c = children[i];
if (c.ssrOptimizability === optimizability.FULL) {
currentOptimizableGroup.push(c);
} else {
// wrap fully-optimizable adjacent siblings inside a template tag
// so that they can be optimized into a single ssrNode by codegen
pushGroup();
optimizedChildren.push(c);
}
}
pushGroup();
return optimizedChildren
}
function isUnOptimizableTree (node) {
if (node.type === 2 || node.type === 3) { // text or expression
return false
}
return (
isBuiltInTag(node.tag) || // built-in (slot, component)
!isPlatformReservedTag(node.tag) || // custom component
!!node.component // "is" component
)
}
var isBuiltInDir = makeMap('text,html,show,on,bind,model,pre,cloak,once');
function hasCustomDirective (node) {
return (
node.type === 1 &&
node.directives &&
node.directives.some(function (d) { return !isBuiltInDir(d.name); })
)
}
/* */
// The SSR codegen is essentially extending the default codegen to handle
// SSR-optimizable nodes and turn them into string render fns. In cases where
// a node is not optimizable it simply falls back to the default codegen.
// segment types
var RAW = 0;
var INTERPOLATION = 1;
var EXPRESSION = 2;
function generate (
ast,
options
) {
var state = new CodegenState(options);
var code = ast ? genSSRElement(ast, state) : '_c("div")';
return {
render: ("with(this){return " + code + "}"),
staticRenderFns: state.staticRenderFns
}
}
function genSSRElement (el, state) {
if (el.for && !el.forProcessed) {
return genFor(el, state, genSSRElement)
} else if (el.if && !el.ifProcessed) {
return genIf(el, state, genSSRElement)
} else if (el.tag === 'template' && !el.slotTarget) {
return el.ssrOptimizability === optimizability.FULL
? genChildrenAsStringNode(el, state)
: genSSRChildren(el, state) || 'void 0'
}
switch (el.ssrOptimizability) {
case optimizability.FULL:
// stringify whole tree
return genStringElement(el, state)
case optimizability.SELF:
// stringify self and check children
return genStringElementWithChildren(el, state)
case optimizability.CHILDREN:
// generate self as VNode and stringify children
return genNormalElement(el, state, true)
case optimizability.PARTIAL:
// generate self as VNode and check children
return genNormalElement(el, state, false)
default:
// bail whole tree
return genElement(el, state)
}
}
function genNormalElement (el, state, stringifyChildren) {
var data = el.plain ? undefined : genData$2(el, state);
var children = stringifyChildren
? ("[" + (genChildrenAsStringNode(el, state)) + "]")
: genSSRChildren(el, state, true);
return ("_c('" + (el.tag) + "'" + (data ? ("," + data) : '') + (children ? ("," + children) : '') + ")")
}
function genSSRChildren (el, state, checkSkip) {
return genChildren(el, state, checkSkip, genSSRElement, genSSRNode)
}
function genSSRNode (el, state) {
return el.type === 1
? genSSRElement(el, state)
: genText(el)
}
function genChildrenAsStringNode (el, state) {
return el.children.length
? ("_ssrNode(" + (flattenSegments(childrenToSegments(el, state))) + ")")
: ''
}
function genStringElement (el, state) {
return ("_ssrNode(" + (elementToString(el, state)) + ")")
}
function genStringElementWithChildren (el, state) {
var children = genSSRChildren(el, state, true);
return ("_ssrNode(" + (flattenSegments(elementToOpenTagSegments(el, state))) + ",\"\"" + (children ? ("," + children) : '') + ")")
}
function elementToString (el, state) {
return ("(" + (flattenSegments(elementToSegments(el, state))) + ")")
}
function elementToSegments (el, state) {
// v-for / v-if
if (el.for && !el.forProcessed) {
el.forProcessed = true;
return [{
type: EXPRESSION,
value: genFor(el, state, elementToString, '_ssrList')
}]
} else if (el.if && !el.ifProcessed) {
el.ifProcessed = true;
return [{
type: EXPRESSION,
value: genIf(el, state, elementToString, '""')
}]
} else if (el.tag === 'template') {
return childrenToSegments(el, state)
}
var openSegments = elementToOpenTagSegments(el, state);
var childrenSegments = childrenToSegments(el, state);
var ref = state.options;
var isUnaryTag = ref.isUnaryTag;
var close = (isUnaryTag && isUnaryTag(el.tag))
? []
: [{ type: RAW, value: ("") }];
return openSegments.concat(childrenSegments, close)
}
function elementToOpenTagSegments (el, state) {
applyModelTransform(el, state);
var binding;
var segments = [{ type: RAW, value: ("<" + (el.tag)) }];
// attrs
if (el.attrs) {
segments.push.apply(segments, genAttrSegments(el.attrs));
}
// domProps
if (el.props) {
segments.push.apply(segments, genDOMPropSegments(el.props, el.attrs));
}
// v-bind="object"
if ((binding = el.attrsMap['v-bind'])) {
segments.push({ type: EXPRESSION, value: ("_ssrAttrs(" + binding + ")") });
}
// v-bind.prop="object"
if ((binding = el.attrsMap['v-bind.prop'])) {
segments.push({ type: EXPRESSION, value: ("_ssrDOMProps(" + binding + ")") });
}
// class
if (el.staticClass || el.classBinding) {
segments.push.apply(
segments,
genClassSegments(el.staticClass, el.classBinding)
);
}
// style & v-show
if (el.staticStyle || el.styleBinding || el.attrsMap['v-show']) {
segments.push.apply(
segments,
genStyleSegments(
el.attrsMap.style,
el.staticStyle,
el.styleBinding,
el.attrsMap['v-show']
)
);
}
// _scopedId
if (state.options.scopeId) {
segments.push({ type: RAW, value: (" " + (state.options.scopeId)) });
}
segments.push({ type: RAW, value: ">" });
return segments
}
function childrenToSegments (el, state) {
var binding;
if ((binding = el.attrsMap['v-html'])) {
return [{ type: EXPRESSION, value: binding }]
}
if ((binding = el.attrsMap['v-text'])) {
return [{ type: INTERPOLATION, value: binding }]
}
return el.children
? nodesToSegments(el.children, state)
: []
}
function nodesToSegments (
children,
state
) {
var segments = [];
for (var i = 0; i < children.length; i++) {
var c = children[i];
if (c.type === 1) {
segments.push.apply(segments, elementToSegments(c, state));
} else if (c.type === 2) {
segments.push({ type: INTERPOLATION, value: c.expression });
} else if (c.type === 3) {
segments.push({ type: RAW, value: c.text });
}
}
return segments
}
function flattenSegments (segments) {
var mergedSegments = [];
var textBuffer = '';
var pushBuffer = function () {
if (textBuffer) {
mergedSegments.push(JSON.stringify(textBuffer));
textBuffer = '';
}
};
for (var i = 0; i < segments.length; i++) {
var s = segments[i];
if (s.type === RAW) {
textBuffer += s.value;
} else if (s.type === INTERPOLATION) {
pushBuffer();
mergedSegments.push(("_ssrEscape(" + (s.value) + ")"));
} else if (s.type === EXPRESSION) {
pushBuffer();
mergedSegments.push(("(" + (s.value) + ")"));
}
}
pushBuffer();
return mergedSegments.join('+')
}
/* */
// 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*\\([^\\)]*\\)');
// check valid identifier for v-for
var identRE = /[A-Za-z_$][\w$]*/;
// strip strings in expressions
var stripStringRE = /'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*\$\{|\}(?:[^`\\]|\\.)*`|`(?:[^`\\]|\\.)*`/g;
// detect problematic expressions in a template
function detectErrors (ast) {
var errors = [];
if (ast) {
checkNode(ast, errors);
}
return errors
}
function checkNode (node, errors) {
if (node.type === 1) {
for (var name in node.attrsMap) {
if (dirRE.test(name)) {
var value = node.attrsMap[name];
if (value) {
if (name === 'v-for') {
checkFor(node, ("v-for=\"" + value + "\""), errors);
} else if (onRE.test(name)) {
checkEvent(value, (name + "=\"" + value + "\""), errors);
} else {
checkExpression(value, (name + "=\"" + value + "\""), errors);
}
}
}
}
if (node.children) {
for (var i = 0; i < node.children.length; i++) {
checkNode(node.children[i], errors);
}
}
} else if (node.type === 2) {
checkExpression(node.expression, node.text, errors);
}
}
function checkEvent (exp, text, errors) {
var stipped = exp.replace(stripStringRE, '');
var keywordMatch = stipped.match(unaryOperatorsRE);
if (keywordMatch && stipped.charAt(keywordMatch.index - 1) !== '$') {
errors.push(
"avoid using JavaScript unary operator as property name: " +
"\"" + (keywordMatch[0]) + "\" in expression " + (text.trim())
);
}
checkExpression(exp, text, errors);
}
function checkFor (node, text, errors) {
checkExpression(node.for || '', text, errors);
checkIdentifier(node.alias, 'v-for alias', text, errors);
checkIdentifier(node.iterator1, 'v-for iterator', text, errors);
checkIdentifier(node.iterator2, 'v-for iterator', text, errors);
}
function checkIdentifier (ident, type, text, errors) {
if (typeof ident === 'string' && !identRE.test(ident)) {
errors.push(("invalid " + type + " \"" + ident + "\" in expression: " + (text.trim())));
}
}
function checkExpression (exp, text, errors) {
try {
new Function(("return " + exp));
} catch (e) {
var keywordMatch = exp.replace(stripStringRE, '').match(prohibitedKeywordRE);
if (keywordMatch) {
errors.push(
"avoid using JavaScript keyword as property name: " +
"\"" + (keywordMatch[0]) + "\" in expression " + (text.trim())
);
} else {
errors.push(("invalid expression: " + (text.trim())));
}
}
}
/* */
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 = options || {};
/* istanbul ignore if */
{
// detect possible CSP restriction
try {
new Function('return 1');
} catch (e) {
if (e.toString().match(/unsafe-eval|CSP/)) {
warn(
'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) {
warn(
"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) {
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(
"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 = [];
finalOptions.warn = function (msg, tip) {
(tip ? tips : errors).push(msg);
};
if (options) {
// 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),
options.directives
);
}
// copy other options
for (var key in options) {
if (key !== 'modules' && key !== 'directives') {
finalOptions[key] = options[key];
}
}
}
var compiled = baseCompile(template, finalOptions);
{
errors.push.apply(errors, detectErrors(compiled.ast));
}
compiled.errors = errors;
compiled.tips = tips;
return compiled
}
return {
compile: compile,
compileToFunctions: createCompileToFunctionFn(compile)
}
}
}
/* */
var createCompiler = createCompilerCreator(function baseCompile (
template,
options
) {
var ast = parse(template.trim(), options);
optimize(ast, options);
var code = generate(ast, options);
return {
ast: ast,
render: code.render,
staticRenderFns: code.staticRenderFns
}
});
/* */
var ref = createCompiler(baseOptions);
var compileToFunctions = ref.compileToFunctions;
/* */
// 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
. 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. , , 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, last;
for (i = 0; i < children.length; i++) {
c = children[i];
if (isUndef(c) || typeof c === 'boolean') { continue }
last = res[res.length - 1];
// nested
if (Array.isArray(c)) {
res.push.apply(res, normalizeArrayChildren(c, ((nestedIndex || '') + "_" + i)));
} 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
(last).text += String(c);
} else if (c !== '') {
// convert primitive to vnode
res.push(createTextVNode(c));
}
} else {
if (isTextNode(c) && isTextNode(last)) {
// merge adjacent text nodes
res[res.length - 1] = 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 installSSRHelpers (vm) {
if (vm._ssrNode) { return }
var Ctor = vm.constructor;
while (Ctor.super) {
Ctor = Ctor.super;
}
Object.assign(Ctor.prototype, {
_ssrEscape: escape,
_ssrNode: renderStringNode$1,
_ssrList: renderStringList,
_ssrAttr: renderAttr,
_ssrAttrs: renderAttrs$1,
_ssrDOMProps: renderDOMProps$1,
_ssrClass: renderSSRClass,
_ssrStyle: renderSSRStyle
});
}
var StringNode = function StringNode (
open,
close,
children,
normalizationType
) {
this.isString = true;
this.open = open;
this.close = close;
if (children) {
this.children = normalizationType === 1
? simpleNormalizeChildren(children)
: normalizationType === 2
? normalizeChildren(children)
: children;
} else {
this.children = void 0;
}
};
function renderStringNode$1 (
open,
close,
children,
normalizationType
) {
return new StringNode(open, close, children, normalizationType)
}
function renderStringList (
val,
render
) {
var ret = '';
var i, l, keys, key;
if (Array.isArray(val) || typeof val === 'string') {
for (i = 0, l = val.length; i < l; i++) {
ret += render(val[i], i);
}
} else if (typeof val === 'number') {
for (i = 0; i < val; i++) {
ret += render(i + 1, i);
}
} else if (isObject(val)) {
keys = Object.keys(val);
for (i = 0, l = keys.length; i < l; i++) {
key = keys[i];
ret += render(val[key], key, i);
}
}
return ret
}
function renderAttrs$1 (obj) {
var res = '';
for (var key in obj) {
res += renderAttr(key, obj[key]);
}
return res
}
function renderDOMProps$1 (obj) {
var res = '';
for (var key in obj) {
var attr = propsToAttrMap[key] || key.toLowerCase();
if (isRenderableAttr(attr)) {
res += renderAttr(attr, obj[key]);
}
}
return res
}
function renderSSRClass (
staticClass,
dynamic
) {
var res = renderClass$1(staticClass, dynamic);
return res === '' ? res : (" class=\"" + (cachedEscape(res)) + "\"")
}
function renderSSRStyle (
staticStyle,
dynamic,
extra
) {
var style = {};
if (staticStyle) { extend(style, staticStyle); }
if (dynamic) { extend(style, normalizeStyleBinding(dynamic)); }
if (extra) { extend(style, extra); }
var res = genStyle(style);
return res === '' ? res : (" style=" + (JSON.stringify(cachedEscape(res))))
}
/* 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 to declare reactive data " +
"properties in the data option.",
target
);
};
var hasProxy =
typeof Proxy !== 'undefined' &&
Proxy.toString().match(/native code/);
if (hasProxy) {
var isBuiltInModifier = makeMap('stop,prevent,self,ctrl,shift,alt,meta');
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) || key.charAt(0) === '_';
if (!has && !isAllowed) {
warnNonPresent(target, key);
}
return has || !isAllowed
}
};
var getHandler = {
get: function get (target, key) {
if (typeof key === 'string' && !(key in target)) {
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 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);
};
}
}
/* */
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) {
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++) {
cloned[i].apply(null, arguments$1);
}
} else {
// return handler return value for single handlers
return fns.apply(null, arguments)
}
}
invoker.fns = fns;
return invoker
}
function updateListeners (
on,
oldOn,
add,
remove$$1,
vm
) {
var name, cur, old, event;
for (name in on) {
cur = on[name];
old = oldOn[name];
event = normalizeEvent(name);
if (isUndef(cur)) {
"development" !== 'production' && warn(
"Invalid handler for event \"" + (event.name) + "\": got " + String(cur),
vm
);
} else if (isUndef(old)) {
if (isUndef(cur.fns)) {
cur = on[name] = createFnInvoker(cur);
}
add(event.name, cur, event.once, event.capture, event.passive);
} 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 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
}
/* */
function ensureCtor (comp, base) {
if (comp.__esModule && comp.default) {
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,
context
) {
if (isTrue(factory.error) && isDef(factory.errorComp)) {
return factory.errorComp
}
if (isDef(factory.resolved)) {
return factory.resolved
}
if (isTrue(factory.loading) && isDef(factory.loadingComp)) {
return factory.loadingComp
}
if (isDef(factory.contexts)) {
// already pending
factory.contexts.push(context);
} else {
var contexts = factory.contexts = [context];
var sync = true;
var forceRender = function () {
for (var i = 0, l = contexts.length; i < l; i++) {
contexts[i].$forceUpdate();
}
};
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();
}
});
var reject = once(function (reason) {
"development" !== 'production' && warn(
"Failed to resolve async component: " + (String(factory)) +
(reason ? ("\nReason: " + reason) : '')
);
if (isDef(factory.errorComp)) {
factory.error = true;
forceRender();
}
});
var res = factory(resolve, reject);
if (isObject(res)) {
if (typeof res.then === 'function') {
// () => Promise
if (isUndef(factory.resolved)) {
res.then(resolve, reject);
}
} else if (isDef(res.component) && typeof res.component.then === 'function') {
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 {
setTimeout(function () {
if (isUndef(factory.resolved) && isUndef(factory.error)) {
factory.loading = true;
forceRender();
}
}, res.delay || 200);
}
}
if (isDef(res.timeout)) {
setTimeout(function () {
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
}
}
/* */
/* */
/* */
var target;
function add (event, fn, once$$1) {
if (once$$1) {
target.$once(event, fn);
} else {
target.$on(event, fn);
}
}
function remove$1 (event, fn) {
target.$off(event, fn);
}
function updateComponentListeners (
vm,
listeners,
oldListeners
) {
target = vm;
updateListeners(listeners, oldListeners || {}, add, remove$1, vm);
}
/* */
/**
* Runtime helper for resolving raw children VNodes into a slot object.
*/
function resolveSlots (
children,
context
) {
var slots = {};
if (!children) {
return slots
}
var defaultSlot = [];
for (var i = 0, l = children.length; i < l; i++) {
var child = children[i];
// named slots should only be respected if the vnode was rendered in the
// same context.
if ((child.context === context || child.functionalContext === context) &&
child.data && child.data.slot != null
) {
var name = child.data.slot;
var slot = (slots[name] || (slots[name] = []));
if (child.tag === 'template') {
slot.push.apply(slot, child.children);
} else {
slot.push(child);
}
} else {
defaultSlot.push(child);
}
}
// ignore whitespace
if (!defaultSlot.every(isWhitespace)) {
slots.default = defaultSlot;
}
return slots
}
function isWhitespace (node) {
return node.isComment || node.text === ' '
}
/* */
var activeInstance = null;
var isUpdatingChildComponent = false;
function updateChildComponent (
vm,
propsData,
listeners,
parentVnode,
renderChildren
) {
{
isUpdatingChildComponent = true;
}
// determine whether component has slot children
// we need to do this before overwriting $options._renderChildren
var hasChildren = !!(
renderChildren || // has new static slots
vm.$options._renderChildren || // has old static slots
parentVnode.data.scopedSlots || // has new scoped slots
vm.$scopedSlots !== emptyObject // has old scoped slots
);
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 $listensers hash
// these are also reactive so they may trigger child update if the child
// used them during render
vm.$attrs = parentVnode.data && parentVnode.data.attrs;
vm.$listeners = listeners;
// update props
if (propsData && vm.$options.props) {
observerState.shouldConvert = false;
var props = vm._props;
var propKeys = vm.$options._propKeys || [];
for (var i = 0; i < propKeys.length; i++) {
var key = propKeys[i];
props[key] = validateProp(key, vm.$options.props, propsData, vm);
}
observerState.shouldConvert = true;
// keep a copy of raw propsData
vm.$options.propsData = propsData;
}
// update listeners
if (listeners) {
var oldListeners = vm.$options._parentListeners;
vm.$options._parentListeners = listeners;
updateComponentListeners(vm, listeners, oldListeners);
}
// resolve slots + force update if has children
if (hasChildren) {
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) {
var handlers = vm.$options[hook];
if (handlers) {
for (var i = 0, j = handlers.length; i < j; i++) {
try {
handlers[i].call(vm);
} catch (e) {
handleError(e, vm, (hook + " hook"));
}
}
}
if (vm._hasHookEvent) {
vm.$emit('hook:' + hook);
}
}
/* */
var MAX_UPDATE_COUNT = 100;
var queue = [];
var activatedChildren = [];
var has = {};
var circular = {};
var waiting = false;
var flushing = false;
var index$1 = 0;
/**
* Reset the scheduler's state.
*/
function resetSchedulerState () {
index$1 = queue.length = activatedChildren.length = 0;
has = {};
{
circular = {};
}
waiting = flushing = false;
}
/**
* Flush both queues and run the watchers.
*/
function flushSchedulerQueue () {
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$1 = 0; index$1 < queue.length; index$1++) {
watcher = queue[index$1];
id = watcher.id;
has[id] = null;
watcher.run();
// in dev build, check and stop circular updates.
if ("development" !== 'production' && 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) {
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$1 && queue[i].id > watcher.id) {
i--;
}
queue.splice(i + 1, 0, watcher);
}
// queue the flush
if (!waiting) {
waiting = true;
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
) {
this.vm = vm;
vm._watchers.push(this);
// options
if (options) {
this.deep = !!options.deep;
this.user = !!options.user;
this.lazy = !!options.lazy;
this.sync = !!options.sync;
} 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 = function () {};
"development" !== 'production' && 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 this$1 = this;
var i = this.deps.length;
while (i--) {
var dep = this$1.deps[i];
if (!this$1.newDepIds.has(dep.id)) {
dep.removeSub(this$1);
}
}
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 this$1 = this;
var i = this.deps.length;
while (i--) {
this$1.deps[i].depend();
}
};
/**
* Remove self from all dependencies' subscriber list.
*/
Watcher.prototype.teardown = function teardown () {
var this$1 = this;
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$1.deps[i].removeSub(this$1);
}
this.active = false;
}
};
/**
* Recursively traverse an object to evoke all converted
* getters, so that every nested property inside the object
* is collected as a "deep" dependency.
*/
var seenObjects = new _Set();
function traverse (val) {
seenObjects.clear();
_traverse(val, seenObjects);
}
function _traverse (val, seen) {
var i, keys;
var isA = Array.isArray(val);
if ((!isA && !isObject(val)) || !Object.isExtensible(val)) {
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 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 getData (data, vm) {
try {
return data.call(vm)
} catch (e) {
handleError(e, vm, "data()");
return {}
}
}
/* */
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__)) {
"development" !== 'production' && 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 ("development" !== 'production' &&
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 = config.getTagNamespace(tag);
if (config.isReservedTag(tag)) {
// platform built-in elements
vnode = new VNode(
config.parsePlatformTagName(tag), data, children,
undefined, undefined, context
);
} else if (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 (isDef(vnode)) {
if (ns) { applyNS(vnode, ns); }
return vnode
} else {
return createEmptyVNode()
}
}
function applyNS (vnode, ns) {
vnode.ns = ns;
if (vnode.tag === 'foreignObject') {
// use default namespace inside foreignObject
return
}
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)) {
applyNS(child, ns);
}
}
}
}
/* */
/**
* Runtime helper for rendering v-for lists.
*/
/* */
/**
* Runtime helper for rendering
*/
/* */
/**
* Runtime helper for resolving filters
*/
/* */
/**
* Runtime helper for checking keyCodes from config.
*/
/* */
/**
* Runtime helper for merging v-bind="object" into a VNode's data.
*/
/* */
/**
* Runtime helper for rendering static trees.
*/
/**
* Runtime helper for v-once.
* Effectively it means marking the node as static with a unique key.
*/
/* */
/* */
/* */
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];
var provideKey = inject[key];
var source = vm;
while (source) {
if (source._provided && provideKey in source._provided) {
result[key] = source._provided[provideKey];
break
}
source = source.$parent;
}
if ("development" !== 'production' && !source) {
warn(("Injection \"" + key + "\" not found"), vm);
}
}
return result
}
}
/* */
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 extended = Ctor.extendOptions;
var sealed = Ctor.sealedOptions;
for (var key in latest) {
if (latest[key] !== sealed[key]) {
if (!modified) { modified = {}; }
modified[key] = dedupe(latest[key], extended[key], sealed[key]);
}
}
return modified
}
function dedupe (latest, extended, sealed) {
// compare latest and sealed to ensure lifecycle hooks won't be duplicated
// between merges
if (Array.isArray(latest)) {
var res = [];
sealed = Array.isArray(sealed) ? sealed : [sealed];
extended = Array.isArray(extended) ? extended : [extended];
for (var i = 0; i < latest.length; i++) {
// push original options and not sealed options to exclude duplicated options
if (extended.indexOf(latest[i]) >= 0 || sealed.indexOf(latest[i]) < 0) {
res.push(latest[i]);
}
}
return res
} else {
return latest
}
}
/* */
function createFunctionalComponent (
Ctor,
propsData,
data,
context,
children
) {
var props = {};
var propOptions = Ctor.options.props;
if (isDef(propOptions)) {
for (var key in propOptions) {
props[key] = validateProp(key, propOptions, propsData || {});
}
} else {
if (isDef(data.attrs)) { mergeProps(props, data.attrs); }
if (isDef(data.props)) { mergeProps(props, data.props); }
}
// ensure the createElement function in functional components
// gets a unique context - this is necessary for correct named slot check
var _context = Object.create(context);
var h = function (a, b, c, d) { return createElement(_context, a, b, c, d, true); };
var vnode = Ctor.options.render.call(null, h, {
data: data,
props: props,
children: children,
parent: context,
listeners: data.on || {},
injections: resolveInject(Ctor.options.inject, context),
slots: function () { return resolveSlots(children, context); }
});
if (vnode instanceof VNode) {
vnode.functionalContext = context;
vnode.functionalOptions = Ctor.options;
if (data.slot) {
(vnode.data || (vnode.data = {})).slot = data.slot;
}
}
return vnode
}
function mergeProps (to, from) {
for (var key in from) {
to[camelize(key)] = from[key];
}
}
/* */
// hooks to be invoked on component VNodes during patch
var componentVNodeHooks = {
init: function init (
vnode,
hydrating,
parentElm,
refElm
) {
if (!vnode.componentInstance || vnode.componentInstance._isDestroyed) {
var child = vnode.componentInstance = createComponentInstanceForVnode(
vnode,
activeInstance,
parentElm,
refElm
);
child.$mount(hydrating ? vnode.elm : undefined, hydrating);
} else if (vnode.data.keepAlive) {
// kept-alive components, treat as a patch
var mountedNode = vnode; // work around flow
componentVNodeHooks.prepatch(mountedNode, mountedNode);
}
},
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, context);
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;
}
}
// merge component management hooks onto the placeholder node
mergeHooks(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
parentElm,
refElm
) {
var vnodeComponentOptions = vnode.componentOptions;
var options = {
_isComponent: true,
parent: parent,
propsData: vnodeComponentOptions.propsData,
_componentTag: vnodeComponentOptions.tag,
_parentVnode: vnode,
_parentListeners: vnodeComponentOptions.listeners,
_renderChildren: vnodeComponentOptions.children,
_parentElm: parentElm || null,
_refElm: refElm || null
};
// check inline-template render functions
var inlineTemplate = vnode.data.inlineTemplate;
if (isDef(inlineTemplate)) {
options.render = inlineTemplate.render;
options.staticRenderFns = inlineTemplate.staticRenderFns;
}
return new vnodeComponentOptions.Ctor(options)
}
function mergeHooks (data) {
if (!data.hook) {
data.hook = {};
}
for (var i = 0; i < hooksToMerge.length; i++) {
var key = hooksToMerge[i];
var fromParent = data.hook[key];
var ours = componentVNodeHooks[key];
data.hook[key] = fromParent ? mergeHook$1(ours, fromParent) : ours;
}
}
function mergeHook$1 (one, two) {
return function (a, b, c, d) {
one(a, b, c, d);
two(a, b, c, d);
}
}
// 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.props || (data.props = {}))[prop] = data.model.value;
var on = data.on || (data.on = {});
if (isDef(on[event])) {
on[event] = [data.model.callback].concat(on[event]);
} else {
on[event] = data.model.callback;
}
}
/* */
var warned = Object.create(null);
var warnOnce = function (msg) {
if (!warned[msg]) {
warned[msg] = true;
console.warn(("\n\u001b[31m" + msg + "\u001b[39m\n"));
}
};
var normalizeRender = function (vm) {
var ref = vm.$options;
var render = ref.render;
var template = ref.template;
var _scopeId = ref._scopeId;
if (isUndef(render)) {
if (template) {
Object.assign(vm.$options, compileToFunctions(template, {
scopeId: _scopeId
}));
} else {
throw new Error(
("render function or template not defined in component: " + (vm.$options.name || vm.$options._componentTag || 'anonymous'))
)
}
}
};
function renderNode (node, isRoot, context) {
if (node.isString) {
renderStringNode(node, context);
} else if (isDef(node.componentOptions)) {
renderComponent(node, isRoot, context);
} else if (isDef(node.tag)) {
renderElement(node, isRoot, context);
} else if (isTrue(node.isComment)) {
if (isDef(node.asyncFactory)) {
// async component
renderAsyncComponent(node, isRoot, context);
} else {
context.write((""), context.next);
}
} else {
context.write(
node.raw ? node.text : escape(String(node.text)),
context.next
);
}
}
function registerComponentForCache (options, write) {
// exposed by vue-loader, need to call this if cache hit because
// component lifecycle hooks will not be called.
var register = options._ssrRegister;
if (write.caching && isDef(register)) {
write.componentBuffer[write.componentBuffer.length - 1].add(register);
}
return register
}
function renderComponent (node, isRoot, context) {
var write = context.write;
var next = context.next;
var userContext = context.userContext;
// check cache hit
var Ctor = node.componentOptions.Ctor;
var getKey = Ctor.options.serverCacheKey;
var name = Ctor.options.name;
var cache = context.cache;
var registerComponent = registerComponentForCache(Ctor.options, write);
if (isDef(getKey) && isDef(cache) && isDef(name)) {
var key = name + '::' + getKey(node.componentOptions.propsData);
var has = context.has;
var get = context.get;
if (isDef(has)) {
has(key, function (hit) {
if (hit === true && isDef(get)) {
get(key, function (res) {
if (isDef(registerComponent)) {
registerComponent(userContext);
}
res.components.forEach(function (register) { return register(userContext); });
write(res.html, next);
});
} else {
renderComponentWithCache(node, isRoot, key, context);
}
});
} else if (isDef(get)) {
get(key, function (res) {
if (isDef(res)) {
if (isDef(registerComponent)) {
registerComponent(userContext);
}
res.components.forEach(function (register) { return register(userContext); });
write(res.html, next);
} else {
renderComponentWithCache(node, isRoot, key, context);
}
});
}
} else {
if (isDef(getKey) && isUndef(cache)) {
warnOnce(
"[vue-server-renderer] Component " + (Ctor.options.name || '(anonymous)') + " implemented serverCacheKey, " +
'but no cache was provided to the renderer.'
);
}
if (isDef(getKey) && isUndef(name)) {
warnOnce(
"[vue-server-renderer] Components that implement \"serverCacheKey\" " +
"must also define a unique \"name\" option."
);
}
renderComponentInner(node, isRoot, context);
}
}
function renderComponentWithCache (node, isRoot, key, context) {
var write = context.write;
write.caching = true;
var buffer = write.cacheBuffer;
var bufferIndex = buffer.push('') - 1;
var componentBuffer = write.componentBuffer;
componentBuffer.push(new Set());
context.renderStates.push({
type: 'ComponentWithCache',
key: key,
buffer: buffer,
bufferIndex: bufferIndex,
componentBuffer: componentBuffer
});
renderComponentInner(node, isRoot, context);
}
function renderComponentInner (node, isRoot, context) {
var prevActive = context.activeInstance;
// expose userContext on vnode
node.ssrContext = context.userContext;
var child = context.activeInstance = createComponentInstanceForVnode(
node,
context.activeInstance
);
normalizeRender(child);
var childNode = child._render();
childNode.parent = node;
context.renderStates.push({
type: 'Component',
prevActive: prevActive
});
renderNode(childNode, isRoot, context);
}
function renderAsyncComponent (node, isRoot, context) {
var factory = node.asyncFactory;
var resolve = function (comp) {
if (comp.__esModule && comp.default) {
comp = comp.default;
}
var ref = node.asyncMeta;
var data = ref.data;
var children = ref.children;
var tag = ref.tag;
var nodeContext = node.asyncMeta.context;
var resolvedNode = createComponent(
comp,
data,
nodeContext,
children,
tag
);
if (resolvedNode) {
renderComponent(resolvedNode, isRoot, context);
} else {
reject();
}
};
var reject = function (err) {
console.error("[vue-server-renderer] error when rendering async component:\n");
if (err) { console.error(err.stack); }
context.write((""), context.next);
};
if (factory.resolved) {
resolve(factory.resolved);
return
}
var res;
try {
res = factory(resolve, reject);
} catch (e) {
reject(e);
}
if (res) {
if (typeof res.then === 'function') {
res.then(resolve, reject).catch(reject);
} else {
// new syntax in 2.3
var comp = res.component;
if (comp && typeof comp.then === 'function') {
comp.then(resolve, reject).catch(reject);
}
}
}
}
function renderStringNode (el, context) {
var write = context.write;
var next = context.next;
if (isUndef(el.children) || el.children.length === 0) {
write(el.open + (el.close || ''), next);
} else {
var children = el.children;
context.renderStates.push({
type: 'Element',
rendered: 0,
total: children.length,
endTag: el.close, children: children
});
write(el.open, next);
}
}
function renderElement (el, isRoot, context) {
var write = context.write;
var next = context.next;
if (isTrue(isRoot)) {
if (!el.data) { el.data = {}; }
if (!el.data.attrs) { el.data.attrs = {}; }
el.data.attrs[SSR_ATTR] = 'true';
}
if (el.functionalOptions) {
registerComponentForCache(el.functionalOptions, write);
}
var startTag = renderStartingTag(el, context);
var endTag = "";
if (context.isUnaryTag(el.tag)) {
write(startTag, next);
} else if (isUndef(el.children) || el.children.length === 0) {
write(startTag + endTag, next);
} else {
var children = el.children;
context.renderStates.push({
type: 'Element',
rendered: 0,
total: children.length,
endTag: endTag, children: children
});
write(startTag, next);
}
}
function hasAncestorData (node) {
var parentNode = node.parent;
return isDef(parentNode) && (isDef(parentNode.data) || hasAncestorData(parentNode))
}
function getVShowDirectiveInfo (node) {
var dir;
var tmp;
while (isDef(node)) {
if (node.data && node.data.directives) {
tmp = node.data.directives.find(function (dir) { return dir.name === 'show'; });
if (tmp) {
dir = tmp;
}
}
node = node.parent;
}
return dir
}
function renderStartingTag (node, context) {
var markup = "<" + (node.tag);
var directives = context.directives;
var modules = context.modules;
// construct synthetic data for module processing
// because modules like style also produce code by parent VNode data
if (isUndef(node.data) && hasAncestorData(node)) {
node.data = {};
}
if (isDef(node.data)) {
// check directives
var dirs = node.data.directives;
if (dirs) {
for (var i = 0; i < dirs.length; i++) {
var name = dirs[i].name;
var dirRenderer = directives[name];
if (dirRenderer && name !== 'show') {
// directives mutate the node's data
// which then gets rendered by modules
dirRenderer(node, dirs[i]);
}
}
}
// v-show directive needs to be merged from parent to child
var vshowDirectiveInfo = getVShowDirectiveInfo(node);
if (vshowDirectiveInfo) {
directives.show(node, vshowDirectiveInfo);
}
// apply other modules
for (var i$1 = 0; i$1 < modules.length; i$1++) {
var res = modules[i$1](node);
if (res) {
markup += res;
}
}
}
// attach scoped CSS ID
var scopeId;
var activeInstance = context.activeInstance;
if (isDef(activeInstance) &&
activeInstance !== node.context &&
isDef(scopeId = activeInstance.$options._scopeId)
) {
markup += " " + ((scopeId));
}
while (isDef(node)) {
if (isDef(scopeId = node.context.$options._scopeId)) {
markup += " " + scopeId;
}
node = node.parent;
}
return markup + '>'
}
function createRenderFunction (
modules,
directives,
isUnaryTag,
cache
) {
return function render (
component,
write,
userContext,
done
) {
warned = Object.create(null);
var context = new RenderContext({
activeInstance: component,
userContext: userContext,
write: write, done: done, renderNode: renderNode,
isUnaryTag: isUnaryTag, modules: modules, directives: directives,
cache: cache
});
installSSRHelpers(component);
normalizeRender(component);
renderNode(component._render(), true, context);
}
}
/* */
function createBasicRenderer (ref) {
if ( ref === void 0 ) ref = {};
var modules = ref.modules; if ( modules === void 0 ) modules = [];
var directives = ref.directives; if ( directives === void 0 ) directives = {};
var isUnaryTag = ref.isUnaryTag; if ( isUnaryTag === void 0 ) isUnaryTag = (function () { return false; });
var cache = ref.cache;
var render = createRenderFunction(modules, directives, isUnaryTag, cache);
return function renderToString (
component,
context,
done
) {
if (typeof context === 'function') {
done = context;
context = {};
}
var result = '';
var write = createWriteFunction(function (text) {
result += text;
return false
}, done);
try {
render(component, write, context, function () {
done(null, result);
});
} catch (e) {
done(e);
}
}
}
/* */
var entryServerBasicRenderer = createBasicRenderer({
modules: modules,
directives: directives,
isUnaryTag: isUnaryTag,
canBeLeftOpenTag: canBeLeftOpenTag
});
return entryServerBasicRenderer;
})));
node-vue-template-compiler-2.4.2+dfsg/packages/vue-server-renderer/build.js000066400000000000000000006274261361753775300267650ustar00rootroot00000000000000'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var he = _interopDefault(require('he'));
/* */
// these helpers produces 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' ||
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'
}
var _toString = Object.prototype.toString;
/**
* Strict object type check. Only returns true
* for plain JavaScript objects.
*/
function isPlainObject (obj) {
return _toString.call(obj) === '[object Object]'
}
/**
* Check if val is a valid array index.
*/
function isValidArrayIndex (val) {
var n = parseFloat(val);
return n >= 0 && Math.floor(n) === n && isFinite(val)
}
/**
* Convert a value to a string that is actually rendered.
*/
/**
* Convert a input value to a number for persistence.
* If the conversion fails, return original string.
*/
/**
* 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 a attribute is a reserved attribute.
*/
var isReservedAttribute = makeMap('key,ref,slot,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 the 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 = /([^-])([A-Z])/g;
var hyphenate = cached(function (str) {
return str
.replace(hyphenateRE, '$1-$2')
.replace(hyphenateRE, '$1-$2')
.toLowerCase()
});
/**
* Simple bind, faster than native
*/
/**
* Convert an Array-like object to a real Array.
*/
/**
* 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
}
/**
* 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; };
/**
* Return same value
*/
var identity = function (_) { return _; };
/**
* Generate a static keys string 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?
*/
/**
* Ensure a function is called only once.
*/
function once (fn) {
var called = false;
return function () {
if (!called) {
called = true;
fn.apply(this, arguments);
}
}
}
/* */
var isAttr = makeMap(
'accept,accept-charset,accesskey,action,align,alt,async,autocomplete,' +
'autofocus,autoplay,autosave,bgcolor,border,buffered,challenge,charset,' +
'checked,cite,class,code,codebase,color,cols,colspan,content,http-equiv,' +
'name,contenteditable,contextmenu,controls,coords,data,datetime,default,' +
'defer,dir,dirname,disabled,download,draggable,dropzone,enctype,method,for,' +
'form,formaction,headers,height,hidden,high,href,hreflang,http-equiv,' +
'icon,id,ismap,itemprop,keytype,kind,label,lang,language,list,loop,low,' +
'manifest,max,maxlength,media,method,GET,POST,min,multiple,email,file,' +
'muted,name,novalidate,open,optimum,pattern,ping,placeholder,poster,' +
'preload,radiogroup,readonly,rel,required,reversed,rows,rowspan,sandbox,' +
'scope,scoped,seamless,selected,shape,size,type,text,password,sizes,span,' +
'spellcheck,src,srcdoc,srclang,srcset,start,step,style,summary,tabindex,' +
'target,title,type,usemap,value,width,wrap'
);
/* istanbul ignore next */
var isRenderableAttr = function (name) {
return (
isAttr(name) ||
name.indexOf('data-') === 0 ||
name.indexOf('aria-') === 0
)
};
var propsToAttrMap = {
acceptCharset: 'accept-charset',
className: 'class',
htmlFor: 'for',
httpEquiv: 'http-equiv'
};
var ESC = {
'<': '<',
'>': '>',
'"': '"',
'&': '&'
};
function escape (s) {
return s.replace(/[<>"&]/g, escapeChar)
}
var cachedEscape = cached(escape);
function escapeChar (a) {
return ESC[a] || a
}
/* */
// 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');
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 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 isFalsyAttrValue = function (val) {
return val == null || val === false
};
/* */
function renderAttrs (node) {
var attrs = node.data.attrs;
var res = '';
var opts = node.parent && node.parent.componentOptions;
if (isUndef(opts) || opts.Ctor.options.inheritAttrs !== false) {
var parent = node.parent;
while (isDef(parent)) {
if (isDef(parent.data) && isDef(parent.data.attrs)) {
attrs = Object.assign({}, attrs, parent.data.attrs);
}
parent = parent.parent;
}
}
if (isUndef(attrs)) {
return res
}
for (var key in attrs) {
if (key === 'style') {
// leave it to the style module
continue
}
res += renderAttr(key, attrs[key]);
}
return res
}
function renderAttr (key, value) {
if (isBooleanAttr(key)) {
if (!isFalsyAttrValue(value)) {
return (" " + key + "=\"" + key + "\"")
}
} else if (isEnumeratedAttr(key)) {
return (" " + key + "=\"" + (isFalsyAttrValue(value) || value === 'false' ? 'false' : 'true') + "\"")
} else if (!isFalsyAttrValue(value)) {
return (" " + key + "=\"" + (typeof value === 'string' ? cachedEscape(value) : value) + "\"")
}
return ''
}
/* */
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.functionalContext = 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: {} };
// 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 renderDOMProps (node) {
var props = node.data.domProps;
var res = '';
var parent = node.parent;
while (isDef(parent)) {
if (parent.data && parent.data.domProps) {
props = Object.assign({}, props, parent.data.domProps);
}
parent = parent.parent;
}
if (isUndef(props)) {
return res
}
var attrs = node.data.attrs;
for (var key in props) {
if (key === 'innerHTML') {
setText(node, props[key], true);
} else if (key === 'textContent') {
setText(node, props[key], false);
} else {
var attr = propsToAttrMap[key] || key.toLowerCase();
if (isRenderableAttr(attr) &&
// avoid rendering double-bound props/attrs twice
!(isDef(attrs) && isDef(attrs[attr]))
) {
res += renderAttr(attr, props[key]);
}
}
}
return res
}
function setText (node, text, raw) {
var child = new VNode(undefined, undefined, undefined, text);
child.raw = raw;
node.children = [child];
}
/* */
var emptyObject = Object.freeze({});
/**
* 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 = /[^\w.$]/;
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
}
}
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'
];
/* */
var config = ({
/**
* Option merge strategies (used in core/util/options)
*/
optionMergeStrategies: Object.create(null),
/**
* Whether to suppress warnings.
*/
silent: false,
/**
* Show production mode tip message on boot?
*/
productionTip: process.env.NODE_ENV !== 'production',
/**
* Whether to enable devtools
*/
devtools: process.env.NODE_ENV !== '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
*/
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,
/**
* Exposed for legacy reasons
*/
_lifecycleHooks: LIFECYCLE_HOOKS
});
/* */
var warn = noop;
var tip = noop;
var formatComponentName = (null); // work around flow check
if (process.env.NODE_ENV !== 'production') {
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 ''
}
var name = typeof vm === 'string'
? vm
: typeof vm === 'function' && vm.options
? vm.options.name
: vm._isVue
? vm.$options.name || vm.$options._componentTag
: vm.name;
var file = vm._isVue && vm.$options.__file;
if (!name && file) {
var match = file.match(/([^/\\]+)\.vue$/);
name = match && match[1];
}
return (
(name ? ("<" + (classify(name)) + ">") : "") +
(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
};
var 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)) + ")")
}
};
}
/* */
function handleError (err, vm, info) {
if (config.errorHandler) {
config.errorHandler.call(null, err, vm, info);
} else {
if (process.env.NODE_ENV !== 'production') {
warn(("Error in " + info + ": \"" + (err.toString()) + "\""), vm);
}
/* istanbul ignore else */
if (inBrowser && typeof console !== 'undefined') {
console.error(err);
} else {
throw err
}
}
}
/* */
/* globals MutationObserver */
// can we use __proto__?
var hasProto = '__proto__' in {};
// Browser environment sniffing
var inBrowser = typeof window !== 'undefined';
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;
var isIOS = UA && /iphone|ipad|ipod|ios/.test(UA);
var isChrome = UA && /chrome\/\d+/.test(UA) && !isEdge;
// Firefix 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 && typeof global !== 'undefined') {
// detect presence of vue-server-renderer and avoid
// Webpack shimming the process
_isServer = 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);
/**
* Defer a task to execute it asynchronously.
*/
var nextTick = (function () {
var callbacks = [];
var pending = false;
var timerFunc;
function nextTickHandler () {
pending = false;
var copies = callbacks.slice(0);
callbacks.length = 0;
for (var i = 0; i < copies.length; i++) {
copies[i]();
}
}
// 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 if */
if (typeof Promise !== 'undefined' && isNative(Promise)) {
var p = Promise.resolve();
var logError = function (err) { console.error(err); };
timerFunc = function () {
p.then(nextTickHandler).catch(logError);
// 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); }
};
} else if (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 IE11, iOS7, Android 4.4
var counter = 1;
var observer = new MutationObserver(nextTickHandler);
var textNode = document.createTextNode(String(counter));
observer.observe(textNode, {
characterData: true
});
timerFunc = function () {
counter = (counter + 1) % 2;
textNode.data = String(counter);
};
} else {
// fallback to setTimeout
/* istanbul ignore next */
timerFunc = function () {
setTimeout(nextTickHandler, 0);
};
}
return function queueNextTick (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();
}
if (!cb && typeof Promise !== 'undefined') {
return new Promise(function (resolve, reject) {
_resolve = resolve;
})
}
}
})();
var _Set;
/* istanbul ignore if */
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 = (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 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();
for (var i = 0, l = subs.length; i < l; i++) {
subs[i].update();
}
};
// the current target watcher being evaluated.
// this is globally unique because there could be only one
// watcher being evaluated at any time.
Dep.target = null;
var targetStack = [];
function pushTarget (_target) {
if (Dep.target) { targetStack.push(Dep.target); }
Dep.target = _target;
}
function popTarget () {
Dep.target = targetStack.pop();
}
/*
* 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);[
'push',
'pop',
'shift',
'unshift',
'splice',
'sort',
'reverse'
]
.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);
/**
* By default, when a reactive property is set, the new value is
* also converted to become reactive. However when passing down props,
* we don't want to force conversion because the value may be a nested value
* under a frozen data structure. Converting it would defeat the optimization.
*/
var observerState = {
shouldConvert: true
};
/**
* Observer class that are attached to each observed
* object. Once attached, the observer converts target
* object's property keys into getter/setters that
* collect dependencies and dispatches updates.
*/
var Observer = function Observer (value) {
this.value = value;
this.dep = new Dep();
this.vmCount = 0;
def(value, '__ob__', this);
if (Array.isArray(value)) {
var augment = hasProto
? protoAugment
: copyAugment;
augment(value, arrayMethods, arrayKeys);
this.observeArray(value);
} else {
this.walk(value);
}
};
/**
* Walk through each property 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], 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 an target Object or Array by intercepting
* the prototype chain using __proto__
*/
function protoAugment (target, src, keys) {
/* eslint-disable no-proto */
target.__proto__ = src;
/* eslint-enable no-proto */
}
/**
* Augment an 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)) {
return
}
var ob;
if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) {
ob = value.__ob__;
} else if (
observerState.shouldConvert &&
!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;
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 (process.env.NODE_ENV !== 'production' && customSetter) {
customSetter();
}
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 (Array.isArray(target) && isValidArrayIndex(key)) {
target.length = Math.max(target.length, key);
target.splice(key, 1, val);
return val
}
if (hasOwn(target, key)) {
target[key] = val;
return val
}
var ob = (target).__ob__;
if (target._isVue || (ob && ob.vmCount)) {
process.env.NODE_ENV !== 'production' && 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.
*/
/**
* 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
*/
if (process.env.NODE_ENV !== 'production') {
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 = Object.keys(from);
for (var i = 0; i < keys.length; i++) {
key = keys[i];
toVal = to[key];
fromVal = from[key];
if (!hasOwn(to, key)) {
set(to, key, fromVal);
} else if (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) : childVal,
typeof parentVal === 'function' ? parentVal.call(this) : parentVal
)
}
} else if (parentVal || childVal) {
return function mergedInstanceDataFn () {
// instance merge
var instanceData = typeof childVal === 'function'
? childVal.call(vm)
: childVal;
var defaultData = typeof parentVal === 'function'
? parentVal.call(vm)
: undefined;
if (instanceData) {
return mergeData(instanceData, defaultData)
} else {
return defaultData
}
}
}
}
strats.data = function (
parentVal,
childVal,
vm
) {
if (!vm) {
if (childVal && typeof childVal !== 'function') {
process.env.NODE_ENV !== 'production' && warn(
'The "data" option should be a function ' +
'that returns a per-instance value in component ' +
'definitions.',
vm
);
return parentVal
}
return mergeDataOrFn.call(this, parentVal, childVal)
}
return mergeDataOrFn(parentVal, childVal, vm)
};
/**
* Hooks and props are merged as arrays.
*/
function mergeHook (
parentVal,
childVal
) {
return childVal
? parentVal
? parentVal.concat(childVal)
: Array.isArray(childVal)
? childVal
: [childVal]
: parentVal
}
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) {
var res = Object.create(parentVal || null);
return childVal
? extend(res, childVal)
: 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) {
// 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) }
if (!parentVal) { return childVal }
var ret = {};
extend(ret, parentVal);
for (var key in childVal) {
var parent = ret[key];
var child = childVal[key];
if (parent && !Array.isArray(parent)) {
parent = [parent];
}
ret[key] = 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) {
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) {
var lower = key.toLowerCase();
if (isBuiltInTag(lower) || config.isReservedTag(lower)) {
warn(
'Do not use built-in or reserved HTML elements as component ' +
'id: ' + key
);
}
}
}
/**
* Ensure all props option syntax are normalized into the
* Object-based format.
*/
function normalizeProps (options) {
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 if (process.env.NODE_ENV !== 'production') {
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 };
}
}
options.props = res;
}
/**
* Normalize all injections into Object-based format
*/
function normalizeInject (options) {
var inject = options.inject;
if (Array.isArray(inject)) {
var normalized = options.inject = {};
for (var i = 0; i < inject.length; i++) {
normalized[inject[i]] = inject[i];
}
}
}
/**
* Normalize raw function directives into object format.
*/
function normalizeDirectives (options) {
var dirs = options.directives;
if (dirs) {
for (var key in dirs) {
var def = dirs[key];
if (typeof def === 'function') {
dirs[key] = { bind: def, update: def };
}
}
}
}
/**
* Merge two option objects into a new one.
* Core utility used in both instantiation and inheritance.
*/
function mergeOptions (
parent,
child,
vm
) {
if (process.env.NODE_ENV !== 'production') {
checkComponents(child);
}
if (typeof child === 'function') {
child = child.options;
}
normalizeProps(child);
normalizeInject(child);
normalizeDirectives(child);
var extendsFrom = child.extends;
if (extendsFrom) {
parent = mergeOptions(parent, extendsFrom, 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 (process.env.NODE_ENV !== 'production' && 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];
// handle boolean props
if (isType(Boolean, prop.type)) {
if (absent && !hasOwn(prop, 'default')) {
value = false;
} else if (!isType(String, prop.type) && (value === '' || value === hyphenate(key))) {
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 prevShouldConvert = observerState.shouldConvert;
observerState.shouldConvert = true;
observe(value);
observerState.shouldConvert = prevShouldConvert;
}
if (process.env.NODE_ENV !== 'production') {
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 (process.env.NODE_ENV !== 'production' && 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(
'Invalid prop: type check failed for prop "' + name + '".' +
' Expected ' + expectedTypes.map(capitalize).join(', ') +
', got ' + Object.prototype.toString.call(value).slice(8, -1) + '.',
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)) {
valid = typeof value === expectedType.toLowerCase();
} 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 isType (type, fn) {
if (!Array.isArray(fn)) {
return getType(fn) === getType(type)
}
for (var i = 0, len = fn.length; i < len; i++) {
if (getType(fn[i]) === getType(type)) {
return true
}
}
/* istanbul ignore next */
return false
}
/* */
/* */
function genClassForVnode (vnode) {
var data = vnode.data;
var parentNode = vnode;
var childNode = vnode;
while (isDef(childNode.componentInstance)) {
childNode = childNode.componentInstance._vnode;
if (childNode.data) {
data = mergeClassData(childNode.data, data);
}
}
while (isDef(parentNode = parentNode.parent)) {
if (parentNode.data) {
data = mergeClassData(data, parentNode.data);
}
}
return renderClass$1(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$1 (
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 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'
}
}
/* */
/**
* Query an element selector if it's not an element already.
*/
/* */
function renderClass (node) {
var classList = genClassForVnode(node);
if (classList !== '') {
return (" class=\"" + (cachedEscape(classList)) + "\"")
}
}
/* */
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.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
}
/* */
function genStyle (style) {
var styleText = '';
for (var key in style) {
var value = style[key];
var hyphenatedKey = hyphenate(key);
if (Array.isArray(value)) {
for (var i = 0, len = value.length; i < len; i++) {
styleText += hyphenatedKey + ":" + (value[i]) + ";";
}
} else {
styleText += hyphenatedKey + ":" + value + ";";
}
}
return styleText
}
function renderStyle (vnode) {
var styleText = genStyle(getStyle(vnode, false));
if (styleText !== '') {
return (" style=" + (JSON.stringify(cachedEscape(styleText))))
}
}
var modules = [
renderAttrs,
renderDOMProps,
renderClass,
renderStyle
];
/* */
function show (node, dir) {
if (!dir.value) {
var style = node.data.style || (node.data.style = {});
style.display = 'none';
}
}
var baseDirectives = {
show: show
};
/* */
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'
);
/* */
var MAX_STACK_DEPTH = 1000;
function createWriteFunction (
write,
onError
) {
var stackDepth = 0;
var cachedWrite = function (text, next) {
if (text && cachedWrite.caching) {
cachedWrite.cacheBuffer[cachedWrite.cacheBuffer.length - 1] += text;
}
var waitForNext = write(text, next);
if (waitForNext !== true) {
if (stackDepth >= MAX_STACK_DEPTH) {
process.nextTick(function () {
try { next(); } catch (e) {
onError(e);
}
});
} else {
stackDepth++;
next();
stackDepth--;
}
}
};
cachedWrite.caching = false;
cachedWrite.cacheBuffer = [];
cachedWrite.componentBuffer = [];
return cachedWrite
}
/* */
/**
* Original RenderStream implementation by Sasha Aickin (@aickin)
* Licensed under the Apache License, Version 2.0
* http://www.apache.org/licenses/LICENSE-2.0
*
* Modified by Evan You (@yyx990803)
*/
var stream = require('stream');
var RenderStream = (function (superclass) {
function RenderStream (render) {
var this$1 = this;
superclass.call(this);
this.buffer = '';
this.render = render;
this.expectedSize = 0;
this.write = createWriteFunction(function (text, next) {
var n = this$1.expectedSize;
this$1.buffer += text;
if (this$1.buffer.length >= n) {
this$1.next = next;
this$1.pushBySize(n);
return true // we will decide when to call next
}
return false
}, function (err) {
this$1.emit('error', err);
});
this.end = function () {
// the rendering is finished; we should push out the last of the buffer.
this$1.done = true;
this$1.push(this$1.buffer);
};
}
if ( superclass ) RenderStream.__proto__ = superclass;
RenderStream.prototype = Object.create( superclass && superclass.prototype );
RenderStream.prototype.constructor = RenderStream;
RenderStream.prototype.pushBySize = function pushBySize (n) {
var bufferToPush = this.buffer.substring(0, n);
this.buffer = this.buffer.substring(n);
this.push(bufferToPush);
};
RenderStream.prototype.tryRender = function tryRender () {
try {
this.render(this.write, this.end);
} catch (e) {
this.emit('error', e);
}
};
RenderStream.prototype.tryNext = function tryNext () {
try {
this.next();
} catch (e) {
this.emit('error', e);
}
};
RenderStream.prototype._read = function _read (n) {
this.expectedSize = n;
// it's possible that the last chunk added bumped the buffer up to > 2 * n,
// which means we will need to go through multiple read calls to drain it
// down to < n.
if (isTrue(this.done)) {
this.push(null);
return
}
if (this.buffer.length >= n) {
this.pushBySize(n);
return
}
if (isUndef(this.next)) {
// start the rendering chain.
this.tryRender();
} else {
// continue with the rendering.
this.tryNext();
}
};
return RenderStream;
}(stream.Readable));
/* */
var RenderContext = function RenderContext (options) {
this.userContext = options.userContext;
this.activeInstance = options.activeInstance;
this.renderStates = [];
this.write = options.write;
this.done = options.done;
this.renderNode = options.renderNode;
this.isUnaryTag = options.isUnaryTag;
this.modules = options.modules;
this.directives = options.directives;
var cache = options.cache;
if (cache && (!cache.get || !cache.set)) {
throw new Error('renderer cache must implement at least get & set.')
}
this.cache = cache;
this.get = cache && normalizeAsync(cache, 'get');
this.has = cache && normalizeAsync(cache, 'has');
this.next = this.next.bind(this);
};
RenderContext.prototype.next = function next () {
var lastState = this.renderStates[this.renderStates.length - 1];
if (isUndef(lastState)) {
return this.done()
}
switch (lastState.type) {
case 'Element':
var children = lastState.children;
var total = lastState.total;
var rendered = lastState.rendered++;
if (rendered < total) {
this.renderNode(children[rendered], false, this);
} else {
this.renderStates.pop();
this.write(lastState.endTag, this.next);
}
break
case 'Component':
this.renderStates.pop();
this.activeInstance = lastState.prevActive;
this.next();
break
case 'ComponentWithCache':
this.renderStates.pop();
var buffer = lastState.buffer;
var bufferIndex = lastState.bufferIndex;
var componentBuffer = lastState.componentBuffer;
var key = lastState.key;
var result = {
html: buffer[bufferIndex],
components: componentBuffer[bufferIndex]
};
this.cache.set(key, result);
if (bufferIndex === 0) {
// this is a top-level cached component,
// exit caching mode.
this.write.caching = false;
} else {
// parent component is also being cached,
// merge self into parent's result
buffer[bufferIndex - 1] += result.html;
var prev = componentBuffer[bufferIndex - 1];
result.components.forEach(function (c) { return prev.add(c); });
}
buffer.length = bufferIndex;
componentBuffer.length = bufferIndex;
this.next();
break
}
};
function normalizeAsync (cache, method) {
var fn = cache[method];
if (isUndef(fn)) {
return
} else if (fn.length > 1) {
return function (key, cb) { return fn.call(cache, key, cb); }
} else {
return function (key, cb) { return cb(fn.call(cache, key)); }
}
}
/* */
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)
}
}
/* */
var defaultTagRE = /\{\{((?:.|\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 lastIndex = tagRE.lastIndex = 0;
var match, index;
while ((match = tagRE.exec(text))) {
index = match.index;
// push text token
if (index > lastIndex) {
tokens.push(JSON.stringify(text.slice(lastIndex, index)));
}
// tag token
var exp = parseFilters(match[1].trim());
tokens.push(("_s(" + exp + ")"));
lastIndex = index + match[0].length;
}
if (lastIndex < text.length) {
tokens.push(JSON.stringify(text.slice(lastIndex)));
}
return tokens.join('+')
}
/* */
function baseWarn (msg) {
console.error(("[Vue compiler]: " + msg));
}
function pluckModuleFunction (
modules,
key
) {
return modules
? modules.map(function (m) { return m[key]; }).filter(function (_) { return _; })
: []
}
function addProp (el, name, value) {
(el.props || (el.props = [])).push({ name: name, value: value });
}
function addAttr (el, name, value) {
(el.attrs || (el.attrs = [])).push({ name: name, value: value });
}
function addDirective (
el,
name,
rawName,
value,
arg,
modifiers
) {
(el.directives || (el.directives = [])).push({ name: name, rawName: rawName, value: value, arg: arg, modifiers: modifiers });
}
function addHandler (
el,
name,
value,
modifiers,
important,
warn
) {
// warn prevent and passive modifier
/* istanbul ignore if */
if (
process.env.NODE_ENV !== 'production' && warn &&
modifiers && modifiers.prevent && modifiers.passive
) {
warn(
'passive and prevent can\'t be used together. ' +
'Passive handler can\'t prevent default event.'
);
}
// check capture modifier
if (modifiers && modifiers.capture) {
delete modifiers.capture;
name = '!' + name; // mark the event as captured
}
if (modifiers && modifiers.once) {
delete modifiers.once;
name = '~' + name; // mark the event as once
}
/* istanbul ignore if */
if (modifiers && modifiers.passive) {
delete modifiers.passive;
name = '&' + name; // mark the event as passive
}
var events;
if (modifiers && modifiers.native) {
delete modifiers.native;
events = el.nativeEvents || (el.nativeEvents = {});
} else {
events = el.events || (el.events = {});
}
var newHandler = { value: value, 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;
}
}
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)
}
}
}
function getAndRemoveAttr (el, name) {
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
}
}
}
return val
}
/* */
function transformNode (el, options) {
var warn = options.warn || baseWarn;
var staticClass = getAndRemoveAttr(el, 'class');
if (process.env.NODE_ENV !== 'production' && staticClass) {
var expression = parseText(staticClass, options.delimiters);
if (expression) {
warn(
"class=\"" + staticClass + "\": " +
'Interpolation inside attributes has been removed. ' +
'Use v-bind or the colon shorthand instead. For example, ' +
'instead of , use
.'
);
}
}
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 = {
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 */
if (process.env.NODE_ENV !== 'production') {
var expression = parseText(staticStyle, options.delimiters);
if (expression) {
warn(
"style=\"" + staticStyle + "\": " +
'Interpolation inside attributes has been removed. ' +
'Use v-bind or the colon shorthand instead. For example, ' +
'instead of
, use
.'
);
}
}
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 = {
staticKeys: ['staticStyle'],
transformNode: transformNode$1,
genData: genData$1
};
var modules$1 = [
klass,
style
];
/* */
/**
* 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: ("\"" + value + "\""),
callback: ("function (" + baseValueExpression + ") {" + assignment + "}")
};
}
/**
* Cross-platform codegen helper for generating v-model value assignment code.
*/
function genAssignmentCode (
value,
assignment
) {
var modelRs = parseModel(value);
if (modelRs.idx === null) {
return (value + "=" + assignment)
} else {
return ("$set(" + (modelRs.exp) + ", " + (modelRs.idx) + ", " + assignment + ")")
}
}
/**
* parse directive model to do the array update transform. a[idx] = val => $$a.splice($$idx, 1, val)
*
* for loop possible cases:
*
* - test
* - test[idx]
* - test[test1[idx]]
* - test["a"][idx]
* - xxx.test[a[a].test1[idx]]
* - test.xxx.a["asa"][test1[idx]]
*
*/
var len;
var str;
var chr;
var index;
var expressionPos;
var expressionEndPos;
function parseModel (val) {
str = val;
len = str.length;
index = expressionPos = expressionEndPos = 0;
if (val.indexOf('[') < 0 || val.lastIndexOf(']') < len - 1) {
return {
exp: val,
idx: null
}
}
while (!eof()) {
chr = next();
/* istanbul ignore if */
if (isStringStart(chr)) {
parseString(chr);
} else if (chr === 0x5B) {
parseBracket(chr);
}
}
return {
exp: val.substring(0, expressionPos),
idx: val.substring(expressionPos + 1, expressionEndPos)
}
}
function next () {
return str.charCodeAt(++index)
}
function eof () {
return index >= len
}
function isStringStart (chr) {
return chr === 0x22 || chr === 0x27
}
function parseBracket (chr) {
var inBracket = 1;
expressionPos = index;
while (!eof()) {
chr = next();
if (isStringStart(chr)) {
parseString(chr);
continue
}
if (chr === 0x5B) { inBracket++; }
if (chr === 0x5D) { inBracket--; }
if (inBracket === 0) {
expressionEndPos = index;
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;
if (process.env.NODE_ENV !== 'production') {
var dynamicType = el.attrsMap['v-bind:type'] || el.attrsMap[':type'];
if (tag === 'input' && dynamicType) {
warn$1(
"
:\n" +
"v-model does not support dynamic input types. Use v-if branches instead."
);
}
// 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."
);
}
}
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 if (process.env.NODE_ENV !== 'production') {
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.'
);
}
// 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, CHECKBOX_RADIO_TOKEN,
"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&&(" + value + "=$$a.concat($$v))}" +
"else{$$i>-1&&(" + 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, CHECKBOX_RADIO_TOKEN, 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;
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()');
}
}
/* */
function text (el, dir) {
if (dir.value) {
addProp(el, 'textContent', ("_s(" + (dir.value) + ")"));
}
}
/* */
function html (el, dir) {
if (dir.value) {
addProp(el, 'innerHTML', ("_s(" + (dir.value) + ")"));
}
}
var directives = {
model: model,
text: text,
html: html
};
/* */
var baseOptions = {
expectHTML: true,
modules: modules$1,
directives: directives,
isPreTag: isPreTag,
isUnaryTag: isUnaryTag,
mustUseProp: mustUseProp,
canBeLeftOpenTag: canBeLeftOpenTag,
isReservedTag: isReservedTag,
getTagNamespace: getTagNamespace,
staticKeys: genStaticKeys(modules$1)
};
/**
* Not type-checking this file because it's mostly vendor code.
*/
/*!
* HTML Parser By John Resig (ejohn.org)
* Modified by Juriy "kangax" Zaytsev
* Original code by Erik Arvidsson, Mozilla Public License
* http://erik.eae.net/simplehtmlparser/simplehtmlparser.js
*/
// Regular Expressions for parsing tags and attributes
var singleAttrIdentifier = /([^\s"'<>/=]+)/;
var singleAttrAssign = /(?:=)/;
var singleAttrValues = [
// attr value double quotes
/"([^"]*)"+/.source,
// attr value, single quotes
/'([^']*)'+/.source,
// attr value, no quotes
/([^\s"'=<>`]+)/.source
];
var attribute = new RegExp(
'^\\s*' + singleAttrIdentifier.source +
'(?:\\s*(' + singleAttrAssign.source + ')' +
'\\s*(?:' + singleAttrValues.join('|') + '))?'
);
// could use https://www.w3.org/TR/1999/REC-xml-names-19990114/#NT-QName
// but for Vue templates we can enforce a simple charset
var ncname = '[a-zA-Z_][\\w\\-\\.]*';
var qnameCapture = '((?:' + ncname + '\\:)?' + ncname + ')';
var startTagOpen = new RegExp('^<' + qnameCapture);
var startTagClose = /^\s*(\/?)>/;
var endTag = new RegExp('^<\\/' + qnameCapture + '[^>]*>');
var doctype = /^]+>/i;
var comment = /^');
if (commentEnd >= 0) {
if (options.shouldKeepComment) {
options.comment(html.substring(4, commentEnd));
}
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(lastTag, 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);
advance(textEnd);
}
if (textEnd < 0) {
text = html;
html = '';
}
if (options.chars && text) {
options.chars(text);
}
} else {
var endTagLength = 0;
var stackedTag = lastTag.toLowerCase();
var reStackedTag = reCache[stackedTag] || (reCache[stackedTag] = new RegExp('([\\s\\S]*?)(]*>)', 'i'));
var rest$1 = html.replace(reStackedTag, function (all, text, endTag) {
endTagLength = endTag.length;
if (!isPlainTextElement(stackedTag) && stackedTag !== 'noscript') {
text = text
.replace(//g, '$1')
.replace(//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 (process.env.NODE_ENV !== 'production' && !stack.length && options.warn) {
options.warn(("Mal-formatted tag at end of template: \"" + html + "\""));
}
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(attribute))) {
advance(attr[0].length);
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];
// hackish work around FF bug https://bugzilla.mozilla.org/show_bug.cgi?id=369778
if (IS_REGEX_CAPTURING_BROKEN && args[0].indexOf('""') === -1) {
if (args[3] === '') { delete args[3]; }
if (args[4] === '') { delete args[4]; }
if (args[5] === '') { delete args[5]; }
}
var value = args[3] || args[4] || args[5] || '';
attrs[i] = {
name: args[1],
value: decodeAttr(
value,
options.shouldDecodeNewlines
)
};
}
if (!unary) {
stack.push({ tag: tagName, lowerCasedTag: tagName.toLowerCase(), attrs: attrs });
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; }
if (tagName) {
lowerCasedTagName = tagName.toLowerCase();
}
// Find the closest opened tag of the same type
if (tagName) {
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 (process.env.NODE_ENV !== 'production' &&
(i > pos || !tagName) &&
options.warn
) {
options.warn(
("tag <" + (stack[i].tag) + "> has no matching end tag.")
);
}
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+(?:in|of)\s+(.*)/;
var forIteratorRE = /\((\{[^}]*\}|[^,]*),([^,]*)(?:,([^,]*))?\)/;
var argRE = /:(.*)$/;
var bindRE = /^:|^v-bind:/;
var modifierRE = /\.[^.]+/g;
var decodeHTMLCached = cached(he.decode);
// configurable state
var warn$2;
var delimiters;
var transforms;
var preTransforms;
var postTransforms;
var platformIsPreTag;
var platformMustUseProp;
var platformGetTagNamespace;
/**
* 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;
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 root;
var currentParent;
var inVPre = false;
var inPre = false;
var warned = false;
function warnOnce (msg) {
if (!warned) {
warned = true;
warn$2(msg);
}
}
function endPre (element) {
// check pre state
if (element.pre) {
inVPre = false;
}
if (platformIsPreTag(element.tag)) {
inPre = false;
}
}
parseHTML(template, {
warn: warn$2,
expectHTML: options.expectHTML,
isUnaryTag: options.isUnaryTag,
canBeLeftOpenTag: options.canBeLeftOpenTag,
shouldDecodeNewlines: options.shouldDecodeNewlines,
shouldKeepComment: options.comments,
start: function start (tag, attrs, unary) {
// 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 = {
type: 1,
tag: tag,
attrsList: attrs,
attrsMap: makeAttrsMap(attrs),
parent: currentParent,
children: []
};
if (ns) {
element.ns = ns;
}
if (isForbiddenTag(element) && !isServerRendering()) {
element.forbidden = true;
process.env.NODE_ENV !== 'production' && 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.'
);
}
// apply pre-transforms
for (var i = 0; i < preTransforms.length; i++) {
preTransforms[i](element, options);
}
if (!inVPre) {
processPre(element);
if (element.pre) {
inVPre = true;
}
}
if (platformIsPreTag(element.tag)) {
inPre = true;
}
if (inVPre) {
processRawAttrs(element);
} else {
processFor(element);
processIf(element);
processOnce(element);
processKey(element);
// determine whether this is a plain element after
// removing structural attributes
element.plain = !element.key && !attrs.length;
processRef(element);
processSlot(element);
processComponent(element);
for (var i$1 = 0; i$1 < transforms.length; i$1++) {
transforms[i$1](element, options);
}
processAttrs(element);
}
function checkRootConstraints (el) {
if (process.env.NODE_ENV !== 'production') {
if (el.tag === 'slot' || el.tag === 'template') {
warnOnce(
"Cannot use <" + (el.tag) + "> as component root element because it may " +
'contain multiple nodes.'
);
}
if (el.attrsMap.hasOwnProperty('v-for')) {
warnOnce(
'Cannot use v-for on stateful component root element because ' +
'it renders multiple elements.'
);
}
}
}
// tree management
if (!root) {
root = element;
checkRootConstraints(root);
} else if (!stack.length) {
// 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 if (process.env.NODE_ENV !== 'production') {
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."
);
}
}
if (currentParent && !element.forbidden) {
if (element.elseif || element.else) {
processIfConditions(element, currentParent);
} else if (element.slotScope) { // scoped slot
currentParent.plain = false;
var name = element.slotTarget || '"default"';(currentParent.scopedSlots || (currentParent.scopedSlots = {}))[name] = element;
} else {
currentParent.children.push(element);
element.parent = currentParent;
}
}
if (!unary) {
currentParent = element;
stack.push(element);
} else {
endPre(element);
}
// apply post-transforms
for (var i$2 = 0; i$2 < postTransforms.length; i$2++) {
postTransforms[i$2](element, options);
}
},
end: function end () {
// remove trailing whitespace
var element = stack[stack.length - 1];
var lastNode = element.children[element.children.length - 1];
if (lastNode && lastNode.type === 3 && lastNode.text === ' ' && !inPre) {
element.children.pop();
}
// pop stack
stack.length -= 1;
currentParent = stack[stack.length - 1];
endPre(element);
},
chars: function chars (text) {
if (!currentParent) {
if (process.env.NODE_ENV !== 'production') {
if (text === template) {
warnOnce(
'Component template requires a root element, rather than just text.'
);
} else if ((text = text.trim())) {
warnOnce(
("text \"" + text + "\" outside root element will be ignored.")
);
}
}
return
}
// IE textarea placeholder bug
/* istanbul ignore if */
if (isIE &&
currentParent.tag === 'textarea' &&
currentParent.attrsMap.placeholder === text
) {
return
}
var children = currentParent.children;
text = inPre || text.trim()
? isTextTag(currentParent) ? text : decodeHTMLCached(text)
// only preserve whitespace if its not right after a starting tag
: preserveWhitespace && children.length ? ' ' : '';
if (text) {
var expression;
if (!inVPre && text !== ' ' && (expression = parseText(text, delimiters))) {
children.push({
type: 2,
expression: expression,
text: text
});
} else if (text !== ' ' || !children.length || children[children.length - 1].text !== ' ') {
children.push({
type: 3,
text: text
});
}
}
},
comment: function comment (text) {
currentParent.children.push({
type: 3,
text: text,
isComment: true
});
}
});
return root
}
function processPre (el) {
if (getAndRemoveAttr(el, 'v-pre') != null) {
el.pre = true;
}
}
function processRawAttrs (el) {
var l = el.attrsList.length;
if (l) {
var attrs = el.attrs = new Array(l);
for (var i = 0; i < l; i++) {
attrs[i] = {
name: el.attrsList[i].name,
value: JSON.stringify(el.attrsList[i].value)
};
}
} else if (!el.pre) {
// non root node in pre blocks with no attributes
el.plain = true;
}
}
function processKey (el) {
var exp = getBindingAttr(el, 'key');
if (exp) {
if (process.env.NODE_ENV !== 'production' && el.tag === 'template') {
warn$2("
cannot be keyed. Place the key on real elements instead.");
}
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 inMatch = exp.match(forAliasRE);
if (!inMatch) {
process.env.NODE_ENV !== 'production' && warn$2(
("Invalid v-for expression: " + exp)
);
return
}
el.for = inMatch[2].trim();
var alias = inMatch[1].trim();
var iteratorMatch = alias.match(forIteratorRE);
if (iteratorMatch) {
el.alias = iteratorMatch[1].trim();
el.iterator1 = iteratorMatch[2].trim();
if (iteratorMatch[3]) {
el.iterator2 = iteratorMatch[3].trim();
}
} else {
el.alias = alias;
}
}
}
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 if (process.env.NODE_ENV !== 'production') {
warn$2(
"v-" + (el.elseif ? ('else-if="' + el.elseif + '"') : 'else') + " " +
"used on element <" + (el.tag) + "> without corresponding v-if."
);
}
}
function findPrevElement (children) {
var i = children.length;
while (i--) {
if (children[i].type === 1) {
return children[i]
} else {
if (process.env.NODE_ENV !== 'production' && children[i].text !== ' ') {
warn$2(
"text \"" + (children[i].text.trim()) + "\" between v-if and v-else(-if) " +
"will be ignored."
);
}
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;
}
}
function processSlot (el) {
if (el.tag === 'slot') {
el.slotName = getBindingAttr(el, 'name');
if (process.env.NODE_ENV !== 'production' && el.key) {
warn$2(
"`key` does not work on because slots are abstract outlets " +
"and can possibly expand into multiple elements. " +
"Use the key on a wrapping element instead."
);
}
} else {
var slotTarget = getBindingAttr(el, 'slot');
if (slotTarget) {
el.slotTarget = slotTarget === '""' ? '"default"' : slotTarget;
}
if (el.tag === 'template') {
el.slotScope = getAndRemoveAttr(el, 'scope');
}
}
}
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, isProp;
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);
if (modifiers) {
name = name.replace(modifierRE, '');
}
if (bindRE.test(name)) { // v-bind
name = name.replace(bindRE, '');
value = parseFilters(value);
isProp = false;
if (modifiers) {
if (modifiers.prop) {
isProp = true;
name = camelize(name);
if (name === 'innerHtml') { name = 'innerHTML'; }
}
if (modifiers.camel) {
name = camelize(name);
}
if (modifiers.sync) {
addHandler(
el,
("update:" + (camelize(name))),
genAssignmentCode(value, "$event")
);
}
}
if (isProp || (
!el.component && platformMustUseProp(el.tag, el.attrsMap.type, name)
)) {
addProp(el, name, value);
} else {
addAttr(el, name, value);
}
} else if (onRE.test(name)) { // v-on
name = name.replace(onRE, '');
addHandler(el, name, value, modifiers, false, warn$2);
} else { // normal directives
name = name.replace(dirRE, '');
// parse arg
var argMatch = name.match(argRE);
var arg = argMatch && argMatch[1];
if (arg) {
name = name.slice(0, -(arg.length + 1));
}
addDirective(el, name, rawName, value, arg, modifiers);
if (process.env.NODE_ENV !== 'production' && name === 'model') {
checkForAliasModel(el, value);
}
}
} else {
// literal attribute
if (process.env.NODE_ENV !== 'production') {
var expression = parseText(value, delimiters);
if (expression) {
warn$2(
name + "=\"" + value + "\": " +
'Interpolation inside attributes has been removed. ' +
'Use v-bind or the colon shorthand instead. For example, ' +
'instead of , use
.'
);
}
}
addAttr(el, name, JSON.stringify(value));
}
}
}
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 (
process.env.NODE_ENV !== 'production' &&
map[attrs[i].name] && !isIE && !isEdge
) {
warn$2('duplicate attribute: ' + attrs[i].name);
}
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 = _el.parent;
}
}
/* */
var fnExpRE = /^\s*([\w$_]+|\([^)]*?\))\s*=>|^function\s*\(/;
var simplePathRE = /^\s*[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\['.*?']|\[".*?"]|\[\d+]|\[[A-Za-z_$][\w$]*])*\s*$/;
// keyCode aliases
var keyCodes = {
esc: 27,
tab: 9,
enter: 13,
space: 32,
up: 38,
left: 37,
right: 39,
down: 40,
'delete': [8, 46]
};
// #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,
warn
) {
var res = isNative ? 'nativeOn:{' : 'on:{';
for (var name in events) {
var handler = events[name];
// #5330: warn click.right, since right clicks do not actually fire click events.
if (process.env.NODE_ENV !== 'production' &&
name === 'click' &&
handler && handler.modifiers && handler.modifiers.right
) {
warn(
"Use \"contextmenu\" instead of \"click.right\" since right clicks " +
"do not actually fire \"click\" events."
);
}
res += "\"" + name + "\":" + (genHandler(name, handler)) + ",";
}
return res.slice(0, -1) + '}'
}
function genHandler (
name,
handler
) {
if (!handler) {
return 'function(){}'
}
if (Array.isArray(handler)) {
return ("[" + (handler.map(function (handler) { return genHandler(name, handler); }).join(',')) + "]")
}
var isMethodPath = simplePathRE.test(handler.value);
var isFunctionExpression = fnExpRE.test(handler.value);
if (!handler.modifiers) {
return isMethodPath || isFunctionExpression
? handler.value
: ("function($event){" + (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 {
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
? handler.value + '($event)'
: isFunctionExpression
? ("(" + (handler.value) + ")($event)")
: handler.value;
return ("function($event){" + code + handlerCode + "}")
}
}
function genKeyFilter (keys) {
return ("if(!('button' in $event)&&" + (keys.map(genFilterCode).join('&&')) + ")return null;")
}
function genFilterCode (key) {
var keyVal = parseInt(key, 10);
if (keyVal) {
return ("$event.keyCode!==" + keyVal)
}
var alias = keyCodes[key];
return ("_k($event.keyCode," + (JSON.stringify(key)) + (alias ? ',' + JSON.stringify(alias) : '') + ")")
}
/* */
function on (el, dir) {
if (process.env.NODE_ENV !== 'production' && 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$1 = {
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$1), options.directives);
var isReservedTag = options.isReservedTag || no;
this.maybeComponent = function (el) { return !isReservedTag(el.tag); };
this.onceId = 0;
this.staticRenderFns = [];
};
function generate$1 (
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.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) {
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 = el.plain ? undefined : 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;
state.staticRenderFns.push(("with(this){return " + (genElement(el, state)) + "}"));
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) {
process.env.NODE_ENV !== 'production' && state.warn(
"v-once can only be used inside v-for that is keyed. "
);
return genElement(el, state)
}
return ("_o(" + (genElement(el, state)) + "," + (state.onceId++) + (key ? ("," + 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 (process.env.NODE_ENV !== 'production' &&
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.",
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, state.warn)) + ",";
}
if (el.nativeEvents) {
data += (genHandlers(el.nativeEvents, true, state.warn)) + ",";
}
// slot target
if (el.slotTarget) {
data += "slot:" + (el.slotTarget) + ",";
}
// scoped slots
if (el.scopedSlots) {
data += (genScopedSlots(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 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.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 (process.env.NODE_ENV !== 'production' && (
el.children.length > 1 || ast.type !== 1
)) {
state.warn('Inline-template components must have exactly one child element.');
}
if (ast.type === 1) {
var inlineRenderFns = generate$1(ast, state.options);
return ("inlineTemplate:{render:function(){" + (inlineRenderFns.render) + "},staticRenderFns:[" + (inlineRenderFns.staticRenderFns.map(function (code) { return ("function(){" + code + "}"); }).join(',')) + "]}")
}
}
function genScopedSlots (
slots,
state
) {
return ("scopedSlots:_u([" + (Object.keys(slots).map(function (key) {
return genScopedSlot(key, slots[key], state)
}).join(',')) + "])")
}
function genScopedSlot (
key,
el,
state
) {
if (el.for && !el.forProcessed) {
return genForScopedSlot(key, el, state)
}
return "{key:" + key + ",fn:function(" + (String(el.attrsMap.scope)) + "){" +
"return " + (el.tag === 'template'
? genChildren(el, state) || 'void 0'
: genElement(el, state)) + "}}"
}
function genForScopedSlot (
key,
el,
state
) {
var exp = el.for;
var alias = el.alias;
var iterator1 = el.iterator1 ? ("," + (el.iterator1)) : '';
var iterator2 = el.iterator2 ? ("," + (el.iterator2)) : '';
el.forProcessed = true; // avoid recursion
return "_l((" + exp + ")," +
"function(" + alias + iterator1 + iterator2 + "){" +
"return " + (genScopedSlot(key, el, state)) +
'})'
}
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'
) {
return (altGenElement || genElement)(el$1, state)
}
var normalizationType = checkSkip
? getNormalizationType(children, state.maybeComponent)
: 0;
var gen = altGenNode || genNode;
return ("[" + (children.map(function (c) { return gen(c, state); }).join(',')) + "]" + (normalizationType ? ("," + normalizationType) : ''))
}
}
// 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)
} 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.attrs.map(function (a) { return ((camelize(a.name)) + ":" + (a.value)); }).join(',')) + "}");
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 res = '';
for (var i = 0; i < props.length; i++) {
var prop = props[i];
res += "\"" + (prop.name) + "\":" + (transformSpecialNewlines(prop.value)) + ",";
}
return res.slice(0, -1)
}
// #3895, #4268
function transformSpecialNewlines (text) {
return text
.replace(/\u2028/g, '\\u2028')
.replace(/\u2029/g, '\\u2029')
}
/* */
var plainStringRE = /^"(?:[^"\\]|\\.)*"$|^'(?:[^'\\]|\\.)*'$/;
// let the model AST transform translate v-model into appropriate
// props bindings
function applyModelTransform (el, state) {
if (el.directives) {
for (var i = 0; i < el.directives.length; i++) {
var dir = el.directives[i];
if (dir.name === 'model') {
state.directives.model(el, dir, state.warn);
break
}
}
}
}
function genAttrSegments (
attrs
) {
return attrs.map(function (ref) {
var name = ref.name;
var value = ref.value;
return genAttrSegment(name, value);
})
}
function genDOMPropSegments (
props,
attrs
) {
var segments = [];
props.forEach(function (ref) {
var name = ref.name;
var value = ref.value;
name = propsToAttrMap[name] || name.toLowerCase();
if (isRenderableAttr(name) &&
!(attrs && attrs.some(function (a) { return a.name === name; }))
) {
segments.push(genAttrSegment(name, value));
}
});
return segments
}
function genAttrSegment (name, value) {
if (plainStringRE.test(value)) {
// force double quote
value = value.replace(/^'|'$/g, '"');
// force enumerated attr to "true"
if (isEnumeratedAttr(name) && value !== "\"false\"") {
value = "\"true\"";
}
return {
type: RAW,
value: isBooleanAttr(name)
? (" " + name + "=\"" + name + "\"")
: value === '""'
? (" " + name)
: (" " + name + "=" + value)
}
} else {
return {
type: EXPRESSION,
value: ("_ssrAttr(" + (JSON.stringify(name)) + "," + value + ")")
}
}
}
function genClassSegments (
staticClass,
classBinding
) {
if (staticClass && !classBinding) {
return [{ type: RAW, value: (" class=" + staticClass) }]
} else {
return [{
type: EXPRESSION,
value: ("_ssrClass(" + (staticClass || 'null') + "," + (classBinding || 'null') + ")")
}]
}
}
function genStyleSegments (
staticStyle,
parsedStaticStyle,
styleBinding,
vShowExpression
) {
if (staticStyle && !styleBinding && !vShowExpression) {
return [{ type: RAW, value: (" style=" + (JSON.stringify(staticStyle))) }]
} else {
return [{
type: EXPRESSION,
value: ("_ssrStyle(" + (parsedStaticStyle || 'null') + "," + (styleBinding || 'null') + ", " + (vShowExpression
? ("{ display: (" + vShowExpression + ") ? '' : 'none' }")
: 'null') + ")")
}]
}
}
/* */
/**
* In SSR, the vdom tree is generated only once and never patched, so
* we can optimize most element / trees into plain string render functions.
* The SSR optimizer walks the AST tree to detect optimizable elements and trees.
*
* The criteria for SSR optimizability is quite a bit looser than static tree
* detection (which is designed for client re-render). In SSR we bail only for
* components/slots/custom directives.
*/
// optimizability constants
var optimizability = {
FALSE: 0, // whole sub tree un-optimizable
FULL: 1, // whole sub tree optimizable
SELF: 2, // self optimizable but has some un-optimizable children
CHILDREN: 3, // self un-optimizable but have fully optimizable children
PARTIAL: 4 // self un-optimizable with some un-optimizable children
};
var isPlatformReservedTag;
function optimize (root, options) {
if (!root) { return }
isPlatformReservedTag = options.isReservedTag || no;
walk(root, true);
}
function walk (node, isRoot) {
if (isUnOptimizableTree(node)) {
node.ssrOptimizability = optimizability.FALSE;
return
}
// root node or nodes with custom directives should always be a VNode
var selfUnoptimizable = isRoot || hasCustomDirective(node);
var check = function (child) {
if (child.ssrOptimizability !== optimizability.FULL) {
node.ssrOptimizability = selfUnoptimizable
? optimizability.PARTIAL
: optimizability.SELF;
}
};
if (selfUnoptimizable) {
node.ssrOptimizability = optimizability.CHILDREN;
}
if (node.type === 1) {
for (var i = 0, l = node.children.length; i < l; i++) {
var child = node.children[i];
walk(child);
check(child);
}
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;
walk(block);
check(block);
}
}
if (node.ssrOptimizability == null ||
(!isRoot && (node.attrsMap['v-html'] || node.attrsMap['v-text']))
) {
node.ssrOptimizability = optimizability.FULL;
} else {
node.children = optimizeSiblings(node);
}
} else {
node.ssrOptimizability = optimizability.FULL;
}
}
function optimizeSiblings (el) {
var children = el.children;
var optimizedChildren = [];
var currentOptimizableGroup = [];
var pushGroup = function () {
if (currentOptimizableGroup.length) {
optimizedChildren.push({
type: 1,
parent: el,
tag: 'template',
attrsList: [],
attrsMap: {},
children: currentOptimizableGroup,
ssrOptimizability: optimizability.FULL
});
}
currentOptimizableGroup = [];
};
for (var i = 0; i < children.length; i++) {
var c = children[i];
if (c.ssrOptimizability === optimizability.FULL) {
currentOptimizableGroup.push(c);
} else {
// wrap fully-optimizable adjacent siblings inside a template tag
// so that they can be optimized into a single ssrNode by codegen
pushGroup();
optimizedChildren.push(c);
}
}
pushGroup();
return optimizedChildren
}
function isUnOptimizableTree (node) {
if (node.type === 2 || node.type === 3) { // text or expression
return false
}
return (
isBuiltInTag(node.tag) || // built-in (slot, component)
!isPlatformReservedTag(node.tag) || // custom component
!!node.component // "is" component
)
}
var isBuiltInDir = makeMap('text,html,show,on,bind,model,pre,cloak,once');
function hasCustomDirective (node) {
return (
node.type === 1 &&
node.directives &&
node.directives.some(function (d) { return !isBuiltInDir(d.name); })
)
}
/* */
// The SSR codegen is essentially extending the default codegen to handle
// SSR-optimizable nodes and turn them into string render fns. In cases where
// a node is not optimizable it simply falls back to the default codegen.
// segment types
var RAW = 0;
var INTERPOLATION = 1;
var EXPRESSION = 2;
function generate (
ast,
options
) {
var state = new CodegenState(options);
var code = ast ? genSSRElement(ast, state) : '_c("div")';
return {
render: ("with(this){return " + code + "}"),
staticRenderFns: state.staticRenderFns
}
}
function genSSRElement (el, state) {
if (el.for && !el.forProcessed) {
return genFor(el, state, genSSRElement)
} else if (el.if && !el.ifProcessed) {
return genIf(el, state, genSSRElement)
} else if (el.tag === 'template' && !el.slotTarget) {
return el.ssrOptimizability === optimizability.FULL
? genChildrenAsStringNode(el, state)
: genSSRChildren(el, state) || 'void 0'
}
switch (el.ssrOptimizability) {
case optimizability.FULL:
// stringify whole tree
return genStringElement(el, state)
case optimizability.SELF:
// stringify self and check children
return genStringElementWithChildren(el, state)
case optimizability.CHILDREN:
// generate self as VNode and stringify children
return genNormalElement(el, state, true)
case optimizability.PARTIAL:
// generate self as VNode and check children
return genNormalElement(el, state, false)
default:
// bail whole tree
return genElement(el, state)
}
}
function genNormalElement (el, state, stringifyChildren) {
var data = el.plain ? undefined : genData$2(el, state);
var children = stringifyChildren
? ("[" + (genChildrenAsStringNode(el, state)) + "]")
: genSSRChildren(el, state, true);
return ("_c('" + (el.tag) + "'" + (data ? ("," + data) : '') + (children ? ("," + children) : '') + ")")
}
function genSSRChildren (el, state, checkSkip) {
return genChildren(el, state, checkSkip, genSSRElement, genSSRNode)
}
function genSSRNode (el, state) {
return el.type === 1
? genSSRElement(el, state)
: genText(el)
}
function genChildrenAsStringNode (el, state) {
return el.children.length
? ("_ssrNode(" + (flattenSegments(childrenToSegments(el, state))) + ")")
: ''
}
function genStringElement (el, state) {
return ("_ssrNode(" + (elementToString(el, state)) + ")")
}
function genStringElementWithChildren (el, state) {
var children = genSSRChildren(el, state, true);
return ("_ssrNode(" + (flattenSegments(elementToOpenTagSegments(el, state))) + ",\"\"" + (children ? ("," + children) : '') + ")")
}
function elementToString (el, state) {
return ("(" + (flattenSegments(elementToSegments(el, state))) + ")")
}
function elementToSegments (el, state) {
// v-for / v-if
if (el.for && !el.forProcessed) {
el.forProcessed = true;
return [{
type: EXPRESSION,
value: genFor(el, state, elementToString, '_ssrList')
}]
} else if (el.if && !el.ifProcessed) {
el.ifProcessed = true;
return [{
type: EXPRESSION,
value: genIf(el, state, elementToString, '""')
}]
} else if (el.tag === 'template') {
return childrenToSegments(el, state)
}
var openSegments = elementToOpenTagSegments(el, state);
var childrenSegments = childrenToSegments(el, state);
var ref = state.options;
var isUnaryTag = ref.isUnaryTag;
var close = (isUnaryTag && isUnaryTag(el.tag))
? []
: [{ type: RAW, value: ("") }];
return openSegments.concat(childrenSegments, close)
}
function elementToOpenTagSegments (el, state) {
applyModelTransform(el, state);
var binding;
var segments = [{ type: RAW, value: ("<" + (el.tag)) }];
// attrs
if (el.attrs) {
segments.push.apply(segments, genAttrSegments(el.attrs));
}
// domProps
if (el.props) {
segments.push.apply(segments, genDOMPropSegments(el.props, el.attrs));
}
// v-bind="object"
if ((binding = el.attrsMap['v-bind'])) {
segments.push({ type: EXPRESSION, value: ("_ssrAttrs(" + binding + ")") });
}
// v-bind.prop="object"
if ((binding = el.attrsMap['v-bind.prop'])) {
segments.push({ type: EXPRESSION, value: ("_ssrDOMProps(" + binding + ")") });
}
// class
if (el.staticClass || el.classBinding) {
segments.push.apply(
segments,
genClassSegments(el.staticClass, el.classBinding)
);
}
// style & v-show
if (el.staticStyle || el.styleBinding || el.attrsMap['v-show']) {
segments.push.apply(
segments,
genStyleSegments(
el.attrsMap.style,
el.staticStyle,
el.styleBinding,
el.attrsMap['v-show']
)
);
}
// _scopedId
if (state.options.scopeId) {
segments.push({ type: RAW, value: (" " + (state.options.scopeId)) });
}
segments.push({ type: RAW, value: ">" });
return segments
}
function childrenToSegments (el, state) {
var binding;
if ((binding = el.attrsMap['v-html'])) {
return [{ type: EXPRESSION, value: binding }]
}
if ((binding = el.attrsMap['v-text'])) {
return [{ type: INTERPOLATION, value: binding }]
}
return el.children
? nodesToSegments(el.children, state)
: []
}
function nodesToSegments (
children,
state
) {
var segments = [];
for (var i = 0; i < children.length; i++) {
var c = children[i];
if (c.type === 1) {
segments.push.apply(segments, elementToSegments(c, state));
} else if (c.type === 2) {
segments.push({ type: INTERPOLATION, value: c.expression });
} else if (c.type === 3) {
segments.push({ type: RAW, value: c.text });
}
}
return segments
}
function flattenSegments (segments) {
var mergedSegments = [];
var textBuffer = '';
var pushBuffer = function () {
if (textBuffer) {
mergedSegments.push(JSON.stringify(textBuffer));
textBuffer = '';
}
};
for (var i = 0; i < segments.length; i++) {
var s = segments[i];
if (s.type === RAW) {
textBuffer += s.value;
} else if (s.type === INTERPOLATION) {
pushBuffer();
mergedSegments.push(("_ssrEscape(" + (s.value) + ")"));
} else if (s.type === EXPRESSION) {
pushBuffer();
mergedSegments.push(("(" + (s.value) + ")"));
}
}
pushBuffer();
return mergedSegments.join('+')
}
/* */
// 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*\\([^\\)]*\\)');
// check valid identifier for v-for
var identRE = /[A-Za-z_$][\w$]*/;
// strip strings in expressions
var stripStringRE = /'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*\$\{|\}(?:[^`\\]|\\.)*`|`(?:[^`\\]|\\.)*`/g;
// detect problematic expressions in a template
function detectErrors (ast) {
var errors = [];
if (ast) {
checkNode(ast, errors);
}
return errors
}
function checkNode (node, errors) {
if (node.type === 1) {
for (var name in node.attrsMap) {
if (dirRE.test(name)) {
var value = node.attrsMap[name];
if (value) {
if (name === 'v-for') {
checkFor(node, ("v-for=\"" + value + "\""), errors);
} else if (onRE.test(name)) {
checkEvent(value, (name + "=\"" + value + "\""), errors);
} else {
checkExpression(value, (name + "=\"" + value + "\""), errors);
}
}
}
}
if (node.children) {
for (var i = 0; i < node.children.length; i++) {
checkNode(node.children[i], errors);
}
}
} else if (node.type === 2) {
checkExpression(node.expression, node.text, errors);
}
}
function checkEvent (exp, text, errors) {
var stipped = exp.replace(stripStringRE, '');
var keywordMatch = stipped.match(unaryOperatorsRE);
if (keywordMatch && stipped.charAt(keywordMatch.index - 1) !== '$') {
errors.push(
"avoid using JavaScript unary operator as property name: " +
"\"" + (keywordMatch[0]) + "\" in expression " + (text.trim())
);
}
checkExpression(exp, text, errors);
}
function checkFor (node, text, errors) {
checkExpression(node.for || '', text, errors);
checkIdentifier(node.alias, 'v-for alias', text, errors);
checkIdentifier(node.iterator1, 'v-for iterator', text, errors);
checkIdentifier(node.iterator2, 'v-for iterator', text, errors);
}
function checkIdentifier (ident, type, text, errors) {
if (typeof ident === 'string' && !identRE.test(ident)) {
errors.push(("invalid " + type + " \"" + ident + "\" in expression: " + (text.trim())));
}
}
function checkExpression (exp, text, errors) {
try {
new Function(("return " + exp));
} catch (e) {
var keywordMatch = exp.replace(stripStringRE, '').match(prohibitedKeywordRE);
if (keywordMatch) {
errors.push(
"avoid using JavaScript keyword as property name: " +
"\"" + (keywordMatch[0]) + "\" in expression " + (text.trim())
);
} else {
errors.push(("invalid expression: " + (text.trim())));
}
}
}
/* */
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 = options || {};
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production') {
// detect possible CSP restriction
try {
new Function('return 1');
} catch (e) {
if (e.toString().match(/unsafe-eval|CSP/)) {
warn(
'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 (process.env.NODE_ENV !== 'production') {
if (compiled.errors && compiled.errors.length) {
warn(
"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) {
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 (process.env.NODE_ENV !== 'production') {
if ((!compiled.errors || !compiled.errors.length) && fnGenErrors.length) {
warn(
"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 = [];
finalOptions.warn = function (msg, tip) {
(tip ? tips : errors).push(msg);
};
if (options) {
// 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),
options.directives
);
}
// copy other options
for (var key in options) {
if (key !== 'modules' && key !== 'directives') {
finalOptions[key] = options[key];
}
}
}
var compiled = baseCompile(template, finalOptions);
if (process.env.NODE_ENV !== 'production') {
errors.push.apply(errors, detectErrors(compiled.ast));
}
compiled.errors = errors;
compiled.tips = tips;
return compiled
}
return {
compile: compile,
compileToFunctions: createCompileToFunctionFn(compile)
}
}
}
/* */
var createCompiler = createCompilerCreator(function baseCompile (
template,
options
) {
var ast = parse(template.trim(), options);
optimize(ast, options);
var code = generate(ast, options);
return {
ast: ast,
render: code.render,
staticRenderFns: code.staticRenderFns
}
});
/* */
var ref = createCompiler(baseOptions);
var compileToFunctions = ref.compileToFunctions;
/* */
// 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
. 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. , , 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, last;
for (i = 0; i < children.length; i++) {
c = children[i];
if (isUndef(c) || typeof c === 'boolean') { continue }
last = res[res.length - 1];
// nested
if (Array.isArray(c)) {
res.push.apply(res, normalizeArrayChildren(c, ((nestedIndex || '') + "_" + i)));
} 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
(last).text += String(c);
} else if (c !== '') {
// convert primitive to vnode
res.push(createTextVNode(c));
}
} else {
if (isTextNode(c) && isTextNode(last)) {
// merge adjacent text nodes
res[res.length - 1] = 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 installSSRHelpers (vm) {
if (vm._ssrNode) { return }
var Ctor = vm.constructor;
while (Ctor.super) {
Ctor = Ctor.super;
}
Object.assign(Ctor.prototype, {
_ssrEscape: escape,
_ssrNode: renderStringNode$1,
_ssrList: renderStringList,
_ssrAttr: renderAttr,
_ssrAttrs: renderAttrs$1,
_ssrDOMProps: renderDOMProps$1,
_ssrClass: renderSSRClass,
_ssrStyle: renderSSRStyle
});
}
var StringNode = function StringNode (
open,
close,
children,
normalizationType
) {
this.isString = true;
this.open = open;
this.close = close;
if (children) {
this.children = normalizationType === 1
? simpleNormalizeChildren(children)
: normalizationType === 2
? normalizeChildren(children)
: children;
} else {
this.children = void 0;
}
};
function renderStringNode$1 (
open,
close,
children,
normalizationType
) {
return new StringNode(open, close, children, normalizationType)
}
function renderStringList (
val,
render
) {
var ret = '';
var i, l, keys, key;
if (Array.isArray(val) || typeof val === 'string') {
for (i = 0, l = val.length; i < l; i++) {
ret += render(val[i], i);
}
} else if (typeof val === 'number') {
for (i = 0; i < val; i++) {
ret += render(i + 1, i);
}
} else if (isObject(val)) {
keys = Object.keys(val);
for (i = 0, l = keys.length; i < l; i++) {
key = keys[i];
ret += render(val[key], key, i);
}
}
return ret
}
function renderAttrs$1 (obj) {
var res = '';
for (var key in obj) {
res += renderAttr(key, obj[key]);
}
return res
}
function renderDOMProps$1 (obj) {
var res = '';
for (var key in obj) {
var attr = propsToAttrMap[key] || key.toLowerCase();
if (isRenderableAttr(attr)) {
res += renderAttr(attr, obj[key]);
}
}
return res
}
function renderSSRClass (
staticClass,
dynamic
) {
var res = renderClass$1(staticClass, dynamic);
return res === '' ? res : (" class=\"" + (cachedEscape(res)) + "\"")
}
function renderSSRStyle (
staticStyle,
dynamic,
extra
) {
var style = {};
if (staticStyle) { extend(style, staticStyle); }
if (dynamic) { extend(style, normalizeStyleBinding(dynamic)); }
if (extra) { extend(style, extra); }
var res = genStyle(style);
return res === '' ? res : (" style=" + (JSON.stringify(cachedEscape(res))))
}
/* not type checking this file because flow doesn't play well with Proxy */
var initProxy;
if (process.env.NODE_ENV !== 'production') {
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 to declare reactive data " +
"properties in the data option.",
target
);
};
var hasProxy =
typeof Proxy !== 'undefined' &&
Proxy.toString().match(/native code/);
if (hasProxy) {
var isBuiltInModifier = makeMap('stop,prevent,self,ctrl,shift,alt,meta');
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) || key.charAt(0) === '_';
if (!has && !isAllowed) {
warnNonPresent(target, key);
}
return has || !isAllowed
}
};
var getHandler = {
get: function get (target, key) {
if (typeof key === 'string' && !(key in target)) {
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 mark;
var measure;
if (process.env.NODE_ENV !== 'production') {
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);
};
}
}
/* */
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) {
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++) {
cloned[i].apply(null, arguments$1);
}
} else {
// return handler return value for single handlers
return fns.apply(null, arguments)
}
}
invoker.fns = fns;
return invoker
}
function updateListeners (
on,
oldOn,
add,
remove$$1,
vm
) {
var name, cur, old, event;
for (name in on) {
cur = on[name];
old = oldOn[name];
event = normalizeEvent(name);
if (isUndef(cur)) {
process.env.NODE_ENV !== 'production' && warn(
"Invalid handler for event \"" + (event.name) + "\": got " + String(cur),
vm
);
} else if (isUndef(old)) {
if (isUndef(cur.fns)) {
cur = on[name] = createFnInvoker(cur);
}
add(event.name, cur, event.once, event.capture, event.passive);
} 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 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);
if (process.env.NODE_ENV !== 'production') {
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
}
/* */
function ensureCtor (comp, base) {
if (comp.__esModule && comp.default) {
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,
context
) {
if (isTrue(factory.error) && isDef(factory.errorComp)) {
return factory.errorComp
}
if (isDef(factory.resolved)) {
return factory.resolved
}
if (isTrue(factory.loading) && isDef(factory.loadingComp)) {
return factory.loadingComp
}
if (isDef(factory.contexts)) {
// already pending
factory.contexts.push(context);
} else {
var contexts = factory.contexts = [context];
var sync = true;
var forceRender = function () {
for (var i = 0, l = contexts.length; i < l; i++) {
contexts[i].$forceUpdate();
}
};
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();
}
});
var reject = once(function (reason) {
process.env.NODE_ENV !== 'production' && warn(
"Failed to resolve async component: " + (String(factory)) +
(reason ? ("\nReason: " + reason) : '')
);
if (isDef(factory.errorComp)) {
factory.error = true;
forceRender();
}
});
var res = factory(resolve, reject);
if (isObject(res)) {
if (typeof res.then === 'function') {
// () => Promise
if (isUndef(factory.resolved)) {
res.then(resolve, reject);
}
} else if (isDef(res.component) && typeof res.component.then === 'function') {
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 {
setTimeout(function () {
if (isUndef(factory.resolved) && isUndef(factory.error)) {
factory.loading = true;
forceRender();
}
}, res.delay || 200);
}
}
if (isDef(res.timeout)) {
setTimeout(function () {
if (isUndef(factory.resolved)) {
reject(
process.env.NODE_ENV !== 'production'
? ("timeout (" + (res.timeout) + "ms)")
: null
);
}
}, res.timeout);
}
}
}
sync = false;
// return in case resolved synchronously
return factory.loading
? factory.loadingComp
: factory.resolved
}
}
/* */
/* */
/* */
var target;
function add (event, fn, once$$1) {
if (once$$1) {
target.$once(event, fn);
} else {
target.$on(event, fn);
}
}
function remove$1 (event, fn) {
target.$off(event, fn);
}
function updateComponentListeners (
vm,
listeners,
oldListeners
) {
target = vm;
updateListeners(listeners, oldListeners || {}, add, remove$1, vm);
}
/* */
/**
* Runtime helper for resolving raw children VNodes into a slot object.
*/
function resolveSlots (
children,
context
) {
var slots = {};
if (!children) {
return slots
}
var defaultSlot = [];
for (var i = 0, l = children.length; i < l; i++) {
var child = children[i];
// named slots should only be respected if the vnode was rendered in the
// same context.
if ((child.context === context || child.functionalContext === context) &&
child.data && child.data.slot != null
) {
var name = child.data.slot;
var slot = (slots[name] || (slots[name] = []));
if (child.tag === 'template') {
slot.push.apply(slot, child.children);
} else {
slot.push(child);
}
} else {
defaultSlot.push(child);
}
}
// ignore whitespace
if (!defaultSlot.every(isWhitespace)) {
slots.default = defaultSlot;
}
return slots
}
function isWhitespace (node) {
return node.isComment || node.text === ' '
}
/* */
var activeInstance = null;
var isUpdatingChildComponent = false;
function updateChildComponent (
vm,
propsData,
listeners,
parentVnode,
renderChildren
) {
if (process.env.NODE_ENV !== 'production') {
isUpdatingChildComponent = true;
}
// determine whether component has slot children
// we need to do this before overwriting $options._renderChildren
var hasChildren = !!(
renderChildren || // has new static slots
vm.$options._renderChildren || // has old static slots
parentVnode.data.scopedSlots || // has new scoped slots
vm.$scopedSlots !== emptyObject // has old scoped slots
);
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 $listensers hash
// these are also reactive so they may trigger child update if the child
// used them during render
vm.$attrs = parentVnode.data && parentVnode.data.attrs;
vm.$listeners = listeners;
// update props
if (propsData && vm.$options.props) {
observerState.shouldConvert = false;
var props = vm._props;
var propKeys = vm.$options._propKeys || [];
for (var i = 0; i < propKeys.length; i++) {
var key = propKeys[i];
props[key] = validateProp(key, vm.$options.props, propsData, vm);
}
observerState.shouldConvert = true;
// keep a copy of raw propsData
vm.$options.propsData = propsData;
}
// update listeners
if (listeners) {
var oldListeners = vm.$options._parentListeners;
vm.$options._parentListeners = listeners;
updateComponentListeners(vm, listeners, oldListeners);
}
// resolve slots + force update if has children
if (hasChildren) {
vm.$slots = resolveSlots(renderChildren, parentVnode.context);
vm.$forceUpdate();
}
if (process.env.NODE_ENV !== 'production') {
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) {
var handlers = vm.$options[hook];
if (handlers) {
for (var i = 0, j = handlers.length; i < j; i++) {
try {
handlers[i].call(vm);
} catch (e) {
handleError(e, vm, (hook + " hook"));
}
}
}
if (vm._hasHookEvent) {
vm.$emit('hook:' + hook);
}
}
/* */
var MAX_UPDATE_COUNT = 100;
var queue = [];
var activatedChildren = [];
var has = {};
var circular = {};
var waiting = false;
var flushing = false;
var index$1 = 0;
/**
* Reset the scheduler's state.
*/
function resetSchedulerState () {
index$1 = queue.length = activatedChildren.length = 0;
has = {};
if (process.env.NODE_ENV !== 'production') {
circular = {};
}
waiting = flushing = false;
}
/**
* Flush both queues and run the watchers.
*/
function flushSchedulerQueue () {
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$1 = 0; index$1 < queue.length; index$1++) {
watcher = queue[index$1];
id = watcher.id;
has[id] = null;
watcher.run();
// in dev build, check and stop circular updates.
if (process.env.NODE_ENV !== 'production' && 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) {
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$1 && queue[i].id > watcher.id) {
i--;
}
queue.splice(i + 1, 0, watcher);
}
// queue the flush
if (!waiting) {
waiting = true;
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
) {
this.vm = vm;
vm._watchers.push(this);
// options
if (options) {
this.deep = !!options.deep;
this.user = !!options.user;
this.lazy = !!options.lazy;
this.sync = !!options.sync;
} 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 = process.env.NODE_ENV !== 'production'
? expOrFn.toString()
: '';
// parse expression for getter
if (typeof expOrFn === 'function') {
this.getter = expOrFn;
} else {
this.getter = parsePath(expOrFn);
if (!this.getter) {
this.getter = function () {};
process.env.NODE_ENV !== 'production' && 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 this$1 = this;
var i = this.deps.length;
while (i--) {
var dep = this$1.deps[i];
if (!this$1.newDepIds.has(dep.id)) {
dep.removeSub(this$1);
}
}
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 this$1 = this;
var i = this.deps.length;
while (i--) {
this$1.deps[i].depend();
}
};
/**
* Remove self from all dependencies' subscriber list.
*/
Watcher.prototype.teardown = function teardown () {
var this$1 = this;
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$1.deps[i].removeSub(this$1);
}
this.active = false;
}
};
/**
* Recursively traverse an object to evoke all converted
* getters, so that every nested property inside the object
* is collected as a "deep" dependency.
*/
var seenObjects = new _Set();
function traverse (val) {
seenObjects.clear();
_traverse(val, seenObjects);
}
function _traverse (val, seen) {
var i, keys;
var isA = Array.isArray(val);
if ((!isA && !isObject(val)) || !Object.isExtensible(val)) {
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 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 getData (data, vm) {
try {
return data.call(vm)
} catch (e) {
handleError(e, vm, "data()");
return {}
}
}
/* */
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__)) {
process.env.NODE_ENV !== 'production' && 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 (process.env.NODE_ENV !== 'production' &&
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 = config.getTagNamespace(tag);
if (config.isReservedTag(tag)) {
// platform built-in elements
vnode = new VNode(
config.parsePlatformTagName(tag), data, children,
undefined, undefined, context
);
} else if (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 (isDef(vnode)) {
if (ns) { applyNS(vnode, ns); }
return vnode
} else {
return createEmptyVNode()
}
}
function applyNS (vnode, ns) {
vnode.ns = ns;
if (vnode.tag === 'foreignObject') {
// use default namespace inside foreignObject
return
}
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)) {
applyNS(child, ns);
}
}
}
}
/* */
/**
* Runtime helper for rendering v-for lists.
*/
/* */
/**
* Runtime helper for rendering
*/
/* */
/**
* Runtime helper for resolving filters
*/
/* */
/**
* Runtime helper for checking keyCodes from config.
*/
/* */
/**
* Runtime helper for merging v-bind="object" into a VNode's data.
*/
/* */
/**
* Runtime helper for rendering static trees.
*/
/**
* Runtime helper for v-once.
* Effectively it means marking the node as static with a unique key.
*/
/* */
/* */
/* */
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];
var provideKey = inject[key];
var source = vm;
while (source) {
if (source._provided && provideKey in source._provided) {
result[key] = source._provided[provideKey];
break
}
source = source.$parent;
}
if (process.env.NODE_ENV !== 'production' && !source) {
warn(("Injection \"" + key + "\" not found"), vm);
}
}
return result
}
}
/* */
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 extended = Ctor.extendOptions;
var sealed = Ctor.sealedOptions;
for (var key in latest) {
if (latest[key] !== sealed[key]) {
if (!modified) { modified = {}; }
modified[key] = dedupe(latest[key], extended[key], sealed[key]);
}
}
return modified
}
function dedupe (latest, extended, sealed) {
// compare latest and sealed to ensure lifecycle hooks won't be duplicated
// between merges
if (Array.isArray(latest)) {
var res = [];
sealed = Array.isArray(sealed) ? sealed : [sealed];
extended = Array.isArray(extended) ? extended : [extended];
for (var i = 0; i < latest.length; i++) {
// push original options and not sealed options to exclude duplicated options
if (extended.indexOf(latest[i]) >= 0 || sealed.indexOf(latest[i]) < 0) {
res.push(latest[i]);
}
}
return res
} else {
return latest
}
}
/* */
function createFunctionalComponent (
Ctor,
propsData,
data,
context,
children
) {
var props = {};
var propOptions = Ctor.options.props;
if (isDef(propOptions)) {
for (var key in propOptions) {
props[key] = validateProp(key, propOptions, propsData || {});
}
} else {
if (isDef(data.attrs)) { mergeProps(props, data.attrs); }
if (isDef(data.props)) { mergeProps(props, data.props); }
}
// ensure the createElement function in functional components
// gets a unique context - this is necessary for correct named slot check
var _context = Object.create(context);
var h = function (a, b, c, d) { return createElement(_context, a, b, c, d, true); };
var vnode = Ctor.options.render.call(null, h, {
data: data,
props: props,
children: children,
parent: context,
listeners: data.on || {},
injections: resolveInject(Ctor.options.inject, context),
slots: function () { return resolveSlots(children, context); }
});
if (vnode instanceof VNode) {
vnode.functionalContext = context;
vnode.functionalOptions = Ctor.options;
if (data.slot) {
(vnode.data || (vnode.data = {})).slot = data.slot;
}
}
return vnode
}
function mergeProps (to, from) {
for (var key in from) {
to[camelize(key)] = from[key];
}
}
/* */
// hooks to be invoked on component VNodes during patch
var componentVNodeHooks = {
init: function init (
vnode,
hydrating,
parentElm,
refElm
) {
if (!vnode.componentInstance || vnode.componentInstance._isDestroyed) {
var child = vnode.componentInstance = createComponentInstanceForVnode(
vnode,
activeInstance,
parentElm,
refElm
);
child.$mount(hydrating ? vnode.elm : undefined, hydrating);
} else if (vnode.data.keepAlive) {
// kept-alive components, treat as a patch
var mountedNode = vnode; // work around flow
componentVNodeHooks.prepatch(mountedNode, mountedNode);
}
},
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') {
if (process.env.NODE_ENV !== 'production') {
warn(("Invalid Component definition: " + (String(Ctor))), context);
}
return
}
// async component
var asyncFactory;
if (isUndef(Ctor.cid)) {
asyncFactory = Ctor;
Ctor = resolveAsyncComponent(asyncFactory, baseCtor, context);
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;
}
}
// merge component management hooks onto the placeholder node
mergeHooks(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
parentElm,
refElm
) {
var vnodeComponentOptions = vnode.componentOptions;
var options = {
_isComponent: true,
parent: parent,
propsData: vnodeComponentOptions.propsData,
_componentTag: vnodeComponentOptions.tag,
_parentVnode: vnode,
_parentListeners: vnodeComponentOptions.listeners,
_renderChildren: vnodeComponentOptions.children,
_parentElm: parentElm || null,
_refElm: refElm || null
};
// check inline-template render functions
var inlineTemplate = vnode.data.inlineTemplate;
if (isDef(inlineTemplate)) {
options.render = inlineTemplate.render;
options.staticRenderFns = inlineTemplate.staticRenderFns;
}
return new vnodeComponentOptions.Ctor(options)
}
function mergeHooks (data) {
if (!data.hook) {
data.hook = {};
}
for (var i = 0; i < hooksToMerge.length; i++) {
var key = hooksToMerge[i];
var fromParent = data.hook[key];
var ours = componentVNodeHooks[key];
data.hook[key] = fromParent ? mergeHook$1(ours, fromParent) : ours;
}
}
function mergeHook$1 (one, two) {
return function (a, b, c, d) {
one(a, b, c, d);
two(a, b, c, d);
}
}
// 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.props || (data.props = {}))[prop] = data.model.value;
var on = data.on || (data.on = {});
if (isDef(on[event])) {
on[event] = [data.model.callback].concat(on[event]);
} else {
on[event] = data.model.callback;
}
}
/* */
var warned = Object.create(null);
var warnOnce = function (msg) {
if (!warned[msg]) {
warned[msg] = true;
console.warn(("\n\u001b[31m" + msg + "\u001b[39m\n"));
}
};
var normalizeRender = function (vm) {
var ref = vm.$options;
var render = ref.render;
var template = ref.template;
var _scopeId = ref._scopeId;
if (isUndef(render)) {
if (template) {
Object.assign(vm.$options, compileToFunctions(template, {
scopeId: _scopeId
}));
} else {
throw new Error(
("render function or template not defined in component: " + (vm.$options.name || vm.$options._componentTag || 'anonymous'))
)
}
}
};
function renderNode (node, isRoot, context) {
if (node.isString) {
renderStringNode(node, context);
} else if (isDef(node.componentOptions)) {
renderComponent(node, isRoot, context);
} else if (isDef(node.tag)) {
renderElement(node, isRoot, context);
} else if (isTrue(node.isComment)) {
if (isDef(node.asyncFactory)) {
// async component
renderAsyncComponent(node, isRoot, context);
} else {
context.write((""), context.next);
}
} else {
context.write(
node.raw ? node.text : escape(String(node.text)),
context.next
);
}
}
function registerComponentForCache (options, write) {
// exposed by vue-loader, need to call this if cache hit because
// component lifecycle hooks will not be called.
var register = options._ssrRegister;
if (write.caching && isDef(register)) {
write.componentBuffer[write.componentBuffer.length - 1].add(register);
}
return register
}
function renderComponent (node, isRoot, context) {
var write = context.write;
var next = context.next;
var userContext = context.userContext;
// check cache hit
var Ctor = node.componentOptions.Ctor;
var getKey = Ctor.options.serverCacheKey;
var name = Ctor.options.name;
var cache = context.cache;
var registerComponent = registerComponentForCache(Ctor.options, write);
if (isDef(getKey) && isDef(cache) && isDef(name)) {
var key = name + '::' + getKey(node.componentOptions.propsData);
var has = context.has;
var get = context.get;
if (isDef(has)) {
has(key, function (hit) {
if (hit === true && isDef(get)) {
get(key, function (res) {
if (isDef(registerComponent)) {
registerComponent(userContext);
}
res.components.forEach(function (register) { return register(userContext); });
write(res.html, next);
});
} else {
renderComponentWithCache(node, isRoot, key, context);
}
});
} else if (isDef(get)) {
get(key, function (res) {
if (isDef(res)) {
if (isDef(registerComponent)) {
registerComponent(userContext);
}
res.components.forEach(function (register) { return register(userContext); });
write(res.html, next);
} else {
renderComponentWithCache(node, isRoot, key, context);
}
});
}
} else {
if (isDef(getKey) && isUndef(cache)) {
warnOnce(
"[vue-server-renderer] Component " + (Ctor.options.name || '(anonymous)') + " implemented serverCacheKey, " +
'but no cache was provided to the renderer.'
);
}
if (isDef(getKey) && isUndef(name)) {
warnOnce(
"[vue-server-renderer] Components that implement \"serverCacheKey\" " +
"must also define a unique \"name\" option."
);
}
renderComponentInner(node, isRoot, context);
}
}
function renderComponentWithCache (node, isRoot, key, context) {
var write = context.write;
write.caching = true;
var buffer = write.cacheBuffer;
var bufferIndex = buffer.push('') - 1;
var componentBuffer = write.componentBuffer;
componentBuffer.push(new Set());
context.renderStates.push({
type: 'ComponentWithCache',
key: key,
buffer: buffer,
bufferIndex: bufferIndex,
componentBuffer: componentBuffer
});
renderComponentInner(node, isRoot, context);
}
function renderComponentInner (node, isRoot, context) {
var prevActive = context.activeInstance;
// expose userContext on vnode
node.ssrContext = context.userContext;
var child = context.activeInstance = createComponentInstanceForVnode(
node,
context.activeInstance
);
normalizeRender(child);
var childNode = child._render();
childNode.parent = node;
context.renderStates.push({
type: 'Component',
prevActive: prevActive
});
renderNode(childNode, isRoot, context);
}
function renderAsyncComponent (node, isRoot, context) {
var factory = node.asyncFactory;
var resolve = function (comp) {
if (comp.__esModule && comp.default) {
comp = comp.default;
}
var ref = node.asyncMeta;
var data = ref.data;
var children = ref.children;
var tag = ref.tag;
var nodeContext = node.asyncMeta.context;
var resolvedNode = createComponent(
comp,
data,
nodeContext,
children,
tag
);
if (resolvedNode) {
renderComponent(resolvedNode, isRoot, context);
} else {
reject();
}
};
var reject = function (err) {
console.error("[vue-server-renderer] error when rendering async component:\n");
if (err) { console.error(err.stack); }
context.write((""), context.next);
};
if (factory.resolved) {
resolve(factory.resolved);
return
}
var res;
try {
res = factory(resolve, reject);
} catch (e) {
reject(e);
}
if (res) {
if (typeof res.then === 'function') {
res.then(resolve, reject).catch(reject);
} else {
// new syntax in 2.3
var comp = res.component;
if (comp && typeof comp.then === 'function') {
comp.then(resolve, reject).catch(reject);
}
}
}
}
function renderStringNode (el, context) {
var write = context.write;
var next = context.next;
if (isUndef(el.children) || el.children.length === 0) {
write(el.open + (el.close || ''), next);
} else {
var children = el.children;
context.renderStates.push({
type: 'Element',
rendered: 0,
total: children.length,
endTag: el.close, children: children
});
write(el.open, next);
}
}
function renderElement (el, isRoot, context) {
var write = context.write;
var next = context.next;
if (isTrue(isRoot)) {
if (!el.data) { el.data = {}; }
if (!el.data.attrs) { el.data.attrs = {}; }
el.data.attrs[SSR_ATTR] = 'true';
}
if (el.functionalOptions) {
registerComponentForCache(el.functionalOptions, write);
}
var startTag = renderStartingTag(el, context);
var endTag = "";
if (context.isUnaryTag(el.tag)) {
write(startTag, next);
} else if (isUndef(el.children) || el.children.length === 0) {
write(startTag + endTag, next);
} else {
var children = el.children;
context.renderStates.push({
type: 'Element',
rendered: 0,
total: children.length,
endTag: endTag, children: children
});
write(startTag, next);
}
}
function hasAncestorData (node) {
var parentNode = node.parent;
return isDef(parentNode) && (isDef(parentNode.data) || hasAncestorData(parentNode))
}
function getVShowDirectiveInfo (node) {
var dir;
var tmp;
while (isDef(node)) {
if (node.data && node.data.directives) {
tmp = node.data.directives.find(function (dir) { return dir.name === 'show'; });
if (tmp) {
dir = tmp;
}
}
node = node.parent;
}
return dir
}
function renderStartingTag (node, context) {
var markup = "<" + (node.tag);
var directives = context.directives;
var modules = context.modules;
// construct synthetic data for module processing
// because modules like style also produce code by parent VNode data
if (isUndef(node.data) && hasAncestorData(node)) {
node.data = {};
}
if (isDef(node.data)) {
// check directives
var dirs = node.data.directives;
if (dirs) {
for (var i = 0; i < dirs.length; i++) {
var name = dirs[i].name;
var dirRenderer = directives[name];
if (dirRenderer && name !== 'show') {
// directives mutate the node's data
// which then gets rendered by modules
dirRenderer(node, dirs[i]);
}
}
}
// v-show directive needs to be merged from parent to child
var vshowDirectiveInfo = getVShowDirectiveInfo(node);
if (vshowDirectiveInfo) {
directives.show(node, vshowDirectiveInfo);
}
// apply other modules
for (var i$1 = 0; i$1 < modules.length; i$1++) {
var res = modules[i$1](node);
if (res) {
markup += res;
}
}
}
// attach scoped CSS ID
var scopeId;
var activeInstance = context.activeInstance;
if (isDef(activeInstance) &&
activeInstance !== node.context &&
isDef(scopeId = activeInstance.$options._scopeId)
) {
markup += " " + ((scopeId));
}
while (isDef(node)) {
if (isDef(scopeId = node.context.$options._scopeId)) {
markup += " " + scopeId;
}
node = node.parent;
}
return markup + '>'
}
function createRenderFunction (
modules,
directives,
isUnaryTag,
cache
) {
return function render (
component,
write,
userContext,
done
) {
warned = Object.create(null);
var context = new RenderContext({
activeInstance: component,
userContext: userContext,
write: write, done: done, renderNode: renderNode,
isUnaryTag: isUnaryTag, modules: modules, directives: directives,
cache: cache
});
installSSRHelpers(component);
normalizeRender(component);
renderNode(component._render(), true, context);
}
}
/* */
var isJS = function (file) { return /\.js(\?[^.]+)?$/.test(file); };
var isCSS = function (file) { return /\.css(\?[^.]+)?$/.test(file); };
/* */
var Transform = require('stream').Transform;
var TemplateStream = (function (Transform) {
function TemplateStream (
renderer,
template,
context
) {
Transform.call(this);
this.started = false;
this.renderer = renderer;
this.template = template;
this.context = context || {};
this.inject = renderer.inject;
}
if ( Transform ) TemplateStream.__proto__ = Transform;
TemplateStream.prototype = Object.create( Transform && Transform.prototype );
TemplateStream.prototype.constructor = TemplateStream;
TemplateStream.prototype._transform = function _transform (data, encoding, done) {
if (!this.started) {
this.emit('beforeStart');
this.start();
}
this.push(data);
done();
};
TemplateStream.prototype.start = function start () {
this.started = true;
this.push(this.template.head(this.context));
if (this.inject) {
// inline server-rendered head meta information
if (this.context.head) {
this.push(this.context.head);
}
// inline preload/prefetch directives for initial/async chunks
var links = this.renderer.renderResourceHints(this.context);
if (links) {
this.push(links);
}
// CSS files and inline server-rendered CSS collected by vue-style-loader
var styles = this.renderer.renderStyles(this.context);
if (styles) {
this.push(styles);
}
}
this.push(this.template.neck(this.context));
};
TemplateStream.prototype._flush = function _flush (done) {
this.emit('beforeEnd');
if (this.inject) {
// inline initial store state
var state = this.renderer.renderState(this.context);
if (state) {
this.push(state);
}
// embed scripts needed
var scripts = this.renderer.renderScripts(this.context);
if (scripts) {
this.push(scripts);
}
}
this.push(this.template.tail(this.context));
done();
};
return TemplateStream;
}(Transform));
/* */
var compile$1 = require('lodash.template');
var compileOptions = {
escape: /{{([^{][\s\S]+?[^}])}}/g,
interpolate: /{{{([\s\S]+?)}}}/g
};
function parseTemplate (
template,
contentPlaceholder
) {
if ( contentPlaceholder === void 0 ) contentPlaceholder = '';
if (typeof template === 'object') {
return template
}
var i = template.indexOf('');
var j = template.indexOf(contentPlaceholder);
if (j < 0) {
throw new Error("Content placeholder not found in template.")
}
if (i < 0) {
i = template.indexOf('');
if (i < 0) {
i = j;
}
}
return {
head: compile$1(template.slice(0, i), compileOptions),
neck: compile$1(template.slice(i, j), compileOptions),
tail: compile$1(template.slice(j + contentPlaceholder.length), compileOptions)
}
}
/* */
/**
* Creates a mapper that maps components used during a server-side render
* to async chunk files in the client-side build, so that we can inline them
* directly in the rendered HTML to avoid waterfall requests.
*/
function createMapper (
clientManifest
) {
var map = createMap(clientManifest);
// map server-side moduleIds to client-side files
return function mapper (moduleIds) {
var res = new Set();
for (var i = 0; i < moduleIds.length; i++) {
var mapped = map.get(moduleIds[i]);
if (mapped) {
for (var j = 0; j < mapped.length; j++) {
res.add(mapped[j]);
}
}
}
return Array.from(res)
}
}
function createMap (clientManifest) {
var map = new Map();
Object.keys(clientManifest.modules).forEach(function (id) {
map.set(id, mapIdToFile(id, clientManifest));
});
return map
}
function mapIdToFile (id, clientManifest) {
var files = [];
var fileIndices = clientManifest.modules[id];
if (fileIndices) {
fileIndices.forEach(function (index) {
var file = clientManifest.all[index];
// only include async files or non-js assets
if (clientManifest.async.indexOf(file) > -1 || !(/\.js($|\?)/.test(file))) {
files.push(file);
}
});
}
return files
}
/* */
var path = require('path');
var serialize = require('serialize-javascript');
var TemplateRenderer = function TemplateRenderer (options) {
this.options = options;
this.inject = options.inject !== false;
// if no template option is provided, the renderer is created
// as a utility object for rendering assets like preload links and scripts.
this.parsedTemplate = options.template
? parseTemplate(options.template)
: null;
// extra functionality with client manifest
if (options.clientManifest) {
var clientManifest = this.clientManifest = options.clientManifest;
this.publicPath = clientManifest.publicPath.replace(/\/$/, '');
// preload/prefetch drectives
this.preloadFiles = clientManifest.initial;
this.prefetchFiles = clientManifest.async;
// initial async chunk mapping
this.mapFiles = createMapper(clientManifest);
}
};
TemplateRenderer.prototype.bindRenderFns = function bindRenderFns (context) {
var renderer = this;['ResourceHints', 'State', 'Scripts', 'Styles'].forEach(function (type) {
context[("render" + type)] = renderer[("render" + type)].bind(renderer, context);
});
// also expose getPreloadFiles, useful for HTTP/2 push
context.getPreloadFiles = renderer.getPreloadFiles.bind(renderer, context);
};
// render synchronously given rendered app content and render context
TemplateRenderer.prototype.renderSync = function renderSync (content, context) {
var template = this.parsedTemplate;
if (!template) {
throw new Error('renderSync cannot be called without a template.')
}
context = context || {};
if (this.inject) {
return (
template.head(context) +
(context.head || '') +
this.renderResourceHints(context) +
this.renderStyles(context) +
template.neck(context) +
content +
this.renderState(context) +
this.renderScripts(context) +
template.tail(context)
)
} else {
return (
template.head(context) +
template.neck(context) +
content +
template.tail(context)
)
}
};
TemplateRenderer.prototype.renderStyles = function renderStyles (context) {
var this$1 = this;
var cssFiles = this.clientManifest
? this.clientManifest.all.filter(isCSS)
: [];
return (
// render links for css files
(cssFiles.length
? cssFiles.map(function (file) { return (" "); }).join('')
: '') +
// context.styles is a getter exposed by vue-style-loader which contains
// the inline component styles collected during SSR
(context.styles || '')
)
};
TemplateRenderer.prototype.renderResourceHints = function renderResourceHints (context) {
return this.renderPreloadLinks(context) + this.renderPrefetchLinks(context)
};
TemplateRenderer.prototype.getPreloadFiles = function getPreloadFiles (context) {
var usedAsyncFiles = this.getUsedAsyncFiles(context);
if (this.preloadFiles || usedAsyncFiles) {
return (this.preloadFiles || []).concat(usedAsyncFiles || []).map(function (file) {
var withoutQuery = file.replace(/\?.*/, '');
var extension = path.extname(withoutQuery).slice(1);
return {
file: file,
extension: extension,
fileWithoutQuery: withoutQuery,
asType: getPreloadType(extension)
}
})
} else {
return []
}
};
TemplateRenderer.prototype.renderPreloadLinks = function renderPreloadLinks (context) {
var this$1 = this;
var files = this.getPreloadFiles(context);
if (files.length) {
return files.map(function (ref) {
var file = ref.file;
var extension = ref.extension;
var fileWithoutQuery = ref.fileWithoutQuery;
var asType = ref.asType;
var extra = '';
var shouldPreload = this$1.options.shouldPreload;
// by default, we only preload scripts or css
if (!shouldPreload && asType !== 'script' && asType !== 'style') {
return ''
}
// user wants to explicitly control what to preload
if (shouldPreload && !shouldPreload(fileWithoutQuery, asType)) {
return ''
}
if (asType === 'font') {
extra = " type=\"font/" + extension + "\" crossorigin";
}
return (" ")
}).join('')
} else {
return ''
}
};
TemplateRenderer.prototype.renderPrefetchLinks = function renderPrefetchLinks (context) {
var this$1 = this;
if (this.prefetchFiles) {
var usedAsyncFiles = this.getUsedAsyncFiles(context);
var alreadyRendered = function (file) {
return usedAsyncFiles && usedAsyncFiles.some(function (f) { return f === file; })
};
return this.prefetchFiles.map(function (file) {
if (!alreadyRendered(file)) {
return (" ")
} else {
return ''
}
}).join('')
} else {
return ''
}
};
TemplateRenderer.prototype.renderState = function renderState (context, options) {
var ref = options || {};
var contextKey = ref.contextKey; if ( contextKey === void 0 ) contextKey = 'state';
var windowKey = ref.windowKey; if ( windowKey === void 0 ) windowKey = '__INITIAL_STATE__';
return context[contextKey]
? ("")
: ''
};
TemplateRenderer.prototype.renderScripts = function renderScripts (context) {
var this$1 = this;
if (this.clientManifest) {
var initial = this.clientManifest.initial;
var async = this.getUsedAsyncFiles(context);
var needed = [initial[0]].concat(async || [], initial.slice(1));
return needed.filter(isJS).map(function (file) {
return ("")
}).join('')
} else {
return ''
}
};
TemplateRenderer.prototype.getUsedAsyncFiles = function getUsedAsyncFiles (context) {
if (!context._mappedFiles && context._registeredComponents && this.mapFiles) {
context._mappedFiles = this.mapFiles(Array.from(context._registeredComponents));
}
return context._mappedFiles
};
// create a transform stream
TemplateRenderer.prototype.createStream = function createStream (context) {
if (!this.parsedTemplate) {
throw new Error('createStream cannot be called without a template.')
}
return new TemplateStream(this, this.parsedTemplate, context || {})
};
function getPreloadType (ext) {
if (ext === 'js') {
return 'script'
} else if (ext === 'css') {
return 'style'
} else if (/jpe?g|png|svg|gif|webp|ico/.test(ext)) {
return 'image'
} else if (/woff2?|ttf|otf|eot/.test(ext)) {
return 'font'
} else {
// not exhausting all possbilities here, but above covers common cases
return ''
}
}
/* */
function createRenderer$1 (ref) {
if ( ref === void 0 ) ref = {};
var modules = ref.modules; if ( modules === void 0 ) modules = [];
var directives = ref.directives; if ( directives === void 0 ) directives = {};
var isUnaryTag = ref.isUnaryTag; if ( isUnaryTag === void 0 ) isUnaryTag = (function () { return false; });
var template = ref.template;
var inject = ref.inject;
var cache = ref.cache;
var shouldPreload = ref.shouldPreload;
var clientManifest = ref.clientManifest;
var render = createRenderFunction(modules, directives, isUnaryTag, cache);
var templateRenderer = new TemplateRenderer({
template: template,
inject: inject,
shouldPreload: shouldPreload,
clientManifest: clientManifest
});
return {
renderToString: function renderToString (
component,
context,
done
) {
if (typeof context === 'function') {
done = context;
context = {};
}
if (context) {
templateRenderer.bindRenderFns(context);
}
var result = '';
var write = createWriteFunction(function (text) {
result += text;
return false
}, done);
try {
render(component, write, context, function () {
if (template) {
result = templateRenderer.renderSync(result, context);
}
done(null, result);
});
} catch (e) {
done(e);
}
},
renderToStream: function renderToStream (
component,
context
) {
if (context) {
templateRenderer.bindRenderFns(context);
}
var renderStream = new RenderStream(function (write, done) {
render(component, write, context, done);
});
if (!template) {
return renderStream
} else {
var templateStream = templateRenderer.createStream(context);
renderStream.on('error', function (err) {
templateStream.emit('error', err);
});
renderStream.pipe(templateStream);
return templateStream
}
}
}
}
var vm = require('vm');
var path$2 = require('path');
var resolve = require('resolve');
var NativeModule = require('module');
function createSandbox (context) {
var sandbox = {
Buffer: Buffer,
console: console,
process: process,
setTimeout: setTimeout,
setInterval: setInterval,
setImmediate: setImmediate,
clearTimeout: clearTimeout,
clearInterval: clearInterval,
clearImmediate: clearImmediate,
__VUE_SSR_CONTEXT__: context
};
sandbox.global = sandbox;
return sandbox
}
function compileModule (files, basedir, runInNewContext) {
var compiledScripts = {};
var resolvedModules = {};
function getCompiledScript (filename) {
if (compiledScripts[filename]) {
return compiledScripts[filename]
}
var code = files[filename];
var wrapper = NativeModule.wrap(code);
var script = new vm.Script(wrapper, {
filename: filename,
displayErrors: true
});
compiledScripts[filename] = script;
return script
}
function evaluateModule (filename, sandbox, evaluatedFiles) {
if ( evaluatedFiles === void 0 ) evaluatedFiles = {};
if (evaluatedFiles[filename]) {
return evaluatedFiles[filename]
}
var script = getCompiledScript(filename);
var compiledWrapper = runInNewContext === false
? script.runInThisContext()
: script.runInNewContext(sandbox);
var m = { exports: {}};
var r = function (file) {
file = path$2.join('.', file);
if (files[file]) {
return evaluateModule(file, sandbox, evaluatedFiles)
} else if (basedir) {
return require(
resolvedModules[file] ||
(resolvedModules[file] = resolve.sync(file, { basedir: basedir }))
)
} else {
return require(file)
}
};
compiledWrapper.call(m.exports, m.exports, r, m);
var res = Object.prototype.hasOwnProperty.call(m.exports, 'default')
? m.exports.default
: m.exports;
evaluatedFiles[filename] = res;
return res
}
return evaluateModule
}
function deepClone (val) {
if (isPlainObject(val)) {
var res = {};
for (var key in val) {
res[key] = deepClone(val[key]);
}
return res
} else if (Array.isArray(val)) {
return val.slice()
} else {
return val
}
}
function createBundleRunner (entry, files, basedir, runInNewContext) {
var evaluate = compileModule(files, basedir, runInNewContext);
if (runInNewContext !== false && runInNewContext !== 'once') {
// new context mode: creates a fresh context and re-evaluate the bundle
// on each render. Ensures entire application state is fresh for each
// render, but incurs extra evaluation cost.
return function (userContext) {
if ( userContext === void 0 ) userContext = {};
return new Promise(function (resolve) {
userContext._registeredComponents = new Set();
var res = evaluate(entry, createSandbox(userContext));
resolve(typeof res === 'function' ? res(userContext) : res);
});
}
} else {
// direct mode: instead of re-evaluating the whole bundle on
// each render, it simply calls the exported function. This avoids the
// module evaluation costs but requires the source code to be structured
// slightly differently.
var runner; // lazy creation so that errors can be caught by user
var initialContext;
return function (userContext) {
if ( userContext === void 0 ) userContext = {};
return new Promise(function (resolve) {
if (!runner) {
var sandbox = runInNewContext === 'once'
? createSandbox()
: global;
// the initial context is only used for collecting possible non-component
// styles injected by vue-style-loader.
initialContext = sandbox.__VUE_SSR_CONTEXT__ = {};
runner = evaluate(entry, sandbox);
// On subsequent renders, __VUE_SSR_CONTEXT__ will not be available
// to prevent cross-request pollution.
delete sandbox.__VUE_SSR_CONTEXT__;
if (typeof runner !== 'function') {
throw new Error(
'bundle export should be a function when using ' +
'{ runInNewContext: false }.'
)
}
}
userContext._registeredComponents = new Set();
// vue-style-loader styles imported outside of component lifecycle hooks
if (initialContext._styles) {
userContext._styles = deepClone(initialContext._styles);
}
resolve(runner(userContext));
});
}
}
}
/* */
var SourceMapConsumer = require('source-map').SourceMapConsumer;
var filenameRE = /\(([^)]+\.js):(\d+):(\d+)\)$/;
function createSourceMapConsumers (rawMaps) {
var maps = {};
Object.keys(rawMaps).forEach(function (file) {
maps[file] = new SourceMapConsumer(rawMaps[file]);
});
return maps
}
function rewriteErrorTrace (e, mapConsumers) {
if (e && typeof e.stack === 'string') {
e.stack = e.stack.split('\n').map(function (line) {
return rewriteTraceLine(line, mapConsumers)
}).join('\n');
}
}
function rewriteTraceLine (trace, mapConsumers) {
var m = trace.match(filenameRE);
var map = m && mapConsumers[m[1]];
if (m != null && map) {
var originalPosition = map.originalPositionFor({
line: Number(m[2]),
column: Number(m[3])
});
if (originalPosition.source != null) {
var source = originalPosition.source;
var line = originalPosition.line;
var column = originalPosition.column;
var mappedPosition = "(" + (source.replace(/^webpack:\/\/\//, '')) + ":" + (String(line)) + ":" + (String(column)) + ")";
return trace.replace(filenameRE, mappedPosition)
} else {
return trace
}
} else {
return trace
}
}
/* */
var fs = require('fs');
var path$1 = require('path');
var PassThrough = require('stream').PassThrough;
var INVALID_MSG =
'Invalid server-rendering bundle format. Should be a string ' +
'or a bundle Object of type:\n\n' +
"{\n entry: string;\n files: { [filename: string]: string; };\n maps: { [filename: string]: string; };\n}\n";
// The render bundle can either be a string (single bundled file)
// or a bundle manifest object generated by vue-ssr-webpack-plugin.
function createBundleRendererCreator (
createRenderer
) {
return function createBundleRenderer (
bundle,
rendererOptions
) {
if ( rendererOptions === void 0 ) rendererOptions = {};
var files, entry, maps;
var basedir = rendererOptions.basedir;
// load bundle if given filepath
if (
typeof bundle === 'string' &&
/\.js(on)?$/.test(bundle) &&
path$1.isAbsolute(bundle)
) {
if (fs.existsSync(bundle)) {
var isJSON = /\.json$/.test(bundle);
basedir = basedir || path$1.dirname(bundle);
bundle = fs.readFileSync(bundle, 'utf-8');
if (isJSON) {
try {
bundle = JSON.parse(bundle);
} catch (e) {
throw new Error(("Invalid JSON bundle file: " + bundle))
}
}
} else {
throw new Error(("Cannot locate bundle file: " + bundle))
}
}
if (typeof bundle === 'object') {
entry = bundle.entry;
files = bundle.files;
basedir = basedir || bundle.basedir;
maps = createSourceMapConsumers(bundle.maps);
if (typeof entry !== 'string' || typeof files !== 'object') {
throw new Error(INVALID_MSG)
}
} else if (typeof bundle === 'string') {
entry = '__vue_ssr_bundle__';
files = { '__vue_ssr_bundle__': bundle };
maps = {};
} else {
throw new Error(INVALID_MSG)
}
var renderer = createRenderer(rendererOptions);
var run = createBundleRunner(
entry,
files,
basedir,
rendererOptions.runInNewContext
);
return {
renderToString: function (context, cb) {
if (typeof context === 'function') {
cb = context;
context = {};
}
run(context).catch(function (err) {
rewriteErrorTrace(err, maps);
cb(err);
}).then(function (app) {
if (app) {
renderer.renderToString(app, context, function (err, res) {
rewriteErrorTrace(err, maps);
cb(err, res);
});
}
});
},
renderToStream: function (context) {
var res = new PassThrough();
run(context).catch(function (err) {
rewriteErrorTrace(err, maps);
// avoid emitting synchronously before user can
// attach error listener
process.nextTick(function () {
res.emit('error', err);
});
}).then(function (app) {
if (app) {
var renderStream = renderer.renderToStream(app, context);
renderStream.on('error', function (err) {
rewriteErrorTrace(err, maps);
res.emit('error', err);
});
// relay HTMLStream special events
if (rendererOptions && rendererOptions.template) {
renderStream.on('beforeStart', function () {
res.emit('beforeStart');
});
renderStream.on('beforeEnd', function () {
res.emit('beforeEnd');
});
}
renderStream.pipe(res);
}
});
return res
}
}
}
}
/* */
process.env.VUE_ENV = 'server';
function createRenderer (options) {
if ( options === void 0 ) options = {};
return createRenderer$1(Object.assign({}, options, {
isUnaryTag: isUnaryTag,
canBeLeftOpenTag: canBeLeftOpenTag,
modules: modules,
// user can provide server-side implementations for custom directives
// when creating the renderer.
directives: Object.assign(baseDirectives, options.directives)
}))
}
var createBundleRenderer = createBundleRendererCreator(createRenderer);
exports.createRenderer = createRenderer;
exports.createBundleRenderer = createBundleRenderer;
node-vue-template-compiler-2.4.2+dfsg/packages/vue-server-renderer/client-plugin.js000066400000000000000000000054421361753775300304240ustar00rootroot00000000000000'use strict';
/* */
var isJS = function (file) { return /\.js(\?[^.]+)?$/.test(file); };
var ref = require('chalk');
var red = ref.red;
var yellow = ref.yellow;
var prefix = "[vue-server-renderer-webpack-plugin]";
var warn = exports.warn = function (msg) { return console.error(red((prefix + " " + msg + "\n"))); };
var tip = exports.tip = function (msg) { return console.log(yellow((prefix + " " + msg + "\n"))); };
var hash = require('hash-sum');
var uniq = require('lodash.uniq');
var VueSSRClientPlugin = function VueSSRClientPlugin (options) {
if ( options === void 0 ) options = {};
this.options = Object.assign({
filename: 'vue-ssr-client-manifest.json'
}, options);
};
VueSSRClientPlugin.prototype.apply = function apply (compiler) {
var this$1 = this;
compiler.plugin('emit', function (compilation, cb) {
var stats = compilation.getStats().toJson();
var allFiles = uniq(stats.assets
.map(function (a) { return a.name; }));
var initialFiles = uniq(Object.keys(stats.entrypoints)
.map(function (name) { return stats.entrypoints[name].assets; })
.reduce(function (assets, all) { return all.concat(assets); }, [])
.filter(isJS));
var asyncFiles = allFiles
.filter(isJS)
.filter(function (file) { return initialFiles.indexOf(file) < 0; });
var manifest = {
publicPath: stats.publicPath,
all: allFiles,
initial: initialFiles,
async: asyncFiles,
modules: { /* [identifier: string]: Array */ }
};
var assetModules = stats.modules.filter(function (m) { return m.assets.length; });
var fileToIndex = function (file) { return manifest.all.indexOf(file); };
stats.modules.forEach(function (m) {
// ignore modules duplicated in multiple chunks
if (m.chunks.length === 1) {
var cid = m.chunks[0];
var chunk = stats.chunks.find(function (c) { return c.id === cid; });
if (!chunk || !chunk.files) {
return
}
var files = manifest.modules[hash(m.identifier)] = chunk.files.map(fileToIndex);
// find all asset modules associated with the same chunk
assetModules.forEach(function (m) {
if (m.chunks.some(function (id) { return id === cid; })) {
files.push.apply(files, m.assets.map(fileToIndex));
}
});
}
});
// const debug = (file, obj) => {
// require('fs').writeFileSync(__dirname + '/' + file, JSON.stringify(obj, null, 2))
// }
// debug('stats.json', stats)
// debug('client-manifest.json', manifest)
var json = JSON.stringify(manifest, null, 2);
compilation.assets[this$1.options.filename] = {
source: function () { return json; },
size: function () { return json.length; }
};
cb();
});
};
module.exports = VueSSRClientPlugin;
node-vue-template-compiler-2.4.2+dfsg/packages/vue-server-renderer/index.js000066400000000000000000000010031361753775300267460ustar00rootroot00000000000000try {
var vueVersion = require('vue').version
} catch (e) {}
var packageName = require('./package.json').name
var packageVersion = require('./package.json').version
if (vueVersion && vueVersion !== packageVersion) {
throw new Error(
'\n\nVue packages version mismatch:\n\n' +
'- vue@' + vueVersion + '\n' +
'- ' + packageName + '@' + packageVersion + '\n\n' +
'This may cause things to work incorrectly. Make sure to use the same version for both.\n'
)
}
module.exports = require('./build')
node-vue-template-compiler-2.4.2+dfsg/packages/vue-server-renderer/package.json000066400000000000000000000016241361753775300276000ustar00rootroot00000000000000{
"name": "vue-server-renderer",
"version": "2.4.2",
"description": "server renderer for Vue 2.0",
"main": "index.js",
"types": "types/index.d.ts",
"repository": {
"type": "git",
"url": "git+https://github.com/vuejs/vue.git"
},
"keywords": [
"vue",
"server",
"ssr"
],
"author": "Evan You",
"license": "MIT",
"bugs": {
"url": "https://github.com/vuejs/vue/issues"
},
"scripts": {
"test:types": "tsc -p types"
},
"dependencies": {
"chalk": "^1.1.3",
"hash-sum": "^1.0.2",
"he": "^1.1.0",
"lodash.template": "^4.4.0",
"lodash.uniq": "^4.5.0",
"resolve": "^1.2.0",
"source-map": "0.5.6",
"serialize-javascript": "^1.3.0"
},
"devDependencies": {
"@types/node": "^7.0.22",
"typescript": "^2.3.3",
"vue": "file:../.."
},
"homepage": "https://github.com/vuejs/vue/tree/dev/packages/vue-server-renderer#readme"
}
node-vue-template-compiler-2.4.2+dfsg/packages/vue-server-renderer/server-plugin.js000066400000000000000000000053031361753775300304500ustar00rootroot00000000000000'use strict';
/* */
var isJS = function (file) { return /\.js(\?[^.]+)?$/.test(file); };
var ref = require('chalk');
var red = ref.red;
var yellow = ref.yellow;
var prefix = "[vue-server-renderer-webpack-plugin]";
var warn = exports.warn = function (msg) { return console.error(red((prefix + " " + msg + "\n"))); };
var tip = exports.tip = function (msg) { return console.log(yellow((prefix + " " + msg + "\n"))); };
var validate = function (compiler) {
if (compiler.options.target !== 'node') {
warn('webpack config `target` should be "node".');
}
if (compiler.options.output && compiler.options.output.libraryTarget !== 'commonjs2') {
warn('webpack config `output.libraryTarget` should be "commonjs2".');
}
if (!compiler.options.externals) {
tip(
'It is recommended to externalize dependencies in the server build for ' +
'better build performance.'
);
}
};
var VueSSRServerPlugin = function VueSSRServerPlugin (options) {
if ( options === void 0 ) options = {};
this.options = Object.assign({
filename: 'vue-ssr-server-bundle.json'
}, options);
};
VueSSRServerPlugin.prototype.apply = function apply (compiler) {
var this$1 = this;
validate(compiler);
compiler.plugin('emit', function (compilation, cb) {
var stats = compilation.getStats().toJson();
var entryName = Object.keys(stats.entrypoints)[0];
var entryInfo = stats.entrypoints[entryName];
if (!entryInfo) {
// #5553
return cb()
}
var entryAssets = entryInfo.assets.filter(isJS);
if (entryAssets.length > 1) {
throw new Error(
"Server-side bundle should have one single entry file. " +
"Avoid using CommonsChunkPlugin in the server config."
)
}
var entry = entryAssets[0];
if (!entry || typeof entry !== 'string') {
throw new Error(
("Entry \"" + entryName + "\" not found. Did you specify the correct entry option?")
)
}
var bundle = {
entry: entry,
files: {},
maps: {}
};
stats.assets.forEach(function (asset) {
if (asset.name.match(/\.js$/)) {
bundle.files[asset.name] = compilation.assets[asset.name].source();
} else if (asset.name.match(/\.js\.map$/)) {
bundle.maps[asset.name.replace(/\.map$/, '')] = JSON.parse(compilation.assets[asset.name].source());
}
// do not emit anything else for server
delete compilation.assets[asset.name];
});
var json = JSON.stringify(bundle, null, 2);
var filename = this$1.options.filename;
compilation.assets[filename] = {
source: function () { return json; },
size: function () { return json.length; }
};
cb();
});
};
module.exports = VueSSRServerPlugin;
node-vue-template-compiler-2.4.2+dfsg/packages/vue-server-renderer/types/000077500000000000000000000000001361753775300264535ustar00rootroot00000000000000node-vue-template-compiler-2.4.2+dfsg/packages/vue-server-renderer/types/index.d.ts000066400000000000000000000024721361753775300303610ustar00rootroot00000000000000import Vue = require('vue');
import { Readable } from 'stream';
export declare function createRenderer(options?: RendererOptions): Renderer;
export declare function createBundleRenderer(bundle: string | object, options?: BundleRendererOptions): BundleRenderer;
type RenderCallback = (err: Error | null, html: string) => void;
interface Renderer {
renderToString(vm: Vue, callback: RenderCallback): void;
renderToString(vm: Vue, context: object, callback: RenderCallback): void;
renderToStream(vm: Vue, context?: object): Readable;
}
interface BundleRenderer {
renderToString(callback: RenderCallback): void;
renderToString(context: object, callback: RenderCallback): void;
renderToStream(context?: object): Readable;
}
interface RendererOptions {
template?: string;
inject?: boolean;
shouldPreload?: (file: string, type: string) => boolean;
cache?: RenderCache;
directives?: {
[key: string]: (vnode: Vue.VNode, dir: Vue.VNodeDirective) => void
};
}
interface BundleRendererOptions extends RendererOptions {
clientManifest?: object;
runInNewContext?: boolean | 'once';
basedir?: string;
}
interface RenderCache {
get: (key: string, cb?: (res: string) => void) => string | void;
set: (key: string, val: string) => void;
has?: (key: string, cb?: (hit: boolean) => void) => boolean | void;
}
node-vue-template-compiler-2.4.2+dfsg/packages/vue-server-renderer/types/test.ts000066400000000000000000000034731361753775300300110ustar00rootroot00000000000000import Vue = require('vue');
import { readFileSync } from 'fs';
import { createRenderer, createBundleRenderer } from '../';
function createApp (context: any) {
return new Vue({
data: {
url: context.url
},
template: `The visited URL is: {{ url }}
`
});
}
// Renderer test
const app = createApp({ url: 'http://localhost:8000/' });
const renderer = createRenderer({
template: readFileSync('./index.template.html', 'utf-8')
});
const context = {
title: 'Hello',
meta: `
`
};
renderer.renderToString(app, context, (err, html) => {
if (err) throw err;
const res: string = html;
});
renderer.renderToStream(app, context).on('data', chunk => {
const html = chunk.toString();
});
// Bundle renderer test
declare const cacheClient: { [key: string]: string };
const bundleRenderer = createBundleRenderer('/path/to/vue-ssr-server-bundle.json', {
inject: false,
runInNewContext: 'once',
basedir: '/path/to/base',
shouldPreload: (file, type) => {
if (type === 'script' || type === 'style') {
return true;
}
if (type === 'font') {
return /\.woff2$/.test(file);
}
if (type === 'image') {
return file === 'hero.jpg';
}
return false;
},
cache: {
get: key => {
return cacheClient[key];
},
set: (key, val) => {
cacheClient[key] = val;
},
has: key => {
return !!cacheClient[key];
}
},
directives: {
example (vnode: Vue.VNode, directiveMeta: Vue.VNodeDirective) {
// transform vnode based on directive binding metadata
}
}
});
bundleRenderer.renderToString(context, (err, html) => {
if (err) throw err;
const res: string = html;
});
bundleRenderer.renderToStream(context).on('data', chunk => {
const html = chunk.toString();
});
node-vue-template-compiler-2.4.2+dfsg/packages/vue-server-renderer/types/tsconfig.json000066400000000000000000000003211361753775300311560ustar00rootroot00000000000000{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"moduleResolution": "node",
"strict": true,
"noEmit": true
},
"compileOnSave": false,
"include": [
"**/*.ts"
]
}
node-vue-template-compiler-2.4.2+dfsg/packages/vue-template-compiler/000077500000000000000000000000001361753775300256205ustar00rootroot00000000000000node-vue-template-compiler-2.4.2+dfsg/packages/vue-template-compiler/README.md000066400000000000000000000113441361753775300271020ustar00rootroot00000000000000# vue-template-compiler
> This package is auto-generated. For pull requests please see [src/entries/web-compiler.js](https://github.com/vuejs/vue/tree/dev/src/platforms/web/compiler).
This package can be used to pre-compile Vue 2.0 templates into render functions to avoid runtime-compilation overhead and CSP restrictions. You will only need it if you are writing build tools with very specific needs. In most cases you should be using [vue-loader](https://github.com/vuejs/vue-loader) or [vueify](https://github.com/vuejs/vueify) instead, both of which use this package internally.
## Installation
``` bash
npm install vue-template-compiler
```
``` js
const compiler = require('vue-template-compiler')
```
## API
### compiler.compile(template, [options])
Compiles a template string and returns compiled JavaScript code. The returned result is an object of the following format:
``` js
{
ast: ?ASTElement, // parsed template elements to AST
render: string, // main render function code
staticRenderFns: Array, // render code for static sub trees, if any
errors: Array // template syntax errors, if any
}
```
Note the returned function code uses `with` and thus cannot be used in strict mode code.
#### Options
It's possible to hook into the compilation process to support custom template features. **However, beware that by injecting custom compile-time modules, your templates will not work with other build tools built on standard built-in modules, e.g `vue-loader` and `vueify`.**
The optional `options` object can contain the following:
- `modules`
An array of compiler modules. For details on compiler modules, refer to the `ModuleOptions` type in [flow declarations](https://github.com/vuejs/vue/blob/dev/flow/compiler.js) and the [built-in modules](https://github.com/vuejs/vue/tree/dev/src/platforms/web/compiler/modules).
- `directives`
An object where the key is the directive name and the value is a function that transforms an template AST node. For example:
``` js
compiler.compile('
', {
directives: {
test (node, directiveMeta) {
// transform node based on directiveMeta
}
})
```
By default, a compile-time directive will extract the directive and the directive will not be present at runtime. If you want the directive to also be handled by a runtime definition, return `true` in the transform function.
Refer to the implementation of some [built-in compile-time directives](https://github.com/vuejs/vue/tree/dev/src/platforms/web/compiler/directives).
- `preserveWhitespace`
Defaults to `true`. This means the compiled render function respects all the whitespaces between HTML tags. If set to `false`, all whitespaces between tags will be ignored. This can result in slightly better performance but may affect layout for inline elements.
---
### compiler.compileToFunctions(template)
Similar to `compiler.compile`, but directly returns instantiated functions:
``` js
{
render: Function,
staticRenderFns: Array
}
```
This is only useful at runtime with pre-configured builds, so it doesn't accept any compile-time options. In addition, this method uses `new Function()` so it is not CSP-compliant.
---
### compiler.ssrCompile(template, [options])
> 2.4.0+
Same as `compiler.compile` but generates SSR-specific render function code by optimizing parts of the template into string concatenation in order to improve SSR performance.
This is used by default in `vue-loader@>=12` and can be disabled using the [optimizeSSR](https://vue-loader.vuejs.org/en/options.html#optimizessr) option.
---
### compiler.ssrCompileToFunction(template)
> 2.4.0+
Same as `compiler.compileToFunction` but generates SSR-specific render function code by optimizing parts of the template into string concatenation in order to improve SSR performance.
---
### compiler.parseComponent(file, [options])
Parse a SFC (single-file component, or `*.vue` file) into a descriptor (refer to the `SFCDescriptor` type in [flow declarations](https://github.com/vuejs/vue/blob/dev/flow/compiler.js)). This is used in SFC build tools like `vue-loader` and `vueify`.
#### Options
#### `pad`
`pad` is useful when you are piping the extracted content into other pre-processors, as you will get correct line numbers or character indices if there are any syntax errors.
- with `{ pad: "line" }`, the extracted content for each block will be prefixed with one newline for each line in the leading content from the original file to ensure that the line numbers align with the original file.
- with `{ pad: "space" }`, the extracted content for each block will be prefixed with one space for each character in the leading content from the original file to ensure that the character count remains the same as the original file.
node-vue-template-compiler-2.4.2+dfsg/packages/vue-template-compiler/build.js000066400000000000000000003441111361753775300272610ustar00rootroot00000000000000'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var deindent = _interopDefault(require('de-indent'));
var he = _interopDefault(require('he'));
/* */
// these helpers produces better vm code in JS engines due to their
// explicitness and function inlining
/**
* Check if value is primitive
*/
/**
* 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'
}
var _toString = Object.prototype.toString;
/**
* Strict object type check. Only returns true
* for plain JavaScript objects.
*/
function isPlainObject (obj) {
return _toString.call(obj) === '[object Object]'
}
/**
* Check if val is a valid array index.
*/
function isValidArrayIndex (val) {
var n = parseFloat(val);
return n >= 0 && Math.floor(n) === n && isFinite(val)
}
/**
* Convert a value to a string that is actually rendered.
*/
/**
* Convert a input value to a number for persistence.
* If the conversion fails, return original string.
*/
/**
* 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 a attribute is a reserved attribute.
*/
var isReservedAttribute = makeMap('key,ref,slot,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 the 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.
*/
/**
* Simple bind, faster than native
*/
/**
* Convert an Array-like object to a real Array.
*/
/**
* 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.
*/
/**
* 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; };
/**
* Return same value
*/
var identity = function (_) { return _; };
/**
* Generate a static keys string 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?
*/
/**
* Ensure a function is called only once.
*/
/* */
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.
*/
/*!
* HTML Parser By John Resig (ejohn.org)
* Modified by Juriy "kangax" Zaytsev
* Original code by Erik Arvidsson, Mozilla Public License
* http://erik.eae.net/simplehtmlparser/simplehtmlparser.js
*/
// Regular Expressions for parsing tags and attributes
var singleAttrIdentifier = /([^\s"'<>/=]+)/;
var singleAttrAssign = /(?:=)/;
var singleAttrValues = [
// attr value double quotes
/"([^"]*)"+/.source,
// attr value, single quotes
/'([^']*)'+/.source,
// attr value, no quotes
/([^\s"'=<>`]+)/.source
];
var attribute = new RegExp(
'^\\s*' + singleAttrIdentifier.source +
'(?:\\s*(' + singleAttrAssign.source + ')' +
'\\s*(?:' + singleAttrValues.join('|') + '))?'
);
// could use https://www.w3.org/TR/1999/REC-xml-names-19990114/#NT-QName
// but for Vue templates we can enforce a simple charset
var ncname = '[a-zA-Z_][\\w\\-\\.]*';
var qnameCapture = '((?:' + ncname + '\\:)?' + ncname + ')';
var startTagOpen = new RegExp('^<' + qnameCapture);
var startTagClose = /^\s*(\/?)>/;
var endTag = new RegExp('^<\\/' + qnameCapture + '[^>]*>');
var doctype = /^]+>/i;
var comment = /^');
if (commentEnd >= 0) {
if (options.shouldKeepComment) {
options.comment(html.substring(4, commentEnd));
}
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(lastTag, 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);
advance(textEnd);
}
if (textEnd < 0) {
text = html;
html = '';
}
if (options.chars && text) {
options.chars(text);
}
} else {
var endTagLength = 0;
var stackedTag = lastTag.toLowerCase();
var reStackedTag = reCache[stackedTag] || (reCache[stackedTag] = new RegExp('([\\s\\S]*?)(]*>)', 'i'));
var rest$1 = html.replace(reStackedTag, function (all, text, endTag) {
endTagLength = endTag.length;
if (!isPlainTextElement(stackedTag) && stackedTag !== 'noscript') {
text = text
.replace(//g, '$1')
.replace(//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 (process.env.NODE_ENV !== 'production' && !stack.length && options.warn) {
options.warn(("Mal-formatted tag at end of template: \"" + html + "\""));
}
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(attribute))) {
advance(attr[0].length);
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];
// hackish work around FF bug https://bugzilla.mozilla.org/show_bug.cgi?id=369778
if (IS_REGEX_CAPTURING_BROKEN && args[0].indexOf('""') === -1) {
if (args[3] === '') { delete args[3]; }
if (args[4] === '') { delete args[4]; }
if (args[5] === '') { delete args[5]; }
}
var value = args[3] || args[4] || args[5] || '';
attrs[i] = {
name: args[1],
value: decodeAttr(
value,
options.shouldDecodeNewlines
)
};
}
if (!unary) {
stack.push({ tag: tagName, lowerCasedTag: tagName.toLowerCase(), attrs: attrs });
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; }
if (tagName) {
lowerCasedTagName = tagName.toLowerCase();
}
// Find the closest opened tag of the same type
if (tagName) {
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 (process.env.NODE_ENV !== 'production' &&
(i > pos || !tagName) &&
options.warn
) {
options.warn(
("tag <" + (stack[i].tag) + "> has no matching end tag.")
);
}
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 splitRE = /\r?\n/g;
var replaceRE = /./g;
var isSpecialTag = makeMap('script,style,template', true);
/**
* Parse a single-file component (*.vue) file into an SFC Descriptor Object.
*/
function parseComponent (
content,
options
) {
if ( options === void 0 ) options = {};
var sfc = {
template: null,
script: null,
styles: [],
customBlocks: []
};
var depth = 0;
var currentBlock = null;
function start (
tag,
attrs,
unary,
start,
end
) {
if (depth === 0) {
currentBlock = {
type: tag,
content: '',
start: end,
attrs: attrs.reduce(function (cumulated, ref) {
var name = ref.name;
var value = ref.value;
cumulated[name] = value || true;
return cumulated
}, Object.create(null))
};
if (isSpecialTag(tag)) {
checkAttrs(currentBlock, attrs);
if (tag === 'style') {
sfc.styles.push(currentBlock);
} else {
sfc[tag] = currentBlock;
}
} else { // custom blocks
sfc.customBlocks.push(currentBlock);
}
}
if (!unary) {
depth++;
}
}
function checkAttrs (block, attrs) {
for (var i = 0; i < attrs.length; i++) {
var attr = attrs[i];
if (attr.name === 'lang') {
block.lang = attr.value;
}
if (attr.name === 'scoped') {
block.scoped = true;
}
if (attr.name === 'module') {
block.module = attr.value || true;
}
if (attr.name === 'src') {
block.src = attr.value;
}
}
}
function end (tag, start, end) {
if (depth === 1 && currentBlock) {
currentBlock.end = start;
var text = deindent(content.slice(currentBlock.start, currentBlock.end));
// pad content so that linters and pre-processors can output correct
// line numbers in errors and warnings
if (currentBlock.type !== 'template' && options.pad) {
text = padContent(currentBlock, options.pad) + text;
}
currentBlock.content = text;
currentBlock = null;
}
depth--;
}
function padContent (block, pad) {
if (pad === 'space') {
return content.slice(0, block.start).replace(replaceRE, ' ')
} else {
var offset = content.slice(0, block.start).split(splitRE).length;
var padChar = block.type === 'script' && !block.lang
? '//\n'
: '\n';
return Array(offset).join(padChar)
}
}
parseHTML(content, {
start: start,
end: end
});
return sfc
}
/* */
var emptyObject = Object.freeze({});
/**
* Check if a string starts with $ or _
*/
/**
* Define a property.
*/
function def (obj, key, val, enumerable) {
Object.defineProperty(obj, key, {
value: val,
enumerable: !!enumerable,
writable: true,
configurable: true
});
}
var ASSET_TYPES = [
'component',
'directive',
'filter'
];
var LIFECYCLE_HOOKS = [
'beforeCreate',
'created',
'beforeMount',
'mounted',
'beforeUpdate',
'updated',
'beforeDestroy',
'destroyed',
'activated',
'deactivated'
];
/* */
var config = ({
/**
* Option merge strategies (used in core/util/options)
*/
optionMergeStrategies: Object.create(null),
/**
* Whether to suppress warnings.
*/
silent: false,
/**
* Show production mode tip message on boot?
*/
productionTip: process.env.NODE_ENV !== 'production',
/**
* Whether to enable devtools
*/
devtools: process.env.NODE_ENV !== '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
*/
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,
/**
* Exposed for legacy reasons
*/
_lifecycleHooks: LIFECYCLE_HOOKS
});
/* */
var warn = noop;
var tip = noop;
var formatComponentName = (null); // work around flow check
if (process.env.NODE_ENV !== 'production') {
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 ''
}
var name = typeof vm === 'string'
? vm
: typeof vm === 'function' && vm.options
? vm.options.name
: vm._isVue
? vm.$options.name || vm.$options._componentTag
: vm.name;
var file = vm._isVue && vm.$options.__file;
if (!name && file) {
var match = file.match(/([^/\\]+)\.vue$/);
name = match && match[1];
}
return (
(name ? ("<" + (classify(name)) + ">") : "") +
(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
};
var 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)) + ")")
}
};
}
/* */
function handleError (err, vm, info) {
if (config.errorHandler) {
config.errorHandler.call(null, err, vm, info);
} else {
if (process.env.NODE_ENV !== 'production') {
warn(("Error in " + info + ": \"" + (err.toString()) + "\""), vm);
}
/* istanbul ignore else */
if (inBrowser && typeof console !== 'undefined') {
console.error(err);
} else {
throw err
}
}
}
/* */
/* globals MutationObserver */
// can we use __proto__?
var hasProto = '__proto__' in {};
// Browser environment sniffing
var inBrowser = typeof window !== 'undefined';
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;
var isIOS = UA && /iphone|ipad|ipod|ios/.test(UA);
var isChrome = UA && /chrome\/\d+/.test(UA) && !isEdge;
// Firefix 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 && typeof global !== 'undefined') {
// detect presence of vue-server-renderer and avoid
// Webpack shimming the process
_isServer = global['process'].env.VUE_ENV === 'server';
} else {
_isServer = false;
}
}
return _isServer
};
// detect devtools
/* 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);
/**
* Defer a task to execute it asynchronously.
*/
var nextTick = (function () {
var callbacks = [];
var pending = false;
var timerFunc;
function nextTickHandler () {
pending = false;
var copies = callbacks.slice(0);
callbacks.length = 0;
for (var i = 0; i < copies.length; i++) {
copies[i]();
}
}
// 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 if */
if (typeof Promise !== 'undefined' && isNative(Promise)) {
var p = Promise.resolve();
var logError = function (err) { console.error(err); };
timerFunc = function () {
p.then(nextTickHandler).catch(logError);
// 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); }
};
} else if (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 IE11, iOS7, Android 4.4
var counter = 1;
var observer = new MutationObserver(nextTickHandler);
var textNode = document.createTextNode(String(counter));
observer.observe(textNode, {
characterData: true
});
timerFunc = function () {
counter = (counter + 1) % 2;
textNode.data = String(counter);
};
} else {
// fallback to setTimeout
/* istanbul ignore next */
timerFunc = function () {
setTimeout(nextTickHandler, 0);
};
}
return function queueNextTick (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();
}
if (!cb && typeof Promise !== 'undefined') {
return new Promise(function (resolve, reject) {
_resolve = resolve;
})
}
}
})();
var _Set;
/* istanbul ignore if */
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 = (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 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();
for (var i = 0, l = subs.length; i < l; i++) {
subs[i].update();
}
};
// the current target watcher being evaluated.
// this is globally unique because there could be only one
// watcher being evaluated at any time.
Dep.target = null;
/*
* 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);[
'push',
'pop',
'shift',
'unshift',
'splice',
'sort',
'reverse'
]
.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);
/**
* By default, when a reactive property is set, the new value is
* also converted to become reactive. However when passing down props,
* we don't want to force conversion because the value may be a nested value
* under a frozen data structure. Converting it would defeat the optimization.
*/
var observerState = {
shouldConvert: true
};
/**
* Observer class that are attached to each observed
* object. Once attached, the observer converts target
* object's property keys into getter/setters that
* collect dependencies and dispatches updates.
*/
var Observer = function Observer (value) {
this.value = value;
this.dep = new Dep();
this.vmCount = 0;
def(value, '__ob__', this);
if (Array.isArray(value)) {
var augment = hasProto
? protoAugment
: copyAugment;
augment(value, arrayMethods, arrayKeys);
this.observeArray(value);
} else {
this.walk(value);
}
};
/**
* Walk through each property 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], 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 an target Object or Array by intercepting
* the prototype chain using __proto__
*/
function protoAugment (target, src, keys) {
/* eslint-disable no-proto */
target.__proto__ = src;
/* eslint-enable no-proto */
}
/**
* Augment an 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)) {
return
}
var ob;
if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) {
ob = value.__ob__;
} else if (
observerState.shouldConvert &&
!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;
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 (process.env.NODE_ENV !== 'production' && customSetter) {
customSetter();
}
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 (Array.isArray(target) && isValidArrayIndex(key)) {
target.length = Math.max(target.length, key);
target.splice(key, 1, val);
return val
}
if (hasOwn(target, key)) {
target[key] = val;
return val
}
var ob = (target).__ob__;
if (target._isVue || (ob && ob.vmCount)) {
process.env.NODE_ENV !== 'production' && 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.
*/
/**
* 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
*/
if (process.env.NODE_ENV !== 'production') {
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 = Object.keys(from);
for (var i = 0; i < keys.length; i++) {
key = keys[i];
toVal = to[key];
fromVal = from[key];
if (!hasOwn(to, key)) {
set(to, key, fromVal);
} else if (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) : childVal,
typeof parentVal === 'function' ? parentVal.call(this) : parentVal
)
}
} else if (parentVal || childVal) {
return function mergedInstanceDataFn () {
// instance merge
var instanceData = typeof childVal === 'function'
? childVal.call(vm)
: childVal;
var defaultData = typeof parentVal === 'function'
? parentVal.call(vm)
: undefined;
if (instanceData) {
return mergeData(instanceData, defaultData)
} else {
return defaultData
}
}
}
}
strats.data = function (
parentVal,
childVal,
vm
) {
if (!vm) {
if (childVal && typeof childVal !== 'function') {
process.env.NODE_ENV !== 'production' && warn(
'The "data" option should be a function ' +
'that returns a per-instance value in component ' +
'definitions.',
vm
);
return parentVal
}
return mergeDataOrFn.call(this, parentVal, childVal)
}
return mergeDataOrFn(parentVal, childVal, vm)
};
/**
* Hooks and props are merged as arrays.
*/
function mergeHook (
parentVal,
childVal
) {
return childVal
? parentVal
? parentVal.concat(childVal)
: Array.isArray(childVal)
? childVal
: [childVal]
: parentVal
}
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) {
var res = Object.create(parentVal || null);
return childVal
? extend(res, childVal)
: 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) {
// 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) }
if (!parentVal) { return childVal }
var ret = {};
extend(ret, parentVal);
for (var key in childVal) {
var parent = ret[key];
var child = childVal[key];
if (parent && !Array.isArray(parent)) {
parent = [parent];
}
ret[key] = 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) {
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
};
/**
* Merge two option objects into a new one.
* Core utility used in both instantiation and inheritance.
*/
/**
* Resolve an asset.
* This function is used because child instances need access
* to assets defined in its ancestor chain.
*/
/* */
/* */
/* */
// 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');
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 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 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'
}
}
/* */
/**
* Query an element selector if it's not an element already.
*/
/* */
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)
}
}
/* */
var defaultTagRE = /\{\{((?:.|\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 lastIndex = tagRE.lastIndex = 0;
var match, index;
while ((match = tagRE.exec(text))) {
index = match.index;
// push text token
if (index > lastIndex) {
tokens.push(JSON.stringify(text.slice(lastIndex, index)));
}
// tag token
var exp = parseFilters(match[1].trim());
tokens.push(("_s(" + exp + ")"));
lastIndex = index + match[0].length;
}
if (lastIndex < text.length) {
tokens.push(JSON.stringify(text.slice(lastIndex)));
}
return tokens.join('+')
}
/* */
function baseWarn (msg) {
console.error(("[Vue compiler]: " + msg));
}
function pluckModuleFunction (
modules,
key
) {
return modules
? modules.map(function (m) { return m[key]; }).filter(function (_) { return _; })
: []
}
function addProp (el, name, value) {
(el.props || (el.props = [])).push({ name: name, value: value });
}
function addAttr (el, name, value) {
(el.attrs || (el.attrs = [])).push({ name: name, value: value });
}
function addDirective (
el,
name,
rawName,
value,
arg,
modifiers
) {
(el.directives || (el.directives = [])).push({ name: name, rawName: rawName, value: value, arg: arg, modifiers: modifiers });
}
function addHandler (
el,
name,
value,
modifiers,
important,
warn
) {
// warn prevent and passive modifier
/* istanbul ignore if */
if (
process.env.NODE_ENV !== 'production' && warn &&
modifiers && modifiers.prevent && modifiers.passive
) {
warn(
'passive and prevent can\'t be used together. ' +
'Passive handler can\'t prevent default event.'
);
}
// check capture modifier
if (modifiers && modifiers.capture) {
delete modifiers.capture;
name = '!' + name; // mark the event as captured
}
if (modifiers && modifiers.once) {
delete modifiers.once;
name = '~' + name; // mark the event as once
}
/* istanbul ignore if */
if (modifiers && modifiers.passive) {
delete modifiers.passive;
name = '&' + name; // mark the event as passive
}
var events;
if (modifiers && modifiers.native) {
delete modifiers.native;
events = el.nativeEvents || (el.nativeEvents = {});
} else {
events = el.events || (el.events = {});
}
var newHandler = { value: value, 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;
}
}
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)
}
}
}
function getAndRemoveAttr (el, name) {
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
}
}
}
return val
}
/* */
function transformNode (el, options) {
var warn = options.warn || baseWarn;
var staticClass = getAndRemoveAttr(el, 'class');
if (process.env.NODE_ENV !== 'production' && staticClass) {
var expression = parseText(staticClass, options.delimiters);
if (expression) {
warn(
"class=\"" + staticClass + "\": " +
'Interpolation inside attributes has been removed. ' +
'Use v-bind or the colon shorthand instead. For example, ' +
'instead of , use
.'
);
}
}
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 = {
staticKeys: ['staticClass'],
transformNode: transformNode,
genData: genData
};
/* */
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
});
// normalize possible array / string values into Object
/**
* parent component style should be after child's
* so that parent component's style could override it
*/
/* */
function transformNode$1 (el, options) {
var warn = options.warn || baseWarn;
var staticStyle = getAndRemoveAttr(el, 'style');
if (staticStyle) {
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production') {
var expression = parseText(staticStyle, options.delimiters);
if (expression) {
warn(
"style=\"" + staticStyle + "\": " +
'Interpolation inside attributes has been removed. ' +
'Use v-bind or the colon shorthand instead. For example, ' +
'instead of
, use
.'
);
}
}
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 = {
staticKeys: ['staticStyle'],
transformNode: transformNode$1,
genData: genData$1
};
var modules = [
klass,
style
];
/* */
/**
* 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: ("\"" + value + "\""),
callback: ("function (" + baseValueExpression + ") {" + assignment + "}")
};
}
/**
* Cross-platform codegen helper for generating v-model value assignment code.
*/
function genAssignmentCode (
value,
assignment
) {
var modelRs = parseModel(value);
if (modelRs.idx === null) {
return (value + "=" + assignment)
} else {
return ("$set(" + (modelRs.exp) + ", " + (modelRs.idx) + ", " + assignment + ")")
}
}
/**
* parse directive model to do the array update transform. a[idx] = val => $$a.splice($$idx, 1, val)
*
* for loop possible cases:
*
* - test
* - test[idx]
* - test[test1[idx]]
* - test["a"][idx]
* - xxx.test[a[a].test1[idx]]
* - test.xxx.a["asa"][test1[idx]]
*
*/
var len;
var str;
var chr;
var index;
var expressionPos;
var expressionEndPos;
function parseModel (val) {
str = val;
len = str.length;
index = expressionPos = expressionEndPos = 0;
if (val.indexOf('[') < 0 || val.lastIndexOf(']') < len - 1) {
return {
exp: val,
idx: null
}
}
while (!eof()) {
chr = next();
/* istanbul ignore if */
if (isStringStart(chr)) {
parseString(chr);
} else if (chr === 0x5B) {
parseBracket(chr);
}
}
return {
exp: val.substring(0, expressionPos),
idx: val.substring(expressionPos + 1, expressionEndPos)
}
}
function next () {
return str.charCodeAt(++index)
}
function eof () {
return index >= len
}
function isStringStart (chr) {
return chr === 0x22 || chr === 0x27
}
function parseBracket (chr) {
var inBracket = 1;
expressionPos = index;
while (!eof()) {
chr = next();
if (isStringStart(chr)) {
parseString(chr);
continue
}
if (chr === 0x5B) { inBracket++; }
if (chr === 0x5D) { inBracket--; }
if (inBracket === 0) {
expressionEndPos = index;
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;
if (process.env.NODE_ENV !== 'production') {
var dynamicType = el.attrsMap['v-bind:type'] || el.attrsMap[':type'];
if (tag === 'input' && dynamicType) {
warn$1(
"
:\n" +
"v-model does not support dynamic input types. Use v-if branches instead."
);
}
// 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."
);
}
}
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 if (process.env.NODE_ENV !== 'production') {
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.'
);
}
// 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, CHECKBOX_RADIO_TOKEN,
"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&&(" + value + "=$$a.concat($$v))}" +
"else{$$i>-1&&(" + 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, CHECKBOX_RADIO_TOKEN, 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;
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()');
}
}
/* */
function text (el, dir) {
if (dir.value) {
addProp(el, 'textContent', ("_s(" + (dir.value) + ")"));
}
}
/* */
function html (el, dir) {
if (dir.value) {
addProp(el, 'innerHTML', ("_s(" + (dir.value) + ")"));
}
}
var directives = {
model: model,
text: text,
html: html
};
/* */
var baseOptions = {
expectHTML: true,
modules: modules,
directives: directives,
isPreTag: isPreTag,
isUnaryTag: isUnaryTag,
mustUseProp: mustUseProp,
canBeLeftOpenTag: canBeLeftOpenTag,
isReservedTag: isReservedTag,
getTagNamespace: getTagNamespace,
staticKeys: genStaticKeys(modules)
};
/* */
var onRE = /^@|^v-on:/;
var dirRE = /^v-|^@|^:/;
var forAliasRE = /(.*?)\s+(?:in|of)\s+(.*)/;
var forIteratorRE = /\((\{[^}]*\}|[^,]*),([^,]*)(?:,([^,]*))?\)/;
var argRE = /:(.*)$/;
var bindRE = /^:|^v-bind:/;
var modifierRE = /\.[^.]+/g;
var decodeHTMLCached = cached(he.decode);
// configurable state
var warn$2;
var delimiters;
var transforms;
var preTransforms;
var postTransforms;
var platformIsPreTag;
var platformMustUseProp;
var platformGetTagNamespace;
/**
* 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;
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 root;
var currentParent;
var inVPre = false;
var inPre = false;
var warned = false;
function warnOnce (msg) {
if (!warned) {
warned = true;
warn$2(msg);
}
}
function endPre (element) {
// check pre state
if (element.pre) {
inVPre = false;
}
if (platformIsPreTag(element.tag)) {
inPre = false;
}
}
parseHTML(template, {
warn: warn$2,
expectHTML: options.expectHTML,
isUnaryTag: options.isUnaryTag,
canBeLeftOpenTag: options.canBeLeftOpenTag,
shouldDecodeNewlines: options.shouldDecodeNewlines,
shouldKeepComment: options.comments,
start: function start (tag, attrs, unary) {
// 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 = {
type: 1,
tag: tag,
attrsList: attrs,
attrsMap: makeAttrsMap(attrs),
parent: currentParent,
children: []
};
if (ns) {
element.ns = ns;
}
if (isForbiddenTag(element) && !isServerRendering()) {
element.forbidden = true;
process.env.NODE_ENV !== 'production' && 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.'
);
}
// apply pre-transforms
for (var i = 0; i < preTransforms.length; i++) {
preTransforms[i](element, options);
}
if (!inVPre) {
processPre(element);
if (element.pre) {
inVPre = true;
}
}
if (platformIsPreTag(element.tag)) {
inPre = true;
}
if (inVPre) {
processRawAttrs(element);
} else {
processFor(element);
processIf(element);
processOnce(element);
processKey(element);
// determine whether this is a plain element after
// removing structural attributes
element.plain = !element.key && !attrs.length;
processRef(element);
processSlot(element);
processComponent(element);
for (var i$1 = 0; i$1 < transforms.length; i$1++) {
transforms[i$1](element, options);
}
processAttrs(element);
}
function checkRootConstraints (el) {
if (process.env.NODE_ENV !== 'production') {
if (el.tag === 'slot' || el.tag === 'template') {
warnOnce(
"Cannot use <" + (el.tag) + "> as component root element because it may " +
'contain multiple nodes.'
);
}
if (el.attrsMap.hasOwnProperty('v-for')) {
warnOnce(
'Cannot use v-for on stateful component root element because ' +
'it renders multiple elements.'
);
}
}
}
// tree management
if (!root) {
root = element;
checkRootConstraints(root);
} else if (!stack.length) {
// 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 if (process.env.NODE_ENV !== 'production') {
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."
);
}
}
if (currentParent && !element.forbidden) {
if (element.elseif || element.else) {
processIfConditions(element, currentParent);
} else if (element.slotScope) { // scoped slot
currentParent.plain = false;
var name = element.slotTarget || '"default"';(currentParent.scopedSlots || (currentParent.scopedSlots = {}))[name] = element;
} else {
currentParent.children.push(element);
element.parent = currentParent;
}
}
if (!unary) {
currentParent = element;
stack.push(element);
} else {
endPre(element);
}
// apply post-transforms
for (var i$2 = 0; i$2 < postTransforms.length; i$2++) {
postTransforms[i$2](element, options);
}
},
end: function end () {
// remove trailing whitespace
var element = stack[stack.length - 1];
var lastNode = element.children[element.children.length - 1];
if (lastNode && lastNode.type === 3 && lastNode.text === ' ' && !inPre) {
element.children.pop();
}
// pop stack
stack.length -= 1;
currentParent = stack[stack.length - 1];
endPre(element);
},
chars: function chars (text) {
if (!currentParent) {
if (process.env.NODE_ENV !== 'production') {
if (text === template) {
warnOnce(
'Component template requires a root element, rather than just text.'
);
} else if ((text = text.trim())) {
warnOnce(
("text \"" + text + "\" outside root element will be ignored.")
);
}
}
return
}
// IE textarea placeholder bug
/* istanbul ignore if */
if (isIE &&
currentParent.tag === 'textarea' &&
currentParent.attrsMap.placeholder === text
) {
return
}
var children = currentParent.children;
text = inPre || text.trim()
? isTextTag(currentParent) ? text : decodeHTMLCached(text)
// only preserve whitespace if its not right after a starting tag
: preserveWhitespace && children.length ? ' ' : '';
if (text) {
var expression;
if (!inVPre && text !== ' ' && (expression = parseText(text, delimiters))) {
children.push({
type: 2,
expression: expression,
text: text
});
} else if (text !== ' ' || !children.length || children[children.length - 1].text !== ' ') {
children.push({
type: 3,
text: text
});
}
}
},
comment: function comment (text) {
currentParent.children.push({
type: 3,
text: text,
isComment: true
});
}
});
return root
}
function processPre (el) {
if (getAndRemoveAttr(el, 'v-pre') != null) {
el.pre = true;
}
}
function processRawAttrs (el) {
var l = el.attrsList.length;
if (l) {
var attrs = el.attrs = new Array(l);
for (var i = 0; i < l; i++) {
attrs[i] = {
name: el.attrsList[i].name,
value: JSON.stringify(el.attrsList[i].value)
};
}
} else if (!el.pre) {
// non root node in pre blocks with no attributes
el.plain = true;
}
}
function processKey (el) {
var exp = getBindingAttr(el, 'key');
if (exp) {
if (process.env.NODE_ENV !== 'production' && el.tag === 'template') {
warn$2("
cannot be keyed. Place the key on real elements instead.");
}
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 inMatch = exp.match(forAliasRE);
if (!inMatch) {
process.env.NODE_ENV !== 'production' && warn$2(
("Invalid v-for expression: " + exp)
);
return
}
el.for = inMatch[2].trim();
var alias = inMatch[1].trim();
var iteratorMatch = alias.match(forIteratorRE);
if (iteratorMatch) {
el.alias = iteratorMatch[1].trim();
el.iterator1 = iteratorMatch[2].trim();
if (iteratorMatch[3]) {
el.iterator2 = iteratorMatch[3].trim();
}
} else {
el.alias = alias;
}
}
}
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 if (process.env.NODE_ENV !== 'production') {
warn$2(
"v-" + (el.elseif ? ('else-if="' + el.elseif + '"') : 'else') + " " +
"used on element <" + (el.tag) + "> without corresponding v-if."
);
}
}
function findPrevElement (children) {
var i = children.length;
while (i--) {
if (children[i].type === 1) {
return children[i]
} else {
if (process.env.NODE_ENV !== 'production' && children[i].text !== ' ') {
warn$2(
"text \"" + (children[i].text.trim()) + "\" between v-if and v-else(-if) " +
"will be ignored."
);
}
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;
}
}
function processSlot (el) {
if (el.tag === 'slot') {
el.slotName = getBindingAttr(el, 'name');
if (process.env.NODE_ENV !== 'production' && el.key) {
warn$2(
"`key` does not work on because slots are abstract outlets " +
"and can possibly expand into multiple elements. " +
"Use the key on a wrapping element instead."
);
}
} else {
var slotTarget = getBindingAttr(el, 'slot');
if (slotTarget) {
el.slotTarget = slotTarget === '""' ? '"default"' : slotTarget;
}
if (el.tag === 'template') {
el.slotScope = getAndRemoveAttr(el, 'scope');
}
}
}
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, isProp;
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);
if (modifiers) {
name = name.replace(modifierRE, '');
}
if (bindRE.test(name)) { // v-bind
name = name.replace(bindRE, '');
value = parseFilters(value);
isProp = false;
if (modifiers) {
if (modifiers.prop) {
isProp = true;
name = camelize(name);
if (name === 'innerHtml') { name = 'innerHTML'; }
}
if (modifiers.camel) {
name = camelize(name);
}
if (modifiers.sync) {
addHandler(
el,
("update:" + (camelize(name))),
genAssignmentCode(value, "$event")
);
}
}
if (isProp || (
!el.component && platformMustUseProp(el.tag, el.attrsMap.type, name)
)) {
addProp(el, name, value);
} else {
addAttr(el, name, value);
}
} else if (onRE.test(name)) { // v-on
name = name.replace(onRE, '');
addHandler(el, name, value, modifiers, false, warn$2);
} else { // normal directives
name = name.replace(dirRE, '');
// parse arg
var argMatch = name.match(argRE);
var arg = argMatch && argMatch[1];
if (arg) {
name = name.slice(0, -(arg.length + 1));
}
addDirective(el, name, rawName, value, arg, modifiers);
if (process.env.NODE_ENV !== 'production' && name === 'model') {
checkForAliasModel(el, value);
}
}
} else {
// literal attribute
if (process.env.NODE_ENV !== 'production') {
var expression = parseText(value, delimiters);
if (expression) {
warn$2(
name + "=\"" + value + "\": " +
'Interpolation inside attributes has been removed. ' +
'Use v-bind or the colon shorthand instead. For example, ' +
'instead of , use
.'
);
}
}
addAttr(el, name, JSON.stringify(value));
}
}
}
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 (
process.env.NODE_ENV !== 'production' &&
map[attrs[i].name] && !isIE && !isEdge
) {
warn$2('duplicate attribute: ' + attrs[i].name);
}
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 = _el.parent;
}
}
/* */
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(root);
// second pass: mark static roots.
markStaticRoots(root, false);
}
function genStaticKeys$1 (keys) {
return makeMap(
'type,tag,attrsList,attrsMap,plain,parent,children,attrs' +
(keys ? ',' + keys : '')
)
}
function markStatic (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(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(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 = /^\s*([\w$_]+|\([^)]*?\))\s*=>|^function\s*\(/;
var simplePathRE = /^\s*[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\['.*?']|\[".*?"]|\[\d+]|\[[A-Za-z_$][\w$]*])*\s*$/;
// keyCode aliases
var keyCodes = {
esc: 27,
tab: 9,
enter: 13,
space: 32,
up: 38,
left: 37,
right: 39,
down: 40,
'delete': [8, 46]
};
// #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,
warn
) {
var res = isNative ? 'nativeOn:{' : 'on:{';
for (var name in events) {
var handler = events[name];
// #5330: warn click.right, since right clicks do not actually fire click events.
if (process.env.NODE_ENV !== 'production' &&
name === 'click' &&
handler && handler.modifiers && handler.modifiers.right
) {
warn(
"Use \"contextmenu\" instead of \"click.right\" since right clicks " +
"do not actually fire \"click\" events."
);
}
res += "\"" + name + "\":" + (genHandler(name, handler)) + ",";
}
return res.slice(0, -1) + '}'
}
function genHandler (
name,
handler
) {
if (!handler) {
return 'function(){}'
}
if (Array.isArray(handler)) {
return ("[" + (handler.map(function (handler) { return genHandler(name, handler); }).join(',')) + "]")
}
var isMethodPath = simplePathRE.test(handler.value);
var isFunctionExpression = fnExpRE.test(handler.value);
if (!handler.modifiers) {
return isMethodPath || isFunctionExpression
? handler.value
: ("function($event){" + (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 {
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
? handler.value + '($event)'
: isFunctionExpression
? ("(" + (handler.value) + ")($event)")
: handler.value;
return ("function($event){" + code + handlerCode + "}")
}
}
function genKeyFilter (keys) {
return ("if(!('button' in $event)&&" + (keys.map(genFilterCode).join('&&')) + ")return null;")
}
function genFilterCode (key) {
var keyVal = parseInt(key, 10);
if (keyVal) {
return ("$event.keyCode!==" + keyVal)
}
var alias = keyCodes[key];
return ("_k($event.keyCode," + (JSON.stringify(key)) + (alias ? ',' + JSON.stringify(alias) : '') + ")")
}
/* */
function on (el, dir) {
if (process.env.NODE_ENV !== 'production' && 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 !isReservedTag(el.tag); };
this.onceId = 0;
this.staticRenderFns = [];
};
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.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) {
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 = el.plain ? undefined : 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;
state.staticRenderFns.push(("with(this){return " + (genElement(el, state)) + "}"));
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) {
process.env.NODE_ENV !== 'production' && state.warn(
"v-once can only be used inside v-for that is keyed. "
);
return genElement(el, state)
}
return ("_o(" + (genElement(el, state)) + "," + (state.onceId++) + (key ? ("," + 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 (process.env.NODE_ENV !== 'production' &&
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.",
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, state.warn)) + ",";
}
if (el.nativeEvents) {
data += (genHandlers(el.nativeEvents, true, state.warn)) + ",";
}
// slot target
if (el.slotTarget) {
data += "slot:" + (el.slotTarget) + ",";
}
// scoped slots
if (el.scopedSlots) {
data += (genScopedSlots(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 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.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 (process.env.NODE_ENV !== 'production' && (
el.children.length > 1 || ast.type !== 1
)) {
state.warn('Inline-template components must have exactly one child element.');
}
if (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 (
slots,
state
) {
return ("scopedSlots:_u([" + (Object.keys(slots).map(function (key) {
return genScopedSlot(key, slots[key], state)
}).join(',')) + "])")
}
function genScopedSlot (
key,
el,
state
) {
if (el.for && !el.forProcessed) {
return genForScopedSlot(key, el, state)
}
return "{key:" + key + ",fn:function(" + (String(el.attrsMap.scope)) + "){" +
"return " + (el.tag === 'template'
? genChildren(el, state) || 'void 0'
: genElement(el, state)) + "}}"
}
function genForScopedSlot (
key,
el,
state
) {
var exp = el.for;
var alias = el.alias;
var iterator1 = el.iterator1 ? ("," + (el.iterator1)) : '';
var iterator2 = el.iterator2 ? ("," + (el.iterator2)) : '';
el.forProcessed = true; // avoid recursion
return "_l((" + exp + ")," +
"function(" + alias + iterator1 + iterator2 + "){" +
"return " + (genScopedSlot(key, el, state)) +
'})'
}
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'
) {
return (altGenElement || genElement)(el$1, state)
}
var normalizationType = checkSkip
? getNormalizationType(children, state.maybeComponent)
: 0;
var gen = altGenNode || genNode;
return ("[" + (children.map(function (c) { return gen(c, state); }).join(',')) + "]" + (normalizationType ? ("," + normalizationType) : ''))
}
}
// 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)
} 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.attrs.map(function (a) { return ((camelize(a.name)) + ":" + (a.value)); }).join(',')) + "}");
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 res = '';
for (var i = 0; i < props.length; i++) {
var prop = props[i];
res += "\"" + (prop.name) + "\":" + (transformSpecialNewlines(prop.value)) + ",";
}
return res.slice(0, -1)
}
// #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*\\([^\\)]*\\)');
// check valid identifier for v-for
var identRE = /[A-Za-z_$][\w$]*/;
// strip strings in expressions
var stripStringRE = /'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*\$\{|\}(?:[^`\\]|\\.)*`|`(?:[^`\\]|\\.)*`/g;
// detect problematic expressions in a template
function detectErrors (ast) {
var errors = [];
if (ast) {
checkNode(ast, errors);
}
return errors
}
function checkNode (node, errors) {
if (node.type === 1) {
for (var name in node.attrsMap) {
if (dirRE.test(name)) {
var value = node.attrsMap[name];
if (value) {
if (name === 'v-for') {
checkFor(node, ("v-for=\"" + value + "\""), errors);
} else if (onRE.test(name)) {
checkEvent(value, (name + "=\"" + value + "\""), errors);
} else {
checkExpression(value, (name + "=\"" + value + "\""), errors);
}
}
}
}
if (node.children) {
for (var i = 0; i < node.children.length; i++) {
checkNode(node.children[i], errors);
}
}
} else if (node.type === 2) {
checkExpression(node.expression, node.text, errors);
}
}
function checkEvent (exp, text, errors) {
var stipped = exp.replace(stripStringRE, '');
var keywordMatch = stipped.match(unaryOperatorsRE);
if (keywordMatch && stipped.charAt(keywordMatch.index - 1) !== '$') {
errors.push(
"avoid using JavaScript unary operator as property name: " +
"\"" + (keywordMatch[0]) + "\" in expression " + (text.trim())
);
}
checkExpression(exp, text, errors);
}
function checkFor (node, text, errors) {
checkExpression(node.for || '', text, errors);
checkIdentifier(node.alias, 'v-for alias', text, errors);
checkIdentifier(node.iterator1, 'v-for iterator', text, errors);
checkIdentifier(node.iterator2, 'v-for iterator', text, errors);
}
function checkIdentifier (ident, type, text, errors) {
if (typeof ident === 'string' && !identRE.test(ident)) {
errors.push(("invalid " + type + " \"" + ident + "\" in expression: " + (text.trim())));
}
}
function checkExpression (exp, text, errors) {
try {
new Function(("return " + exp));
} catch (e) {
var keywordMatch = exp.replace(stripStringRE, '').match(prohibitedKeywordRE);
if (keywordMatch) {
errors.push(
"avoid using JavaScript keyword as property name: " +
"\"" + (keywordMatch[0]) + "\" in expression " + (text.trim())
);
} else {
errors.push(("invalid expression: " + (text.trim())));
}
}
}
/* */
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 = options || {};
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production') {
// detect possible CSP restriction
try {
new Function('return 1');
} catch (e) {
if (e.toString().match(/unsafe-eval|CSP/)) {
warn(
'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 (process.env.NODE_ENV !== 'production') {
if (compiled.errors && compiled.errors.length) {
warn(
"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) {
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 (process.env.NODE_ENV !== 'production') {
if ((!compiled.errors || !compiled.errors.length) && fnGenErrors.length) {
warn(
"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 = [];
finalOptions.warn = function (msg, tip) {
(tip ? tips : errors).push(msg);
};
if (options) {
// 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),
options.directives
);
}
// copy other options
for (var key in options) {
if (key !== 'modules' && key !== 'directives') {
finalOptions[key] = options[key];
}
}
}
var compiled = baseCompile(template, finalOptions);
if (process.env.NODE_ENV !== 'production') {
errors.push.apply(errors, detectErrors(compiled.ast));
}
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);
optimize(ast, options);
var code = generate(ast, options);
return {
ast: ast,
render: code.render,
staticRenderFns: code.staticRenderFns
}
});
/* */
var ref = createCompiler(baseOptions);
var compile = ref.compile;
var compileToFunctions = ref.compileToFunctions;
/* */
var isAttr = makeMap(
'accept,accept-charset,accesskey,action,align,alt,async,autocomplete,' +
'autofocus,autoplay,autosave,bgcolor,border,buffered,challenge,charset,' +
'checked,cite,class,code,codebase,color,cols,colspan,content,http-equiv,' +
'name,contenteditable,contextmenu,controls,coords,data,datetime,default,' +
'defer,dir,dirname,disabled,download,draggable,dropzone,enctype,method,for,' +
'form,formaction,headers,height,hidden,high,href,hreflang,http-equiv,' +
'icon,id,ismap,itemprop,keytype,kind,label,lang,language,list,loop,low,' +
'manifest,max,maxlength,media,method,GET,POST,min,multiple,email,file,' +
'muted,name,novalidate,open,optimum,pattern,ping,placeholder,poster,' +
'preload,radiogroup,readonly,rel,required,reversed,rows,rowspan,sandbox,' +
'scope,scoped,seamless,selected,shape,size,type,text,password,sizes,span,' +
'spellcheck,src,srcdoc,srclang,srcset,start,step,style,summary,tabindex,' +
'target,title,type,usemap,value,width,wrap'
);
/* istanbul ignore next */
var isRenderableAttr = function (name) {
return (
isAttr(name) ||
name.indexOf('data-') === 0 ||
name.indexOf('aria-') === 0
)
};
var propsToAttrMap = {
acceptCharset: 'accept-charset',
className: 'class',
htmlFor: 'for',
httpEquiv: 'http-equiv'
};
/* */
var plainStringRE = /^"(?:[^"\\]|\\.)*"$|^'(?:[^'\\]|\\.)*'$/;
// let the model AST transform translate v-model into appropriate
// props bindings
function applyModelTransform (el, state) {
if (el.directives) {
for (var i = 0; i < el.directives.length; i++) {
var dir = el.directives[i];
if (dir.name === 'model') {
state.directives.model(el, dir, state.warn);
break
}
}
}
}
function genAttrSegments (
attrs
) {
return attrs.map(function (ref) {
var name = ref.name;
var value = ref.value;
return genAttrSegment(name, value);
})
}
function genDOMPropSegments (
props,
attrs
) {
var segments = [];
props.forEach(function (ref) {
var name = ref.name;
var value = ref.value;
name = propsToAttrMap[name] || name.toLowerCase();
if (isRenderableAttr(name) &&
!(attrs && attrs.some(function (a) { return a.name === name; }))
) {
segments.push(genAttrSegment(name, value));
}
});
return segments
}
function genAttrSegment (name, value) {
if (plainStringRE.test(value)) {
// force double quote
value = value.replace(/^'|'$/g, '"');
// force enumerated attr to "true"
if (isEnumeratedAttr(name) && value !== "\"false\"") {
value = "\"true\"";
}
return {
type: RAW,
value: isBooleanAttr(name)
? (" " + name + "=\"" + name + "\"")
: value === '""'
? (" " + name)
: (" " + name + "=" + value)
}
} else {
return {
type: EXPRESSION,
value: ("_ssrAttr(" + (JSON.stringify(name)) + "," + value + ")")
}
}
}
function genClassSegments (
staticClass,
classBinding
) {
if (staticClass && !classBinding) {
return [{ type: RAW, value: (" class=" + staticClass) }]
} else {
return [{
type: EXPRESSION,
value: ("_ssrClass(" + (staticClass || 'null') + "," + (classBinding || 'null') + ")")
}]
}
}
function genStyleSegments (
staticStyle,
parsedStaticStyle,
styleBinding,
vShowExpression
) {
if (staticStyle && !styleBinding && !vShowExpression) {
return [{ type: RAW, value: (" style=" + (JSON.stringify(staticStyle))) }]
} else {
return [{
type: EXPRESSION,
value: ("_ssrStyle(" + (parsedStaticStyle || 'null') + "," + (styleBinding || 'null') + ", " + (vShowExpression
? ("{ display: (" + vShowExpression + ") ? '' : 'none' }")
: 'null') + ")")
}]
}
}
/* */
/**
* In SSR, the vdom tree is generated only once and never patched, so
* we can optimize most element / trees into plain string render functions.
* The SSR optimizer walks the AST tree to detect optimizable elements and trees.
*
* The criteria for SSR optimizability is quite a bit looser than static tree
* detection (which is designed for client re-render). In SSR we bail only for
* components/slots/custom directives.
*/
// optimizability constants
var optimizability = {
FALSE: 0, // whole sub tree un-optimizable
FULL: 1, // whole sub tree optimizable
SELF: 2, // self optimizable but has some un-optimizable children
CHILDREN: 3, // self un-optimizable but have fully optimizable children
PARTIAL: 4 // self un-optimizable with some un-optimizable children
};
var isPlatformReservedTag$1;
function optimize$1 (root, options) {
if (!root) { return }
isPlatformReservedTag$1 = options.isReservedTag || no;
walk(root, true);
}
function walk (node, isRoot) {
if (isUnOptimizableTree(node)) {
node.ssrOptimizability = optimizability.FALSE;
return
}
// root node or nodes with custom directives should always be a VNode
var selfUnoptimizable = isRoot || hasCustomDirective(node);
var check = function (child) {
if (child.ssrOptimizability !== optimizability.FULL) {
node.ssrOptimizability = selfUnoptimizable
? optimizability.PARTIAL
: optimizability.SELF;
}
};
if (selfUnoptimizable) {
node.ssrOptimizability = optimizability.CHILDREN;
}
if (node.type === 1) {
for (var i = 0, l = node.children.length; i < l; i++) {
var child = node.children[i];
walk(child);
check(child);
}
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;
walk(block);
check(block);
}
}
if (node.ssrOptimizability == null ||
(!isRoot && (node.attrsMap['v-html'] || node.attrsMap['v-text']))
) {
node.ssrOptimizability = optimizability.FULL;
} else {
node.children = optimizeSiblings(node);
}
} else {
node.ssrOptimizability = optimizability.FULL;
}
}
function optimizeSiblings (el) {
var children = el.children;
var optimizedChildren = [];
var currentOptimizableGroup = [];
var pushGroup = function () {
if (currentOptimizableGroup.length) {
optimizedChildren.push({
type: 1,
parent: el,
tag: 'template',
attrsList: [],
attrsMap: {},
children: currentOptimizableGroup,
ssrOptimizability: optimizability.FULL
});
}
currentOptimizableGroup = [];
};
for (var i = 0; i < children.length; i++) {
var c = children[i];
if (c.ssrOptimizability === optimizability.FULL) {
currentOptimizableGroup.push(c);
} else {
// wrap fully-optimizable adjacent siblings inside a template tag
// so that they can be optimized into a single ssrNode by codegen
pushGroup();
optimizedChildren.push(c);
}
}
pushGroup();
return optimizedChildren
}
function isUnOptimizableTree (node) {
if (node.type === 2 || node.type === 3) { // text or expression
return false
}
return (
isBuiltInTag(node.tag) || // built-in (slot, component)
!isPlatformReservedTag$1(node.tag) || // custom component
!!node.component // "is" component
)
}
var isBuiltInDir = makeMap('text,html,show,on,bind,model,pre,cloak,once');
function hasCustomDirective (node) {
return (
node.type === 1 &&
node.directives &&
node.directives.some(function (d) { return !isBuiltInDir(d.name); })
)
}
/* */
// The SSR codegen is essentially extending the default codegen to handle
// SSR-optimizable nodes and turn them into string render fns. In cases where
// a node is not optimizable it simply falls back to the default codegen.
// segment types
var RAW = 0;
var INTERPOLATION = 1;
var EXPRESSION = 2;
function generate$1 (
ast,
options
) {
var state = new CodegenState(options);
var code = ast ? genSSRElement(ast, state) : '_c("div")';
return {
render: ("with(this){return " + code + "}"),
staticRenderFns: state.staticRenderFns
}
}
function genSSRElement (el, state) {
if (el.for && !el.forProcessed) {
return genFor(el, state, genSSRElement)
} else if (el.if && !el.ifProcessed) {
return genIf(el, state, genSSRElement)
} else if (el.tag === 'template' && !el.slotTarget) {
return el.ssrOptimizability === optimizability.FULL
? genChildrenAsStringNode(el, state)
: genSSRChildren(el, state) || 'void 0'
}
switch (el.ssrOptimizability) {
case optimizability.FULL:
// stringify whole tree
return genStringElement(el, state)
case optimizability.SELF:
// stringify self and check children
return genStringElementWithChildren(el, state)
case optimizability.CHILDREN:
// generate self as VNode and stringify children
return genNormalElement(el, state, true)
case optimizability.PARTIAL:
// generate self as VNode and check children
return genNormalElement(el, state, false)
default:
// bail whole tree
return genElement(el, state)
}
}
function genNormalElement (el, state, stringifyChildren) {
var data = el.plain ? undefined : genData$2(el, state);
var children = stringifyChildren
? ("[" + (genChildrenAsStringNode(el, state)) + "]")
: genSSRChildren(el, state, true);
return ("_c('" + (el.tag) + "'" + (data ? ("," + data) : '') + (children ? ("," + children) : '') + ")")
}
function genSSRChildren (el, state, checkSkip) {
return genChildren(el, state, checkSkip, genSSRElement, genSSRNode)
}
function genSSRNode (el, state) {
return el.type === 1
? genSSRElement(el, state)
: genText(el)
}
function genChildrenAsStringNode (el, state) {
return el.children.length
? ("_ssrNode(" + (flattenSegments(childrenToSegments(el, state))) + ")")
: ''
}
function genStringElement (el, state) {
return ("_ssrNode(" + (elementToString(el, state)) + ")")
}
function genStringElementWithChildren (el, state) {
var children = genSSRChildren(el, state, true);
return ("_ssrNode(" + (flattenSegments(elementToOpenTagSegments(el, state))) + ",\"\"" + (children ? ("," + children) : '') + ")")
}
function elementToString (el, state) {
return ("(" + (flattenSegments(elementToSegments(el, state))) + ")")
}
function elementToSegments (el, state) {
// v-for / v-if
if (el.for && !el.forProcessed) {
el.forProcessed = true;
return [{
type: EXPRESSION,
value: genFor(el, state, elementToString, '_ssrList')
}]
} else if (el.if && !el.ifProcessed) {
el.ifProcessed = true;
return [{
type: EXPRESSION,
value: genIf(el, state, elementToString, '""')
}]
} else if (el.tag === 'template') {
return childrenToSegments(el, state)
}
var openSegments = elementToOpenTagSegments(el, state);
var childrenSegments = childrenToSegments(el, state);
var ref = state.options;
var isUnaryTag = ref.isUnaryTag;
var close = (isUnaryTag && isUnaryTag(el.tag))
? []
: [{ type: RAW, value: ("") }];
return openSegments.concat(childrenSegments, close)
}
function elementToOpenTagSegments (el, state) {
applyModelTransform(el, state);
var binding;
var segments = [{ type: RAW, value: ("<" + (el.tag)) }];
// attrs
if (el.attrs) {
segments.push.apply(segments, genAttrSegments(el.attrs));
}
// domProps
if (el.props) {
segments.push.apply(segments, genDOMPropSegments(el.props, el.attrs));
}
// v-bind="object"
if ((binding = el.attrsMap['v-bind'])) {
segments.push({ type: EXPRESSION, value: ("_ssrAttrs(" + binding + ")") });
}
// v-bind.prop="object"
if ((binding = el.attrsMap['v-bind.prop'])) {
segments.push({ type: EXPRESSION, value: ("_ssrDOMProps(" + binding + ")") });
}
// class
if (el.staticClass || el.classBinding) {
segments.push.apply(
segments,
genClassSegments(el.staticClass, el.classBinding)
);
}
// style & v-show
if (el.staticStyle || el.styleBinding || el.attrsMap['v-show']) {
segments.push.apply(
segments,
genStyleSegments(
el.attrsMap.style,
el.staticStyle,
el.styleBinding,
el.attrsMap['v-show']
)
);
}
// _scopedId
if (state.options.scopeId) {
segments.push({ type: RAW, value: (" " + (state.options.scopeId)) });
}
segments.push({ type: RAW, value: ">" });
return segments
}
function childrenToSegments (el, state) {
var binding;
if ((binding = el.attrsMap['v-html'])) {
return [{ type: EXPRESSION, value: binding }]
}
if ((binding = el.attrsMap['v-text'])) {
return [{ type: INTERPOLATION, value: binding }]
}
return el.children
? nodesToSegments(el.children, state)
: []
}
function nodesToSegments (
children,
state
) {
var segments = [];
for (var i = 0; i < children.length; i++) {
var c = children[i];
if (c.type === 1) {
segments.push.apply(segments, elementToSegments(c, state));
} else if (c.type === 2) {
segments.push({ type: INTERPOLATION, value: c.expression });
} else if (c.type === 3) {
segments.push({ type: RAW, value: c.text });
}
}
return segments
}
function flattenSegments (segments) {
var mergedSegments = [];
var textBuffer = '';
var pushBuffer = function () {
if (textBuffer) {
mergedSegments.push(JSON.stringify(textBuffer));
textBuffer = '';
}
};
for (var i = 0; i < segments.length; i++) {
var s = segments[i];
if (s.type === RAW) {
textBuffer += s.value;
} else if (s.type === INTERPOLATION) {
pushBuffer();
mergedSegments.push(("_ssrEscape(" + (s.value) + ")"));
} else if (s.type === EXPRESSION) {
pushBuffer();
mergedSegments.push(("(" + (s.value) + ")"));
}
}
pushBuffer();
return mergedSegments.join('+')
}
/* */
var createCompiler$1 = createCompilerCreator(function baseCompile (
template,
options
) {
var ast = parse(template.trim(), options);
optimize$1(ast, options);
var code = generate$1(ast, options);
return {
ast: ast,
render: code.render,
staticRenderFns: code.staticRenderFns
}
});
/* */
var ref$1 = createCompiler$1(baseOptions);
var compile$1 = ref$1.compile;
var compileToFunctions$1 = ref$1.compileToFunctions;
/* */
exports.parseComponent = parseComponent;
exports.compile = compile;
exports.compileToFunctions = compileToFunctions;
exports.ssrCompile = compile$1;
exports.ssrCompileToFunctions = compileToFunctions$1;
node-vue-template-compiler-2.4.2+dfsg/packages/vue-template-compiler/index.js000066400000000000000000000013341361753775300272660ustar00rootroot00000000000000try {
var vueVersion = require('vue').version
} catch (e) {}
var packageName = require('./package.json').name
var packageVersion = require('./package.json').version
if (vueVersion && vueVersion !== packageVersion) {
throw new Error(
'\n\nVue packages version mismatch:\n\n' +
'- vue@' + vueVersion + '\n' +
'- ' + packageName + '@' + packageVersion + '\n\n' +
'This may cause things to work incorrectly. Make sure to use the same version for both.\n' +
'If you are using vue-loader@>=10.0, simply update vue-template-compiler.\n' +
'If you are using vue-loader@<10.0 or vueify, re-installing vue-loader/vueify should bump ' + packageName + ' to the latest.\n'
)
}
module.exports = require('./build')
node-vue-template-compiler-2.4.2+dfsg/packages/vue-template-compiler/package.json000066400000000000000000000010411361753775300301020ustar00rootroot00000000000000{
"name": "vue-template-compiler",
"version": "2.4.2",
"description": "template compiler for Vue 2.0",
"main": "index.js",
"repository": {
"type": "git",
"url": "git+https://github.com/vuejs/vue.git"
},
"keywords": [
"vue",
"compiler"
],
"author": "Evan You",
"license": "MIT",
"bugs": {
"url": "https://github.com/vuejs/vue/issues"
},
"homepage": "https://github.com/vuejs/vue/tree/dev/packages/vue-template-compiler#readme",
"dependencies": {
"he": "^1.1.0",
"de-indent": "^1.0.2"
}
}
node-vue-template-compiler-2.4.2+dfsg/packages/weex-template-compiler/000077500000000000000000000000001361753775300257715ustar00rootroot00000000000000node-vue-template-compiler-2.4.2+dfsg/packages/weex-template-compiler/README.md000066400000000000000000000002741361753775300272530ustar00rootroot00000000000000# weex-template-compiler
> This package is auto-generated. For pull requests please see [src/entries/weex-compiler.js](https://github.com/vuejs/vue/tree/dev/src/platforms/weex/compiler).
node-vue-template-compiler-2.4.2+dfsg/packages/weex-template-compiler/build.js000066400000000000000000002323601361753775300274340ustar00rootroot00000000000000'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var he = require('he');
/* */
// these helpers produces better vm code in JS engines due to their
// explicitness and function inlining
/**
* Check if value is primitive
*/
/**
* Quick object check - this is primarily used to tell
* Objects from primitive values when we know the value
* is a JSON-compliant type.
*/
/**
* Strict object type check. Only returns true
* for plain JavaScript objects.
*/
/**
* Convert a value to a string that is actually rendered.
*/
/**
* Convert a input value to a number for persistence.
* If the conversion fails, return original string.
*/
/**
* 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);
/**
* Remove an item from an array
*/
/**
* 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.
*/
/**
* Simple bind, faster than native
*/
/**
* Convert an Array-like object to a real Array.
*/
/**
* 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.
*/
/**
* Perform no operation.
*/
function noop () {}
/**
* Always return false.
*/
var no = function () { return false; };
/**
* Return same value
*/
var identity = function (_) { return _; };
/**
* Generate a static keys string 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?
*/
/**
* Ensure a function is called only once.
*/
/* */
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.
*/
/*!
* HTML Parser By John Resig (ejohn.org)
* Modified by Juriy "kangax" Zaytsev
* Original code by Erik Arvidsson, Mozilla Public License
* http://erik.eae.net/simplehtmlparser/simplehtmlparser.js
*/
// Regular Expressions for parsing tags and attributes
var singleAttrIdentifier = /([^\s"'<>/=]+)/;
var singleAttrAssign = /(?:=)/;
var singleAttrValues = [
// attr value double quotes
/"([^"]*)"+/.source,
// attr value, single quotes
/'([^']*)'+/.source,
// attr value, no quotes
/([^\s"'=<>`]+)/.source
];
var attribute = new RegExp(
'^\\s*' + singleAttrIdentifier.source +
'(?:\\s*(' + singleAttrAssign.source + ')' +
'\\s*(?:' + singleAttrValues.join('|') + '))?'
);
// could use https://www.w3.org/TR/1999/REC-xml-names-19990114/#NT-QName
// but for Vue templates we can enforce a simple charset
var ncname = '[a-zA-Z_][\\w\\-\\.]*';
var qnameCapture = '((?:' + ncname + '\\:)?' + ncname + ')';
var startTagOpen = new RegExp('^<' + qnameCapture);
var startTagClose = /^\s*(\/?)>/;
var endTag = new RegExp('^<\\/' + qnameCapture + '[^>]*>');
var doctype = /^]+>/i;
var comment = /^');
if (commentEnd >= 0) {
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);
continue
}
}
var text = (void 0), rest$1 = (void 0), next = (void 0);
if (textEnd >= 0) {
rest$1 = html.slice(textEnd);
while (
!endTag.test(rest$1) &&
!startTagOpen.test(rest$1) &&
!comment.test(rest$1) &&
!conditionalComment.test(rest$1)
) {
// < in plain text, be forgiving and treat it as text
next = rest$1.indexOf('<', 1);
if (next < 0) { break }
textEnd += next;
rest$1 = html.slice(textEnd);
}
text = html.substring(0, textEnd);
advance(textEnd);
}
if (textEnd < 0) {
text = html;
html = '';
}
if (options.chars && text) {
options.chars(text);
}
} else {
var stackedTag = lastTag.toLowerCase();
var reStackedTag = reCache[stackedTag] || (reCache[stackedTag] = new RegExp('([\\s\\S]*?)(]*>)', 'i'));
var endTagLength = 0;
var rest = html.replace(reStackedTag, function (all, text, endTag) {
endTagLength = endTag.length;
if (!isPlainTextElement(stackedTag) && stackedTag !== 'noscript') {
text = text
.replace(//g, '$1')
.replace(//g, '$1');
}
if (options.chars) {
options.chars(text);
}
return ''
});
index += html.length - rest.length;
html = rest;
parseEndTag(stackedTag, index - endTagLength, index);
}
if (html === last) {
options.chars && options.chars(html);
if (process.env.NODE_ENV !== 'production' && !stack.length && options.warn) {
options.warn(("Mal-formatted tag at end of template: \"" + html + "\""));
}
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(attribute))) {
advance(attr[0].length);
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) || tagName === 'html' && lastTag === 'head' || !!unarySlash;
var l = match.attrs.length;
var attrs = new Array(l);
for (var i = 0; i < l; i++) {
var args = match.attrs[i];
// hackish work around FF bug https://bugzilla.mozilla.org/show_bug.cgi?id=369778
if (IS_REGEX_CAPTURING_BROKEN && args[0].indexOf('""') === -1) {
if (args[3] === '') { delete args[3]; }
if (args[4] === '') { delete args[4]; }
if (args[5] === '') { delete args[5]; }
}
var value = args[3] || args[4] || args[5] || '';
attrs[i] = {
name: args[1],
value: decodeAttr(
value,
options.shouldDecodeNewlines
)
};
}
if (!unary) {
stack.push({ tag: tagName, lowerCasedTag: tagName.toLowerCase(), attrs: attrs });
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; }
if (tagName) {
lowerCasedTagName = tagName.toLowerCase();
}
// Find the closest opened tag of the same type
if (tagName) {
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 (process.env.NODE_ENV !== 'production' &&
(i > pos || !tagName) &&
options.warn) {
options.warn(
("tag <" + (stack[i].tag) + "> has no matching end tag.")
);
}
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 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)
}
}
/* */
var defaultTagRE = /\{\{((?:.|\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 lastIndex = tagRE.lastIndex = 0;
var match, index;
while ((match = tagRE.exec(text))) {
index = match.index;
// push text token
if (index > lastIndex) {
tokens.push(JSON.stringify(text.slice(lastIndex, index)));
}
// tag token
var exp = parseFilters(match[1].trim());
tokens.push(("_s(" + exp + ")"));
lastIndex = index + match[0].length;
}
if (lastIndex < text.length) {
tokens.push(JSON.stringify(text.slice(lastIndex)));
}
return tokens.join('+')
}
/* */
/**
* 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: ("\"" + value + "\""),
callback: ("function (" + baseValueExpression + ") {" + assignment + "}")
};
}
/**
* Cross-platform codegen helper for generating v-model value assignment code.
*/
function genAssignmentCode (
value,
assignment
) {
var modelRs = parseModel(value);
if (modelRs.idx === null) {
return (value + "=" + assignment)
} else {
return "var $$exp = " + (modelRs.exp) + ", $$idx = " + (modelRs.idx) + ";" +
"if (!Array.isArray($$exp)){" +
value + "=" + assignment + "}" +
"else{$$exp.splice($$idx, 1, " + assignment + ")}"
}
}
/**
* parse directive model to do the array update transform. a[idx] = val => $$a.splice($$idx, 1, val)
*
* for loop possible cases:
*
* - test
* - test[idx]
* - test[test1[idx]]
* - test["a"][idx]
* - xxx.test[a[a].test1[idx]]
* - test.xxx.a["asa"][test1[idx]]
*
*/
var len;
var str;
var chr;
var index;
var expressionPos;
var expressionEndPos;
function parseModel (val) {
str = val;
len = str.length;
index = expressionPos = expressionEndPos = 0;
if (val.indexOf('[') < 0 || val.lastIndexOf(']') < len - 1) {
return {
exp: val,
idx: null
}
}
while (!eof()) {
chr = next();
/* istanbul ignore if */
if (isStringStart(chr)) {
parseString(chr);
} else if (chr === 0x5B) {
parseBracket(chr);
}
}
return {
exp: val.substring(0, expressionPos),
idx: val.substring(expressionPos + 1, expressionEndPos)
}
}
function next () {
return str.charCodeAt(++index)
}
function eof () {
return index >= len
}
function isStringStart (chr) {
return chr === 0x22 || chr === 0x27
}
function parseBracket (chr) {
var inBracket = 1;
expressionPos = index;
while (!eof()) {
chr = next();
if (isStringStart(chr)) {
parseString(chr);
continue
}
if (chr === 0x5B) { inBracket++; }
if (chr === 0x5D) { inBracket--; }
if (inBracket === 0) {
expressionEndPos = index;
break
}
}
}
function parseString (chr) {
var stringQuote = chr;
while (!eof()) {
chr = next();
if (chr === stringQuote) {
break
}
}
}
var LIFECYCLE_HOOKS = [
'beforeCreate',
'created',
'beforeMount',
'mounted',
'beforeUpdate',
'updated',
'beforeDestroy',
'destroyed',
'activated',
'deactivated'
];
/* */
var config = ({
/**
* Option merge strategies (used in core/util/options)
*/
optionMergeStrategies: Object.create(null),
/**
* Whether to suppress warnings.
*/
silent: false,
/**
* Show production mode tip message on boot?
*/
productionTip: process.env.NODE_ENV !== 'production',
/**
* Whether to enable devtools
*/
devtools: process.env.NODE_ENV !== 'production',
/**
* Whether to record perf
*/
performance: false,
/**
* Error handler for watcher errors
*/
errorHandler: null,
/**
* Ignore certain custom elements
*/
ignoredElements: [],
/**
* Custom user key aliases for v-on
*/
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,
/**
* Exposed for legacy reasons
*/
_lifecycleHooks: LIFECYCLE_HOOKS
});
var warn$1 = noop;
var tip = noop;
var formatComponentName;
if (process.env.NODE_ENV !== 'production') {
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$1 = function (msg, vm) {
if (hasConsole && (!config.silent)) {
console.error("[Vue warn]: " + msg + (
vm ? generateComponentTrace(vm) : ''
));
}
};
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 '
'
}
var name = typeof vm === 'string'
? vm
: typeof vm === 'function' && vm.options
? vm.options.name
: vm._isVue
? vm.$options.name || vm.$options._componentTag
: vm.name;
var file = vm._isVue && vm.$options.__file;
if (!name && file) {
var match = file.match(/([^/\\]+)\.vue$/);
name = match && match[1];
}
return (
(name ? ("<" + (classify(name)) + ">") : "") +
(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
};
var 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)) + ")")
}
};
}
function handleError (err, vm, info) {
if (config.errorHandler) {
config.errorHandler.call(null, err, vm, info);
} else {
if (process.env.NODE_ENV !== 'production') {
warn$1(("Error in " + info + ": \"" + (err.toString()) + "\""), vm);
}
/* istanbul ignore else */
if (inBrowser && typeof console !== 'undefined') {
console.error(err);
} else {
throw err
}
}
}
/* */
/* globals MutationObserver */
// can we use __proto__?
// Browser environment sniffing
var inBrowser = typeof window !== 'undefined';
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;
var isIOS = UA && /iphone|ipad|ipod|ios/.test(UA);
var isChrome = UA && /chrome\/\d+/.test(UA) && !isEdge;
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 && typeof global !== 'undefined') {
// detect presence of vue-server-renderer and avoid
// Webpack shimming the process
_isServer = global['process'].env.VUE_ENV === 'server';
} else {
_isServer = false;
}
}
return _isServer
};
// detect devtools
/* 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);
/**
* Defer a task to execute it asynchronously.
*/
var nextTick = (function () {
var callbacks = [];
var pending = false;
var timerFunc;
function nextTickHandler () {
pending = false;
var copies = callbacks.slice(0);
callbacks.length = 0;
for (var i = 0; i < copies.length; i++) {
copies[i]();
}
}
// 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 if */
if (typeof Promise !== 'undefined' && isNative(Promise)) {
var p = Promise.resolve();
var logError = function (err) { console.error(err); };
timerFunc = function () {
p.then(nextTickHandler).catch(logError);
// 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); }
};
} else if (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 IE11, iOS7, Android 4.4
var counter = 1;
var observer = new MutationObserver(nextTickHandler);
var textNode = document.createTextNode(String(counter));
observer.observe(textNode, {
characterData: true
});
timerFunc = function () {
counter = (counter + 1) % 2;
textNode.data = String(counter);
};
} else {
// fallback to setTimeout
/* istanbul ignore next */
timerFunc = function () {
setTimeout(nextTickHandler, 0);
};
}
return function queueNextTick (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();
}
if (!cb && typeof Promise !== 'undefined') {
return new Promise(function (resolve, reject) {
_resolve = resolve;
})
}
}
})();
var _Set;
/* istanbul ignore if */
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 = (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;
}());
}
/* */
function baseWarn (msg) {
console.error(("[Vue compiler]: " + msg));
}
function pluckModuleFunction (
modules,
key
) {
return modules
? modules.map(function (m) { return m[key]; }).filter(function (_) { return _; })
: []
}
function addProp (el, name, value) {
(el.props || (el.props = [])).push({ name: name, value: value });
}
function addAttr (el, name, value) {
(el.attrs || (el.attrs = [])).push({ name: name, value: value });
}
function addDirective (
el,
name,
rawName,
value,
arg,
modifiers
) {
(el.directives || (el.directives = [])).push({ name: name, rawName: rawName, value: value, arg: arg, modifiers: modifiers });
}
function addHandler (
el,
name,
value,
modifiers,
important,
warn
) {
// warn prevent and passive modifier
/* istanbul ignore if */
if (
process.env.NODE_ENV !== 'production' && warn &&
modifiers && modifiers.prevent && modifiers.passive
) {
warn(
'passive and prevent can\'t be used together. ' +
'Passive handler can\'t prevent default event.'
);
}
// check capture modifier
if (modifiers && modifiers.capture) {
delete modifiers.capture;
name = '!' + name; // mark the event as captured
}
if (modifiers && modifiers.once) {
delete modifiers.once;
name = '~' + name; // mark the event as once
}
/* istanbul ignore if */
if (modifiers && modifiers.passive) {
delete modifiers.passive;
name = '&' + name; // mark the event as passive
}
var events;
if (modifiers && modifiers.native) {
delete modifiers.native;
events = el.nativeEvents || (el.nativeEvents = {});
} else {
events = el.events || (el.events = {});
}
var newHandler = { value: value, 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;
}
}
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)
}
}
}
function getAndRemoveAttr (el, name) {
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
}
}
}
return val
}
/* */
var onRE = /^@|^v-on:/;
var dirRE = /^v-|^@|^:/;
var forAliasRE = /(.*?)\s+(?:in|of)\s+(.*)/;
var forIteratorRE = /\((\{[^}]*\}|[^,]*),([^,]*)(?:,([^,]*))?\)/;
var argRE = /:(.*)$/;
var bindRE = /^:|^v-bind:/;
var modifierRE = /\.[^.]+/g;
var decodeHTMLCached = cached(he.decode);
// configurable state
var warn;
var delimiters;
var transforms;
var preTransforms;
var postTransforms;
var platformIsPreTag;
var platformMustUseProp;
var platformGetTagNamespace;
/**
* Convert HTML string to AST.
*/
function parse (
template,
options
) {
warn = options.warn || baseWarn;
platformGetTagNamespace = options.getTagNamespace || no;
platformMustUseProp = options.mustUseProp || no;
platformIsPreTag = options.isPreTag || no;
preTransforms = pluckModuleFunction(options.modules, 'preTransformNode');
transforms = pluckModuleFunction(options.modules, 'transformNode');
postTransforms = pluckModuleFunction(options.modules, 'postTransformNode');
delimiters = options.delimiters;
var stack = [];
var preserveWhitespace = options.preserveWhitespace !== false;
var root;
var currentParent;
var inVPre = false;
var inPre = false;
var warned = false;
function warnOnce (msg) {
if (!warned) {
warned = true;
warn(msg);
}
}
function endPre (element) {
// check pre state
if (element.pre) {
inVPre = false;
}
if (platformIsPreTag(element.tag)) {
inPre = false;
}
}
parseHTML(template, {
warn: warn,
expectHTML: options.expectHTML,
isUnaryTag: options.isUnaryTag,
canBeLeftOpenTag: options.canBeLeftOpenTag,
shouldDecodeNewlines: options.shouldDecodeNewlines,
start: function start (tag, attrs, unary) {
// 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 = {
type: 1,
tag: tag,
attrsList: attrs,
attrsMap: makeAttrsMap(attrs),
parent: currentParent,
children: []
};
if (ns) {
element.ns = ns;
}
if (isForbiddenTag(element) && !isServerRendering()) {
element.forbidden = true;
process.env.NODE_ENV !== 'production' && warn(
'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.'
);
}
// apply pre-transforms
for (var i = 0; i < preTransforms.length; i++) {
preTransforms[i](element, options);
}
if (!inVPre) {
processPre(element);
if (element.pre) {
inVPre = true;
}
}
if (platformIsPreTag(element.tag)) {
inPre = true;
}
if (inVPre) {
processRawAttrs(element);
} else {
processFor(element);
processIf(element);
processOnce(element);
processKey(element);
// determine whether this is a plain element after
// removing structural attributes
element.plain = !element.key && !attrs.length;
processRef(element);
processSlot(element);
processComponent(element);
for (var i$1 = 0; i$1 < transforms.length; i$1++) {
transforms[i$1](element, options);
}
processAttrs(element);
}
function checkRootConstraints (el) {
if (process.env.NODE_ENV !== 'production') {
if (el.tag === 'slot' || el.tag === 'template') {
warnOnce(
"Cannot use <" + (el.tag) + "> as component root element because it may " +
'contain multiple nodes.'
);
}
if (el.attrsMap.hasOwnProperty('v-for')) {
warnOnce(
'Cannot use v-for on stateful component root element because ' +
'it renders multiple elements.'
);
}
}
}
// tree management
if (!root) {
root = element;
checkRootConstraints(root);
} else if (!stack.length) {
// 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 if (process.env.NODE_ENV !== 'production') {
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."
);
}
}
if (currentParent && !element.forbidden) {
if (element.elseif || element.else) {
processIfConditions(element, currentParent);
} else if (element.slotScope) { // scoped slot
currentParent.plain = false;
var name = element.slotTarget || '"default"';(currentParent.scopedSlots || (currentParent.scopedSlots = {}))[name] = element;
} else {
currentParent.children.push(element);
element.parent = currentParent;
}
}
if (!unary) {
currentParent = element;
stack.push(element);
} else {
endPre(element);
}
// apply post-transforms
for (var i$2 = 0; i$2 < postTransforms.length; i$2++) {
postTransforms[i$2](element, options);
}
},
end: function end () {
// remove trailing whitespace
var element = stack[stack.length - 1];
var lastNode = element.children[element.children.length - 1];
if (lastNode && lastNode.type === 3 && lastNode.text === ' ' && !inPre) {
element.children.pop();
}
// pop stack
stack.length -= 1;
currentParent = stack[stack.length - 1];
endPre(element);
},
chars: function chars (text) {
if (!currentParent) {
if (process.env.NODE_ENV !== 'production') {
if (text === template) {
warnOnce(
'Component template requires a root element, rather than just text.'
);
} else if ((text = text.trim())) {
warnOnce(
("text \"" + text + "\" outside root element will be ignored.")
);
}
}
return
}
// IE textarea placeholder bug
/* istanbul ignore if */
if (isIE &&
currentParent.tag === 'textarea' &&
currentParent.attrsMap.placeholder === text) {
return
}
var children = currentParent.children;
text = inPre || text.trim()
? isTextTag(currentParent) ? text : decodeHTMLCached(text)
// only preserve whitespace if its not right after a starting tag
: preserveWhitespace && children.length ? ' ' : '';
if (text) {
var expression;
if (!inVPre && text !== ' ' && (expression = parseText(text, delimiters))) {
children.push({
type: 2,
expression: expression,
text: text
});
} else if (text !== ' ' || !children.length || children[children.length - 1].text !== ' ') {
children.push({
type: 3,
text: text
});
}
}
}
});
return root
}
function processPre (el) {
if (getAndRemoveAttr(el, 'v-pre') != null) {
el.pre = true;
}
}
function processRawAttrs (el) {
var l = el.attrsList.length;
if (l) {
var attrs = el.attrs = new Array(l);
for (var i = 0; i < l; i++) {
attrs[i] = {
name: el.attrsList[i].name,
value: JSON.stringify(el.attrsList[i].value)
};
}
} else if (!el.pre) {
// non root node in pre blocks with no attributes
el.plain = true;
}
}
function processKey (el) {
var exp = getBindingAttr(el, 'key');
if (exp) {
if (process.env.NODE_ENV !== 'production' && el.tag === 'template') {
warn(" cannot be keyed. Place the key on real elements instead.");
}
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 inMatch = exp.match(forAliasRE);
if (!inMatch) {
process.env.NODE_ENV !== 'production' && warn(
("Invalid v-for expression: " + exp)
);
return
}
el.for = inMatch[2].trim();
var alias = inMatch[1].trim();
var iteratorMatch = alias.match(forIteratorRE);
if (iteratorMatch) {
el.alias = iteratorMatch[1].trim();
el.iterator1 = iteratorMatch[2].trim();
if (iteratorMatch[3]) {
el.iterator2 = iteratorMatch[3].trim();
}
} else {
el.alias = alias;
}
}
}
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 if (process.env.NODE_ENV !== 'production') {
warn(
"v-" + (el.elseif ? ('else-if="' + el.elseif + '"') : 'else') + " " +
"used on element <" + (el.tag) + "> without corresponding v-if."
);
}
}
function findPrevElement (children) {
var i = children.length;
while (i--) {
if (children[i].type === 1) {
return children[i]
} else {
if (process.env.NODE_ENV !== 'production' && children[i].text !== ' ') {
warn(
"text \"" + (children[i].text.trim()) + "\" between v-if and v-else(-if) " +
"will be ignored."
);
}
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;
}
}
function processSlot (el) {
if (el.tag === 'slot') {
el.slotName = getBindingAttr(el, 'name');
if (process.env.NODE_ENV !== 'production' && el.key) {
warn(
"`key` does not work on because slots are abstract outlets " +
"and can possibly expand into multiple elements. " +
"Use the key on a wrapping element instead."
);
}
} else {
var slotTarget = getBindingAttr(el, 'slot');
if (slotTarget) {
el.slotTarget = slotTarget === '""' ? '"default"' : slotTarget;
}
if (el.tag === 'template') {
el.slotScope = getAndRemoveAttr(el, 'scope');
}
}
}
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, isProp;
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);
if (modifiers) {
name = name.replace(modifierRE, '');
}
if (bindRE.test(name)) { // v-bind
name = name.replace(bindRE, '');
value = parseFilters(value);
isProp = false;
if (modifiers) {
if (modifiers.prop) {
isProp = true;
name = camelize(name);
if (name === 'innerHtml') { name = 'innerHTML'; }
}
if (modifiers.camel) {
name = camelize(name);
}
if (modifiers.sync) {
addHandler(
el,
("update:" + (camelize(name))),
genAssignmentCode(value, "$event")
);
}
}
if (isProp || platformMustUseProp(el.tag, el.attrsMap.type, name)) {
addProp(el, name, value);
} else {
addAttr(el, name, value);
}
} else if (onRE.test(name)) { // v-on
name = name.replace(onRE, '');
addHandler(el, name, value, modifiers, false, warn);
} else { // normal directives
name = name.replace(dirRE, '');
// parse arg
var argMatch = name.match(argRE);
var arg = argMatch && argMatch[1];
if (arg) {
name = name.slice(0, -(arg.length + 1));
}
addDirective(el, name, rawName, value, arg, modifiers);
if (process.env.NODE_ENV !== 'production' && name === 'model') {
checkForAliasModel(el, value);
}
}
} else {
// literal attribute
if (process.env.NODE_ENV !== 'production') {
var expression = parseText(value, delimiters);
if (expression) {
warn(
name + "=\"" + value + "\": " +
'Interpolation inside attributes has been removed. ' +
'Use v-bind or the colon shorthand instead. For example, ' +
'instead of , use
.'
);
}
}
addAttr(el, name, JSON.stringify(value));
}
}
}
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 (
process.env.NODE_ENV !== 'production' &&
map[attrs[i].name] && !isIE && !isEdge
) {
warn('duplicate attribute: ' + attrs[i].name);
}
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(
"<" + (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 = _el.parent;
}
}
/* */
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(root);
// second pass: mark static roots.
markStaticRoots(root, false);
}
function genStaticKeys$1 (keys) {
return makeMap(
'type,tag,attrsList,attrsMap,plain,parent,children,attrs' +
(keys ? ',' + keys : '')
)
}
function markStatic (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(child);
if (!child.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) {
walkThroughConditionsBlocks(node.ifConditions, isInFor);
}
}
}
function walkThroughConditionsBlocks (conditionBlocks, isInFor) {
for (var i = 1, len = conditionBlocks.length; i < len; i++) {
markStaticRoots(conditionBlocks[i].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 = /^\s*([\w$_]+|\([^)]*?\))\s*=>|^function\s*\(/;
var simplePathRE = /^\s*[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\['.*?']|\[".*?"]|\[\d+]|\[[A-Za-z_$][\w$]*])*\s*$/;
// keyCode aliases
var keyCodes = {
esc: 27,
tab: 9,
enter: 13,
space: 32,
up: 38,
left: 37,
right: 39,
down: 40,
'delete': [8, 46]
};
// #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,
native,
warn
) {
var res = native ? 'nativeOn:{' : 'on:{';
for (var name in events) {
var handler = events[name];
// #5330: warn click.right, since right clicks do not actually fire click events.
if (process.env.NODE_ENV !== 'production' &&
name === 'click' &&
handler && handler.modifiers && handler.modifiers.right
) {
warn(
"Use \"contextmenu\" instead of \"click.right\" since right clicks " +
"do not actually fire \"click\" events."
);
}
res += "\"" + name + "\":" + (genHandler(name, handler)) + ",";
}
return res.slice(0, -1) + '}'
}
function genHandler (
name,
handler
) {
if (!handler) {
return 'function(){}'
}
if (Array.isArray(handler)) {
return ("[" + (handler.map(function (handler) { return genHandler(name, handler); }).join(',')) + "]")
}
var isMethodPath = simplePathRE.test(handler.value);
var isFunctionExpression = fnExpRE.test(handler.value);
if (!handler.modifiers) {
return isMethodPath || isFunctionExpression
? handler.value
: ("function($event){" + (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 {
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
? handler.value + '($event)'
: isFunctionExpression
? ("(" + (handler.value) + ")($event)")
: handler.value;
return ("function($event){" + code + handlerCode + "}")
}
}
function genKeyFilter (keys) {
return ("if(!('button' in $event)&&" + (keys.map(genFilterCode).join('&&')) + ")return null;")
}
function genFilterCode (key) {
var keyVal = parseInt(key, 10);
if (keyVal) {
return ("$event.keyCode!==" + keyVal)
}
var alias = keyCodes[key];
return ("_k($event.keyCode," + (JSON.stringify(key)) + (alias ? ',' + JSON.stringify(alias) : '') + ")")
}
/* */
function bind$1 (el, dir) {
el.wrapData = function (code) {
return ("_b(" + code + ",'" + (el.tag) + "'," + (dir.value) + (dir.modifiers && dir.modifiers.prop ? ',true' : '') + ")")
};
}
/* */
var baseDirectives = {
bind: bind$1,
cloak: noop
};
/* */
// configurable state
var warn$2;
var transforms$1;
var dataGenFns;
var platformDirectives;
var isPlatformReservedTag$1;
var staticRenderFns;
var onceCount;
var currentOptions;
function generate (
ast,
options
) {
// save previous staticRenderFns so generate calls can be nested
var prevStaticRenderFns = staticRenderFns;
var currentStaticRenderFns = staticRenderFns = [];
var prevOnceCount = onceCount;
onceCount = 0;
currentOptions = options;
warn$2 = options.warn || baseWarn;
transforms$1 = pluckModuleFunction(options.modules, 'transformCode');
dataGenFns = pluckModuleFunction(options.modules, 'genData');
platformDirectives = options.directives || {};
isPlatformReservedTag$1 = options.isReservedTag || no;
var code = ast ? genElement(ast) : '_c("div")';
staticRenderFns = prevStaticRenderFns;
onceCount = prevOnceCount;
return {
render: ("with(this){return " + code + "}"),
staticRenderFns: currentStaticRenderFns
}
}
function genElement (el) {
if (el.staticRoot && !el.staticProcessed) {
return genStatic(el)
} else if (el.once && !el.onceProcessed) {
return genOnce(el)
} else if (el.for && !el.forProcessed) {
return genFor(el)
} else if (el.if && !el.ifProcessed) {
return genIf(el)
} else if (el.tag === 'template' && !el.slotTarget) {
return genChildren(el) || 'void 0'
} else if (el.tag === 'slot') {
return genSlot(el)
} else {
// component or element
var code;
if (el.component) {
code = genComponent(el.component, el);
} else {
var data = el.plain ? undefined : genData(el);
var children = el.inlineTemplate ? null : genChildren(el, true);
code = "_c('" + (el.tag) + "'" + (data ? ("," + data) : '') + (children ? ("," + children) : '') + ")";
}
// module transforms
for (var i = 0; i < transforms$1.length; i++) {
code = transforms$1[i](el, code);
}
return code
}
}
// hoist static sub-trees out
function genStatic (el) {
el.staticProcessed = true;
staticRenderFns.push(("with(this){return " + (genElement(el)) + "}"));
return ("_m(" + (staticRenderFns.length - 1) + (el.staticInFor ? ',true' : '') + ")")
}
// v-once
function genOnce (el) {
el.onceProcessed = true;
if (el.if && !el.ifProcessed) {
return genIf(el)
} else if (el.staticInFor) {
var key = '';
var parent = el.parent;
while (parent) {
if (parent.for) {
key = parent.key;
break
}
parent = parent.parent;
}
if (!key) {
process.env.NODE_ENV !== 'production' && warn$2(
"v-once can only be used inside v-for that is keyed. "
);
return genElement(el)
}
return ("_o(" + (genElement(el)) + "," + (onceCount++) + (key ? ("," + key) : "") + ")")
} else {
return genStatic(el)
}
}
function genIf (el) {
el.ifProcessed = true; // avoid recursion
return genIfConditions(el.ifConditions.slice())
}
function genIfConditions (conditions) {
if (!conditions.length) {
return '_e()'
}
var condition = conditions.shift();
if (condition.exp) {
return ("(" + (condition.exp) + ")?" + (genTernaryExp(condition.block)) + ":" + (genIfConditions(conditions)))
} else {
return ("" + (genTernaryExp(condition.block)))
}
// v-if with v-once should generate code like (a)?_m(0):_m(1)
function genTernaryExp (el) {
return el.once ? genOnce(el) : genElement(el)
}
}
function genFor (el) {
var exp = el.for;
var alias = el.alias;
var iterator1 = el.iterator1 ? ("," + (el.iterator1)) : '';
var iterator2 = el.iterator2 ? ("," + (el.iterator2)) : '';
if (
process.env.NODE_ENV !== 'production' &&
maybeComponent(el) && el.tag !== 'slot' && el.tag !== 'template' && !el.key
) {
warn$2(
"<" + (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.",
true /* tip */
);
}
el.forProcessed = true; // avoid recursion
return "_l((" + exp + ")," +
"function(" + alias + iterator1 + iterator2 + "){" +
"return " + (genElement(el)) +
'})'
}
function genData (el) {
var data = '{';
// directives first.
// directives may mutate the el's other properties before they are generated.
var dirs = genDirectives(el);
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 < dataGenFns.length; i++) {
data += 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, warn$2)) + ",";
}
if (el.nativeEvents) {
data += (genHandlers(el.nativeEvents, true, warn$2)) + ",";
}
// slot target
if (el.slotTarget) {
data += "slot:" + (el.slotTarget) + ",";
}
// scoped slots
if (el.scopedSlots) {
data += (genScopedSlots(el.scopedSlots)) + ",";
}
// 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);
if (inlineTemplate) {
data += inlineTemplate + ",";
}
}
data = data.replace(/,$/, '') + '}';
// v-bind data wrap
if (el.wrapData) {
data = el.wrapData(data);
}
return data
}
function genDirectives (el) {
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 = platformDirectives[dir.name] || baseDirectives[dir.name];
if (gen) {
// compile-time directive that manipulates AST.
// returns true if it also needs a runtime counterpart.
needRuntime = !!gen(el, dir, warn$2);
}
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.arg) + "\"") : '') + (dir.modifiers ? (",modifiers:" + (JSON.stringify(dir.modifiers))) : '') + "},";
}
}
if (hasRuntime) {
return res.slice(0, -1) + ']'
}
}
function genInlineTemplate (el) {
var ast = el.children[0];
if (process.env.NODE_ENV !== 'production' && (
el.children.length > 1 || ast.type !== 1
)) {
warn$2('Inline-template components must have exactly one child element.');
}
if (ast.type === 1) {
var inlineRenderFns = generate(ast, currentOptions);
return ("inlineTemplate:{render:function(){" + (inlineRenderFns.render) + "},staticRenderFns:[" + (inlineRenderFns.staticRenderFns.map(function (code) { return ("function(){" + code + "}"); }).join(',')) + "]}")
}
}
function genScopedSlots (slots) {
return ("scopedSlots:_u([" + (Object.keys(slots).map(function (key) { return genScopedSlot(key, slots[key]); }).join(',')) + "])")
}
function genScopedSlot (key, el) {
return "[" + key + ",function(" + (String(el.attrsMap.scope)) + "){" +
"return " + (el.tag === 'template'
? genChildren(el) || 'void 0'
: genElement(el)) + "}]"
}
function genChildren (el, checkSkip) {
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') {
return genElement(el$1)
}
var normalizationType = checkSkip ? getNormalizationType(children) : 0;
return ("[" + (children.map(genNode).join(',')) + "]" + (normalizationType ? ("," + normalizationType) : ''))
}
}
// 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) {
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 maybeComponent (el) {
return !isPlatformReservedTag$1(el.tag)
}
function genNode (node) {
if (node.type === 1) {
return genElement(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 genSlot (el) {
var slotName = el.slotName || '"default"';
var children = genChildren(el);
var res = "_t(" + slotName + (children ? ("," + children) : '');
var attrs = el.attrs && ("{" + (el.attrs.map(function (a) { return ((camelize(a.name)) + ":" + (a.value)); }).join(',')) + "}");
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) {
var children = el.inlineTemplate ? null : genChildren(el, true);
return ("_c(" + componentName + "," + (genData(el)) + (children ? ("," + children) : '') + ")")
}
function genProps (props) {
var res = '';
for (var i = 0; i < props.length; i++) {
var prop = props[i];
res += "\"" + (prop.name) + "\":" + (transformSpecialNewlines(prop.value)) + ",";
}
return res.slice(0, -1)
}
// #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*\\([^\\)]*\\)');
// check valid identifier for v-for
var identRE = /[A-Za-z_$][\w$]*/;
// strip strings in expressions
var stripStringRE = /'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*\$\{|\}(?:[^`\\]|\\.)*`|`(?:[^`\\]|\\.)*`/g;
// detect problematic expressions in a template
function detectErrors (ast) {
var errors = [];
if (ast) {
checkNode(ast, errors);
}
return errors
}
function checkNode (node, errors) {
if (node.type === 1) {
for (var name in node.attrsMap) {
if (dirRE.test(name)) {
var value = node.attrsMap[name];
if (value) {
if (name === 'v-for') {
checkFor(node, ("v-for=\"" + value + "\""), errors);
} else if (onRE.test(name)) {
checkEvent(value, (name + "=\"" + value + "\""), errors);
} else {
checkExpression(value, (name + "=\"" + value + "\""), errors);
}
}
}
}
if (node.children) {
for (var i = 0; i < node.children.length; i++) {
checkNode(node.children[i], errors);
}
}
} else if (node.type === 2) {
checkExpression(node.expression, node.text, errors);
}
}
function checkEvent (exp, text, errors) {
var stipped = exp.replace(stripStringRE, '');
var keywordMatch = stipped.match(unaryOperatorsRE);
if (keywordMatch && stipped.charAt(keywordMatch.index - 1) !== '$') {
errors.push(
"avoid using JavaScript unary operator as property name: " +
"\"" + (keywordMatch[0]) + "\" in expression " + (text.trim())
);
}
checkExpression(exp, text, errors);
}
function checkFor (node, text, errors) {
checkExpression(node.for || '', text, errors);
checkIdentifier(node.alias, 'v-for alias', text, errors);
checkIdentifier(node.iterator1, 'v-for iterator', text, errors);
checkIdentifier(node.iterator2, 'v-for iterator', text, errors);
}
function checkIdentifier (ident, type, text, errors) {
if (typeof ident === 'string' && !identRE.test(ident)) {
errors.push(("invalid " + type + " \"" + ident + "\" in expression: " + (text.trim())));
}
}
function checkExpression (exp, text, errors) {
try {
new Function(("return " + exp));
} catch (e) {
var keywordMatch = exp.replace(stripStringRE, '').match(prohibitedKeywordRE);
if (keywordMatch) {
errors.push(
"avoid using JavaScript keyword as property name: " +
"\"" + (keywordMatch[0]) + "\" in expression " + (text.trim())
);
} else {
errors.push(("invalid expression: " + (text.trim())));
}
}
}
/* */
function baseCompile (
template,
options
) {
var ast = parse(template.trim(), options);
optimize(ast, options);
var code = generate(ast, options);
return {
ast: ast,
render: code.render,
staticRenderFns: code.staticRenderFns
}
}
function makeFunction (code, errors) {
try {
return new Function(code)
} catch (err) {
errors.push({ err: err, code: code });
return noop
}
}
function createCompiler (baseOptions) {
var functionCompileCache = Object.create(null);
function compile (
template,
options
) {
var finalOptions = Object.create(baseOptions);
var errors = [];
var tips = [];
finalOptions.warn = function (msg, tip$$1) {
(tip$$1 ? tips : errors).push(msg);
};
if (options) {
// 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),
options.directives
);
}
// copy other options
for (var key in options) {
if (key !== 'modules' && key !== 'directives') {
finalOptions[key] = options[key];
}
}
}
var compiled = baseCompile(template, finalOptions);
if (process.env.NODE_ENV !== 'production') {
errors.push.apply(errors, detectErrors(compiled.ast));
}
compiled.errors = errors;
compiled.tips = tips;
return compiled
}
function compileToFunctions (
template,
options,
vm
) {
options = options || {};
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production') {
// 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 (functionCompileCache[key]) {
return functionCompileCache[key]
}
// compile
var compiled = compile(template, options);
// check compilation errors/tips
if (process.env.NODE_ENV !== 'production') {
if (compiled.errors && compiled.errors.length) {
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) {
compiled.tips.forEach(function (msg) { return tip(msg, vm); });
}
}
// turn code into functions
var res = {};
var fnGenErrors = [];
res.render = makeFunction(compiled.render, fnGenErrors);
var l = compiled.staticRenderFns.length;
res.staticRenderFns = new Array(l);
for (var i = 0; i < l; i++) {
res.staticRenderFns[i] = makeFunction(compiled.staticRenderFns[i], 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 (process.env.NODE_ENV !== 'production') {
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 (functionCompileCache[key] = res)
}
return {
compile: compile,
compileToFunctions: compileToFunctions
}
}
/* */
function transformNode (el, options) {
var warn = options.warn || baseWarn;
var staticClass = getAndRemoveAttr(el, 'class');
var ref = parseStaticClass(staticClass, options);
var dynamic = ref.dynamic;
var classResult = ref.classResult;
if (process.env.NODE_ENV !== 'production' && dynamic && staticClass) {
warn(
"class=\"" + staticClass + "\": " +
'Interpolation inside attributes has been deprecated. ' +
'Use v-bind or the colon shorthand instead.'
);
}
if (!dynamic && classResult) {
el.staticClass = classResult;
}
var classBinding = getBindingAttr(el, 'class', false /* getStatic */);
if (classBinding) {
el.classBinding = classBinding;
} else if (dynamic) {
el.classBinding = classResult;
}
}
function genData$1 (el) {
var data = '';
if (el.staticClass) {
data += "staticClass:" + (el.staticClass) + ",";
}
if (el.classBinding) {
data += "class:" + (el.classBinding) + ",";
}
return data
}
function parseStaticClass (staticClass, options) {
// "a b c" -> ["a", "b", "c"] => staticClass: ["a", "b", "c"]
// "a {{x}} c" -> ["a", x, "c"] => classBinding: '["a", x, "c"]'
var dynamic = false;
var classResult = '';
if (staticClass) {
var classList = staticClass.trim().split(' ').map(function (name) {
var result = parseText(name, options.delimiters);
if (result) {
dynamic = true;
return result
}
return JSON.stringify(name)
});
if (classList.length) {
classResult = '[' + classList.join(',') + ']';
}
}
return { dynamic: dynamic, classResult: classResult }
}
var klass = {
staticKeys: ['staticClass'],
transformNode: transformNode,
genData: genData$1
};
/* */
var normalize = cached(camelize);
function transformNode$1 (el, options) {
var warn = options.warn || baseWarn;
var staticStyle = getAndRemoveAttr(el, 'style');
var ref = parseStaticStyle(staticStyle, options);
var dynamic = ref.dynamic;
var styleResult = ref.styleResult;
if (process.env.NODE_ENV !== 'production' && dynamic) {
warn(
"style=\"" + (String(staticStyle)) + "\": " +
'Interpolation inside attributes has been deprecated. ' +
'Use v-bind or the colon shorthand instead.'
);
}
if (!dynamic && styleResult) {
el.staticStyle = styleResult;
}
var styleBinding = getBindingAttr(el, 'style', false /* getStatic */);
if (styleBinding) {
el.styleBinding = styleBinding;
} else if (dynamic) {
el.styleBinding = styleResult;
}
}
function genData$2 (el) {
var data = '';
if (el.staticStyle) {
data += "staticStyle:" + (el.staticStyle) + ",";
}
if (el.styleBinding) {
data += "style:" + (el.styleBinding) + ",";
}
return data
}
function parseStaticStyle (staticStyle, options) {
// "width: 200px; height: 200px;" -> {width: 200, height: 200}
// "width: 200px; height: {{y}}" -> {width: 200, height: y}
var dynamic = false;
var styleResult = '';
if (staticStyle) {
var styleList = staticStyle.trim().split(';').map(function (style) {
var result = style.trim().split(':');
if (result.length !== 2) {
return
}
var key = normalize(result[0].trim());
var value = result[1].trim();
var dynamicValue = parseText(value, options.delimiters);
if (dynamicValue) {
dynamic = true;
return key + ':' + dynamicValue
}
return key + ':' + JSON.stringify(value)
}).filter(function (result) { return result; });
if (styleList.length) {
styleResult = '{' + styleList.join(',') + '}';
}
}
return { dynamic: dynamic, styleResult: styleResult }
}
var style = {
staticKeys: ['staticStyle'],
transformNode: transformNode$1,
genData: genData$2
};
/* */
var normalize$1 = cached(camelize);
function normalizeKeyName (str) {
if (str.match(/^v\-/)) {
return str.replace(/(v-[a-z\-]+\:)([a-z\-]+)$/i, function ($, directive, prop) {
return directive + normalize$1(prop)
})
}
return normalize$1(str)
}
function transformNode$2 (el, options) {
if (Array.isArray(el.attrsList)) {
el.attrsList.forEach(function (attr) {
if (attr.name && attr.name.match(/\-/)) {
var realName = normalizeKeyName(attr.name);
if (el.attrsMap) {
el.attrsMap[realName] = el.attrsMap[attr.name];
delete el.attrsMap[attr.name];
}
attr.name = realName;
}
});
}
}
var props = {
transformNode: transformNode$2
};
/* */
function preTransformNode (el, options) {
if (el.tag === 'cell' && !el.attrsList.some(function (item) { return item.name === 'append'; })) {
el.attrsMap.append = 'tree';
el.attrsList.push({ name: 'append', value: 'tree' });
}
if (el.attrsMap.append === 'tree') {
el.appendAsTree = true;
}
}
function genData$3 (el) {
return el.appendAsTree ? "appendAsTree:true," : ''
}
var append = {
staticKeys: ['appendAsTree'],
preTransformNode: preTransformNode,
genData: genData$3
};
var modules = [
klass,
style,
props,
append
];
/* */
function model (
el,
dir,
_warn
) {
if (el.tag === 'input' || el.tag === 'textarea') {
genDefaultModel(el, dir.value, dir.modifiers);
} else {
genComponentModel(el, dir.value, dir.modifiers);
}
}
function genDefaultModel (
el,
value,
modifiers
) {
var ref = modifiers || {};
var lazy = ref.lazy;
var trim = ref.trim;
var number = ref.number;
var event = lazy ? 'change' : 'input';
var valueExpression = "$event.target.attr.value" + (trim ? '.trim()' : '');
if (number) {
valueExpression = "_n(" + valueExpression + ")";
}
var code = genAssignmentCode(value, valueExpression);
addAttr(el, 'value', ("(" + value + ")"));
addHandler(el, event, code, null, true);
}
var directives = {
model: model
};
/* globals renderer */
var isReservedTag = makeMap(
'template,script,style,element,content,slot,link,meta,svg,view,' +
'a,div,img,image,text,span,richtext,input,switch,textarea,spinner,select,' +
'slider,slider-neighbor,indicator,trisition,trisition-group,canvas,' +
'list,cell,header,loading,loading-indicator,refresh,scrollable,scroller,' +
'video,web,embed,tabbar,tabheader,datepicker,timepicker,marquee,countdown',
true
);
// Elements that you can, intentionally, leave open (and which close themselves)
// more flexable than web
var canBeLeftOpenTag$1 = makeMap(
'web,spinner,switch,video,textarea,canvas,' +
'indicator,marquee,countdown',
true
);
var isUnaryTag$1 = makeMap(
'embed,img,image,input,link,meta',
true
);
function mustUseProp () { /* console.log('mustUseProp') */ }
function getTagNamespace () { /* console.log('getTagNamespace') */ }
/* */
var baseOptions = {
modules: modules,
directives: directives,
isUnaryTag: isUnaryTag$1,
mustUseProp: mustUseProp,
canBeLeftOpenTag: canBeLeftOpenTag$1,
isReservedTag: isReservedTag,
getTagNamespace: getTagNamespace,
preserveWhitespace: false,
staticKeys: genStaticKeys(modules)
};
var ref = createCompiler(baseOptions);
var compile = ref.compile;
exports.compile = compile;
node-vue-template-compiler-2.4.2+dfsg/packages/weex-template-compiler/index.js000066400000000000000000000012001361753775300274270ustar00rootroot00000000000000try {
var vueVersion = require('weex-vue-framework').version
} catch (e) {}
var packageName = require('./package.json').name
var packageVersion = require('./package.json').version
if (vueVersion && vueVersion !== packageVersion) {
throw new Error(
'\n\nVue packages version mismatch:\n\n' +
'- vue@' + vueVersion + '\n' +
'- ' + packageName + '@' + packageVersion + '\n\n' +
'This may cause things to work incorrectly. Make sure to use the same version for both.\n' +
'If you are using weex-vue-loader, re-installing them should bump ' + packageName + ' to the latest.\n'
)
}
module.exports = require('./build')
node-vue-template-compiler-2.4.2+dfsg/packages/weex-template-compiler/package.json000066400000000000000000000010241361753775300302540ustar00rootroot00000000000000{
"name": "weex-template-compiler",
"version": "2.1.9-weex.1",
"description": "Weex template compiler for Vue 2.0",
"main": "index.js",
"repository": {
"type": "git",
"url": "git+https://github.com/vuejs/vue.git"
},
"keywords": [
"vue",
"compiler"
],
"author": "Evan You",
"license": "MIT",
"bugs": {
"url": "https://github.com/vuejs/vue/issues"
},
"homepage": "https://github.com/vuejs/vue/tree/dev/packages/weex-template-compiler#readme",
"dependencies": {
"he": "^1.1.0"
}
}
node-vue-template-compiler-2.4.2+dfsg/packages/weex-vue-framework/000077500000000000000000000000001361753775300251405ustar00rootroot00000000000000node-vue-template-compiler-2.4.2+dfsg/packages/weex-vue-framework/README.md000066400000000000000000000002751361753775300264230ustar00rootroot00000000000000# weex-vue-framework
> This package is auto-generated. For pull requests please see [src/entries/weex-framework.js](https://github.com/vuejs/vue/blob/dev/src/platforms/weex/framework.js).
node-vue-template-compiler-2.4.2+dfsg/packages/weex-vue-framework/factory.js000066400000000000000000004753161361753775300271650ustar00rootroot00000000000000'use strict';
module.exports = function weexFactory (exports, renderer) {
/* */
// these helpers produces 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
}
/**
* Check if value is primitive
*/
function isPrimitive (value) {
return typeof value === 'string' || typeof value === 'number'
}
/**
* 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'
}
var toString = Object.prototype.toString;
/**
* 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]'
}
/**
* Convert a value to a string that is actually rendered.
*/
function _toString (val) {
return val == null
? ''
: typeof val === 'object'
? JSON.stringify(val, null, 2)
: String(val)
}
/**
* Convert a 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);
/**
* 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 the 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 = /([^-])([A-Z])/g;
var hyphenate = cached(function (str) {
return str
.replace(hyphenateRE, '$1-$2')
.replace(hyphenateRE, '$1-$2')
.toLowerCase()
});
/**
* Simple bind, faster than native
*/
function bind (fn, ctx) {
function boundFn (a) {
var l = arguments.length;
return l
? l > 1
? fn.apply(ctx, arguments)
: fn.call(ctx, a)
: fn.call(ctx)
}
// record original fn length
boundFn._length = fn.length;
return boundFn
}
/**
* 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
}
/**
* Perform no operation.
*/
function noop () {}
/**
* Always return false.
*/
var no = function () { return false; };
/**
* Return same value
*/
var identity = function (_) { return _; };
/**
* Generate a static keys string from compiler modules.
*/
/**
* Check if two values are loosely equal - that is,
* if they are plain objects, do they have the same shape?
*/
function looseEqual (a, b) {
var isObjectA = isObject(a);
var isObjectB = isObject(b);
if (isObjectA && isObjectB) {
try {
return JSON.stringify(a) === JSON.stringify(b)
} catch (e) {
// possible circular reference
return a === b
}
} else if (!isObjectA && !isObjectB) {
return String(a) === String(b)
} else {
return false
}
}
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'
];
/* */
var config = ({
/**
* Option merge strategies (used in core/util/options)
*/
optionMergeStrategies: Object.create(null),
/**
* Whether to suppress warnings.
*/
silent: false,
/**
* Show production mode tip message on boot?
*/
productionTip: process.env.NODE_ENV !== 'production',
/**
* Whether to enable devtools
*/
devtools: process.env.NODE_ENV !== 'production',
/**
* Whether to record perf
*/
performance: false,
/**
* Error handler for watcher errors
*/
errorHandler: null,
/**
* Ignore certain custom elements
*/
ignoredElements: [],
/**
* Custom user key aliases for v-on
*/
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,
/**
* Exposed for legacy reasons
*/
_lifecycleHooks: LIFECYCLE_HOOKS
});
/* */
var emptyObject = Object.freeze({});
/**
* 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 = /[^\w.$]/;
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
}
}
var warn = noop;
var tip = noop;
var formatComponentName;
if (process.env.NODE_ENV !== 'production') {
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) {
if (hasConsole && (!config.silent)) {
console.error("[Vue warn]: " + msg + (
vm ? generateComponentTrace(vm) : ''
));
}
};
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 '
'
}
var name = typeof vm === 'string'
? vm
: typeof vm === 'function' && vm.options
? vm.options.name
: vm._isVue
? vm.$options.name || vm.$options._componentTag
: vm.name;
var file = vm._isVue && vm.$options.__file;
if (!name && file) {
var match = file.match(/([^/\\]+)\.vue$/);
name = match && match[1];
}
return (
(name ? ("<" + (classify(name)) + ">") : "") +
(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
};
var 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)) + ")")
}
};
}
function handleError (err, vm, info) {
if (config.errorHandler) {
config.errorHandler.call(null, err, vm, info);
} else {
if (process.env.NODE_ENV !== 'production') {
warn(("Error in " + info + ": \"" + (err.toString()) + "\""), vm);
}
/* istanbul ignore else */
if (inBrowser && typeof console !== 'undefined') {
console.error(err);
} else {
throw err
}
}
}
/* */
/* globals MutationObserver */
// can we use __proto__?
var hasProto = '__proto__' in {};
// Browser environment sniffing
var inBrowser = typeof window !== 'undefined';
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;
var isIOS = UA && /iphone|ipad|ipod|ios/.test(UA);
var isChrome = UA && /chrome\/\d+/.test(UA) && !isEdge;
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 && typeof global !== 'undefined') {
// detect presence of vue-server-renderer and avoid
// Webpack shimming the process
_isServer = 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);
/**
* Defer a task to execute it asynchronously.
*/
var nextTick = (function () {
var callbacks = [];
var pending = false;
var timerFunc;
function nextTickHandler () {
pending = false;
var copies = callbacks.slice(0);
callbacks.length = 0;
for (var i = 0; i < copies.length; i++) {
copies[i]();
}
}
// 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 if */
if (typeof Promise !== 'undefined' && isNative(Promise)) {
var p = Promise.resolve();
var logError = function (err) { console.error(err); };
timerFunc = function () {
p.then(nextTickHandler).catch(logError);
// 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); }
};
} else if (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 IE11, iOS7, Android 4.4
var counter = 1;
var observer = new MutationObserver(nextTickHandler);
var textNode = document.createTextNode(String(counter));
observer.observe(textNode, {
characterData: true
});
timerFunc = function () {
counter = (counter + 1) % 2;
textNode.data = String(counter);
};
} else {
// fallback to setTimeout
/* istanbul ignore next */
timerFunc = function () {
setTimeout(nextTickHandler, 0);
};
}
return function queueNextTick (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();
}
if (!cb && typeof Promise !== 'undefined') {
return new Promise(function (resolve, reject) {
_resolve = resolve;
})
}
}
})();
var _Set;
/* istanbul ignore if */
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 = (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 uid$1 = 0;
/**
* A dep is an observable that can have multiple
* directives subscribing to it.
*/
var Dep = function Dep () {
this.id = uid$1++;
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();
for (var i = 0, l = subs.length; i < l; i++) {
subs[i].update();
}
};
// the current target watcher being evaluated.
// this is globally unique because there could be only one
// watcher being evaluated at any time.
Dep.target = null;
var targetStack = [];
function pushTarget (_target) {
if (Dep.target) { targetStack.push(Dep.target); }
Dep.target = _target;
}
function popTarget () {
Dep.target = targetStack.pop();
}
/*
* 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);[
'push',
'pop',
'shift',
'unshift',
'splice',
'sort',
'reverse'
]
.forEach(function (method) {
// cache original method
var original = arrayProto[method];
def(arrayMethods, method, function mutator () {
var arguments$1 = arguments;
// avoid leaking arguments:
// http://jsperf.com/closure-with-arguments
var i = arguments.length;
var args = new Array(i);
while (i--) {
args[i] = arguments$1[i];
}
var result = original.apply(this, args);
var ob = this.__ob__;
var inserted;
switch (method) {
case 'push':
inserted = args;
break
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);
/**
* By default, when a reactive property is set, the new value is
* also converted to become reactive. However when passing down props,
* we don't want to force conversion because the value may be a nested value
* under a frozen data structure. Converting it would defeat the optimization.
*/
var observerState = {
shouldConvert: true,
isSettingProps: false
};
/**
* Observer class that are attached to each observed
* object. Once attached, the observer converts target
* object's property keys into getter/setters that
* collect dependencies and dispatches updates.
*/
var Observer = function Observer (value) {
this.value = value;
this.dep = new Dep();
this.vmCount = 0;
def(value, '__ob__', this);
if (Array.isArray(value)) {
var augment = hasProto
? protoAugment
: copyAugment;
augment(value, arrayMethods, arrayKeys);
this.observeArray(value);
} else {
this.walk(value);
}
};
/**
* Walk through each property 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], 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 an 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 an 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)) {
return
}
var ob;
if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) {
ob = value.__ob__;
} else if (
observerState.shouldConvert &&
!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
) {
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;
var childOb = 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 (process.env.NODE_ENV !== 'production' && customSetter) {
customSetter();
}
if (setter) {
setter.call(obj, newVal);
} else {
val = newVal;
}
childOb = 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 (Array.isArray(target) && typeof key === 'number') {
target.length = Math.max(target.length, key);
target.splice(key, 1, val);
return val
}
if (hasOwn(target, key)) {
target[key] = val;
return val
}
var ob = (target ).__ob__;
if (target._isVue || (ob && ob.vmCount)) {
process.env.NODE_ENV !== 'production' && 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 (Array.isArray(target) && typeof key === 'number') {
target.splice(key, 1);
return
}
var ob = (target ).__ob__;
if (target._isVue || (ob && ob.vmCount)) {
process.env.NODE_ENV !== 'production' && 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
*/
if (process.env.NODE_ENV !== 'production') {
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 = Object.keys(from);
for (var i = 0; i < keys.length; i++) {
key = keys[i];
toVal = to[key];
fromVal = from[key];
if (!hasOwn(to, key)) {
set(to, key, fromVal);
} else if (isPlainObject(toVal) && isPlainObject(fromVal)) {
mergeData(toVal, fromVal);
}
}
return to
}
/**
* Data
*/
strats.data = function (
parentVal,
childVal,
vm
) {
if (!vm) {
// in a Vue.extend merge, both should be functions
if (!childVal) {
return parentVal
}
if (typeof childVal !== 'function') {
process.env.NODE_ENV !== 'production' && warn(
'The "data" option should be a function ' +
'that returns a per-instance value in component ' +
'definitions.',
vm
);
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(
childVal.call(this),
parentVal.call(this)
)
}
} else if (parentVal || childVal) {
return function mergedInstanceDataFn () {
// instance merge
var instanceData = typeof childVal === 'function'
? childVal.call(vm)
: childVal;
var defaultData = typeof parentVal === 'function'
? parentVal.call(vm)
: undefined;
if (instanceData) {
return mergeData(instanceData, defaultData)
} else {
return defaultData
}
}
}
};
/**
* Hooks and props are merged as arrays.
*/
function mergeHook (
parentVal,
childVal
) {
return childVal
? parentVal
? parentVal.concat(childVal)
: Array.isArray(childVal)
? childVal
: [childVal]
: parentVal
}
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) {
var res = Object.create(parentVal || null);
return childVal
? extend(res, childVal)
: 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) {
/* istanbul ignore if */
if (!childVal) { return Object.create(parentVal || null) }
if (!parentVal) { return childVal }
var ret = {};
extend(ret, parentVal);
for (var key in childVal) {
var parent = ret[key];
var child = childVal[key];
if (parent && !Array.isArray(parent)) {
parent = [parent];
}
ret[key] = parent
? parent.concat(child)
: [child];
}
return ret
};
/**
* Other object hashes.
*/
strats.props =
strats.methods =
strats.computed = function (parentVal, childVal) {
if (!childVal) { return Object.create(parentVal || null) }
if (!parentVal) { return childVal }
var ret = Object.create(null);
extend(ret, parentVal);
extend(ret, childVal);
return ret
};
/**
* Default strategy.
*/
var defaultStrat = function (parentVal, childVal) {
return childVal === undefined
? parentVal
: childVal
};
/**
* Validate component names
*/
function checkComponents (options) {
for (var key in options.components) {
var lower = key.toLowerCase();
if (isBuiltInTag(lower) || config.isReservedTag(lower)) {
warn(
'Do not use built-in or reserved HTML elements as component ' +
'id: ' + key
);
}
}
}
/**
* Ensure all props option syntax are normalized into the
* Object-based format.
*/
function normalizeProps (options) {
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 if (process.env.NODE_ENV !== 'production') {
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 };
}
}
options.props = res;
}
/**
* Normalize raw function directives into object format.
*/
function normalizeDirectives (options) {
var dirs = options.directives;
if (dirs) {
for (var key in dirs) {
var def = dirs[key];
if (typeof def === 'function') {
dirs[key] = { bind: def, update: def };
}
}
}
}
/**
* Merge two option objects into a new one.
* Core utility used in both instantiation and inheritance.
*/
function mergeOptions (
parent,
child,
vm
) {
if (process.env.NODE_ENV !== 'production') {
checkComponents(child);
}
if (typeof child === 'function') {
child = child.options;
}
normalizeProps(child);
normalizeDirectives(child);
var extendsFrom = child.extends;
if (extendsFrom) {
parent = mergeOptions(parent, extendsFrom, 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 (process.env.NODE_ENV !== 'production' && 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];
// handle boolean props
if (isType(Boolean, prop.type)) {
if (absent && !hasOwn(prop, 'default')) {
value = false;
} else if (!isType(String, prop.type) && (value === '' || value === hyphenate(key))) {
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 prevShouldConvert = observerState.shouldConvert;
observerState.shouldConvert = true;
observe(value);
observerState.shouldConvert = prevShouldConvert;
}
if (process.env.NODE_ENV !== 'production') {
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 (process.env.NODE_ENV !== 'production' && 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(
'Invalid prop: type check failed for prop "' + name + '".' +
' Expected ' + expectedTypes.map(capitalize).join(', ') +
', got ' + Object.prototype.toString.call(value).slice(8, -1) + '.',
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)) {
valid = typeof value === expectedType.toLowerCase();
} 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 isType (type, fn) {
if (!Array.isArray(fn)) {
return getType(fn) === getType(type)
}
for (var i = 0, len = fn.length; i < len; i++) {
if (getType(fn[i]) === getType(type)) {
return true
}
}
/* istanbul ignore next */
return false
}
/* not type checking this file because flow doesn't play well with Proxy */
var initProxy;
if (process.env.NODE_ENV !== 'production') {
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 to declare reactive data " +
"properties in the data option.",
target
);
};
var hasProxy =
typeof Proxy !== 'undefined' &&
Proxy.toString().match(/native code/);
if (hasProxy) {
var isBuiltInModifier = makeMap('stop,prevent,self,ctrl,shift,alt,meta');
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) || key.charAt(0) === '_';
if (!has && !isAllowed) {
warnNonPresent(target, key);
}
return has || !isAllowed
}
};
var getHandler = {
get: function get (target, key) {
if (typeof key === 'string' && !(key in target)) {
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 mark;
var measure;
if (process.env.NODE_ENV !== 'production') {
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);
};
}
}
/* */
var VNode = function VNode (
tag,
data,
children,
text,
elm,
context,
componentOptions
) {
this.tag = tag;
this.data = data;
this.children = children;
this.text = text;
this.elm = elm;
this.ns = undefined;
this.context = context;
this.functionalContext = 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;
};
var prototypeAccessors = { child: {} };
// 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 () {
var node = new VNode();
node.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,
vnode.children,
vnode.text,
vnode.elm,
vnode.context,
vnode.componentOptions
);
cloned.ns = vnode.ns;
cloned.isStatic = vnode.isStatic;
cloned.key = vnode.key;
cloned.isCloned = true;
return cloned
}
function cloneVNodes (vnodes) {
var len = vnodes.length;
var res = new Array(len);
for (var i = 0; i < len; i++) {
res[i] = cloneVNode(vnodes[i]);
}
return res
}
/* */
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) {
function invoker () {
var arguments$1 = arguments;
var fns = invoker.fns;
if (Array.isArray(fns)) {
for (var i = 0; i < fns.length; i++) {
fns[i].apply(null, arguments$1);
}
} else {
// return handler return value for single handlers
return fns.apply(null, arguments)
}
}
invoker.fns = fns;
return invoker
}
function updateListeners (
on,
oldOn,
add,
remove$$1,
vm
) {
var name, cur, old, event;
for (name in on) {
cur = on[name];
old = oldOn[name];
event = normalizeEvent(name);
if (isUndef(cur)) {
process.env.NODE_ENV !== 'production' && warn(
"Invalid handler for event \"" + (event.name) + "\": got " + String(cur),
vm
);
} else if (isUndef(old)) {
if (isUndef(cur.fns)) {
cur = on[name] = createFnInvoker(cur);
}
add(event.name, cur, event.once, event.capture, event.passive);
} 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) {
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);
if (process.env.NODE_ENV !== 'production') {
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. 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. , , 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 normalizeArrayChildren (children, nestedIndex) {
var res = [];
var i, c, last;
for (i = 0; i < children.length; i++) {
c = children[i];
if (isUndef(c) || typeof c === 'boolean') { continue }
last = res[res.length - 1];
// nested
if (Array.isArray(c)) {
res.push.apply(res, normalizeArrayChildren(c, ((nestedIndex || '') + "_" + i)));
} else if (isPrimitive(c)) {
if (isDef(last) && isDef(last.text)) {
(last).text += String(c);
} else if (c !== '') {
// convert primitive to vnode
res.push(createTextVNode(c));
}
} else {
if (isDef(c.text) && isDef(last) && isDef(last.text)) {
res[res.length - 1] = createTextVNode(last.text + c.text);
} else {
// default key for nested array children (likely generated by v-for)
if (isDef(c.tag) && isUndef(c.key) && isDef(nestedIndex)) {
c.key = "__vlist" + ((nestedIndex)) + "_" + i + "__";
}
res.push(c);
}
}
}
return res
}
/* */
function ensureCtor (comp, base) {
return isObject(comp)
? base.extend(comp)
: comp
}
function resolveAsyncComponent (
factory,
baseCtor,
context
) {
if (isTrue(factory.error) && isDef(factory.errorComp)) {
return factory.errorComp
}
if (isDef(factory.resolved)) {
return factory.resolved
}
if (isTrue(factory.loading) && isDef(factory.loadingComp)) {
return factory.loadingComp
}
if (isDef(factory.contexts)) {
// already pending
factory.contexts.push(context);
} else {
var contexts = factory.contexts = [context];
var sync = true;
var forceRender = function () {
for (var i = 0, l = contexts.length; i < l; i++) {
contexts[i].$forceUpdate();
}
};
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();
}
});
var reject = once(function (reason) {
process.env.NODE_ENV !== 'production' && warn(
"Failed to resolve async component: " + (String(factory)) +
(reason ? ("\nReason: " + reason) : '')
);
if (isDef(factory.errorComp)) {
factory.error = true;
forceRender();
}
});
var res = factory(resolve, reject);
if (isObject(res)) {
if (typeof res.then === 'function') {
// () => Promise
if (isUndef(factory.resolved)) {
res.then(resolve, reject);
}
} else if (isDef(res.component) && typeof res.component.then === 'function') {
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 {
setTimeout(function () {
if (isUndef(factory.resolved) && isUndef(factory.error)) {
factory.loading = true;
forceRender();
}
}, res.delay || 200);
}
}
if (isDef(res.timeout)) {
setTimeout(function () {
reject(
process.env.NODE_ENV !== 'production'
? ("timeout (" + (res.timeout) + "ms)")
: null
);
}, res.timeout);
}
}
}
sync = false;
// return in case resolved synchronously
return factory.loading
? factory.loadingComp
: factory.resolved
}
}
/* */
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)) {
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, once$$1) {
if (once$$1) {
target.$once(event, fn);
} else {
target.$on(event, fn);
}
}
function remove$1 (event, fn) {
target.$off(event, fn);
}
function updateComponentListeners (
vm,
listeners,
oldListeners
) {
target = vm;
updateListeners(listeners, oldListeners || {}, add, remove$1, vm);
}
function eventsMixin (Vue) {
var hookRE = /^hook:/;
Vue.prototype.$on = function (event, fn) {
var this$1 = this;
var vm = this;
if (Array.isArray(event)) {
for (var i = 0, l = event.length; i < l; i++) {
this$1.$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 this$1 = this;
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++) {
this$1.$off(event[i$1], fn);
}
return vm
}
// specific event
var cbs = vm._events[event];
if (!cbs) {
return vm
}
if (arguments.length === 1) {
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;
if (process.env.NODE_ENV !== 'production') {
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);
for (var i = 0, l = cbs.length; i < l; i++) {
cbs[i].apply(vm, args);
}
}
return vm
};
}
/* */
/**
* Runtime helper for resolving raw children VNodes into a slot object.
*/
function resolveSlots (
children,
context
) {
var slots = {};
if (!children) {
return slots
}
var defaultSlot = [];
for (var i = 0, l = children.length; i < l; i++) {
var child = children[i];
// named slots should only be respected if the vnode was rendered in the
// same context.
if ((child.context === context || child.functionalContext === context) &&
child.data && child.data.slot != null) {
var name = child.data.slot;
var slot = (slots[name] || (slots[name] = []));
if (child.tag === 'template') {
slot.push.apply(slot, child.children);
} else {
slot.push(child);
}
} else {
defaultSlot.push(child);
}
}
// ignore whitespace
if (!defaultSlot.every(isWhitespace)) {
slots.default = defaultSlot;
}
return slots
}
function isWhitespace (node) {
return node.isComment || node.text === ' '
}
function resolveScopedSlots (
fns
) {
var res = {};
for (var i = 0; i < fns.length; i++) {
res[fns[i][0]] = fns[i][1];
}
return res
}
/* */
var activeInstance = null;
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;
if (vm._isMounted) {
callHook(vm, 'beforeUpdate');
}
var prevEl = vm.$el;
var prevVnode = vm._vnode;
var prevActiveInstance = activeInstance;
activeInstance = 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 */,
vm.$options._parentElm,
vm.$options._refElm
);
} else {
// updates
vm.$el = vm.__patch__(prevVnode, vnode);
}
activeInstance = prevActiveInstance;
// 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;
}
// remove reference to DOM nodes (prevents leak)
vm.$options._parentElm = vm.$options._refElm = null;
};
}
function mountComponent (
vm,
el,
hydrating
) {
vm.$el = el;
if (!vm.$options.render) {
vm.$options.render = createEmptyVNode;
if (process.env.NODE_ENV !== 'production') {
/* 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 (process.env.NODE_ENV !== 'production' && 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((name + " render"), startTag, endTag);
mark(startTag);
vm._update(vnode, hydrating);
mark(endTag);
measure((name + " patch"), startTag, endTag);
};
} else {
updateComponent = function () {
vm._update(vm._render(), hydrating);
};
}
vm._watcher = new Watcher(vm, updateComponent, noop);
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
) {
// determine whether component has slot children
// we need to do this before overwriting $options._renderChildren
var hasChildren = !!(
renderChildren || // has new static slots
vm.$options._renderChildren || // has old static slots
parentVnode.data.scopedSlots || // has new scoped slots
vm.$scopedSlots !== emptyObject // has old scoped slots
);
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 props
if (propsData && vm.$options.props) {
observerState.shouldConvert = false;
if (process.env.NODE_ENV !== 'production') {
observerState.isSettingProps = true;
}
var props = vm._props;
var propKeys = vm.$options._propKeys || [];
for (var i = 0; i < propKeys.length; i++) {
var key = propKeys[i];
props[key] = validateProp(key, vm.$options.props, propsData, vm);
}
observerState.shouldConvert = true;
if (process.env.NODE_ENV !== 'production') {
observerState.isSettingProps = false;
}
// keep a copy of raw propsData
vm.$options.propsData = propsData;
}
// update listeners
if (listeners) {
var oldListeners = vm.$options._parentListeners;
vm.$options._parentListeners = listeners;
updateComponentListeners(vm, listeners, oldListeners);
}
// resolve slots + force update if has children
if (hasChildren) {
vm.$slots = resolveSlots(renderChildren, parentVnode.context);
vm.$forceUpdate();
}
}
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) {
var handlers = vm.$options[hook];
if (handlers) {
for (var i = 0, j = handlers.length; i < j; i++) {
try {
handlers[i].call(vm);
} catch (e) {
handleError(e, vm, (hook + " hook"));
}
}
}
if (vm._hasHookEvent) {
vm.$emit('hook:' + hook);
}
}
/* */
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 () {
queue.length = activatedChildren.length = 0;
has = {};
if (process.env.NODE_ENV !== 'production') {
circular = {};
}
waiting = flushing = false;
}
/**
* Flush both queues and run the watchers.
*/
function flushSchedulerQueue () {
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];
id = watcher.id;
has[id] = null;
watcher.run();
// in dev build, check and stop circular updates.
if (process.env.NODE_ENV !== 'production' && 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);
callUpdateHooks(updatedQueue);
// devtool hook
/* istanbul ignore if */
if (devtools && config.devtools) {
devtools.emit('flush');
}
}
function callUpdateHooks (queue) {
var i = queue.length;
while (i--) {
var watcher = queue[i];
var vm = watcher.vm;
if (vm._watcher === watcher && vm._isMounted) {
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 >= 0 && queue[i].id > watcher.id) {
i--;
}
queue.splice(Math.max(i, index) + 1, 0, watcher);
}
// queue the flush
if (!waiting) {
waiting = true;
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
) {
this.vm = vm;
vm._watchers.push(this);
// options
if (options) {
this.deep = !!options.deep;
this.user = !!options.user;
this.lazy = !!options.lazy;
this.sync = !!options.sync;
} 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 = process.env.NODE_ENV !== 'production'
? expOrFn.toString()
: '';
// parse expression for getter
if (typeof expOrFn === 'function') {
this.getter = expOrFn;
} else {
this.getter = parsePath(expOrFn);
if (!this.getter) {
this.getter = function () {};
process.env.NODE_ENV !== 'production' && 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;
if (this.user) {
try {
value = this.getter.call(vm, vm);
} catch (e) {
handleError(e, vm, ("getter for watcher \"" + (this.expression) + "\""));
}
} else {
value = this.getter.call(vm, vm);
}
// "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 this$1 = this;
var i = this.deps.length;
while (i--) {
var dep = this$1.deps[i];
if (!this$1.newDepIds.has(dep.id)) {
dep.removeSub(this$1);
}
}
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 this$1 = this;
var i = this.deps.length;
while (i--) {
this$1.deps[i].depend();
}
};
/**
* Remove self from all dependencies' subscriber list.
*/
Watcher.prototype.teardown = function teardown () {
var this$1 = this;
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$1.deps[i].removeSub(this$1);
}
this.active = false;
}
};
/**
* Recursively traverse an object to evoke all converted
* getters, so that every nested property inside the object
* is collected as a "deep" dependency.
*/
var seenObjects = new _Set();
function traverse (val) {
seenObjects.clear();
_traverse(val, seenObjects);
}
function _traverse (val, seen) {
var i, keys;
var isA = Array.isArray(val);
if ((!isA && !isObject(val)) || !Object.isExtensible(val)) {
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 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) { initWatch(vm, opts.watch); }
}
var isReservedProp = {
key: 1,
ref: 1,
slot: 1
};
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
observerState.shouldConvert = isRoot;
var loop = function ( key ) {
keys.push(key);
var value = validateProp(key, propsOptions, propsData, vm);
/* istanbul ignore else */
if (process.env.NODE_ENV !== 'production') {
if (isReservedProp[key] || config.isReservedAttr(key)) {
warn(
("\"" + key + "\" is a reserved attribute and cannot be used as component prop."),
vm
);
}
defineReactive$$1(props, key, value, function () {
if (vm.$parent && !observerState.isSettingProps) {
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
);
}
});
} else {
defineReactive$$1(props, key, value);
}
// 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 );
observerState.shouldConvert = true;
}
function initData (vm) {
var data = vm.$options.data;
data = vm._data = typeof data === 'function'
? getData(data, vm)
: data || {};
if (!isPlainObject(data)) {
data = {};
process.env.NODE_ENV !== 'production' && 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 i = keys.length;
while (i--) {
if (props && hasOwn(props, keys[i])) {
process.env.NODE_ENV !== 'production' && warn(
"The data property \"" + (keys[i]) + "\" is already declared as a prop. " +
"Use prop default value instead.",
vm
);
} else if (!isReserved(keys[i])) {
proxy(vm, "_data", keys[i]);
}
}
// observe data
observe(data, true /* asRootData */);
}
function getData (data, vm) {
try {
return data.call(vm)
} catch (e) {
handleError(e, vm, "data()");
return {}
}
}
var computedWatcherOptions = { lazy: true };
function initComputed (vm, computed) {
var watchers = vm._computedWatchers = Object.create(null);
for (var key in computed) {
var userDef = computed[key];
var getter = typeof userDef === 'function' ? userDef : userDef.get;
if (process.env.NODE_ENV !== 'production') {
if (getter === undefined) {
warn(
("No getter function has been defined for computed property \"" + key + "\"."),
vm
);
getter = noop;
}
}
// create internal watcher for the computed property.
watchers[key] = new Watcher(vm, getter, 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 (process.env.NODE_ENV !== 'production') {
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) {
if (typeof userDef === 'function') {
sharedPropertyDefinition.get = createComputedGetter(key);
sharedPropertyDefinition.set = noop;
} else {
sharedPropertyDefinition.get = userDef.get
? userDef.cache !== false
? createComputedGetter(key)
: userDef.get
: noop;
sharedPropertyDefinition.set = userDef.set
? userDef.set
: noop;
}
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 initMethods (vm, methods) {
var props = vm.$options.props;
for (var key in methods) {
vm[key] = methods[key] == null ? noop : bind(methods[key], vm);
if (process.env.NODE_ENV !== 'production') {
if (methods[key] == null) {
warn(
"method \"" + key + "\" has an undefined value 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
);
}
}
}
}
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, key, handler) {
var options;
if (isPlainObject(handler)) {
options = handler;
handler = handler.handler;
}
if (typeof handler === 'string') {
handler = vm[handler];
}
vm.$watch(key, 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 };
if (process.env.NODE_ENV !== 'production') {
dataDef.set = function (newData) {
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;
options = options || {};
options.user = true;
var watcher = new Watcher(vm, expOrFn, cb, options);
if (options.immediate) {
cb.call(vm, watcher.value);
}
return function unwatchFn () {
watcher.teardown();
}
};
}
/* */
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) {
Object.keys(result).forEach(function (key) {
/* istanbul ignore else */
if (process.env.NODE_ENV !== 'production') {
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
);
});
} else {
defineReactive$$1(vm, key, result[key]);
}
});
}
}
function resolveInject (inject, vm) {
if (inject) {
// inject is :any because flow is not smart enough to figure out cached
// isArray here
var isArray = Array.isArray(inject);
var result = Object.create(null);
var keys = isArray
? inject
: hasSymbol
? Reflect.ownKeys(inject)
: Object.keys(inject);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var provideKey = isArray ? key : inject[key];
var source = vm;
while (source) {
if (source._provided && provideKey in source._provided) {
result[key] = source._provided[provideKey];
break
}
source = source.$parent;
}
}
return result
}
}
/* */
function createFunctionalComponent (
Ctor,
propsData,
data,
context,
children
) {
var props = {};
var propOptions = Ctor.options.props;
if (isDef(propOptions)) {
for (var key in propOptions) {
props[key] = validateProp(key, propOptions, propsData);
}
} else {
if (isDef(data.attrs)) { mergeProps(props, data.attrs); }
if (isDef(data.props)) { mergeProps(props, data.props); }
}
// ensure the createElement function in functional components
// gets a unique context - this is necessary for correct named slot check
var _context = Object.create(context);
var h = function (a, b, c, d) { return createElement(_context, a, b, c, d, true); };
var vnode = Ctor.options.render.call(null, h, {
data: data,
props: props,
children: children,
parent: context,
listeners: data.on || {},
injections: resolveInject(Ctor.options.inject, context),
slots: function () { return resolveSlots(children, context); }
});
if (vnode instanceof VNode) {
vnode.functionalContext = context;
if (data.slot) {
(vnode.data || (vnode.data = {})).slot = data.slot;
}
}
return vnode
}
function mergeProps (to, from) {
for (var key in from) {
to[camelize(key)] = from[key];
}
}
/* */
// hooks to be invoked on component VNodes during patch
var componentVNodeHooks = {
init: function init (
vnode,
hydrating,
parentElm,
refElm
) {
if (!vnode.componentInstance || vnode.componentInstance._isDestroyed) {
var child = vnode.componentInstance = createComponentInstanceForVnode(
vnode,
activeInstance,
parentElm,
refElm
);
child.$mount(hydrating ? vnode.elm : undefined, hydrating);
} else if (vnode.data.keepAlive) {
// kept-alive components, treat as a patch
var mountedNode = vnode; // work around flow
componentVNodeHooks.prepatch(mountedNode, mountedNode);
}
},
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') {
if (process.env.NODE_ENV !== 'production') {
warn(("Invalid Component definition: " + (String(Ctor))), context);
}
return
}
// async component
if (isUndef(Ctor.cid)) {
Ctor = resolveAsyncComponent(Ctor, baseCtor, context);
if (Ctor === undefined) {
// return nothing if this is indeed an async component
// wait for the callback to trigger parent update.
return
}
}
// resolve constructor options in case global mixins are applied after
// component constructor creation
resolveConstructorOptions(Ctor);
data = data || {};
// 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
data.on = data.nativeOn;
if (isTrue(Ctor.options.abstract)) {
// abstract components do not keep anything
// other than props & listeners
data = {};
}
// merge component management hooks onto the placeholder node
mergeHooks(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 }
);
return vnode
}
function createComponentInstanceForVnode (
vnode, // we know it's MountedComponentVNode but flow doesn't
parent, // activeInstance in lifecycle state
parentElm,
refElm
) {
var vnodeComponentOptions = vnode.componentOptions;
var options = {
_isComponent: true,
parent: parent,
propsData: vnodeComponentOptions.propsData,
_componentTag: vnodeComponentOptions.tag,
_parentVnode: vnode,
_parentListeners: vnodeComponentOptions.listeners,
_renderChildren: vnodeComponentOptions.children,
_parentElm: parentElm || null,
_refElm: refElm || null
};
// check inline-template render functions
var inlineTemplate = vnode.data.inlineTemplate;
if (isDef(inlineTemplate)) {
options.render = inlineTemplate.render;
options.staticRenderFns = inlineTemplate.staticRenderFns;
}
return new vnodeComponentOptions.Ctor(options)
}
function mergeHooks (data) {
if (!data.hook) {
data.hook = {};
}
for (var i = 0; i < hooksToMerge.length; i++) {
var key = hooksToMerge[i];
var fromParent = data.hook[key];
var ours = componentVNodeHooks[key];
data.hook[key] = fromParent ? mergeHook$1(ours, fromParent) : ours;
}
}
function mergeHook$1 (one, two) {
return function (a, b, c, d) {
one(a, b, c, d);
two(a, b, c, d);
}
}
// 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.props || (data.props = {}))[prop] = data.model.value;
var on = data.on || (data.on = {});
if (isDef(on[event])) {
on[event] = [data.model.callback].concat(on[event]);
} else {
on[event] = data.model.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__)) {
process.env.NODE_ENV !== 'production' && 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()
}
if (!tag) {
// in case of component :is set to falsy value
return createEmptyVNode()
}
// 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 = config.getTagNamespace(tag);
if (config.isReservedTag(tag)) {
// platform built-in elements
vnode = new VNode(
config.parsePlatformTagName(tag), data, children,
undefined, undefined, context
);
} else if (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 (vnode !== undefined) {
if (ns) { applyNS(vnode, ns); }
return vnode
} else {
return createEmptyVNode()
}
}
function applyNS (vnode, ns) {
vnode.ns = ns;
if (vnode.tag === 'foreignObject') {
// use default namespace inside foreignObject
return
}
if (Array.isArray(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)) {
applyNS(child, ns);
}
}
}
}
/* */
/**
* 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)) {
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);
}
}
return ret
}
/* */
/**
* Runtime helper for rendering
*/
function renderSlot (
name,
fallback,
props,
bindObject
) {
var scopedSlotFn = this.$scopedSlots[name];
if (scopedSlotFn) { // scoped slot
props = props || {};
if (bindObject) {
extend(props, bindObject);
}
return scopedSlotFn(props) || fallback
} else {
var slotNodes = this.$slots[name];
// warn duplicate slot usage
if (slotNodes && process.env.NODE_ENV !== 'production') {
slotNodes._rendered && warn(
"Duplicate presence of slot \"" + name + "\" found in the same render tree " +
"- this will likely cause render errors.",
this
);
slotNodes._rendered = true;
}
return slotNodes || fallback
}
}
/* */
/**
* Runtime helper for resolving filters
*/
function resolveFilter (id) {
return resolveAsset(this.$options, 'filters', id, true) || identity
}
/* */
/**
* Runtime helper for checking keyCodes from config.
*/
function checkKeyCodes (
eventKeyCode,
key,
builtInAlias
) {
var keyCodes = config.keyCodes[key] || builtInAlias;
if (Array.isArray(keyCodes)) {
return keyCodes.indexOf(eventKeyCode) === -1
} else {
return keyCodes !== eventKeyCode
}
}
/* */
/**
* Runtime helper for merging v-bind="object" into a VNode's data.
*/
function bindObjectProps (
data,
tag,
value,
asProp
) {
if (value) {
if (!isObject(value)) {
process.env.NODE_ENV !== 'production' && warn(
'v-bind without argument expects an Object or Array value',
this
);
} else {
if (Array.isArray(value)) {
value = toObject(value);
}
var hash;
for (var key in value) {
if (key === 'class' || key === 'style') {
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 = {});
}
if (!(key in hash)) {
hash[key] = value[key];
}
}
}
}
return data
}
/* */
/**
* Runtime helper for rendering static trees.
*/
function renderStatic (
index,
isInFor
) {
var tree = this._staticTrees[index];
// if has already-rendered static tree and not inside v-for,
// we can reuse the same tree by doing a shallow clone.
if (tree && !isInFor) {
return Array.isArray(tree)
? cloneVNodes(tree)
: cloneVNode(tree)
}
// otherwise, render a fresh tree.
tree = this._staticTrees[index] =
this.$options.staticRenderFns[index].call(this._renderProxy);
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 initRender (vm) {
vm._vnode = null; // the root of the child tree
vm._staticTrees = null;
var parentVnode = vm.$vnode = vm.$options._parentVnode; // the placeholder node in parent tree
var renderContext = parentVnode && parentVnode.context;
vm.$slots = resolveSlots(vm.$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); };
}
function renderMixin (Vue) {
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 staticRenderFns = ref.staticRenderFns;
var _parentVnode = ref._parentVnode;
if (vm._isMounted) {
// clone slot nodes on re-renders
for (var key in vm.$slots) {
vm.$slots[key] = cloneVNodes(vm.$slots[key]);
}
}
vm.$scopedSlots = (_parentVnode && _parentVnode.data.scopedSlots) || emptyObject;
if (staticRenderFns && !vm._staticTrees) {
vm._staticTrees = [];
}
// 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 {
vnode = render.call(vm._renderProxy, vm.$createElement);
} catch (e) {
handleError(e, vm, "render function");
// return error render result,
// or previous vnode to prevent render error causing blank component
/* istanbul ignore else */
if (process.env.NODE_ENV !== 'production') {
vnode = vm.$options.renderError
? vm.$options.renderError.call(vm._renderProxy, vm.$createElement, e)
: vm._vnode;
} else {
vnode = vm._vnode;
}
}
// return empty vnode in case the render function errored out
if (!(vnode instanceof VNode)) {
if (process.env.NODE_ENV !== 'production' && 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
};
// internal render helpers.
// these are exposed on the instance prototype to reduce generated render
// code size.
Vue.prototype._o = markOnce;
Vue.prototype._n = toNumber;
Vue.prototype._s = _toString;
Vue.prototype._l = renderList;
Vue.prototype._t = renderSlot;
Vue.prototype._q = looseEqual;
Vue.prototype._i = looseIndexOf;
Vue.prototype._m = renderStatic;
Vue.prototype._f = resolveFilter;
Vue.prototype._k = checkKeyCodes;
Vue.prototype._b = bindObjectProps;
Vue.prototype._v = createTextVNode;
Vue.prototype._e = createEmptyVNode;
Vue.prototype._u = resolveScopedSlots;
}
/* */
var uid = 0;
function initMixin (Vue) {
Vue.prototype._init = function (options) {
var vm = this;
// a uid
vm._uid = uid++;
var startTag, endTag;
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
startTag = "vue-perf-init:" + (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 */
if (process.env.NODE_ENV !== 'production') {
initProxy(vm);
} else {
vm._renderProxy = 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 (process.env.NODE_ENV !== 'production' && config.performance && mark) {
vm._name = formatComponentName(vm, false);
mark(endTag);
measure(((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.
opts.parent = options.parent;
opts.propsData = options.propsData;
opts._parentVnode = options._parentVnode;
opts._parentListeners = options._parentListeners;
opts._renderChildren = options._renderChildren;
opts._componentTag = options._componentTag;
opts._parentElm = options._parentElm;
opts._refElm = options._refElm;
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 extended = Ctor.extendOptions;
var sealed = Ctor.sealedOptions;
for (var key in latest) {
if (latest[key] !== sealed[key]) {
if (!modified) { modified = {}; }
modified[key] = dedupe(latest[key], extended[key], sealed[key]);
}
}
return modified
}
function dedupe (latest, extended, sealed) {
// compare latest and sealed to ensure lifecycle hooks won't be duplicated
// between merges
if (Array.isArray(latest)) {
var res = [];
sealed = Array.isArray(sealed) ? sealed : [sealed];
extended = Array.isArray(extended) ? extended : [extended];
for (var i = 0; i < latest.length; i++) {
// push original options and not sealed options to exclude duplicated options
if (extended.indexOf(latest[i]) >= 0 || sealed.indexOf(latest[i]) < 0) {
res.push(latest[i]);
}
}
return res
} else {
return latest
}
}
function Vue$2 (options) {
if (process.env.NODE_ENV !== 'production' &&
!(this instanceof Vue$2)) {
warn('Vue is a constructor and should be called with the `new` keyword');
}
this._init(options);
}
initMixin(Vue$2);
stateMixin(Vue$2);
eventsMixin(Vue$2);
lifecycleMixin(Vue$2);
renderMixin(Vue$2);
/* */
function initUse (Vue) {
Vue.use = function (plugin) {
/* istanbul ignore if */
if (plugin.installed) {
return
}
// 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);
}
plugin.installed = true;
return this
};
}
/* */
function initMixin$1 (Vue) {
Vue.mixin = function (mixin) {
this.options = mergeOptions(this.options, mixin);
};
}
/* */
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 (process.env.NODE_ENV !== 'production') {
if (!/^[a-zA-Z][\w-]*$/.test(name)) {
warn(
'Invalid component name: "' + name + '". Component names ' +
'can only contain alphanumeric characters and the hyphen, ' +
'and must start with a letter.'
);
}
}
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 (process.env.NODE_ENV !== 'production') {
if (type === 'component' && config.isReservedTag(id)) {
warn(
'Do not use built-in or reserved HTML elements as component ' +
'id: ' + 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
}
};
});
}
/* */
var patternTypes = [String, RegExp];
function getComponentName (opts) {
return opts && (opts.Ctor.options.name || opts.tag)
}
function matches (pattern, name) {
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 (cache, current, filter) {
for (var key in cache) {
var cachedNode = cache[key];
if (cachedNode) {
var name = getComponentName(cachedNode.componentOptions);
if (name && !filter(name)) {
if (cachedNode !== current) {
pruneCacheEntry(cachedNode);
}
cache[key] = null;
}
}
}
}
function pruneCacheEntry (vnode) {
if (vnode) {
vnode.componentInstance.$destroy();
}
}
var KeepAlive = {
name: 'keep-alive',
abstract: true,
props: {
include: patternTypes,
exclude: patternTypes
},
created: function created () {
this.cache = Object.create(null);
},
destroyed: function destroyed () {
var this$1 = this;
for (var key in this$1.cache) {
pruneCacheEntry(this$1.cache[key]);
}
},
watch: {
include: function include (val) {
pruneCache(this.cache, this._vnode, function (name) { return matches(val, name); });
},
exclude: function exclude (val) {
pruneCache(this.cache, this._vnode, function (name) { return !matches(val, name); });
}
},
render: function render () {
var vnode = getFirstComponentChild(this.$slots.default);
var componentOptions = vnode && vnode.componentOptions;
if (componentOptions) {
// check pattern
var name = getComponentName(componentOptions);
if (name && (
(this.include && !matches(this.include, name)) ||
(this.exclude && matches(this.exclude, name))
)) {
return vnode
}
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 (this.cache[key]) {
vnode.componentInstance = this.cache[key].componentInstance;
} else {
this.cache[key] = vnode;
}
vnode.data.keepAlive = true;
}
return vnode
}
};
var builtInComponents = {
KeepAlive: KeepAlive
};
/* */
function initGlobalAPI (Vue) {
// config
var configDef = {};
configDef.get = function () { return config; };
if (process.env.NODE_ENV !== 'production') {
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;
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$2);
Object.defineProperty(Vue$2.prototype, '$isServer', {
get: isServerRendering
});
Vue$2.version = '2.3.0-beta.1';
/* globals renderer */
// renderer is injected by weex factory wrapper
var namespaceMap = {};
function createElement$1 (tagName) {
return new renderer.Element(tagName)
}
function createElementNS (namespace, tagName) {
return new renderer.Element(namespace + ':' + tagName)
}
function createTextNode (text) {
return new renderer.TextNode(text)
}
function createComment (text) {
return new renderer.Comment(text)
}
function insertBefore (node, target, before) {
if (target.nodeType === 3) {
if (node.type === 'text') {
node.setAttr('value', target.text);
target.parentNode = node;
} else {
var text = createElement$1('text');
text.setAttr('value', target.text);
node.insertBefore(text, before);
}
return
}
node.insertBefore(target, before);
}
function removeChild (node, child) {
if (child.nodeType === 3) {
node.setAttr('value', '');
return
}
node.removeChild(child);
}
function appendChild (node, child) {
if (child.nodeType === 3) {
if (node.type === 'text') {
node.setAttr('value', child.text);
child.parentNode = node;
} else {
var text = createElement$1('text');
text.setAttr('value', child.text);
node.appendChild(text);
}
return
}
node.appendChild(child);
}
function parentNode (node) {
return node.parentNode
}
function nextSibling (node) {
return node.nextSibling
}
function tagName (node) {
return node.type
}
function setTextContent (node, text) {
node.parentNode.setAttr('value', text);
}
function setAttribute (node, key, val) {
node.setAttr(key, val);
}
var nodeOps = Object.freeze({
namespaceMap: namespaceMap,
createElement: createElement$1,
createElementNS: createElementNS,
createTextNode: createTextNode,
createComment: createComment,
insertBefore: insertBefore,
removeChild: removeChild,
appendChild: appendChild,
parentNode: parentNode,
nextSibling: nextSibling,
tagName: tagName,
setTextContent: setTextContent,
setAttribute: setAttribute
});
/* */
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 (!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].indexOf(ref) < 0) {
refs[key].push(ref);
} else {
refs[key] = [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)
)
}
// Some browsers do not support dynamically changing type for
// so they need to be treated as different nodes
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
}
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);
}
}
var inPre = 0;
function createElm (vnode, insertedVnodeQueue, parentElm, refElm, nested) {
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 (process.env.NODE_ENV !== 'production') {
if (data && data.pre) {
inPre++;
}
if (
!inPre &&
!vnode.ns &&
!(config.ignoredElements.length && config.ignoredElements.indexOf(tag) > -1) &&
config.isUnknownElement(tag)
) {
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 */
{
// in Weex, the default insertion order is parent-first.
// List items can be optimized to use children-first insertion
// with append="tree".
var appendAsTree = isDef(data) && isTrue(data.appendAsTree);
if (!appendAsTree) {
if (isDef(data)) {
invokeCreateHooks(vnode, insertedVnodeQueue);
}
insert(parentElm, vnode.elm, refElm);
}
createChildren(vnode, children, insertedVnodeQueue);
if (appendAsTree) {
if (isDef(data)) {
invokeCreateHooks(vnode, insertedVnodeQueue);
}
insert(parentElm, vnode.elm, refElm);
}
}
if (process.env.NODE_ENV !== 'production' && data && data.pre) {
inPre--;
}
} 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 */, parentElm, refElm);
}
// 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);
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.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) {
if (isDef(parent)) {
if (isDef(ref)) {
if (ref.parentNode === parent) {
nodeOps.insertBefore(parent, elm, ref);
}
} else {
nodeOps.appendChild(parent, elm);
}
}
}
function createChildren (vnode, children, insertedVnodeQueue) {
if (Array.isArray(children)) {
for (var i = 0; i < children.length; ++i) {
createElm(children[i], insertedVnodeQueue, vnode.elm, null, true);
}
} else if (isPrimitive(vnode.text)) {
nodeOps.appendChild(vnode.elm, nodeOps.createTextNode(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;
var ancestor = vnode;
while (ancestor) {
if (isDef(i = ancestor.context) && isDef(i = i.$options._scopeId)) {
nodeOps.setAttribute(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 &&
isDef(i = i.$options._scopeId)) {
nodeOps.setAttribute(vnode.elm, i, '');
}
}
function addVnodes (parentElm, refElm, vnodes, startIdx, endIdx, insertedVnodeQueue) {
for (; startIdx <= endIdx; ++startIdx) {
createElm(vnodes[startIdx], insertedVnodeQueue, parentElm, refElm);
}
}
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, elmToMove, refElm;
// removeOnly is a special flag used only by
// to ensure removed elements stay in correct relative positions
// during leaving transitions
var canMove = !removeOnly;
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);
oldStartVnode = oldCh[++oldStartIdx];
newStartVnode = newCh[++newStartIdx];
} else if (sameVnode(oldEndVnode, newEndVnode)) {
patchVnode(oldEndVnode, newEndVnode, insertedVnodeQueue);
oldEndVnode = oldCh[--oldEndIdx];
newEndVnode = newCh[--newEndIdx];
} else if (sameVnode(oldStartVnode, newEndVnode)) { // Vnode moved right
patchVnode(oldStartVnode, newEndVnode, insertedVnodeQueue);
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);
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] : null;
if (isUndef(idxInOld)) { // New element
createElm(newStartVnode, insertedVnodeQueue, parentElm, oldStartVnode.elm);
newStartVnode = newCh[++newStartIdx];
} else {
elmToMove = oldCh[idxInOld];
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production' && !elmToMove) {
warn(
'It seems there are duplicate keys that is causing an update error. ' +
'Make sure each v-for item has a unique key.'
);
}
if (sameVnode(elmToMove, newStartVnode)) {
patchVnode(elmToMove, newStartVnode, insertedVnodeQueue);
oldCh[idxInOld] = undefined;
canMove && nodeOps.insertBefore(parentElm, newStartVnode.elm, oldStartVnode.elm);
newStartVnode = newCh[++newStartIdx];
} else {
// same key but different element. treat as new element
createElm(newStartVnode, insertedVnodeQueue, parentElm, oldStartVnode.elm);
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 patchVnode (oldVnode, vnode, insertedVnodeQueue, removeOnly) {
if (oldVnode === vnode) {
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.elm = oldVnode.elm;
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 elm = vnode.elm = oldVnode.elm;
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)) {
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 bailed = 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
var isRenderedModule = makeMap('attrs,style,class,staticClass,staticStyle,key');
// Note: this is a browser-only function so we can assume elms are DOM nodes.
function hydrate (elm, vnode, insertedVnodeQueue) {
if (process.env.NODE_ENV !== 'production') {
if (!assertNodeMatch(elm, vnode)) {
return false
}
}
vnode.elm = elm;
var tag = vnode.tag;
var data = vnode.data;
var children = vnode.children;
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 {
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)) {
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) {
if (process.env.NODE_ENV !== 'production' &&
typeof console !== 'undefined' &&
!bailed) {
bailed = true;
console.warn('Parent: ', elm);
console.warn('Mismatching childNodes vs. VNodes: ', elm.childNodes, children);
}
return false
}
}
}
if (isDef(data)) {
for (var key in data) {
if (!isRenderedModule(key)) {
invokeCreateHooks(vnode, insertedVnodeQueue);
break
}
}
}
} else if (elm.data !== vnode.text) {
elm.data = vnode.text;
}
return true
}
function assertNodeMatch (node, vnode) {
if (isDef(vnode.tag)) {
return (
vnode.tag.indexOf('vue-component') === 0 ||
vnode.tag.toLowerCase() === (node.tagName && node.tagName.toLowerCase())
)
} else {
return node.nodeType === (vnode.isComment ? 8 : 3)
}
}
return function patch (oldVnode, vnode, hydrating, removeOnly, parentElm, refElm) {
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, parentElm, refElm);
} else {
var isRealElement = isDef(oldVnode.nodeType);
if (!isRealElement && sameVnode(oldVnode, vnode)) {
// patch existing root node
patchVnode(oldVnode, vnode, insertedVnodeQueue, 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 if (process.env.NODE_ENV !== 'production') {
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 ' +
', or missing . 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$1 = nodeOps.parentNode(oldElm);
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$1,
nodeOps.nextSibling(oldElm)
);
if (isDef(vnode.parent)) {
// component root element replaced.
// update parent placeholder node element, recursively
var ancestor = vnode.parent;
while (ancestor) {
ancestor.elm = vnode.elm;
ancestor = ancestor.parent;
}
if (isPatchable(vnode)) {
for (var i = 0; i < cbs.create.length; ++i) {
cbs.create[i](emptyNode, vnode.parent);
}
}
}
if (isDef(parentElm$1)) {
removeVnodes(parentElm$1, [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;
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.data.hook || (vnode.data.hook = {}), 'insert', callInsert);
} else {
callInsert();
}
}
if (dirsWithPostpatch.length) {
mergeVNodeHook(vnode.data.hook || (vnode.data.hook = {}), '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) {
return res
}
var i, dir;
for (i = 0; i < dirs.length; i++) {
dir = dirs[i];
if (!dir.modifiers) {
dir.modifiers = emptyModifiers;
}
res[getRawDirName(dir)] = dir;
dir.def = resolveAsset(vm.$options, 'directives', dir.name, true);
}
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) {
if (!oldVnode.data.attrs && !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 (attrs.__ob__) {
attrs = vnode.data.attrs = extend({}, attrs);
}
for (key in attrs) {
cur = attrs[key];
old = oldAttrs[key];
if (old !== cur) {
elm.setAttr(key, cur);
}
}
for (key in oldAttrs) {
if (attrs[key] == null) {
elm.setAttr(key);
}
}
}
var attrs = {
create: updateAttrs,
update: updateAttrs
};
/* */
function updateClass (oldVnode, vnode) {
var el = vnode.elm;
var ctx = vnode.context;
var data = vnode.data;
var oldData = oldVnode.data;
if (!data.staticClass && !data.class &&
(!oldData || (!oldData.staticClass && !oldData.class))) {
return
}
var oldClassList = [];
// unlike web, weex vnode staticClass is an Array
var oldStaticClass = oldData.staticClass;
if (oldStaticClass) {
oldClassList.push.apply(oldClassList, oldStaticClass);
}
if (oldData.class) {
oldClassList.push.apply(oldClassList, oldData.class);
}
var classList = [];
// unlike web, weex vnode staticClass is an Array
var staticClass = data.staticClass;
if (staticClass) {
classList.push.apply(classList, staticClass);
}
if (data.class) {
classList.push.apply(classList, data.class);
}
var style = getStyle(oldClassList, classList, ctx);
for (var key in style) {
el.setStyle(key, style[key]);
}
}
function getStyle (oldClassList, classList, ctx) {
// style is a weex-only injected object
// compiled from ',
state: { a: 1 }
}
renderer.renderToString(new Vue({
template: '
hi
'
}), context, (err, res) => {
expect(err).toBeNull()
expect(res).toContain(
`${context.head}${context.styles}` +
`hi
` +
`` +
``
)
done()
})
})
it('renderToString with interpolation', done => {
const renderer = createRenderer({
template: interpolateTemplate
})
const context = {
title: '',
snippet: 'foo
',
head: ' ',
styles: '',
state: { a: 1 }
}
renderer.renderToString(new Vue({
template: 'hi
'
}), context, (err, res) => {
expect(err).toBeNull()
expect(res).toContain(
`` +
// double mustache should be escaped
`<script>hacks</script> ` +
`${context.head}${context.styles}` +
`hi
` +
`` +
// triple should be raw
`foo
` +
``
)
done()
})
})
it('renderToStream', done => {
const renderer = createRenderer({
template: defaultTemplate
})
const context = {
head: ' ',
styles: '',
state: { a: 1 }
}
const stream = renderer.renderToStream(new Vue({
template: 'hi
'
}), context)
let res = ''
stream.on('data', chunk => {
res += chunk
})
stream.on('end', () => {
expect(res).toContain(
`${context.head}${context.styles}` +
`hi
` +
`` +
``
)
done()
})
})
it('renderToStream with interpolation', done => {
const renderer = createRenderer({
template: interpolateTemplate
})
const context = {
title: '',
snippet: 'foo
',
head: ' ',
styles: '',
state: { a: 1 }
}
const stream = renderer.renderToStream(new Vue({
template: 'hi
'
}), context)
let res = ''
stream.on('data', chunk => {
res += chunk
})
stream.on('end', () => {
expect(res).toContain(
`` +
// double mustache should be escaped
`<script>hacks</script> ` +
`${context.head}${context.styles}` +
`hi
` +
`` +
// triple should be raw
`foo
` +
``
)
done()
})
})
it('bundleRenderer + renderToString', done => {
createBundleRenderer('app.js', {
asBundle: true,
template: defaultTemplate
}, renderer => {
const context = {
head: ' ',
styles: '',
state: { a: 1 },
url: '/test'
}
renderer.renderToString(context, (err, res) => {
expect(err).toBeNull()
expect(res).toContain(
`${context.head}${context.styles}` +
`/test
` +
`` +
``
)
expect(context.msg).toBe('hello')
done()
})
})
})
it('bundleRenderer + renderToStream', done => {
createBundleRenderer('app.js', {
asBundle: true,
template: defaultTemplate
}, renderer => {
const context = {
head: ' ',
styles: '',
state: { a: 1 },
url: '/test'
}
const stream = renderer.renderToStream(context)
let res = ''
stream.on('data', chunk => {
res += chunk.toString()
})
stream.on('end', () => {
expect(res).toContain(
`${context.head}${context.styles}` +
`/test
` +
`` +
``
)
expect(context.msg).toBe('hello')
done()
})
})
})
const expectedHTMLWithManifest = (options = {}) =>
`` +
// used chunks should have preload
` ` +
` ` +
` ` +
` ` +
// images and fonts are only preloaded when explicitly asked for
(options.preloadOtherAssets ? ` ` : ``) +
(options.preloadOtherAssets ? ` ` : ``) +
// unused chunks should have prefetch
` ` +
// css assets should be loaded
` ` +
`` +
`async test.woff2 test.png
` +
// state should be inlined before scripts
`` +
// manifest chunk should be first
`` +
// async chunks should be before main chunk
`` +
`` +
``
createClientManifestAssertions(true)
createClientManifestAssertions(false)
function createClientManifestAssertions (runInNewContext) {
it('bundleRenderer + renderToString + clientManifest ()', done => {
createRendererWithManifest('split.js', { runInNewContext }, renderer => {
renderer.renderToString({ state: { a: 1 }}, (err, res) => {
expect(err).toBeNull()
expect(res).toContain(expectedHTMLWithManifest())
done()
})
})
})
it('bundleRenderer + renderToStream + clientManifest + shouldPreload', done => {
createRendererWithManifest('split.js', {
runInNewContext,
shouldPreload: (file, type) => {
if (type === 'image' || type === 'script' || type === 'font' || type === 'style') {
return true
}
}
}, renderer => {
const stream = renderer.renderToStream({ state: { a: 1 }})
let res = ''
stream.on('data', chunk => {
res += chunk.toString()
})
stream.on('end', () => {
expect(res).toContain(expectedHTMLWithManifest({
preloadOtherAssets: true
}))
done()
})
})
})
it('bundleRenderer + renderToString + clientManifest + inject: false', done => {
createRendererWithManifest('split.js', {
runInNewContext,
template: `` +
`{{{ renderResourceHints() }}}{{{ renderStyles() }}}` +
`{{{ renderState({ windowKey: '__FOO__', contextKey: 'foo' }) }}}{{{ renderScripts() }}}` +
``,
inject: false
}, renderer => {
const context = { foo: { a: 1 }}
renderer.renderToString(context, (err, res) => {
expect(err).toBeNull()
expect(res).toContain(expectedHTMLWithManifest({
stateKey: '__FOO__'
}))
done()
})
})
})
it('bundleRenderer + renderToString + clientManifest + no template', done => {
createRendererWithManifest('split.js', {
runInNewContext,
template: null
}, renderer => {
const context = { foo: { a: 1 }}
renderer.renderToString(context, (err, res) => {
expect(err).toBeNull()
const customOutput =
`${
context.renderResourceHints() +
context.renderStyles()
}${
res +
context.renderState({
windowKey: '__FOO__',
contextKey: 'foo'
}) +
context.renderScripts()
}`
expect(customOutput).toContain(expectedHTMLWithManifest({
stateKey: '__FOO__'
}))
done()
})
})
})
it('whitespace insensitive interpolation', done => {
const interpolateTemplate = `{{title}} {{{snippet}}}`
const renderer = createRenderer({
template: interpolateTemplate
})
const context = {
title: '',
snippet: 'foo
',
head: ' ',
styles: '',
state: { a: 1 }
}
renderer.renderToString(new Vue({
template: 'hi
'
}), context, (err, res) => {
expect(err).toBeNull()
expect(res).toContain(
`` +
// double mustache should be escaped
`<script>hacks</script> ` +
`${context.head}${context.styles}` +
`hi
` +
`` +
// triple should be raw
`foo
` +
``
)
done()
})
})
}
})
node-vue-template-compiler-2.4.2+dfsg/test/unit/000077500000000000000000000000001361753775300215605ustar00rootroot00000000000000node-vue-template-compiler-2.4.2+dfsg/test/unit/.eslintrc000066400000000000000000000003321361753775300234020ustar00rootroot00000000000000{
"env": {
"jasmine": true
},
"globals": {
"waitForUpdate": true,
"triggerEvent": true,
"createTextVNode": true
},
"plugins": ["jasmine"],
"rules": {
"jasmine/no-focused-tests": 2
}
}
node-vue-template-compiler-2.4.2+dfsg/test/unit/features/000077500000000000000000000000001361753775300233765ustar00rootroot00000000000000node-vue-template-compiler-2.4.2+dfsg/test/unit/features/component/000077500000000000000000000000001361753775300254005ustar00rootroot00000000000000node-vue-template-compiler-2.4.2+dfsg/test/unit/features/component/component-async.spec.js000066400000000000000000000217141361753775300320110ustar00rootroot00000000000000import Vue from 'vue'
import { Promise } from 'es6-promise'
describe('Component async', () => {
it('normal', done => {
const vm = new Vue({
template: '
',
components: {
test: (resolve) => {
setTimeout(() => {
resolve({
template: 'hi
'
})
// wait for parent update
Vue.nextTick(next)
}, 0)
}
}
}).$mount()
expect(vm.$el.innerHTML).toBe('')
expect(vm.$children.length).toBe(0)
function next () {
expect(vm.$el.innerHTML).toBe('hi
')
expect(vm.$children.length).toBe(1)
done()
}
})
it('resolve ES module default', done => {
const vm = new Vue({
template: '
',
components: {
test: (resolve) => {
setTimeout(() => {
resolve({
__esModule: true,
default: {
template: 'hi
'
}
})
// wait for parent update
Vue.nextTick(next)
}, 0)
}
}
}).$mount()
expect(vm.$el.innerHTML).toBe('')
expect(vm.$children.length).toBe(0)
function next () {
expect(vm.$el.innerHTML).toBe('hi
')
expect(vm.$children.length).toBe(1)
done()
}
})
it('as root', done => {
const vm = new Vue({
template: ' ',
components: {
test: resolve => {
setTimeout(() => {
resolve({
template: 'hi
'
})
// wait for parent update
Vue.nextTick(next)
}, 0)
}
}
}).$mount()
expect(vm.$el.nodeType).toBe(8)
expect(vm.$children.length).toBe(0)
function next () {
expect(vm.$el.nodeType).toBe(1)
expect(vm.$el.outerHTML).toBe('hi
')
expect(vm.$children.length).toBe(1)
done()
}
})
it('dynamic', done => {
var vm = new Vue({
template: ' ',
data: {
view: 'view-a'
},
components: {
'view-a': resolve => {
setTimeout(() => {
resolve({
template: 'A
'
})
Vue.nextTick(step1)
}, 0)
},
'view-b': resolve => {
setTimeout(() => {
resolve({
template: 'B
'
})
Vue.nextTick(step2)
}, 0)
}
}
}).$mount()
var aCalled = false
function step1 () {
// ensure A is resolved only once
expect(aCalled).toBe(false)
aCalled = true
expect(vm.$el.tagName).toBe('DIV')
expect(vm.$el.textContent).toBe('A')
vm.view = 'view-b'
}
function step2 () {
expect(vm.$el.tagName).toBe('P')
expect(vm.$el.textContent).toBe('B')
vm.view = 'view-a'
waitForUpdate(function () {
expect(vm.$el.tagName).toBe('DIV')
expect(vm.$el.textContent).toBe('A')
}).then(done)
}
})
it('warn reject', () => {
new Vue({
template: ' ',
components: {
test: (resolve, reject) => {
reject('nooooo')
}
}
}).$mount()
expect('Reason: nooooo').toHaveBeenWarned()
})
it('with v-for', done => {
const vm = new Vue({
template: '
',
data: {
list: [1, 2, 3]
},
components: {
test: resolve => {
setTimeout(() => {
resolve({
props: ['n'],
template: '{{n}}
'
})
Vue.nextTick(next)
}, 0)
}
}
}).$mount()
function next () {
expect(vm.$el.innerHTML).toBe('1
2
3
')
done()
}
})
it('returning Promise', done => {
const vm = new Vue({
template: '
',
components: {
test: () => {
return new Promise(resolve => {
setTimeout(() => {
resolve({
template: 'hi
'
})
// wait for promise resolve and then parent update
Promise.resolve().then(() => {
Vue.nextTick(next)
})
}, 0)
})
}
}
}).$mount()
expect(vm.$el.innerHTML).toBe('')
expect(vm.$children.length).toBe(0)
function next () {
expect(vm.$el.innerHTML).toBe('hi
')
expect(vm.$children.length).toBe(1)
done()
}
})
describe('loading/error/timeout', () => {
it('with loading component', done => {
const vm = new Vue({
template: `
`,
components: {
test: () => ({
component: new Promise(resolve => {
setTimeout(() => {
resolve({ template: 'hi
' })
// wait for promise resolve and then parent update
Promise.resolve().then(() => {
Vue.nextTick(next)
})
}, 50)
}),
loading: { template: `loading
` },
delay: 1
})
}
}).$mount()
expect(vm.$el.innerHTML).toBe('')
let loadingAsserted = false
setTimeout(() => {
Vue.nextTick(() => {
loadingAsserted = true
expect(vm.$el.textContent).toBe('loading')
})
}, 1)
function next () {
expect(loadingAsserted).toBe(true)
expect(vm.$el.textContent).toBe('hi')
done()
}
})
it('with loading component (0 delay)', done => {
const vm = new Vue({
template: `
`,
components: {
test: () => ({
component: new Promise(resolve => {
setTimeout(() => {
resolve({ template: 'hi
' })
// wait for promise resolve and then parent update
Promise.resolve().then(() => {
Vue.nextTick(next)
})
}, 50)
}),
loading: { template: `loading
` },
delay: 0
})
}
}).$mount()
expect(vm.$el.textContent).toBe('loading')
function next () {
expect(vm.$el.textContent).toBe('hi')
done()
}
})
it('with error component', done => {
const vm = new Vue({
template: `
`,
components: {
test: () => ({
component: new Promise((resolve, reject) => {
setTimeout(() => {
reject()
// wait for promise resolve and then parent update
Promise.resolve().then(() => {
Vue.nextTick(next)
})
}, 50)
}),
loading: { template: `loading
` },
error: { template: `error
` },
delay: 0
})
}
}).$mount()
expect(vm.$el.textContent).toBe('loading')
function next () {
expect(`Failed to resolve async component`).toHaveBeenWarned()
expect(vm.$el.textContent).toBe('error')
done()
}
})
it('with error component + timeout', done => {
const vm = new Vue({
template: `
`,
components: {
test: () => ({
component: new Promise((resolve, reject) => {
setTimeout(() => {
resolve({ template: 'hi
' })
// wait for promise resolve and then parent update
Promise.resolve().then(() => {
Vue.nextTick(next)
})
}, 50)
}),
loading: { template: `loading
` },
error: { template: `error
` },
delay: 0,
timeout: 1
})
}
}).$mount()
expect(vm.$el.textContent).toBe('loading')
setTimeout(() => {
Vue.nextTick(() => {
expect(`Failed to resolve async component`).toHaveBeenWarned()
expect(vm.$el.textContent).toBe('error')
})
}, 1)
function next () {
expect(vm.$el.textContent).toBe('error') // late resolve ignored
done()
}
})
it('should not trigger timeout if resolved', done => {
const vm = new Vue({
template: `
`,
components: {
test: () => ({
component: new Promise((resolve, reject) => {
setTimeout(() => {
resolve({ template: 'hi
' })
}, 10)
}),
error: { template: `error
` },
timeout: 20
})
}
}).$mount()
setTimeout(() => {
expect(vm.$el.textContent).toBe('hi')
expect(`Failed to resolve async component`).not.toHaveBeenWarned()
done()
}, 50)
})
})
})
node-vue-template-compiler-2.4.2+dfsg/test/unit/features/component/component-keep-alive.spec.js000066400000000000000000000640761361753775300327260ustar00rootroot00000000000000import Vue from 'vue'
import injectStyles from '../transition/inject-styles'
import { isIE9 } from 'core/util/env'
import { nextFrame } from 'web/runtime/transition-util'
describe('Component keep-alive', () => {
const { duration, buffer } = injectStyles()
let components, one, two, el
beforeEach(() => {
one = {
template: 'one
',
created: jasmine.createSpy('one created'),
mounted: jasmine.createSpy('one mounted'),
activated: jasmine.createSpy('one activated'),
deactivated: jasmine.createSpy('one deactivated'),
destroyed: jasmine.createSpy('one destroyed')
}
two = {
template: 'two
',
created: jasmine.createSpy('two created'),
mounted: jasmine.createSpy('two mounted'),
activated: jasmine.createSpy('two activated'),
deactivated: jasmine.createSpy('two deactivated'),
destroyed: jasmine.createSpy('two destroyed')
}
components = {
one,
two
}
el = document.createElement('div')
document.body.appendChild(el)
})
function assertHookCalls (component, callCounts) {
expect([
component.created.calls.count(),
component.mounted.calls.count(),
component.activated.calls.count(),
component.deactivated.calls.count(),
component.destroyed.calls.count()
]).toEqual(callCounts)
}
it('should work', done => {
const vm = new Vue({
template: `
`,
data: {
view: 'one',
ok: true
},
components
}).$mount()
expect(vm.$el.textContent).toBe('one')
assertHookCalls(one, [1, 1, 1, 0, 0])
assertHookCalls(two, [0, 0, 0, 0, 0])
vm.view = 'two'
waitForUpdate(() => {
expect(vm.$el.textContent).toBe('two')
assertHookCalls(one, [1, 1, 1, 1, 0])
assertHookCalls(two, [1, 1, 1, 0, 0])
vm.view = 'one'
}).then(() => {
expect(vm.$el.textContent).toBe('one')
assertHookCalls(one, [1, 1, 2, 1, 0])
assertHookCalls(two, [1, 1, 1, 1, 0])
vm.view = 'two'
}).then(() => {
expect(vm.$el.textContent).toBe('two')
assertHookCalls(one, [1, 1, 2, 2, 0])
assertHookCalls(two, [1, 1, 2, 1, 0])
vm.ok = false // teardown
}).then(() => {
expect(vm.$el.textContent).toBe('')
assertHookCalls(one, [1, 1, 2, 2, 1])
assertHookCalls(two, [1, 1, 2, 2, 1])
}).then(done)
})
it('should invoke hooks on the entire sub tree', done => {
one.template = ''
one.components = { two }
const vm = new Vue({
template: `
`,
data: {
ok: true
},
components
}).$mount()
expect(vm.$el.textContent).toBe('two')
assertHookCalls(one, [1, 1, 1, 0, 0])
assertHookCalls(two, [1, 1, 1, 0, 0])
vm.ok = false
waitForUpdate(() => {
expect(vm.$el.textContent).toBe('')
assertHookCalls(one, [1, 1, 1, 1, 0])
assertHookCalls(two, [1, 1, 1, 1, 0])
vm.ok = true
}).then(() => {
expect(vm.$el.textContent).toBe('two')
assertHookCalls(one, [1, 1, 2, 1, 0])
assertHookCalls(two, [1, 1, 2, 1, 0])
vm.ok = false
}).then(() => {
expect(vm.$el.textContent).toBe('')
assertHookCalls(one, [1, 1, 2, 2, 0])
assertHookCalls(two, [1, 1, 2, 2, 0])
}).then(done)
})
it('should handle nested keep-alive hooks properly', done => {
one.template = ' '
one.data = () => ({ ok: true })
one.components = { two }
const vm = new Vue({
template: `
`,
data: {
ok: true
},
components
}).$mount()
var oneInstance = vm.$refs.one
expect(vm.$el.textContent).toBe('two')
assertHookCalls(one, [1, 1, 1, 0, 0])
assertHookCalls(two, [1, 1, 1, 0, 0])
vm.ok = false
waitForUpdate(() => {
expect(vm.$el.textContent).toBe('')
assertHookCalls(one, [1, 1, 1, 1, 0])
assertHookCalls(two, [1, 1, 1, 1, 0])
}).then(() => {
vm.ok = true
}).then(() => {
expect(vm.$el.textContent).toBe('two')
assertHookCalls(one, [1, 1, 2, 1, 0])
assertHookCalls(two, [1, 1, 2, 1, 0])
}).then(() => {
// toggle sub component when activated
oneInstance.ok = false
}).then(() => {
expect(vm.$el.textContent).toBe('')
assertHookCalls(one, [1, 1, 2, 1, 0])
assertHookCalls(two, [1, 1, 2, 2, 0])
}).then(() => {
oneInstance.ok = true
}).then(() => {
expect(vm.$el.textContent).toBe('two')
assertHookCalls(one, [1, 1, 2, 1, 0])
assertHookCalls(two, [1, 1, 3, 2, 0])
}).then(() => {
vm.ok = false
}).then(() => {
expect(vm.$el.textContent).toBe('')
assertHookCalls(one, [1, 1, 2, 2, 0])
assertHookCalls(two, [1, 1, 3, 3, 0])
}).then(() => {
// toggle sub component when parent is deactivated
oneInstance.ok = false
}).then(() => {
expect(vm.$el.textContent).toBe('')
assertHookCalls(one, [1, 1, 2, 2, 0])
assertHookCalls(two, [1, 1, 3, 3, 0]) // should not be affected
}).then(() => {
oneInstance.ok = true
}).then(() => {
expect(vm.$el.textContent).toBe('')
assertHookCalls(one, [1, 1, 2, 2, 0])
assertHookCalls(two, [1, 1, 3, 3, 0]) // should not be affected
}).then(() => {
vm.ok = true
}).then(() => {
expect(vm.$el.textContent).toBe('two')
assertHookCalls(one, [1, 1, 3, 2, 0])
assertHookCalls(two, [1, 1, 4, 3, 0])
}).then(() => {
oneInstance.ok = false
vm.ok = false
}).then(() => {
expect(vm.$el.textContent).toBe('')
assertHookCalls(one, [1, 1, 3, 3, 0])
assertHookCalls(two, [1, 1, 4, 4, 0])
}).then(() => {
vm.ok = true
}).then(() => {
expect(vm.$el.textContent).toBe('')
assertHookCalls(one, [1, 1, 4, 3, 0])
assertHookCalls(two, [1, 1, 4, 4, 0]) // should remain inactive
}).then(done)
})
function sharedAssertions (vm, done) {
expect(vm.$el.textContent).toBe('one')
assertHookCalls(one, [1, 1, 1, 0, 0])
assertHookCalls(two, [0, 0, 0, 0, 0])
vm.view = 'two'
waitForUpdate(() => {
expect(vm.$el.textContent).toBe('two')
assertHookCalls(one, [1, 1, 1, 1, 0])
assertHookCalls(two, [1, 1, 0, 0, 0])
vm.view = 'one'
}).then(() => {
expect(vm.$el.textContent).toBe('one')
assertHookCalls(one, [1, 1, 2, 1, 0])
assertHookCalls(two, [1, 1, 0, 0, 1])
vm.view = 'two'
}).then(() => {
expect(vm.$el.textContent).toBe('two')
assertHookCalls(one, [1, 1, 2, 2, 0])
assertHookCalls(two, [2, 2, 0, 0, 1])
vm.ok = false // teardown
}).then(() => {
expect(vm.$el.textContent).toBe('')
assertHookCalls(one, [1, 1, 2, 2, 1])
assertHookCalls(two, [2, 2, 0, 0, 2])
}).then(done)
}
it('include (string)', done => {
const vm = new Vue({
template: `
`,
data: {
view: 'one',
ok: true
},
components
}).$mount()
sharedAssertions(vm, done)
})
it('include (regex)', done => {
const vm = new Vue({
template: `
`,
data: {
view: 'one',
ok: true
},
components
}).$mount()
sharedAssertions(vm, done)
})
it('include (array)', done => {
const vm = new Vue({
template: `
`,
data: {
view: 'one',
ok: true
},
components
}).$mount()
sharedAssertions(vm, done)
})
it('exclude (string)', done => {
const vm = new Vue({
template: `
`,
data: {
view: 'one',
ok: true
},
components
}).$mount()
sharedAssertions(vm, done)
})
it('exclude (regex)', done => {
const vm = new Vue({
template: `
`,
data: {
view: 'one',
ok: true
},
components
}).$mount()
sharedAssertions(vm, done)
})
it('exclude (array)', done => {
const vm = new Vue({
template: `
`,
data: {
view: 'one',
ok: true
},
components
}).$mount()
sharedAssertions(vm, done)
})
it('include + exclude', done => {
const vm = new Vue({
template: `
`,
data: {
view: 'one',
ok: true
},
components
}).$mount()
sharedAssertions(vm, done)
})
it('prune cache on include/exclude change', done => {
const vm = new Vue({
template: `
`,
data: {
view: 'one',
include: 'one,two'
},
components
}).$mount()
vm.view = 'two'
waitForUpdate(() => {
assertHookCalls(one, [1, 1, 1, 1, 0])
assertHookCalls(two, [1, 1, 1, 0, 0])
vm.include = 'two'
}).then(() => {
assertHookCalls(one, [1, 1, 1, 1, 1])
assertHookCalls(two, [1, 1, 1, 0, 0])
vm.view = 'one'
}).then(() => {
assertHookCalls(one, [2, 2, 1, 1, 1])
assertHookCalls(two, [1, 1, 1, 1, 0])
}).then(done)
})
it('should not prune currently active instance', done => {
const vm = new Vue({
template: `
`,
data: {
view: 'one',
include: 'one,two'
},
components
}).$mount()
vm.include = 'two'
waitForUpdate(() => {
assertHookCalls(one, [1, 1, 1, 0, 0])
assertHookCalls(two, [0, 0, 0, 0, 0])
vm.view = 'two'
}).then(() => {
assertHookCalls(one, [1, 1, 1, 0, 1])
assertHookCalls(two, [1, 1, 1, 0, 0])
}).then(done)
})
// #3882
it('deeply nested keep-alive should be destroyed properly', done => {
one.template = `
`
one.components = { two }
const vm = new Vue({
template: ``,
data: { ok: true },
components: {
parent: {
template: `
`,
components: { one }
}
}
}).$mount()
assertHookCalls(one, [1, 1, 1, 0, 0])
assertHookCalls(two, [1, 1, 1, 0, 0])
vm.ok = false
waitForUpdate(() => {
assertHookCalls(one, [1, 1, 1, 1, 1])
assertHookCalls(two, [1, 1, 1, 1, 1])
}).then(done)
})
// #4237
it('should update latest props/listeners for a re-activated component', done => {
const one = {
props: ['prop'],
template: `one {{ prop }}
`
}
const two = {
props: ['prop'],
template: `two {{ prop }}
`
}
const vm = new Vue({
data: { view: 'one', n: 1 },
template: `
`,
components: { one, two }
}).$mount()
expect(vm.$el.textContent).toBe('one 1')
vm.n++
waitForUpdate(() => {
expect(vm.$el.textContent).toBe('one 2')
vm.view = 'two'
}).then(() => {
expect(vm.$el.textContent).toBe('two 2')
}).then(done)
})
if (!isIE9) {
it('with transition-mode out-in', done => {
let next
const vm = new Vue({
template: `
`,
data: {
view: 'one'
},
components,
methods: {
afterLeave () {
next()
}
}
}).$mount(el)
expect(vm.$el.textContent).toBe('one')
assertHookCalls(one, [1, 1, 1, 0, 0])
assertHookCalls(two, [0, 0, 0, 0, 0])
vm.view = 'two'
waitForUpdate(() => {
expect(vm.$el.innerHTML).toBe(
'one
'
)
assertHookCalls(one, [1, 1, 1, 1, 0])
assertHookCalls(two, [0, 0, 0, 0, 0])
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.innerHTML).toBe(
'one
'
)
}).thenWaitFor(_next => { next = _next }).then(() => {
expect(vm.$el.innerHTML).toBe('')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.innerHTML).toBe(
'two
'
)
assertHookCalls(one, [1, 1, 1, 1, 0])
assertHookCalls(two, [1, 1, 1, 0, 0])
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.innerHTML).toBe(
'two
'
)
}).thenWaitFor(duration + buffer).then(() => {
expect(vm.$el.innerHTML).toBe(
'two
'
)
assertHookCalls(one, [1, 1, 1, 1, 0])
assertHookCalls(two, [1, 1, 1, 0, 0])
}).then(() => {
vm.view = 'one'
}).then(() => {
expect(vm.$el.innerHTML).toBe(
'two
'
)
assertHookCalls(one, [1, 1, 1, 1, 0])
assertHookCalls(two, [1, 1, 1, 1, 0])
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.innerHTML).toBe(
'two
'
)
}).thenWaitFor(_next => { next = _next }).then(() => {
expect(vm.$el.innerHTML).toBe('')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.innerHTML).toBe(
'one
'
)
assertHookCalls(one, [1, 1, 2, 1, 0])
assertHookCalls(two, [1, 1, 1, 1, 0])
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.innerHTML).toBe(
'one
'
)
}).thenWaitFor(duration + buffer).then(() => {
expect(vm.$el.innerHTML).toBe(
'one
'
)
assertHookCalls(one, [1, 1, 2, 1, 0])
assertHookCalls(two, [1, 1, 1, 1, 0])
}).then(done)
})
it('with transition-mode out-in + include', done => {
let next
const vm = new Vue({
template: `
`,
data: {
view: 'one'
},
components,
methods: {
afterLeave () {
next()
}
}
}).$mount(el)
expect(vm.$el.textContent).toBe('one')
assertHookCalls(one, [1, 1, 1, 0, 0])
assertHookCalls(two, [0, 0, 0, 0, 0])
vm.view = 'two'
waitForUpdate(() => {
expect(vm.$el.innerHTML).toBe(
'one
'
)
assertHookCalls(one, [1, 1, 1, 1, 0])
assertHookCalls(two, [0, 0, 0, 0, 0])
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.innerHTML).toBe(
'one
'
)
}).thenWaitFor(_next => { next = _next }).then(() => {
expect(vm.$el.innerHTML).toBe('')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.innerHTML).toBe(
'two
'
)
assertHookCalls(one, [1, 1, 1, 1, 0])
assertHookCalls(two, [1, 1, 0, 0, 0])
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.innerHTML).toBe(
'two
'
)
}).thenWaitFor(duration + buffer).then(() => {
expect(vm.$el.innerHTML).toBe(
'two
'
)
assertHookCalls(one, [1, 1, 1, 1, 0])
assertHookCalls(two, [1, 1, 0, 0, 0])
}).then(() => {
vm.view = 'one'
}).then(() => {
expect(vm.$el.innerHTML).toBe(
'two
'
)
assertHookCalls(one, [1, 1, 1, 1, 0])
assertHookCalls(two, [1, 1, 0, 0, 1])
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.innerHTML).toBe(
'two
'
)
}).thenWaitFor(_next => { next = _next }).then(() => {
expect(vm.$el.innerHTML).toBe('')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.innerHTML).toBe(
'one
'
)
assertHookCalls(one, [1, 1, 2, 1, 0])
assertHookCalls(two, [1, 1, 0, 0, 1])
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.innerHTML).toBe(
'one
'
)
}).thenWaitFor(duration + buffer).then(() => {
expect(vm.$el.innerHTML).toBe(
'one
'
)
assertHookCalls(one, [1, 1, 2, 1, 0])
assertHookCalls(two, [1, 1, 0, 0, 1])
}).then(done)
})
it('with transition-mode in-out', done => {
let next
const vm = new Vue({
template: `
`,
data: {
view: 'one'
},
components,
methods: {
afterEnter () {
next()
}
}
}).$mount(el)
expect(vm.$el.textContent).toBe('one')
assertHookCalls(one, [1, 1, 1, 0, 0])
assertHookCalls(two, [0, 0, 0, 0, 0])
vm.view = 'two'
waitForUpdate(() => {
expect(vm.$el.innerHTML).toBe(
'one
' +
'two
'
)
assertHookCalls(one, [1, 1, 1, 1, 0])
assertHookCalls(two, [1, 1, 1, 0, 0])
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.innerHTML).toBe(
'one
' +
'two
'
)
}).thenWaitFor(_next => { next = _next }).then(() => {
expect(vm.$el.innerHTML).toBe(
'one
' +
'two
'
)
}).then(() => {
expect(vm.$el.innerHTML).toBe(
'one
' +
'two
'
)
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.innerHTML).toBe(
'one
' +
'two
'
)
}).thenWaitFor(duration + buffer).then(() => {
expect(vm.$el.innerHTML).toBe(
'two
'
)
assertHookCalls(one, [1, 1, 1, 1, 0])
assertHookCalls(two, [1, 1, 1, 0, 0])
}).then(() => {
vm.view = 'one'
}).then(() => {
expect(vm.$el.innerHTML).toBe(
'two
' +
'one
'
)
assertHookCalls(one, [1, 1, 2, 1, 0])
assertHookCalls(two, [1, 1, 1, 1, 0])
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.innerHTML).toBe(
'two
' +
'one
'
)
}).thenWaitFor(_next => { next = _next }).then(() => {
expect(vm.$el.innerHTML).toBe(
'two
' +
'one
'
)
}).then(() => {
expect(vm.$el.innerHTML).toBe(
'two
' +
'one
'
)
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.innerHTML).toBe(
'two
' +
'one
'
)
}).thenWaitFor(duration + buffer).then(() => {
expect(vm.$el.innerHTML).toBe(
'one
'
)
assertHookCalls(one, [1, 1, 2, 1, 0])
assertHookCalls(two, [1, 1, 1, 1, 0])
}).then(done)
})
it('dynamic components, in-out with early cancel', done => {
let next
const vm = new Vue({
template: `
`,
data: { view: 'one' },
components,
methods: {
afterEnter () {
next()
}
}
}).$mount(el)
expect(vm.$el.textContent).toBe('one')
vm.view = 'two'
waitForUpdate(() => {
expect(vm.$el.innerHTML).toBe(
'one
' +
'two
'
)
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.innerHTML).toBe(
'one
' +
'two
'
)
// switch again before enter finishes,
// this cancels both enter and leave.
vm.view = 'one'
}).then(() => {
// 1. the pending leaving "one" should be removed instantly.
// 2. the entering "two" should be placed into its final state instantly.
// 3. a new "one" is created and entering
expect(vm.$el.innerHTML).toBe(
'two
' +
'one
'
)
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.innerHTML).toBe(
'two
' +
'one
'
)
}).thenWaitFor(_next => { next = _next }).then(() => {
expect(vm.$el.innerHTML).toBe(
'two
' +
'one
'
)
}).then(() => {
expect(vm.$el.innerHTML).toBe(
'two
' +
'one
'
)
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.innerHTML).toBe(
'two
' +
'one
'
)
}).thenWaitFor(duration + buffer).then(() => {
expect(vm.$el.innerHTML).toBe(
'one
'
)
}).then(done).then(done)
})
// #4339
it('component with inner transition', done => {
const vm = new Vue({
template: `
`,
data: { view: 'foo' },
components: {
foo: { template: 'foo
' },
bar: { template: 'bar
' }
}
}).$mount(el)
// should not apply transition on initial render by default
expect(vm.$el.innerHTML).toBe('foo
')
vm.view = 'bar'
waitForUpdate(() => {
expect(vm.$el.innerHTML).toBe(
'foo
' +
'bar
'
)
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.innerHTML).toBe(
'foo
' +
'bar
'
)
}).thenWaitFor(duration + buffer).then(() => {
expect(vm.$el.innerHTML).toBe(
'bar
'
)
vm.view = 'foo'
}).then(() => {
expect(vm.$el.innerHTML).toBe(
'bar
' +
'foo
'
)
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.innerHTML).toBe(
'bar
' +
'foo
'
)
}).thenWaitFor(duration + buffer).then(() => {
expect(vm.$el.innerHTML).toBe(
'foo
'
)
}).then(done)
})
}
})
node-vue-template-compiler-2.4.2+dfsg/test/unit/features/component/component-scoped-slot.spec.js000066400000000000000000000235531361753775300331330ustar00rootroot00000000000000import Vue from 'vue'
describe('Component scoped slot', () => {
it('default slot', done => {
const vm = new Vue({
template: `
{{ props.msg }}
`,
components: {
test: {
data () {
return { msg: 'hello' }
},
template: `
`
}
}
}).$mount()
expect(vm.$el.innerHTML).toBe('hello ')
vm.$refs.test.msg = 'world'
waitForUpdate(() => {
expect(vm.$el.innerHTML).toBe('world ')
}).then(done)
})
it('with v-bind', done => {
const vm = new Vue({
template: `
{{ props.msg }} {{ props.msg2 }} {{ props.msg3 }}
`,
components: {
test: {
data () {
return {
msg: 'hello',
obj: { msg2: 'world', msg3: '.' }
}
},
template: `
`
}
}
}).$mount()
expect(vm.$el.innerHTML).toBe('hello world ! ')
vm.$refs.test.msg = 'bye'
vm.$refs.test.obj.msg2 = 'bye'
waitForUpdate(() => {
expect(vm.$el.innerHTML).toBe('bye bye ! ')
}).then(done)
})
it('template slot', done => {
const vm = new Vue({
template: `
{{ props.foo }} {{ props.bar }}
`,
components: {
test: {
data () {
return { foo: 'FOO', bar: 'BAR' }
},
template: `
`
}
}
}).$mount()
expect(vm.$el.innerHTML).toBe('FOO BAR ')
vm.$refs.test.foo = 'BAZ'
waitForUpdate(() => {
expect(vm.$el.innerHTML).toBe('BAZ BAR ')
}).then(done)
})
it('fallback content', () => {
const vm = new Vue({
template: ` `,
components: {
test: {
data () {
return { msg: 'hello' }
},
template: `
{{ msg }} fallback
`
}
}
}).$mount()
expect(vm.$el.innerHTML).toBe('hello fallback ')
})
it('slot with v-for', done => {
const vm = new Vue({
template: `
{{ props.text }}
`,
components: {
test: {
data () {
return {
items: ['foo', 'bar', 'baz']
}
},
template: `
`
}
}
}).$mount()
function assertOutput () {
expect(vm.$el.innerHTML).toBe(vm.$refs.test.items.map(item => {
return `${item} `
}).join(''))
}
assertOutput()
vm.$refs.test.items.reverse()
waitForUpdate(assertOutput).then(() => {
vm.$refs.test.items.push('qux')
}).then(assertOutput).then(done)
})
it('slot inside v-for', done => {
const vm = new Vue({
template: `
{{ props.text }}
`,
components: {
test: {
data () {
return {
items: ['foo', 'bar', 'baz']
}
},
template: `
`
}
}
}).$mount()
function assertOutput () {
expect(vm.$el.innerHTML).toBe(vm.$refs.test.items.map(item => {
return `${item} `
}).join(''))
}
assertOutput()
vm.$refs.test.items.reverse()
waitForUpdate(assertOutput).then(() => {
vm.$refs.test.items.push('qux')
}).then(assertOutput).then(done)
})
it('scoped slot without scope alias', () => {
const vm = new Vue({
template: `
I am static
`,
components: {
test: {
data () {
return { msg: 'hello' }
},
template: `
`
}
}
}).$mount()
expect(vm.$el.innerHTML).toBe('I am static ')
})
it('non-scoped slot with scope alias', () => {
const vm = new Vue({
template: `
{{ props.text || 'meh' }}
`,
components: {
test: {
data () {
return { msg: 'hello' }
},
template: `
`
}
}
}).$mount()
expect(vm.$el.innerHTML).toBe('meh ')
})
it('warn key on slot', () => {
new Vue({
template: `
{{ props.text }}
`,
components: {
test: {
data () {
return {
items: ['foo', 'bar', 'baz']
}
},
template: `
`
}
}
}).$mount()
expect(`\`key\` does not work on `).toHaveBeenWarned()
})
it('render function usage (named, via data)', done => {
const vm = new Vue({
render (h) {
return h('test', {
ref: 'test',
scopedSlots: {
item: props => h('span', props.text)
}
})
},
components: {
test: {
data () {
return { msg: 'hello' }
},
render (h) {
return h('div', [
this.$scopedSlots.item({
text: this.msg
})
])
}
}
}
}).$mount()
expect(vm.$el.innerHTML).toBe('hello ')
vm.$refs.test.msg = 'world'
waitForUpdate(() => {
expect(vm.$el.innerHTML).toBe('world ')
}).then(done)
})
it('render function usage (default, as children)', () => {
const vm = new Vue({
render (h) {
return h('test', [
props => h('span', [props.msg])
])
},
components: {
test: {
data () {
return { msg: 'hello' }
},
render (h) {
return h('div', [
this.$scopedSlots.default({ msg: this.msg })
])
}
}
}
}).$mount()
expect(vm.$el.innerHTML).toBe('hello ')
})
// #4779
it('should support dynamic slot target', done => {
const Child = {
template: `
`
}
const vm = new Vue({
data: {
a: 'a',
b: 'b'
},
template: `
A {{ props.msg }}
B {{ props.msg }}
`,
components: { Child }
}).$mount()
expect(vm.$el.textContent.trim()).toBe('A a B b')
// switch slots
vm.a = 'b'
vm.b = 'a'
waitForUpdate(() => {
expect(vm.$el.textContent.trim()).toBe('B a A b')
}).then(done)
})
it('render function usage (JSX)', () => {
const vm = new Vue({
render (h) {
return {
props => {props.msg}
}
},
components: {
test: {
data () {
return { msg: 'hello' }
},
render (h) {
return
{this.$scopedSlots.default({ msg: this.msg })}
}
}
}
}).$mount()
expect(vm.$el.innerHTML).toBe('hello ')
})
// #5615
it('scoped slot with v-for', done => {
const vm = new Vue({
data: { names: ['foo', 'bar'] },
template: `
{{ props.msg }}
{{ props.msg }}
`,
components: {
test: {
data: () => ({ msg: 'hello' }),
template: `
`
}
}
}).$mount()
expect(vm.$el.innerHTML).toBe('hello foo hello bar hello abc ')
vm.$refs.test.msg = 'world'
waitForUpdate(() => {
expect(vm.$el.innerHTML).toBe('world foo world bar world abc ')
}).then(done)
})
})
node-vue-template-compiler-2.4.2+dfsg/test/unit/features/component/component-slot.spec.js000066400000000000000000000447011361753775300316560ustar00rootroot00000000000000import Vue from 'vue'
describe('Component slot', () => {
let vm, child
function mount (options) {
vm = new Vue({
data: {
msg: 'parent message'
},
template: `${options.parentContent || ''}
`,
components: {
test: {
template: options.childTemplate,
data () {
return {
msg: 'child message'
}
}
}
}
}).$mount()
child = vm.$children[0]
}
it('no content', () => {
mount({
childTemplate: '
'
})
expect(child.$el.childNodes.length).toBe(0)
})
it('default slot', done => {
mount({
childTemplate: '
',
parentContent: '{{ msg }}
'
})
expect(child.$el.tagName).toBe('DIV')
expect(child.$el.children[0].tagName).toBe('P')
expect(child.$el.children[0].textContent).toBe('parent message')
vm.msg = 'changed'
waitForUpdate(() => {
expect(child.$el.children[0].textContent).toBe('changed')
}).then(done)
})
it('named slot', done => {
mount({
childTemplate: '
',
parentContent: '{{ msg }}
'
})
expect(child.$el.tagName).toBe('DIV')
expect(child.$el.children[0].tagName).toBe('P')
expect(child.$el.children[0].textContent).toBe('parent message')
vm.msg = 'changed'
waitForUpdate(() => {
expect(child.$el.children[0].textContent).toBe('changed')
}).then(done)
})
it('named slot with 0 as a number', done => {
mount({
childTemplate: '
',
parentContent: '{{ msg }}
'
})
expect(child.$el.tagName).toBe('DIV')
expect(child.$el.children[0].tagName).toBe('P')
expect(child.$el.children[0].textContent).toBe('parent message')
vm.msg = 'changed'
waitForUpdate(() => {
expect(child.$el.children[0].textContent).toBe('changed')
}).then(done)
})
it('fallback content', () => {
mount({
childTemplate: ''
})
expect(child.$el.children[0].tagName).toBe('P')
expect(child.$el.textContent).toBe('child message')
})
it('fallback content with multiple named slots', () => {
mount({
childTemplate: `
`,
parentContent: 'slot b
'
})
expect(child.$el.children.length).toBe(2)
expect(child.$el.children[0].textContent).toBe('fallback a')
expect(child.$el.children[1].textContent).toBe('slot b')
})
it('fallback content with mixed named/unnamed slots', () => {
mount({
childTemplate: `
`,
parentContent: 'slot b
'
})
expect(child.$el.children.length).toBe(2)
expect(child.$el.children[0].textContent).toBe('fallback a')
expect(child.$el.children[1].textContent).toBe('slot b')
})
it('selector matching multiple elements', () => {
mount({
childTemplate: '
',
parentContent: '1
2
'
})
expect(child.$el.innerHTML).toBe('1
2
')
})
it('default content should only render parts not selected', () => {
mount({
childTemplate: `
`,
parentContent: 'foo
1
2
'
})
expect(child.$el.innerHTML).toBe('1
foo
2
')
})
it('name should only match children', function () {
mount({
childTemplate: `
fallback a
fallback b
fallback c
`,
parentContent: `
'select b
'nested b
'nested c
`
})
expect(child.$el.children.length).toBe(3)
expect(child.$el.children[0].textContent).toBe('fallback a')
expect(child.$el.children[1].textContent).toBe('select b')
expect(child.$el.children[2].textContent).toBe('fallback c')
})
it('should accept expressions in slot attribute and slot names', () => {
mount({
childTemplate: `
`,
parentContent: `one
two
`
})
expect(child.$el.innerHTML).toBe('two
')
})
it('slot inside v-if', done => {
const vm = new Vue({
data: {
a: 1,
b: 2,
show: true
},
template: '{{b}}
{{a}}
',
components: {
test: {
props: ['show'],
template: '
'
}
}
}).$mount()
expect(vm.$el.textContent).toBe('12')
vm.a = 2
waitForUpdate(() => {
expect(vm.$el.textContent).toBe('22')
vm.show = false
}).then(() => {
expect(vm.$el.textContent).toBe('')
vm.show = true
vm.a = 3
}).then(() => {
expect(vm.$el.textContent).toBe('32')
}).then(done)
})
it('slot inside v-for', () => {
mount({
childTemplate: '
',
parentContent: '{{ i - 1 }}
'
})
expect(child.$el.innerHTML).toBe('0
1
2
')
})
it('nested slots', done => {
const vm = new Vue({
template: '{{ msg }}
',
data: {
msg: 'foo'
},
components: {
test: {
template: '
'
},
test2: {
template: '
'
}
}
}).$mount()
expect(vm.$el.innerHTML).toBe('')
vm.msg = 'bar'
waitForUpdate(() => {
expect(vm.$el.innerHTML).toBe('')
}).then(done)
})
it('v-if on inserted content', done => {
const vm = new Vue({
template: '{{ msg }}
',
data: {
ok: true,
msg: 'hi'
},
components: {
test: {
template: 'fallback
'
}
}
}).$mount()
expect(vm.$el.innerHTML).toBe('hi
')
vm.ok = false
waitForUpdate(() => {
expect(vm.$el.innerHTML).toBe('fallback')
vm.ok = true
vm.msg = 'bye'
}).then(() => {
expect(vm.$el.innerHTML).toBe('bye
')
}).then(done)
})
it('template slot', function () {
const vm = new Vue({
template: 'hello ',
components: {
test: {
template: ' world
'
}
}
}).$mount()
expect(vm.$el.innerHTML).toBe('hello world')
})
it('combined with v-for', () => {
const vm = new Vue({
template: '{{ i }}
',
components: {
test: {
template: '
'
}
}
}).$mount()
expect(vm.$el.innerHTML).toBe('1
2
3
')
})
it('inside template v-if', () => {
mount({
childTemplate: `
`,
parentContent: 'foo'
})
expect(child.$el.innerHTML).toBe('foo')
})
it('default slot should use fallback content if has only whitespace', () => {
mount({
childTemplate: `
first slot
this is the default slot
second named slot
`,
parentContent: `1
2
2+
`
})
expect(child.$el.innerHTML).toBe(
'1
this is the default slot
2
2+
'
)
})
it('programmatic access to $slots', () => {
const vm = new Vue({
template: 'A
C
B
',
components: {
test: {
render () {
expect(this.$slots.a.length).toBe(1)
expect(this.$slots.a[0].tag).toBe('p')
expect(this.$slots.a[0].children.length).toBe(1)
expect(this.$slots.a[0].children[0].text).toBe('A')
expect(this.$slots.b.length).toBe(1)
expect(this.$slots.b[0].tag).toBe('p')
expect(this.$slots.b[0].children.length).toBe(1)
expect(this.$slots.b[0].children[0].text).toBe('B')
expect(this.$slots.default.length).toBe(1)
expect(this.$slots.default[0].tag).toBe('div')
expect(this.$slots.default[0].children.length).toBe(1)
expect(this.$slots.default[0].children[0].text).toBe('C')
return this.$slots.default[0]
}
}
}
}).$mount()
expect(vm.$el.tagName).toBe('DIV')
expect(vm.$el.textContent).toBe('C')
})
it('warn if user directly returns array', () => {
new Vue({
template: '
',
components: {
test: {
render () {
return this.$slots.default
}
}
}
}).$mount()
expect('Render function should return a single root node').toHaveBeenWarned()
})
// #3254
it('should not keep slot name when passed further down', () => {
const vm = new Vue({
template: 'foo ',
components: {
test: {
template: ' ',
components: {
child: {
template: `
`
}
}
}
}
}).$mount()
expect(vm.$el.querySelector('.default').textContent).toBe('foo')
expect(vm.$el.querySelector('.named').textContent).toBe('')
})
it('should not keep slot name when passed further down (nested)', () => {
const vm = new Vue({
template: 'foo ',
components: {
wrap: {
template: '
'
},
test: {
template: ' ',
components: {
child: {
template: `
`
}
}
}
}
}).$mount()
expect(vm.$el.querySelector('.default').textContent).toBe('foo')
expect(vm.$el.querySelector('.named').textContent).toBe('')
})
it('should not keep slot name when passed further down (functional)', () => {
const child = {
template: `
`
}
const vm = new Vue({
template: 'foo ',
components: {
test: {
functional: true,
render (h, ctx) {
const slots = ctx.slots()
return h(child, slots.foo)
}
}
}
}).$mount()
expect(vm.$el.querySelector('.default').textContent).toBe('foo')
expect(vm.$el.querySelector('.named').textContent).toBe('')
})
// #3400
it('named slots should be consistent across re-renders', done => {
const vm = new Vue({
template: `
foo
`,
components: {
comp: {
data () {
return { a: 1 }
},
template: ` {{ a }}
`
}
}
}).$mount()
expect(vm.$el.textContent).toBe('foo1')
vm.$children[0].a = 2
waitForUpdate(() => {
expect(vm.$el.textContent).toBe('foo2')
}).then(done)
})
// #3437
it('should correctly re-create components in slot', done => {
const calls = []
const vm = new Vue({
template: `
`,
components: {
comp: {
data () {
return { ok: true }
},
template: `
`
},
child: {
template: 'child
',
created () {
calls.push(1)
},
destroyed () {
calls.push(2)
}
}
}
}).$mount()
expect(calls).toEqual([1])
vm.$refs.child.ok = false
waitForUpdate(() => {
expect(calls).toEqual([1, 2])
vm.$refs.child.ok = true
}).then(() => {
expect(calls).toEqual([1, 2, 1])
vm.$refs.child.ok = false
}).then(() => {
expect(calls).toEqual([1, 2, 1, 2])
}).then(done)
})
it('warn duplicate slots', () => {
new Vue({
template: ``,
components: {
test: {
template: ``
}
}
}).$mount()
expect('Duplicate presence of slot "default"').toHaveBeenWarned()
expect('Duplicate presence of slot "a"').toHaveBeenWarned()
})
it('should not warn valid conditional slots', () => {
new Vue({
template: ``,
components: {
test: {
template: `
`
}
}
}).$mount()
expect('Duplicate presence of slot "default"').not.toHaveBeenWarned()
})
// #3518
it('events should not break when slot is toggled by v-if', done => {
const spy = jasmine.createSpy()
const vm = new Vue({
template: `hi
`,
methods: {
test: spy
},
components: {
test: {
data: () => ({
toggle: true
}),
template: `
`
}
}
}).$mount()
expect(vm.$el.textContent).toBe('hi')
vm.$children[0].toggle = false
waitForUpdate(() => {
vm.$children[0].toggle = true
}).then(() => {
triggerEvent(vm.$el.querySelector('.click'), 'click')
expect(spy).toHaveBeenCalled()
}).then(done)
})
it('renders static tree with text', () => {
const vm = new Vue({
template: ``,
components: {
test: {
template: '
'
}
}
})
vm.$mount()
expect('Error when rendering root').not.toHaveBeenWarned()
})
// #3872
it('functional component as slot', () => {
const vm = new Vue({
template: `
one
two
`,
components: {
parent: {
template: `
`
},
child: {
functional: true,
render (h, { slots }) {
return h('div', slots().default)
}
}
}
}).$mount()
expect(vm.$el.innerHTML.trim()).toBe('two
one
')
})
// #4209
it('slot of multiple text nodes should not be infinitely merged', done => {
const wrap = {
template: `foo `,
components: {
inner: {
data: () => ({ a: 1 }),
template: `{{a}}
`
}
}
}
const vm = new Vue({
template: `bar `,
components: { wrap }
}).$mount()
expect(vm.$el.textContent).toBe('1foobar')
vm.$refs.wrap.$refs.inner.a++
waitForUpdate(() => {
expect(vm.$el.textContent).toBe('2foobar')
}).then(done)
})
// #4315
it('functional component passing slot content to stateful child component', done => {
const ComponentWithSlots = {
render (h) {
return h('div', this.$slots.slot1)
}
}
const FunctionalComp = {
functional: true,
render (h) {
return h(ComponentWithSlots, [h('span', { slot: 'slot1' }, 'foo')])
}
}
const vm = new Vue({
data: { n: 1 },
render (h) {
return h('div', [this.n, h(FunctionalComp)])
}
}).$mount()
expect(vm.$el.textContent).toBe('1foo')
vm.n++
waitForUpdate(() => {
// should not lose named slot
expect(vm.$el.textContent).toBe('2foo')
}).then(done)
})
it('the elements of slot should be updated correctly', done => {
const vm = new Vue({
data: { n: 1 },
template: '{{ i }}
',
components: {
test: {
template: '
'
}
}
}).$mount()
expect(vm.$el.innerHTML).toBe('1
')
const input = vm.$el.querySelector('input')
input.value = 'b'
vm.n++
waitForUpdate(() => {
expect(vm.$el.innerHTML).toBe('1 2
')
expect(vm.$el.querySelector('input')).toBe(input)
expect(vm.$el.querySelector('input').value).toBe('b')
}).then(done)
})
// Github issue #5888
it('should resolve correctly slot with keep-alive', () => {
const vm = new Vue({
template: `
`,
components: {
container: {
template:
'default named
'
},
child: {
template: 'foo '
}
}
}).$mount()
expect(vm.$el.innerHTML).toBe('defaultfoo
')
})
})
node-vue-template-compiler-2.4.2+dfsg/test/unit/features/component/component.spec.js000066400000000000000000000257021361753775300306770ustar00rootroot00000000000000import Vue from 'vue'
describe('Component', () => {
it('static', () => {
const vm = new Vue({
template: ' ',
components: {
test: {
data () {
return { a: 123 }
},
template: '{{a}} '
}
}
}).$mount()
expect(vm.$el.tagName).toBe('SPAN')
expect(vm.$el.innerHTML).toBe('123')
})
it('using component in restricted elements', () => {
const vm = new Vue({
template: '',
components: {
test: {
data () {
return { a: 123 }
},
template: '{{a}}'
}
}
}).$mount()
expect(vm.$el.innerHTML).toBe('')
})
it('"is" attribute', () => {
const vm = new Vue({
template: '',
components: {
test: {
data () {
return { a: 123 }
},
template: '{{a}}'
}
}
}).$mount()
expect(vm.$el.innerHTML).toBe('')
})
it('inline-template', () => {
const vm = new Vue({
template: '{{a}}
',
data: {
a: 'parent'
},
components: {
test: {
data () {
return { a: 'child' }
}
}
}
}).$mount()
expect(vm.$el.innerHTML).toBe('child ')
})
it('fragment instance warning', () => {
new Vue({
template: ' ',
components: {
test: {
data () {
return { a: 123, b: 234 }
},
template: '{{a}}
{{b}}
'
}
}
}).$mount()
expect('Component template should contain exactly one root element').toHaveBeenWarned()
})
it('dynamic', done => {
const vm = new Vue({
template: ' ',
data: {
view: 'view-a'
},
components: {
'view-a': {
template: 'foo {{view}}
',
data () {
return { view: 'a' }
}
},
'view-b': {
template: 'bar {{view}}
',
data () {
return { view: 'b' }
}
}
}
}).$mount()
expect(vm.$el.outerHTML).toBe('foo a
')
vm.view = 'view-b'
waitForUpdate(() => {
expect(vm.$el.outerHTML).toBe('bar b
')
vm.view = ''
})
.then(() => {
expect(vm.$el.nodeType).toBe(8)
expect(vm.$el.data).toBe('')
}).then(done)
})
it('dynamic with props', done => {
const vm = new Vue({
template: ' ',
data: {
view: 'view-a'
},
components: {
'view-a': {
template: 'foo {{view}}
',
props: ['view']
},
'view-b': {
template: 'bar {{view}}
',
props: ['view']
}
}
}).$mount()
expect(vm.$el.outerHTML).toBe('foo view-a
')
vm.view = 'view-b'
waitForUpdate(() => {
expect(vm.$el.outerHTML).toBe('bar view-b
')
vm.view = ''
})
.then(() => {
expect(vm.$el.nodeType).toBe(8)
expect(vm.$el.data).toBe('')
}).then(done)
})
it(':is using raw component constructor', () => {
const vm = new Vue({
template:
'' +
' ' +
' ' +
'
',
components: {
test: {
template: 'foo '
},
async: function (resolve) {
resolve({
template: 'bar '
})
}
}
}).$mount()
expect(vm.$el.innerHTML).toBe('foo bar ')
})
it('dynamic combined with v-for', done => {
const vm = new Vue({
template:
'' +
' ' +
'
',
data: {
comps: [{ type: 'one' }, { type: 'two' }]
},
components: {
one: {
template: 'one '
},
two: {
template: 'two '
}
}
}).$mount()
expect(vm.$el.innerHTML).toBe('one two ')
vm.comps[1].type = 'one'
waitForUpdate(() => {
expect(vm.$el.innerHTML).toBe('one one ')
}).then(done)
})
it('dynamic elements with domProps', done => {
const vm = new Vue({
template: ' ',
data: {
view: 'input',
val: 'hello'
}
}).$mount()
expect(vm.$el.tagName).toBe('INPUT')
expect(vm.$el.value).toBe('hello')
vm.view = 'textarea'
vm.val += ' world'
waitForUpdate(() => {
expect(vm.$el.tagName).toBe('TEXTAREA')
expect(vm.$el.value).toBe('hello world')
vm.view = ''
}).then(done)
})
it('should compile parent template directives & content in parent scope', done => {
const vm = new Vue({
data: {
ok: false,
message: 'hello'
},
template: '{{message}} ',
components: {
test: {
template: ' {{message}}
',
data () {
return {
message: 'world'
}
}
}
}
}).$mount()
expect(vm.$el.style.display).toBe('none')
expect(vm.$el.textContent).toBe('hello world')
vm.ok = true
vm.message = 'bye'
waitForUpdate(() => {
expect(vm.$el.style.display).toBe('')
expect(vm.$el.textContent).toBe('bye world')
}).then(done)
})
it('parent content + v-if', done => {
const vm = new Vue({
data: {
ok: false,
message: 'hello'
},
template: '{{message}} ',
components: {
test: {
template: ' {{message}}
',
data () {
return {
message: 'world'
}
}
}
}
}).$mount()
expect(vm.$el.textContent).toBe('')
expect(vm.$children.length).toBe(0)
vm.ok = true
waitForUpdate(() => {
expect(vm.$children.length).toBe(1)
expect(vm.$el.textContent).toBe('hello world')
}).then(done)
})
it('props', () => {
const vm = new Vue({
data: {
list: [{ a: 1 }, { a: 2 }]
},
template: ' ',
components: {
test: {
template: '',
props: ['collection']
}
}
}).$mount()
expect(vm.$el.outerHTML).toBe('')
})
it('should warn when using camelCased props in in-DOM template', () => {
new Vue({
data: {
list: [{ a: 1 }, { a: 2 }]
},
template: ' ', // <-- simulate lowercased template
components: {
test: {
template: '',
props: ['someCollection']
}
}
}).$mount()
expect(
'You should probably use "some-collection" instead of "someCollection".'
).toHaveBeenTipped()
})
it('should warn when using camelCased events in in-DOM template', () => {
new Vue({
template: ' ', // <-- simulate lowercased template
components: {
test: {
template: '
',
created () {
this.$emit('fooBar')
}
}
}
}).$mount()
expect(
'You should probably use "foo-bar" instead of "fooBar".'
).toHaveBeenTipped()
})
it('not found component should not throw', () => {
expect(function () {
new Vue({
template: '
'
})
}).not.toThrow()
})
it('properly update replaced higher-order component root node', done => {
const vm = new Vue({
data: {
color: 'red'
},
template: ' ',
components: {
test: {
data () {
return { tag: 'div' }
},
render (h) {
return h(this.tag, { class: 'test' }, 'hi')
}
}
}
}).$mount()
expect(vm.$el.tagName).toBe('DIV')
expect(vm.$el.id).toBe('foo')
expect(vm.$el.className).toBe('test red')
vm.color = 'green'
waitForUpdate(() => {
expect(vm.$el.tagName).toBe('DIV')
expect(vm.$el.id).toBe('foo')
expect(vm.$el.className).toBe('test green')
vm.$children[0].tag = 'p'
}).then(() => {
expect(vm.$el.tagName).toBe('P')
expect(vm.$el.id).toBe('foo')
expect(vm.$el.className).toBe('test green')
vm.color = 'red'
}).then(() => {
expect(vm.$el.tagName).toBe('P')
expect(vm.$el.id).toBe('foo')
expect(vm.$el.className).toBe('test red')
}).then(done)
})
it('catch component render error and preserve previous vnode', done => {
const spy = jasmine.createSpy()
Vue.config.errorHandler = spy
const vm = new Vue({
data: {
a: {
b: 123
}
},
render (h) {
return h('div', [this.a.b])
}
}).$mount()
expect(vm.$el.textContent).toBe('123')
expect(spy).not.toHaveBeenCalled()
vm.a = null
waitForUpdate(() => {
expect(spy).toHaveBeenCalled()
expect(vm.$el.textContent).toBe('123') // should preserve rendered DOM
vm.a = { b: 234 }
}).then(() => {
expect(vm.$el.textContent).toBe('234') // should be able to recover
Vue.config.errorHandler = null
}).then(done)
})
it('relocates node without error', done => {
const el = document.createElement('div')
document.body.appendChild(el)
const target = document.createElement('div')
document.body.appendChild(target)
const Test = {
render (h) {
return h('div', { class: 'test' }, this.$slots.default)
},
mounted () {
target.appendChild(this.$el)
},
beforeDestroy () {
const parent = this.$el.parentNode
if (parent) {
parent.removeChild(this.$el)
}
}
}
const vm = new Vue({
data () {
return {
view: true
}
},
template: `Test
`,
components: {
test: Test
}
}).$mount(el)
expect(el.outerHTML).toBe('
')
expect(target.outerHTML).toBe('')
vm.view = false
waitForUpdate(() => {
expect(el.outerHTML).toBe('
')
expect(target.outerHTML).toBe('
')
vm.$destroy()
}).then(done)
})
})
node-vue-template-compiler-2.4.2+dfsg/test/unit/features/debug.spec.js000066400000000000000000000052631361753775300257610ustar00rootroot00000000000000import Vue from 'vue'
import { formatComponentName, warn } from 'core/util/debug'
describe('Debug utilities', () => {
it('properly format component names', () => {
const vm = new Vue()
expect(formatComponentName(vm)).toBe('')
vm.$root = null
vm.$options.name = 'hello-there'
expect(formatComponentName(vm)).toBe('')
vm.$options.name = null
vm.$options._componentTag = 'foo-bar-1'
expect(formatComponentName(vm)).toBe('')
vm.$options._componentTag = null
vm.$options.__file = '/foo/bar/baz/SomeThing.vue'
expect(formatComponentName(vm)).toBe(` at ${vm.$options.__file}`)
expect(formatComponentName(vm, false)).toBe('')
vm.$options.__file = 'C:\\foo\\bar\\baz\\windows_file.vue'
expect(formatComponentName(vm)).toBe(` at ${vm.$options.__file}`)
expect(formatComponentName(vm, false)).toBe('')
})
it('generate correct component hierarchy trace', () => {
const one = {
name: 'one',
render: h => h(two)
}
const two = {
name: 'two',
render: h => h(three)
}
const three = {
name: 'three'
}
new Vue({
render: h => h(one)
}).$mount()
expect(
`Failed to mount component: template or render function not defined.
found in
--->
`
).toHaveBeenWarned()
})
it('generate correct component hierarchy trace (recursive)', () => {
let i = 0
const one = {
name: 'one',
render: h => i++ < 5 ? h(one) : h(two)
}
const two = {
name: 'two',
render: h => h(three)
}
const three = {
name: 'three'
}
new Vue({
render: h => h(one)
}).$mount()
expect(
`Failed to mount component: template or render function not defined.
found in
--->
... (5 recursive calls)
`
).toHaveBeenWarned()
})
describe('warn', () => {
const msg = 'message'
const vm = new Vue()
it('calls warnHandler if warnHandler is set', () => {
Vue.config.warnHandler = jasmine.createSpy()
warn(msg, vm)
expect(Vue.config.warnHandler).toHaveBeenCalledWith(msg, vm, jasmine.any(String))
Vue.config.warnHandler = null
})
it('calls console.error if silent is false', () => {
Vue.config.silent = false
warn(msg, vm)
expect(msg).toHaveBeenWarned()
expect(console.error).toHaveBeenCalled()
})
it('does not call console.error if silent is true', () => {
Vue.config.silent = true
warn(msg, vm)
expect(console.error).not.toHaveBeenCalled()
Vue.config.silent = false
})
})
})
node-vue-template-compiler-2.4.2+dfsg/test/unit/features/directives/000077500000000000000000000000001361753775300255375ustar00rootroot00000000000000node-vue-template-compiler-2.4.2+dfsg/test/unit/features/directives/bind.spec.js000066400000000000000000000265021361753775300277470ustar00rootroot00000000000000import Vue from 'vue'
describe('Directive v-bind', () => {
it('normal attr', done => {
const vm = new Vue({
template: 'hello
',
data: { foo: 'ok' }
}).$mount()
expect(vm.$el.firstChild.getAttribute('test')).toBe('ok')
vm.foo = 'again'
waitForUpdate(() => {
expect(vm.$el.firstChild.getAttribute('test')).toBe('again')
vm.foo = null
}).then(() => {
expect(vm.$el.firstChild.hasAttribute('test')).toBe(false)
vm.foo = false
}).then(() => {
expect(vm.$el.firstChild.hasAttribute('test')).toBe(false)
vm.foo = true
}).then(() => {
expect(vm.$el.firstChild.getAttribute('test')).toBe('true')
vm.foo = 0
}).then(() => {
expect(vm.$el.firstChild.getAttribute('test')).toBe('0')
}).then(done)
})
it('should set property for input value', done => {
const vm = new Vue({
template: `
`,
data: {
foo: 'ok',
bar: false
}
}).$mount()
expect(vm.$el.firstChild.value).toBe('ok')
expect(vm.$el.lastChild.checked).toBe(false)
vm.bar = true
waitForUpdate(() => {
expect(vm.$el.lastChild.checked).toBe(true)
}).then(done)
})
it('xlink', done => {
const vm = new Vue({
template: ' ',
data: {
foo: 'ok'
}
}).$mount()
const xlinkNS = 'http://www.w3.org/1999/xlink'
expect(vm.$el.firstChild.getAttributeNS(xlinkNS, 'special')).toBe('ok')
vm.foo = 'again'
waitForUpdate(() => {
expect(vm.$el.firstChild.getAttributeNS(xlinkNS, 'special')).toBe('again')
vm.foo = null
}).then(() => {
expect(vm.$el.firstChild.hasAttributeNS(xlinkNS, 'special')).toBe(false)
vm.foo = true
}).then(() => {
expect(vm.$el.firstChild.getAttributeNS(xlinkNS, 'special')).toBe('true')
}).then(done)
})
it('enumerated attr', done => {
const vm = new Vue({
template: 'hello
',
data: { foo: true }
}).$mount()
expect(vm.$el.firstChild.getAttribute('draggable')).toBe('true')
vm.foo = 'again'
waitForUpdate(() => {
expect(vm.$el.firstChild.getAttribute('draggable')).toBe('true')
vm.foo = null
}).then(() => {
expect(vm.$el.firstChild.getAttribute('draggable')).toBe('false')
vm.foo = ''
}).then(() => {
expect(vm.$el.firstChild.getAttribute('draggable')).toBe('true')
vm.foo = false
}).then(() => {
expect(vm.$el.firstChild.getAttribute('draggable')).toBe('false')
vm.foo = 'false'
}).then(() => {
expect(vm.$el.firstChild.getAttribute('draggable')).toBe('false')
}).then(done)
})
it('boolean attr', done => {
const vm = new Vue({
template: 'hello
',
data: { foo: true }
}).$mount()
expect(vm.$el.firstChild.getAttribute('disabled')).toBe('disabled')
vm.foo = 'again'
waitForUpdate(() => {
expect(vm.$el.firstChild.getAttribute('disabled')).toBe('disabled')
vm.foo = null
}).then(() => {
expect(vm.$el.firstChild.hasAttribute('disabled')).toBe(false)
vm.foo = ''
}).then(() => {
expect(vm.$el.firstChild.hasAttribute('disabled')).toBe(true)
}).then(done)
})
it('.prop modifier', () => {
const vm = new Vue({
template: '
',
data: {
foo: 'hello',
bar: 'qux '
}
}).$mount()
expect(vm.$el.children[0].textContent).toBe('hello')
expect(vm.$el.children[1].innerHTML).toBe('qux ')
})
it('.prop modifier with normal attribute binding', () => {
const vm = new Vue({
template: ' ',
data: {
some: 'hello',
id: false
}
}).$mount()
expect(vm.$el.some).toBe('hello')
expect(vm.$el.getAttribute('id')).toBe(null)
})
it('.camel modifier', () => {
const vm = new Vue({
template: ' ',
data: {
viewBox: '0 0 1 1'
}
}).$mount()
expect(vm.$el.getAttribute('viewBox')).toBe('0 0 1 1')
})
it('.sync modifier', done => {
const vm = new Vue({
template: ``,
data: {
bar: 1
},
components: {
test: {
props: ['fooBar'],
template: `{{ fooBar }}
`
}
}
}).$mount()
expect(vm.$el.textContent).toBe('1')
triggerEvent(vm.$el, 'click')
waitForUpdate(() => {
expect(vm.$el.textContent).toBe('2')
}).then(done)
})
it('bind object', done => {
const vm = new Vue({
template: ' ',
data: {
test: {
id: 'test',
class: 'ok',
value: 'hello'
}
}
}).$mount()
expect(vm.$el.getAttribute('id')).toBe('test')
expect(vm.$el.getAttribute('class')).toBe('ok')
expect(vm.$el.value).toBe('hello')
vm.test.id = 'hi'
vm.test.value = 'bye'
waitForUpdate(() => {
expect(vm.$el.getAttribute('id')).toBe('hi')
expect(vm.$el.getAttribute('class')).toBe('ok')
expect(vm.$el.value).toBe('bye')
}).then(done)
})
it('.sync modifier with bind object', done => {
const vm = new Vue({
template: ``,
data: {
test: {
fooBar: 1
}
},
components: {
test: {
props: ['fooBar'],
template: `{{ fooBar }}
`,
methods: {
handleUpdate () {
this.$emit('update:fooBar', 2)
}
}
}
}
}).$mount()
expect(vm.$el.textContent).toBe('1')
triggerEvent(vm.$el, 'click')
waitForUpdate(() => {
expect(vm.$el.textContent).toBe('2')
vm.test.fooBar = 3
}).then(() => {
expect(vm.$el.textContent).toBe('3')
}).then(done)
})
it('bind object with overwrite', done => {
const vm = new Vue({
template: ' ',
data: {
test: {
id: 'test',
class: 'ok',
value: 'hello'
}
}
}).$mount()
expect(vm.$el.getAttribute('id')).toBe('foo')
expect(vm.$el.getAttribute('class')).toBe('hello')
expect(vm.$el.value).toBe('hello')
vm.test.id = 'hi'
vm.test.value = 'bye'
waitForUpdate(() => {
expect(vm.$el.getAttribute('id')).toBe('foo')
expect(vm.$el.getAttribute('class')).toBe('bye')
expect(vm.$el.value).toBe('bye')
}).then(done)
})
it('bind object with class/style', done => {
const vm = new Vue({
template: ' ',
data: {
test: {
id: 'test',
class: ['b', 'c'],
style: { fontSize: '12px' }
}
}
}).$mount()
expect(vm.$el.id).toBe('test')
expect(vm.$el.className).toBe('a b c')
expect(vm.$el.style.color).toBe('red')
expect(vm.$el.style.fontSize).toBe('12px')
vm.test.id = 'hi'
vm.test.class = ['d']
vm.test.style = { fontSize: '14px' }
waitForUpdate(() => {
expect(vm.$el.id).toBe('hi')
expect(vm.$el.className).toBe('a d')
expect(vm.$el.style.color).toBe('red')
expect(vm.$el.style.fontSize).toBe('14px')
}).then(done)
})
it('bind object as prop', done => {
const vm = new Vue({
template: ' ',
data: {
test: {
id: 'test',
className: 'ok',
value: 'hello'
}
}
}).$mount()
expect(vm.$el.id).toBe('test')
expect(vm.$el.className).toBe('ok')
expect(vm.$el.value).toBe('hello')
vm.test.id = 'hi'
vm.test.className = 'okay'
vm.test.value = 'bye'
waitForUpdate(() => {
expect(vm.$el.id).toBe('hi')
expect(vm.$el.className).toBe('okay')
expect(vm.$el.value).toBe('bye')
}).then(done)
})
it('bind array', done => {
const vm = new Vue({
template: ' ',
data: {
test: [
{ id: 'test', class: 'ok' },
{ value: 'hello' }
]
}
}).$mount()
expect(vm.$el.getAttribute('id')).toBe('test')
expect(vm.$el.getAttribute('class')).toBe('ok')
expect(vm.$el.value).toBe('hello')
vm.test[0].id = 'hi'
vm.test[1].value = 'bye'
waitForUpdate(() => {
expect(vm.$el.getAttribute('id')).toBe('hi')
expect(vm.$el.getAttribute('class')).toBe('ok')
expect(vm.$el.value).toBe('bye')
}).then(done)
})
it('warn expect object', () => {
new Vue({
template: ' ',
data: {
test: 1
}
}).$mount()
expect('v-bind without argument expects an Object or Array value').toHaveBeenWarned()
})
it('set value for option element', () => {
const vm = new Vue({
template: 'val ',
data: {
val: 'val'
}
}).$mount()
// check value attribute
expect(vm.$el.options[0].getAttribute('value')).toBe('val')
})
// a vdom patch edge case where the user has several un-keyed elements of the
// same tag next to each other, and toggling them.
it('properly update for toggling un-keyed children', done => {
const vm = new Vue({
template: `
`,
data: {
ok: true
}
}).$mount()
expect(vm.$el.children[0].id).toBe('a')
expect(vm.$el.children[0].getAttribute('data-test')).toBe('1')
vm.ok = false
waitForUpdate(() => {
expect(vm.$el.children[0].id).toBe('b')
expect(vm.$el.children[0].getAttribute('data-test')).toBe(null)
}).then(done)
})
describe('bind object with special attribute', () => {
function makeInstance (options) {
return new Vue({
template: `${options.parentTemp}
`,
data: {
attrs: {
[options.attr]: options.value
}
},
components: {
comp: {
template: options.childTemp
}
}
}).$mount()
}
it('key', () => {
const vm = makeInstance({
attr: 'key',
value: 'test',
parentTemp: '
'
})
expect(vm._vnode.children[0].key).toBe('test')
})
it('ref', () => {
const vm = makeInstance({
attr: 'ref',
value: 'test',
parentTemp: '
'
})
expect(vm.$refs.test).toBe(vm.$el.firstChild)
})
it('slot', () => {
const vm = makeInstance({
attr: 'slot',
value: 'test',
parentTemp: '123 ',
childTemp: 'slot:
'
})
expect(vm.$el.innerHTML).toBe('slot:123
')
})
it('is', () => {
const vm = makeInstance({
attr: 'is',
value: 'comp',
parentTemp: ' ',
childTemp: 'comp
'
})
expect(vm.$el.innerHTML).toBe('comp
')
})
})
})
node-vue-template-compiler-2.4.2+dfsg/test/unit/features/directives/class.spec.js000066400000000000000000000112401361753775300301310ustar00rootroot00000000000000import Vue from 'vue'
function assertClass (assertions, done) {
const vm = new Vue({
template: '
',
data: { value: '' }
}).$mount()
var chain = waitForUpdate()
assertions.forEach(([value, expected], i) => {
chain.then(() => {
if (typeof value === 'function') {
value(vm.value)
} else {
vm.value = value
}
}).then(() => {
expect(vm.$el.className).toBe(expected)
if (i >= assertions.length - 1) {
done()
}
})
})
chain.then(done)
}
describe('Directive v-bind:class', () => {
it('plain string', done => {
assertClass([
['bar', 'foo bar'],
['baz qux', 'foo baz qux'],
['qux', 'foo qux'],
[undefined, 'foo']
], done)
})
it('object value', done => {
assertClass([
[{ bar: true, baz: false }, 'foo bar'],
[{ baz: true }, 'foo baz'],
[null, 'foo'],
[{ 'bar baz': true, qux: false }, 'foo bar baz'],
[{ qux: true }, 'foo qux']
], done)
})
it('array value', done => {
assertClass([
[['bar', 'baz'], 'foo bar baz'],
[['qux', 'baz'], 'foo qux baz'],
[['w', 'x y z'], 'foo w x y z'],
[undefined, 'foo'],
[['bar'], 'foo bar'],
[val => val.push('baz'), 'foo bar baz']
], done)
})
it('array of mixed values', done => {
assertClass([
[['x', { y: true, z: true }], 'foo x y z'],
[['x', { y: true, z: false }], 'foo x y'],
[['f', { z: true }], 'foo f z'],
[['l', 'f', { n: true, z: true }], 'foo l f n z'],
[['x', {}], 'foo x'],
[undefined, 'foo']
], done)
})
it('class merge between parent and child', done => {
const vm = new Vue({
template: ' ',
data: { value: 'b' },
components: {
child: {
template: '
',
data: () => ({ value: 'd' })
}
}
}).$mount()
const child = vm.$children[0]
expect(vm.$el.className).toBe('c a d b')
vm.value = 'e'
waitForUpdate(() => {
expect(vm.$el.className).toBe('c a d e')
}).then(() => {
child.value = 'f'
}).then(() => {
expect(vm.$el.className).toBe('c a f e')
}).then(() => {
vm.value = { foo: true }
child.value = ['bar', 'baz']
}).then(() => {
expect(vm.$el.className).toBe('c a bar baz foo')
}).then(done)
})
it('class merge between multiple nested components sharing same element', done => {
const vm = new Vue({
template: `
some text
`,
data: {
componentClass1: 'componentClass1',
componentClass2: 'componentClass2',
componentClass3: 'componentClass3'
},
components: {
component1: {
render () {
return this.$slots.default[0]
}
},
component2: {
render () {
return this.$slots.default[0]
}
},
component3: {
template: '
'
}
}
}).$mount()
expect(vm.$el.className).toBe('staticClass componentClass3 componentClass2 componentClass1')
vm.componentClass1 = 'c1'
waitForUpdate(() => {
expect(vm.$el.className).toBe('staticClass componentClass3 componentClass2 c1')
vm.componentClass2 = 'c2'
}).then(() => {
expect(vm.$el.className).toBe('staticClass componentClass3 c2 c1')
vm.componentClass3 = 'c3'
}).then(() => {
expect(vm.$el.className).toBe('staticClass c3 c2 c1')
}).then(done)
})
it('deep update', done => {
const vm = new Vue({
template: '
',
data: {
test: { a: true, b: false }
}
}).$mount()
expect(vm.$el.className).toBe('a')
vm.test.b = true
waitForUpdate(() => {
expect(vm.$el.className).toBe('a b')
}).then(done)
})
// a vdom patch edge case where the user has several un-keyed elements of the
// same tag next to each other, and toggling them.
it('properly remove staticClass for toggling un-keyed children', done => {
const vm = new Vue({
template: `
`,
data: {
ok: true
}
}).$mount()
expect(vm.$el.children[0].className).toBe('a')
vm.ok = false
waitForUpdate(() => {
expect(vm.$el.children[0].className).toBe('')
}).then(done)
})
})
node-vue-template-compiler-2.4.2+dfsg/test/unit/features/directives/cloak.spec.js000066400000000000000000000004331361753775300301170ustar00rootroot00000000000000import Vue from 'vue'
describe('Directive v-cloak', () => {
it('should be removed after compile', () => {
const el = document.createElement('div')
el.setAttribute('v-cloak', '')
const vm = new Vue({ el })
expect(vm.$el.hasAttribute('v-cloak')).toBe(false)
})
})
node-vue-template-compiler-2.4.2+dfsg/test/unit/features/directives/for.spec.js000066400000000000000000000321311361753775300276140ustar00rootroot00000000000000import Vue from 'vue'
describe('Directive v-for', () => {
it('should render array of primitive values', done => {
const vm = new Vue({
template: `
{{item}}
`,
data: {
list: ['a', 'b', 'c']
}
}).$mount()
expect(vm.$el.innerHTML).toBe('a b c ')
Vue.set(vm.list, 0, 'd')
waitForUpdate(() => {
expect(vm.$el.innerHTML).toBe('d b c ')
vm.list.push('d')
}).then(() => {
expect(vm.$el.innerHTML).toBe('d b c d ')
vm.list.splice(1, 2)
}).then(() => {
expect(vm.$el.innerHTML).toBe('d d ')
vm.list = ['x', 'y']
}).then(() => {
expect(vm.$el.innerHTML).toBe('x y ')
}).then(done)
})
it('should render array of primitive values with index', done => {
const vm = new Vue({
template: `
{{i}}-{{item}}
`,
data: {
list: ['a', 'b', 'c']
}
}).$mount()
expect(vm.$el.innerHTML).toBe('0-a 1-b 2-c ')
Vue.set(vm.list, 0, 'd')
waitForUpdate(() => {
expect(vm.$el.innerHTML).toBe('0-d 1-b 2-c ')
vm.list.push('d')
}).then(() => {
expect(vm.$el.innerHTML).toBe('0-d 1-b 2-c 3-d ')
vm.list.splice(1, 2)
}).then(() => {
expect(vm.$el.innerHTML).toBe('0-d 1-d ')
vm.list = ['x', 'y']
}).then(() => {
expect(vm.$el.innerHTML).toBe('0-x 1-y ')
}).then(done)
})
it('should render array of object values', done => {
const vm = new Vue({
template: `
{{item.value}}
`,
data: {
list: [
{ value: 'a' },
{ value: 'b' },
{ value: 'c' }
]
}
}).$mount()
expect(vm.$el.innerHTML).toBe('a b c ')
Vue.set(vm.list, 0, { value: 'd' })
waitForUpdate(() => {
expect(vm.$el.innerHTML).toBe('d b c ')
vm.list[0].value = 'e'
}).then(() => {
expect(vm.$el.innerHTML).toBe('e b c ')
vm.list.push({})
}).then(() => {
expect(vm.$el.innerHTML).toBe('e b c ')
vm.list.splice(1, 2)
}).then(() => {
expect(vm.$el.innerHTML).toBe('e ')
vm.list = [{ value: 'x' }, { value: 'y' }]
}).then(() => {
expect(vm.$el.innerHTML).toBe('x y ')
}).then(done)
})
it('should render array of object values with index', done => {
const vm = new Vue({
template: `
{{i}}-{{item.value}}
`,
data: {
list: [
{ value: 'a' },
{ value: 'b' },
{ value: 'c' }
]
}
}).$mount()
expect(vm.$el.innerHTML).toBe('0-a 1-b 2-c ')
Vue.set(vm.list, 0, { value: 'd' })
waitForUpdate(() => {
expect(vm.$el.innerHTML).toBe('0-d 1-b 2-c ')
vm.list[0].value = 'e'
}).then(() => {
expect(vm.$el.innerHTML).toBe('0-e 1-b 2-c ')
vm.list.push({})
}).then(() => {
expect(vm.$el.innerHTML).toBe('0-e 1-b 2-c 3- ')
vm.list.splice(1, 2)
}).then(() => {
expect(vm.$el.innerHTML).toBe('0-e 1- ')
vm.list = [{ value: 'x' }, { value: 'y' }]
}).then(() => {
expect(vm.$el.innerHTML).toBe('0-x 1-y ')
}).then(done)
})
it('should render an Object', done => {
const vm = new Vue({
template: `
{{val}}
`,
data: {
obj: { a: 0, b: 1, c: 2 }
}
}).$mount()
expect(vm.$el.innerHTML).toBe('0 1 2 ')
vm.obj.a = 3
waitForUpdate(() => {
expect(vm.$el.innerHTML).toBe('3 1 2 ')
Vue.set(vm.obj, 'd', 4)
}).then(() => {
expect(vm.$el.innerHTML).toBe('3 1 2 4 ')
Vue.delete(vm.obj, 'a')
}).then(() => {
expect(vm.$el.innerHTML).toBe('1 2 4 ')
}).then(done)
})
it('should render an Object with key', done => {
const vm = new Vue({
template: `
{{val}}-{{key}}
`,
data: {
obj: { a: 0, b: 1, c: 2 }
}
}).$mount()
expect(vm.$el.innerHTML).toBe('0-a 1-b 2-c ')
vm.obj.a = 3
waitForUpdate(() => {
expect(vm.$el.innerHTML).toBe('3-a 1-b 2-c ')
Vue.set(vm.obj, 'd', 4)
}).then(() => {
expect(vm.$el.innerHTML).toBe('3-a 1-b 2-c 4-d ')
Vue.delete(vm.obj, 'a')
}).then(() => {
expect(vm.$el.innerHTML).toBe('1-b 2-c 4-d ')
}).then(done)
})
it('should render an Object with key and index', done => {
const vm = new Vue({
template: `
{{val}}-{{key}}-{{i}}
`,
data: {
obj: { a: 0, b: 1, c: 2 }
}
}).$mount()
expect(vm.$el.innerHTML).toBe('0-a-0 1-b-1 2-c-2 ')
vm.obj.a = 3
waitForUpdate(() => {
expect(vm.$el.innerHTML).toBe('3-a-0 1-b-1 2-c-2 ')
Vue.set(vm.obj, 'd', 4)
}).then(() => {
expect(vm.$el.innerHTML).toBe('3-a-0 1-b-1 2-c-2 4-d-3 ')
Vue.delete(vm.obj, 'a')
}).then(() => {
expect(vm.$el.innerHTML).toBe('1-b-0 2-c-1 4-d-2 ')
}).then(done)
})
it('should render each key of data', done => {
const vm = new Vue({
template: `
{{val}}-{{key}}
`,
data: { a: 0, b: 1, c: 2 }
}).$mount()
expect(vm.$el.innerHTML).toBe('0-a 1-b 2-c ')
vm.a = 3
waitForUpdate(() => {
expect(vm.$el.innerHTML).toBe('3-a 1-b 2-c ')
}).then(done)
})
it('check priorities: v-if before v-for', function () {
const vm = new Vue({
data: {
items: [1, 2, 3]
},
template: ''
}).$mount()
expect(vm.$el.textContent).toBe('12')
})
it('check priorities: v-if after v-for', function () {
const vm = new Vue({
data: {
items: [1, 2, 3]
},
template: ''
}).$mount()
expect(vm.$el.textContent).toBe('12')
})
it('range v-for', () => {
const vm = new Vue({
template: ''
}).$mount()
expect(vm.$el.textContent).toBe('123')
})
it('without key', done => {
const vm = new Vue({
data: {
items: [
{ id: 1, msg: 'a' },
{ id: 2, msg: 'b' },
{ id: 3, msg: 'c' }
]
},
template: ''
}).$mount()
expect(vm.$el.textContent).toBe('abc')
const first = vm.$el.children[0]
vm.items.reverse()
waitForUpdate(() => {
expect(vm.$el.textContent).toBe('cba')
// assert reusing DOM element in place
expect(vm.$el.children[0]).toBe(first)
}).then(done)
})
it('with key', done => {
const vm = new Vue({
data: {
items: [
{ id: 1, msg: 'a' },
{ id: 2, msg: 'b' },
{ id: 3, msg: 'c' }
]
},
template: ''
}).$mount()
expect(vm.$el.textContent).toBe('abc')
const first = vm.$el.children[0]
vm.items.reverse()
waitForUpdate(() => {
expect(vm.$el.textContent).toBe('cba')
// assert moving DOM element
expect(vm.$el.children[0]).not.toBe(first)
expect(vm.$el.children[2]).toBe(first)
}).then(done)
})
it('nested loops', () => {
const vm = new Vue({
data: {
items: [
{ items: [{ a: 1 }, { a: 2 }], a: 1 },
{ items: [{ a: 3 }, { a: 4 }], a: 2 }
]
},
template:
'' +
'
' +
'
{{j}} {{subItem.a}} {{i}} {{item.a}}
' +
'
' +
'
'
}).$mount()
expect(vm.$el.innerHTML).toBe(
'' +
''
)
})
it('template v-for', done => {
const vm = new Vue({
data: {
list: [
{ a: 1 },
{ a: 2 },
{ a: 3 }
]
},
template:
'' +
'
' +
'{{item.a}}
' +
'{{item.a + 1}}
' +
' ' +
'
'
}).$mount()
assertMarkup()
vm.list.reverse()
waitForUpdate(() => {
assertMarkup()
vm.list.splice(1, 1)
}).then(() => {
assertMarkup()
vm.list.splice(1, 0, { a: 2 })
}).then(done)
function assertMarkup () {
var markup = vm.list.map(function (item) {
return '' + item.a + '
' + (item.a + 1) + '
'
}).join('')
expect(vm.$el.innerHTML).toBe(markup)
}
})
it('component v-for', done => {
const vm = new Vue({
data: {
list: [
{ a: 1 },
{ a: 2 },
{ a: 3 }
]
},
template:
'' +
'' +
'{{item.a}} ' +
' ' +
'
',
components: {
test: {
props: ['msg'],
template: '{{msg}}
'
}
}
}).$mount()
assertMarkup()
vm.list.reverse()
waitForUpdate(() => {
assertMarkup()
vm.list.splice(1, 1)
}).then(() => {
assertMarkup()
vm.list.splice(1, 0, { a: 2 })
}).then(done)
function assertMarkup () {
var markup = vm.list.map(function (item) {
return `${item.a}${item.a}
`
}).join('')
expect(vm.$el.innerHTML).toBe(markup)
}
})
it('dynamic component v-for', done => {
const vm = new Vue({
data: {
list: [
{ type: 'one' },
{ type: 'two' }
]
},
template:
'' +
' ' +
'
',
components: {
one: {
template: 'One!
'
},
two: {
template: 'Two!
'
}
}
}).$mount()
expect(vm.$el.innerHTML).toContain('One!
Two!
')
vm.list.reverse()
waitForUpdate(() => {
expect(vm.$el.innerHTML).toContain('Two!
One!
')
}).then(done)
})
it('should warn component v-for without keys', () => {
const warn = console.warn
console.warn = jasmine.createSpy()
new Vue({
template: `
`,
components: {
test: {
render () {}
}
}
}).$mount()
expect(console.warn.calls.argsFor(0)[0]).toContain(
`: component lists rendered with v-for should have explicit keys`
)
console.warn = warn
})
it('multi nested array reactivity', done => {
const vm = new Vue({
data: {
list: [[['foo']]]
},
template: `
`
}).$mount()
expect(vm.$el.textContent).toMatch(/\s+foo\s+/)
vm.list[0][0].push('bar')
waitForUpdate(() => {
expect(vm.$el.textContent).toMatch(/\s+foo\s+bar\s+/)
}).then(done)
})
it('strings', done => {
const vm = new Vue({
data: {
text: 'foo'
},
template: `
{{ letter }}.
`
}).$mount()
expect(vm.$el.textContent).toMatch('f.o.o.')
vm.text += 'bar'
waitForUpdate(() => {
expect(vm.$el.textContent).toMatch('f.o.o.b.a.r.')
}).then(done)
})
})
node-vue-template-compiler-2.4.2+dfsg/test/unit/features/directives/html.spec.js000066400000000000000000000034331361753775300277750ustar00rootroot00000000000000import Vue from 'vue'
describe('Directive v-html', () => {
it('should render html', () => {
const vm = new Vue({
template: '
',
data: { a: 'hello' }
}).$mount()
expect(vm.$el.innerHTML).toBe('hello')
})
it('should encode html entities', () => {
const vm = new Vue({
template: '
',
data: { a: '< ' }
}).$mount()
expect(vm.$el.innerHTML).toBe('< ')
})
it('should work inline', () => {
const vm = new Vue({
template: `
`
}).$mount()
expect(vm.$el.innerHTML).toBe('< ')
})
it('should work inline in DOM', () => {
const el = document.createElement('div')
el.innerHTML = `
`
const vm = new Vue({ el })
expect(vm.$el.children[0].innerHTML).toBe('< ')
})
it('should support all value types', done => {
const vm = new Vue({
template: '
',
data: { a: false }
}).$mount()
waitForUpdate(() => {
expect(vm.$el.innerHTML).toBe('false')
vm.a = []
}).then(() => {
expect(vm.$el.innerHTML).toBe('[]')
vm.a = {}
}).then(() => {
expect(vm.$el.innerHTML).toBe('{}')
vm.a = 123
}).then(() => {
expect(vm.$el.innerHTML).toBe('123')
vm.a = 0
}).then(() => {
expect(vm.$el.innerHTML).toBe('0')
vm.a = ' '
}).then(() => {
expect(vm.$el.innerHTML).toBe(' ')
vm.a = ' '
}).then(() => {
expect(vm.$el.innerHTML).toBe(' ')
vm.a = null
}).then(() => {
expect(vm.$el.innerHTML).toBe('')
vm.a = undefined
}).then(() => {
expect(vm.$el.innerHTML).toBe('')
}).then(done)
})
})
node-vue-template-compiler-2.4.2+dfsg/test/unit/features/directives/if.spec.js000066400000000000000000000177251361753775300274400ustar00rootroot00000000000000import Vue from 'vue'
describe('Directive v-if', () => {
it('should check if value is truthy', () => {
const vm = new Vue({
template: 'hello
',
data: { foo: true }
}).$mount()
expect(vm.$el.innerHTML).toBe('hello ')
})
it('should check if value is falsy', () => {
const vm = new Vue({
template: 'hello
',
data: { foo: false }
}).$mount()
expect(vm.$el.innerHTML).toBe('')
})
it('should update if value changed', done => {
const vm = new Vue({
template: 'hello
',
data: { foo: true }
}).$mount()
expect(vm.$el.innerHTML).toBe('hello ')
vm.foo = false
waitForUpdate(() => {
expect(vm.$el.innerHTML).toBe('')
vm.foo = {}
}).then(() => {
expect(vm.$el.innerHTML).toBe('hello ')
vm.foo = 0
}).then(() => {
expect(vm.$el.innerHTML).toBe('')
vm.foo = []
}).then(() => {
expect(vm.$el.innerHTML).toBe('hello ')
vm.foo = null
}).then(() => {
expect(vm.$el.innerHTML).toBe('')
vm.foo = '0'
}).then(() => {
expect(vm.$el.innerHTML).toBe('hello ')
vm.foo = undefined
}).then(() => {
expect(vm.$el.innerHTML).toBe('')
vm.foo = 1
}).then(() => {
expect(vm.$el.innerHTML).toBe('hello ')
}).then(done)
})
it('should work well with v-else', done => {
const vm = new Vue({
template: `
hello
bye
`,
data: { foo: true }
}).$mount()
expect(vm.$el.innerHTML.trim()).toBe('hello ')
vm.foo = false
waitForUpdate(() => {
expect(vm.$el.innerHTML.trim()).toBe('bye ')
vm.foo = {}
}).then(() => {
expect(vm.$el.innerHTML.trim()).toBe('hello ')
vm.foo = 0
}).then(() => {
expect(vm.$el.innerHTML.trim()).toBe('bye ')
vm.foo = []
}).then(() => {
expect(vm.$el.innerHTML.trim()).toBe('hello ')
vm.foo = null
}).then(() => {
expect(vm.$el.innerHTML.trim()).toBe('bye ')
vm.foo = '0'
}).then(() => {
expect(vm.$el.innerHTML.trim()).toBe('hello ')
vm.foo = undefined
}).then(() => {
expect(vm.$el.innerHTML.trim()).toBe('bye ')
vm.foo = 1
}).then(() => {
expect(vm.$el.innerHTML.trim()).toBe('hello ')
}).then(done)
})
it('should work well with v-else-if', done => {
const vm = new Vue({
template: `
hello
elseif
bye
`,
data: { foo: true, bar: false }
}).$mount()
expect(vm.$el.innerHTML.trim()).toBe('hello ')
vm.foo = false
waitForUpdate(() => {
expect(vm.$el.innerHTML.trim()).toBe('bye ')
vm.bar = true
}).then(() => {
expect(vm.$el.innerHTML.trim()).toBe('elseif ')
vm.bar = false
}).then(() => {
expect(vm.$el.innerHTML.trim()).toBe('bye ')
vm.foo = true
}).then(() => {
expect(vm.$el.innerHTML.trim()).toBe('hello ')
vm.foo = false
vm.bar = {}
}).then(() => {
expect(vm.$el.innerHTML.trim()).toBe('elseif ')
vm.bar = 0
}).then(() => {
expect(vm.$el.innerHTML.trim()).toBe('bye ')
vm.bar = []
}).then(() => {
expect(vm.$el.innerHTML.trim()).toBe('elseif ')
vm.bar = null
}).then(() => {
expect(vm.$el.innerHTML.trim()).toBe('bye ')
vm.bar = '0'
}).then(() => {
expect(vm.$el.innerHTML.trim()).toBe('elseif ')
vm.bar = undefined
}).then(() => {
expect(vm.$el.innerHTML.trim()).toBe('bye ')
vm.bar = 1
}).then(() => {
expect(vm.$el.innerHTML.trim()).toBe('elseif ')
}).then(done)
})
it('should work well with v-for', done => {
const vm = new Vue({
template: `
{{i}}
`,
data: {
list: [
{ value: true },
{ value: false },
{ value: true }
]
}
}).$mount()
expect(vm.$el.innerHTML).toBe('0 2 ')
vm.list[0].value = false
waitForUpdate(() => {
expect(vm.$el.innerHTML).toBe('2 ')
vm.list.push({ value: true })
}).then(() => {
expect(vm.$el.innerHTML).toBe('2 3 ')
vm.list.splice(1, 2)
}).then(() => {
expect(vm.$el.innerHTML).toBe('1 ')
}).then(done)
})
it('should work well with v-for and v-else', done => {
const vm = new Vue({
template: `
hello
bye
`,
data: {
list: [
{ value: true },
{ value: false },
{ value: true }
]
}
}).$mount()
expect(vm.$el.innerHTML.trim()).toBe('hello bye hello ')
vm.list[0].value = false
waitForUpdate(() => {
expect(vm.$el.innerHTML.trim()).toBe('bye bye hello ')
vm.list.push({ value: true })
}).then(() => {
expect(vm.$el.innerHTML.trim()).toBe('bye bye hello hello ')
vm.list.splice(1, 2)
}).then(() => {
expect(vm.$el.innerHTML.trim()).toBe('bye hello ')
}).then(done)
})
it('should work with v-for on v-else branch', done => {
const vm = new Vue({
template: `
hello
{{ item }}
`,
data: {
list: [1, 2, 3]
}
}).$mount()
expect(vm.$el.textContent.trim()).toBe('123')
vm.list.reverse()
waitForUpdate(() => {
expect(vm.$el.textContent.trim()).toBe('321')
}).then(done)
})
it('should work properly on component root', done => {
const vm = new Vue({
template: `
`,
components: {
test: {
data () {
return { ok: true }
},
template: 'test
'
}
}
}).$mount()
expect(vm.$el.children[0].id).toBe('ok')
expect(vm.$el.children[0].className).toBe('inner test')
vm.$children[0].ok = false
waitForUpdate(() => {
// attrs / class modules should not attempt to patch the comment node
expect(vm.$el.innerHTML).toBe('')
vm.$children[0].ok = true
}).then(() => {
expect(vm.$el.children[0].id).toBe('ok')
expect(vm.$el.children[0].className).toBe('inner test')
}).then(done)
})
it('should maintain stable list to avoid unnecessary patches', done => {
const created = jasmine.createSpy()
const destroyed = jasmine.createSpy()
const vm = new Vue({
data: {
ok: true
},
// when the first div is toggled, the second div should be reused
// instead of re-created/destroyed
template: `
`,
components: {
test: {
template: '
',
created,
destroyed
}
}
}).$mount()
expect(created.calls.count()).toBe(1)
vm.ok = false
waitForUpdate(() => {
expect(created.calls.count()).toBe(1)
expect(destroyed).not.toHaveBeenCalled()
}).then(done)
})
})
node-vue-template-compiler-2.4.2+dfsg/test/unit/features/directives/model-checkbox.spec.js000066400000000000000000000225411361753775300317160ustar00rootroot00000000000000import Vue from 'vue'
describe('Directive v-model checkbox', () => {
it('should work', done => {
const vm = new Vue({
data: {
test: true
},
template: ' '
}).$mount()
document.body.appendChild(vm.$el)
expect(vm.$el.checked).toBe(true)
vm.test = false
waitForUpdate(function () {
expect(vm.$el.checked).toBe(false)
expect(vm.test).toBe(false)
vm.$el.click()
expect(vm.$el.checked).toBe(true)
expect(vm.test).toBe(true)
}).then(() => {
document.body.removeChild(vm.$el)
}).then(done)
})
it('should respect value bindings', done => {
const vm = new Vue({
data: {
test: 1,
a: 1,
b: 2
},
template: ' '
}).$mount()
document.body.appendChild(vm.$el)
expect(vm.$el.checked).toBe(true)
vm.$el.click()
expect(vm.$el.checked).toBe(false)
expect(vm.test).toBe(2)
vm.$el.click()
expect(vm.$el.checked).toBe(true)
expect(vm.test).toBe(1)
vm.test = 2
waitForUpdate(() => {
expect(vm.$el.checked).toBe(false)
vm.test = 1
}).then(() => {
expect(vm.$el.checked).toBe(true)
document.body.removeChild(vm.$el)
}).then(done)
})
it('bind to Array value', done => {
const vm = new Vue({
data: {
test: ['1']
},
template: `
`
}).$mount()
document.body.appendChild(vm.$el)
expect(vm.$el.children[0].checked).toBe(true)
expect(vm.$el.children[1].checked).toBe(false)
vm.$el.children[0].click()
expect(vm.test.length).toBe(0)
vm.$el.children[1].click()
expect(vm.test).toEqual(['2'])
vm.$el.children[0].click()
expect(vm.test).toEqual(['2', '1'])
vm.test = ['1']
waitForUpdate(() => {
expect(vm.$el.children[0].checked).toBe(true)
expect(vm.$el.children[1].checked).toBe(false)
}).then(done)
})
it('bind to Array value ignores false-value', done => {
const vm = new Vue({
data: {
test: ['1']
},
template: `
`
}).$mount()
document.body.appendChild(vm.$el)
expect(vm.$el.children[0].checked).toBe(true)
expect(vm.$el.children[1].checked).toBe(false)
vm.$el.children[0].click()
expect(vm.test.length).toBe(0)
vm.$el.children[1].click()
expect(vm.test).toEqual(['2'])
vm.$el.children[0].click()
expect(vm.test).toEqual(['2', '1'])
vm.test = ['1']
waitForUpdate(() => {
expect(vm.$el.children[0].checked).toBe(true)
expect(vm.$el.children[1].checked).toBe(false)
}).then(done)
})
it('bind to Array value with value bindings', done => {
const vm = new Vue({
data: {
test: [1]
},
template: `
`
}).$mount()
document.body.appendChild(vm.$el)
expect(vm.$el.children[0].checked).toBe(true)
expect(vm.$el.children[1].checked).toBe(false)
vm.$el.children[0].click()
expect(vm.test.length).toBe(0)
vm.$el.children[1].click()
expect(vm.test).toEqual([2])
vm.$el.children[0].click()
expect(vm.test).toEqual([2, 1])
vm.test = [1]
waitForUpdate(() => {
expect(vm.$el.children[0].checked).toBe(true)
expect(vm.$el.children[1].checked).toBe(false)
}).then(done)
})
it('bind to Array value with value bindings (object loose equal)', done => {
const vm = new Vue({
data: {
test: [{ a: 1 }]
},
template: `
`
}).$mount()
document.body.appendChild(vm.$el)
expect(vm.$el.children[0].checked).toBe(true)
expect(vm.$el.children[1].checked).toBe(false)
vm.$el.children[0].click()
expect(vm.test.length).toBe(0)
vm.$el.children[1].click()
expect(vm.test).toEqual([{ a: 2 }])
vm.$el.children[0].click()
expect(vm.test).toEqual([{ a: 2 }, { a: 1 }])
vm.test = [{ a: 1 }]
waitForUpdate(() => {
expect(vm.$el.children[0].checked).toBe(true)
expect(vm.$el.children[1].checked).toBe(false)
}).then(done)
})
it('.number modifier', () => {
const vm = new Vue({
data: {
test: [],
check: true
},
template: `
`
}).$mount()
document.body.appendChild(vm.$el)
const checkboxInputs = vm.$el.getElementsByTagName('input')
expect(checkboxInputs[0].checked).toBe(false)
expect(checkboxInputs[1].checked).toBe(false)
expect(checkboxInputs[2].checked).toBe(true)
checkboxInputs[0].click()
checkboxInputs[1].click()
checkboxInputs[2].click()
expect(vm.test).toEqual([1, '2'])
expect(vm.check).toEqual(false)
})
it('should respect different primitive type value', (done) => {
const vm = new Vue({
data: {
test: [0]
},
template:
'' +
' ' +
' ' +
' ' +
' ' +
' ' +
'
'
}).$mount()
const checkboxInput = vm.$el.children
expect(checkboxInput[0].checked).toBe(false)
expect(checkboxInput[1].checked).toBe(true)
expect(checkboxInput[2].checked).toBe(false)
expect(checkboxInput[3].checked).toBe(false)
expect(checkboxInput[4].checked).toBe(false)
vm.test = [1]
waitForUpdate(() => {
expect(checkboxInput[0].checked).toBe(false)
expect(checkboxInput[1].checked).toBe(false)
expect(checkboxInput[2].checked).toBe(true)
expect(checkboxInput[3].checked).toBe(false)
expect(checkboxInput[4].checked).toBe(false)
vm.test = ['']
}).then(() => {
expect(checkboxInput[0].checked).toBe(true)
expect(checkboxInput[1].checked).toBe(false)
expect(checkboxInput[2].checked).toBe(false)
expect(checkboxInput[3].checked).toBe(false)
expect(checkboxInput[4].checked).toBe(false)
vm.test = [false]
}).then(() => {
expect(checkboxInput[0].checked).toBe(false)
expect(checkboxInput[1].checked).toBe(false)
expect(checkboxInput[2].checked).toBe(false)
expect(checkboxInput[3].checked).toBe(true)
expect(checkboxInput[4].checked).toBe(false)
vm.test = [true]
}).then(() => {
expect(checkboxInput[0].checked).toBe(false)
expect(checkboxInput[1].checked).toBe(false)
expect(checkboxInput[2].checked).toBe(false)
expect(checkboxInput[3].checked).toBe(false)
expect(checkboxInput[4].checked).toBe(true)
vm.test = ['', 0, 1, false, true]
}).then(() => {
expect(checkboxInput[0].checked).toBe(true)
expect(checkboxInput[1].checked).toBe(true)
expect(checkboxInput[2].checked).toBe(true)
expect(checkboxInput[3].checked).toBe(true)
expect(checkboxInput[4].checked).toBe(true)
}).then(done)
})
// #4521
it('should work with click event', (done) => {
const vm = new Vue({
data: {
num: 1,
checked: false
},
template: 'click {{ num }}
',
methods: {
add: function () {
this.num++
}
}
}).$mount()
document.body.appendChild(vm.$el)
const checkbox = vm.$refs.checkbox
checkbox.click()
waitForUpdate(() => {
expect(checkbox.checked).toBe(true)
expect(vm.num).toBe(2)
}).then(done)
})
it('should get updated with model when in focus', (done) => {
const vm = new Vue({
data: {
a: 2
},
template: ' '
}).$mount()
document.body.appendChild(vm.$el)
vm.$el.click()
waitForUpdate(() => {
expect(vm.$el.checked).toBe(false)
vm.a = 2
}).then(() => {
expect(vm.$el.checked).toBe(true)
}).then(done)
})
it('triggers a watcher when binding to an array value in a checkbox', done => {
const vm = new Vue({
data: {
test: {
thing: false,
arr: [true]
}
},
template: `
{{ test.arr[0] }}
`
}).$mount()
document.body.appendChild(vm.$el)
expect(vm.$el.children[0].checked).toBe(true)
expect(vm.$el.children[1].textContent).toBe('true')
vm.$el.children[0].click()
expect(vm.$el.children[0].checked).toBe(false)
waitForUpdate(() => {
expect(vm.$el.children[1].textContent).toBe('false')
}).then(done)
})
})
node-vue-template-compiler-2.4.2+dfsg/test/unit/features/directives/model-component.spec.js000066400000000000000000000102551361753775300321310ustar00rootroot00000000000000import Vue from 'vue'
describe('Directive v-model component', () => {
it('should work', done => {
const vm = new Vue({
data: {
msg: 'hello'
},
template: `
`,
components: {
test: {
props: ['value'],
template: ` `
}
}
}).$mount()
document.body.appendChild(vm.$el)
waitForUpdate(() => {
const input = vm.$el.querySelector('input')
input.value = 'world'
triggerEvent(input, 'input')
}).then(() => {
expect(vm.msg).toEqual('world')
expect(vm.$el.querySelector('p').textContent).toEqual('world')
vm.msg = 'changed'
}).then(() => {
expect(vm.$el.querySelector('p').textContent).toEqual('changed')
expect(vm.$el.querySelector('input').value).toEqual('changed')
}).then(() => {
document.body.removeChild(vm.$el)
}).then(done)
})
it('should work with native tags with "is"', done => {
const vm = new Vue({
data: {
msg: 'hello'
},
template: `
`,
components: {
test: {
props: ['value'],
template: ` `
}
}
}).$mount()
document.body.appendChild(vm.$el)
waitForUpdate(() => {
const input = vm.$el.querySelector('input')
input.value = 'world'
triggerEvent(input, 'input')
}).then(() => {
expect(vm.msg).toEqual('world')
expect(vm.$el.querySelector('p').textContent).toEqual('world')
vm.msg = 'changed'
}).then(() => {
expect(vm.$el.querySelector('p').textContent).toEqual('changed')
expect(vm.$el.querySelector('input').value).toEqual('changed')
}).then(() => {
document.body.removeChild(vm.$el)
}).then(done)
})
it('should support customization via model option', done => {
const spy = jasmine.createSpy('update')
const vm = new Vue({
data: {
msg: 'hello'
},
methods: {
spy
},
template: `
`,
components: {
test: {
model: {
prop: 'currentValue',
event: 'update'
},
props: ['currentValue'],
template: ` `
}
}
}).$mount()
document.body.appendChild(vm.$el)
waitForUpdate(() => {
const input = vm.$el.querySelector('input')
input.value = 'world'
triggerEvent(input, 'input')
}).then(() => {
expect(vm.msg).toEqual('world')
expect(vm.$el.querySelector('p').textContent).toEqual('world')
expect(spy).toHaveBeenCalledWith('world')
vm.msg = 'changed'
}).then(() => {
expect(vm.$el.querySelector('p').textContent).toEqual('changed')
expect(vm.$el.querySelector('input').value).toEqual('changed')
}).then(() => {
document.body.removeChild(vm.$el)
}).then(done)
})
it('modifier: .number', () => {
const vm = new Vue({
template: `
`,
data: { text: 'foo' },
components: {
'my-input': {
template: ' '
}
}
}).$mount()
expect(vm.text).toBe('foo')
vm.$refs.input.$emit('input', 'bar')
expect(vm.text).toBe('bar')
vm.$refs.input.$emit('input', '123')
expect(vm.text).toBe(123)
})
it('modifier: .trim', () => {
const vm = new Vue({
template: `
`,
data: { text: 'foo' },
components: {
'my-input': {
template: ' '
}
}
}).$mount()
expect(vm.text).toBe('foo')
vm.$refs.input.$emit('input', ' bar ')
expect(vm.text).toBe('bar')
vm.$refs.input.$emit('input', ' foo o ')
expect(vm.text).toBe('foo o')
})
})
node-vue-template-compiler-2.4.2+dfsg/test/unit/features/directives/model-dynamic.spec.js000066400000000000000000000005341361753775300315520ustar00rootroot00000000000000import Vue from 'vue'
describe('Directive v-model dynamic input type', () => {
it('should warn', function () {
new Vue({
data: {
type: 'text',
text: 'hi'
},
template: ` `
}).$mount()
expect(`v-model does not support dynamic input types`).toHaveBeenWarned()
})
})
node-vue-template-compiler-2.4.2+dfsg/test/unit/features/directives/model-file.spec.js000066400000000000000000000004651361753775300310500ustar00rootroot00000000000000import Vue from 'vue'
describe('Directive v-model file', () => {
it('warn to use @change instead', () => {
new Vue({
data: {
file: ''
},
template: ' '
}).$mount()
expect('Use a v-on:change listener instead').toHaveBeenWarned()
})
})
node-vue-template-compiler-2.4.2+dfsg/test/unit/features/directives/model-parse.spec.js000066400000000000000000000016071361753775300312420ustar00rootroot00000000000000import { parseModel } from 'compiler/directives/model'
describe('model expression parser', () => {
it('parse object dot notation', () => {
const res = parseModel('a.b.c')
expect(res.exp).toBe('a.b.c')
expect(res.idx).toBe(null)
})
it('parse string in brackets', () => {
const res = parseModel('a["b"][c]')
expect(res.exp).toBe('a["b"]')
expect(res.idx).toBe('c')
})
it('parse brackets with object dot notation', () => {
const res = parseModel('a["b"][c].xxx')
expect(res.exp).toBe('a["b"][c].xxx')
expect(res.idx).toBe(null)
})
it('parse nested brackets', () => {
const res = parseModel('a[i[c]]')
expect(res.exp).toBe('a')
expect(res.idx).toBe('i[c]')
})
it('combined', () => {
const res = parseModel('test.xxx.a["asa"][test1[idx]]')
expect(res.exp).toBe('test.xxx.a["asa"]')
expect(res.idx).toBe('test1[idx]')
})
})
node-vue-template-compiler-2.4.2+dfsg/test/unit/features/directives/model-radio.spec.js000066400000000000000000000174311361753775300312300ustar00rootroot00000000000000import Vue from 'vue'
describe('Directive v-model radio', () => {
it('should work', done => {
const vm = new Vue({
data: {
test: '1'
},
template: `
`
}).$mount()
document.body.appendChild(vm.$el)
expect(vm.$el.children[0].checked).toBe(true)
expect(vm.$el.children[1].checked).toBe(false)
vm.test = '2'
waitForUpdate(() => {
expect(vm.$el.children[0].checked).toBe(false)
expect(vm.$el.children[1].checked).toBe(true)
vm.$el.children[0].click()
expect(vm.$el.children[0].checked).toBe(true)
expect(vm.$el.children[1].checked).toBe(false)
expect(vm.test).toBe('1')
}).then(() => {
document.body.removeChild(vm.$el)
}).then(done)
})
it('should respect value bindings', done => {
const vm = new Vue({
data: {
test: 1
},
template: `
`
}).$mount()
document.body.appendChild(vm.$el)
expect(vm.$el.children[0].checked).toBe(true)
expect(vm.$el.children[1].checked).toBe(false)
vm.test = 2
waitForUpdate(() => {
expect(vm.$el.children[0].checked).toBe(false)
expect(vm.$el.children[1].checked).toBe(true)
vm.$el.children[0].click()
expect(vm.$el.children[0].checked).toBe(true)
expect(vm.$el.children[1].checked).toBe(false)
expect(vm.test).toBe(1)
}).then(() => {
document.body.removeChild(vm.$el)
}).then(done)
})
it('should respect value bindings (object loose equal)', done => {
const vm = new Vue({
data: {
test: { a: 1 }
},
template: `
`
}).$mount()
document.body.appendChild(vm.$el)
expect(vm.$el.children[0].checked).toBe(true)
expect(vm.$el.children[1].checked).toBe(false)
vm.test = { a: 2 }
waitForUpdate(() => {
expect(vm.$el.children[0].checked).toBe(false)
expect(vm.$el.children[1].checked).toBe(true)
vm.$el.children[0].click()
expect(vm.$el.children[0].checked).toBe(true)
expect(vm.$el.children[1].checked).toBe(false)
expect(vm.test).toEqual({ a: 1 })
}).then(() => {
document.body.removeChild(vm.$el)
}).then(done)
})
it('multiple radios ', (done) => {
const spy = jasmine.createSpy()
const vm = new Vue({
data: {
selections: ['a', '1'],
radioList: [
{
name: 'questionA',
data: ['a', 'b', 'c']
},
{
name: 'questionB',
data: ['1', '2']
}
]
},
watch: {
selections: spy
},
template:
'' +
'
' +
'
' +
'' +
' ' +
'{{item}} ' +
' ' +
'
' +
'
' +
'
'
}).$mount()
document.body.appendChild(vm.$el)
var inputs = vm.$el.getElementsByTagName('input')
inputs[1].click()
waitForUpdate(() => {
expect(vm.selections).toEqual(['b', '1'])
expect(spy).toHaveBeenCalled()
}).then(done)
})
it('.number modifier', () => {
const vm = new Vue({
data: {
test: 1
},
template: `
`
}).$mount()
document.body.appendChild(vm.$el)
expect(vm.$el.children[0].checked).toBe(true)
expect(vm.$el.children[1].checked).toBe(false)
vm.$el.children[1].click()
expect(vm.$el.children[0].checked).toBe(false)
expect(vm.$el.children[1].checked).toBe(true)
expect(vm.test).toBe(2)
})
it('should respect different primitive type value', (done) => {
const vm = new Vue({
data: {
test: 1
},
template:
'' +
' ' +
' ' +
' ' +
' ' +
' ' +
'
'
}).$mount()
var radioboxInput = vm.$el.children
expect(radioboxInput[0].checked).toBe(false)
expect(radioboxInput[1].checked).toBe(false)
expect(radioboxInput[2].checked).toBe(true)
expect(radioboxInput[3].checked).toBe(false)
expect(radioboxInput[4].checked).toBe(false)
vm.test = 0
waitForUpdate(() => {
expect(radioboxInput[0].checked).toBe(false)
expect(radioboxInput[1].checked).toBe(true)
expect(radioboxInput[2].checked).toBe(false)
expect(radioboxInput[3].checked).toBe(false)
expect(radioboxInput[4].checked).toBe(false)
vm.test = ''
}).then(() => {
expect(radioboxInput[0].checked).toBe(true)
expect(radioboxInput[1].checked).toBe(false)
expect(radioboxInput[2].checked).toBe(false)
expect(radioboxInput[3].checked).toBe(false)
expect(radioboxInput[4].checked).toBe(false)
vm.test = false
}).then(() => {
expect(radioboxInput[0].checked).toBe(false)
expect(radioboxInput[1].checked).toBe(false)
expect(radioboxInput[2].checked).toBe(false)
expect(radioboxInput[3].checked).toBe(true)
expect(radioboxInput[4].checked).toBe(false)
vm.test = true
}).then(() => {
expect(radioboxInput[0].checked).toBe(false)
expect(radioboxInput[1].checked).toBe(false)
expect(radioboxInput[2].checked).toBe(false)
expect(radioboxInput[3].checked).toBe(false)
expect(radioboxInput[4].checked).toBe(true)
}).then(done)
})
// #4521
it('should work with click event', (done) => {
const vm = new Vue({
data: {
num: 1,
checked: 1
},
template:
'' +
'click {{ num }} ' +
' ' +
'
',
methods: {
add: function () {
this.num++
}
}
}).$mount()
document.body.appendChild(vm.$el)
const radios = vm.$el.getElementsByTagName('input')
radios[0].click()
waitForUpdate(() => {
expect(radios[0].checked).toBe(true)
expect(radios[1].checked).toBe(false)
expect(vm.num).toBe(2)
radios[0].click()
}).then(() => {
expect(radios[0].checked).toBe(true)
expect(radios[1].checked).toBe(false)
expect(vm.num).toBe(3)
radios[1].click()
}).then(() => {
expect(radios[0].checked).toBe(false)
expect(radios[1].checked).toBe(true)
expect(vm.num).toBe(4)
}).then(done)
})
it('should get updated with model when in focus', (done) => {
const vm = new Vue({
data: {
a: '2'
},
template: ' '
}).$mount()
document.body.appendChild(vm.$el)
vm.$el.click()
waitForUpdate(() => {
expect(vm.$el.checked).toBe(true)
vm.a = 2
}).then(() => {
expect(vm.$el.checked).toBe(false)
}).then(done)
})
})
node-vue-template-compiler-2.4.2+dfsg/test/unit/features/directives/model-select.spec.js000066400000000000000000000354731361753775300314170ustar00rootroot00000000000000import Vue from 'vue'
import { looseEqual } from 'shared/util'
// Android 4.4 Chrome 30 has the bug that a multi-select option cannot be
// deseleted by setting its "selected" prop via JavaScript.
function hasMultiSelectBug () {
var s = document.createElement('select')
s.setAttribute('multiple', '')
var o = document.createElement('option')
s.appendChild(o)
o.selected = true
o.selected = false
return o.selected !== false
}
/**
* setting 's value in IE9 doesn't work
* we have to manually loop through the options
*/
function updateSelect (el, value) {
var options = el.options
var i = options.length
while (i--) {
if (looseEqual(getValue(options[i]), value)) {
options[i].selected = true
break
}
}
}
function getValue (option) {
return '_value' in option
? option._value
: option.value || option.text
}
describe('Directive v-model select', () => {
it('should work', done => {
const vm = new Vue({
data: {
test: 'b'
},
template:
' ' +
'a ' +
'b ' +
'c ' +
''
}).$mount()
document.body.appendChild(vm.$el)
expect(vm.test).toBe('b')
expect(vm.$el.value).toBe('b')
expect(vm.$el.childNodes[1].selected).toBe(true)
vm.test = 'c'
waitForUpdate(function () {
expect(vm.$el.value).toBe('c')
expect(vm.$el.childNodes[2].selected).toBe(true)
updateSelect(vm.$el, 'a')
triggerEvent(vm.$el, 'change')
expect(vm.test).toBe('a')
}).then(done)
})
it('should work with value bindings', done => {
const vm = new Vue({
data: {
test: 2
},
template:
'' +
'a ' +
'b ' +
'c ' +
' '
}).$mount()
document.body.appendChild(vm.$el)
expect(vm.$el.value).toBe('2')
expect(vm.$el.childNodes[1].selected).toBe(true)
vm.test = 3
waitForUpdate(function () {
expect(vm.$el.value).toBe('3')
expect(vm.$el.childNodes[2].selected).toBe(true)
updateSelect(vm.$el, '1')
triggerEvent(vm.$el, 'change')
expect(vm.test).toBe('1')
updateSelect(vm.$el, '2')
triggerEvent(vm.$el, 'change')
expect(vm.test).toBe(2)
}).then(done)
})
it('should work with value bindings (object loose equal)', done => {
const vm = new Vue({
data: {
test: { a: 2 }
},
template:
'' +
'a ' +
'b ' +
'c ' +
' '
}).$mount()
document.body.appendChild(vm.$el)
expect(vm.$el.childNodes[1].selected).toBe(true)
vm.test = { a: 3 }
waitForUpdate(function () {
expect(vm.$el.childNodes[2].selected).toBe(true)
updateSelect(vm.$el, '1')
triggerEvent(vm.$el, 'change')
expect(vm.test).toBe('1')
updateSelect(vm.$el, { a: 2 })
triggerEvent(vm.$el, 'change')
expect(vm.test).toEqual({ a: 2 })
}).then(done)
})
it('should work with value bindings (Array loose equal)', done => {
const vm = new Vue({
data: {
test: [{ a: 2 }]
},
template:
'' +
'a ' +
'b ' +
'c ' +
' '
}).$mount()
document.body.appendChild(vm.$el)
expect(vm.$el.childNodes[1].selected).toBe(true)
vm.test = [{ a: 3 }]
waitForUpdate(function () {
expect(vm.$el.childNodes[2].selected).toBe(true)
updateSelect(vm.$el, '1')
triggerEvent(vm.$el, 'change')
expect(vm.test).toBe('1')
updateSelect(vm.$el, [{ a: 2 }])
triggerEvent(vm.$el, 'change')
expect(vm.test).toEqual([{ a: 2 }])
}).then(done)
})
it('should work with v-for', done => {
const vm = new Vue({
data: {
test: 'b',
opts: ['a', 'b', 'c']
},
template:
'' +
'{{ o }} ' +
' '
}).$mount()
document.body.appendChild(vm.$el)
expect(vm.test).toBe('b')
expect(vm.$el.value).toBe('b')
expect(vm.$el.childNodes[1].selected).toBe(true)
vm.test = 'c'
waitForUpdate(function () {
expect(vm.$el.value).toBe('c')
expect(vm.$el.childNodes[2].selected).toBe(true)
updateSelect(vm.$el, 'a')
triggerEvent(vm.$el, 'change')
expect(vm.test).toBe('a')
// update v-for opts
vm.opts = ['d', 'a']
}).then(() => {
expect(vm.$el.childNodes[0].selected).toBe(false)
expect(vm.$el.childNodes[1].selected).toBe(true)
}).then(done)
})
it('should work with v-for & value bindings', done => {
const vm = new Vue({
data: {
test: 2,
opts: [1, 2, 3]
},
template:
'' +
'option {{ o }} ' +
' '
}).$mount()
document.body.appendChild(vm.$el)
expect(vm.$el.value).toBe('2')
expect(vm.$el.childNodes[1].selected).toBe(true)
vm.test = 3
waitForUpdate(function () {
expect(vm.$el.value).toBe('3')
expect(vm.$el.childNodes[2].selected).toBe(true)
updateSelect(vm.$el, 1)
triggerEvent(vm.$el, 'change')
expect(vm.test).toBe(1)
// update v-for opts
vm.opts = [0, 1]
}).then(() => {
expect(vm.$el.childNodes[0].selected).toBe(false)
expect(vm.$el.childNodes[1].selected).toBe(true)
}).then(done)
})
it('should work with select which has no default selected options', (done) => {
const spy = jasmine.createSpy()
const vm = new Vue({
data: {
id: 4,
list: [1, 2, 3],
testChange: 5
},
template:
'' +
'' +
'{{item}} ' +
' ' +
'{{testChange}}' +
'
',
methods: {
test: spy
}
}).$mount()
document.body.appendChild(vm.$el)
vm.testChange = 10
waitForUpdate(() => {
expect(spy.calls.count()).toBe(0)
}).then(done)
})
if (!hasMultiSelectBug()) {
it('multiple', done => {
const vm = new Vue({
data: {
test: ['b']
},
template:
'' +
'a ' +
'b ' +
'c ' +
' '
}).$mount()
var opts = vm.$el.options
expect(opts[0].selected).toBe(false)
expect(opts[1].selected).toBe(true)
expect(opts[2].selected).toBe(false)
vm.test = ['a', 'c']
waitForUpdate(() => {
expect(opts[0].selected).toBe(true)
expect(opts[1].selected).toBe(false)
expect(opts[2].selected).toBe(true)
opts[0].selected = false
opts[1].selected = true
triggerEvent(vm.$el, 'change')
expect(vm.test).toEqual(['b', 'c'])
}).then(done)
})
it('multiple + v-for', done => {
const vm = new Vue({
data: {
test: ['b'],
opts: ['a', 'b', 'c']
},
template:
'' +
'{{ o }} ' +
' '
}).$mount()
var opts = vm.$el.options
expect(opts[0].selected).toBe(false)
expect(opts[1].selected).toBe(true)
expect(opts[2].selected).toBe(false)
vm.test = ['a', 'c']
waitForUpdate(() => {
expect(opts[0].selected).toBe(true)
expect(opts[1].selected).toBe(false)
expect(opts[2].selected).toBe(true)
opts[0].selected = false
opts[1].selected = true
triggerEvent(vm.$el, 'change')
expect(vm.test).toEqual(['b', 'c'])
// update v-for opts
vm.opts = ['c', 'd']
}).then(() => {
expect(opts[0].selected).toBe(true)
expect(opts[1].selected).toBe(false)
expect(vm.test).toEqual(['c']) // should remove 'd' which no longer has a matching option
}).then(done)
})
}
it('should work with multiple binding', (done) => {
const spy = jasmine.createSpy()
const vm = new Vue({
data: {
isMultiple: true,
selections: ['1']
},
template:
'' +
'item 1 ' +
'item 2 ' +
' ',
watch: {
selections: spy
}
}).$mount()
document.body.appendChild(vm.$el)
vm.$el.options[1].selected = true
triggerEvent(vm.$el, 'change')
waitForUpdate(() => {
expect(spy).toHaveBeenCalled()
expect(vm.selections).toEqual(['1', '2'])
}).then(done)
})
it('should not have multiple attr with falsy values except \'\'', () => {
const vm = new Vue({
template:
'' +
' ' +
' ' +
' ' +
' ' +
'
'
}).$mount()
expect(vm.$el.querySelector('#undefined').multiple).toEqual(false)
expect(vm.$el.querySelector('#null').multiple).toEqual(false)
expect(vm.$el.querySelector('#false').multiple).toEqual(false)
expect(vm.$el.querySelector('#string').multiple).toEqual(true)
})
it('multiple with static template', () => {
const vm = new Vue({
template:
'' +
'a ' +
'b ' +
'c ' +
' '
}).$mount()
var opts = vm.$el.options
expect(opts[0].selected).toBe(true)
expect(opts[1].selected).toBe(true)
expect(opts[2].selected).toBe(true)
})
it('multiple selects', (done) => {
const spy = jasmine.createSpy()
const vm = new Vue({
data: {
selections: ['', ''],
selectBoxes: [
[
{ value: 'foo', text: 'foo' },
{ value: 'bar', text: 'bar' }
],
[
{ value: 'day', text: 'day' },
{ value: 'night', text: 'night' }
]
]
},
watch: {
selections: spy
},
template:
'' +
'' +
' ' +
' ' +
'{{selections}} ' +
'
'
}).$mount()
document.body.appendChild(vm.$el)
var selects = vm.$el.getElementsByTagName('select')
var select0 = selects[0]
select0.options[0].selected = true
triggerEvent(select0, 'change')
waitForUpdate(() => {
expect(spy).toHaveBeenCalled()
expect(vm.selections).toEqual(['foo', ''])
}).then(done)
})
it('.number modifier', () => {
const vm = new Vue({
data: {
test: 2
},
template:
'' +
'a ' +
'b ' +
'c ' +
' '
}).$mount()
document.body.appendChild(vm.$el)
updateSelect(vm.$el, '1')
triggerEvent(vm.$el, 'change')
expect(vm.test).toBe(1)
})
it('should respect different primitive type value', (done) => {
const vm = new Vue({
data: {
test: 0
},
template:
'' +
'a ' +
'b ' +
'c ' +
'c ' +
'c ' +
' '
}).$mount()
var opts = vm.$el.options
expect(opts[0].selected).toBe(false)
expect(opts[1].selected).toBe(true)
expect(opts[2].selected).toBe(false)
expect(opts[3].selected).toBe(false)
expect(opts[4].selected).toBe(false)
vm.test = 1
waitForUpdate(() => {
expect(opts[0].selected).toBe(false)
expect(opts[1].selected).toBe(false)
expect(opts[2].selected).toBe(true)
expect(opts[3].selected).toBe(false)
expect(opts[4].selected).toBe(false)
vm.test = ''
}).then(() => {
expect(opts[0].selected).toBe(true)
expect(opts[1].selected).toBe(false)
expect(opts[2].selected).toBe(false)
expect(opts[3].selected).toBe(false)
expect(opts[4].selected).toBe(false)
vm.test = false
}).then(() => {
expect(opts[0].selected).toBe(false)
expect(opts[1].selected).toBe(false)
expect(opts[2].selected).toBe(false)
expect(opts[3].selected).toBe(true)
expect(opts[4].selected).toBe(false)
vm.test = true
}).then(() => {
expect(opts[0].selected).toBe(false)
expect(opts[1].selected).toBe(false)
expect(opts[2].selected).toBe(false)
expect(opts[3].selected).toBe(false)
expect(opts[4].selected).toBe(true)
}).then(done)
})
it('should warn multiple with non-Array value', done => {
new Vue({
data: {
test: 'meh'
},
template:
' '
}).$mount()
// IE warns on a setTimeout as well
setTimeout(() => {
expect(' expects an Array value for its binding, but got String')
.toHaveBeenWarned()
done()
}, 0)
})
it('should work with option value that has circular reference', done => {
const circular = {}
circular.self = circular
const vm = new Vue({
data: {
test: 'b',
circular
},
template:
' ' +
'a ' +
'b ' +
'c ' +
''
}).$mount()
document.body.appendChild(vm.$el)
expect(vm.test).toBe('b')
expect(vm.$el.value).toBe('b')
expect(vm.$el.childNodes[1].selected).toBe(true)
vm.test = circular
waitForUpdate(function () {
expect(vm.$el.childNodes[0].selected).toBe(true)
}).then(done)
})
// #6112
it('should not set non-matching value to undefined if options did not change', done => {
const vm = new Vue({
data: {
test: '1'
},
template:
'' +
'a ' +
' '
}).$mount()
vm.test = '2'
waitForUpdate(() => {
expect(vm.test).toBe('2')
}).then(done)
})
})
node-vue-template-compiler-2.4.2+dfsg/test/unit/features/directives/model-text.spec.js000066400000000000000000000170251361753775300311150ustar00rootroot00000000000000import Vue from 'vue'
import { isIE9, isAndroid } from 'core/util/env'
describe('Directive v-model text', () => {
it('should update value both ways', done => {
const vm = new Vue({
data: {
test: 'b'
},
template: ' '
}).$mount()
expect(vm.$el.value).toBe('b')
vm.test = 'a'
waitForUpdate(() => {
expect(vm.$el.value).toBe('a')
vm.$el.value = 'c'
triggerEvent(vm.$el, 'input')
expect(vm.test).toBe('c')
}).then(done)
})
it('.lazy modifier', () => {
const vm = new Vue({
data: {
test: 'b'
},
template: ' '
}).$mount()
expect(vm.$el.value).toBe('b')
expect(vm.test).toBe('b')
vm.$el.value = 'c'
triggerEvent(vm.$el, 'input')
expect(vm.test).toBe('b')
triggerEvent(vm.$el, 'change')
expect(vm.test).toBe('c')
})
it('.number modifier', () => {
const vm = new Vue({
data: {
test: 1
},
template: ' '
}).$mount()
expect(vm.test).toBe(1)
vm.$el.value = '2'
triggerEvent(vm.$el, 'input')
expect(vm.test).toBe(2)
// should let strings pass through
vm.$el.value = 'f'
triggerEvent(vm.$el, 'input')
expect(vm.test).toBe('f')
})
it('.trim modifier', () => {
const vm = new Vue({
data: {
test: 'hi'
},
template: ' '
}).$mount()
expect(vm.test).toBe('hi')
vm.$el.value = ' what '
triggerEvent(vm.$el, 'input')
expect(vm.test).toBe('what')
})
it('.number focus and typing', (done) => {
const vm = new Vue({
data: {
test: 0,
update: 0
},
template:
'' +
' {{ update }}' +
' ' +
'
'
}).$mount()
document.body.appendChild(vm.$el)
vm.$refs.input.focus()
expect(vm.test).toBe(0)
vm.$refs.input.value = '1.0'
triggerEvent(vm.$refs.input, 'input')
expect(vm.test).toBe(1)
vm.update++
waitForUpdate(() => {
expect(vm.$refs.input.value).toBe('1.0')
vm.$refs.blur.focus()
vm.update++
}).then(() => {
expect(vm.$refs.input.value).toBe('1')
}).then(done)
})
it('.trim focus and typing', (done) => {
const vm = new Vue({
data: {
test: 'abc',
update: 0
},
template:
'' +
' {{ update }}' +
' ' +
'
'
}).$mount()
document.body.appendChild(vm.$el)
vm.$refs.input.focus()
vm.$refs.input.value = ' abc '
triggerEvent(vm.$refs.input, 'input')
expect(vm.test).toBe('abc')
vm.update++
waitForUpdate(() => {
expect(vm.$refs.input.value).toBe(' abc ')
vm.$refs.blur.focus()
vm.update++
}).then(() => {
expect(vm.$refs.input.value).toBe('abc')
}).then(done)
})
it('multiple inputs', (done) => {
const spy = jasmine.createSpy()
const vm = new Vue({
data: {
selections: [[1, 2, 3], [4, 5]],
inputList: [
{
name: 'questionA',
data: ['a', 'b', 'c']
},
{
name: 'questionB',
data: ['1', '2']
}
]
},
watch: {
selections: spy
},
template:
'' +
'
' +
'
' +
'' +
' ' +
'{{item}} ' +
' ' +
'
' +
'
' +
'
{{selections}} ' +
'
'
}).$mount()
var inputs = vm.$el.getElementsByTagName('input')
inputs[1].value = 'test'
triggerEvent(inputs[1], 'input')
waitForUpdate(() => {
expect(spy).toHaveBeenCalled()
expect(vm.selections).toEqual([[1, 'test', 3], [4, 5]])
}).then(done)
})
if (isIE9) {
it('IE9 selectionchange', done => {
const vm = new Vue({
data: {
test: 'foo'
},
template: ' '
}).$mount()
const input = vm.$el
input.value = 'bar'
document.body.appendChild(input)
input.focus()
triggerEvent(input, 'selectionchange')
waitForUpdate(() => {
expect(vm.test).toBe('bar')
input.value = 'a'
triggerEvent(input, 'selectionchange')
expect(vm.test).toBe('a')
}).then(done)
})
}
if (!isAndroid) {
it('compositionevents', function (done) {
const vm = new Vue({
data: {
test: 'foo'
},
template: ' '
}).$mount()
const input = vm.$el
triggerEvent(input, 'compositionstart')
input.value = 'baz'
// input before composition unlock should not call set
triggerEvent(input, 'input')
expect(vm.test).toBe('foo')
// after composition unlock it should work
triggerEvent(input, 'compositionend')
triggerEvent(input, 'input')
expect(vm.test).toBe('baz')
done()
})
}
it('warn invalid tag', () => {
new Vue({
data: {
test: 'foo'
},
template: '
'
}).$mount()
expect(': v-model is not supported on this element type').toHaveBeenWarned()
})
// #3468
it('should have higher priority than user v-on events', () => {
const spy = jasmine.createSpy()
const vm = new Vue({
data: {
a: 'a'
},
template: '
',
methods: {
onInput (e) {
spy(e.target.value)
}
}
}).$mount()
vm.$el.value = 'b'
triggerEvent(vm.$el, 'input')
expect(spy).toHaveBeenCalledWith('b')
})
it('warn binding to v-for alias', () => {
new Vue({
data: {
strings: ['hi']
},
template: `
`
}).$mount()
expect('You are binding v-model directly to a v-for iteration alias').toHaveBeenWarned()
})
if (!isAndroid) {
it('does not trigger extra input events with single compositionend', () => {
const spy = jasmine.createSpy()
const vm = new Vue({
data: {
a: 'a'
},
template: '
',
methods: {
onInput (e) {
spy(e.target.value)
}
}
}).$mount()
expect(spy.calls.count()).toBe(0)
vm.$el.value = 'b'
triggerEvent(vm.$el, 'input')
expect(spy.calls.count()).toBe(1)
triggerEvent(vm.$el, 'compositionend')
expect(spy.calls.count()).toBe(1)
})
it('triggers extra input on compositionstart + end', () => {
const spy = jasmine.createSpy()
const vm = new Vue({
data: {
a: 'a'
},
template: '
',
methods: {
onInput (e) {
spy(e.target.value)
}
}
}).$mount()
expect(spy.calls.count()).toBe(0)
vm.$el.value = 'b'
triggerEvent(vm.$el, 'input')
expect(spy.calls.count()).toBe(1)
triggerEvent(vm.$el, 'compositionstart')
triggerEvent(vm.$el, 'compositionend')
expect(spy.calls.count()).toBe(2)
})
}
})
node-vue-template-compiler-2.4.2+dfsg/test/unit/features/directives/on.spec.js000066400000000000000000000465311361753775300274530ustar00rootroot00000000000000import Vue from 'vue'
import { supportsPassive } from 'core/util/env'
describe('Directive v-on', () => {
let vm, spy, el
beforeEach(() => {
vm = null
spy = jasmine.createSpy()
el = document.createElement('div')
document.body.appendChild(el)
})
afterEach(() => {
if (vm) {
document.body.removeChild(vm.$el)
}
})
it('should bind event to a method', () => {
vm = new Vue({
el,
template: '
',
methods: { foo: spy }
})
triggerEvent(vm.$el, 'click')
expect(spy.calls.count()).toBe(1)
const args = spy.calls.allArgs()
const event = args[0] && args[0][0] || {}
expect(event.type).toBe('click')
})
it('should bind event to a inline statement', () => {
vm = new Vue({
el,
template: '
',
methods: { foo: spy }
})
triggerEvent(vm.$el, 'click')
expect(spy.calls.count()).toBe(1)
const args = spy.calls.allArgs()
const firstArgs = args[0]
expect(firstArgs.length).toBe(4)
expect(firstArgs[0]).toBe(1)
expect(firstArgs[1]).toBe(2)
expect(firstArgs[2]).toBe(3)
expect(firstArgs[3].type).toBe('click')
})
it('should support inline function expression', () => {
const spy = jasmine.createSpy()
vm = new Vue({
el,
template: `
`,
methods: {
log: spy
}
}).$mount()
triggerEvent(vm.$el, 'click')
expect(spy).toHaveBeenCalledWith('test')
})
it('should support shorthand', () => {
vm = new Vue({
el,
template: '
',
methods: { foo: spy }
})
triggerEvent(vm.$el, 'click')
expect(spy.calls.count()).toBe(1)
})
it('should support stop propagation', () => {
vm = new Vue({
el,
template: `
`,
methods: { foo: spy }
})
const hash = window.location.hash
triggerEvent(vm.$el, 'click')
expect(window.location.hash).toBe(hash)
})
it('should support prevent default', () => {
vm = new Vue({
el,
template: `
`,
methods: {
foo ($event) {
spy($event.defaultPrevented)
}
}
})
vm.$refs.input.checked = false
triggerEvent(vm.$refs.input, 'click')
expect(spy).toHaveBeenCalledWith(true)
})
it('should support capture', () => {
const callOrder = []
vm = new Vue({
el,
template: `
`,
methods: {
foo () { callOrder.push(1) },
bar () { callOrder.push(2) }
}
})
triggerEvent(vm.$el.firstChild, 'click')
expect(callOrder.toString()).toBe('1,2')
})
it('should support once', () => {
vm = new Vue({
el,
template: `
`,
methods: { foo: spy }
})
triggerEvent(vm.$el, 'click')
expect(spy.calls.count()).toBe(1)
triggerEvent(vm.$el, 'click')
expect(spy.calls.count()).toBe(1) // should no longer trigger
})
// #4655
it('should handle .once on multiple elements properly', () => {
vm = new Vue({
el,
template: `
one
two
`,
methods: { foo: spy }
})
triggerEvent(vm.$refs.one, 'click')
expect(spy.calls.count()).toBe(1)
triggerEvent(vm.$refs.one, 'click')
expect(spy.calls.count()).toBe(1)
triggerEvent(vm.$refs.two, 'click')
expect(spy.calls.count()).toBe(2)
triggerEvent(vm.$refs.one, 'click')
triggerEvent(vm.$refs.two, 'click')
expect(spy.calls.count()).toBe(2)
})
it('should support capture and once', () => {
const callOrder = []
vm = new Vue({
el,
template: `
`,
methods: {
foo () { callOrder.push(1) },
bar () { callOrder.push(2) }
}
})
triggerEvent(vm.$el.firstChild, 'click')
expect(callOrder.toString()).toBe('1,2')
triggerEvent(vm.$el.firstChild, 'click')
expect(callOrder.toString()).toBe('1,2,2')
})
// #4846
it('should support once and other modifiers', () => {
vm = new Vue({
el,
template: `
`,
methods: { foo: spy }
})
triggerEvent(vm.$el.firstChild, 'click')
expect(spy).not.toHaveBeenCalled()
triggerEvent(vm.$el, 'click')
expect(spy).toHaveBeenCalled()
triggerEvent(vm.$el, 'click')
expect(spy.calls.count()).toBe(1)
})
it('should support keyCode', () => {
vm = new Vue({
el,
template: `
`,
methods: { foo: spy }
})
triggerEvent(vm.$el, 'keyup', e => {
e.keyCode = 13
})
expect(spy).toHaveBeenCalled()
})
it('should support number keyCode', () => {
vm = new Vue({
el,
template: `
`,
methods: { foo: spy }
})
triggerEvent(vm.$el, 'keyup', e => {
e.keyCode = 13
})
expect(spy).toHaveBeenCalled()
})
it('should support mouse modifier', () => {
const left = 0
const middle = 1
const right = 2
const spyLeft = jasmine.createSpy()
const spyMiddle = jasmine.createSpy()
const spyRight = jasmine.createSpy()
vm = new Vue({
el,
template: `
`,
methods: {
foo: spyLeft,
foo1: spyRight,
foo2: spyMiddle
}
})
triggerEvent(vm.$refs.left, 'mousedown', e => { e.button = right })
triggerEvent(vm.$refs.left, 'mousedown', e => { e.button = middle })
expect(spyLeft).not.toHaveBeenCalled()
triggerEvent(vm.$refs.left, 'mousedown', e => { e.button = left })
expect(spyLeft).toHaveBeenCalled()
triggerEvent(vm.$refs.right, 'mousedown', e => { e.button = left })
triggerEvent(vm.$refs.right, 'mousedown', e => { e.button = middle })
expect(spyRight).not.toHaveBeenCalled()
triggerEvent(vm.$refs.right, 'mousedown', e => { e.button = right })
expect(spyRight).toHaveBeenCalled()
triggerEvent(vm.$refs.middle, 'mousedown', e => { e.button = left })
triggerEvent(vm.$refs.middle, 'mousedown', e => { e.button = right })
expect(spyMiddle).not.toHaveBeenCalled()
triggerEvent(vm.$refs.middle, 'mousedown', e => { e.button = middle })
expect(spyMiddle).toHaveBeenCalled()
})
it('should support custom keyCode', () => {
Vue.config.keyCodes.test = 1
vm = new Vue({
el,
template: `
`,
methods: { foo: spy }
})
triggerEvent(vm.$el, 'keyup', e => {
e.keyCode = 1
})
expect(spy).toHaveBeenCalled()
Vue.config.keyCodes = Object.create(null)
})
it('should override build-in keyCode', () => {
Vue.config.keyCodes.up = [1, 87]
vm = new Vue({
el,
template: `
`,
methods: { foo: spy }
})
triggerEvent(vm.$el, 'keyup', e => {
e.keyCode = 87
})
expect(spy).toHaveBeenCalled()
triggerEvent(vm.$el, 'keyup', e => {
e.keyCode = 1
})
expect(spy).toHaveBeenCalledTimes(2)
// should not affect build-in down keycode
triggerEvent(vm.$el, 'keyup', e => {
e.keyCode = 40
})
expect(spy).toHaveBeenCalledTimes(3)
Vue.config.keyCodes = Object.create(null)
})
it('should bind to a child component', () => {
vm = new Vue({
el,
template: '
',
methods: { foo: spy },
components: {
bar: {
template: '
Hello '
}
}
})
vm.$children[0].$emit('custom', 'foo', 'bar')
expect(spy).toHaveBeenCalledWith('foo', 'bar')
})
it('should be able to bind native events for a child component', () => {
vm = new Vue({
el,
template: '
',
methods: { foo: spy },
components: {
bar: {
template: '
Hello '
}
}
})
vm.$children[0].$emit('click')
expect(spy).not.toHaveBeenCalled()
triggerEvent(vm.$children[0].$el, 'click')
expect(spy).toHaveBeenCalled()
})
it('.once modifier should work with child components', () => {
vm = new Vue({
el,
template: '
',
methods: { foo: spy },
components: {
bar: {
template: '
Hello '
}
}
})
vm.$children[0].$emit('custom')
expect(spy.calls.count()).toBe(1)
vm.$children[0].$emit('custom')
expect(spy.calls.count()).toBe(1) // should not be called again
})
it('remove listener', done => {
const spy2 = jasmine.createSpy('remove listener')
vm = new Vue({
el,
methods: { foo: spy, bar: spy2 },
data: {
ok: true
},
render (h) {
return this.ok
? h('input', { on: { click: this.foo }})
: h('input', { on: { input: this.bar }})
}
})
triggerEvent(vm.$el, 'click')
expect(spy.calls.count()).toBe(1)
expect(spy2.calls.count()).toBe(0)
vm.ok = false
waitForUpdate(() => {
triggerEvent(vm.$el, 'click')
expect(spy.calls.count()).toBe(1) // should no longer trigger
triggerEvent(vm.$el, 'input')
expect(spy2.calls.count()).toBe(1)
}).then(done)
})
it('remove capturing listener', done => {
const spy2 = jasmine.createSpy('remove listener')
vm = new Vue({
el,
methods: { foo: spy, bar: spy2, stopped (ev) { ev.stopPropagation() } },
data: {
ok: true
},
render (h) {
return this.ok
? h('div', { on: { '!click': this.foo }}, [h('div', { on: { click: this.stopped }})])
: h('div', { on: { mouseOver: this.bar }}, [h('div')])
}
})
triggerEvent(vm.$el.firstChild, 'click')
expect(spy.calls.count()).toBe(1)
expect(spy2.calls.count()).toBe(0)
vm.ok = false
waitForUpdate(() => {
triggerEvent(vm.$el.firstChild, 'click')
expect(spy.calls.count()).toBe(1) // should no longer trigger
triggerEvent(vm.$el, 'mouseOver')
expect(spy2.calls.count()).toBe(1)
}).then(done)
})
it('remove once listener', done => {
const spy2 = jasmine.createSpy('remove listener')
vm = new Vue({
el,
methods: { foo: spy, bar: spy2 },
data: {
ok: true
},
render (h) {
return this.ok
? h('input', { on: { '~click': this.foo }})
: h('input', { on: { input: this.bar }})
}
})
triggerEvent(vm.$el, 'click')
expect(spy.calls.count()).toBe(1)
triggerEvent(vm.$el, 'click')
expect(spy.calls.count()).toBe(1) // should no longer trigger
expect(spy2.calls.count()).toBe(0)
vm.ok = false
waitForUpdate(() => {
triggerEvent(vm.$el, 'click')
expect(spy.calls.count()).toBe(1) // should no longer trigger
triggerEvent(vm.$el, 'input')
expect(spy2.calls.count()).toBe(1)
}).then(done)
})
it('remove capturing and once listener', done => {
const spy2 = jasmine.createSpy('remove listener')
vm = new Vue({
el,
methods: { foo: spy, bar: spy2, stopped (ev) { ev.stopPropagation() } },
data: {
ok: true
},
render (h) {
return this.ok
? h('div', { on: { '~!click': this.foo }}, [h('div', { on: { click: this.stopped }})])
: h('div', { on: { mouseOver: this.bar }}, [h('div')])
}
})
triggerEvent(vm.$el.firstChild, 'click')
expect(spy.calls.count()).toBe(1)
triggerEvent(vm.$el.firstChild, 'click')
expect(spy.calls.count()).toBe(1) // should no longer trigger
expect(spy2.calls.count()).toBe(0)
vm.ok = false
waitForUpdate(() => {
triggerEvent(vm.$el.firstChild, 'click')
expect(spy.calls.count()).toBe(1) // should no longer trigger
triggerEvent(vm.$el, 'mouseOver')
expect(spy2.calls.count()).toBe(1)
}).then(done)
})
it('remove listener on child component', done => {
const spy2 = jasmine.createSpy('remove listener')
vm = new Vue({
el,
methods: { foo: spy, bar: spy2 },
data: {
ok: true
},
components: {
test: {
template: '
'
}
},
render (h) {
return this.ok
? h('test', { on: { foo: this.foo }})
: h('test', { on: { bar: this.bar }})
}
})
vm.$children[0].$emit('foo')
expect(spy.calls.count()).toBe(1)
expect(spy2.calls.count()).toBe(0)
vm.ok = false
waitForUpdate(() => {
vm.$children[0].$emit('foo')
expect(spy.calls.count()).toBe(1) // should no longer trigger
vm.$children[0].$emit('bar')
expect(spy2.calls.count()).toBe(1)
}).then(done)
})
it('warn missing handlers', () => {
vm = new Vue({
el,
data: { none: null },
template: `
`
})
expect(`Invalid handler for event "click": got null`).toHaveBeenWarned()
expect(() => {
triggerEvent(vm.$el, 'click')
}).not.toThrow()
})
// Github Issue #5046
it('should support keyboard modifier', () => {
const spyLeft = jasmine.createSpy()
const spyRight = jasmine.createSpy()
const spyUp = jasmine.createSpy()
const spyDown = jasmine.createSpy()
vm = new Vue({
el,
template: `
`,
methods: {
foo: spyLeft,
foo1: spyRight,
foo2: spyUp,
foo3: spyDown
}
})
triggerEvent(vm.$refs.left, 'keydown', e => { e.keyCode = 37 })
triggerEvent(vm.$refs.left, 'keydown', e => { e.keyCode = 39 })
triggerEvent(vm.$refs.right, 'keydown', e => { e.keyCode = 39 })
triggerEvent(vm.$refs.right, 'keydown', e => { e.keyCode = 38 })
triggerEvent(vm.$refs.up, 'keydown', e => { e.keyCode = 38 })
triggerEvent(vm.$refs.up, 'keydown', e => { e.keyCode = 37 })
triggerEvent(vm.$refs.down, 'keydown', e => { e.keyCode = 40 })
triggerEvent(vm.$refs.down, 'keydown', e => { e.keyCode = 39 })
expect(spyLeft.calls.count()).toBe(1)
expect(spyRight.calls.count()).toBe(1)
expect(spyUp.calls.count()).toBe(1)
expect(spyDown.calls.count()).toBe(1)
})
// This test case should only run when the test browser supports passive.
if (supportsPassive) {
it('should support passive', () => {
vm = new Vue({
el,
template: `
`,
methods: {
foo (e) {
e.preventDefault()
}
}
})
vm.$refs.normal.checked = false
vm.$refs.passive.checked = false
vm.$refs.exclusive.checked = false
vm.$refs.normal.click()
vm.$refs.passive.click()
vm.$refs.exclusive.click()
expect(vm.$refs.normal.checked).toBe(false)
expect(vm.$refs.passive.checked).toBe(true)
expect(vm.$refs.exclusive.checked).toBe(true)
expect('passive and prevent can\'t be used together. Passive handler can\'t prevent default event.').toHaveBeenWarned()
})
}
// Github Issues #5146
it('should only prevent when match keycode', () => {
let prevented = false
vm = new Vue({
el,
template: `
`,
methods: {
foo ($event) {
prevented = $event.defaultPrevented
}
}
})
triggerEvent(vm.$refs.input, 'keydown', e => { e.keyCode = 32 })
expect(prevented).toBe(false)
triggerEvent(vm.$refs.input, 'keydown', e => { e.keyCode = 13 })
expect(prevented).toBe(true)
})
it('should warn click.right', () => {
new Vue({
template: `
`,
methods: { foo () {} }
}).$mount()
expect(`Use "contextmenu" instead`).toHaveBeenWarned()
})
it('object syntax (no argument)', () => {
const click = jasmine.createSpy('click')
const mouseup = jasmine.createSpy('mouseup')
vm = new Vue({
el,
template: `
foo `,
created () {
this.listeners = {
click,
mouseup
}
}
})
triggerEvent(vm.$el, 'click')
expect(click.calls.count()).toBe(1)
expect(mouseup.calls.count()).toBe(0)
triggerEvent(vm.$el, 'mouseup')
expect(click.calls.count()).toBe(1)
expect(mouseup.calls.count()).toBe(1)
})
it('object syntax (no argument, mixed with normal listeners)', () => {
const click1 = jasmine.createSpy('click1')
const click2 = jasmine.createSpy('click2')
const mouseup = jasmine.createSpy('mouseup')
vm = new Vue({
el,
template: `
foo `,
created () {
this.listeners = {
click: click1,
mouseup
}
},
methods: {
click2
}
})
triggerEvent(vm.$el, 'click')
expect(click1.calls.count()).toBe(1)
expect(click2.calls.count()).toBe(1)
expect(mouseup.calls.count()).toBe(0)
triggerEvent(vm.$el, 'mouseup')
expect(click1.calls.count()).toBe(1)
expect(click2.calls.count()).toBe(1)
expect(mouseup.calls.count()).toBe(1)
})
it('object syntax (usage in HOC, mixed with native listners)', () => {
const click = jasmine.createSpy('click')
const mouseup = jasmine.createSpy('mouseup')
const mousedown = jasmine.createSpy('mousedown')
var vm = new Vue({
el,
template: `
`,
methods: {
click,
mouseup,
mousedown
},
components: {
fooButton: {
template: `
`
}
}
})
triggerEvent(vm.$el, 'click')
expect(click.calls.count()).toBe(1)
expect(mouseup.calls.count()).toBe(0)
expect(mousedown.calls.count()).toBe(0)
triggerEvent(vm.$el, 'mouseup')
expect(click.calls.count()).toBe(1)
expect(mouseup.calls.count()).toBe(1)
expect(mousedown.calls.count()).toBe(0)
triggerEvent(vm.$el, 'mousedown')
expect(click.calls.count()).toBe(1)
expect(mouseup.calls.count()).toBe(1)
expect(mousedown.calls.count()).toBe(1)
})
it('warn object syntax with modifier', () => {
new Vue({
template: `
`
}).$mount()
expect(`v-on without argument does not support modifiers`).toHaveBeenWarned()
})
it('warn object syntax with non-object value', () => {
new Vue({
template: `
`
}).$mount()
expect(`v-on without argument expects an Object value`).toHaveBeenWarned()
})
})
node-vue-template-compiler-2.4.2+dfsg/test/unit/features/directives/once.spec.js000066400000000000000000000216401361753775300277550ustar00rootroot00000000000000import Vue from 'vue'
describe('Directive v-once', () => {
it('should not rerender component', done => {
const vm = new Vue({
template: '
{{ a }}
',
data: { a: 'hello' }
}).$mount()
expect(vm.$el.innerHTML).toBe('hello')
vm.a = 'world'
waitForUpdate(() => {
expect(vm.$el.innerHTML).toBe('hello')
}).then(done)
})
it('should not rerender self and child component', done => {
const vm = new Vue({
template: `
{{ a }}
`,
data: { a: 'hello' },
components: {
item: {
template: '
{{ b }}
',
props: ['b']
}
}
}).$mount()
expect(vm.$children.length).toBe(1)
expect(vm.$el.innerHTML)
.toBe('
hello hello
')
vm.a = 'world'
waitForUpdate(() => {
expect(vm.$el.innerHTML)
.toBe('
hello hello
')
}).then(done)
})
it('should rerender parent but not self', done => {
const vm = new Vue({
template: `
{{ a }}
`,
data: { a: 'hello' },
components: {
item: {
template: '
{{ b }}
',
props: ['b']
}
}
}).$mount()
expect(vm.$children.length).toBe(1)
expect(vm.$el.innerHTML)
.toBe('
hello hello
')
vm.a = 'world'
waitForUpdate(() => {
expect(vm.$el.innerHTML)
.toBe('
world hello
')
}).then(done)
})
it('should not rerender static sub nodes', done => {
const vm = new Vue({
template: `
{{ a }}
{{ suffix }}
`,
data: {
a: 'hello',
suffix: '?'
},
components: {
item: {
template: '
{{ b }}
',
props: ['b']
}
}
}).$mount()
expect(vm.$el.innerHTML)
.toBe('
hello hello
? ')
vm.a = 'world'
waitForUpdate(() => {
expect(vm.$el.innerHTML)
.toBe('
hello world
? ')
vm.suffix = '!'
}).then(() => {
expect(vm.$el.innerHTML)
.toBe('
hello world
! ')
}).then(done)
})
it('should work with v-if', done => {
const vm = new Vue({
data: {
tester: true,
yes: 'y',
no: 'n'
},
template: `
{{ yes }}
{{ no }}
{{ yes }}
{{ no }}
{{ yes }}
{{ no }}
{{ yes }}
{{ no }}
`
}).$mount()
expectTextContent(vm, 'yyyy')
vm.yes = 'yes'
waitForUpdate(() => {
expectTextContent(vm, 'yesyyesy')
vm.tester = false
}).then(() => {
expectTextContent(vm, 'nnnn')
vm.no = 'no'
}).then(() => {
expectTextContent(vm, 'nononn')
}).then(done)
})
it('should work with v-for', done => {
const vm = new Vue({
data: {
list: [1, 2, 3]
},
template: `
`
}).$mount()
expect(vm.$el.textContent).toBe('123')
vm.list.reverse()
waitForUpdate(() => {
expect(vm.$el.textContent).toBe('123')
}).then(done)
})
it('should work inside v-for', done => {
const vm = new Vue({
data: {
list: [
{ id: 0, text: 'a' },
{ id: 1, text: 'b' },
{ id: 2, text: 'c' }
]
},
template: `
`
}).$mount()
expect(vm.$el.textContent).toBe('aabbcc')
vm.list[0].text = 'd'
waitForUpdate(() => {
expect(vm.$el.textContent).toBe('adbbcc')
vm.list[1].text = 'e'
}).then(() => {
expect(vm.$el.textContent).toBe('adbecc')
vm.list.reverse()
}).then(() => {
expect(vm.$el.textContent).toBe('ccbead')
}).then(done)
})
it('should work inside v-for with v-if', done => {
const vm = new Vue({
data: {
list: [
{ id: 0, text: 'a', tester: true, truthy: 'y' }
]
},
template: `
{{ i.truthy }}
{{ i.text }}
{{ i.truthy }}
{{ i.text }}
{{ i.truthy }}
{{ i.text }}
{{ i.truthy }}
{{ i.text }}
`
}).$mount()
expectTextContent(vm, 'yyyy')
vm.list[0].truthy = 'yy'
waitForUpdate(() => {
expectTextContent(vm, 'yyyyyy')
vm.list[0].tester = false
}).then(() => {
expectTextContent(vm, 'aaaa')
vm.list[0].text = 'nn'
}).then(() => {
expectTextContent(vm, 'annann')
}).then(done)
})
it('should work inside v-for with nested v-else', done => {
const vm = new Vue({
data: {
list: [{ id: 0, text: 'a', tester: true, truthy: 'y' }]
},
template: `
{{ i.truthy }}
{{ i.text }}
`
}).$mount()
expectTextContent(vm, 'y')
vm.list[0].truthy = 'yy'
waitForUpdate(() => {
expectTextContent(vm, 'y')
vm.list[0].tester = false
}).then(() => {
expectTextContent(vm, 'a')
vm.list[0].text = 'nn'
}).then(() => {
expectTextContent(vm, 'a')
}).then(done)
})
it('should work inside v-for with nested v-else-if and v-else', done => {
const vm = new Vue({
data: {
tester: false,
list: [{ id: 0, text: 'a', tester: true, truthy: 'y' }]
},
template: `
{{ i.truthy }}
{{ i.text }}elseif
{{ i.text }}
{{ i.truthy }}
{{ i.text }}elseif
{{ i.text }}
`
}).$mount()
expectTextContent(vm, 'y')
vm.list[0].truthy = 'yy'
waitForUpdate(() => {
expectTextContent(vm, 'y')
vm.list[0].tester = false
}).then(() => {
expectTextContent(vm, 'a')
vm.list[0].text = 'nn'
}).then(() => {
expectTextContent(vm, 'a')
vm.tester = true
}).then(() => {
expectTextContent(vm, 'nnelseif')
vm.list[0].text = 'xx'
}).then(() => {
expectTextContent(vm, 'nnelseif')
vm.list[0].tester = true
}).then(() => {
expectTextContent(vm, 'yy')
vm.list[0].truthy = 'nn'
}).then(() => {
expectTextContent(vm, 'yy')
}).then(done)
})
it('should warn inside non-keyed v-for', () => {
const vm = new Vue({
data: {
list: [
{ id: 0, text: 'a' },
{ id: 1, text: 'b' },
{ id: 2, text: 'c' }
]
},
template: `
`
}).$mount()
expect(vm.$el.textContent).toBe('aabbcc')
expect(`v-once can only be used inside v-for that is keyed.`).toHaveBeenWarned()
})
// #4288
it('should inherit child reference for v-once', done => {
const vm = new Vue({
template: `
{{a}}
`,
data: {
a: 0,
ok: true
},
components: {
test: {
template: '
foo
'
}
}
}).$mount()
vm.a++ // first update to force a patch
waitForUpdate(() => {
expect(vm.$el.textContent).toBe('1foo')
}).then(() => {
vm.ok = false // teardown component with v-once
}).then(done) // should not throw
})
})
function expectTextContent (vm, text) {
expect(vm.$el.textContent.replace(/\s+/g, '')).toBe(text)
}
node-vue-template-compiler-2.4.2+dfsg/test/unit/features/directives/pre.spec.js000066400000000000000000000015001361753775300276100ustar00rootroot00000000000000import Vue from 'vue'
describe('Directive v-pre', function () {
it('should not compile inner content', function () {
const vm = new Vue({
template: `
`,
data: {
a: 123
}
})
vm.$mount()
expect(vm.$el.firstChild.textContent).toBe('{{ a }}')
expect(vm.$el.children[1].textContent).toBe('123')
expect(vm.$el.lastChild.innerHTML).toBe('
')
})
it('should not compile on root node', function () {
const vm = new Vue({
template: '
{{ a }}
',
replace: true,
data: {
a: 123
}
})
vm.$mount()
expect(vm.$el.firstChild.textContent).toBe('{{ a }}')
})
})
node-vue-template-compiler-2.4.2+dfsg/test/unit/features/directives/show.spec.js000066400000000000000000000051161361753775300300110ustar00rootroot00000000000000import Vue from 'vue'
describe('Directive v-show', () => {
it('should check show value is truthy', () => {
const vm = new Vue({
template: '
hello
',
data: { foo: true }
}).$mount()
expect(vm.$el.firstChild.style.display).toBe('')
})
it('should check show value is falsy', () => {
const vm = new Vue({
template: '
hello
',
data: { foo: false }
}).$mount()
expect(vm.$el.firstChild.style.display).toBe('none')
})
it('should update show value changed', done => {
const vm = new Vue({
template: '
hello
',
data: { foo: true }
}).$mount()
expect(vm.$el.firstChild.style.display).toBe('')
vm.foo = false
waitForUpdate(() => {
expect(vm.$el.firstChild.style.display).toBe('none')
vm.foo = {}
}).then(() => {
expect(vm.$el.firstChild.style.display).toBe('')
vm.foo = 0
}).then(() => {
expect(vm.$el.firstChild.style.display).toBe('none')
vm.foo = []
}).then(() => {
expect(vm.$el.firstChild.style.display).toBe('')
vm.foo = null
}).then(() => {
expect(vm.$el.firstChild.style.display).toBe('none')
vm.foo = '0'
}).then(() => {
expect(vm.$el.firstChild.style.display).toBe('')
vm.foo = undefined
}).then(() => {
expect(vm.$el.firstChild.style.display).toBe('none')
vm.foo = 1
}).then(() => {
expect(vm.$el.firstChild.style.display).toBe('')
}).then(done)
})
it('should respect display value in style attribute', done => {
const vm = new Vue({
template: '
hello
',
data: { foo: true }
}).$mount()
expect(vm.$el.firstChild.style.display).toBe('block')
vm.foo = false
waitForUpdate(() => {
expect(vm.$el.firstChild.style.display).toBe('none')
vm.foo = true
}).then(() => {
expect(vm.$el.firstChild.style.display).toBe('block')
}).then(done)
})
it('should support unbind when reused', done => {
const vm = new Vue({
template:
'
' +
'
show
',
data: { tester: true }
}).$mount()
expect(vm.$el.firstChild.style.display).toBe('none')
vm.tester = false
waitForUpdate(() => {
expect(vm.$el.firstChild.style.display).toBe('')
vm.tester = true
}).then(() => {
expect(vm.$el.firstChild.style.display).toBe('none')
}).then(done)
})
})
node-vue-template-compiler-2.4.2+dfsg/test/unit/features/directives/static-style-parser.spec.js000066400000000000000000000030531361753775300327460ustar00rootroot00000000000000import { parseStyleText } from 'web/util/style'
const base64ImgUrl = 'url("data:image/webp;base64,UklGRkoAAABXRUJQVlA4WAoAAAAQAAAAAAAAAAAAQUxQSAwAAAARBxAR/Q9ERP8DAABWUDggGAAAABQBAJ0BKgEAAQAAAP4AAA3AAP7mtQAAAA==")'
const logoUrl = 'url(https://vuejs.org/images/logo.png)'
it('should parse normal static style', () => {
const staticStyle = `font-size: 12px;background: ${logoUrl};color:red`
const res = parseStyleText(staticStyle)
expect(res.background).toBe(logoUrl)
expect(res.color).toBe('red')
expect(res['font-size']).toBe('12px')
})
it('should parse base64 background', () => {
const staticStyle = `background: ${base64ImgUrl}`
const res = parseStyleText(staticStyle)
expect(res.background).toBe(base64ImgUrl)
})
it('should parse multiple background images ', () => {
let staticStyle = `background: ${logoUrl}, ${logoUrl};`
let res = parseStyleText(staticStyle)
expect(res.background).toBe(`${logoUrl}, ${logoUrl}`)
staticStyle = `background: ${base64ImgUrl}, ${base64ImgUrl}`
res = parseStyleText(staticStyle)
expect(res.background).toBe(`${base64ImgUrl}, ${base64ImgUrl}`)
})
it('should parse other images ', () => {
let staticStyle = `shape-outside: ${logoUrl}`
let res = parseStyleText(staticStyle)
expect(res['shape-outside']).toBe(logoUrl)
staticStyle = `list-style-image: ${logoUrl}`
res = parseStyleText(staticStyle)
expect(res['list-style-image']).toBe(logoUrl)
staticStyle = `border-image: ${logoUrl} 30 30 repeat`
res = parseStyleText(staticStyle)
expect(res['border-image']).toBe(`${logoUrl} 30 30 repeat`)
})
node-vue-template-compiler-2.4.2+dfsg/test/unit/features/directives/style.spec.js000066400000000000000000000262601361753775300301740ustar00rootroot00000000000000import Vue from 'vue'
function checkPrefixedProp (prop) {
var el = document.createElement('div')
var upper = prop.charAt(0).toUpperCase() + prop.slice(1)
if (!(prop in el.style)) {
var prefixes = ['Webkit', 'Moz', 'ms']
var i = prefixes.length
while (i--) {
if ((prefixes[i] + upper) in el.style) {
prop = prefixes[i] + upper
}
}
}
return prop
}
describe('Directive v-bind:style', () => {
let vm
beforeEach(() => {
vm = new Vue({
template: '
',
data () {
return {
styles: {},
fontSize: 16
}
}
}).$mount()
})
it('string', done => {
vm.styles = 'color:red;'
waitForUpdate(() => {
expect(vm.$el.style.cssText.replace(/\s/g, '')).toBe('color:red;')
}).then(done)
})
it('falsy number', done => {
vm.styles = { opacity: 0 }
waitForUpdate(() => {
expect(vm.$el.style.opacity).toBe('0')
}).then(done)
})
it('plain object', done => {
vm.styles = { color: 'red' }
waitForUpdate(() => {
expect(vm.$el.style.cssText.replace(/\s/g, '')).toBe('color:red;')
}).then(done)
})
it('camelCase', done => {
vm.styles = { marginRight: '10px' }
waitForUpdate(() => {
expect(vm.$el.style.marginRight).toBe('10px')
}).then(done)
})
it('remove if falsy value', done => {
vm.$el.style.color = 'red'
waitForUpdate(() => {
vm.styles = { color: null }
}).then(() => {
expect(vm.$el.style.color).toBe('')
}).then(done)
})
it('ignore unsupported property', done => {
vm.styles = { foo: 'bar' }
waitForUpdate(() => {
expect(vm.$el.style.foo).not.toBe('bar')
}).then(done)
})
it('auto prefix', done => {
const prop = checkPrefixedProp('transform')
const val = 'scale(0.5)'
vm.styles = { transform: val }
waitForUpdate(() => {
expect(vm.$el.style[prop]).toBe(val)
}).then(done)
})
it('auto-prefixed style value as array', done => {
vm.styles = { display: ['-webkit-box', '-ms-flexbox', 'flex'] }
const testEl = document.createElement('div')
vm.styles.display.forEach(value => {
testEl.style.display = value
})
waitForUpdate(() => {
expect(vm.$el.style.display).toBe(testEl.style.display)
}).then(done)
})
it('!important', done => {
vm.styles = { display: 'block !important' }
waitForUpdate(() => {
expect(vm.$el.style.getPropertyPriority('display')).toBe('important')
}).then(done)
})
it('object with multiple entries', done => {
vm.$el.style.color = 'red'
vm.styles = {
marginLeft: '10px',
marginRight: '15px'
}
waitForUpdate(() => {
expect(vm.$el.style.getPropertyValue('color')).toBe('red')
expect(vm.$el.style.getPropertyValue('margin-left')).toBe('10px')
expect(vm.$el.style.getPropertyValue('margin-right')).toBe('15px')
vm.styles = {
color: 'blue',
padding: null
}
}).then(() => {
expect(vm.$el.style.getPropertyValue('color')).toBe('blue')
expect(vm.$el.style.getPropertyValue('padding')).toBeFalsy()
expect(vm.$el.style.getPropertyValue('margin-left')).toBeFalsy()
expect(vm.$el.style.getPropertyValue('margin-right')).toBeFalsy()
// handle falsy value
vm.styles = null
}).then(() => {
expect(vm.$el.style.getPropertyValue('color')).toBeFalsy()
expect(vm.$el.style.getPropertyValue('padding')).toBeFalsy()
expect(vm.$el.style.getPropertyValue('margin-left')).toBeFalsy()
expect(vm.$el.style.getPropertyValue('margin-right')).toBeFalsy()
}).then(done)
})
it('array of objects', done => {
vm.$el.style.padding = '10px'
vm.styles = [{ color: 'red' }, { marginRight: '20px' }]
waitForUpdate(() => {
expect(vm.$el.style.getPropertyValue('color')).toBe('red')
expect(vm.$el.style.getPropertyValue('margin-right')).toBe('20px')
expect(vm.$el.style.getPropertyValue('padding')).toBe('10px')
vm.styles = [{ color: 'blue' }, { padding: null }]
}).then(() => {
expect(vm.$el.style.getPropertyValue('color')).toBe('blue')
expect(vm.$el.style.getPropertyValue('margin-right')).toBeFalsy()
expect(vm.$el.style.getPropertyValue('padding')).toBeFalsy()
}).then(done)
})
it('updates objects deeply', done => {
vm.styles = { display: 'none' }
waitForUpdate(() => {
expect(vm.$el.style.display).toBe('none')
vm.styles.display = 'block'
}).then(() => {
expect(vm.$el.style.display).toBe('block')
}).then(done)
})
it('background size with only one value', done => {
vm.styles = { backgroundSize: '100%' }
waitForUpdate(() => {
expect(vm.$el.style.cssText.replace(/\s/g, '')).toMatch(/background-size:100%(auto)?;/)
}).then(done)
})
it('should work with interpolation', done => {
vm.styles = { fontSize: `${vm.fontSize}px` }
waitForUpdate(() => {
expect(vm.$el.style.fontSize).toBe('16px')
}).then(done)
})
const supportCssVariable = () => {
const el = document.createElement('div')
el.style.setProperty('--color', 'red')
return el.style.getPropertyValue('--color') === 'red'
}
if (supportCssVariable()) {
it('CSS variables', done => {
vm.styles = { '--color': 'red' }
waitForUpdate(() => {
expect(vm.$el.style.getPropertyValue('--color')).toBe('red')
}).then(done)
})
}
it('should merge static style with binding style', () => {
const vm = new Vue({
template: '
',
data: {
test: { color: 'red', fontSize: '12px' }
}
}).$mount()
const style = vm.$el.style
expect(style.getPropertyValue('background-image')).toMatch('https://vuejs.org/images/logo.png')
expect(style.getPropertyValue('color')).toBe('red')
expect(style.getPropertyValue('font-size')).toBe('12px')
})
it('should merge between parent and child', done => {
const vm = new Vue({
template: '
',
data: {
test: { color: 'red', fontSize: '12px' }
},
components: {
child: {
template: '
',
data: () => ({ marginLeft: '16px' })
}
}
}).$mount()
const style = vm.$el.style
const child = vm.$children[0]
const css = style.cssText.replace(/\s/g, '')
expect(css).toContain('margin-right:20px;')
expect(css).toContain('margin-left:16px;')
expect(css).toContain('text-align:left;')
expect(css).toContain('color:red;')
expect(css).toContain('font-size:12px;')
expect(style.color).toBe('red')
expect(style.marginRight).toBe('20px')
vm.test.color = 'blue'
waitForUpdate(() => {
expect(style.color).toBe('blue')
child.marginLeft = '30px'
}).then(() => {
expect(style.marginLeft).toBe('30px')
child.fontSize = '30px'
}).then(() => {
expect(style.fontSize).toBe('12px')
}).then(done)
})
it('should not pass to child root element', () => {
const vm = new Vue({
template: '
',
data: {
test: { color: 'red', fontSize: '12px' }
},
components: {
child: {
template: '
',
components: {
nested: {
template: '
'
}
}
}
}
}).$mount()
const style = vm.$el.style
expect(style.color).toBe('red')
expect(style.textAlign).toBe('')
expect(style.fontSize).toBe('12px')
expect(vm.$children[0].$refs.nested.$el.style.color).toBe('blue')
})
it('should merge between nested components', (done) => {
const vm = new Vue({
template: '
',
data: {
test: { color: 'red', fontSize: '12px' }
},
components: {
child: {
template: '
',
components: {
nested: {
template: '
',
data: () => ({ nestedStyle: { marginLeft: '30px' }})
}
}
}
}
}).$mount()
const style = vm.$el.style
const child = vm.$children[0].$children[0]
expect(style.color).toBe('red')
expect(style.marginLeft).toBe('30px')
expect(style.textAlign).toBe('left')
expect(style.fontSize).toBe('12px')
vm.test.color = 'yellow'
waitForUpdate(() => {
child.nestedStyle.marginLeft = '60px'
}).then(() => {
expect(style.marginLeft).toBe('60px')
child.nestedStyle = {
fontSize: '14px',
marginLeft: '40px'
}
}).then(() => {
expect(style.fontSize).toBe('12px')
expect(style.marginLeft).toBe('40px')
}).then(done)
})
it('should not merge for different adjacent elements', (done) => {
const vm = new Vue({
template:
'
',
data: {
bool: false,
style: {
fontSize: '12px'
}
}
}).$mount()
const style = vm.$el.children[0].style
expect(style.fontSize).toBe('12px')
expect(style.color).toBe('blue')
waitForUpdate(() => {
vm.bool = true
}).then(() => {
expect(style.color).toBe('')
expect(style.fontSize).toBe('')
expect(style.marginTop).toBe('12px')
}).then(done)
})
it('should not merge for v-if, v-else-if and v-else elements', (done) => {
const vm = new Vue({
template:
'
' +
'
' +
'
' +
'
' +
'
' +
'
',
data: {
foo: true,
bar: false,
style: {
fontSize: '12px'
}
}
}).$mount()
const style = vm.$el.children[0].style
expect(style.fontSize).toBe('12px')
expect(style.color).toBe('blue')
waitForUpdate(() => {
vm.foo = false
}).then(() => {
expect(style.color).toBe('')
expect(style.fontSize).toBe('')
expect(style.marginBottom).toBe('24px')
vm.bar = true
}).then(() => {
expect(style.color).toBe('')
expect(style.fontSize).toBe('')
expect(style.marginBottom).toBe('')
expect(style.marginTop).toBe('12px')
}).then(done)
})
// #5318
it('should work for elements passed down as a slot', done => {
const vm = new Vue({
template: `
`,
data: {
style: { color: 'red' }
},
components: {
test: {
template: `
`
}
}
}).$mount()
expect(vm.$el.children[0].style.color).toBe('red')
vm.style.color = 'green'
waitForUpdate(() => {
expect(vm.$el.children[0].style.color).toBe('green')
}).then(done)
})
})
node-vue-template-compiler-2.4.2+dfsg/test/unit/features/directives/text.spec.js000066400000000000000000000025101361753775300300100ustar00rootroot00000000000000import Vue from 'vue'
describe('Directive v-text', () => {
it('should render text', () => {
const vm = new Vue({
template: '
',
data: { a: 'hello' }
}).$mount()
expect(vm.$el.innerHTML).toBe('hello')
})
it('should encode html entities', () => {
const vm = new Vue({
template: '
',
data: { a: '
' }
}).$mount()
expect(vm.$el.innerHTML).toBe('<foo>')
})
it('should support all value types', done => {
const vm = new Vue({
template: '
',
data: { a: false }
}).$mount()
waitForUpdate(() => {
expect(vm.$el.innerHTML).toBe('false')
vm.a = []
}).then(() => {
expect(vm.$el.innerHTML).toBe('[]')
vm.a = {}
}).then(() => {
expect(vm.$el.innerHTML).toBe('{}')
vm.a = 123
}).then(() => {
expect(vm.$el.innerHTML).toBe('123')
vm.a = 0
}).then(() => {
expect(vm.$el.innerHTML).toBe('0')
vm.a = ' '
}).then(() => {
expect(vm.$el.innerHTML).toBe(' ')
vm.a = ' '
}).then(() => {
expect(vm.$el.innerHTML).toBe(' ')
vm.a = null
}).then(() => {
expect(vm.$el.innerHTML).toBe('')
vm.a = undefined
}).then(() => {
expect(vm.$el.innerHTML).toBe('')
}).then(done)
})
})
node-vue-template-compiler-2.4.2+dfsg/test/unit/features/error-handling.spec.js000066400000000000000000000160541361753775300276060ustar00rootroot00000000000000import Vue from 'vue'
const components = createErrorTestComponents()
describe('Error handling', () => {
// hooks that prevents the component from rendering, but should not
// break parent component
;[
['data', 'data()'],
['render', 'render function'],
['beforeCreate', 'beforeCreate hook'],
['created', 'created hook'],
['beforeMount', 'beforeMount hook'],
['directive bind', 'directive foo bind hook'],
['event', 'event handler for "e"']
].forEach(([type, description]) => {
it(`should recover from errors in ${type}`, done => {
const vm = createTestInstance(components[type])
expect(`Error in ${description}`).toHaveBeenWarned()
expect(`Error: ${type}`).toHaveBeenWarned()
assertRootInstanceActive(vm).then(done)
})
})
// error in mounted hook should affect neither child nor parent
it('should recover from errors in mounted hook', done => {
const vm = createTestInstance(components.mounted)
expect(`Error in mounted hook`).toHaveBeenWarned()
expect(`Error: mounted`).toHaveBeenWarned()
assertBothInstancesActive(vm).then(done)
})
// error in beforeUpdate/updated should affect neither child nor parent
;[
['beforeUpdate', 'beforeUpdate hook'],
['updated', 'updated hook'],
['directive update', 'directive foo update hook']
].forEach(([type, description]) => {
it(`should recover from errors in ${type} hook`, done => {
const vm = createTestInstance(components[type])
assertBothInstancesActive(vm).then(() => {
expect(`Error in ${description}`).toHaveBeenWarned()
expect(`Error: ${type}`).toHaveBeenWarned()
}).then(done)
})
})
;[
['beforeDestroy', 'beforeDestroy hook'],
['destroyed', 'destroyed hook'],
['directive unbind', 'directive foo unbind hook']
].forEach(([type, description]) => {
it(`should recover from errors in ${type} hook`, done => {
const vm = createTestInstance(components[type])
vm.ok = false
waitForUpdate(() => {
expect(`Error in ${description}`).toHaveBeenWarned()
expect(`Error: ${type}`).toHaveBeenWarned()
}).thenWaitFor(next => {
assertRootInstanceActive(vm).end(next)
}).then(done)
})
})
it('should recover from errors in user watcher getter', done => {
const vm = createTestInstance(components.userWatcherGetter)
vm.n++
waitForUpdate(() => {
expect(`Error in getter for watcher`).toHaveBeenWarned()
function getErrorMsg () {
try {
this.a.b.c
} catch (e) {
return e.toString()
}
}
const msg = getErrorMsg.call(vm)
expect(msg).toHaveBeenWarned()
}).thenWaitFor(next => {
assertBothInstancesActive(vm).end(next)
}).then(done)
})
it('should recover from errors in user watcher callback', done => {
const vm = createTestInstance(components.userWatcherCallback)
vm.n++
waitForUpdate(() => {
expect(`Error in callback for watcher "n"`).toHaveBeenWarned()
expect(`Error: userWatcherCallback`).toHaveBeenWarned()
}).thenWaitFor(next => {
assertBothInstancesActive(vm).end(next)
}).then(done)
})
it('config.errorHandler should capture errors', done => {
const spy = Vue.config.errorHandler = jasmine.createSpy('errorHandler')
const vm = createTestInstance(components.render)
const args = spy.calls.argsFor(0)
expect(args[0].toString()).toContain('Error: render') // error
expect(args[1]).toBe(vm.$refs.child) // vm
expect(args[2]).toContain('render function') // description
assertRootInstanceActive(vm).then(() => {
Vue.config.errorHandler = null
}).then(done)
})
it('should capture and recover from nextTick errors', done => {
const err1 = new Error('nextTick')
const err2 = new Error('nextTick2')
const spy = Vue.config.errorHandler = jasmine.createSpy('errorHandler')
Vue.nextTick(() => { throw err1 })
Vue.nextTick(() => {
expect(spy).toHaveBeenCalledWith(err1, undefined, 'nextTick')
const vm = new Vue()
vm.$nextTick(() => { throw err2 })
Vue.nextTick(() => {
// should be called with correct instance info
expect(spy).toHaveBeenCalledWith(err2, vm, 'nextTick')
Vue.config.errorHandler = null
done()
})
})
})
})
function createErrorTestComponents () {
const components = {}
// data
components.data = {
data () {
throw new Error('data')
},
render (h) {
return h('div')
}
}
// render error
components.render = {
render (h) {
throw new Error('render')
}
}
// lifecycle errors
;['create', 'mount', 'update', 'destroy'].forEach(hook => {
// before
const before = 'before' + hook.charAt(0).toUpperCase() + hook.slice(1)
const beforeComp = components[before] = {
props: ['n'],
render (h) {
return h('div', this.n)
}
}
beforeComp[before] = function () {
throw new Error(before)
}
// after
const after = hook.replace(/e?$/, 'ed')
const afterComp = components[after] = {
props: ['n'],
render (h) {
return h('div', this.n)
}
}
afterComp[after] = function () {
throw new Error(after)
}
})
// directive hooks errors
;['bind', 'update', 'unbind'].forEach(hook => {
const key = 'directive ' + hook
const dirComp = components[key] = {
props: ['n'],
template: `{{ n }}
`
}
const dirFoo = {}
dirFoo[hook] = function () {
throw new Error(key)
}
dirComp.directives = {
foo: dirFoo
}
})
// user watcher
components.userWatcherGetter = {
props: ['n'],
created () {
this.$watch(function () {
return this.n + this.a.b.c
}, val => {
console.log('user watcher fired: ' + val)
})
},
render (h) {
return h('div', this.n)
}
}
components.userWatcherCallback = {
props: ['n'],
watch: {
n () {
throw new Error('userWatcherCallback error')
}
},
render (h) {
return h('div', this.n)
}
}
// event errors
components.event = {
beforeCreate () {
this.$on('e', () => { throw new Error('event') })
},
mounted () {
this.$emit('e')
},
render (h) {
return h('div')
}
}
return components
}
function createTestInstance (Comp) {
return new Vue({
data: {
n: 0,
ok: true
},
render (h) {
return h('div', [
'n:' + this.n + '\n',
this.ok
? h(Comp, { ref: 'child', props: { n: this.n }})
: null
])
}
}).$mount()
}
function assertRootInstanceActive (vm, chain) {
expect(vm.$el.innerHTML).toContain('n:0\n')
vm.n++
return waitForUpdate(() => {
expect(vm.$el.innerHTML).toContain('n:1\n')
})
}
function assertBothInstancesActive (vm) {
vm.n = 0
return waitForUpdate(() => {
expect(vm.$refs.child.$el.innerHTML).toContain('0')
}).thenWaitFor(next => {
assertRootInstanceActive(vm).then(() => {
expect(vm.$refs.child.$el.innerHTML).toContain('1')
}).end(next)
})
}
node-vue-template-compiler-2.4.2+dfsg/test/unit/features/filter/000077500000000000000000000000001361753775300246635ustar00rootroot00000000000000node-vue-template-compiler-2.4.2+dfsg/test/unit/features/filter/filter.spec.js000066400000000000000000000114741361753775300274460ustar00rootroot00000000000000import Vue from 'vue'
import { parseFilters } from 'compiler/parser/filter-parser'
describe('Filters', () => {
it('basic usage', () => {
const vm = new Vue({
template: '{{ msg | upper }}
',
data: {
msg: 'hi'
},
filters: {
upper: v => v.toUpperCase()
}
}).$mount()
expect(vm.$el.textContent).toBe('HI')
})
it('chained usage', () => {
const vm = new Vue({
template: '{{ msg | upper | reverse }}
',
data: {
msg: 'hi'
},
filters: {
upper: v => v.toUpperCase(),
reverse: v => v.split('').reverse().join('')
}
}).$mount()
expect(vm.$el.textContent).toBe('IH')
})
it('in v-bind', () => {
const vm = new Vue({
template: `
`,
filters: {
upper: v => v.toUpperCase(),
reverse: v => v.split('').reverse().join(''),
lower: v => v.toLowerCase()
},
data: {
id: 'abc',
cls: 'foo',
ref: 'BAR'
}
}).$mount()
expect(vm.$el.id).toBe('CBA')
expect(vm.$el.className).toBe('oof')
expect(vm.$refs.bar).toBe(vm.$el)
})
it('handle regex with pipe', () => {
const vm = new Vue({
template: ` `,
filters: { identity: v => v },
components: {
test: {
props: ['pattern'],
template: '
'
}
}
}).$mount()
expect(vm.$refs.test.pattern instanceof RegExp).toBe(true)
expect(vm.$refs.test.pattern.toString()).toBe('/a|b\\//')
})
it('handle division', () => {
const vm = new Vue({
data: { a: 2 },
template: `{{ 1/a / 4 | double }}
`,
filters: { double: v => v * 2 }
}).$mount()
expect(vm.$el.textContent).toBe(String(1 / 4))
})
it('handle division with parenthesis', () => {
const vm = new Vue({
data: { a: 20 },
template: `{{ (a*2) / 5 | double }}
`,
filters: { double: v => v * 2 }
}).$mount()
expect(vm.$el.textContent).toBe(String(16))
})
it('handle division with dot', () => {
const vm = new Vue({
template: `{{ 20. / 5 | double }}
`,
filters: { double: v => v * 2 }
}).$mount()
expect(vm.$el.textContent).toBe(String(8))
})
it('handle division with array values', () => {
const vm = new Vue({
data: { a: [20] },
template: `{{ a[0] / 5 | double }}
`,
filters: { double: v => v * 2 }
}).$mount()
expect(vm.$el.textContent).toBe(String(8))
})
it('handle division with hash values', () => {
const vm = new Vue({
data: { a: { n: 20 }},
template: `{{ a['n'] / 5 | double }}
`,
filters: { double: v => v * 2 }
}).$mount()
expect(vm.$el.textContent).toBe(String(8))
})
it('handle division with variable_', () => {
const vm = new Vue({
data: { a_: 8 },
template: `{{ a_ / 2 | double }}
`,
filters: { double: v => v * 2 }
}).$mount()
expect(vm.$el.textContent).toBe(String(8))
})
it('arguments', () => {
const vm = new Vue({
template: `{{ msg | add(a, 3) }}
`,
data: {
msg: 1,
a: 2
},
filters: {
add: (v, arg1, arg2) => v + arg1 + arg2
}
}).$mount()
expect(vm.$el.textContent).toBe('6')
})
it('quotes', () => {
const vm = new Vue({
template: `{{ msg + "b | c" + 'd' | upper }}
`,
data: {
msg: 'a'
},
filters: {
upper: v => v.toUpperCase()
}
}).$mount()
expect(vm.$el.textContent).toBe('AB | CD')
})
it('double pipe', () => {
const vm = new Vue({
template: `{{ b || msg | upper }}
`,
data: {
b: false,
msg: 'a'
},
filters: {
upper: v => v.toUpperCase()
}
}).$mount()
expect(vm.$el.textContent).toBe('A')
})
it('object literal', () => {
const vm = new Vue({
template: `{{ { a: 123 } | pick('a') }}
`,
filters: {
pick: (v, key) => v[key]
}
}).$mount()
expect(vm.$el.textContent).toBe('123')
})
it('array literal', () => {
const vm = new Vue({
template: `{{ [1, 2, 3] | reverse }}
`,
filters: {
reverse: arr => arr.reverse().join(',')
}
}).$mount()
expect(vm.$el.textContent).toBe('3,2,1')
})
it('warn non-existent', () => {
new Vue({
template: '{{ msg | upper }}
',
data: { msg: 'foo' }
}).$mount()
expect('Failed to resolve filter: upper').toHaveBeenWarned()
})
it('support template string', () => {
expect(parseFilters('`a | ${b}c` | d')).toBe('_f("d")(`a | ${b}c`)')
})
})
node-vue-template-compiler-2.4.2+dfsg/test/unit/features/global-api/000077500000000000000000000000001361753775300254055ustar00rootroot00000000000000node-vue-template-compiler-2.4.2+dfsg/test/unit/features/global-api/assets.spec.js000066400000000000000000000040251361753775300301770ustar00rootroot00000000000000import Vue from 'vue'
describe('Global API: assets', () => {
const Test = Vue.extend()
it('directive / filters', () => {
const assets = ['directive', 'filter']
assets.forEach(function (type) {
const def = {}
Test[type]('test', def)
expect(Test.options[type + 's'].test).toBe(def)
expect(Test[type]('test')).toBe(def)
// extended registration should not pollute global
expect(Vue.options[type + 's'].test).toBeUndefined()
})
})
describe('Vue.component', () => {
it('should register a component', () => {
Vue.component('foo', {
template: 'foo '
})
Vue.component('bar', {
template: 'bar '
})
const vm = new Vue({
template: '
'
}).$mount()
expect(vm.$el.innerHTML).toBe('foo bar ')
// unregister them
delete Vue.options.components.foo
delete Vue.options.components.bar
})
})
it('component on extended constructor', () => {
const def = { a: 1 }
Test.component('test', def)
const component = Test.options.components.test
expect(typeof component).toBe('function')
expect(component.super).toBe(Vue)
expect(component.options.a).toBe(1)
expect(component.options.name).toBe('test')
expect(Test.component('test')).toBe(component)
// already extended
Test.component('test2', component)
expect(Test.component('test2')).toBe(component)
// extended registration should not pollute global
expect(Vue.options.components.test).toBeUndefined()
})
// #4434
it('local registration should take priority regardless of naming convention', () => {
Vue.component('x-foo', {
template: 'global '
})
const vm = new Vue({
components: {
xFoo: {
template: 'local '
}
},
template: '
'
}).$mount()
expect(vm.$el.textContent).toBe('local')
delete Vue.options.components['x-foo']
})
})
node-vue-template-compiler-2.4.2+dfsg/test/unit/features/global-api/compile.spec.js000066400000000000000000000006171361753775300303300ustar00rootroot00000000000000import Vue from 'vue'
describe('Global API: compile', () => {
it('should compile render functions', () => {
const res = Vue.compile('{{ msg }}
')
const vm = new Vue({
data: {
msg: 'hello'
},
render: res.render,
staticRenderFns: res.staticRenderFns
}).$mount()
expect(vm.$el.innerHTML).toContain('hello ')
})
})
node-vue-template-compiler-2.4.2+dfsg/test/unit/features/global-api/config.spec.js000066400000000000000000000025421361753775300301440ustar00rootroot00000000000000import Vue from 'vue'
import { warn } from 'core/util/debug'
describe('Global config', () => {
it('should warn replacing config object', () => {
const originalConfig = Vue.config
Vue.config = {}
expect(Vue.config).toBe(originalConfig)
expect('Do not replace the Vue.config object').toHaveBeenWarned()
})
describe('silent', () => {
it('should be false by default', () => {
warn('foo')
expect('foo').toHaveBeenWarned()
})
it('should work when set to true', () => {
Vue.config.silent = true
warn('foo')
expect('foo').not.toHaveBeenWarned()
Vue.config.silent = false
})
})
describe('optionMergeStrategies', () => {
it('should allow defining custom option merging strategies', () => {
const spy = jasmine.createSpy('option merging')
Vue.config.optionMergeStrategies.__test__ = (parent, child, vm) => {
spy(parent, child, vm)
return child + 1
}
const Test = Vue.extend({
__test__: 1
})
expect(spy.calls.count()).toBe(1)
expect(spy).toHaveBeenCalledWith(undefined, 1, undefined)
expect(Test.options.__test__).toBe(2)
const test = new Test({
__test__: 2
})
expect(spy.calls.count()).toBe(2)
expect(spy).toHaveBeenCalledWith(2, 2, test)
expect(test.$options.__test__).toBe(3)
})
})
})
node-vue-template-compiler-2.4.2+dfsg/test/unit/features/global-api/extend.spec.js000066400000000000000000000060021361753775300301610ustar00rootroot00000000000000import Vue from 'vue'
describe('Global API: extend', () => {
it('should correctly merge options', () => {
const Test = Vue.extend({
name: 'test',
a: 1,
b: 2
})
expect(Test.options.a).toBe(1)
expect(Test.options.b).toBe(2)
expect(Test.super).toBe(Vue)
const t = new Test({
a: 2
})
expect(t.$options.a).toBe(2)
expect(t.$options.b).toBe(2)
// inheritance
const Test2 = Test.extend({
a: 2
})
expect(Test2.options.a).toBe(2)
expect(Test2.options.b).toBe(2)
const t2 = new Test2({
a: 3
})
expect(t2.$options.a).toBe(3)
expect(t2.$options.b).toBe(2)
})
it('should warn invalid names', () => {
Vue.extend({ name: '123' })
expect('Invalid component name: "123"').toHaveBeenWarned()
Vue.extend({ name: '_fesf' })
expect('Invalid component name: "_fesf"').toHaveBeenWarned()
Vue.extend({ name: 'Some App' })
expect('Invalid component name: "Some App"').toHaveBeenWarned()
})
it('should work when used as components', () => {
const foo = Vue.extend({
template: 'foo '
})
const bar = Vue.extend({
template: 'bar '
})
const vm = new Vue({
template: '
',
components: { foo, bar }
}).$mount()
expect(vm.$el.innerHTML).toBe('foo bar ')
})
it('should merge lifecycle hooks', () => {
const calls = []
const A = Vue.extend({
created () {
calls.push(1)
}
})
const B = A.extend({
created () {
calls.push(2)
}
})
new B({
created () {
calls.push(3)
}
})
expect(calls).toEqual([1, 2, 3])
})
it('should merge methods', () => {
const A = Vue.extend({
methods: {
a () { return this.n }
}
})
const B = A.extend({
methods: {
b () { return this.n + 1 }
}
})
const b = new B({
data: { n: 0 },
methods: {
c () { return this.n + 2 }
}
})
expect(b.a()).toBe(0)
expect(b.b()).toBe(1)
expect(b.c()).toBe(2)
})
it('should merge assets', () => {
const A = Vue.extend({
components: {
aa: {
template: 'A
'
}
}
})
const B = A.extend({
components: {
bb: {
template: 'B
'
}
}
})
const b = new B({
template: ''
}).$mount()
expect(b.$el.innerHTML).toBe('A
B
')
})
it('caching', () => {
const options = {
template: '
'
}
const A = Vue.extend(options)
const B = Vue.extend(options)
expect(A).toBe(B)
})
// #4767
it('extended options should use different identify from parent', () => {
const A = Vue.extend({ computed: {}})
const B = A.extend()
B.options.computed.b = () => 'foo'
expect(B.options.computed).not.toBe(A.options.computed)
expect(A.options.computed.b).toBeUndefined()
})
})
node-vue-template-compiler-2.4.2+dfsg/test/unit/features/global-api/mixin.spec.js000066400000000000000000000073721361753775300300310ustar00rootroot00000000000000import Vue from 'vue'
describe('Global API: mixin', () => {
let options
beforeEach(() => { options = Vue.options })
afterEach(() => { Vue.options = options })
it('should work', () => {
const spy = jasmine.createSpy('global mixin')
Vue.mixin({
created () {
spy(this.$options.myOption)
}
})
new Vue({
myOption: 'hello'
})
expect(spy).toHaveBeenCalledWith('hello')
})
it('should work for constructors created before mixin is applied', () => {
const calls = []
const Test = Vue.extend({
name: 'test',
beforeCreate () {
calls.push(this.$options.myOption + ' local')
}
})
Vue.mixin({
beforeCreate () {
calls.push(this.$options.myOption + ' global')
}
})
expect(Test.options.name).toBe('test')
new Test({
myOption: 'hello'
})
expect(calls).toEqual(['hello global', 'hello local'])
})
// #3957
it('should work for global props', () => {
const Test = Vue.extend({
template: `{{ prop }}
`
})
Vue.mixin({
props: ['prop']
})
// test child component
const vm = new Vue({
template: ' ',
components: { Test }
}).$mount()
expect(vm.$el.textContent).toBe('hi')
})
// vue-loader#433
it('should not drop late-set render functions', () => {
const Test = Vue.extend({})
Test.options.render = h => h('div', 'hello')
Vue.mixin({})
const vm = new Vue({
render: h => h(Test)
}).$mount()
expect(vm.$el.textContent).toBe('hello')
})
// #4266
it('should not drop scopedId', () => {
const Test = Vue.extend({})
Test.options._scopeId = 'foo'
Vue.mixin({})
const vm = new Test({
template: ''
}).$mount()
expect(vm.$el.children[0].hasAttribute('foo')).toBe(true)
})
// #4976
it('should not drop late-attached custom options on existing constructors', () => {
const baseSpy = jasmine.createSpy('base')
const Base = Vue.extend({
beforeCreate: baseSpy
})
const Test = Base.extend({})
// Inject options later
// vue-loader and vue-hot-reload-api are doing like this
Test.options.computed = {
$style: () => 123
}
const spy = jasmine.createSpy('late attached')
Test.options.beforeCreate = Test.options.beforeCreate.concat(spy)
// Update super constructor's options
const mixinSpy = jasmine.createSpy('mixin')
Vue.mixin({
beforeCreate: mixinSpy
})
// mount the component
const vm = new Test({
template: '{{ $style }}
'
}).$mount()
expect(spy.calls.count()).toBe(1)
expect(baseSpy.calls.count()).toBe(1)
expect(mixinSpy.calls.count()).toBe(1)
expect(vm.$el.textContent).toBe('123')
expect(vm.$style).toBe(123)
// Should not be dropped
expect(Test.options.computed.$style()).toBe(123)
expect(Test.options.beforeCreate).toEqual([mixinSpy, baseSpy, spy])
})
// vue-class-component#83
it('should work for a constructor mixin', () => {
const spy = jasmine.createSpy('global mixin')
const Mixin = Vue.extend({
created () {
spy(this.$options.myOption)
}
})
Vue.mixin(Mixin)
new Vue({
myOption: 'hello'
})
expect(spy).toHaveBeenCalledWith('hello')
})
// vue-class-component#87
it('should not drop original lifecycle hooks', () => {
const base = jasmine.createSpy('base')
const Base = Vue.extend({
beforeCreate: base
})
const injected = jasmine.createSpy('injected')
// inject a function
Base.options.beforeCreate = Base.options.beforeCreate.concat(injected)
Vue.mixin({})
new Base({})
expect(base).toHaveBeenCalled()
expect(injected).toHaveBeenCalled()
})
})
node-vue-template-compiler-2.4.2+dfsg/test/unit/features/global-api/set-delete.spec.js000066400000000000000000000107211361753775300307300ustar00rootroot00000000000000import Vue from 'vue'
describe('Global API: set/delete', () => {
describe('Vue.set', () => {
it('should update a vue object', done => {
const vm = new Vue({
template: '{{x}}
',
data: { x: 1 }
}).$mount()
expect(vm.$el.innerHTML).toBe('1')
Vue.set(vm, 'x', 2)
waitForUpdate(() => {
expect(vm.$el.innerHTML).toBe('2')
}).then(done)
})
it('should update a observing object', done => {
const vm = new Vue({
template: '{{foo.x}}
',
data: { foo: { x: 1 }}
}).$mount()
expect(vm.$el.innerHTML).toBe('1')
Vue.set(vm.foo, 'x', 2)
waitForUpdate(() => {
expect(vm.$el.innerHTML).toBe('2')
}).then(done)
})
it('should update a observing array', done => {
const vm = new Vue({
template: '',
data: { list: ['a', 'b', 'c'] }
}).$mount()
expect(vm.$el.innerHTML).toBe('0-a
1-b
2-c
')
Vue.set(vm.list, 1, 'd')
waitForUpdate(() => {
expect(vm.$el.innerHTML).toBe('0-a
1-d
2-c
')
Vue.set(vm.list, '2', 'e')
}).then(() => {
expect(vm.$el.innerHTML).toBe('0-a
1-d
2-e
')
/* eslint-disable no-new-wrappers */
Vue.set(vm.list, new Number(1), 'f')
}).then(() => {
expect(vm.$el.innerHTML).toBe('0-a
1-f
2-e
')
Vue.set(vm.list, '3g', 'g')
}).then(() => {
expect(vm.$el.innerHTML).toBe('0-a
1-f
2-e
')
}).then(done)
})
it('should update a vue object with nothing', done => {
const vm = new Vue({
template: '{{x}}
',
data: { x: 1 }
}).$mount()
expect(vm.$el.innerHTML).toBe('1')
Vue.set(vm, 'x', null)
waitForUpdate(() => {
expect(vm.$el.innerHTML).toBe('')
Vue.set(vm, 'x')
}).then(() => {
expect(vm.$el.innerHTML).toBe('')
}).then(done)
})
it('be able to use string type index in array', done => {
const vm = new Vue({
template: '',
data: {
lists: [
{ name: 'A' },
{ name: 'B' },
{ name: 'C' }
]
}
}).$mount()
expect(vm.$el.innerHTML).toBe('A
B
C
')
Vue.set(vm.lists, '0', { name: 'D' })
waitForUpdate(() => {
expect(vm.$el.innerHTML).toBe('D
B
C
')
}).then(done)
})
})
describe('Vue.delete', () => {
it('should delete a key', done => {
const vm = new Vue({
template: '{{obj.x}}
',
data: { obj: { x: 1 }}
}).$mount()
expect(vm.$el.innerHTML).toBe('1')
vm.obj.x = 2
waitForUpdate(() => {
expect(vm.$el.innerHTML).toBe('2')
Vue.delete(vm.obj, 'x')
}).then(() => {
expect(vm.$el.innerHTML).toBe('')
vm.obj.x = 3
}).then(() => {
expect(vm.$el.innerHTML).toBe('')
}).then(done)
})
it('be able to delete an item in array', done => {
const vm = new Vue({
template: '',
data: {
lists: [
{ name: 'A' },
{ name: 'B' },
{ name: 'C' }
]
}
}).$mount()
expect(vm.$el.innerHTML).toBe('A
B
C
')
Vue.delete(vm.lists, 1)
waitForUpdate(() => {
expect(vm.$el.innerHTML).toBe('A
C
')
Vue.delete(vm.lists, NaN)
}).then(() => {
expect(vm.$el.innerHTML).toBe('A
C
')
Vue.delete(vm.lists, -1)
}).then(() => {
expect(vm.$el.innerHTML).toBe('A
C
')
Vue.delete(vm.lists, '1.3')
}).then(() => {
expect(vm.$el.innerHTML).toBe('A
C
')
Vue.delete(vm.lists, true)
}).then(() => {
expect(vm.$el.innerHTML).toBe('A
C
')
Vue.delete(vm.lists, {})
}).then(() => {
expect(vm.$el.innerHTML).toBe('A
C
')
Vue.delete(vm.lists, '1')
}).then(() => {
expect(vm.$el.innerHTML).toBe('A
')
/* eslint-disable no-new-wrappers */
Vue.delete(vm.lists, new Number(0))
}).then(() => {
expect(vm.$el.innerHTML).toBe('')
}).then(done)
})
})
})
node-vue-template-compiler-2.4.2+dfsg/test/unit/features/global-api/use.spec.js000066400000000000000000000031571361753775300274760ustar00rootroot00000000000000import Vue from 'vue'
describe('Global API: use', () => {
const def = {}
const options = {}
const pluginStub = {
install: (Vue, opts) => {
Vue.directive('plugin-test', def)
expect(opts).toBe(options)
}
}
it('should apply Object plugin', () => {
Vue.use(pluginStub, options)
expect(Vue.options.directives['plugin-test']).toBe(def)
delete Vue.options.directives['plugin-test']
expect(Vue.options.directives['plugin-test']).toBeUndefined()
// should not double apply
Vue.use(pluginStub, options)
expect(Vue.options.directives['plugin-test']).toBeUndefined()
})
it('should apply Function plugin', () => {
Vue.use(pluginStub.install, options)
expect(Vue.options.directives['plugin-test']).toBe(def)
delete Vue.options.directives['plugin-test']
})
it('should work on extended constructors without polluting the base', () => {
const Ctor = Vue.extend({})
Ctor.use(pluginStub, options)
expect(Vue.options.directives['plugin-test']).toBeUndefined()
expect(Ctor.options.directives['plugin-test']).toBe(def)
})
// Github issue #5970
it('should work on multi version', () => {
const Ctor1 = Vue.extend({})
const Ctor2 = Vue.extend({})
Ctor1.use(pluginStub, options)
expect(Vue.options.directives['plugin-test']).toBeUndefined()
expect(Ctor1.options.directives['plugin-test']).toBe(def)
// multi version Vue Ctor with the same cid
Ctor2.cid = Ctor1.cid
Ctor2.use(pluginStub, options)
expect(Vue.options.directives['plugin-test']).toBeUndefined()
expect(Ctor2.options.directives['plugin-test']).toBe(def)
})
})
node-vue-template-compiler-2.4.2+dfsg/test/unit/features/instance/000077500000000000000000000000001361753775300252025ustar00rootroot00000000000000node-vue-template-compiler-2.4.2+dfsg/test/unit/features/instance/init.spec.js000066400000000000000000000004561361753775300274410ustar00rootroot00000000000000import Vue from 'vue'
describe('Initialization', () => {
it('without new', () => {
try { Vue() } catch (e) {}
expect('Vue is a constructor and should be called with the `new` keyword').toHaveBeenWarned()
})
it('with new', () => {
expect(new Vue() instanceof Vue).toBe(true)
})
})
node-vue-template-compiler-2.4.2+dfsg/test/unit/features/instance/methods-data.spec.js000066400000000000000000000052631361753775300310510ustar00rootroot00000000000000import Vue from 'vue'
describe('Instance methods data', () => {
it('$set/$delete', done => {
const vm = new Vue({
template: '{{ a.msg }}
',
data: {
a: {}
}
}).$mount()
expect(vm.$el.innerHTML).toBe('')
vm.$set(vm.a, 'msg', 'hello')
waitForUpdate(() => {
expect(vm.$el.innerHTML).toBe('hello')
vm.$delete(vm.a, 'msg')
}).then(() => {
expect(vm.$el.innerHTML).toBe('')
}).then(done)
})
describe('$watch', () => {
let vm, spy
beforeEach(() => {
spy = jasmine.createSpy('watch')
vm = new Vue({
data: {
a: {
b: 1
}
},
methods: {
foo: spy
}
})
})
it('basic usage', done => {
vm.$watch('a.b', spy)
vm.a.b = 2
waitForUpdate(() => {
expect(spy.calls.count()).toBe(1)
expect(spy).toHaveBeenCalledWith(2, 1)
vm.a = { b: 3 }
}).then(() => {
expect(spy.calls.count()).toBe(2)
expect(spy).toHaveBeenCalledWith(3, 2)
}).then(done)
})
it('immediate', () => {
vm.$watch('a.b', spy, { immediate: true })
expect(spy.calls.count()).toBe(1)
expect(spy).toHaveBeenCalledWith(1)
})
it('unwatch', done => {
const unwatch = vm.$watch('a.b', spy)
unwatch()
vm.a.b = 2
waitForUpdate(() => {
expect(spy.calls.count()).toBe(0)
}).then(done)
})
it('function watch', done => {
vm.$watch(function () {
return this.a.b
}, spy)
vm.a.b = 2
waitForUpdate(() => {
expect(spy).toHaveBeenCalledWith(2, 1)
}).then(done)
})
it('deep watch', done => {
var oldA = vm.a
vm.$watch('a', spy, { deep: true })
vm.a.b = 2
waitForUpdate(() => {
expect(spy).toHaveBeenCalledWith(oldA, oldA)
vm.a = { b: 3 }
}).then(() => {
expect(spy).toHaveBeenCalledWith(vm.a, oldA)
}).then(done)
})
it('handler option', done => {
var oldA = vm.a
vm.$watch('a', {
handler: spy,
deep: true
})
vm.a.b = 2
waitForUpdate(() => {
expect(spy).toHaveBeenCalledWith(oldA, oldA)
vm.a = { b: 3 }
}).then(() => {
expect(spy).toHaveBeenCalledWith(vm.a, oldA)
}).then(done)
})
it('handler option in string', () => {
vm.$watch('a.b', {
handler: 'foo',
immediate: true
})
expect(spy.calls.count()).toBe(1)
expect(spy).toHaveBeenCalledWith(1)
})
it('warn expresssion', () => {
vm.$watch('a + b', spy)
expect('Watcher only accepts simple dot-delimited paths').toHaveBeenWarned()
})
})
})
node-vue-template-compiler-2.4.2+dfsg/test/unit/features/instance/methods-events.spec.js000066400000000000000000000040551361753775300314420ustar00rootroot00000000000000import Vue from 'vue'
describe('Instance methods events', () => {
let vm, spy
beforeEach(() => {
vm = new Vue()
spy = jasmine.createSpy('emitter')
})
it('$on', () => {
vm.$on('test', function () {
// expect correct context
expect(this).toBe(vm)
spy.apply(this, arguments)
})
vm.$emit('test', 1, 2, 3, 4)
expect(spy.calls.count()).toBe(1)
expect(spy).toHaveBeenCalledWith(1, 2, 3, 4)
})
it('$on multi event', () => {
vm.$on(['test1', 'test2'], function () {
expect(this).toBe(vm)
spy.apply(this, arguments)
})
vm.$emit('test1', 1, 2, 3, 4)
expect(spy.calls.count()).toBe(1)
expect(spy).toHaveBeenCalledWith(1, 2, 3, 4)
vm.$emit('test2', 5, 6, 7, 8)
expect(spy.calls.count()).toBe(2)
expect(spy).toHaveBeenCalledWith(5, 6, 7, 8)
})
it('$off multi event', () => {
vm.$on(['test1', 'test2', 'test3'], spy)
vm.$off(['test1', 'test2'], spy)
vm.$emit('test1')
vm.$emit('test2')
expect(spy).not.toHaveBeenCalled()
vm.$emit('test3', 1, 2, 3, 4)
expect(spy.calls.count()).toBe(1)
})
it('$once', () => {
vm.$once('test', spy)
vm.$emit('test', 1, 2, 3)
vm.$emit('test', 2, 3, 4)
expect(spy.calls.count()).toBe(1)
expect(spy).toHaveBeenCalledWith(1, 2, 3)
})
it('$off', () => {
vm.$on('test1', spy)
vm.$on('test2', spy)
vm.$off()
vm.$emit('test1')
vm.$emit('test2')
expect(spy).not.toHaveBeenCalled()
})
it('$off event', () => {
vm.$on('test1', spy)
vm.$on('test2', spy)
vm.$off('test1')
vm.$off('test1') // test off something that's already off
vm.$emit('test1', 1)
vm.$emit('test2', 2)
expect(spy.calls.count()).toBe(1)
expect(spy).toHaveBeenCalledWith(2)
})
it('$off event + fn', () => {
var spy2 = jasmine.createSpy('emitter')
vm.$on('test', spy)
vm.$on('test', spy2)
vm.$off('test', spy)
vm.$emit('test', 1, 2, 3)
expect(spy).not.toHaveBeenCalled()
expect(spy2.calls.count()).toBe(1)
expect(spy2).toHaveBeenCalledWith(1, 2, 3)
})
})
node-vue-template-compiler-2.4.2+dfsg/test/unit/features/instance/methods-lifecycle.spec.js000066400000000000000000000065301361753775300320750ustar00rootroot00000000000000import Vue from 'vue'
describe('Instance methods lifecycle', () => {
describe('$mount', () => {
it('empty mount', () => {
const vm = new Vue({
data: { msg: 'hi' },
template: '{{ msg }}
'
}).$mount()
expect(vm.$el.tagName).toBe('DIV')
expect(vm.$el.textContent).toBe('hi')
})
it('mount to existing element', () => {
const el = document.createElement('div')
el.innerHTML = '{{ msg }}'
const vm = new Vue({
data: { msg: 'hi' }
}).$mount(el)
expect(vm.$el.tagName).toBe('DIV')
expect(vm.$el.textContent).toBe('hi')
})
it('mount to id', () => {
const el = document.createElement('div')
el.id = 'mount-test'
el.innerHTML = '{{ msg }}'
document.body.appendChild(el)
const vm = new Vue({
data: { msg: 'hi' }
}).$mount('#mount-test')
expect(vm.$el.tagName).toBe('DIV')
expect(vm.$el.textContent).toBe('hi')
})
})
describe('$destroy', () => {
it('remove self from parent', () => {
const vm = new Vue({
template: ' ',
components: {
test: { template: '
' }
}
}).$mount()
vm.$children[0].$destroy()
expect(vm.$children.length).toBe(0)
})
it('teardown watchers', () => {
const vm = new Vue({
data: { a: 123 },
template: '
'
}).$mount()
vm.$watch('a', () => {})
vm.$destroy()
expect(vm._watcher.active).toBe(false)
expect(vm._watchers.every(w => !w.active)).toBe(true)
})
it('remove self from data observer', () => {
const vm = new Vue({ data: { a: 1 }})
vm.$destroy()
expect(vm.$data.__ob__.vmCount).toBe(0)
})
it('avoid duplicate calls', () => {
const spy = jasmine.createSpy('destroy')
const vm = new Vue({
beforeDestroy: spy
})
vm.$destroy()
vm.$destroy()
expect(spy.calls.count()).toBe(1)
})
})
describe('$forceUpdate', () => {
it('should force update', done => {
const vm = new Vue({
data: {
a: {}
},
template: '{{ a.b }}
'
}).$mount()
expect(vm.$el.textContent).toBe('')
vm.a.b = 'foo'
waitForUpdate(() => {
// should not work because adding new property
expect(vm.$el.textContent).toBe('')
vm.$forceUpdate()
}).then(() => {
expect(vm.$el.textContent).toBe('foo')
}).then(done)
})
})
describe('$nextTick', () => {
it('should be called after DOM update in correct context', done => {
const vm = new Vue({
template: '{{ msg }}
',
data: {
msg: 'foo'
}
}).$mount()
vm.msg = 'bar'
vm.$nextTick(function () {
expect(this).toBe(vm)
expect(vm.$el.textContent).toBe('bar')
done()
})
})
if (typeof Promise !== 'undefined') {
it('should be called after DOM update in correct context, when using Promise syntax', done => {
const vm = new Vue({
template: '{{ msg }}
',
data: {
msg: 'foo'
}
}).$mount()
vm.msg = 'bar'
vm.$nextTick().then(ctx => {
expect(ctx).toBe(vm)
expect(vm.$el.textContent).toBe('bar')
done()
})
})
}
})
})
node-vue-template-compiler-2.4.2+dfsg/test/unit/features/instance/properties.spec.js000066400000000000000000000110571361753775300306710ustar00rootroot00000000000000import Vue from 'vue'
describe('Instance properties', () => {
it('$data', () => {
const data = { a: 1 }
const vm = new Vue({
data
})
expect(vm.a).toBe(1)
expect(vm.$data).toBe(data)
// vm -> data
vm.a = 2
expect(data.a).toBe(2)
// data -> vm
data.a = 3
expect(vm.a).toBe(3)
})
it('$options', () => {
const A = Vue.extend({
methods: {
a () {}
}
})
const vm = new A({
methods: {
b () {}
}
})
expect(typeof vm.$options.methods.a).toBe('function')
expect(typeof vm.$options.methods.b).toBe('function')
})
it('$root/$children', done => {
const vm = new Vue({
template: '
',
data: { ok: true },
components: {
test: {
template: '
'
}
}
}).$mount()
expect(vm.$root).toBe(vm)
expect(vm.$children.length).toBe(1)
expect(vm.$children[0].$root).toBe(vm)
vm.ok = false
waitForUpdate(() => {
expect(vm.$children.length).toBe(0)
vm.ok = true
}).then(() => {
expect(vm.$children.length).toBe(1)
expect(vm.$children[0].$root).toBe(vm)
}).then(done)
})
it('$parent', () => {
const calls = []
const makeOption = name => ({
name,
template: `
`,
created () {
calls.push(`${name}:${this.$parent.$options.name}`)
}
})
new Vue({
template: `
`,
components: {
outer: makeOption('outer'),
middle: makeOption('middle'),
inner: makeOption('inner'),
next: makeOption('next')
}
}).$mount()
expect(calls).toEqual(['outer:undefined', 'middle:outer', 'inner:middle', 'next:undefined'])
})
it('$props', done => {
const Comp = Vue.extend({
props: ['msg'],
template: '{{ msg }} {{ $props.msg }}
'
})
const vm = new Comp({
propsData: {
msg: 'foo'
}
}).$mount()
// check render
expect(vm.$el.textContent).toContain('foo foo')
// warn set
vm.$props = {}
expect('$props is readonly').toHaveBeenWarned()
// check existence
expect(vm.$props.msg).toBe('foo')
// check change
vm.msg = 'bar'
expect(vm.$props.msg).toBe('bar')
waitForUpdate(() => {
expect(vm.$el.textContent).toContain('bar bar')
}).then(() => {
vm.$props.msg = 'baz'
expect(vm.msg).toBe('baz')
}).then(() => {
expect(vm.$el.textContent).toContain('baz baz')
}).then(done)
})
it('warn mutating $props', () => {
const Comp = {
props: ['msg'],
render () {},
mounted () {
expect(this.$props.msg).toBe('foo')
this.$props.msg = 'bar'
}
}
new Vue({
template: ``,
components: { Comp }
}).$mount()
expect(`Avoid mutating a prop`).toHaveBeenWarned()
})
it('$attrs', done => {
const vm = new Vue({
template: ``,
data: { foo: 'foo' },
components: {
foo: {
props: ['bar'],
template: ``
}
}
}).$mount()
expect(vm.$el.children[0].id).toBe('foo')
expect(vm.$el.children[0].hasAttribute('bar')).toBe(false)
vm.foo = 'bar'
waitForUpdate(() => {
expect(vm.$el.children[0].id).toBe('bar')
expect(vm.$el.children[0].hasAttribute('bar')).toBe(false)
}).then(done)
})
it('warn mutating $attrs', () => {
const vm = new Vue()
vm.$attrs = {}
expect(`$attrs is readonly`).toHaveBeenWarned()
})
it('$listeners', done => {
const spyA = jasmine.createSpy('A')
const spyB = jasmine.createSpy('B')
const vm = new Vue({
template: ``,
data: { foo: spyA },
components: {
foo: {
template: `
`
}
}
}).$mount()
// has to be in dom for test to pass in IE
document.body.appendChild(vm.$el)
triggerEvent(vm.$el, 'click')
expect(spyA.calls.count()).toBe(1)
expect(spyB.calls.count()).toBe(0)
vm.foo = spyB
waitForUpdate(() => {
triggerEvent(vm.$el, 'click')
expect(spyA.calls.count()).toBe(1)
expect(spyB.calls.count()).toBe(1)
document.body.removeChild(vm.$el)
}).then(done)
})
it('warn mutating $listeners', () => {
const vm = new Vue()
vm.$listeners = {}
expect(`$listeners is readonly`).toHaveBeenWarned()
})
})
node-vue-template-compiler-2.4.2+dfsg/test/unit/features/instance/render-proxy.spec.js000066400000000000000000000016031361753775300311270ustar00rootroot00000000000000import Vue from 'vue'
if (typeof Proxy !== 'undefined') {
describe('render proxy', () => {
it('should warn missing property in render fns with `with`', () => {
new Vue({
template: `{{ a }}
`
}).$mount()
expect(`Property or method "a" is not defined`).toHaveBeenWarned()
})
it('should warn missing property in render fns without `with`', () => {
const render = function (h) {
return h('div', [this.a])
}
render._withStripped = true
new Vue({
render
}).$mount()
expect(`Property or method "a" is not defined`).toHaveBeenWarned()
})
it('should not warn for hand-written render functions', () => {
new Vue({
render (h) {
return h('div', [this.a])
}
}).$mount()
expect(`Property or method "a" is not defined`).not.toHaveBeenWarned()
})
})
}
node-vue-template-compiler-2.4.2+dfsg/test/unit/features/options/000077500000000000000000000000001361753775300250715ustar00rootroot00000000000000node-vue-template-compiler-2.4.2+dfsg/test/unit/features/options/_scopeId.spec.js000066400000000000000000000041151361753775300301060ustar00rootroot00000000000000import Vue from 'vue'
describe('Options _scopeId', () => {
it('should add scopeId attributes', () => {
const vm = new Vue({
_scopeId: 'foo',
template: ''
}).$mount()
expect(vm.$el.hasAttribute('foo')).toBe(true)
expect(vm.$el.children[0].hasAttribute('foo')).toBe(true)
expect(vm.$el.children[0].children[0].hasAttribute('foo')).toBe(true)
})
it('should add scopedId attributes from both parent and child on child root', () => {
const vm = new Vue({
_scopeId: 'foo',
template: '
',
components: {
child: {
_scopeId: 'bar',
template: '
'
}
}
}).$mount()
expect(vm.$el.children[0].hasAttribute('foo')).toBe(true)
expect(vm.$el.children[0].hasAttribute('bar')).toBe(true)
})
it('should add scopedId attributes from both parent and child on slot contents', () => {
const vm = new Vue({
_scopeId: 'foo',
template: '',
components: {
child: {
_scopeId: 'bar',
template: '
'
}
}
}).$mount()
expect(vm.$el.children[0].children[0].hasAttribute('foo')).toBe(true)
expect(vm.$el.children[0].children[0].hasAttribute('bar')).toBe(true)
})
// #4774
it('should not discard parent scopeId when component root element is replaced', done => {
const vm = new Vue({
_scopeId: 'data-1',
template: `
`,
components: {
child: {
_scopeId: 'data-2',
data: () => ({ show: true }),
template: '
'
}
}
}).$mount()
const child = vm.$refs.child
expect(child.$el.hasAttribute('data-1')).toBe(true)
expect(child.$el.hasAttribute('data-2')).toBe(true)
child.show = false
waitForUpdate(() => {
child.show = true
}).then(() => {
expect(child.$el.hasAttribute('data-1')).toBe(true)
expect(child.$el.hasAttribute('data-2')).toBe(true)
}).then(done)
})
})
node-vue-template-compiler-2.4.2+dfsg/test/unit/features/options/comments.spec.js000066400000000000000000000006271361753775300302120ustar00rootroot00000000000000import Vue from 'vue'
describe('Comments', () => {
it('comments should be kept', () => {
const vm = new Vue({
comments: true,
data () {
return {
foo: 1
}
},
template: 'node1 {{foo}}
'
}).$mount()
expect(vm.$el.innerHTML).toEqual('node1 1')
})
})
node-vue-template-compiler-2.4.2+dfsg/test/unit/features/options/components.spec.js000066400000000000000000000043041361753775300305460ustar00rootroot00000000000000import Vue from 'vue'
import { UA } from 'core/util/env'
describe('Options components', () => {
it('should accept plain object', () => {
const vm = new Vue({
template: ' ',
components: {
test: {
template: 'hi
'
}
}
}).$mount()
expect(vm.$el.tagName).toBe('DIV')
expect(vm.$el.textContent).toBe('hi')
})
it('should accept extended constructor', () => {
const Test = Vue.extend({
template: 'hi
'
})
const vm = new Vue({
template: ' ',
components: {
test: Test
}
}).$mount()
expect(vm.$el.tagName).toBe('DIV')
expect(vm.$el.textContent).toBe('hi')
})
it('should accept camelCase', () => {
const myComp = {
template: 'hi
'
}
const vm = new Vue({
template: ' ',
components: {
myComp
}
}).$mount()
expect(vm.$el.tagName).toBe('DIV')
expect(vm.$el.textContent).toBe('hi')
})
it('should accept PascalCase', () => {
const MyComp = {
template: 'hi
'
}
const vm = new Vue({
template: ' ',
components: {
MyComp
}
}).$mount()
expect(vm.$el.tagName).toBe('DIV')
expect(vm.$el.textContent).toBe('hi')
})
it('should warn native HTML elements', () => {
new Vue({
components: {
div: { template: '
' }
}
})
expect('Do not use built-in or reserved HTML elements as component').toHaveBeenWarned()
})
it('should warn built-in elements', () => {
new Vue({
components: {
component: { template: '
' }
}
})
expect('Do not use built-in or reserved HTML elements as component').toHaveBeenWarned()
})
// the HTMLUnknownElement check doesn't work in Android 4.2
// but since it doesn't support custom elements nor will any dev use it
// as their primary debugging browser, it doesn't really matter.
if (!(UA && /android 4\.2/.test(UA))) {
it('warn non-existent', () => {
new Vue({
template: ' '
}).$mount()
expect('Unknown custom element: ').toHaveBeenWarned()
})
}
})
node-vue-template-compiler-2.4.2+dfsg/test/unit/features/options/computed.spec.js000066400000000000000000000107101361753775300301770ustar00rootroot00000000000000import Vue from 'vue'
import testObjectOption from '../../../helpers/test-object-option'
describe('Options computed', () => {
it('basic usage', done => {
const vm = new Vue({
template: '{{ b }}
',
data: {
a: 1
},
computed: {
b () {
return this.a + 1
}
}
}).$mount()
expect(vm.b).toBe(2)
expect(vm.$el.textContent).toBe('2')
vm.a = 2
expect(vm.b).toBe(3)
waitForUpdate(() => {
expect(vm.$el.textContent).toBe('3')
}).then(done)
})
it('with setter', done => {
const vm = new Vue({
template: '{{ b }}
',
data: {
a: 1
},
computed: {
b: {
get () { return this.a + 1 },
set (v) { this.a = v - 1 }
}
}
}).$mount()
expect(vm.b).toBe(2)
expect(vm.$el.textContent).toBe('2')
vm.a = 2
expect(vm.b).toBe(3)
waitForUpdate(() => {
expect(vm.$el.textContent).toBe('3')
vm.b = 1
expect(vm.a).toBe(0)
}).then(() => {
expect(vm.$el.textContent).toBe('1')
}).then(done)
})
testObjectOption('computed')
it('warn with setter and no getter', () => {
const vm = new Vue({
template: `
`,
components: {
test: {
data () {
return {
a: 1
}
},
computed: {
b: {
set (v) { this.a = v }
}
},
template: `{{a}}
`
}
}
}).$mount()
expect(vm.$el.innerHTML).toBe('1
')
expect('Getter is missing for computed property "b".').toHaveBeenWarned()
})
it('warn assigning to computed with no setter', () => {
const vm = new Vue({
computed: {
b () {
return 1
}
}
})
vm.b = 2
expect(`Computed property "b" was assigned to but it has no setter.`).toHaveBeenWarned()
})
it('watching computed', done => {
const spy = jasmine.createSpy('watch computed')
const vm = new Vue({
data: {
a: 1
},
computed: {
b () { return this.a + 1 }
}
})
vm.$watch('b', spy)
vm.a = 2
waitForUpdate(() => {
expect(spy).toHaveBeenCalledWith(3, 2)
}).then(done)
})
it('caching', () => {
const spy = jasmine.createSpy('cached computed')
const vm = new Vue({
data: {
a: 1
},
computed: {
b () {
spy()
return this.a + 1
}
}
})
expect(spy.calls.count()).toBe(0)
vm.b
expect(spy.calls.count()).toBe(1)
vm.b
expect(spy.calls.count()).toBe(1)
})
it('cache: false', () => {
const spy = jasmine.createSpy('cached computed')
const vm = new Vue({
data: {
a: 1
},
computed: {
b: {
cache: false,
get () {
spy()
return this.a + 1
}
}
}
})
expect(spy.calls.count()).toBe(0)
vm.b
expect(spy.calls.count()).toBe(1)
vm.b
expect(spy.calls.count()).toBe(2)
})
it('as component', done => {
const Comp = Vue.extend({
template: `{{ b }} {{ c }}
`,
data () {
return { a: 1 }
},
computed: {
// defined on prototype
b () {
return this.a + 1
}
}
})
const vm = new Comp({
computed: {
// defined at instantiation
c () {
return this.b + 1
}
}
}).$mount()
expect(vm.b).toBe(2)
expect(vm.c).toBe(3)
expect(vm.$el.textContent).toBe('2 3')
vm.a = 2
expect(vm.b).toBe(3)
expect(vm.c).toBe(4)
waitForUpdate(() => {
expect(vm.$el.textContent).toBe('3 4')
}).then(done)
})
it('warn conflict with data', () => {
new Vue({
data: {
a: 1
},
computed: {
a: () => 2
}
})
expect(`computed property "a" is already defined in data`).toHaveBeenWarned()
})
it('warn conflict with props', () => {
new Vue({
props: ['a'],
propsData: { a: 1 },
computed: {
a: () => 2
}
})
expect(`computed property "a" is already defined as a prop`).toHaveBeenWarned()
})
it('rethrow computed error', () => {
const vm = new Vue({
computed: {
a: () => {
throw new Error('rethrow')
}
}
})
expect(() => vm.a).toThrowError('rethrow')
})
})
node-vue-template-compiler-2.4.2+dfsg/test/unit/features/options/data.spec.js000066400000000000000000000043411361753775300272730ustar00rootroot00000000000000import Vue from 'vue'
describe('Options data', () => {
it('should proxy and be reactive', done => {
const data = { msg: 'foo' }
const vm = new Vue({
data,
template: '{{ msg }}
'
}).$mount()
expect(vm.$data).toEqual({ msg: 'foo' })
expect(vm.$data).toBe(data)
data.msg = 'bar'
waitForUpdate(() => {
expect(vm.$el.textContent).toBe('bar')
}).then(done)
})
it('should merge data properly', () => {
const Test = Vue.extend({
data () {
return { a: 1 }
}
})
let vm = new Test({
data: { b: 2 }
})
expect(vm.a).toBe(1)
expect(vm.b).toBe(2)
// no instance data
vm = new Test()
expect(vm.a).toBe(1)
// no child-val
const Extended = Test.extend({})
vm = new Extended()
expect(vm.a).toBe(1)
// recursively merge objects
const WithObject = Vue.extend({
data () {
return {
obj: {
a: 1
}
}
}
})
vm = new WithObject({
data: {
obj: {
b: 2
}
}
})
expect(vm.obj.a).toBe(1)
expect(vm.obj.b).toBe(2)
})
it('should warn non-function during extend', () => {
Vue.extend({
data: { msg: 'foo' }
})
expect('The "data" option should be a function').toHaveBeenWarned()
})
it('should warn non object return', () => {
new Vue({
data () {}
})
expect('data functions should return an object').toHaveBeenWarned()
})
it('should warn replacing root $data', () => {
const vm = new Vue({
data: {}
})
vm.$data = {}
expect('Avoid replacing instance root $data').toHaveBeenWarned()
})
it('should have access to props', () => {
const Test = {
props: ['a'],
render () {},
data () {
return {
b: this.a
}
}
}
const vm = new Vue({
template: ` `,
components: { Test }
}).$mount()
expect(vm.$refs.test.b).toBe(1)
})
it('should have access to methods', () => {
const vm = new Vue({
methods: {
get () {
return { a: 1 }
}
},
data () {
return this.get()
}
})
expect(vm.a).toBe(1)
})
})
node-vue-template-compiler-2.4.2+dfsg/test/unit/features/options/delimiters.spec.js000066400000000000000000000050141361753775300305210ustar00rootroot00000000000000import Vue from 'vue'
describe('Delimiters', () => {
it('default delimiters should work', () => {
const vm = new Vue({
data: {
a: 1
},
template: '{{ a }}
'
}).$mount()
expect(vm.$el.textContent).toEqual('1')
})
it('custom delimiters should work', () => {
const vm = new Vue({
delimiters: ['[[', ']]'],
template: '[[ a ]]
',
data: {
a: 1
}
}).$mount()
expect(vm.$el.textContent).toEqual('1')
})
it('default delimiters should be ignored when custom delimiters defined', () => {
const vm = new Vue({
delimiters: ['[[', ']]'],
template: '{{ a }}
',
data: {
a: 1
}
}).$mount()
expect(vm.$el.textContent).toEqual('{{ a }}')
})
it('delimiters should only affect vm', () => {
const Component = Vue.extend({
data: function () {
return {
b: 2
}
},
template: '[[ b ]] '
})
const vm = new Vue({
delimiters: ['[[', ']]'],
template: '[[ a ]] -
',
data: {
a: 2
},
components: {
'test-component': Component
}
}).$mount()
expect(vm.$el.textContent).toEqual('2 - [[ b ]]')
})
it('delimiters defined globally should work on all vms', () => {
Vue.options.delimiters = ['[[', ']]']
const Component = Vue.extend({
template: '[[ a ]] ',
data: function () {
return {
a: 2
}
}
})
const vm = new Vue({
data: {
b: 1
},
template: '[[ b ]] -
',
components: {
'test-component': Component
}
}).$mount()
expect(vm.$el.textContent).toEqual('1 - 2')
// restore default options
delete Vue.options.delimiters
})
it('component specific delimiters should override global delimiters', () => {
Vue.options.delimiters = ['[[', ']]']
const Component = Vue.extend({
delimiters: ['@{{', '}}'],
template: '@{{ a }} ',
data: function () {
return {
a: 2
}
}
})
const vm = new Vue({
data: {
b: 1
},
template: '[[ b ]] -
',
components: {
'test-component': Component
}
}).$mount()
expect(vm.$el.textContent).toEqual('1 - 2')
// restore default options
delete Vue.options.delimiters
})
})
node-vue-template-compiler-2.4.2+dfsg/test/unit/features/options/directives.spec.js000066400000000000000000000157701361753775300305330ustar00rootroot00000000000000import Vue from 'vue'
describe('Options directives', () => {
it('basic usage', done => {
const bindSpy = jasmine.createSpy('bind')
const insertedSpy = jasmine.createSpy('inserted')
const updateSpy = jasmine.createSpy('update')
const componentUpdatedSpy = jasmine.createSpy('componentUpdated')
const unbindSpy = jasmine.createSpy('unbind')
const assertContext = (el, binding, vnode) => {
expect(vnode.context).toBe(vm)
expect(binding.arg).toBe('arg')
expect(binding.modifiers).toEqual({ hello: true })
}
const vm = new Vue({
template: '',
data: {
msg: 'hi',
a: 'foo',
ok: true
},
directives: {
test: {
bind (el, binding, vnode) {
bindSpy()
assertContext(el, binding, vnode)
expect(binding.value).toBe('foo')
expect(binding.expression).toBe('a')
expect(binding.oldValue).toBeUndefined()
expect(el.parentNode).toBeNull()
},
inserted (el, binding, vnode) {
insertedSpy()
assertContext(el, binding, vnode)
expect(binding.value).toBe('foo')
expect(binding.expression).toBe('a')
expect(binding.oldValue).toBeUndefined()
expect(el.parentNode.className).toBe('hi')
},
update (el, binding, vnode, oldVnode) {
updateSpy()
assertContext(el, binding, vnode)
expect(el).toBe(vm.$el.children[0])
expect(oldVnode).not.toBe(vnode)
expect(binding.expression).toBe('a')
if (binding.value !== binding.oldValue) {
expect(binding.value).toBe('bar')
expect(binding.oldValue).toBe('foo')
}
},
componentUpdated (el, binding, vnode) {
componentUpdatedSpy()
assertContext(el, binding, vnode)
},
unbind (el, binding, vnode) {
unbindSpy()
assertContext(el, binding, vnode)
}
}
}
})
vm.$mount()
expect(bindSpy).toHaveBeenCalled()
expect(insertedSpy).toHaveBeenCalled()
expect(updateSpy).not.toHaveBeenCalled()
expect(componentUpdatedSpy).not.toHaveBeenCalled()
expect(unbindSpy).not.toHaveBeenCalled()
vm.a = 'bar'
waitForUpdate(() => {
expect(updateSpy).toHaveBeenCalled()
expect(componentUpdatedSpy).toHaveBeenCalled()
expect(unbindSpy).not.toHaveBeenCalled()
vm.msg = 'bye'
}).then(() => {
expect(componentUpdatedSpy.calls.count()).toBe(2)
vm.ok = false
}).then(() => {
expect(unbindSpy).toHaveBeenCalled()
}).then(done)
})
it('function shorthand', done => {
const spy = jasmine.createSpy('directive')
const vm = new Vue({
template: '
',
data: { a: 'foo' },
directives: {
test (el, binding, vnode) {
expect(vnode.context).toBe(vm)
expect(binding.arg).toBe('arg')
expect(binding.modifiers).toEqual({ hello: true })
spy(binding.value, binding.oldValue)
}
}
})
vm.$mount()
expect(spy).toHaveBeenCalledWith('foo', undefined)
vm.a = 'bar'
waitForUpdate(() => {
expect(spy).toHaveBeenCalledWith('bar', 'foo')
}).then(done)
})
it('function shorthand (global)', done => {
const spy = jasmine.createSpy('directive')
Vue.directive('test', function (el, binding, vnode) {
expect(vnode.context).toBe(vm)
expect(binding.arg).toBe('arg')
expect(binding.modifiers).toEqual({ hello: true })
spy(binding.value, binding.oldValue)
})
const vm = new Vue({
template: '
',
data: { a: 'foo' }
})
vm.$mount()
expect(spy).toHaveBeenCalledWith('foo', undefined)
vm.a = 'bar'
waitForUpdate(() => {
expect(spy).toHaveBeenCalledWith('bar', 'foo')
delete Vue.options.directives.test
}).then(done)
})
it('should teardown directives on old vnodes when new vnodes have none', done => {
const vm = new Vue({
data: {
ok: true
},
template: `
`,
directives: {
test: {
bind: el => { el.id = 'a' },
unbind: el => { el.id = '' }
}
}
}).$mount()
expect(vm.$el.children[0].id).toBe('a')
vm.ok = false
waitForUpdate(() => {
expect(vm.$el.children[0].id).toBe('')
expect(vm.$el.children[0].className).toBe('b')
}).then(done)
})
it('should properly handle same node with different directive sets', done => {
const spies = {}
const createSpy = name => (spies[name] = jasmine.createSpy(name))
const vm = new Vue({
data: {
ok: true,
val: 123
},
template: `
`,
directives: {
test: {
bind: createSpy('bind1'),
inserted: createSpy('inserted1'),
update: createSpy('update1'),
componentUpdated: createSpy('componentUpdated1'),
unbind: createSpy('unbind1')
},
test2: {
bind: createSpy('bind2'),
inserted: createSpy('inserted2'),
update: createSpy('update2'),
componentUpdated: createSpy('componentUpdated2'),
unbind: createSpy('unbind2')
}
}
}).$mount()
expect(spies.bind1.calls.count()).toBe(2)
expect(spies.inserted1.calls.count()).toBe(2)
expect(spies.bind2.calls.count()).toBe(0)
expect(spies.inserted2.calls.count()).toBe(0)
vm.ok = false
waitForUpdate(() => {
// v-test with modifier should be updated
expect(spies.update1.calls.count()).toBe(1)
expect(spies.componentUpdated1.calls.count()).toBe(1)
// v-test without modifier should be unbound
expect(spies.unbind1.calls.count()).toBe(1)
// v-test2 should be bound
expect(spies.bind2.calls.count()).toBe(1)
expect(spies.inserted2.calls.count()).toBe(1)
vm.ok = true
}).then(() => {
// v-test without modifier should be bound again
expect(spies.bind1.calls.count()).toBe(3)
expect(spies.inserted1.calls.count()).toBe(3)
// v-test2 should be unbound
expect(spies.unbind2.calls.count()).toBe(1)
// v-test with modifier should be updated again
expect(spies.update1.calls.count()).toBe(2)
expect(spies.componentUpdated1.calls.count()).toBe(2)
vm.val = 234
}).then(() => {
expect(spies.update1.calls.count()).toBe(4)
expect(spies.componentUpdated1.calls.count()).toBe(4)
}).then(done)
})
it('warn non-existent', () => {
new Vue({
template: '
'
}).$mount()
expect('Failed to resolve directive: test').toHaveBeenWarned()
})
})
node-vue-template-compiler-2.4.2+dfsg/test/unit/features/options/el.spec.js000066400000000000000000000060741361753775300267670ustar00rootroot00000000000000import Vue from 'vue'
describe('Options el', () => {
it('basic usage', () => {
const el = document.createElement('div')
el.innerHTML = '{{message}} '
const vm = new Vue({
el,
data: { message: 'hello world' }
})
expect(vm.$el.tagName).toBe('DIV')
expect(vm.$el.textContent).toBe(vm.message)
})
it('should be replaced when use together with `template` option', () => {
const el = document.createElement('div')
el.innerHTML = '{{message}} '
const vm = new Vue({
el,
template: '{{message}}
',
data: { message: 'hello world' }
})
expect(vm.$el.tagName).toBe('P')
expect(vm.$el.textContent).toBe(vm.message)
})
it('should be replaced when use together with `render` option', () => {
const el = document.createElement('div')
el.innerHTML = '{{message}} '
const vm = new Vue({
el,
render (h) {
return h('p', { staticAttrs: { id: 'app' }}, [
h('span', {}, [this.message])
])
},
data: { message: 'hello world' }
})
expect(vm.$el.tagName).toBe('P')
expect(vm.$el.textContent).toBe(vm.message)
})
it('svg element', () => {
const parent = document.createElement('div')
parent.innerHTML =
'' +
'{{ text }} ' +
' ' +
' '
const vm = new Vue({
el: parent.childNodes[0],
data: {
x: 64,
y: 128,
color: 'red',
text: 'svg text'
}
})
expect(vm.$el.tagName).toBe('svg')
expect(vm.$el.childNodes[0].getAttribute('x')).toBe(vm.x.toString())
expect(vm.$el.childNodes[0].getAttribute('y')).toBe(vm.y.toString())
expect(vm.$el.childNodes[0].getAttribute('fill')).toBe(vm.color)
expect(vm.$el.childNodes[0].textContent).toBe(vm.text)
// nested, non-explicitly listed SVG elements
expect(vm.$el.childNodes[1].childNodes[0].namespaceURI).toContain('svg')
expect(vm.$el.childNodes[1].childNodes[0].childNodes[0].namespaceURI).toContain('svg')
})
// https://w3c.github.io/DOM-Parsing/#dfn-serializing-an-attribute-value
it('properly decode attribute values when parsing templates from DOM', () => {
const el = document.createElement('div')
el.innerHTML = ' '
const vm = new Vue({ el })
expect(vm.$el.children[0].getAttribute('href')).toBe('/a?foo=bar&baz=qux')
expect(vm.$el.children[0].getAttribute('name')).toBe('')
expect(vm.$el.children[0].getAttribute('single')).toBe('"hi"')
})
it('decode attribute value newlines when parsing templates from DOM in IE', () => {
const el = document.createElement('div')
el.innerHTML = ` `
const vm = new Vue({ el })
expect(vm.$el.children[0].style.color).toBe('red')
})
it('warn cannot find element', () => {
new Vue({ el: '#non-existent' })
expect('Cannot find element: #non-existent').toHaveBeenWarned()
})
})
node-vue-template-compiler-2.4.2+dfsg/test/unit/features/options/extends.spec.js000066400000000000000000000031771361753775300300420ustar00rootroot00000000000000import Vue from 'vue'
describe('Options extends', () => {
it('should work on objects', () => {
const A = {
data () {
return { a: 1 }
}
}
const B = {
extends: A,
data () {
return { b: 2 }
}
}
const vm = new Vue({
extends: B,
data: {
c: 3
}
})
expect(vm.a).toBe(1)
expect(vm.b).toBe(2)
expect(vm.c).toBe(3)
})
it('should work on extended constructors', () => {
const A = Vue.extend({
data () {
return { a: 1 }
}
})
const B = Vue.extend({
extends: A,
data () {
return { b: 2 }
}
})
const vm = new Vue({
extends: B,
data: {
c: 3
}
})
expect(vm.a).toBe(1)
expect(vm.b).toBe(2)
expect(vm.c).toBe(3)
})
it('should work with global mixins + Object.prototype.watch', done => {
let fakeWatch = false
if (!Object.prototype.watch) {
fakeWatch = true
// eslint-disable-next-line no-extend-native
Object.defineProperty(Object.prototype, 'watch', {
writable: true,
configurable: true,
enumerable: false,
value: () => {}
})
}
Vue.mixin({})
const spy = jasmine.createSpy('watch')
const A = Vue.extend({
data: function () {
return { a: 1 }
},
watch: {
a: spy
},
created: function () {
this.a = 2
}
})
new Vue({
extends: A
})
waitForUpdate(() => {
expect(spy).toHaveBeenCalledWith(2, 1)
if (fakeWatch) {
delete Object.prototype.watch
}
}).then(done)
})
})
node-vue-template-compiler-2.4.2+dfsg/test/unit/features/options/functional.spec.js000066400000000000000000000117471361753775300305340ustar00rootroot00000000000000import Vue from 'vue'
import { createEmptyVNode } from 'core/vdom/vnode'
describe('Options functional', () => {
it('should work', done => {
const vm = new Vue({
data: { test: 'foo' },
template: 'bar
',
components: {
wrap: {
functional: true,
props: ['msg'],
render (h, { props, children }) {
return h('div', null, [props.msg, ' '].concat(children))
}
}
}
}).$mount()
expect(vm.$el.innerHTML).toBe('foo bar
')
vm.test = 'qux'
waitForUpdate(() => {
expect(vm.$el.innerHTML).toBe('qux bar
')
}).then(done)
})
it('should expose all props when not declared', done => {
const fn = {
functional: true,
render (h, { props }) {
return h('div', `${props.msg} ${props.kebabMsg}`)
}
}
const vm = new Vue({
data: { test: 'foo' },
render (h) {
return h('div', [
h(fn, {
props: { msg: this.test },
attrs: { 'kebab-msg': 'bar' }
})
])
}
}).$mount()
expect(vm.$el.innerHTML).toBe('foo bar
')
vm.test = 'qux'
waitForUpdate(() => {
expect(vm.$el.innerHTML).toBe('qux bar
')
}).then(done)
})
it('should expose data.on as listeners', () => {
const foo = jasmine.createSpy('foo')
const bar = jasmine.createSpy('bar')
const vm = new Vue({
template: '
',
methods: { foo, bar },
components: {
wrap: {
functional: true,
render (h, { listeners }) {
return h('div', {
on: {
click: [listeners.click, () => listeners.test('bar')]
}
})
}
}
}
}).$mount()
triggerEvent(vm.$el.children[0], 'click')
expect(foo).toHaveBeenCalled()
expect(foo.calls.argsFor(0)[0].type).toBe('click') // should have click event
triggerEvent(vm.$el.children[0], 'mousedown')
expect(bar).toHaveBeenCalledWith('bar')
})
it('should support returning more than one root node', () => {
const vm = new Vue({
template: `
`,
components: {
test: {
functional: true,
render (h) {
return [h('span', 'foo'), h('span', 'bar')]
}
}
}
}).$mount()
expect(vm.$el.innerHTML).toBe('foo bar ')
})
it('should support slots', () => {
const vm = new Vue({
data: { test: 'foo' },
template: '',
components: {
wrap: {
functional: true,
props: ['msg'],
render (h, { slots }) {
slots = slots()
return h('div', null, [slots.b, slots.a])
}
}
}
}).$mount()
expect(vm.$el.innerHTML).toBe('')
})
it('should let vnode raw data pass through', done => {
const onValid = jasmine.createSpy('valid')
const vm = new Vue({
data: { msg: 'hello' },
template: `
`,
components: {
validate: {
functional: true,
props: ['field'],
render (h, { props, children, data: { on }}) {
props.child = children[0]
return h('validate-control', { props, on })
}
},
'validate-control': {
props: ['field', 'child'],
render () {
return this.child
},
mounted () {
this.$el.addEventListener('input', this.onInput)
},
destroyed () {
this.$el.removeEventListener('input', this.onInput)
},
methods: {
onInput (e) {
const value = e.target.value
if (this.validate(value)) {
this.$emit('valid', this)
}
},
// something validation logic here
validate (val) {
return val.length > 0
}
}
}
},
methods: { onValid }
}).$mount()
document.body.appendChild(vm.$el)
const input = vm.$el.querySelector('input')
expect(onValid).not.toHaveBeenCalled()
waitForUpdate(() => {
input.value = 'foo'
triggerEvent(input, 'input')
}).then(() => {
expect(onValid).toHaveBeenCalled()
}).then(() => {
document.body.removeChild(vm.$el)
vm.$destroy()
}).then(done)
})
it('create empty vnode when render return null', () => {
const child = {
functional: true,
render () {
return null
}
}
const vm = new Vue({
components: {
child
}
})
const h = vm.$createElement
const vnode = h('child')
expect(vnode).toEqual(createEmptyVNode())
})
})
node-vue-template-compiler-2.4.2+dfsg/test/unit/features/options/inheritAttrs.spec.js000066400000000000000000000016101361753775300310360ustar00rootroot00000000000000import Vue from 'vue'
describe('Options inheritAttrs', () => {
it('should work', done => {
const vm = new Vue({
template: ``,
data: { foo: 'foo' },
components: {
foo: {
inheritAttrs: false,
template: `foo
`
}
}
}).$mount()
expect(vm.$el.id).toBe('')
vm.foo = 'bar'
waitForUpdate(() => {
expect(vm.$el.id).toBe('')
}).then(done)
})
it('with inner v-bind', done => {
const vm = new Vue({
template: ``,
data: { foo: 'foo' },
components: {
foo: {
inheritAttrs: false,
template: ``
}
}
}).$mount()
expect(vm.$el.children[0].id).toBe('foo')
vm.foo = 'bar'
waitForUpdate(() => {
expect(vm.$el.children[0].id).toBe('bar')
}).then(done)
})
})
node-vue-template-compiler-2.4.2+dfsg/test/unit/features/options/inject.spec.js000066400000000000000000000273011361753775300276370ustar00rootroot00000000000000import Vue from 'vue'
import { Observer } from 'core/observer/index'
import { isNative, isObject, hasOwn } from 'core/util/index'
describe('Options provide/inject', () => {
let injected
const injectedComp = {
inject: ['foo', 'bar'],
render () {},
created () {
injected = [this.foo, this.bar]
}
}
beforeEach(() => {
injected = null
})
it('should work', () => {
new Vue({
template: ``,
provide: {
foo: 1,
bar: false
},
components: {
child: {
template: ``,
components: {
injectedComp
}
}
}
}).$mount()
expect(injected).toEqual([1, false])
})
it('should use closest parent', () => {
new Vue({
template: ``,
provide: {
foo: 1,
bar: null
},
components: {
child: {
provide: {
foo: 3
},
template: ``,
components: {
injectedComp
}
}
}
}).$mount()
expect(injected).toEqual([3, null])
})
it('provide function', () => {
new Vue({
template: ``,
data: {
a: 1,
b: false
},
provide () {
return {
foo: this.a,
bar: this.b
}
},
components: {
child: {
template: ``,
components: {
injectedComp
}
}
}
}).$mount()
expect(injected).toEqual([1, false])
})
it('inject with alias', () => {
const injectAlias = {
inject: {
baz: 'foo',
qux: 'bar'
},
render () {},
created () {
injected = [this.baz, this.qux]
}
}
new Vue({
template: ``,
provide: {
foo: false,
bar: 2
},
components: {
child: {
template: ``,
components: {
injectAlias
}
}
}
}).$mount()
expect(injected).toEqual([false, 2])
})
it('inject before resolving data/props', () => {
const vm = new Vue({
provide: {
foo: 1
}
})
const child = new Vue({
parent: vm,
inject: ['foo'],
data () {
return {
bar: this.foo + 1
}
},
props: {
baz: {
default () {
return this.foo + 2
}
}
}
})
expect(child.foo).toBe(1)
expect(child.bar).toBe(2)
expect(child.baz).toBe(3)
})
// Github issue #5194
it('should work with functional', () => {
new Vue({
template: ``,
provide: {
foo: 1,
bar: false
},
components: {
child: {
functional: true,
inject: ['foo', 'bar'],
render (h, context) {
const { injections } = context
injected = [injections.foo, injections.bar]
}
}
}
}).$mount()
expect(injected).toEqual([1, false])
})
if (typeof Reflect !== 'undefined' && isNative(Reflect.ownKeys)) {
it('with Symbol keys', () => {
const s = Symbol()
const vm = new Vue({
template: ``,
provide: {
[s]: 123
},
components: {
child: {
inject: { s },
template: `{{ s }}
`
}
}
}).$mount()
expect(vm.$el.textContent).toBe('123')
})
}
// Github issue #5223
it('should work with reactive array', done => {
const vm = new Vue({
template: `
`,
data () {
return {
foo: []
}
},
provide () {
return {
foo: this.foo
}
},
components: {
child: {
inject: ['foo'],
template: `{{foo.length}} `
}
}
}).$mount()
expect(vm.$el.innerHTML).toEqual(`0 `)
vm.foo.push(vm.foo.length)
vm.$nextTick(() => {
expect(vm.$el.innerHTML).toEqual(`1 `)
vm.foo.pop()
vm.$nextTick(() => {
expect(vm.$el.innerHTML).toEqual(`0 `)
done()
})
})
})
it('should extend properly', () => {
const parent = Vue.extend({
template: ``,
inject: ['foo']
})
const child = parent.extend({
template: ``,
inject: ['bar'],
created () {
injected = [this.foo, this.bar]
}
})
new Vue({
template: ``,
provide: {
foo: 1,
bar: false
},
components: {
parent,
child
}
}).$mount()
expect(injected).toEqual([1, false])
})
it('should merge from mixins properly (objects)', () => {
const mixinA = { inject: { foo: 'foo' }}
const mixinB = { inject: { bar: 'bar' }}
const child = {
mixins: [mixinA, mixinB],
template: ``,
created () {
injected = [this.foo, this.bar]
}
}
new Vue({
provide: { foo: 'foo', bar: 'bar', baz: 'baz' },
render (h) {
return h(child)
}
}).$mount()
expect(injected).toEqual(['foo', 'bar'])
})
it('should merge from mixins properly (arrays)', () => {
const mixinA = { inject: ['foo'] }
const mixinB = { inject: ['bar'] }
const child = {
mixins: [mixinA, mixinB],
inject: ['baz'],
template: ``,
created () {
injected = [this.foo, this.bar, this.baz]
}
}
new Vue({
provide: { foo: 'foo', bar: 'bar', baz: 'baz' },
render (h) {
return h(child)
}
}).$mount()
expect(injected).toEqual(['foo', 'bar', 'baz'])
})
it('should merge from mixins properly (mix of objects and arrays)', () => {
const mixinA = { inject: { foo: 'foo' }}
const mixinB = { inject: ['bar'] }
const child = {
mixins: [mixinA, mixinB],
inject: { qux: 'baz' },
template: ``,
created () {
injected = [this.foo, this.bar, this.qux]
}
}
new Vue({
provide: { foo: 'foo', bar: 'bar', baz: 'baz' },
render (h) {
return h(child)
}
}).$mount()
expect(injected).toEqual(['foo', 'bar', 'baz'])
})
it('should warn when injections has been modified', () => {
const key = 'foo'
const vm = new Vue({
provide: {
foo: 1
}
})
const child = new Vue({
parent: vm,
inject: ['foo']
})
expect(child.foo).toBe(1)
child.foo = 2
expect(
`Avoid mutating an injected value directly since the changes will be ` +
`overwritten whenever the provided component re-renders. ` +
`injection being mutated: "${key}"`).toHaveBeenWarned()
})
it('should warn when injections cannot be found', () => {
const vm = new Vue({})
new Vue({
parent: vm,
inject: ['foo', 'bar'],
created () {}
})
expect(`Injection "foo" not found`).toHaveBeenWarned()
expect(`Injection "bar" not found`).toHaveBeenWarned()
})
it('should not warn when injections can be found', () => {
const vm = new Vue({
provide: {
foo: 1,
bar: false,
baz: undefined
}
})
new Vue({
parent: vm,
inject: ['foo', 'bar', 'baz'],
created () {}
})
expect(`Injection "foo" not found`).not.toHaveBeenWarned()
expect(`Injection "bar" not found`).not.toHaveBeenWarned()
expect(`Injection "baz" not found`).not.toHaveBeenWarned()
})
// Github issue #6008
it('should merge provide from mixins (objects)', () => {
const mixinA = { provide: { foo: 'foo' }}
const mixinB = { provide: { bar: 'bar' }}
const child = {
inject: ['foo', 'bar'],
template: ``,
created () {
injected = [this.foo, this.bar]
}
}
new Vue({
mixins: [mixinA, mixinB],
render (h) {
return h(child)
}
}).$mount()
expect(injected).toEqual(['foo', 'bar'])
})
it('should merge provide from mixins (functions)', () => {
const mixinA = { provide: () => ({ foo: 'foo' }) }
const mixinB = { provide: () => ({ bar: 'bar' }) }
const child = {
inject: ['foo', 'bar'],
template: ``,
created () {
injected = [this.foo, this.bar]
}
}
new Vue({
mixins: [mixinA, mixinB],
render (h) {
return h(child)
}
}).$mount()
expect(injected).toEqual(['foo', 'bar'])
})
it('should merge provide from mixins (mix of objects and functions)', () => {
const mixinA = { provide: { foo: 'foo' }}
const mixinB = { provide: () => ({ bar: 'bar' }) }
const mixinC = { provide: { baz: 'baz' }}
const mixinD = { provide: () => ({ bam: 'bam' }) }
const child = {
inject: ['foo', 'bar', 'baz', 'bam'],
template: ``,
created () {
injected = [this.foo, this.bar, this.baz, this.bam]
}
}
new Vue({
mixins: [mixinA, mixinB, mixinC, mixinD],
render (h) {
return h(child)
}
}).$mount()
expect(injected).toEqual(['foo', 'bar', 'baz', 'bam'])
})
it('should merge provide from mixins and override existing keys', () => {
const mixinA = { provide: { foo: 'foo' }}
const mixinB = { provide: { foo: 'bar' }}
const child = {
inject: ['foo'],
template: ``,
created () {
injected = [this.foo]
}
}
new Vue({
mixins: [mixinA, mixinB],
render (h) {
return h(child)
}
}).$mount()
expect(injected).toEqual(['bar'])
})
it('should merge provide when Vue.extend', () => {
const mixinA = { provide: () => ({ foo: 'foo' }) }
const child = {
inject: ['foo', 'bar'],
template: ``,
created () {
injected = [this.foo, this.bar]
}
}
const Ctor = Vue.extend({
mixins: [mixinA],
provide: { bar: 'bar' },
render (h) {
return h(child)
}
})
new Ctor().$mount()
expect(injected).toEqual(['foo', 'bar'])
})
// #5913
it('should keep the reactive with provide', () => {
function isObserver (obj) {
if (isObject(obj)) {
return hasOwn(obj, '__ob__') && obj.__ob__ instanceof Observer
}
return false
}
const vm = new Vue({
template: `
`,
data () {
return {
foo: {},
$foo: {},
foo1: []
}
},
provide () {
return {
foo: this.foo,
$foo: this.$foo,
foo1: this.foo1,
bar: {},
baz: []
}
},
components: {
child: {
inject: ['foo', '$foo', 'foo1', 'bar', 'baz'],
template: ``
}
}
}).$mount()
const child = vm.$refs.child
expect(isObserver(child.foo)).toBe(true)
expect(isObserver(child.$foo)).toBe(false)
expect(isObserver(child.foo1)).toBe(true)
expect(isObserver(child.bar)).toBe(false)
expect(isObserver(child.baz)).toBe(false)
})
// #6175
it('merge provide properly from mixins', () => {
const ProvideFooMixin = {
provide: {
foo: 'foo injected'
}
}
const ProvideBarMixin = {
provide: {
bar: 'bar injected'
}
}
const Child = {
inject: ['foo', 'bar'],
render (h) {
return h('div', [`foo: ${this.foo}, `, `bar: ${this.bar}`])
}
}
const Parent = {
mixins: [ProvideFooMixin, ProvideBarMixin],
render (h) {
return h(Child)
}
}
const vm = new Vue({
render (h) {
return h(Parent)
}
}).$mount()
expect(vm.$el.textContent).toBe(`foo: foo injected, bar: bar injected`)
})
})
node-vue-template-compiler-2.4.2+dfsg/test/unit/features/options/lifecycle.spec.js000066400000000000000000000143161361753775300303240ustar00rootroot00000000000000import Vue from 'vue'
describe('Options lifecycle hooks', () => {
let spy
beforeEach(() => {
spy = jasmine.createSpy('hook')
})
describe('beforeCreate', () => {
it('should allow modifying options', () => {
const vm = new Vue({
data: {
a: 1
},
beforeCreate () {
spy()
expect(this.a).toBeUndefined()
this.$options.computed = {
b () {
return this.a + 1
}
}
}
})
expect(spy).toHaveBeenCalled()
expect(vm.b).toBe(2)
})
})
describe('created', () => {
it('should have completed observation', () => {
new Vue({
data: {
a: 1
},
created () {
expect(this.a).toBe(1)
spy()
}
})
expect(spy).toHaveBeenCalled()
})
})
describe('beforeMount', () => {
it('should not have mounted', () => {
const vm = new Vue({
render () {},
beforeMount () {
spy()
expect(this._isMounted).toBe(false)
expect(this.$el).toBeUndefined() // due to empty mount
expect(this._vnode).toBeNull()
expect(this._watcher).toBeNull()
}
})
expect(spy).not.toHaveBeenCalled()
vm.$mount()
expect(spy).toHaveBeenCalled()
})
})
describe('mounted', () => {
it('should have mounted', () => {
const vm = new Vue({
template: '
',
mounted () {
spy()
expect(this._isMounted).toBe(true)
expect(this.$el.tagName).toBe('DIV')
expect(this._vnode.tag).toBe('div')
}
})
expect(spy).not.toHaveBeenCalled()
vm.$mount()
expect(spy).toHaveBeenCalled()
})
// #3898
it('should call for manually mounted instance with parent', () => {
const parent = new Vue()
expect(spy).not.toHaveBeenCalled()
new Vue({
parent,
template: '
',
mounted () {
spy()
}
}).$mount()
expect(spy).toHaveBeenCalled()
})
it('should mount child parent in correct order', () => {
const calls = []
new Vue({
template: '
',
mounted () {
calls.push('parent')
},
components: {
test: {
template: ' ',
mounted () {
expect(this.$el.parentNode).toBeTruthy()
calls.push('child')
},
components: {
nested: {
template: '
',
mounted () {
expect(this.$el.parentNode).toBeTruthy()
calls.push('nested')
}
}
}
}
}
}).$mount()
expect(calls).toEqual(['nested', 'child', 'parent'])
})
})
describe('beforeUpdate', () => {
it('should be called before update', done => {
const vm = new Vue({
template: '{{ msg }}
',
data: { msg: 'foo' },
beforeUpdate () {
spy()
expect(this.$el.textContent).toBe('foo')
}
}).$mount()
expect(spy).not.toHaveBeenCalled()
vm.msg = 'bar'
expect(spy).not.toHaveBeenCalled() // should be async
waitForUpdate(() => {
expect(spy).toHaveBeenCalled()
}).then(done)
})
})
describe('updated', () => {
it('should be called after update', done => {
const vm = new Vue({
template: '{{ msg }}
',
data: { msg: 'foo' },
updated () {
spy()
expect(this.$el.textContent).toBe('bar')
}
}).$mount()
expect(spy).not.toHaveBeenCalled()
vm.msg = 'bar'
expect(spy).not.toHaveBeenCalled() // should be async
waitForUpdate(() => {
expect(spy).toHaveBeenCalled()
}).then(done)
})
it('should be called after children are updated', done => {
const calls = []
const vm = new Vue({
template: '{{ msg }}
',
data: { msg: 'foo' },
components: {
test: {
template: `
`,
updated () {
expect(this.$el.textContent).toBe('bar')
calls.push('child')
}
}
},
updated () {
expect(this.$el.textContent).toBe('bar')
calls.push('parent')
}
}).$mount()
expect(calls).toEqual([])
vm.msg = 'bar'
expect(calls).toEqual([])
waitForUpdate(() => {
expect(calls).toEqual(['child', 'parent'])
}).then(done)
})
})
describe('beforeDestroy', () => {
it('should be called before destroy', () => {
const vm = new Vue({
render () {},
beforeDestroy () {
spy()
expect(this._isBeingDestroyed).toBe(false)
expect(this._isDestroyed).toBe(false)
}
}).$mount()
expect(spy).not.toHaveBeenCalled()
vm.$destroy()
vm.$destroy()
expect(spy).toHaveBeenCalled()
expect(spy.calls.count()).toBe(1)
})
})
describe('destroyed', () => {
it('should be called after destroy', () => {
const vm = new Vue({
render () {},
destroyed () {
spy()
expect(this._isBeingDestroyed).toBe(true)
expect(this._isDestroyed).toBe(true)
}
}).$mount()
expect(spy).not.toHaveBeenCalled()
vm.$destroy()
vm.$destroy()
expect(spy).toHaveBeenCalled()
expect(spy.calls.count()).toBe(1)
})
})
it('should emit hook events', () => {
const created = jasmine.createSpy()
const mounted = jasmine.createSpy()
const destroyed = jasmine.createSpy()
const vm = new Vue({
render () {},
beforeCreate () {
this.$on('hook:created', created)
this.$on('hook:mounted', mounted)
this.$on('hook:destroyed', destroyed)
}
})
expect(created).toHaveBeenCalled()
expect(mounted).not.toHaveBeenCalled()
expect(destroyed).not.toHaveBeenCalled()
vm.$mount()
expect(mounted).toHaveBeenCalled()
expect(destroyed).not.toHaveBeenCalled()
vm.$destroy()
expect(destroyed).toHaveBeenCalled()
})
})
node-vue-template-compiler-2.4.2+dfsg/test/unit/features/options/methods.spec.js000066400000000000000000000015421361753775300300250ustar00rootroot00000000000000import Vue from 'vue'
import testObjectOption from '../../../helpers/test-object-option'
describe('Options methods', () => {
it('should have correct context', () => {
const vm = new Vue({
data: {
a: 1
},
methods: {
plus () {
this.a++
}
}
})
vm.plus()
expect(vm.a).toBe(2)
})
testObjectOption('methods')
it('should warn undefined methods', () => {
new Vue({
methods: {
hello: undefined
}
})
expect(`method "hello" has an undefined value in the component definition`).toHaveBeenWarned()
})
it('should warn methods conflicting with data', () => {
new Vue({
data: {
foo: 1
},
methods: {
foo () {}
}
})
expect(`method "foo" has already been defined as a data property`).toHaveBeenWarned()
})
})
node-vue-template-compiler-2.4.2+dfsg/test/unit/features/options/mixins.spec.js000066400000000000000000000043561361753775300276770ustar00rootroot00000000000000import Vue from 'vue'
import { mergeOptions } from 'core/util/index'
describe('Options mixins', () => {
it('vm should have options from mixin', () => {
const mixin = {
directives: {
c: {}
},
methods: {
a: function () {}
}
}
const vm = new Vue({
mixins: [mixin],
methods: {
b: function () {}
}
})
expect(vm.a).toBeDefined()
expect(vm.b).toBeDefined()
expect(vm.$options.directives.c).toBeDefined()
})
it('should call hooks from mixins first', () => {
const a = {}
const b = {}
const c = {}
const f1 = function () {}
const f2 = function () {}
const f3 = function () {}
const mixinA = {
a: 1,
template: 'foo',
directives: {
a: a
},
created: f1
}
const mixinB = {
b: 1,
directives: {
b: b
},
created: f2
}
const result = mergeOptions({}, {
directives: {
c: c
},
template: 'bar',
mixins: [mixinA, mixinB],
created: f3
})
expect(result.a).toBe(1)
expect(result.b).toBe(1)
expect(result.directives.a).toBe(a)
expect(result.directives.b).toBe(b)
expect(result.directives.c).toBe(c)
expect(result.created[0]).toBe(f1)
expect(result.created[1]).toBe(f2)
expect(result.created[2]).toBe(f3)
expect(result.template).toBe('bar')
})
it('mixin methods should not override defined method', () => {
const f1 = function () {}
const f2 = function () {}
const f3 = function () {}
const mixinA = {
methods: {
xyz: f1
}
}
const mixinB = {
methods: {
xyz: f2
}
}
const result = mergeOptions({}, {
mixins: [mixinA, mixinB],
methods: {
xyz: f3
}
})
expect(result.methods.xyz).toBe(f3)
})
it('should accept constructors as mixins', () => {
const mixin = Vue.extend({
directives: {
c: {}
},
methods: {
a: function () {}
}
})
const vm = new Vue({
mixins: [mixin],
methods: {
b: function () {}
}
})
expect(vm.a).toBeDefined()
expect(vm.b).toBeDefined()
expect(vm.$options.directives.c).toBeDefined()
})
})
node-vue-template-compiler-2.4.2+dfsg/test/unit/features/options/name.spec.js000066400000000000000000000022661361753775300273060ustar00rootroot00000000000000import Vue from 'vue'
describe('Options name', () => {
it('should contain itself in self components', () => {
const vm = Vue.extend({
name: 'SuperVue'
})
expect(vm.options.components['SuperVue']).toEqual(vm)
})
it('should warn when incorrect name given', () => {
Vue.extend({
name: 'Hyper*Vue'
})
/* eslint-disable */
expect(`Invalid component name: "Hyper*Vue". Component names can only contain alphanumeric characters and the hyphen, and must start with a letter.`)
.toHaveBeenWarned()
/* eslint-enable */
Vue.extend({
name: '2Cool2BValid'
})
/* eslint-disable */
expect(`Invalid component name: "2Cool2BValid". Component names can only contain alphanumeric characters and the hyphen, and must start with a letter.`)
.toHaveBeenWarned()
/* eslint-enable */
})
it('id should not override given name when using Vue.component', () => {
const SuperComponent = Vue.component('super-component', {
name: 'SuperVue'
})
expect(SuperComponent.options.components['SuperVue']).toEqual(SuperComponent)
expect(SuperComponent.options.components['super-component']).toEqual(SuperComponent)
})
})
node-vue-template-compiler-2.4.2+dfsg/test/unit/features/options/parent.spec.js000066400000000000000000000014271361753775300276550ustar00rootroot00000000000000import Vue from 'vue'
describe('Options parent', () => {
it('should work', () => {
const parent = new Vue({
render () {}
}).$mount()
const child = new Vue({
parent: parent,
render () {}
}).$mount()
// this option is straight-forward
// it should register 'parent' as a $parent for 'child'
// and push 'child' to $children array on 'parent'
expect(child.$options.parent).toBeDefined()
expect(child.$options.parent).toEqual(parent)
expect(child.$parent).toBeDefined()
expect(child.$parent).toEqual(parent)
expect(parent.$children).toContain(child)
// destroy 'child' and check if it was removed from 'parent' $children
child.$destroy()
expect(parent.$children.length).toEqual(0)
parent.$destroy()
})
})
node-vue-template-compiler-2.4.2+dfsg/test/unit/features/options/props.spec.js000066400000000000000000000310011361753775300275160ustar00rootroot00000000000000import Vue from 'vue'
import { hasSymbol } from 'core/util/env'
describe('Options props', () => {
it('array syntax', done => {
const vm = new Vue({
data: {
b: 'bar'
},
template: ' ',
components: {
test: {
props: ['b'],
template: '{{b}}
'
}
}
}).$mount()
expect(vm.$el.innerHTML).toBe('bar')
vm.b = 'baz'
waitForUpdate(() => {
expect(vm.$el.innerHTML).toBe('baz')
vm.$refs.child.b = 'qux'
}).then(() => {
expect(vm.$el.innerHTML).toBe('qux')
expect('Avoid mutating a prop directly').toHaveBeenWarned()
}).then(done)
})
it('object syntax', done => {
const vm = new Vue({
data: {
b: 'bar'
},
template: ' ',
components: {
test: {
props: { b: String },
template: '{{b}}
'
}
}
}).$mount()
expect(vm.$el.innerHTML).toBe('bar')
vm.b = 'baz'
waitForUpdate(() => {
expect(vm.$el.innerHTML).toBe('baz')
vm.$refs.child.b = 'qux'
}).then(() => {
expect(vm.$el.innerHTML).toBe('qux')
expect('Avoid mutating a prop directly').toHaveBeenWarned()
}).then(done)
})
it('warn mixed syntax', () => {
new Vue({
props: [{ b: String }]
})
expect('props must be strings when using array syntax').toHaveBeenWarned()
})
it('default values', () => {
const vm = new Vue({
data: {
b: undefined
},
template: ' ',
components: {
test: {
props: {
a: {
default: 'A' // absent
},
b: {
default: 'B' // undefined
}
},
template: '{{a}}{{b}}
'
}
}
}).$mount()
expect(vm.$el.textContent).toBe('AB')
})
it('default value reactivity', done => {
const vm = new Vue({
props: {
a: {
default: () => ({ b: 1 })
}
},
propsData: {
a: undefined
},
template: '{{ a.b }}
'
}).$mount()
expect(vm.$el.textContent).toBe('1')
vm.a.b = 2
waitForUpdate(() => {
expect(vm.$el.textContent).toBe('2')
}).then(done)
})
it('default value Function', () => {
const func = () => 132
const vm = new Vue({
props: {
a: {
type: Function,
default: func
}
},
propsData: {
a: undefined
}
})
expect(vm.a).toBe(func)
})
it('warn object/array default values', () => {
new Vue({
props: {
a: {
default: { b: 1 }
}
},
propsData: {
a: undefined
}
})
expect('Props with type Object/Array must use a factory function').toHaveBeenWarned()
})
it('warn missing required', () => {
new Vue({
template: ' ',
components: {
test: {
props: { a: { required: true }},
template: '{{a}}
'
}
}
}).$mount()
expect('Missing required prop: "a"').toHaveBeenWarned()
})
describe('assertions', () => {
function makeInstance (value, type, validator, required) {
return new Vue({
template: ' ',
data: {
val: value
},
components: {
test: {
template: '
',
props: {
test: {
type,
validator,
required
}
}
}
}
}).$mount()
}
it('string', () => {
makeInstance('hello', String)
expect(console.error.calls.count()).toBe(0)
makeInstance(123, String)
expect('Expected String').toHaveBeenWarned()
})
it('number', () => {
makeInstance(123, Number)
expect(console.error.calls.count()).toBe(0)
makeInstance('123', Number)
expect('Expected Number').toHaveBeenWarned()
})
it('boolean', () => {
makeInstance(true, Boolean)
expect(console.error.calls.count()).toBe(0)
makeInstance('123', Boolean)
expect('Expected Boolean').toHaveBeenWarned()
})
it('function', () => {
makeInstance(() => {}, Function)
expect(console.error.calls.count()).toBe(0)
makeInstance(123, Function)
expect('Expected Function').toHaveBeenWarned()
})
it('object', () => {
makeInstance({}, Object)
expect(console.error.calls.count()).toBe(0)
makeInstance([], Object)
expect('Expected Object').toHaveBeenWarned()
})
it('array', () => {
makeInstance([], Array)
expect(console.error.calls.count()).toBe(0)
makeInstance({}, Array)
expect('Expected Array').toHaveBeenWarned()
})
if (hasSymbol) {
it('symbol', () => {
makeInstance(Symbol('foo'), Symbol)
expect(console.error.calls.count()).toBe(0)
makeInstance({}, Symbol)
expect('Expected Symbol').toHaveBeenWarned()
})
}
it('custom constructor', () => {
function Class () {}
makeInstance(new Class(), Class)
expect(console.error.calls.count()).toBe(0)
makeInstance({}, Class)
expect('type check failed').toHaveBeenWarned()
})
it('multiple types', () => {
makeInstance([], [Array, Number, Boolean])
expect(console.error.calls.count()).toBe(0)
makeInstance({}, [Array, Number, Boolean])
expect('Expected Array, Number, Boolean, got Object').toHaveBeenWarned()
})
it('custom validator', () => {
makeInstance(123, null, v => v === 123)
expect(console.error.calls.count()).toBe(0)
makeInstance(123, null, v => v === 234)
expect('custom validator check failed').toHaveBeenWarned()
})
it('type check + custom validator', () => {
makeInstance(123, Number, v => v === 123)
expect(console.error.calls.count()).toBe(0)
makeInstance(123, Number, v => v === 234)
expect('custom validator check failed').toHaveBeenWarned()
makeInstance(123, String, v => v === 123)
expect('Expected String').toHaveBeenWarned()
})
it('multiple types + custom validator', () => {
makeInstance(123, [Number, String, Boolean], v => v === 123)
expect(console.error.calls.count()).toBe(0)
makeInstance(123, [Number, String, Boolean], v => v === 234)
expect('custom validator check failed').toHaveBeenWarned()
makeInstance(123, [String, Boolean], v => v === 123)
expect('Expected String, Boolean').toHaveBeenWarned()
})
it('optional with type + null/undefined', () => {
makeInstance(undefined, String)
expect(console.error.calls.count()).toBe(0)
makeInstance(null, String)
expect(console.error.calls.count()).toBe(0)
})
it('required with type + null/undefined', () => {
makeInstance(undefined, String, null, true)
expect(console.error.calls.count()).toBe(1)
expect('Expected String').toHaveBeenWarned()
makeInstance(null, Boolean, null, true)
expect(console.error.calls.count()).toBe(2)
expect('Expected Boolean').toHaveBeenWarned()
})
it('optional prop of any type (type: true or prop: true)', () => {
makeInstance(1, true)
expect(console.error.calls.count()).toBe(0)
makeInstance('any', true)
expect(console.error.calls.count()).toBe(0)
makeInstance({}, true)
expect(console.error.calls.count()).toBe(0)
makeInstance(undefined, true)
expect(console.error.calls.count()).toBe(0)
makeInstance(null, true)
expect(console.error.calls.count()).toBe(0)
})
})
it('should work with v-bind', () => {
const vm = new Vue({
template: ` `,
components: {
test: {
props: ['a', 'b'],
template: '{{ a }} {{ b }}
'
}
}
}).$mount()
expect(vm.$el.textContent).toBe('1 2')
})
it('should warn data fields already defined as a prop', () => {
new Vue({
template: ' ',
components: {
test: {
template: '
',
data: function () {
return { a: 123 }
},
props: {
a: null
}
}
}
}).$mount()
expect('already declared as a prop').toHaveBeenWarned()
})
it('should warn methods already defined as a prop', () => {
new Vue({
template: ' ',
components: {
test: {
template: '
',
props: {
a: null
},
methods: {
a () {
}
}
}
}
}).$mount()
expect(`method "a" has already been defined as a prop`).toHaveBeenWarned()
expect(`Avoid mutating a prop directly`).toHaveBeenWarned()
})
it('treat boolean props properly', () => {
const vm = new Vue({
template: ' ',
components: {
comp: {
template: '
',
props: {
propA: Boolean,
propB: Boolean,
propC: Boolean
}
}
}
}).$mount()
expect(vm.$refs.child.propA).toBe(true)
expect(vm.$refs.child.propB).toBe(true)
expect(vm.$refs.child.propC).toBe(false)
})
it('should respect default value of a Boolean prop', function () {
const vm = new Vue({
template: ' ',
components: {
test: {
props: {
prop: {
type: Boolean,
default: true
}
},
template: '{{prop}}
'
}
}
}).$mount()
expect(vm.$el.textContent).toBe('true')
})
it('non reactive values passed down as prop should not be converted', done => {
const a = Object.freeze({
nested: {
msg: 'hello'
}
})
const parent = new Vue({
template: ' ',
data: {
a: a
},
components: {
comp: {
template: '
',
props: ['a']
}
}
}).$mount()
const child = parent.$children[0]
expect(child.a.msg).toBe('hello')
expect(child.a.__ob__).toBeUndefined() // should not be converted
parent.a = Object.freeze({
nested: {
msg: 'yo'
}
})
waitForUpdate(() => {
expect(child.a.msg).toBe('yo')
expect(child.a.__ob__).toBeUndefined()
}).then(done)
})
it('should not warn for non-required, absent prop', function () {
new Vue({
template: ' ',
components: {
test: {
template: '
',
props: {
prop: {
type: String
}
}
}
}
}).$mount()
expect(console.error.calls.count()).toBe(0)
})
// #3453
it('should not fire watcher on object/array props when parent re-renders', done => {
const spy = jasmine.createSpy()
const vm = new Vue({
data: {
arr: []
},
template: 'hi ',
components: {
test: {
props: ['prop'],
watch: {
prop: spy
},
template: '
'
}
}
}).$mount()
vm.$forceUpdate()
waitForUpdate(() => {
expect(spy).not.toHaveBeenCalled()
}).then(done)
})
// #4090
it('should not trigger watcher on default value', done => {
const spy = jasmine.createSpy()
const vm = new Vue({
template: ` `,
data: {
a: 1,
b: undefined
},
components: {
test: {
template: '{{ value }}
',
props: {
value: { type: Number },
test: {
type: Object,
default: () => ({})
}
},
watch: {
test: spy
}
}
}
}).$mount()
vm.a++
waitForUpdate(() => {
expect(spy).not.toHaveBeenCalled()
vm.b = {}
}).then(() => {
expect(spy.calls.count()).toBe(1)
}).then(() => {
vm.b = undefined
}).then(() => {
expect(spy.calls.count()).toBe(2)
vm.a++
}).then(() => {
expect(spy.calls.count()).toBe(2)
}).then(done)
})
it('warn reserved props', () => {
const specialAttrs = ['key', 'ref', 'slot', 'is']
new Vue({
props: specialAttrs
})
specialAttrs.forEach(attr => {
expect(`"${attr}" is a reserved attribute`).toHaveBeenWarned()
})
})
})
node-vue-template-compiler-2.4.2+dfsg/test/unit/features/options/propsData.spec.js000066400000000000000000000012201361753775300303100ustar00rootroot00000000000000import Vue from 'vue'
describe('Options propsData', () => {
it('should work', done => {
const A = Vue.extend({
props: ['a'],
template: '{{ a }}
'
})
const vm = new A({
propsData: {
a: 123
}
}).$mount()
expect(vm.a).toBe(123)
expect(vm.$el.textContent).toBe('123')
vm.a = 234
waitForUpdate(() => {
expect(vm.$el.textContent).toBe('234')
}).then(done)
})
it('warn non instantiation usage', () => {
Vue.extend({
propsData: {
a: 123
}
})
expect('option "propsData" can only be used during instance creation').toHaveBeenWarned()
})
})
node-vue-template-compiler-2.4.2+dfsg/test/unit/features/options/render.spec.js000066400000000000000000000022141361753775300276360ustar00rootroot00000000000000import Vue from 'vue'
describe('Options render', () => {
it('basic usage', () => {
const vm = new Vue({
render (h) {
const children = []
for (let i = 0; i < this.items.length; i++) {
children.push(h('li', { staticClass: 'task' }, [this.items[i].name]))
}
return h('ul', { staticClass: 'tasks' }, children)
},
data: {
items: [{ id: 1, name: 'task1' }, { id: 2, name: 'task2' }]
}
}).$mount()
expect(vm.$el.tagName).toBe('UL')
for (let i = 0; i < vm.$el.children.length; i++) {
const li = vm.$el.children[i]
expect(li.tagName).toBe('LI')
expect(li.textContent).toBe(vm.items[i].name)
}
})
it('allow null data', () => {
const vm = new Vue({
render (h) {
return h('div', null, 'hello' /* string as children*/)
}
}).$mount()
expect(vm.$el.tagName).toBe('DIV')
expect(vm.$el.textContent).toBe('hello')
})
it('should warn non `render` option and non `template` option', () => {
new Vue().$mount()
expect('Failed to mount component: template or render function not defined.').toHaveBeenWarned()
})
})
node-vue-template-compiler-2.4.2+dfsg/test/unit/features/options/renderError.spec.js000066400000000000000000000012141361753775300306470ustar00rootroot00000000000000import Vue from 'vue'
describe('Options renderError', () => {
it('should be used on render errors', done => {
Vue.config.errorHandler = () => {}
const vm = new Vue({
data: {
ok: true
},
render (h) {
if (this.ok) {
return h('div', 'ok')
} else {
throw new Error('no')
}
},
renderError (h, err) {
return h('div', err.toString())
}
}).$mount()
expect(vm.$el.textContent).toBe('ok')
vm.ok = false
waitForUpdate(() => {
expect(vm.$el.textContent).toBe('Error: no')
Vue.config.errorHandler = null
}).then(done)
})
})
node-vue-template-compiler-2.4.2+dfsg/test/unit/features/options/template.spec.js000066400000000000000000000053461361753775300302030ustar00rootroot00000000000000import Vue from 'vue'
describe('Options template', () => {
let el
beforeEach(() => {
el = document.createElement('script')
el.type = 'x-template'
el.id = 'app'
el.innerHTML = '{{message}}
'
document.body.appendChild(el)
})
afterEach(() => {
document.body.removeChild(el)
})
it('basic usage', () => {
const vm = new Vue({
template: '{{message}}
',
data: { message: 'hello world' }
}).$mount()
expect(vm.$el.tagName).toBe('DIV')
expect(vm.$el.textContent).toBe(vm.message)
})
it('id reference', () => {
const vm = new Vue({
template: '#app',
data: { message: 'hello world' }
}).$mount()
expect(vm.$el.tagName).toBe('P')
expect(vm.$el.textContent).toBe(vm.message)
})
it('DOM element', () => {
const elm = document.createElement('p')
elm.innerHTML = '{{message}}
'
const vm = new Vue({
template: elm,
data: { message: 'hello world' }
}).$mount()
expect(vm.$el.tagName).toBe('P')
expect(vm.$el.textContent).toBe(vm.message)
})
it('invalid template', () => {
new Vue({
template: Vue,
data: { message: 'hello world' }
}).$mount()
expect('invalid template option').toHaveBeenWarned()
})
it('warn error in generated function', () => {
new Vue({
template: '{{ a"" }} {{ do + 1 }}
'
}).$mount()
expect('Error compiling template').toHaveBeenWarned()
expect('invalid expression: v-if="!@"').toHaveBeenWarned()
expect('invalid expression: {{ a"" }}').toHaveBeenWarned()
expect('avoid using JavaScript keyword as property name: "do" in expression {{ do + 1 }}').toHaveBeenWarned()
})
it('should not warn $ prefixed keywords', () => {
new Vue({
template: `
`
}).$mount()
expect('avoid using JavaScript keyword as property name').not.toHaveBeenWarned()
})
it('warn error in generated function (v-for)', () => {
new Vue({
template: ''
}).$mount()
expect('Error compiling template').toHaveBeenWarned()
expect('invalid v-for alias "1"').toHaveBeenWarned()
expect('invalid v-for iterator "2"').toHaveBeenWarned()
expect('invalid expression: v-for="(1, 2) in a----"').toHaveBeenWarned()
})
it('warn error in generated function (v-on)', () => {
new Vue({
template: `
`,
methods: { delete: function () {} }
}).$mount()
expect('Error compiling template').toHaveBeenWarned()
expect(
`avoid using JavaScript unary operator as property name: "delete()" in expression @click="delete('Delete')"`
).toHaveBeenWarned()
})
})
node-vue-template-compiler-2.4.2+dfsg/test/unit/features/options/watch.spec.js000066400000000000000000000054771361753775300275030ustar00rootroot00000000000000import Vue from 'vue'
import testObjectOption from '../../../helpers/test-object-option'
describe('Options watch', () => {
let spy
beforeEach(() => {
spy = jasmine.createSpy('watch')
})
testObjectOption('watch')
it('basic usage', done => {
const vm = new Vue({
data: {
a: 1
},
watch: {
a: spy
}
})
expect(spy).not.toHaveBeenCalled()
vm.a = 2
expect(spy).not.toHaveBeenCalled()
waitForUpdate(() => {
expect(spy).toHaveBeenCalledWith(2, 1)
}).then(done)
})
it('string method name', done => {
const vm = new Vue({
data: {
a: 1
},
watch: {
a: 'onChange'
},
methods: {
onChange: spy
}
})
expect(spy).not.toHaveBeenCalled()
vm.a = 2
expect(spy).not.toHaveBeenCalled()
waitForUpdate(() => {
expect(spy).toHaveBeenCalledWith(2, 1)
}).then(done)
})
it('multiple cbs (after option merge)', done => {
const spy1 = jasmine.createSpy('watch')
const Test = Vue.extend({
watch: {
a: spy1
}
})
const vm = new Test({
data: { a: 1 },
watch: {
a: spy
}
})
vm.a = 2
waitForUpdate(() => {
expect(spy1).toHaveBeenCalledWith(2, 1)
expect(spy).toHaveBeenCalledWith(2, 1)
}).then(done)
})
it('with option: immediate', done => {
const vm = new Vue({
data: { a: 1 },
watch: {
a: {
handler: spy,
immediate: true
}
}
})
expect(spy).toHaveBeenCalledWith(1)
vm.a = 2
waitForUpdate(() => {
expect(spy).toHaveBeenCalledWith(2, 1)
}).then(done)
})
it('with option: deep', done => {
const vm = new Vue({
data: { a: { b: 1 }},
watch: {
a: {
handler: spy,
deep: true
}
}
})
const oldA = vm.a
expect(spy).not.toHaveBeenCalled()
vm.a.b = 2
expect(spy).not.toHaveBeenCalled()
waitForUpdate(() => {
expect(spy).toHaveBeenCalledWith(vm.a, vm.a)
vm.a = { b: 3 }
}).then(() => {
expect(spy).toHaveBeenCalledWith(vm.a, oldA)
}).then(done)
})
it('correctly merges multiple extends', done => {
var spy2 = jasmine.createSpy('A')
var spy3 = jasmine.createSpy('B')
var A = Vue.extend({
data: function () {
return {
a: 0,
b: 0
}
},
watch: {
b: spy
}
})
var B = Vue.extend({
extends: A,
watch: {
a: spy2
}
})
var C = Vue.extend({
extends: B,
watch: {
a: spy3
}
})
var vm = new C()
vm.a = 1
waitForUpdate(() => {
expect(spy).not.toHaveBeenCalled()
expect(spy2).toHaveBeenCalledWith(1, 0)
expect(spy3).toHaveBeenCalledWith(1, 0)
}).then(done)
})
})
node-vue-template-compiler-2.4.2+dfsg/test/unit/features/ref.spec.js000066400000000000000000000122201361753775300254360ustar00rootroot00000000000000import Vue from 'vue'
describe('ref', () => {
const components = {
test: {
id: 'test',
template: 'test
'
},
test2: {
id: 'test2',
template: 'test2
'
}
}
it('should work', () => {
const vm = new Vue({
data: {
value: 'bar'
},
template: `
`,
components
})
vm.$mount()
expect(vm.$refs.foo).toBeTruthy()
expect(vm.$refs.foo.$options.id).toBe('test')
expect(vm.$refs.bar).toBeTruthy()
expect(vm.$refs.bar.$options.id).toBe('test2')
})
it('should dynamically update refs', done => {
const vm = new Vue({
data: {
value: 'foo'
},
template: '
'
}).$mount()
expect(vm.$refs.foo).toBe(vm.$el)
vm.value = 'bar'
waitForUpdate(() => {
expect(vm.$refs.foo).toBeUndefined()
expect(vm.$refs.bar).toBe(vm.$el)
}).then(done)
})
it('should work as a hyperscript prop', () => {
const vm = new Vue({
components,
render (h) {
return h('div', null, [
h('test', { ref: 'test' })
])
}
})
vm.$mount()
expect(vm.$refs.test).toBeTruthy()
expect(vm.$refs.test.$options.id).toBe('test')
})
it('should accept HOC component', () => {
const vm = new Vue({
template: ' ',
components
})
vm.$mount()
expect(vm.$refs.test).toBeTruthy()
expect(vm.$refs.test.$options.id).toBe('test')
})
it('should accept dynamic component', done => {
const vm = new Vue({
template: `
`,
components,
data: { test: 'test' }
})
vm.$mount()
expect(vm.$refs.test.$options.id).toBe('test')
vm.test = 'test2'
waitForUpdate(() => {
expect(vm.$refs.test.$options.id).toBe('test2')
vm.test = ''
}).then(() => {
expect(vm.$refs.test).toBeUndefined()
}).then(done)
})
it('should register as Array when used with v-for', done => {
const vm = new Vue({
data: {
items: [1, 2, 3]
},
template: `
`
}).$mount()
assertRefs()
// updating
vm.items.push(4)
waitForUpdate(assertRefs)
.then(() => { vm.items = [] })
.then(assertRefs)
.then(done)
function assertRefs () {
expect(Array.isArray(vm.$refs.list)).toBe(true)
expect(vm.$refs.list.length).toBe(vm.items.length)
expect(vm.$refs.list.every((item, i) => item.textContent === String(i + 1))).toBe(true)
}
})
it('should register as Array when used with v-for (components)', done => {
const vm = new Vue({
data: {
items: [1, 2, 3]
},
template: `
`,
components: {
test: {
props: ['n'],
template: '{{ n }}
'
}
}
}).$mount()
assertRefs()
// updating
vm.items.push(4)
waitForUpdate(assertRefs)
.then(() => { vm.items = [] })
.then(assertRefs)
.then(done)
function assertRefs () {
expect(Array.isArray(vm.$refs.list)).toBe(true)
expect(vm.$refs.list.length).toBe(vm.items.length)
expect(vm.$refs.list.every((comp, i) => comp.$el.textContent === String(i + 1))).toBe(true)
}
})
it('should work with v-for on dynamic component', done => {
components.test3 = {
id: 'test3',
template: `test3
`,
data () {
return { normal: false }
},
components: { test1: components.test }
}
// a flag that representing whether to test component content or not
let testContent = false
const vm = new Vue({
template: `
`,
data: {
items: ['test2', 'test3']
},
components
}).$mount()
assertRefs()
expect(vm.$refs.children[0].$el.textContent).toBe('test2')
expect(vm.$refs.children[1].$el.textContent).toBe('test')
// updating
vm.$refs.children[1].normal = true
testContent = true
waitForUpdate(assertRefs)
.then(() => { vm.items.push('test') })
.then(assertRefs)
.then(done)
function assertRefs () {
expect(Array.isArray(vm.$refs.children)).toBe(true)
expect(vm.$refs.children.length).toBe(vm.items.length)
if (testContent) {
expect(
vm.$refs.children.every((comp, i) => comp.$el.textContent === vm.items[i])
).toBe(true)
}
}
})
it('should register on component with empty roots', () => {
const vm = new Vue({
template: ' ',
components: {
child: {
template: '
'
}
}
}).$mount()
expect(vm.$refs.test).toBe(vm.$children[0])
})
})
node-vue-template-compiler-2.4.2+dfsg/test/unit/features/transition/000077500000000000000000000000001361753775300255705ustar00rootroot00000000000000node-vue-template-compiler-2.4.2+dfsg/test/unit/features/transition/inject-styles.js000066400000000000000000000033211361753775300307220ustar00rootroot00000000000000function insertCSS (text) {
var cssEl = document.createElement('style')
cssEl.textContent = text.trim()
document.head.appendChild(cssEl)
}
const duration = process.env.TRANSITION_DURATION || 50
const buffer = process.env.TRANSITION_BUFFER || 10
let injected = false
export default function injectStyles () {
if (injected) return { duration, buffer }
injected = true
insertCSS(`
.test {
-webkit-transition: opacity ${duration}ms ease;
transition: opacity ${duration}ms ease;
}
.group-move {
-webkit-transition: -webkit-transform ${duration}ms ease;
transition: transform ${duration}ms ease;
}
.v-appear, .v-enter, .v-leave-active,
.test-appear, .test-enter, .test-leave-active,
.hello, .bye.active,
.changed-enter {
opacity: 0;
}
.test-anim-enter-active {
animation: test-enter ${duration}ms;
-webkit-animation: test-enter ${duration}ms;
}
.test-anim-leave-active {
animation: test-leave ${duration}ms;
-webkit-animation: test-leave ${duration}ms;
}
.test-anim-long-enter-active {
animation: test-enter ${duration * 2}ms;
-webkit-animation: test-enter ${duration * 2}ms;
}
.test-anim-long-leave-active {
animation: test-leave ${duration * 2}ms;
-webkit-animation: test-leave ${duration * 2}ms;
}
@keyframes test-enter {
from { opacity: 0 }
to { opacity: 1 }
}
@-webkit-keyframes test-enter {
from { opacity: 0 }
to { opacity: 1 }
}
@keyframes test-leave {
from { opacity: 1 }
to { opacity: 0 }
}
@-webkit-keyframes test-leave {
from { opacity: 1 }
to { opacity: 0 }
}
`)
return { duration, buffer }
}
node-vue-template-compiler-2.4.2+dfsg/test/unit/features/transition/transition-group.spec.js000066400000000000000000000256671361753775300324230ustar00rootroot00000000000000import Vue from 'vue'
import injectStyles from './inject-styles'
import { isIE9 } from 'core/util/env'
import { nextFrame } from 'web/runtime/transition-util'
if (!isIE9) {
describe('Transition group', () => {
const { duration, buffer } = injectStyles()
let el
beforeEach(() => {
el = document.createElement('div')
document.body.appendChild(el)
})
function createBasicVM (useIs, appear) {
const vm = new Vue({
template: `
${useIs ? `
` : ``}
{{ item }}
${useIs ? ` ` : ``}
`,
data: {
items: ['a', 'b', 'c']
}
}).$mount(el)
if (!appear) {
expect(vm.$el.innerHTML).toBe(
`` +
vm.items.map(i => `${i}
`).join('') +
` `
)
}
return vm
}
it('enter', done => {
const vm = createBasicVM()
vm.items.push('d', 'e')
waitForUpdate(() => {
expect(vm.$el.innerHTML).toBe(
`` +
['a', 'b', 'c'].map(i => `${i}
`).join('') +
`d
` +
`e
` +
` `
)
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.innerHTML).toBe(
`` +
['a', 'b', 'c'].map(i => `${i}
`).join('') +
`d
` +
`e
` +
` `
)
}).thenWaitFor(duration + buffer).then(() => {
expect(vm.$el.innerHTML).toBe(
`` +
vm.items.map(i => `${i}
`).join('') +
` `
)
}).then(done)
})
it('leave', done => {
const vm = createBasicVM()
vm.items = ['b']
waitForUpdate(() => {
expect(vm.$el.innerHTML).toBe(
`` +
`a
` +
`b
` +
`c
` +
` `
)
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.innerHTML).toBe(
`` +
`a
` +
`b
` +
`c
` +
` `
)
}).thenWaitFor(duration + buffer).then(() => {
expect(vm.$el.innerHTML).toBe(
`` +
vm.items.map(i => `${i}
`).join('') +
` `
)
}).then(done)
})
it('enter + leave', done => {
const vm = createBasicVM()
vm.items = ['b', 'c', 'd']
waitForUpdate(() => {
expect(vm.$el.innerHTML).toBe(
`` +
`a
` +
`b
` +
`c
` +
`d
` +
` `
)
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.innerHTML).toBe(
`` +
`a
` +
`b
` +
`c
` +
`d
` +
` `
)
}).thenWaitFor(duration + buffer).then(() => {
expect(vm.$el.innerHTML).toBe(
`` +
vm.items.map(i => `${i}
`).join('') +
` `
)
}).then(done)
})
it('use with "is" attribute', done => {
const vm = createBasicVM(true)
vm.items = ['b', 'c', 'd']
waitForUpdate(() => {
expect(vm.$el.innerHTML).toBe(
`` +
`a
` +
`b
` +
`c
` +
`d
` +
` `
)
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.innerHTML).toBe(
`` +
`a
` +
`b
` +
`c
` +
`d
` +
` `
)
}).thenWaitFor(duration + buffer).then(() => {
expect(vm.$el.innerHTML).toBe(
`` +
vm.items.map(i => `${i}
`).join('') +
` `
)
}).then(done)
})
it('appear', done => {
const vm = createBasicVM(false, true /* appear */)
waitForUpdate(() => {
expect(vm.$el.innerHTML).toBe(
`` +
vm.items.map(i => `${i}
`).join('') +
` `
)
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.innerHTML).toBe(
`` +
vm.items.map(i => `${i}
`).join('') +
` `
)
}).thenWaitFor(duration + buffer).then(() => {
expect(vm.$el.innerHTML).toBe(
`` +
vm.items.map(i => `${i}
`).join('') +
` `
)
}).then(done)
})
it('events', done => {
let next
const beforeEnterSpy = jasmine.createSpy()
const afterEnterSpy = jasmine.createSpy()
const afterLeaveSpy = jasmine.createSpy()
const vm = new Vue({
template: `
`,
data: {
items: ['a', 'b', 'c']
},
methods: {
beforeEnter (el) {
expect(el.textContent).toBe('d')
beforeEnterSpy()
},
afterEnter (el) {
expect(el.textContent).toBe('d')
afterEnterSpy()
next()
},
afterLeave (el) {
expect(el.textContent).toBe('a')
afterLeaveSpy()
next()
}
}
}).$mount(el)
vm.items.push('d')
waitForUpdate(() => {
expect(vm.$el.innerHTML).toBe(
`` +
`a
` +
`b
` +
`c
` +
`d
` +
` `
)
expect(beforeEnterSpy.calls.count()).toBe(1)
}).thenWaitFor(_next => { next = _next }).then(() => {
expect(vm.$el.innerHTML).toBe(
`` +
`a
` +
`b
` +
`c
` +
`d
` +
` `
)
expect(afterEnterSpy.calls.count()).toBe(1)
vm.items.shift()
}).thenWaitFor(_next => { next = _next }).then(() => {
expect(vm.$el.innerHTML).toBe(
`` +
`b
` +
`c
` +
`d
` +
` `
)
expect(afterLeaveSpy.calls.count()).toBe(1)
}).then(done)
})
it('move', done => {
const vm = new Vue({
template: `
`,
data: {
items: ['a', 'b', 'c']
}
}).$mount(el)
vm.items = ['d', 'b', 'a']
waitForUpdate(() => {
expect(vm.$el.innerHTML.replace(/\s?style=""(\s?)/g, '$1')).toBe(
`` +
`d
` +
`b
` +
`a
` +
`c
` +
` `
)
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.innerHTML.replace(/\s?style=""(\s?)/g, '$1')).toBe(
`` +
`d
` +
`b
` +
`a
` +
`c
` +
` `
)
}).thenWaitFor(duration * 2).then(() => {
expect(vm.$el.innerHTML.replace(/\s?style=""(\s?)/g, '$1')).toBe(
`` +
`d
` +
`b
` +
`a
` +
` `
)
}).then(done)
})
it('warn unkeyed children', () => {
new Vue({
template: ``
}).$mount()
expect(' children must be keyed: ').toHaveBeenWarned()
})
// Github issue #6006
it('should work with dynamic name', done => {
const vm = new Vue({
template: `
`,
data: {
items: ['a', 'b', 'c'],
name: 'group'
}
}).$mount(el)
vm.name = 'invalid-name'
vm.items = ['b', 'c', 'a']
waitForUpdate(() => {
expect(vm.$el.innerHTML.replace(/\s?style=""(\s?)/g, '$1')).toBe(
`
` +
`b
` +
`c
` +
`a
` +
` `
)
vm.name = 'group'
vm.items = ['a', 'b', 'c']
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.innerHTML.replace(/\s?style=""(\s?)/g, '$1')).toBe(
`
` +
`a
` +
`b
` +
`c
` +
` `
)
}).thenWaitFor(duration * 2 + buffer).then(() => {
expect(vm.$el.innerHTML.replace(/\s?style=""(\s?)/g, '$1')).toBe(
`
` +
`a
` +
`b
` +
`c
` +
` `
)
}).then(done)
})
})
}
node-vue-template-compiler-2.4.2+dfsg/test/unit/features/transition/transition-mode.spec.js000066400000000000000000000464631361753775300322100ustar00rootroot00000000000000import Vue from 'vue'
import injectStyles from './inject-styles'
import { isIE9 } from 'core/util/env'
import { nextFrame } from 'web/runtime/transition-util'
if (!isIE9) {
describe('Transition mode', () => {
const { duration, buffer } = injectStyles()
const components = {
one: { template: '
one
' },
two: { template: '
two
' }
}
let el
beforeEach(() => {
el = document.createElement('div')
document.body.appendChild(el)
})
it('dynamic components, simultaneous', done => {
const vm = new Vue({
template: `
`,
data: { view: 'one' },
components
}).$mount(el)
expect(vm.$el.textContent).toBe('one')
vm.view = 'two'
waitForUpdate(() => {
expect(vm.$el.innerHTML).toBe(
'
one
' +
'
two
'
)
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.innerHTML).toBe(
'
one
' +
'
two
'
)
}).thenWaitFor(duration + buffer).then(() => {
expect(vm.$el.innerHTML).toBe(
'
two
'
)
}).then(done)
})
it('dynamic components, out-in', done => {
let next
const vm = new Vue({
template: `
`,
data: { view: 'one' },
components,
methods: {
afterLeave () {
next()
}
}
}).$mount(el)
expect(vm.$el.textContent).toBe('one')
vm.view = 'two'
waitForUpdate(() => {
expect(vm.$el.innerHTML).toBe(
'
one
'
)
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.innerHTML).toBe(
'
one
'
)
}).thenWaitFor(_next => { next = _next }).then(() => {
expect(vm.$el.innerHTML).toBe('')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.innerHTML).toBe(
'
two
'
)
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.innerHTML).toBe(
'
two
'
)
}).thenWaitFor(duration + buffer).then(() => {
expect(vm.$el.innerHTML).toBe(
'
two
'
)
}).then(done)
})
// #3440
it('dynamic components, out-in (with extra re-render)', done => {
let next
const vm = new Vue({
template: `
`,
data: { view: 'one' },
components,
methods: {
afterLeave () {
next()
}
}
}).$mount(el)
expect(vm.$el.textContent).toBe('one')
vm.view = 'two'
waitForUpdate(() => {
expect(vm.$el.innerHTML).toBe(
'
one
'
)
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.innerHTML).toBe(
'
one
'
)
// Force re-render before the element finishes leaving
// this should not cause the incoming element to enter early
vm.$forceUpdate()
}).thenWaitFor(_next => { next = _next }).then(() => {
expect(vm.$el.innerHTML).toBe('')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.innerHTML).toBe(
'
two
'
)
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.innerHTML).toBe(
'
two
'
)
}).thenWaitFor(duration + buffer).then(() => {
expect(vm.$el.innerHTML).toBe(
'
two
'
)
}).then(done)
})
it('dynamic components, in-out', done => {
let next
const vm = new Vue({
template: `
`,
data: { view: 'one' },
components,
methods: {
afterEnter () {
next()
}
}
}).$mount(el)
expect(vm.$el.textContent).toBe('one')
vm.view = 'two'
waitForUpdate(() => {
expect(vm.$el.innerHTML).toBe(
'
one
' +
'
two
'
)
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.innerHTML).toBe(
'
one
' +
'
two
'
)
}).thenWaitFor(_next => { next = _next }).then(() => {
expect(vm.$el.innerHTML).toBe(
'
one
' +
'
two
'
)
}).then(() => {
expect(vm.$el.innerHTML).toBe(
'
one
' +
'
two
'
)
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.innerHTML).toBe(
'
one
' +
'
two
'
)
}).thenWaitFor(duration + buffer).then(() => {
expect(vm.$el.innerHTML).toBe(
'
two
'
)
}).then(done)
})
it('dynamic components, in-out with early cancel', done => {
let next
const vm = new Vue({
template: `
`,
data: { view: 'one' },
components,
methods: {
afterEnter () {
next()
}
}
}).$mount(el)
expect(vm.$el.textContent).toBe('one')
vm.view = 'two'
waitForUpdate(() => {
expect(vm.$el.innerHTML).toBe(
'
one
' +
'
two
'
)
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.innerHTML).toBe(
'
one
' +
'
two
'
)
// switch again before enter finishes,
// this cancels both enter and leave.
vm.view = 'one'
}).then(() => {
// 1. the pending leaving "one" should be removed instantly.
// 2. the entering "two" should be placed into its final state instantly.
// 3. a new "one" is created and entering
expect(vm.$el.innerHTML).toBe(
'
two
' +
'
one
'
)
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.innerHTML).toBe(
'
two
' +
'
one
'
)
}).thenWaitFor(_next => { next = _next }).then(() => {
expect(vm.$el.innerHTML).toBe(
'
two
' +
'
one
'
)
}).then(() => {
expect(vm.$el.innerHTML).toBe(
'
two
' +
'
one
'
)
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.innerHTML).toBe(
'
two
' +
'
one
'
)
}).thenWaitFor(duration + buffer).then(() => {
expect(vm.$el.innerHTML).toBe(
'
one
'
)
}).then(done).then(done)
})
it('normal elements with different keys, simultaneous', done => {
const vm = new Vue({
template: `
`,
data: { view: 'one' },
components
}).$mount(el)
expect(vm.$el.textContent).toBe('one')
vm.view = 'two'
waitForUpdate(() => {
expect(vm.$el.innerHTML).toBe(
'
one
' +
'
two
'
)
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.innerHTML).toBe(
'
one
' +
'
two
'
)
}).thenWaitFor(duration + buffer).then(() => {
expect(vm.$el.innerHTML).toBe(
'
two
'
)
}).then(done)
})
it('normal elements with different keys, out-in', done => {
let next
const vm = new Vue({
template: `
`,
data: { view: 'one' },
components,
methods: {
afterLeave () {
next()
}
}
}).$mount(el)
expect(vm.$el.textContent).toBe('one')
vm.view = 'two'
waitForUpdate(() => {
expect(vm.$el.innerHTML).toBe(
'
one
'
)
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.innerHTML).toBe(
'
one
'
)
}).thenWaitFor(_next => { next = _next }).then(() => {
expect(vm.$el.innerHTML).toBe('')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.innerHTML).toBe(
'
two
'
)
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.innerHTML).toBe(
'
two
'
)
}).thenWaitFor(duration + buffer).then(() => {
expect(vm.$el.innerHTML).toBe(
'
two
'
)
}).then(done)
})
it('normal elements with different keys, in-out', done => {
let next
const vm = new Vue({
template: `
`,
data: { view: 'one' },
components,
methods: {
afterEnter () {
next()
}
}
}).$mount(el)
expect(vm.$el.textContent).toBe('one')
vm.view = 'two'
waitForUpdate(() => {
expect(vm.$el.innerHTML).toBe(
'
one
' +
'
two
'
)
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.innerHTML).toBe(
'
one
' +
'
two
'
)
}).thenWaitFor(_next => { next = _next }).then(() => {
expect(vm.$el.innerHTML).toBe(
'
one
' +
'
two
'
)
}).then(() => {
expect(vm.$el.innerHTML).toBe(
'
one
' +
'
two
'
)
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.innerHTML).toBe(
'
one
' +
'
two
'
)
}).thenWaitFor(duration + buffer).then(() => {
expect(vm.$el.innerHTML).toBe(
'
two
'
)
}).then(done)
})
it('transition out-in on async component (resolve before leave complete)', done => {
const vm = new Vue({
template: `
`,
components: {
componentA: resolve => {
setTimeout(() => {
resolve({ template: '
component A ' })
next1()
}, duration / 2)
},
componentB: resolve => {
setTimeout(() => {
resolve({ template: '
component B ' })
}, duration / 2)
}
},
data: {
ok: true
}
}).$mount(el)
expect(vm.$el.innerHTML).toBe('')
function next1 () {
Vue.nextTick(() => {
expect(vm.$el.children.length).toBe(1)
expect(vm.$el.textContent).toBe('component A')
expect(vm.$el.children[0].className).toBe('test-anim-enter test-anim-enter-active')
nextFrame(() => {
expect(vm.$el.children[0].className).toBe('test-anim-enter-active test-anim-enter-to')
setTimeout(() => {
expect(vm.$el.children[0].className).toBe('')
vm.ok = false
next2()
}, duration + buffer)
})
})
}
function next2 () {
waitForUpdate(() => {
expect(vm.$el.children.length).toBe(1)
expect(vm.$el.textContent).toBe('component A')
expect(vm.$el.children[0].className).toBe('test-anim-leave test-anim-leave-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test-anim-leave-active test-anim-leave-to')
}).thenWaitFor(duration + buffer).then(() => {
expect(vm.$el.children.length).toBe(1)
expect(vm.$el.textContent).toBe('component B')
expect(vm.$el.children[0].className).toMatch('test-anim-enter-active')
}).thenWaitFor(duration * 2).then(() => {
expect(vm.$el.children[0].className).toBe('')
}).then(done)
}
})
it('transition out-in on async component (resolve after leave complete)', done => {
const vm = new Vue({
template: `
`,
components: {
componentA: { template: '
component A ' },
componentB: resolve => {
setTimeout(() => {
resolve({ template: '
component B ' })
Vue.nextTick(next)
}, (duration + buffer) * 1.5)
}
},
data: {
ok: true
}
}).$mount(el)
expect(vm.$el.innerHTML).toBe('
component A ')
let next
vm.ok = false
waitForUpdate(() => {
expect(vm.$el.children.length).toBe(1)
expect(vm.$el.textContent).toBe('component A')
expect(vm.$el.children[0].className).toBe('test-anim-leave test-anim-leave-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test-anim-leave-active test-anim-leave-to')
}).thenWaitFor(duration + buffer).then(() => {
expect(vm.$el.children.length).toBe(0)
expect(vm.$el.innerHTML).toBe('')
}).thenWaitFor(_next => { next = _next }).then(() => {
expect(vm.$el.children.length).toBe(1)
expect(vm.$el.textContent).toBe('component B')
expect(vm.$el.children[0].className).toBe('test-anim-enter test-anim-enter-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test-anim-enter-active test-anim-enter-to')
}).thenWaitFor(duration + buffer).then(() => {
expect(vm.$el.children.length).toBe(1)
expect(vm.$el.textContent).toBe('component B')
expect(vm.$el.children[0].className).toBe('')
}).then(done)
})
it('transition in-out on async component', done => {
const vm = new Vue({
template: `
`,
components: {
componentA: resolve => {
setTimeout(() => {
resolve({ template: '
component A ' })
next1()
}, duration / 2)
},
componentB: resolve => {
setTimeout(() => {
resolve({ template: '
component B ' })
next2()
}, duration / 2)
}
},
data: {
ok: true
}
}).$mount(el)
expect(vm.$el.innerHTML).toBe('')
function next1 () {
Vue.nextTick(() => {
expect(vm.$el.children.length).toBe(1)
expect(vm.$el.textContent).toBe('component A')
expect(vm.$el.children[0].className).toBe('test-anim-enter test-anim-enter-active')
nextFrame(() => {
expect(vm.$el.children[0].className).toBe('test-anim-enter-active test-anim-enter-to')
setTimeout(() => {
expect(vm.$el.children[0].className).toBe('')
vm.ok = false
}, duration + buffer)
})
})
}
function next2 () {
waitForUpdate(() => {
expect(vm.$el.children.length).toBe(2)
expect(vm.$el.textContent).toBe('component Acomponent B')
expect(vm.$el.children[0].className).toBe('')
expect(vm.$el.children[1].className).toBe('test-anim-enter test-anim-enter-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[1].className).toBe('test-anim-enter-active test-anim-enter-to')
}).thenWaitFor(duration + buffer).then(() => {
expect(vm.$el.children.length).toBe(2)
expect(vm.$el.textContent).toBe('component Acomponent B')
expect(vm.$el.children[0].className).toMatch('test-anim-leave-active')
expect(vm.$el.children[1].className).toBe('')
}).thenWaitFor(duration + buffer).then(() => {
expect(vm.$el.children.length).toBe(1)
expect(vm.$el.textContent).toBe('component B')
expect(vm.$el.children[0].className).toBe('')
}).then(done)
}
})
it('warn invalid mode', () => {
new Vue({
template: '
123
'
}).$mount()
expect('invalid
mode: foo').toHaveBeenWarned()
})
})
}
node-vue-template-compiler-2.4.2+dfsg/test/unit/features/transition/transition.spec.js000066400000000000000000001201061361753775300312510ustar00rootroot00000000000000import Vue from 'vue'
import injectStyles from './inject-styles'
import { isIE9 } from 'core/util/env'
import { nextFrame } from 'web/runtime/transition-util'
if (!isIE9) {
describe('Transition basic', () => {
const { duration, buffer } = injectStyles()
const explicitDuration = duration * 2
let el
beforeEach(() => {
el = document.createElement('div')
document.body.appendChild(el)
})
it('basic transition', done => {
const vm = new Vue({
template: '',
data: { ok: true }
}).$mount(el)
// should not apply transition on initial render by default
expect(vm.$el.innerHTML).toBe('foo
')
vm.ok = false
waitForUpdate(() => {
expect(vm.$el.children[0].className).toBe('test v-leave v-leave-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test v-leave-active v-leave-to')
}).thenWaitFor(duration + buffer).then(() => {
expect(vm.$el.children.length).toBe(0)
vm.ok = true
}).then(() => {
expect(vm.$el.children[0].className).toBe('test v-enter v-enter-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test v-enter-active v-enter-to')
}).thenWaitFor(duration + buffer).then(() => {
expect(vm.$el.children[0].className).toBe('test')
}).then(done)
})
it('named transition', done => {
const vm = new Vue({
template: '',
data: { ok: true }
}).$mount(el)
// should not apply transition on initial render by default
expect(vm.$el.innerHTML).toBe('foo
')
vm.ok = false
waitForUpdate(() => {
expect(vm.$el.children[0].className).toBe('test test-leave test-leave-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test test-leave-active test-leave-to')
}).thenWaitFor(duration + buffer).then(() => {
expect(vm.$el.children.length).toBe(0)
vm.ok = true
}).then(() => {
expect(vm.$el.children[0].className).toBe('test test-enter test-enter-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test test-enter-active test-enter-to')
}).thenWaitFor(duration + buffer).then(() => {
expect(vm.$el.children[0].className).toBe('test')
}).then(done)
})
it('custom transition classes', done => {
const vm = new Vue({
template: `
`,
data: { ok: true }
}).$mount(el)
// should not apply transition on initial render by default
expect(vm.$el.innerHTML).toBe('foo
')
vm.ok = false
waitForUpdate(() => {
expect(vm.$el.children[0].className).toBe('test bye byebye active more')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test byebye active more bye-to')
}).thenWaitFor(duration + buffer).then(() => {
expect(vm.$el.children.length).toBe(0)
vm.ok = true
}).then(() => {
expect(vm.$el.children[0].className).toBe('test hello hello-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test hello-active hello-to')
}).thenWaitFor(duration + buffer).then(() => {
expect(vm.$el.children[0].className).toBe('test')
}).then(done)
})
it('dynamic transition', done => {
const vm = new Vue({
template: `
`,
data: {
ok: true,
trans: 'test'
}
}).$mount(el)
// should not apply transition on initial render by default
expect(vm.$el.innerHTML).toBe('foo
')
vm.ok = false
waitForUpdate(() => {
expect(vm.$el.children[0].className).toBe('test test-leave test-leave-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test test-leave-active test-leave-to')
}).thenWaitFor(duration + buffer).then(() => {
expect(vm.$el.children.length).toBe(0)
vm.ok = true
vm.trans = 'changed'
}).then(() => {
expect(vm.$el.children[0].className).toBe('test changed-enter changed-enter-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test changed-enter-active changed-enter-to')
}).thenWaitFor(duration + buffer).then(() => {
expect(vm.$el.children[0].className).toBe('test')
}).then(done)
})
it('inline transition object', done => {
const enter = jasmine.createSpy('enter')
const leave = jasmine.createSpy('leave')
const vm = new Vue({
render (h) {
return h('div', null, [
h('transition', {
props: {
name: 'inline',
enterClass: 'hello',
enterToClass: 'hello-to',
enterActiveClass: 'hello-active',
leaveClass: 'bye',
leaveToClass: 'bye-to',
leaveActiveClass: 'byebye active'
},
on: {
enter,
leave
}
}, this.ok ? [h('div', { class: 'test' }, 'foo')] : undefined)
])
},
data: { ok: true }
}).$mount(el)
// should not apply transition on initial render by default
expect(vm.$el.innerHTML).toBe('foo
')
vm.ok = false
waitForUpdate(() => {
expect(vm.$el.children[0].className).toBe('test bye byebye active')
expect(leave).toHaveBeenCalled()
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test byebye active bye-to')
}).thenWaitFor(duration + buffer).then(() => {
expect(vm.$el.children.length).toBe(0)
vm.ok = true
}).then(() => {
expect(vm.$el.children[0].className).toBe('test hello hello-active')
expect(enter).toHaveBeenCalled()
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test hello-active hello-to')
}).thenWaitFor(duration + buffer).then(() => {
expect(vm.$el.children[0].className).toBe('test')
}).then(done)
})
it('transition events', done => {
const onLeaveSpy = jasmine.createSpy('leave')
const onEnterSpy = jasmine.createSpy('enter')
const beforeLeaveSpy = jasmine.createSpy('beforeLeave')
const beforeEnterSpy = jasmine.createSpy('beforeEnter')
const afterLeaveSpy = jasmine.createSpy('afterLeave')
const afterEnterSpy = jasmine.createSpy('afterEnter')
const vm = new Vue({
template: `
`,
data: { ok: true },
methods: {
beforeLeave: (el) => {
expect(el).toBe(vm.$el.children[0])
expect(el.className).toBe('test')
beforeLeaveSpy(el)
},
leave: (el) => onLeaveSpy(el),
afterLeave: (el) => afterLeaveSpy(el),
beforeEnter: (el) => {
expect(vm.$el.contains(el)).toBe(false)
expect(el.className).toBe('test')
beforeEnterSpy(el)
},
enter: (el) => {
expect(vm.$el.contains(el)).toBe(true)
onEnterSpy(el)
},
afterEnter: (el) => afterEnterSpy(el)
}
}).$mount(el)
// should not apply transition on initial render by default
expect(vm.$el.innerHTML).toBe('foo
')
let _el = vm.$el.children[0]
vm.ok = false
waitForUpdate(() => {
expect(beforeLeaveSpy).toHaveBeenCalledWith(_el)
expect(onLeaveSpy).toHaveBeenCalledWith(_el)
expect(vm.$el.children[0].className).toBe('test test-leave test-leave-active')
}).thenWaitFor(nextFrame).then(() => {
expect(afterLeaveSpy).not.toHaveBeenCalled()
expect(vm.$el.children[0].className).toBe('test test-leave-active test-leave-to')
}).thenWaitFor(duration + buffer).then(() => {
expect(afterLeaveSpy).toHaveBeenCalledWith(_el)
expect(vm.$el.children.length).toBe(0)
vm.ok = true
}).then(() => {
_el = vm.$el.children[0]
expect(beforeEnterSpy).toHaveBeenCalledWith(_el)
expect(onEnterSpy).toHaveBeenCalledWith(_el)
expect(vm.$el.children[0].className).toBe('test test-enter test-enter-active')
}).thenWaitFor(nextFrame).then(() => {
expect(afterEnterSpy).not.toHaveBeenCalled()
expect(vm.$el.children[0].className).toBe('test test-enter-active test-enter-to')
}).thenWaitFor(duration + buffer).then(() => {
expect(afterEnterSpy).toHaveBeenCalledWith(_el)
expect(vm.$el.children[0].className).toBe('test')
}).then(done)
})
it('transition events (v-show)', done => {
const onLeaveSpy = jasmine.createSpy('leave')
const onEnterSpy = jasmine.createSpy('enter')
const beforeLeaveSpy = jasmine.createSpy('beforeLeave')
const beforeEnterSpy = jasmine.createSpy('beforeEnter')
const afterLeaveSpy = jasmine.createSpy('afterLeave')
const afterEnterSpy = jasmine.createSpy('afterEnter')
const vm = new Vue({
template: `
`,
data: { ok: true },
methods: {
beforeLeave: (el) => {
expect(el.style.display).toBe('')
expect(el).toBe(vm.$el.children[0])
expect(el.className).toBe('test')
beforeLeaveSpy(el)
},
leave: (el) => {
expect(el.style.display).toBe('')
onLeaveSpy(el)
},
afterLeave: (el) => {
expect(el.style.display).toBe('none')
afterLeaveSpy(el)
},
beforeEnter: (el) => {
expect(el.className).toBe('test')
expect(el.style.display).toBe('none')
beforeEnterSpy(el)
},
enter: (el) => {
expect(el.style.display).toBe('')
onEnterSpy(el)
},
afterEnter: (el) => {
expect(el.style.display).toBe('')
afterEnterSpy(el)
}
}
}).$mount(el)
// should not apply transition on initial render by default
expect(vm.$el.innerHTML).toBe('foo
')
let _el = vm.$el.children[0]
vm.ok = false
waitForUpdate(() => {
expect(beforeLeaveSpy).toHaveBeenCalledWith(_el)
expect(onLeaveSpy).toHaveBeenCalledWith(_el)
expect(vm.$el.children[0].className).toBe('test test-leave test-leave-active')
}).thenWaitFor(nextFrame).then(() => {
expect(afterLeaveSpy).not.toHaveBeenCalled()
expect(vm.$el.children[0].className).toBe('test test-leave-active test-leave-to')
}).thenWaitFor(duration + buffer).then(() => {
expect(afterLeaveSpy).toHaveBeenCalledWith(_el)
expect(vm.$el.children[0].style.display).toBe('none')
vm.ok = true
}).then(() => {
_el = vm.$el.children[0]
expect(beforeEnterSpy).toHaveBeenCalledWith(_el)
expect(onEnterSpy).toHaveBeenCalledWith(_el)
expect(vm.$el.children[0].className).toBe('test test-enter test-enter-active')
}).thenWaitFor(nextFrame).then(() => {
expect(afterEnterSpy).not.toHaveBeenCalled()
expect(vm.$el.children[0].className).toBe('test test-enter-active test-enter-to')
}).thenWaitFor(duration + buffer).then(() => {
expect(afterEnterSpy).toHaveBeenCalledWith(_el)
expect(vm.$el.children[0].className).toBe('test')
}).then(done)
})
it('explicit user callback in JavaScript hooks', done => {
let next
const vm = new Vue({
template: ``,
data: { ok: true },
methods: {
enter: (el, cb) => {
next = cb
},
leave: (el, cb) => {
next = cb
}
}
}).$mount(el)
vm.ok = false
waitForUpdate(() => {
expect(vm.$el.children[0].className).toBe('test test-leave test-leave-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test test-leave-active test-leave-to')
}).thenWaitFor(duration + buffer).then(() => {
expect(vm.$el.children[0].className).toBe('test test-leave-active test-leave-to')
expect(next).toBeTruthy()
next()
expect(vm.$el.children.length).toBe(0)
}).then(() => {
vm.ok = true
}).then(() => {
expect(vm.$el.children[0].className).toBe('test test-enter test-enter-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test test-enter-active test-enter-to')
}).thenWaitFor(duration + buffer).then(() => {
expect(vm.$el.children[0].className).toBe('test test-enter-active test-enter-to')
expect(next).toBeTruthy()
next()
expect(vm.$el.children[0].className).toBe('test')
}).then(done)
})
it('css: false', done => {
const enterSpy = jasmine.createSpy('enter')
const leaveSpy = jasmine.createSpy('leave')
const vm = new Vue({
template: `
`,
data: { ok: true },
methods: {
enter: enterSpy,
leave: leaveSpy
}
}).$mount(el)
vm.ok = false
waitForUpdate(() => {
expect(leaveSpy).toHaveBeenCalled()
expect(vm.$el.innerHTML).toBe('')
vm.ok = true
}).then(() => {
expect(enterSpy).toHaveBeenCalled()
expect(vm.$el.innerHTML).toBe('foo
')
}).then(done)
})
it('no transition detected', done => {
const enterSpy = jasmine.createSpy('enter')
const leaveSpy = jasmine.createSpy('leave')
const vm = new Vue({
template: '',
data: { ok: true },
methods: {
enter: enterSpy,
leave: leaveSpy
}
}).$mount(el)
vm.ok = false
waitForUpdate(() => {
expect(leaveSpy).toHaveBeenCalled()
expect(vm.$el.innerHTML).toBe('foo
')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.innerHTML).toBe('')
vm.ok = true
}).then(() => {
expect(enterSpy).toHaveBeenCalled()
expect(vm.$el.innerHTML).toBe('foo
')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.innerHTML).toBe('foo
')
}).then(done)
})
it('enterCancelled', done => {
const spy = jasmine.createSpy('enterCancelled')
const vm = new Vue({
template: `
`,
data: { ok: false },
methods: {
enterCancelled: spy
}
}).$mount(el)
expect(vm.$el.innerHTML).toBe('')
vm.ok = true
waitForUpdate(() => {
expect(vm.$el.children[0].className).toBe('test test-enter test-enter-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test test-enter-active test-enter-to')
}).thenWaitFor(duration / 2).then(() => {
vm.ok = false
}).then(() => {
expect(spy).toHaveBeenCalled()
expect(vm.$el.children[0].className).toBe('test test-leave test-leave-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test test-leave-active test-leave-to')
}).thenWaitFor(duration + buffer).then(() => {
expect(vm.$el.children.length).toBe(0)
}).then(done)
})
it('should remove stale leaving elements', done => {
const spy = jasmine.createSpy('afterLeave')
const vm = new Vue({
template: `
`,
data: { ok: true },
methods: {
afterLeave: spy
}
}).$mount(el)
expect(vm.$el.innerHTML).toBe('foo
')
vm.ok = false
waitForUpdate(() => {
expect(vm.$el.children[0].className).toBe('test test-leave test-leave-active')
}).thenWaitFor(duration / 2).then(() => {
vm.ok = true
}).then(() => {
expect(spy).toHaveBeenCalled()
expect(vm.$el.children.length).toBe(1) // should have removed leaving element
expect(vm.$el.children[0].className).toBe('test test-enter test-enter-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test test-enter-active test-enter-to')
}).thenWaitFor(duration + buffer).then(() => {
expect(vm.$el.innerHTML).toBe('foo
')
}).then(done)
})
it('transition with v-show', done => {
const vm = new Vue({
template: `
`,
data: { ok: true }
}).$mount(el)
// should not apply transition on initial render by default
expect(vm.$el.textContent).toBe('foo')
expect(vm.$el.children[0].style.display).toBe('')
expect(vm.$el.children[0].className).toBe('test')
vm.ok = false
waitForUpdate(() => {
expect(vm.$el.children[0].className).toBe('test test-leave test-leave-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test test-leave-active test-leave-to')
}).thenWaitFor(duration + buffer).then(() => {
expect(vm.$el.children[0].style.display).toBe('none')
vm.ok = true
}).then(() => {
expect(vm.$el.children[0].style.display).toBe('')
expect(vm.$el.children[0].className).toBe('test test-enter test-enter-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test test-enter-active test-enter-to')
}).thenWaitFor(duration + buffer).then(() => {
expect(vm.$el.children[0].className).toBe('test')
}).then(done)
})
it('transition with v-show, inside child component', done => {
const vm = new Vue({
template: `
`,
data: { ok: true },
components: {
test: {
template: `foo
`
}
}
}).$mount(el)
// should not apply transition on initial render by default
expect(vm.$el.textContent).toBe('foo')
expect(vm.$el.children[0].style.display).toBe('')
vm.ok = false
waitForUpdate(() => {
expect(vm.$el.children[0].className).toBe('test test-leave test-leave-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test test-leave-active test-leave-to')
}).thenWaitFor(duration + buffer).then(() => {
expect(vm.$el.children[0].style.display).toBe('none')
vm.ok = true
}).then(() => {
expect(vm.$el.children[0].style.display).toBe('')
expect(vm.$el.children[0].className).toBe('test test-enter test-enter-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test test-enter-active test-enter-to')
}).thenWaitFor(duration + buffer).then(() => {
expect(vm.$el.children[0].className).toBe('test')
}).then(done)
})
it('leaveCancelled (v-show only)', done => {
const spy = jasmine.createSpy('leaveCancelled')
const vm = new Vue({
template: `
`,
data: { ok: true },
methods: {
leaveCancelled: spy
}
}).$mount(el)
expect(vm.$el.children[0].style.display).toBe('')
vm.ok = false
waitForUpdate(() => {
expect(vm.$el.children[0].className).toBe('test test-leave test-leave-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test test-leave-active test-leave-to')
}).thenWaitFor(10).then(() => {
vm.ok = true
}).then(() => {
expect(spy).toHaveBeenCalled()
expect(vm.$el.children[0].className).toBe('test test-enter test-enter-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test test-enter-active test-enter-to')
}).thenWaitFor(duration + buffer).then(() => {
expect(vm.$el.children[0].style.display).toBe('')
}).then(done)
})
it('animations', done => {
const vm = new Vue({
template: `
`,
data: { ok: true }
}).$mount(el)
// should not apply transition on initial render by default
expect(vm.$el.innerHTML).toBe('foo
')
vm.ok = false
waitForUpdate(() => {
expect(vm.$el.children[0].className).toBe('test-anim-leave test-anim-leave-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test-anim-leave-active test-anim-leave-to')
}).thenWaitFor(duration + buffer).then(() => {
expect(vm.$el.children.length).toBe(0)
vm.ok = true
}).then(() => {
expect(vm.$el.children[0].className).toBe('test-anim-enter test-anim-enter-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test-anim-enter-active test-anim-enter-to')
}).thenWaitFor(duration + buffer).then(() => {
expect(vm.$el.children[0].className).toBe('')
}).then(done)
})
it('explicit transition type', done => {
const vm = new Vue({
template: `
`,
data: { ok: true }
}).$mount(el)
// should not apply transition on initial render by default
expect(vm.$el.innerHTML).toBe('foo
')
vm.ok = false
waitForUpdate(() => {
expect(vm.$el.children[0].className).toBe('test test-anim-long-leave test-anim-long-leave-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test test-anim-long-leave-active test-anim-long-leave-to')
}).thenWaitFor(duration + 5).then(() => {
// should not end early due to transition presence
expect(vm.$el.children[0].className).toBe('test test-anim-long-leave-active test-anim-long-leave-to')
}).thenWaitFor(duration + 5).then(() => {
expect(vm.$el.children.length).toBe(0)
vm.ok = true
}).then(() => {
expect(vm.$el.children[0].className).toBe('test test-anim-long-enter test-anim-long-enter-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test test-anim-long-enter-active test-anim-long-enter-to')
}).thenWaitFor(duration + 5).then(() => {
expect(vm.$el.children[0].className).toBe('test test-anim-long-enter-active test-anim-long-enter-to')
}).thenWaitFor(duration + 5).then(() => {
expect(vm.$el.children[0].className).toBe('test')
}).then(done)
})
it('transition on appear', done => {
const vm = new Vue({
template: `
`,
data: { ok: true }
}).$mount(el)
waitForUpdate(() => {
expect(vm.$el.children[0].className).toBe('test test-appear test-appear-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test test-appear-active test-appear-to')
}).thenWaitFor(duration + buffer).then(() => {
expect(vm.$el.children[0].className).toBe('test')
}).then(done)
})
it('transition on appear with v-show', done => {
const vm = new Vue({
template: `
`,
data: { ok: true }
}).$mount(el)
waitForUpdate(() => {
expect(vm.$el.children[0].className).toBe('test test-enter test-enter-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test test-enter-active test-enter-to')
}).thenWaitFor(duration + buffer).then(() => {
expect(vm.$el.children[0].className).toBe('test')
}).then(done)
})
it('transition on SVG elements', done => {
const vm = new Vue({
template: `
`,
data: { ok: true }
}).$mount(el)
// should not apply transition on initial render by default
expect(vm.$el.childNodes[0].getAttribute('class')).toBe('test')
vm.ok = false
waitForUpdate(() => {
expect(vm.$el.childNodes[0].getAttribute('class')).toBe('test v-leave v-leave-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.childNodes[0].getAttribute('class')).toBe('test v-leave-active v-leave-to')
}).thenWaitFor(duration + buffer).then(() => {
expect(vm.$el.childNodes.length).toBe(1)
expect(vm.$el.childNodes[0].nodeType).toBe(8) // should be an empty comment node
expect(vm.$el.childNodes[0].textContent).toBe('')
vm.ok = true
}).then(() => {
expect(vm.$el.childNodes[0].getAttribute('class')).toBe('test v-enter v-enter-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.childNodes[0].getAttribute('class')).toBe('test v-enter-active v-enter-to')
}).thenWaitFor(duration + buffer).then(() => {
expect(vm.$el.childNodes[0].getAttribute('class')).toBe('test')
}).then(done)
})
it('transition on child components', done => {
const vm = new Vue({
template: `
`,
data: { ok: true },
components: {
test: {
template: `
foo
` // test transition override from parent
}
}
}).$mount(el)
// should not apply transition on initial render by default
expect(vm.$el.innerHTML).toBe('foo
')
vm.ok = false
waitForUpdate(() => {
expect(vm.$el.children[0].className).toBe('test v-leave v-leave-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test v-leave-active v-leave-to')
}).thenWaitFor(duration + buffer).then(() => {
expect(vm.$el.children.length).toBe(0)
vm.ok = true
}).then(() => {
expect(vm.$el.children[0].className).toBe('test v-enter v-enter-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test v-enter-active v-enter-to')
}).thenWaitFor(duration + buffer).then(() => {
expect(vm.$el.children[0].className).toBe('test')
}).then(done)
})
it('transition inside child component', done => {
const vm = new Vue({
template: `
`,
data: { ok: true },
components: {
test: {
template: `
foo
`
}
}
}).$mount(el)
// should not apply transition on initial render by default
expect(vm.$el.innerHTML).toBe('foo
')
vm.ok = false
waitForUpdate(() => {
expect(vm.$el.children[0].className).toBe('test v-leave v-leave-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test v-leave-active v-leave-to')
}).thenWaitFor(duration + buffer).then(() => {
expect(vm.$el.children.length).toBe(0)
vm.ok = true
}).then(() => {
expect(vm.$el.children[0].className).toBe('test v-enter v-enter-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test v-enter-active v-enter-to')
}).thenWaitFor(duration + buffer).then(() => {
expect(vm.$el.children[0].className).toBe('test')
}).then(done)
})
it('custom transition higher-order component', done => {
const vm = new Vue({
template: '',
data: { ok: true },
components: {
'my-transition': {
functional: true,
render (h, { data, children }) {
(data.props || (data.props = {})).name = 'test'
return h('transition', data, children)
}
}
}
}).$mount(el)
// should not apply transition on initial render by default
expect(vm.$el.innerHTML).toBe('foo
')
vm.ok = false
waitForUpdate(() => {
expect(vm.$el.children[0].className).toBe('test test-leave test-leave-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test test-leave-active test-leave-to')
}).thenWaitFor(duration + buffer).then(() => {
expect(vm.$el.children.length).toBe(0)
vm.ok = true
}).then(() => {
expect(vm.$el.children[0].className).toBe('test test-enter test-enter-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test test-enter-active test-enter-to')
}).thenWaitFor(duration + buffer).then(() => {
expect(vm.$el.children[0].className).toBe('test')
}).then(done)
})
it('warn when used on multiple elements', () => {
new Vue({
template: `1
2
`
}).$mount()
expect(` can only be used on a single element`).toHaveBeenWarned()
})
describe('explicit durations -', () => {
it('single value', done => {
const vm = new Vue({
template: `
`,
data: { ok: true }
}).$mount(el)
vm.ok = false
waitForUpdate(() => {
expect(vm.$el.children[0].className).toBe('test v-leave v-leave-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test v-leave-active v-leave-to')
}).thenWaitFor(explicitDuration + buffer).then(() => {
expect(vm.$el.children.length).toBe(0)
vm.ok = true
}).then(() => {
expect(vm.$el.children[0].className).toBe('test v-enter v-enter-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test v-enter-active v-enter-to')
}).thenWaitFor(explicitDuration + buffer).then(() => {
expect(vm.$el.children[0].className).toBe('test')
}).then(done)
})
it('enter and auto leave', done => {
const vm = new Vue({
template: `
`,
data: { ok: true }
}).$mount(el)
vm.ok = false
waitForUpdate(() => {
expect(vm.$el.children[0].className).toBe('test v-leave v-leave-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test v-leave-active v-leave-to')
}).thenWaitFor(duration + buffer).then(() => {
expect(vm.$el.children.length).toBe(0)
vm.ok = true
}).then(() => {
expect(vm.$el.children[0].className).toBe('test v-enter v-enter-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test v-enter-active v-enter-to')
}).thenWaitFor(explicitDuration + buffer).then(() => {
expect(vm.$el.children[0].className).toBe('test')
}).then(done)
})
it('leave and auto enter', done => {
const vm = new Vue({
template: `
`,
data: { ok: true }
}).$mount(el)
vm.ok = false
waitForUpdate(() => {
expect(vm.$el.children[0].className).toBe('test v-leave v-leave-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test v-leave-active v-leave-to')
}).thenWaitFor(explicitDuration + buffer).then(() => {
expect(vm.$el.children.length).toBe(0)
vm.ok = true
}).then(() => {
expect(vm.$el.children[0].className).toBe('test v-enter v-enter-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test v-enter-active v-enter-to')
}).thenWaitFor(duration + buffer).then(() => {
expect(vm.$el.children[0].className).toBe('test')
}).then(done)
})
it('separate enter and leave', done => {
const enter = explicitDuration
const leave = explicitDuration * 2
const vm = new Vue({
template: `
`,
data: { ok: true }
}).$mount(el)
vm.ok = false
waitForUpdate(() => {
expect(vm.$el.children[0].className).toBe('test v-leave v-leave-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test v-leave-active v-leave-to')
}).thenWaitFor(leave + buffer).then(() => {
expect(vm.$el.children.length).toBe(0)
vm.ok = true
}).then(() => {
expect(vm.$el.children[0].className).toBe('test v-enter v-enter-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test v-enter-active v-enter-to')
}).thenWaitFor(enter + buffer).then(() => {
expect(vm.$el.children[0].className).toBe('test')
}).then(done)
})
it('enter and leave + duration change', done => {
const enter1 = explicitDuration * 2
const enter2 = explicitDuration
const leave1 = explicitDuration * 0.5
const leave2 = explicitDuration * 3
const vm = new Vue({
template: `
`,
data: {
ok: true,
enter: enter1,
leave: leave1
}
}).$mount(el)
vm.ok = false
waitForUpdate(() => {
expect(vm.$el.children[0].className).toBe('test v-leave v-leave-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test v-leave-active v-leave-to')
}).thenWaitFor(leave1 + buffer).then(() => {
expect(vm.$el.children.length).toBe(0)
vm.ok = true
}).then(() => {
expect(vm.$el.children[0].className).toBe('test v-enter v-enter-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test v-enter-active v-enter-to')
}).thenWaitFor(enter1 + buffer).then(() => {
expect(vm.$el.children[0].className).toBe('test')
vm.enter = enter2
vm.leave = leave2
}).then(() => {
vm.ok = false
}).then(() => {
expect(vm.$el.children[0].className).toBe('test v-leave v-leave-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test v-leave-active v-leave-to')
}).thenWaitFor(leave2 + buffer).then(() => {
expect(vm.$el.children.length).toBe(0)
vm.ok = true
}).then(() => {
expect(vm.$el.children[0].className).toBe('test v-enter v-enter-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test v-enter-active v-enter-to')
}).thenWaitFor(enter2 + buffer).then(() => {
expect(vm.$el.children[0].className).toBe('test')
}).then(done)
}, 10000)
it('warn invalid durations', done => {
const vm = new Vue({
template: `
`,
data: {
ok: true
}
}).$mount(el)
vm.ok = false
waitForUpdate(() => {
expect(` explicit leave duration is not a valid number - got "foo"`).toHaveBeenWarned()
}).thenWaitFor(duration + buffer).then(() => {
vm.ok = true
}).then(() => {
expect(` explicit enter duration is NaN`).toHaveBeenWarned()
}).then(done)
})
})
})
}
node-vue-template-compiler-2.4.2+dfsg/test/unit/index.js000066400000000000000000000004351361753775300232270ustar00rootroot00000000000000require('es6-promise/auto')
// import all helpers
const helpersContext = require.context('../helpers', true)
helpersContext.keys().forEach(helpersContext)
// require all test files
const testsContext = require.context('./', true, /\.spec$/)
testsContext.keys().forEach(testsContext)
node-vue-template-compiler-2.4.2+dfsg/test/unit/karma.base.config.js000066400000000000000000000015651361753775300253750ustar00rootroot00000000000000var alias = require('../../build/alias')
var webpack = require('webpack')
var webpackConfig = {
resolve: {
alias: alias
},
module: {
rules: [
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/
}
]
},
plugins: [
new webpack.DefinePlugin({
__WEEX__: false,
'process.env': {
NODE_ENV: '"development"',
TRANSITION_DURATION: 50,
TRANSITION_BUFFER: 10
}
})
],
devtool: '#inline-source-map'
}
// shared config for all unit tests
module.exports = {
frameworks: ['jasmine'],
files: [
'./index.js'
],
preprocessors: {
'./index.js': ['webpack', 'sourcemap']
},
webpack: webpackConfig,
webpackMiddleware: {
noInfo: true
},
plugins: [
'karma-jasmine',
'karma-mocha-reporter',
'karma-sourcemap-loader',
'karma-webpack'
]
}
node-vue-template-compiler-2.4.2+dfsg/test/unit/karma.cover.config.js000066400000000000000000000014721361753775300255760ustar00rootroot00000000000000var base = require('./karma.base.config.js')
module.exports = function (config) {
var options = Object.assign(base, {
browsers: ['PhantomJS'],
reporters: ['mocha', 'coverage'],
coverageReporter: {
reporters: [
{ type: 'lcov', dir: '../../coverage', subdir: '.' },
{ type: 'text-summary', dir: '../../coverage', subdir: '.' }
]
},
singleRun: true,
plugins: base.plugins.concat([
'karma-coverage',
'karma-phantomjs-launcher'
])
})
// add babel-plugin-istanbul for code intrumentation
options.webpack.module.rules[0].options = {
plugins: [['istanbul', {
exclude: [
'test/',
'src/compiler/parser/html-parser.js',
'src/core/instance/proxy.js',
'src/sfc/deindent.js'
]
}]]
}
config.set(options)
}
node-vue-template-compiler-2.4.2+dfsg/test/unit/karma.dev.config.js000066400000000000000000000003751361753775300252370ustar00rootroot00000000000000var base = require('./karma.base.config.js')
module.exports = function (config) {
config.set(Object.assign(base, {
browsers: ['Chrome'],
reporters: ['progress'],
plugins: base.plugins.concat([
'karma-chrome-launcher'
])
}))
}
node-vue-template-compiler-2.4.2+dfsg/test/unit/karma.sauce.config.js000066400000000000000000000045071361753775300255620ustar00rootroot00000000000000var webpack = require('webpack')
var base = require('./karma.base.config.js')
base.webpack.plugins = [
new webpack.DefinePlugin({
__WEEX__: false,
'process.env': {
NODE_ENV: '"development"',
// sauce lab vms are slow!
TRANSITION_DURATION: 500,
TRANSITION_BUFFER: 50
}
})
]
/**
* Having too many tests running concurrently on saucelabs
* causes timeouts and errors, so we have to run them in
* smaller batches.
*/
var batches = [
// the cool kids
{
sl_chrome: {
base: 'SauceLabs',
browserName: 'chrome',
platform: 'Windows 7'
},
sl_firefox: {
base: 'SauceLabs',
browserName: 'firefox'
},
sl_mac_safari: {
base: 'SauceLabs',
browserName: 'safari',
platform: 'OS X 10.10'
}
},
// ie family
{
sl_ie_9: {
base: 'SauceLabs',
browserName: 'internet explorer',
platform: 'Windows 7',
version: '9'
},
sl_ie_10: {
base: 'SauceLabs',
browserName: 'internet explorer',
platform: 'Windows 8',
version: '10'
},
sl_ie_11: {
base: 'SauceLabs',
browserName: 'internet explorer',
platform: 'Windows 8.1',
version: '11'
},
sl_edge: {
base: 'SauceLabs',
browserName: 'MicrosoftEdge',
platform: 'Windows 10'
}
},
// mobile
{
sl_ios_safari_9: {
base: 'SauceLabs',
browserName: 'iphone',
version: '10.3'
},
sl_android_6_0: {
base: 'SauceLabs',
browserName: 'android',
version: '6.0'
}
}
]
module.exports = function (config) {
var batch = batches[process.argv[4] || 0]
config.set(Object.assign(base, {
singleRun: true,
browsers: Object.keys(batch),
customLaunchers: batch,
reporters: process.env.CI
? ['dots', 'saucelabs'] // avoid spamming CI output
: ['progress', 'saucelabs'],
sauceLabs: {
testName: 'Vue.js unit tests',
recordScreenshots: false,
connectOptions: {
'no-ssl-bump-domains': 'all' // Ignore SSL error on Android emulator
},
build: process.env.CIRCLE_BUILD_NUM || process.env.SAUCE_BUILD_ID || Date.now()
},
// mobile emulators are really slow
captureTimeout: 300000,
browserNoActivityTimeout: 300000,
plugins: base.plugins.concat([
'karma-sauce-launcher'
])
}))
}
node-vue-template-compiler-2.4.2+dfsg/test/unit/karma.unit.config.js000066400000000000000000000005461361753775300254400ustar00rootroot00000000000000var base = require('./karma.base.config.js')
module.exports = function (config) {
config.set(Object.assign(base, {
browsers: ['Chrome', 'Firefox', 'Safari'],
reporters: ['progress'],
singleRun: true,
plugins: base.plugins.concat([
'karma-chrome-launcher',
'karma-firefox-launcher',
'karma-safari-launcher'
])
}))
}
node-vue-template-compiler-2.4.2+dfsg/test/unit/modules/000077500000000000000000000000001361753775300232305ustar00rootroot00000000000000node-vue-template-compiler-2.4.2+dfsg/test/unit/modules/compiler/000077500000000000000000000000001361753775300250425ustar00rootroot00000000000000node-vue-template-compiler-2.4.2+dfsg/test/unit/modules/compiler/codegen.spec.js000066400000000000000000000426751361753775300277530ustar00rootroot00000000000000import { parse } from 'compiler/parser/index'
import { optimize } from 'compiler/optimizer'
import { generate } from 'compiler/codegen'
import { isObject, extend } from 'shared/util'
import { isReservedTag } from 'web/util/index'
import { baseOptions } from 'web/compiler/options'
function assertCodegen (template, generatedCode, ...args) {
let staticRenderFnCodes = []
let generateOptions = baseOptions
let proc = null
let len = args.length
while (len--) {
const arg = args[len]
if (Array.isArray(arg)) {
staticRenderFnCodes = arg
} else if (isObject(arg)) {
generateOptions = arg
} else if (typeof arg === 'function') {
proc = arg
}
}
const ast = parse(template, baseOptions)
optimize(ast, baseOptions)
proc && proc(ast)
const res = generate(ast, generateOptions)
expect(res.render).toBe(generatedCode)
expect(res.staticRenderFns).toEqual(staticRenderFnCodes)
}
/* eslint-disable quotes */
describe('codegen', () => {
it('generate directive', () => {
assertCodegen(
'
',
`with(this){return _c('p',{directives:[{name:"custom1",rawName:"v-custom1:arg1.modifier",value:(value1),expression:"value1",arg:"arg1",modifiers:{"modifier":true}},{name:"custom2",rawName:"v-custom2"}]})}`
)
})
it('generate filters', () => {
assertCodegen(
'{{ d | e | f }}
',
`with(this){return _c('div',{attrs:{"id":_f("c")(_f("b")(a))}},[_v(_s(_f("f")(_f("e")(d))))])}`
)
})
it('generate v-for directive', () => {
assertCodegen(
'
',
`with(this){return _c('div',_l((items),function(item){return _c('li',{key:item.uid})}))}`
)
// iterator syntax
assertCodegen(
'
',
`with(this){return _c('div',_l((items),function(item,i){return _c('li')}))}`
)
assertCodegen(
'
',
`with(this){return _c('div',_l((items),function(item,key,index){return _c('li')}))}`
)
// destructuring
assertCodegen(
'
',
`with(this){return _c('div',_l((items),function({ a, b }){return _c('li')}))}`
)
assertCodegen(
'
',
`with(this){return _c('div',_l((items),function({ a, b },key,index){return _c('li')}))}`
)
// v-for with extra element
assertCodegen(
'',
`with(this){return _c('div',[_c('p'),_l((items),function(item){return _c('li')})],2)}`
)
})
it('generate v-if directive', () => {
assertCodegen(
'hello
',
`with(this){return (show)?_c('p',[_v("hello")]):_e()}`
)
})
it('generate v-else directive', () => {
assertCodegen(
'',
`with(this){return _c('div',[(show)?_c('p',[_v("hello")]):_c('p',[_v("world")])])}`
)
})
it('generate v-else-if directive', () => {
assertCodegen(
'',
`with(this){return _c('div',[(show)?_c('p',[_v("hello")]):(hide)?_c('p',[_v("world")]):_e()])}`
)
})
it('generate v-else-if with v-else directive', () => {
assertCodegen(
'',
`with(this){return _c('div',[(show)?_c('p',[_v("hello")]):(hide)?_c('p',[_v("world")]):_c('p',[_v("bye")])])}`
)
})
it('generate multi v-else-if with v-else directive', () => {
assertCodegen(
'',
`with(this){return _c('div',[(show)?_c('p',[_v("hello")]):(hide)?_c('p',[_v("world")]):(3)?_c('p',[_v("elseif")]):_c('p',[_v("bye")])])}`
)
})
it('generate ref', () => {
assertCodegen(
'
',
`with(this){return _c('p',{ref:"component1"})}`
)
})
it('generate ref on v-for', () => {
assertCodegen(
'',
`with(this){return _c('ul',_l((items),function(item){return _c('li',{ref:"component1",refInFor:true})}))}`
)
})
it('generate v-bind directive', () => {
assertCodegen(
'
',
`with(this){return _c('p',_b({},'p',test,false))}`
)
})
it('generate v-bind with prop directive', () => {
assertCodegen(
'
',
`with(this){return _c('p',_b({},'p',test,true))}`
)
})
it('generate v-bind directive with sync modifier', () => {
assertCodegen(
'
',
`with(this){return _c('p',_b({},'p',test,false,true))}`
)
})
it('generate template tag', () => {
assertCodegen(
'',
`with(this){return _c('div',[[_c('p',[_v(_s(hello))])]],2)}`
)
})
it('generate single slot', () => {
assertCodegen(
'
',
`with(this){return _c('div',[_t("default")],2)}`
)
})
it('generate named slot', () => {
assertCodegen(
'
',
`with(this){return _c('div',[_t("one")],2)}`
)
})
it('generate slot fallback content', () => {
assertCodegen(
'',
`with(this){return _c('div',[_t("default",[_c('div',[_v("hi")])])],2)}`
)
})
it('generate slot target', () => {
assertCodegen(
'hello world
',
`with(this){return _c('p',{slot:"one"},[_v("hello world")])}`
)
})
it('generate class binding', () => {
// static
assertCodegen(
'hello world
',
`with(this){return _c('p',{staticClass:"class1"},[_v("hello world")])}`,
)
// dynamic
assertCodegen(
'hello world
',
`with(this){return _c('p',{class:class1},[_v("hello world")])}`
)
})
it('generate style binding', () => {
assertCodegen(
'hello world
',
`with(this){return _c('p',{style:(error)},[_v("hello world")])}`
)
})
it('generate v-show directive', () => {
assertCodegen(
'hello world
',
`with(this){return _c('p',{directives:[{name:"show",rawName:"v-show",value:(shown),expression:"shown"}]},[_v("hello world")])}`
)
})
it('generate DOM props with v-bind directive', () => {
// input + value
assertCodegen(
' ',
`with(this){return _c('input',{domProps:{"value":msg}})}`
)
// non input
assertCodegen(
'',
`with(this){return _c('p',{attrs:{"value":msg}})}`
)
})
it('generate attrs with v-bind directive', () => {
assertCodegen(
' ',
`with(this){return _c('input',{attrs:{"name":field1}})}`
)
})
it('generate static attrs', () => {
assertCodegen(
' ',
`with(this){return _c('input',{attrs:{"name":"field1"}})}`
)
})
it('generate events with v-on directive', () => {
assertCodegen(
' ',
`with(this){return _c('input',{on:{"input":onInput}})}`
)
})
it('generate events with keycode', () => {
assertCodegen(
' ',
`with(this){return _c('input',{on:{"input":function($event){if(!('button' in $event)&&_k($event.keyCode,"enter",13))return null;onInput($event)}}})}`
)
// multiple keycodes (delete)
assertCodegen(
' ',
`with(this){return _c('input',{on:{"input":function($event){if(!('button' in $event)&&_k($event.keyCode,"delete",[8,46]))return null;onInput($event)}}})}`
)
// multiple keycodes (chained)
assertCodegen(
' ',
`with(this){return _c('input',{on:{"keydown":function($event){if(!('button' in $event)&&_k($event.keyCode,"enter",13)&&_k($event.keyCode,"delete",[8,46]))return null;onInput($event)}}})}`
)
// number keycode
assertCodegen(
' ',
`with(this){return _c('input',{on:{"input":function($event){if(!('button' in $event)&&$event.keyCode!==13)return null;onInput($event)}}})}`
)
// custom keycode
assertCodegen(
' ',
`with(this){return _c('input',{on:{"input":function($event){if(!('button' in $event)&&_k($event.keyCode,"custom"))return null;onInput($event)}}})}`
)
})
it('generate events with generic modifiers', () => {
assertCodegen(
' ',
`with(this){return _c('input',{on:{"input":function($event){$event.stopPropagation();onInput($event)}}})}`
)
assertCodegen(
' ',
`with(this){return _c('input',{on:{"input":function($event){$event.preventDefault();onInput($event)}}})}`
)
assertCodegen(
' ',
`with(this){return _c('input',{on:{"input":function($event){if($event.target !== $event.currentTarget)return null;onInput($event)}}})}`
)
})
// Github Issues #5146
it('generate events with generic modifiers and keycode correct order', () => {
assertCodegen(
' ',
`with(this){return _c('input',{on:{"keydown":function($event){if(!('button' in $event)&&_k($event.keyCode,"enter",13))return null;$event.preventDefault();onInput($event)}}})}`
)
assertCodegen(
' ',
`with(this){return _c('input',{on:{"keydown":function($event){if(!('button' in $event)&&_k($event.keyCode,"enter",13))return null;$event.stopPropagation();onInput($event)}}})}`
)
})
it('generate events with mouse event modifiers', () => {
assertCodegen(
' ',
`with(this){return _c('input',{on:{"click":function($event){if(!$event.ctrlKey)return null;onClick($event)}}})}`
)
assertCodegen(
' ',
`with(this){return _c('input',{on:{"click":function($event){if(!$event.shiftKey)return null;onClick($event)}}})}`
)
assertCodegen(
' ',
`with(this){return _c('input',{on:{"click":function($event){if(!$event.altKey)return null;onClick($event)}}})}`
)
assertCodegen(
' ',
`with(this){return _c('input',{on:{"click":function($event){if(!$event.metaKey)return null;onClick($event)}}})}`
)
})
it('generate events with multiple modifiers', () => {
assertCodegen(
' ',
`with(this){return _c('input',{on:{"input":function($event){$event.stopPropagation();$event.preventDefault();if($event.target !== $event.currentTarget)return null;onInput($event)}}})}`
)
})
it('generate events with capture modifier', () => {
assertCodegen(
' ',
`with(this){return _c('input',{on:{"!input":function($event){onInput($event)}}})}`
)
})
it('generate events with once modifier', () => {
assertCodegen(
' ',
`with(this){return _c('input',{on:{"~input":function($event){onInput($event)}}})}`
)
})
it('generate events with capture and once modifier', () => {
assertCodegen(
' ',
`with(this){return _c('input',{on:{"~!input":function($event){onInput($event)}}})}`
)
})
it('generate events with once and capture modifier', () => {
assertCodegen(
' ',
`with(this){return _c('input',{on:{"~!input":function($event){onInput($event)}}})}`
)
})
it('generate events with inline statement', () => {
assertCodegen(
' ',
`with(this){return _c('input',{on:{"input":function($event){current++}}})}`
)
})
it('generate events with inline function expression', () => {
// normal function
assertCodegen(
' ',
`with(this){return _c('input',{on:{"input":function () { current++ }}})}`
)
// arrow with no args
assertCodegen(
' current++">',
`with(this){return _c('input',{on:{"input":()=>current++}})}`
)
// arrow with parens, single arg
assertCodegen(
' current++">',
`with(this){return _c('input',{on:{"input":(e) => current++}})}`
)
// arrow with parens, multi args
assertCodegen(
' current++">',
`with(this){return _c('input',{on:{"input":(a, b, c) => current++}})}`
)
// arrow with destructuring
assertCodegen(
' current++">',
`with(this){return _c('input',{on:{"input":({ a, b }) => current++}})}`
)
// arrow single arg no parens
assertCodegen(
' current++">',
`with(this){return _c('input',{on:{"input":e=>current++}})}`
)
// with modifiers
assertCodegen(
` current++">`,
`with(this){return _c('input',{on:{"keyup":function($event){if(!('button' in $event)&&_k($event.keyCode,"enter",13))return null;(e=>current++)($event)}}})}`
)
})
// #3893
it('should not treat handler with unexpected whitespace as inline statement', () => {
assertCodegen(
' ',
`with(this){return _c('input',{on:{"input": onInput }})}`
)
})
it('generate unhandled events', () => {
assertCodegen(
' ',
`with(this){return _c('input',{on:{"input":function(){}}})}`,
ast => {
ast.events.input = undefined
}
)
})
it('generate multiple event handlers', () => {
assertCodegen(
' ',
`with(this){return _c('input',{on:{"input":[function($event){current++},function($event){$event.stopPropagation();onInput($event)}]}})}`
)
})
it('generate component', () => {
assertCodegen(
'
hi
',
`with(this){return _c('my-component',{attrs:{"name":"mycomponent1","msg":msg},on:{"notify":onNotify}},[_c('div',[_v("hi")])])}`
)
})
it('generate svg component with children', () => {
assertCodegen(
' ',
`with(this){return _c('svg',[_c('my-comp',[_c('circle',{attrs:{"r":10}})])],1)}`
)
})
it('generate is attribute', () => {
assertCodegen(
'
',
`with(this){return _c("component1",{tag:"div"})}`
)
assertCodegen(
'
',
`with(this){return _c(component1,{tag:"div"})}`
)
})
it('generate component with inline-template', () => {
// have "inline-template'"
assertCodegen(
'hello world
',
`with(this){return _c('my-component',{inlineTemplate:{render:function(){with(this){return _m(0)}},staticRenderFns:[function(){with(this){return _c('p',[_c('span',[_v("hello world")])])}}]}})}`
)
// "have inline-template attrs, but not having exactly one child element
assertCodegen(
' ',
`with(this){return _c('my-component',{inlineTemplate:{render:function(){with(this){return _c('hr')}},staticRenderFns:[]}})}`
)
expect('Inline-template components must have exactly one child element.').toHaveBeenWarned()
})
it('generate static trees inside v-for', () => {
assertCodegen(
``,
`with(this){return _c('div',_l((10),function(i){return _c('div',[_m(0,true)])}))}`,
[`with(this){return _c('p',[_c('span')])}`]
)
})
it('generate component with v-for', () => {
// normalize type: 2
assertCodegen(
'{{ item }}
',
`with(this){return _c('div',[_c('child'),_l((list),function(item){return [_v(_s(item))]})],2)}`
)
})
it('generate component with comment', () => {
const options = extend({
comments: true
}, baseOptions)
const template = '
'
const generatedCode = `with(this){return _c('div',[_e("comment")])}`
const ast = parse(template, options)
optimize(ast, options)
const res = generate(ast, options)
expect(res.render).toBe(generatedCode)
})
// #6150
it('generate comments with special characters', () => {
const options = extend({
comments: true
}, baseOptions)
const template = '
'
const generatedCode = `with(this){return _c('div',[_e("\\n'comment'\\n")])}`
const ast = parse(template, options)
optimize(ast, options)
const res = generate(ast, options)
expect(res.render).toBe(generatedCode)
})
it('not specified ast type', () => {
const res = generate(null, baseOptions)
expect(res.render).toBe(`with(this){return _c("div")}`)
expect(res.staticRenderFns).toEqual([])
})
it('not specified directives option', () => {
assertCodegen(
'hello world
',
`with(this){return (show)?_c('p',[_v("hello world")]):_e()}`,
{ isReservedTag }
)
})
})
/* eslint-enable quotes */
node-vue-template-compiler-2.4.2+dfsg/test/unit/modules/compiler/compiler-options.spec.js000066400000000000000000000076501361753775300316440ustar00rootroot00000000000000import Vue from 'vue'
import { compile } from 'web/compiler'
import { getAndRemoveAttr } from 'compiler/helpers'
describe('compile options', () => {
it('should be compiled', () => {
const { render, staticRenderFns, errors } = compile(`
`, {
directives: {
validate (el, dir) {
if (dir.name === 'validate' && dir.arg) {
el.validate = {
field: dir.arg,
groups: dir.modifiers ? Object.keys(dir.modifiers) : []
}
}
}
},
modules: [{
transformNode (el) {
el.validators = el.validators || []
const validators = ['required', 'min', 'max', 'pattern', 'maxlength', 'minlength']
validators.forEach(name => {
const rule = getAndRemoveAttr(el, name)
if (rule !== undefined) {
el.validators.push({ name, rule })
}
})
},
genData (el) {
let data = ''
if (el.validate) {
data += `validate:${JSON.stringify(el.validate)},`
}
if (el.validators) {
data += `validators:${JSON.stringify(el.validators)},`
}
return data
},
transformCode (el, code) {
// check
if (!el.validate || !el.validators) {
return code
}
// setup validation result props
const result = { dirty: false } // define something other prop
el.validators.forEach(validator => {
result[validator.name] = null
})
// generate code
return `_c('validate',{props:{
field:${JSON.stringify(el.validate.field)},
groups:${JSON.stringify(el.validate.groups)},
validators:${JSON.stringify(el.validators)},
result:${JSON.stringify(result)},
child:${code}}
})`
}
}]
})
expect(render).not.toBeUndefined()
expect(staticRenderFns).toEqual([])
expect(errors).toEqual([])
const renderFn = new Function(render)
const vm = new Vue({
data: {
msg: 'hello'
},
components: {
validate: {
props: ['field', 'groups', 'validators', 'result', 'child'],
render (h) {
return this.child
},
computed: {
valid () {
let ret = true
for (let i = 0; i > this.validators.length; i++) {
const { name } = this.validators[i]
if (!this.result[name]) {
ret = false
break
}
}
return ret
}
},
mounted () {
// initialize validation
const value = this.$el.value
this.validators.forEach(validator => {
const ret = this[validator.name](value, validator.rule)
this.result[validator.name] = ret
})
},
methods: {
// something validators logic
required (val) {
return val.length > 0
},
max (val, rule) {
return !(parseInt(val, 10) > parseInt(rule, 10))
}
}
}
},
render: renderFn,
staticRenderFns
}).$mount()
expect(vm.$el.innerHTML).toBe(' ')
expect(vm.$children[0].valid).toBe(true)
})
it('should collect errors', () => {
let compiled = compile('hello')
expect(compiled.errors.length).toBe(1)
expect(compiled.errors[0]).toContain('root element')
compiled = compile('{{ b++++ }}
')
expect(compiled.errors.length).toBe(2)
expect(compiled.errors[0]).toContain('invalid expression: v-if="a----"')
expect(compiled.errors[1]).toContain('invalid expression: {{ b++++ }}')
})
})
node-vue-template-compiler-2.4.2+dfsg/test/unit/modules/compiler/optimizer.spec.js000066400000000000000000000224521361753775300303600ustar00rootroot00000000000000import { parse } from 'compiler/parser/index'
import { extend } from 'shared/util'
import { optimize } from 'compiler/optimizer'
import { baseOptions } from 'web/compiler/options'
describe('optimizer', () => {
it('simple', () => {
const ast = parse('hello world ', baseOptions)
optimize(ast, baseOptions)
expect(ast.static).toBe(true) // h1
expect(ast.staticRoot).toBe(true)
expect(ast.children[0].static).toBe(true) // span
})
it('simple with comment', () => {
const options = extend({
comments: true
}, baseOptions)
const ast = parse('hello world ', options)
optimize(ast, options)
expect(ast.static).toBe(true) // h1
expect(ast.staticRoot).toBe(true)
expect(ast.children.length).toBe(2)
expect(ast.children[0].static).toBe(true) // span
expect(ast.children[1].static).toBe(true) // comment
})
it('skip simple nodes', () => {
const ast = parse('hello ', baseOptions)
optimize(ast, baseOptions)
expect(ast.static).toBe(true)
expect(ast.staticRoot).toBe(false) // this is too simple to warrant a static tree
})
it('interpolation', () => {
const ast = parse('{{msg}} ', baseOptions)
optimize(ast, baseOptions)
expect(ast.static).toBe(false) // h1
expect(ast.children[0].static).toBe(false) // text node with interpolation
})
it('nested elements', () => {
const ast = parse('', baseOptions)
optimize(ast, baseOptions)
// ul
expect(ast.static).toBe(true)
expect(ast.staticRoot).toBe(true)
// li
expect(ast.children[0].static).toBe(true) // first
expect(ast.children[1].static).toBe(true) // second
// text node inside li
expect(ast.children[0].children[0].static).toBe(true) // first
expect(ast.children[1].children[0].static).toBe(true) // second
})
it('nested complex elements', () => {
const ast = parse('', baseOptions)
optimize(ast, baseOptions)
// ul
expect(ast.static).toBe(false) // ul
// li
expect(ast.children[0].static).toBe(false) // first
expect(ast.children[1].static).toBe(true) // second
expect(ast.children[2].static).toBe(false) // third
// text node inside li
expect(ast.children[0].children[0].static).toBe(false) // first
expect(ast.children[1].children[0].static).toBe(true) // second
expect(ast.children[2].children[0].static).toBe(false) // third
})
it('v-if directive', () => {
const ast = parse('', baseOptions)
optimize(ast, baseOptions)
expect(ast.static).toBe(false)
expect(ast.children[0].static).toBe(true)
})
it('v-else directive', () => {
const ast = parse('', baseOptions)
optimize(ast, baseOptions)
expect(ast.static).toBe(false)
expect(ast.children[0].static).toBe(false)
expect(ast.children[0].ifConditions[0].block.static).toBe(false)
expect(ast.children[0].ifConditions[1].block.static).toBe(false)
expect(ast.children[0].ifConditions[0].block.children[0].static).toBe(true)
expect(ast.children[0].ifConditions[1].block.children[0].static).toBe(true)
})
it('v-pre directive', () => {
const ast = parse('', baseOptions)
optimize(ast, baseOptions)
expect(ast.static).toBe(true)
expect(ast.staticRoot).toBe(true)
expect(ast.children[0].static).toBe(true)
expect(ast.children[1].static).toBe(true)
expect(ast.children[0].children[0].static).toBe(true)
expect(ast.children[1].children[0].static).toBe(true)
})
it('v-for directive', () => {
const ast = parse('', baseOptions)
optimize(ast, baseOptions)
// ul
expect(ast.static).toBe(false)
// li with v-for
expect(ast.children[0].static).toBe(false)
expect(ast.children[0].children[0].static).toBe(false)
})
it('v-once directive', () => {
const ast = parse('{{msg}}
', baseOptions)
optimize(ast, baseOptions)
expect(ast.static).toBe(false) // p
expect(ast.children[0].static).toBe(false) // text node
})
it('single slot', () => {
const ast = parse('hello
', baseOptions)
optimize(ast, baseOptions)
expect(ast.children[0].static).toBe(false) // slot
expect(ast.children[0].children[0].static).toBe(true) // text node
})
it('named slot', () => {
const ast = parse('hello world
', baseOptions)
optimize(ast, baseOptions)
expect(ast.children[0].static).toBe(false) // slot
expect(ast.children[0].children[0].static).toBe(true) // text node
})
it('slot target', () => {
const ast = parse('hello world
', baseOptions)
optimize(ast, baseOptions)
expect(ast.static).toBe(false) // slot
expect(ast.children[0].static).toBe(true) // text node
})
it('component', () => {
const ast = parse(' ', baseOptions)
optimize(ast, baseOptions)
expect(ast.static).toBe(false) // component
})
it('component for inline-template', () => {
const ast = parse('hello world
{{msg}}
', baseOptions)
optimize(ast, baseOptions)
// component
expect(ast.static).toBe(false) // component
// p
expect(ast.children[0].static).toBe(true) // first
expect(ast.children[1].static).toBe(false) // second
// text node inside p
expect(ast.children[0].children[0].static).toBe(true) // first
expect(ast.children[1].children[0].static).toBe(false) // second
})
it('class binding', () => {
const ast = parse('hello world
', baseOptions)
optimize(ast, baseOptions)
expect(ast.static).toBe(false)
expect(ast.children[0].static).toBe(true)
})
it('style binding', () => {
const ast = parse('{{msg}}
', baseOptions)
optimize(ast, baseOptions)
expect(ast.static).toBe(false)
expect(ast.children[0].static).toBe(false)
})
it('key', () => {
const ast = parse('hello world
', baseOptions)
optimize(ast, baseOptions)
expect(ast.static).toBe(false)
expect(ast.children[0].static).toBe(true)
})
it('ref', () => {
const ast = parse('hello world
', baseOptions)
optimize(ast, baseOptions)
expect(ast.static).toBe(false)
expect(ast.children[0].static).toBe(true)
})
it('transition', () => {
const ast = parse('hello world
', baseOptions)
optimize(ast, baseOptions)
expect(ast.static).toBe(false)
expect(ast.children[0].static).toBe(true)
})
it('v-bind directive', () => {
const ast = parse(' ', baseOptions)
optimize(ast, baseOptions)
expect(ast.static).toBe(false)
})
it('v-on directive', () => {
const ast = parse(' ', baseOptions)
optimize(ast, baseOptions)
expect(ast.static).toBe(false)
})
it('custom directive', () => {
const ast = parse('', baseOptions)
optimize(ast, baseOptions)
expect(ast.static).toBe(false)
expect(ast.children[0].static).toBe(false)
})
it('not root ast', () => {
const ast = null
optimize(ast, baseOptions)
expect(ast).toBe(null)
})
it('not specified isReservedTag option', () => {
const ast = parse('hello world ', baseOptions)
optimize(ast, {})
expect(ast.static).toBe(false)
})
it('mark static trees inside v-for', () => {
const ast = parse(``, baseOptions)
optimize(ast, baseOptions)
expect(ast.children[0].children[0].staticRoot).toBe(true)
expect(ast.children[0].children[0].staticInFor).toBe(true)
})
it('mark static trees inside v-for with nested v-else and v-once', () => {
const ast = parse(`
`, baseOptions)
optimize(ast, baseOptions)
expect(ast.ifConditions[1].block.children[0].children[0].ifConditions[1].block.staticRoot).toBe(false)
expect(ast.ifConditions[1].block.children[0].children[0].ifConditions[1].block.staticInFor).toBe(true)
expect(ast.ifConditions[1].block.children[0].children[0].ifConditions[2].block.staticRoot).toBe(false)
expect(ast.ifConditions[1].block.children[0].children[0].ifConditions[2].block.staticInFor).toBe(true)
expect(ast.ifConditions[2].block.children[0].children[0].ifConditions[1].block.staticRoot).toBe(false)
expect(ast.ifConditions[2].block.children[0].children[0].ifConditions[1].block.staticInFor).toBe(true)
})
})
node-vue-template-compiler-2.4.2+dfsg/test/unit/modules/compiler/parser.spec.js000066400000000000000000000536441361753775300276410ustar00rootroot00000000000000import { parse } from 'compiler/parser/index'
import { extend } from 'shared/util'
import { baseOptions } from 'web/compiler/options'
import { isIE, isEdge } from 'core/util/env'
describe('parser', () => {
it('simple element', () => {
const ast = parse('hello world ', baseOptions)
expect(ast.tag).toBe('h1')
expect(ast.plain).toBe(true)
expect(ast.children[0].text).toBe('hello world')
})
it('interpolation in element', () => {
const ast = parse('{{msg}} ', baseOptions)
expect(ast.tag).toBe('h1')
expect(ast.plain).toBe(true)
expect(ast.children[0].expression).toBe('_s(msg)')
})
it('child elements', () => {
const ast = parse('', baseOptions)
expect(ast.tag).toBe('ul')
expect(ast.plain).toBe(true)
expect(ast.children[0].tag).toBe('li')
expect(ast.children[0].plain).toBe(true)
expect(ast.children[0].children[0].text).toBe('hello world')
expect(ast.children[0].parent).toBe(ast)
})
it('unary element', () => {
const ast = parse(' ', baseOptions)
expect(ast.tag).toBe('hr')
expect(ast.plain).toBe(true)
expect(ast.children.length).toBe(0)
})
it('svg element', () => {
const ast = parse('hello world ', baseOptions)
expect(ast.tag).toBe('svg')
expect(ast.ns).toBe('svg')
expect(ast.plain).toBe(true)
expect(ast.children[0].tag).toBe('text')
expect(ast.children[0].children[0].text).toBe('hello world')
expect(ast.children[0].parent).toBe(ast)
})
it('camelCase element', () => {
const ast = parse('hello world
', baseOptions)
expect(ast.tag).toBe('MyComponent')
expect(ast.plain).toBe(true)
expect(ast.children[0].tag).toBe('p')
expect(ast.children[0].plain).toBe(true)
expect(ast.children[0].children[0].text).toBe('hello world')
expect(ast.children[0].parent).toBe(ast)
})
it('forbidden element', () => {
// style
const styleAst = parse('', baseOptions)
expect(styleAst.tag).toBe('style')
expect(styleAst.plain).toBe(true)
expect(styleAst.forbidden).toBe(true)
expect(styleAst.children[0].text).toBe('error { color: red; }')
expect('Templates should only be responsible for mapping the state').toHaveBeenWarned()
// script
const scriptAst = parse('', baseOptions)
expect(scriptAst.tag).toBe('script')
expect(scriptAst.plain).toBe(false)
expect(scriptAst.forbidden).toBe(true)
expect(scriptAst.children[0].text).toBe('alert("hello world!")')
expect('Templates should only be responsible for mapping the state').toHaveBeenWarned()
})
it('not contain root element', () => {
parse('hello world', baseOptions)
expect('Component template requires a root element, rather than just text').toHaveBeenWarned()
})
it('warn text before root element', () => {
parse('before root {{ interpolation }}
', baseOptions)
expect('text "before root {{ interpolation }}" outside root element will be ignored.').toHaveBeenWarned()
})
it('warn text after root element', () => {
parse('
after root {{ interpolation }}', baseOptions)
expect('text "after root {{ interpolation }}" outside root element will be ignored.').toHaveBeenWarned()
})
it('warn multiple root elements', () => {
parse('
', baseOptions)
expect('Component template should contain exactly one root element').toHaveBeenWarned()
})
it('remove duplicate whitespace text nodes caused by comments', () => {
const ast = parse(``, baseOptions)
expect(ast.children.length).toBe(3)
expect(ast.children[0].tag).toBe('a')
expect(ast.children[1].text).toBe(' ')
expect(ast.children[2].tag).toBe('a')
})
it('remove text nodes between v-if conditions', () => {
const ast = parse(``, baseOptions)
expect(ast.children.length).toBe(3)
expect(ast.children[0].tag).toBe('div')
expect(ast.children[0].ifConditions.length).toBe(3)
expect(ast.children[1].text).toBe(' ') // text
expect(ast.children[2].tag).toBe('span')
})
it('warn non whitespace text between v-if conditions', () => {
parse(``, baseOptions)
expect(`text "foo" between v-if and v-else(-if) will be ignored`).toHaveBeenWarned()
})
it('not warn 2 root elements with v-if and v-else', () => {
parse('
', baseOptions)
expect('Component template should contain exactly one root element')
.not.toHaveBeenWarned()
})
it('not warn 3 root elements with v-if, v-else-if and v-else', () => {
parse('
', baseOptions)
expect('Component template should contain exactly one root element')
.not.toHaveBeenWarned()
})
it('not warn 2 root elements with v-if and v-else on separate lines', () => {
parse(`
`, baseOptions)
expect('Component template should contain exactly one root element')
.not.toHaveBeenWarned()
})
it('not warn 3 or more root elements with v-if, v-else-if and v-else on separate lines', () => {
parse(`
`, baseOptions)
expect('Component template should contain exactly one root element')
.not.toHaveBeenWarned()
parse(`
`, baseOptions)
expect('Component template should contain exactly one root element')
.not.toHaveBeenWarned()
})
it('generate correct ast for 2 root elements with v-if and v-else on separate lines', () => {
const ast = parse(`
`, baseOptions)
expect(ast.tag).toBe('div')
expect(ast.ifConditions[1].block.tag).toBe('p')
})
it('generate correct ast for 3 or more root elements with v-if and v-else on separate lines', () => {
const ast = parse(`
`, baseOptions)
expect(ast.tag).toBe('div')
expect(ast.ifConditions[0].block.tag).toBe('div')
expect(ast.ifConditions[1].block.tag).toBe('span')
expect(ast.ifConditions[2].block.tag).toBe('p')
const astMore = parse(`
`, baseOptions)
expect(astMore.tag).toBe('div')
expect(astMore.ifConditions[0].block.tag).toBe('div')
expect(astMore.ifConditions[1].block.tag).toBe('span')
expect(astMore.ifConditions[2].block.tag).toBe('div')
expect(astMore.ifConditions[3].block.tag).toBe('span')
expect(astMore.ifConditions[4].block.tag).toBe('p')
})
it('warn 2 root elements with v-if', () => {
parse('
', baseOptions)
expect('Component template should contain exactly one root element').toHaveBeenWarned()
})
it('warn 3 root elements with v-if and v-else on first 2', () => {
parse('
', baseOptions)
expect('Component template should contain exactly one root element').toHaveBeenWarned()
})
it('warn 3 root elements with v-if and v-else-if on first 2', () => {
parse('
', baseOptions)
expect('Component template should contain exactly one root element').toHaveBeenWarned()
})
it('warn 4 root elements with v-if, v-else-if and v-else on first 2', () => {
parse('
', baseOptions)
expect('Component template should contain exactly one root element').toHaveBeenWarned()
})
it('warn 2 root elements with v-if and v-else with v-for on 2nd', () => {
parse('
', baseOptions)
expect('Cannot use v-for on stateful component root element because it renders multiple elements')
.toHaveBeenWarned()
})
it('warn 2 root elements with v-if and v-else-if with v-for on 2nd', () => {
parse('
', baseOptions)
expect('Cannot use v-for on stateful component root element because it renders multiple elements')
.toHaveBeenWarned()
})
it('warn as root element', () => {
parse(' ', baseOptions)
expect('Cannot use as component root element').toHaveBeenWarned()
})
it('warn as root element', () => {
parse(' ', baseOptions)
expect('Cannot use as component root element').toHaveBeenWarned()
})
it('warn v-for on root element', () => {
parse('
', baseOptions)
expect('Cannot use v-for on stateful component root element').toHaveBeenWarned()
})
it('warn key', () => {
parse('
', baseOptions)
expect(' cannot be keyed').toHaveBeenWarned()
})
it('v-pre directive', () => {
const ast = parse('', baseOptions)
expect(ast.pre).toBe(true)
expect(ast.attrs[0].name).toBe('id')
expect(ast.attrs[0].value).toBe('"message1"')
expect(ast.children[0].children[0].text).toBe('{{msg}}')
})
it('v-for directive basic syntax', () => {
const ast = parse('', baseOptions)
const liAst = ast.children[0]
expect(liAst.for).toBe('items')
expect(liAst.alias).toBe('item')
})
it('v-for directive iteration syntax', () => {
const ast = parse('', baseOptions)
const liAst = ast.children[0]
expect(liAst.for).toBe('items')
expect(liAst.alias).toBe('item')
expect(liAst.iterator1).toBe('index')
expect(liAst.iterator2).toBeUndefined()
})
it('v-for directive iteration syntax (multiple)', () => {
const ast = parse('', baseOptions)
const liAst = ast.children[0]
expect(liAst.for).toBe('items')
expect(liAst.alias).toBe('item')
expect(liAst.iterator1).toBe('key')
expect(liAst.iterator2).toBe('index')
})
it('v-for directive key', () => {
const ast = parse('', baseOptions)
const liAst = ast.children[0]
expect(liAst.for).toBe('items')
expect(liAst.alias).toBe('item')
expect(liAst.key).toBe('item.uid')
})
it('v-for directive invalid syntax', () => {
parse('', baseOptions)
expect('Invalid v-for expression').toHaveBeenWarned()
})
it('v-if directive syntax', () => {
const ast = parse('hello world
', baseOptions)
expect(ast.if).toBe('show')
expect(ast.ifConditions[0].exp).toBe('show')
})
it('v-else-if directive syntax', () => {
const ast = parse('', baseOptions)
const ifAst = ast.children[0]
const conditionsAst = ifAst.ifConditions
expect(conditionsAst.length).toBe(3)
expect(conditionsAst[1].block.children[0].text).toBe('elseif')
expect(conditionsAst[1].block.parent).toBe(ast)
expect(conditionsAst[2].block.children[0].text).toBe('world')
expect(conditionsAst[2].block.parent).toBe(ast)
})
it('v-else directive syntax', () => {
const ast = parse('', baseOptions)
const ifAst = ast.children[0]
const conditionsAst = ifAst.ifConditions
expect(conditionsAst.length).toBe(2)
expect(conditionsAst[1].block.children[0].text).toBe('world')
expect(conditionsAst[1].block.parent).toBe(ast)
})
it('v-else-if directive invalid syntax', () => {
parse('', baseOptions)
expect('v-else-if="1" used on element').toHaveBeenWarned()
})
it('v-else directive invalid syntax', () => {
parse('', baseOptions)
expect('v-else used on element').toHaveBeenWarned()
})
it('v-once directive syntax', () => {
const ast = parse('world
', baseOptions)
expect(ast.once).toBe(true)
})
it('slot tag single syntax', () => {
const ast = parse('
', baseOptions)
expect(ast.children[0].tag).toBe('slot')
expect(ast.children[0].slotName).toBeUndefined()
})
it('slot tag named syntax', () => {
const ast = parse('hello world
', baseOptions)
expect(ast.children[0].tag).toBe('slot')
expect(ast.children[0].slotName).toBe('"one"')
})
it('slot target', () => {
const ast = parse('hello world
', baseOptions)
expect(ast.slotTarget).toBe('"one"')
})
it('component properties', () => {
const ast = parse(' ', baseOptions)
expect(ast.attrs[0].name).toBe('msg')
expect(ast.attrs[0].value).toBe('hello')
})
it('component "is" attribute', () => {
const ast = parse(' ', baseOptions)
expect(ast.component).toBe('"component1"')
})
it('component "inline-template" attribute', () => {
const ast = parse('hello world ', baseOptions)
expect(ast.inlineTemplate).toBe(true)
})
it('class binding', () => {
// static
const ast1 = parse('hello world
', baseOptions)
expect(ast1.staticClass).toBe('"class1"')
// dynamic
const ast2 = parse('hello world
', baseOptions)
expect(ast2.classBinding).toBe('class1')
// interpolation warning
parse('hello world
', baseOptions)
expect('Interpolation inside attributes has been removed').toHaveBeenWarned()
})
it('style binding', () => {
const ast = parse('hello world
', baseOptions)
expect(ast.styleBinding).toBe('error')
})
it('attribute with v-bind', () => {
const ast = parse(' ', baseOptions)
expect(ast.attrsList[0].name).toBe('type')
expect(ast.attrsList[0].value).toBe('text')
expect(ast.attrsList[1].name).toBe('name')
expect(ast.attrsList[1].value).toBe('field1')
expect(ast.attrsMap['type']).toBe('text')
expect(ast.attrsMap['name']).toBe('field1')
expect(ast.attrs[0].name).toBe('type')
expect(ast.attrs[0].value).toBe('"text"')
expect(ast.attrs[1].name).toBe('name')
expect(ast.attrs[1].value).toBe('"field1"')
expect(ast.props[0].name).toBe('value')
expect(ast.props[0].value).toBe('msg')
})
it('attribute with v-on', () => {
const ast = parse(' ', baseOptions)
expect(ast.events.input.value).toBe('onInput')
})
it('attribute with directive', () => {
const ast = parse(' ', baseOptions)
expect(ast.directives[0].name).toBe('validate')
expect(ast.directives[0].value).toBe('required')
expect(ast.directives[0].arg).toBe('field1')
})
it('attribute with modifiered directive', () => {
const ast = parse(' ', baseOptions)
expect(ast.directives[0].modifiers.on).toBe(true)
expect(ast.directives[0].modifiers.off).toBe(true)
})
it('literal attribute', () => {
// basic
const ast1 = parse(' ', baseOptions)
expect(ast1.attrsList[0].name).toBe('type')
expect(ast1.attrsList[0].value).toBe('text')
expect(ast1.attrsList[1].name).toBe('name')
expect(ast1.attrsList[1].value).toBe('field1')
expect(ast1.attrsList[2].name).toBe('value')
expect(ast1.attrsList[2].value).toBe('hello world')
expect(ast1.attrsMap['type']).toBe('text')
expect(ast1.attrsMap['name']).toBe('field1')
expect(ast1.attrsMap['value']).toBe('hello world')
expect(ast1.attrs[0].name).toBe('type')
expect(ast1.attrs[0].value).toBe('"text"')
expect(ast1.attrs[1].name).toBe('name')
expect(ast1.attrs[1].value).toBe('"field1"')
expect(ast1.attrs[2].name).toBe('value')
expect(ast1.attrs[2].value).toBe('"hello world"')
// interpolation warning
parse(' ', baseOptions)
expect('Interpolation inside attributes has been removed').toHaveBeenWarned()
})
if (!isIE && !isEdge) {
it('duplicate attribute', () => {
parse('hello world
', baseOptions)
expect('duplicate attribute').toHaveBeenWarned()
})
}
it('custom delimiter', () => {
const ast = parse('{msg}
', extend({ delimiters: ['{', '}'] }, baseOptions))
expect(ast.children[0].expression).toBe('_s(msg)')
})
it('not specified getTagNamespace option', () => {
const options = extend({}, baseOptions)
delete options.getTagNamespace
const ast = parse('hello world ', options)
expect(ast.tag).toBe('svg')
expect(ast.ns).toBeUndefined()
})
it('not specified mustUseProp', () => {
const options = extend({}, baseOptions)
delete options.mustUseProp
const ast = parse(' ', options)
expect(ast.props).toBeUndefined()
})
it('use prop when prop modifier was explicitly declared', () => {
const ast = parse('', baseOptions)
expect(ast.attrs).toBeUndefined()
expect(ast.props.length).toBe(1)
expect(ast.props[0].name).toBe('value')
expect(ast.props[0].value).toBe('val')
})
it('pre/post transforms', () => {
const options = extend({}, baseOptions)
const spy1 = jasmine.createSpy('preTransform')
const spy2 = jasmine.createSpy('postTransform')
options.modules = options.modules.concat([{
preTransformNode (el) {
spy1(el.tag)
},
postTransformNode (el) {
expect(el.attrs.length).toBe(1)
spy2(el.tag)
}
}])
parse(' ', options)
expect(spy1).toHaveBeenCalledWith('img')
expect(spy2).toHaveBeenCalledWith('img')
})
it('preserve whitespace in tag', function () {
const options = extend({}, baseOptions)
const ast = parse(' \nhi \n
', options)
const code = ast.children[0]
expect(code.children[0].type).toBe(3)
expect(code.children[0].text).toBe(' \n')
expect(code.children[2].type).toBe(3)
expect(code.children[2].text).toBe('\n ')
const span = ast.children[1]
expect(span.children[0].type).toBe(3)
expect(span.children[0].text).toBe(' ')
})
// #5992
it('ignore the first newline in tag', function () {
const options = extend({}, baseOptions)
const ast = parse('', options)
const pre = ast.children[0]
expect(pre.children[0].type).toBe(3)
expect(pre.children[0].text).toBe('abc')
const text = ast.children[1]
expect(text.type).toBe(3)
expect(text.text).toBe('\ndef')
const pre2 = ast.children[2]
expect(pre2.children[0].type).toBe(3)
expect(pre2.children[0].text).toBe('\nabc')
})
it('forgivingly handle < in plain text', () => {
const options = extend({}, baseOptions)
const ast = parse('1 < 2 < 3
', options)
expect(ast.tag).toBe('p')
expect(ast.children.length).toBe(1)
expect(ast.children[0].type).toBe(3)
expect(ast.children[0].text).toBe('1 < 2 < 3')
})
it('IE conditional comments', () => {
const options = extend({}, baseOptions)
const ast = parse(`
`, options)
expect(ast.tag).toBe('div')
expect(ast.children.length).toBe(0)
})
it('parse content in textarea as text', () => {
const options = extend({}, baseOptions)
const whitespace = parse(`
`, options)
expect(whitespace.tag).toBe('textarea')
expect(whitespace.children.length).toBe(1)
expect(whitespace.children[0].type).toBe(3)
// textarea is whitespace sensitive
expect(whitespace.children[0].text).toBe(` Test 1
test2
`)
const comment = parse('', options)
expect(comment.tag).toBe('textarea')
expect(comment.children.length).toBe(1)
expect(comment.children[0].type).toBe(3)
expect(comment.children[0].text).toBe('')
})
// #5526
it('should not decode text in script tags', () => {
const options = extend({}, baseOptions)
const ast = parse(``, options)
expect(ast.children[0].text).toBe(`><`)
})
it('should ignore comments', () => {
const options = extend({}, baseOptions)
const ast = parse(`123
`, options)
expect(ast.tag).toBe('div')
expect(ast.children.length).toBe(1)
expect(ast.children[0].type).toBe(3)
expect(ast.children[0].text).toBe('123')
})
it('should kept comments', () => {
const options = extend({
comments: true
}, baseOptions)
const ast = parse(`123
`, options)
expect(ast.tag).toBe('div')
expect(ast.children.length).toBe(2)
expect(ast.children[0].type).toBe(3)
expect(ast.children[0].text).toBe('123')
expect(ast.children[1].type).toBe(3) // parse comment with ASTText
expect(ast.children[1].isComment).toBe(true) // parse comment with ASTText
expect(ast.children[1].text).toBe('comment here')
})
})
node-vue-template-compiler-2.4.2+dfsg/test/unit/modules/observer/000077500000000000000000000000001361753775300250575ustar00rootroot00000000000000node-vue-template-compiler-2.4.2+dfsg/test/unit/modules/observer/observer.spec.js000066400000000000000000000233351361753775300302030ustar00rootroot00000000000000import Vue from 'vue'
import {
Observer,
observe,
set as setProp,
del as delProp
} from 'core/observer/index'
import Dep from 'core/observer/dep'
import { hasOwn } from 'core/util/index'
describe('Observer', () => {
it('create on non-observables', () => {
// skip primitive value
const ob1 = observe(1)
expect(ob1).toBeUndefined()
// avoid vue instance
const ob2 = observe(new Vue())
expect(ob2).toBeUndefined()
// avoid frozen objects
const ob3 = observe(Object.freeze({}))
expect(ob3).toBeUndefined()
})
it('create on object', () => {
// on object
const obj = {
a: {},
b: {}
}
const ob1 = observe(obj)
expect(ob1 instanceof Observer).toBe(true)
expect(ob1.value).toBe(obj)
expect(obj.__ob__).toBe(ob1)
// should've walked children
expect(obj.a.__ob__ instanceof Observer).toBe(true)
expect(obj.b.__ob__ instanceof Observer).toBe(true)
// should return existing ob on already observed objects
const ob2 = observe(obj)
expect(ob2).toBe(ob1)
})
it('create on null', () => {
// on null
const obj = Object.create(null)
obj.a = {}
obj.b = {}
const ob1 = observe(obj)
expect(ob1 instanceof Observer).toBe(true)
expect(ob1.value).toBe(obj)
expect(obj.__ob__).toBe(ob1)
// should've walked children
expect(obj.a.__ob__ instanceof Observer).toBe(true)
expect(obj.b.__ob__ instanceof Observer).toBe(true)
// should return existing ob on already observed objects
const ob2 = observe(obj)
expect(ob2).toBe(ob1)
})
it('create on already observed object', () => {
// on object
const obj = {}
let val = 0
let getCount = 0
Object.defineProperty(obj, 'a', {
configurable: true,
enumerable: true,
get () {
getCount++
return val
},
set (v) { val = v }
})
const ob1 = observe(obj)
expect(ob1 instanceof Observer).toBe(true)
expect(ob1.value).toBe(obj)
expect(obj.__ob__).toBe(ob1)
getCount = 0
// Each read of 'a' should result in only one get underlying get call
obj.a
expect(getCount).toBe(1)
obj.a
expect(getCount).toBe(2)
// should return existing ob on already observed objects
const ob2 = observe(obj)
expect(ob2).toBe(ob1)
// should call underlying setter
obj.a = 10
expect(val).toBe(10)
})
it('create on property with only getter', () => {
// on object
const obj = {}
Object.defineProperty(obj, 'a', {
configurable: true,
enumerable: true,
get () { return 123 }
})
const ob1 = observe(obj)
expect(ob1 instanceof Observer).toBe(true)
expect(ob1.value).toBe(obj)
expect(obj.__ob__).toBe(ob1)
// should be able to read
expect(obj.a).toBe(123)
// should return existing ob on already observed objects
const ob2 = observe(obj)
expect(ob2).toBe(ob1)
// since there is no setter, you shouldn't be able to write to it
// PhantomJS throws when a property with no setter is set
// but other real browsers don't
try {
obj.a = 101
} catch (e) {}
expect(obj.a).toBe(123)
})
it('create on property with only setter', () => {
// on object
const obj = {}
let val = 10
Object.defineProperty(obj, 'a', { // eslint-disable-line accessor-pairs
configurable: true,
enumerable: true,
set (v) { val = v }
})
const ob1 = observe(obj)
expect(ob1 instanceof Observer).toBe(true)
expect(ob1.value).toBe(obj)
expect(obj.__ob__).toBe(ob1)
// reads should return undefined
expect(obj.a).toBe(undefined)
// should return existing ob on already observed objects
const ob2 = observe(obj)
expect(ob2).toBe(ob1)
// writes should call the set function
obj.a = 100
expect(val).toBe(100)
})
it('create on property which is marked not configurable', () => {
// on object
const obj = {}
Object.defineProperty(obj, 'a', {
configurable: false,
enumerable: true,
val: 10
})
const ob1 = observe(obj)
expect(ob1 instanceof Observer).toBe(true)
expect(ob1.value).toBe(obj)
expect(obj.__ob__).toBe(ob1)
})
it('create on array', () => {
// on object
const arr = [{}, {}]
const ob1 = observe(arr)
expect(ob1 instanceof Observer).toBe(true)
expect(ob1.value).toBe(arr)
expect(arr.__ob__).toBe(ob1)
// should've walked children
expect(arr[0].__ob__ instanceof Observer).toBe(true)
expect(arr[1].__ob__ instanceof Observer).toBe(true)
})
it('observing object prop change', () => {
const obj = { a: { b: 2 }, c: NaN }
observe(obj)
// mock a watcher!
const watcher = {
deps: [],
addDep (dep) {
this.deps.push(dep)
dep.addSub(this)
},
update: jasmine.createSpy()
}
// collect dep
Dep.target = watcher
obj.a.b
Dep.target = null
expect(watcher.deps.length).toBe(3) // obj.a + a + a.b
obj.a.b = 3
expect(watcher.update.calls.count()).toBe(1)
// swap object
obj.a = { b: 4 }
expect(watcher.update.calls.count()).toBe(2)
watcher.deps = []
Dep.target = watcher
obj.a.b
obj.c
Dep.target = null
expect(watcher.deps.length).toBe(4)
// set on the swapped object
obj.a.b = 5
expect(watcher.update.calls.count()).toBe(3)
// should not trigger on NaN -> NaN set
obj.c = NaN
expect(watcher.update.calls.count()).toBe(3)
})
it('observing object prop change on defined property', () => {
const obj = { val: 2 }
Object.defineProperty(obj, 'a', {
configurable: true,
enumerable: true,
get () { return this.val },
set (v) {
this.val = v
return this.val
}
})
observe(obj)
// mock a watcher!
const watcher = {
deps: [],
addDep: function (dep) {
this.deps.push(dep)
dep.addSub(this)
},
update: jasmine.createSpy()
}
// collect dep
Dep.target = watcher
expect(obj.a).toBe(2) // Make sure 'this' is preserved
Dep.target = null
obj.a = 3
expect(obj.val).toBe(3) // make sure 'setter' was called
obj.val = 5
expect(obj.a).toBe(5) // make sure 'getter' was called
})
it('observing set/delete', () => {
const obj1 = { a: 1 }
const ob1 = observe(obj1)
const dep1 = ob1.dep
spyOn(dep1, 'notify')
setProp(obj1, 'b', 2)
expect(obj1.b).toBe(2)
expect(dep1.notify.calls.count()).toBe(1)
delProp(obj1, 'a')
expect(hasOwn(obj1, 'a')).toBe(false)
expect(dep1.notify.calls.count()).toBe(2)
// set existing key, should be a plain set and not
// trigger own ob's notify
setProp(obj1, 'b', 3)
expect(obj1.b).toBe(3)
expect(dep1.notify.calls.count()).toBe(2)
// set non-existing key
setProp(obj1, 'c', 1)
expect(obj1.c).toBe(1)
expect(dep1.notify.calls.count()).toBe(3)
// should ignore deleting non-existing key
delProp(obj1, 'a')
expect(dep1.notify.calls.count()).toBe(3)
// should work on non-observed objects
const obj2 = { a: 1 }
delProp(obj2, 'a')
expect(hasOwn(obj2, 'a')).toBe(false)
// should work on Object.create(null)
const obj3 = Object.create(null)
obj3.a = 1
const ob3 = observe(obj3)
const dep3 = ob3.dep
spyOn(dep3, 'notify')
setProp(obj3, 'b', 2)
expect(obj3.b).toBe(2)
expect(dep3.notify.calls.count()).toBe(1)
delProp(obj3, 'a')
expect(hasOwn(obj3, 'a')).toBe(false)
expect(dep3.notify.calls.count()).toBe(2)
// set and delete non-numeric key on array
const arr2 = ['a']
const ob2 = observe(arr2)
const dep2 = ob2.dep
spyOn(dep2, 'notify')
setProp(arr2, 'b', 2)
expect(arr2.b).toBe(2)
expect(dep2.notify.calls.count()).toBe(1)
delProp(arr2, 'b')
expect(hasOwn(arr2, 'b')).toBe(false)
expect(dep2.notify.calls.count()).toBe(2)
})
it('warning set/delete on a Vue instance', done => {
const vm = new Vue({
template: '{{a}}
',
data: { a: 1 }
}).$mount()
expect(vm.$el.outerHTML).toBe('1
')
Vue.set(vm, 'a', 2)
waitForUpdate(() => {
expect(vm.$el.outerHTML).toBe('2
')
expect('Avoid adding reactive properties to a Vue instance').not.toHaveBeenWarned()
Vue.delete(vm, 'a')
}).then(() => {
expect('Avoid deleting properties on a Vue instance').toHaveBeenWarned()
expect(vm.$el.outerHTML).toBe('2
')
Vue.set(vm, 'b', 123)
expect('Avoid adding reactive properties to a Vue instance').toHaveBeenWarned()
}).then(done)
})
it('warning set/delete on Vue instance root $data', done => {
const data = { a: 1 }
const vm = new Vue({
template: '{{a}}
',
data
}).$mount()
expect(vm.$el.outerHTML).toBe('1
')
expect(Vue.set(data, 'a', 2)).toBe(2)
waitForUpdate(() => {
expect(vm.$el.outerHTML).toBe('2
')
expect('Avoid adding reactive properties to a Vue instance').not.toHaveBeenWarned()
Vue.delete(data, 'a')
}).then(() => {
expect('Avoid deleting properties on a Vue instance').toHaveBeenWarned()
expect(vm.$el.outerHTML).toBe('2
')
expect(Vue.set(data, 'b', 123)).toBe(123)
expect('Avoid adding reactive properties to a Vue instance').toHaveBeenWarned()
}).then(done)
})
it('observing array mutation', () => {
const arr = []
const ob = observe(arr)
const dep = ob.dep
spyOn(dep, 'notify')
const objs = [{}, {}, {}]
arr.push(objs[0])
arr.pop()
arr.unshift(objs[1])
arr.shift()
arr.splice(0, 0, objs[2])
arr.sort()
arr.reverse()
expect(dep.notify.calls.count()).toBe(7)
// inserted elements should be observed
objs.forEach(obj => {
expect(obj.__ob__ instanceof Observer).toBe(true)
})
})
})
node-vue-template-compiler-2.4.2+dfsg/test/unit/modules/observer/scheduler.spec.js000066400000000000000000000072171361753775300303330ustar00rootroot00000000000000import Vue from 'vue'
import {
MAX_UPDATE_COUNT,
queueWatcher as _queueWatcher
} from 'core/observer/scheduler'
function queueWatcher (watcher) {
watcher.vm = {} // mock vm
_queueWatcher(watcher)
}
describe('Scheduler', () => {
let spy
beforeEach(() => {
spy = jasmine.createSpy('scheduler')
})
it('queueWatcher', done => {
queueWatcher({
run: spy
})
waitForUpdate(() => {
expect(spy.calls.count()).toBe(1)
}).then(done)
})
it('dedup', done => {
queueWatcher({
id: 1,
run: spy
})
queueWatcher({
id: 1,
run: spy
})
waitForUpdate(() => {
expect(spy.calls.count()).toBe(1)
}).then(done)
})
it('allow duplicate when flushing', done => {
const job = {
id: 1,
run: spy
}
queueWatcher(job)
queueWatcher({
id: 2,
run () { queueWatcher(job) }
})
waitForUpdate(() => {
expect(spy.calls.count()).toBe(2)
}).then(done)
})
it('call user watchers before component re-render', done => {
const calls = []
const vm = new Vue({
data: {
a: 1
},
template: '{{ a }}
',
watch: {
a () { calls.push(1) }
},
beforeUpdate () {
calls.push(2)
}
}).$mount()
vm.a = 2
waitForUpdate(() => {
expect(calls).toEqual([1, 2])
}).then(done)
})
it('call user watcher triggered by component re-render immediately', done => {
// this happens when a component re-render updates the props of a child
const calls = []
const vm = new Vue({
data: {
a: 1
},
watch: {
a () {
calls.push(1)
}
},
beforeUpdate () {
calls.push(2)
},
template: '
',
components: {
test: {
props: ['a'],
template: '{{ a }}
',
watch: {
a () {
calls.push(3)
}
},
beforeUpdate () {
calls.push(4)
}
}
}
}).$mount()
vm.a = 2
waitForUpdate(() => {
expect(calls).toEqual([1, 2, 3, 4])
}).then(done)
})
it('warn against infinite update loops', function (done) {
let count = 0
const job = {
id: 1,
run () {
count++
queueWatcher(job)
}
}
queueWatcher(job)
waitForUpdate(() => {
expect(count).toBe(MAX_UPDATE_COUNT + 1)
expect('infinite update loop').toHaveBeenWarned()
}).then(done)
})
it('should call newly pushed watcher after current watcher is done', done => {
const callOrder = []
queueWatcher({
id: 1,
user: true,
run () {
callOrder.push(1)
queueWatcher({
id: 2,
run () {
callOrder.push(3)
}
})
callOrder.push(2)
}
})
waitForUpdate(() => {
expect(callOrder).toEqual([1, 2, 3])
}).then(done)
})
// Github issue #5191
it('emit should work when updated hook called', done => {
const el = document.createElement('div')
const vm = new Vue({
template: `
`,
data: {
foo: 0
},
methods: {
bar: spy
},
components: {
child: {
template: `{{foo}}
`,
props: ['foo'],
updated () {
this.$emit('change')
}
}
}
}).$mount(el)
vm.$nextTick(() => {
vm.foo = 1
vm.$nextTick(() => {
expect(vm.$el.innerHTML).toBe('1
')
expect(spy).toHaveBeenCalled()
done()
})
})
})
})
node-vue-template-compiler-2.4.2+dfsg/test/unit/modules/observer/watcher.spec.js000066400000000000000000000113771361753775300300140ustar00rootroot00000000000000import Vue from 'vue'
import Watcher from 'core/observer/watcher'
describe('Watcher', () => {
let vm, spy
beforeEach(() => {
vm = new Vue({
template: '
',
data: {
a: 1,
b: {
c: 2,
d: 4
},
c: 'c',
msg: 'yo'
}
}).$mount()
spy = jasmine.createSpy('watcher')
})
it('path', done => {
const watcher = new Watcher(vm, 'b.c', spy)
expect(watcher.value).toBe(2)
vm.b.c = 3
waitForUpdate(() => {
expect(watcher.value).toBe(3)
expect(spy).toHaveBeenCalledWith(3, 2)
vm.b = { c: 4 } // swapping the object
}).then(() => {
expect(watcher.value).toBe(4)
expect(spy).toHaveBeenCalledWith(4, 3)
}).then(done)
})
it('non-existent path, set later', done => {
const watcher1 = new Watcher(vm, 'b.e', spy)
expect(watcher1.value).toBeUndefined()
// check $add should not affect isolated children
const child2 = new Vue({ parent: vm })
const watcher2 = new Watcher(child2, 'b.e', spy)
expect(watcher2.value).toBeUndefined()
Vue.set(vm.b, 'e', 123)
waitForUpdate(() => {
expect(watcher1.value).toBe(123)
expect(watcher2.value).toBeUndefined()
expect(spy.calls.count()).toBe(1)
expect(spy).toHaveBeenCalledWith(123, undefined)
}).then(done)
})
it('delete', done => {
const watcher = new Watcher(vm, 'b.c', spy)
expect(watcher.value).toBe(2)
Vue.delete(vm.b, 'c')
waitForUpdate(() => {
expect(watcher.value).toBeUndefined()
expect(spy).toHaveBeenCalledWith(undefined, 2)
}).then(done)
})
it('path containing $data', done => {
const watcher = new Watcher(vm, '$data.b.c', spy)
expect(watcher.value).toBe(2)
vm.b = { c: 3 }
waitForUpdate(() => {
expect(watcher.value).toBe(3)
expect(spy).toHaveBeenCalledWith(3, 2)
vm.$data.b.c = 4
}).then(() => {
expect(watcher.value).toBe(4)
expect(spy).toHaveBeenCalledWith(4, 3)
}).then(done)
})
it('deep watch', done => {
let oldB
new Watcher(vm, 'b', spy, {
deep: true
})
vm.b.c = { d: 4 }
waitForUpdate(() => {
expect(spy).toHaveBeenCalledWith(vm.b, vm.b)
oldB = vm.b
vm.b = { c: [{ a: 1 }] }
}).then(() => {
expect(spy).toHaveBeenCalledWith(vm.b, oldB)
expect(spy.calls.count()).toBe(2)
vm.b.c[0].a = 2
}).then(() => {
expect(spy).toHaveBeenCalledWith(vm.b, vm.b)
expect(spy.calls.count()).toBe(3)
}).then(done)
})
it('deep watch $data', done => {
new Watcher(vm, '$data', spy, {
deep: true
})
vm.b.c = 3
waitForUpdate(() => {
expect(spy).toHaveBeenCalledWith(vm.$data, vm.$data)
}).then(done)
})
it('deep watch with circular references', done => {
new Watcher(vm, 'b', spy, {
deep: true
})
Vue.set(vm.b, '_', vm.b)
waitForUpdate(() => {
expect(spy).toHaveBeenCalledWith(vm.b, vm.b)
expect(spy.calls.count()).toBe(1)
vm.b._.c = 1
}).then(() => {
expect(spy).toHaveBeenCalledWith(vm.b, vm.b)
expect(spy.calls.count()).toBe(2)
}).then(done)
})
it('fire change for prop addition/deletion in non-deep mode', done => {
new Watcher(vm, 'b', spy)
Vue.set(vm.b, 'e', 123)
waitForUpdate(() => {
expect(spy).toHaveBeenCalledWith(vm.b, vm.b)
expect(spy.calls.count()).toBe(1)
Vue.delete(vm.b, 'e')
}).then(() => {
expect(spy.calls.count()).toBe(2)
}).then(done)
})
it('watch function', done => {
const watcher = new Watcher(vm, function () {
return this.a + this.b.d
}, spy)
expect(watcher.value).toBe(5)
vm.a = 2
waitForUpdate(() => {
expect(spy).toHaveBeenCalledWith(6, 5)
vm.b = { d: 2 }
}).then(() => {
expect(spy).toHaveBeenCalledWith(4, 6)
}).then(done)
})
it('lazy mode', done => {
const watcher = new Watcher(vm, function () {
return this.a + this.b.d
}, null, { lazy: true })
expect(watcher.lazy).toBe(true)
expect(watcher.value).toBeUndefined()
expect(watcher.dirty).toBe(true)
watcher.evaluate()
expect(watcher.value).toBe(5)
expect(watcher.dirty).toBe(false)
vm.a = 2
waitForUpdate(() => {
expect(watcher.value).toBe(5)
expect(watcher.dirty).toBe(true)
watcher.evaluate()
expect(watcher.value).toBe(6)
expect(watcher.dirty).toBe(false)
}).then(done)
})
it('teardown', done => {
const watcher = new Watcher(vm, 'b.c', spy)
watcher.teardown()
vm.b.c = 3
waitForUpdate(() => {
expect(watcher.active).toBe(false)
expect(spy).not.toHaveBeenCalled()
}).then(done)
})
it('warn not support path', () => {
new Watcher(vm, 'd.e + c', spy)
expect('Failed watching path:').toHaveBeenWarned()
})
})
node-vue-template-compiler-2.4.2+dfsg/test/unit/modules/server-compiler/000077500000000000000000000000001361753775300263465ustar00rootroot00000000000000node-vue-template-compiler-2.4.2+dfsg/test/unit/modules/server-compiler/optimizer.spec.js000066400000000000000000000000001361753775300316450ustar00rootroot00000000000000node-vue-template-compiler-2.4.2+dfsg/test/unit/modules/sfc/000077500000000000000000000000001361753775300240035ustar00rootroot00000000000000node-vue-template-compiler-2.4.2+dfsg/test/unit/modules/sfc/sfc-parser.spec.js000066400000000000000000000126651361753775300273510ustar00rootroot00000000000000import { parseComponent } from 'sfc/parser'
describe('Single File Component parser', () => {
it('should parse', () => {
const res = parseComponent(`
hi
`)
expect(res.template.content.trim()).toBe('hi
')
expect(res.styles.length).toBe(4)
expect(res.styles[0].src).toBe('./test.css')
expect(res.styles[1].lang).toBe('stylus')
expect(res.styles[1].scoped).toBe(true)
expect(res.styles[1].content.trim()).toBe('h1\n color red\nh2\n color green')
expect(res.styles[2].module).toBe(true)
expect(res.styles[3].attrs['bool-attr']).toBe(true)
expect(res.styles[3].attrs['val-attr']).toBe('test')
expect(res.script.content.trim()).toBe('export default {}')
})
it('should parse template with closed input', () => {
const res = parseComponent(`
`)
expect(res.template.content.trim()).toBe(' ')
})
it('should handle nested template', () => {
const res = parseComponent(`
hi
`)
expect(res.template.content.trim()).toBe('hi
')
})
it('pad content', () => {
const content = `
`
const padDefault = parseComponent(content.trim(), { pad: true })
const padLine = parseComponent(content.trim(), { pad: 'line' })
const padSpace = parseComponent(content.trim(), { pad: 'space' })
expect(padDefault.script.content).toBe(Array(3 + 1).join('//\n') + '\nexport default {}\n')
expect(padDefault.styles[0].content).toBe(Array(6 + 1).join('\n') + '\nh1 { color: red }\n')
expect(padLine.script.content).toBe(Array(3 + 1).join('//\n') + '\nexport default {}\n')
expect(padLine.styles[0].content).toBe(Array(6 + 1).join('\n') + '\nh1 { color: red }\n')
expect(padSpace.script.content).toBe(`