runtime-dom.cjs.js 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', { value: true });
  3. var runtimeCore = require('@vue/runtime-core');
  4. var shared = require('@vue/shared');
  5. const svgNS = 'http://www.w3.org/2000/svg';
  6. const doc = (typeof document !== 'undefined' ? document : null);
  7. const templateContainer = doc && /*#__PURE__*/ doc.createElement('template');
  8. const nodeOps = {
  9. insert: (child, parent, anchor) => {
  10. parent.insertBefore(child, anchor || null);
  11. },
  12. remove: child => {
  13. const parent = child.parentNode;
  14. if (parent) {
  15. parent.removeChild(child);
  16. }
  17. },
  18. createElement: (tag, isSVG, is, props) => {
  19. const el = isSVG
  20. ? doc.createElementNS(svgNS, tag)
  21. : doc.createElement(tag, is ? { is } : undefined);
  22. if (tag === 'select' && props && props.multiple != null) {
  23. el.setAttribute('multiple', props.multiple);
  24. }
  25. return el;
  26. },
  27. createText: text => doc.createTextNode(text),
  28. createComment: text => doc.createComment(text),
  29. setText: (node, text) => {
  30. node.nodeValue = text;
  31. },
  32. setElementText: (el, text) => {
  33. el.textContent = text;
  34. },
  35. parentNode: node => node.parentNode,
  36. nextSibling: node => node.nextSibling,
  37. querySelector: selector => doc.querySelector(selector),
  38. setScopeId(el, id) {
  39. el.setAttribute(id, '');
  40. },
  41. cloneNode(el) {
  42. const cloned = el.cloneNode(true);
  43. // #3072
  44. // - in `patchDOMProp`, we store the actual value in the `el._value` property.
  45. // - normally, elements using `:value` bindings will not be hoisted, but if
  46. // the bound value is a constant, e.g. `:value="true"` - they do get
  47. // hoisted.
  48. // - in production, hoisted nodes are cloned when subsequent inserts, but
  49. // cloneNode() does not copy the custom property we attached.
  50. // - This may need to account for other custom DOM properties we attach to
  51. // elements in addition to `_value` in the future.
  52. if (`_value` in el) {
  53. cloned._value = el._value;
  54. }
  55. return cloned;
  56. },
  57. // __UNSAFE__
  58. // Reason: innerHTML.
  59. // Static content here can only come from compiled templates.
  60. // As long as the user only uses trusted templates, this is safe.
  61. insertStaticContent(content, parent, anchor, isSVG, start, end) {
  62. // <parent> before | first ... last | anchor </parent>
  63. const before = anchor ? anchor.previousSibling : parent.lastChild;
  64. // #5308 can only take cached path if:
  65. // - has a single root node
  66. // - nextSibling info is still available
  67. if (start && (start === end || start.nextSibling)) {
  68. // cached
  69. while (true) {
  70. parent.insertBefore(start.cloneNode(true), anchor);
  71. if (start === end || !(start = start.nextSibling))
  72. break;
  73. }
  74. }
  75. else {
  76. // fresh insert
  77. templateContainer.innerHTML = isSVG ? `<svg>${content}</svg>` : content;
  78. const template = templateContainer.content;
  79. if (isSVG) {
  80. // remove outer svg wrapper
  81. const wrapper = template.firstChild;
  82. while (wrapper.firstChild) {
  83. template.appendChild(wrapper.firstChild);
  84. }
  85. template.removeChild(wrapper);
  86. }
  87. parent.insertBefore(template, anchor);
  88. }
  89. return [
  90. // first
  91. before ? before.nextSibling : parent.firstChild,
  92. // last
  93. anchor ? anchor.previousSibling : parent.lastChild
  94. ];
  95. }
  96. };
  97. // compiler should normalize class + :class bindings on the same element
  98. // into a single binding ['staticClass', dynamic]
  99. function patchClass(el, value, isSVG) {
  100. // directly setting className should be faster than setAttribute in theory
  101. // if this is an element during a transition, take the temporary transition
  102. // classes into account.
  103. const transitionClasses = el._vtc;
  104. if (transitionClasses) {
  105. value = (value ? [value, ...transitionClasses] : [...transitionClasses]).join(' ');
  106. }
  107. if (value == null) {
  108. el.removeAttribute('class');
  109. }
  110. else if (isSVG) {
  111. el.setAttribute('class', value);
  112. }
  113. else {
  114. el.className = value;
  115. }
  116. }
  117. function patchStyle(el, prev, next) {
  118. const style = el.style;
  119. const isCssString = shared.isString(next);
  120. if (next && !isCssString) {
  121. for (const key in next) {
  122. setStyle(style, key, next[key]);
  123. }
  124. if (prev && !shared.isString(prev)) {
  125. for (const key in prev) {
  126. if (next[key] == null) {
  127. setStyle(style, key, '');
  128. }
  129. }
  130. }
  131. }
  132. else {
  133. const currentDisplay = style.display;
  134. if (isCssString) {
  135. if (prev !== next) {
  136. style.cssText = next;
  137. }
  138. }
  139. else if (prev) {
  140. el.removeAttribute('style');
  141. }
  142. // indicates that the `display` of the element is controlled by `v-show`,
  143. // so we always keep the current `display` value regardless of the `style`
  144. // value, thus handing over control to `v-show`.
  145. if ('_vod' in el) {
  146. style.display = currentDisplay;
  147. }
  148. }
  149. }
  150. const importantRE = /\s*!important$/;
  151. function setStyle(style, name, val) {
  152. if (shared.isArray(val)) {
  153. val.forEach(v => setStyle(style, name, v));
  154. }
  155. else {
  156. if (val == null)
  157. val = '';
  158. if (name.startsWith('--')) {
  159. // custom property definition
  160. style.setProperty(name, val);
  161. }
  162. else {
  163. const prefixed = autoPrefix(style, name);
  164. if (importantRE.test(val)) {
  165. // !important
  166. style.setProperty(shared.hyphenate(prefixed), val.replace(importantRE, ''), 'important');
  167. }
  168. else {
  169. style[prefixed] = val;
  170. }
  171. }
  172. }
  173. }
  174. const prefixes = ['Webkit', 'Moz', 'ms'];
  175. const prefixCache = {};
  176. function autoPrefix(style, rawName) {
  177. const cached = prefixCache[rawName];
  178. if (cached) {
  179. return cached;
  180. }
  181. let name = runtimeCore.camelize(rawName);
  182. if (name !== 'filter' && name in style) {
  183. return (prefixCache[rawName] = name);
  184. }
  185. name = shared.capitalize(name);
  186. for (let i = 0; i < prefixes.length; i++) {
  187. const prefixed = prefixes[i] + name;
  188. if (prefixed in style) {
  189. return (prefixCache[rawName] = prefixed);
  190. }
  191. }
  192. return rawName;
  193. }
  194. const xlinkNS = 'http://www.w3.org/1999/xlink';
  195. function patchAttr(el, key, value, isSVG, instance) {
  196. if (isSVG && key.startsWith('xlink:')) {
  197. if (value == null) {
  198. el.removeAttributeNS(xlinkNS, key.slice(6, key.length));
  199. }
  200. else {
  201. el.setAttributeNS(xlinkNS, key, value);
  202. }
  203. }
  204. else {
  205. // note we are only checking boolean attributes that don't have a
  206. // corresponding dom prop of the same name here.
  207. const isBoolean = shared.isSpecialBooleanAttr(key);
  208. if (value == null || (isBoolean && !shared.includeBooleanAttr(value))) {
  209. el.removeAttribute(key);
  210. }
  211. else {
  212. el.setAttribute(key, isBoolean ? '' : value);
  213. }
  214. }
  215. }
  216. // __UNSAFE__
  217. // functions. The user is responsible for using them with only trusted content.
  218. function patchDOMProp(el, key, value,
  219. // the following args are passed only due to potential innerHTML/textContent
  220. // overriding existing VNodes, in which case the old tree must be properly
  221. // unmounted.
  222. prevChildren, parentComponent, parentSuspense, unmountChildren) {
  223. if (key === 'innerHTML' || key === 'textContent') {
  224. if (prevChildren) {
  225. unmountChildren(prevChildren, parentComponent, parentSuspense);
  226. }
  227. el[key] = value == null ? '' : value;
  228. return;
  229. }
  230. if (key === 'value' &&
  231. el.tagName !== 'PROGRESS' &&
  232. // custom elements may use _value internally
  233. !el.tagName.includes('-')) {
  234. // store value as _value as well since
  235. // non-string values will be stringified.
  236. el._value = value;
  237. const newValue = value == null ? '' : value;
  238. if (el.value !== newValue ||
  239. // #4956: always set for OPTION elements because its value falls back to
  240. // textContent if no value attribute is present. And setting .value for
  241. // OPTION has no side effect
  242. el.tagName === 'OPTION') {
  243. el.value = newValue;
  244. }
  245. if (value == null) {
  246. el.removeAttribute(key);
  247. }
  248. return;
  249. }
  250. let needRemove = false;
  251. if (value === '' || value == null) {
  252. const type = typeof el[key];
  253. if (type === 'boolean') {
  254. // e.g. <select multiple> compiles to { multiple: '' }
  255. value = shared.includeBooleanAttr(value);
  256. }
  257. else if (value == null && type === 'string') {
  258. // e.g. <div :id="null">
  259. value = '';
  260. needRemove = true;
  261. }
  262. else if (type === 'number') {
  263. // e.g. <img :width="null">
  264. // the value of some IDL attr must be greater than 0, e.g. input.size = 0 -> error
  265. value = 0;
  266. needRemove = true;
  267. }
  268. }
  269. // some properties perform value validation and throw,
  270. // some properties has getter, no setter, will error in 'use strict'
  271. // eg. <select :type="null"></select> <select :willValidate="null"></select>
  272. try {
  273. el[key] = value;
  274. }
  275. catch (e) {
  276. {
  277. runtimeCore.warn(`Failed setting prop "${key}" on <${el.tagName.toLowerCase()}>: ` +
  278. `value ${value} is invalid.`, e);
  279. }
  280. }
  281. needRemove && el.removeAttribute(key);
  282. }
  283. // Async edge case fix requires storing an event listener's attach timestamp.
  284. const [_getNow, skipTimestampCheck] = /*#__PURE__*/ (() => {
  285. let _getNow = Date.now;
  286. let skipTimestampCheck = false;
  287. if (typeof window !== 'undefined') {
  288. // Determine what event timestamp the browser is using. Annoyingly, the
  289. // timestamp can either be hi-res (relative to page load) or low-res
  290. // (relative to UNIX epoch), so in order to compare time we have to use the
  291. // same timestamp type when saving the flush timestamp.
  292. if (Date.now() > document.createEvent('Event').timeStamp) {
  293. // if the low-res timestamp which is bigger than the event timestamp
  294. // (which is evaluated AFTER) it means the event is using a hi-res timestamp,
  295. // and we need to use the hi-res version for event listeners as well.
  296. _getNow = () => performance.now();
  297. }
  298. // #3485: Firefox <= 53 has incorrect Event.timeStamp implementation
  299. // and does not fire microtasks in between event propagation, so safe to exclude.
  300. const ffMatch = navigator.userAgent.match(/firefox\/(\d+)/i);
  301. skipTimestampCheck = !!(ffMatch && Number(ffMatch[1]) <= 53);
  302. }
  303. return [_getNow, skipTimestampCheck];
  304. })();
  305. // To avoid the overhead of repeatedly calling performance.now(), we cache
  306. // and use the same timestamp for all event listeners attached in the same tick.
  307. let cachedNow = 0;
  308. const p = /*#__PURE__*/ Promise.resolve();
  309. const reset = () => {
  310. cachedNow = 0;
  311. };
  312. const getNow = () => cachedNow || (p.then(reset), (cachedNow = _getNow()));
  313. function addEventListener(el, event, handler, options) {
  314. el.addEventListener(event, handler, options);
  315. }
  316. function removeEventListener(el, event, handler, options) {
  317. el.removeEventListener(event, handler, options);
  318. }
  319. function patchEvent(el, rawName, prevValue, nextValue, instance = null) {
  320. // vei = vue event invokers
  321. const invokers = el._vei || (el._vei = {});
  322. const existingInvoker = invokers[rawName];
  323. if (nextValue && existingInvoker) {
  324. // patch
  325. existingInvoker.value = nextValue;
  326. }
  327. else {
  328. const [name, options] = parseName(rawName);
  329. if (nextValue) {
  330. // add
  331. const invoker = (invokers[rawName] = createInvoker(nextValue, instance));
  332. addEventListener(el, name, invoker, options);
  333. }
  334. else if (existingInvoker) {
  335. // remove
  336. removeEventListener(el, name, existingInvoker, options);
  337. invokers[rawName] = undefined;
  338. }
  339. }
  340. }
  341. const optionsModifierRE = /(?:Once|Passive|Capture)$/;
  342. function parseName(name) {
  343. let options;
  344. if (optionsModifierRE.test(name)) {
  345. options = {};
  346. let m;
  347. while ((m = name.match(optionsModifierRE))) {
  348. name = name.slice(0, name.length - m[0].length);
  349. options[m[0].toLowerCase()] = true;
  350. }
  351. }
  352. return [shared.hyphenate(name.slice(2)), options];
  353. }
  354. function createInvoker(initialValue, instance) {
  355. const invoker = (e) => {
  356. // async edge case #6566: inner click event triggers patch, event handler
  357. // attached to outer element during patch, and triggered again. This
  358. // happens because browsers fire microtask ticks between event propagation.
  359. // the solution is simple: we save the timestamp when a handler is attached,
  360. // and the handler would only fire if the event passed to it was fired
  361. // AFTER it was attached.
  362. const timeStamp = e.timeStamp || _getNow();
  363. if (skipTimestampCheck || timeStamp >= invoker.attached - 1) {
  364. runtimeCore.callWithAsyncErrorHandling(patchStopImmediatePropagation(e, invoker.value), instance, 5 /* NATIVE_EVENT_HANDLER */, [e]);
  365. }
  366. };
  367. invoker.value = initialValue;
  368. invoker.attached = getNow();
  369. return invoker;
  370. }
  371. function patchStopImmediatePropagation(e, value) {
  372. if (shared.isArray(value)) {
  373. const originalStop = e.stopImmediatePropagation;
  374. e.stopImmediatePropagation = () => {
  375. originalStop.call(e);
  376. e._stopped = true;
  377. };
  378. return value.map(fn => (e) => !e._stopped && fn && fn(e));
  379. }
  380. else {
  381. return value;
  382. }
  383. }
  384. const nativeOnRE = /^on[a-z]/;
  385. const patchProp = (el, key, prevValue, nextValue, isSVG = false, prevChildren, parentComponent, parentSuspense, unmountChildren) => {
  386. if (key === 'class') {
  387. patchClass(el, nextValue, isSVG);
  388. }
  389. else if (key === 'style') {
  390. patchStyle(el, prevValue, nextValue);
  391. }
  392. else if (shared.isOn(key)) {
  393. // ignore v-model listeners
  394. if (!shared.isModelListener(key)) {
  395. patchEvent(el, key, prevValue, nextValue, parentComponent);
  396. }
  397. }
  398. else if (key[0] === '.'
  399. ? ((key = key.slice(1)), true)
  400. : key[0] === '^'
  401. ? ((key = key.slice(1)), false)
  402. : shouldSetAsProp(el, key, nextValue, isSVG)) {
  403. patchDOMProp(el, key, nextValue, prevChildren, parentComponent, parentSuspense, unmountChildren);
  404. }
  405. else {
  406. // special case for <input v-model type="checkbox"> with
  407. // :true-value & :false-value
  408. // store value as dom properties since non-string values will be
  409. // stringified.
  410. if (key === 'true-value') {
  411. el._trueValue = nextValue;
  412. }
  413. else if (key === 'false-value') {
  414. el._falseValue = nextValue;
  415. }
  416. patchAttr(el, key, nextValue, isSVG);
  417. }
  418. };
  419. function shouldSetAsProp(el, key, value, isSVG) {
  420. if (isSVG) {
  421. // most keys must be set as attribute on svg elements to work
  422. // ...except innerHTML & textContent
  423. if (key === 'innerHTML' || key === 'textContent') {
  424. return true;
  425. }
  426. // or native onclick with function values
  427. if (key in el && nativeOnRE.test(key) && shared.isFunction(value)) {
  428. return true;
  429. }
  430. return false;
  431. }
  432. // these are enumerated attrs, however their corresponding DOM properties
  433. // are actually booleans - this leads to setting it with a string "false"
  434. // value leading it to be coerced to `true`, so we need to always treat
  435. // them as attributes.
  436. // Note that `contentEditable` doesn't have this problem: its DOM
  437. // property is also enumerated string values.
  438. if (key === 'spellcheck' || key === 'draggable' || key === 'translate') {
  439. return false;
  440. }
  441. // #1787, #2840 form property on form elements is readonly and must be set as
  442. // attribute.
  443. if (key === 'form') {
  444. return false;
  445. }
  446. // #1526 <input list> must be set as attribute
  447. if (key === 'list' && el.tagName === 'INPUT') {
  448. return false;
  449. }
  450. // #2766 <textarea type> must be set as attribute
  451. if (key === 'type' && el.tagName === 'TEXTAREA') {
  452. return false;
  453. }
  454. // native onclick with string value, must be set as attribute
  455. if (nativeOnRE.test(key) && shared.isString(value)) {
  456. return false;
  457. }
  458. return key in el;
  459. }
  460. function defineCustomElement(options, hydate) {
  461. const Comp = runtimeCore.defineComponent(options);
  462. class VueCustomElement extends VueElement {
  463. constructor(initialProps) {
  464. super(Comp, initialProps, hydate);
  465. }
  466. }
  467. VueCustomElement.def = Comp;
  468. return VueCustomElement;
  469. }
  470. const defineSSRCustomElement = ((options) => {
  471. // @ts-ignore
  472. return defineCustomElement(options, hydrate);
  473. });
  474. const BaseClass = (typeof HTMLElement !== 'undefined' ? HTMLElement : class {
  475. });
  476. class VueElement extends BaseClass {
  477. constructor(_def, _props = {}, hydrate) {
  478. super();
  479. this._def = _def;
  480. this._props = _props;
  481. /**
  482. * @internal
  483. */
  484. this._instance = null;
  485. this._connected = false;
  486. this._resolved = false;
  487. this._numberProps = null;
  488. if (this.shadowRoot && hydrate) {
  489. hydrate(this._createVNode(), this.shadowRoot);
  490. }
  491. else {
  492. if (this.shadowRoot) {
  493. runtimeCore.warn(`Custom element has pre-rendered declarative shadow root but is not ` +
  494. `defined as hydratable. Use \`defineSSRCustomElement\`.`);
  495. }
  496. this.attachShadow({ mode: 'open' });
  497. }
  498. }
  499. connectedCallback() {
  500. this._connected = true;
  501. if (!this._instance) {
  502. this._resolveDef();
  503. }
  504. }
  505. disconnectedCallback() {
  506. this._connected = false;
  507. runtimeCore.nextTick(() => {
  508. if (!this._connected) {
  509. render(null, this.shadowRoot);
  510. this._instance = null;
  511. }
  512. });
  513. }
  514. /**
  515. * resolve inner component definition (handle possible async component)
  516. */
  517. _resolveDef() {
  518. if (this._resolved) {
  519. return;
  520. }
  521. this._resolved = true;
  522. // set initial attrs
  523. for (let i = 0; i < this.attributes.length; i++) {
  524. this._setAttr(this.attributes[i].name);
  525. }
  526. // watch future attr changes
  527. new MutationObserver(mutations => {
  528. for (const m of mutations) {
  529. this._setAttr(m.attributeName);
  530. }
  531. }).observe(this, { attributes: true });
  532. const resolve = (def) => {
  533. const { props, styles } = def;
  534. const hasOptions = !shared.isArray(props);
  535. const rawKeys = props ? (hasOptions ? Object.keys(props) : props) : [];
  536. // cast Number-type props set before resolve
  537. let numberProps;
  538. if (hasOptions) {
  539. for (const key in this._props) {
  540. const opt = props[key];
  541. if (opt === Number || (opt && opt.type === Number)) {
  542. this._props[key] = shared.toNumber(this._props[key]);
  543. (numberProps || (numberProps = Object.create(null)))[key] = true;
  544. }
  545. }
  546. }
  547. this._numberProps = numberProps;
  548. // check if there are props set pre-upgrade or connect
  549. for (const key of Object.keys(this)) {
  550. if (key[0] !== '_') {
  551. this._setProp(key, this[key], true, false);
  552. }
  553. }
  554. // defining getter/setters on prototype
  555. for (const key of rawKeys.map(shared.camelize)) {
  556. Object.defineProperty(this, key, {
  557. get() {
  558. return this._getProp(key);
  559. },
  560. set(val) {
  561. this._setProp(key, val);
  562. }
  563. });
  564. }
  565. // apply CSS
  566. this._applyStyles(styles);
  567. // initial render
  568. this._update();
  569. };
  570. const asyncDef = this._def.__asyncLoader;
  571. if (asyncDef) {
  572. asyncDef().then(resolve);
  573. }
  574. else {
  575. resolve(this._def);
  576. }
  577. }
  578. _setAttr(key) {
  579. let value = this.getAttribute(key);
  580. if (this._numberProps && this._numberProps[key]) {
  581. value = shared.toNumber(value);
  582. }
  583. this._setProp(shared.camelize(key), value, false);
  584. }
  585. /**
  586. * @internal
  587. */
  588. _getProp(key) {
  589. return this._props[key];
  590. }
  591. /**
  592. * @internal
  593. */
  594. _setProp(key, val, shouldReflect = true, shouldUpdate = true) {
  595. if (val !== this._props[key]) {
  596. this._props[key] = val;
  597. if (shouldUpdate && this._instance) {
  598. this._update();
  599. }
  600. // reflect
  601. if (shouldReflect) {
  602. if (val === true) {
  603. this.setAttribute(shared.hyphenate(key), '');
  604. }
  605. else if (typeof val === 'string' || typeof val === 'number') {
  606. this.setAttribute(shared.hyphenate(key), val + '');
  607. }
  608. else if (!val) {
  609. this.removeAttribute(shared.hyphenate(key));
  610. }
  611. }
  612. }
  613. }
  614. _update() {
  615. render(this._createVNode(), this.shadowRoot);
  616. }
  617. _createVNode() {
  618. const vnode = runtimeCore.createVNode(this._def, shared.extend({}, this._props));
  619. if (!this._instance) {
  620. vnode.ce = instance => {
  621. this._instance = instance;
  622. instance.isCE = true;
  623. // HMR
  624. {
  625. instance.ceReload = newStyles => {
  626. // always reset styles
  627. if (this._styles) {
  628. this._styles.forEach(s => this.shadowRoot.removeChild(s));
  629. this._styles.length = 0;
  630. }
  631. this._applyStyles(newStyles);
  632. // if this is an async component, ceReload is called from the inner
  633. // component so no need to reload the async wrapper
  634. if (!this._def.__asyncLoader) {
  635. // reload
  636. this._instance = null;
  637. this._update();
  638. }
  639. };
  640. }
  641. // intercept emit
  642. instance.emit = (event, ...args) => {
  643. this.dispatchEvent(new CustomEvent(event, {
  644. detail: args
  645. }));
  646. };
  647. // locate nearest Vue custom element parent for provide/inject
  648. let parent = this;
  649. while ((parent =
  650. parent && (parent.parentNode || parent.host))) {
  651. if (parent instanceof VueElement) {
  652. instance.parent = parent._instance;
  653. break;
  654. }
  655. }
  656. };
  657. }
  658. return vnode;
  659. }
  660. _applyStyles(styles) {
  661. if (styles) {
  662. styles.forEach(css => {
  663. const s = document.createElement('style');
  664. s.textContent = css;
  665. this.shadowRoot.appendChild(s);
  666. // record for HMR
  667. {
  668. (this._styles || (this._styles = [])).push(s);
  669. }
  670. });
  671. }
  672. }
  673. }
  674. function useCssModule(name = '$style') {
  675. /* istanbul ignore else */
  676. {
  677. const instance = runtimeCore.getCurrentInstance();
  678. if (!instance) {
  679. runtimeCore.warn(`useCssModule must be called inside setup()`);
  680. return shared.EMPTY_OBJ;
  681. }
  682. const modules = instance.type.__cssModules;
  683. if (!modules) {
  684. runtimeCore.warn(`Current instance does not have CSS modules injected.`);
  685. return shared.EMPTY_OBJ;
  686. }
  687. const mod = modules[name];
  688. if (!mod) {
  689. runtimeCore.warn(`Current instance does not have CSS module named "${name}".`);
  690. return shared.EMPTY_OBJ;
  691. }
  692. return mod;
  693. }
  694. }
  695. /**
  696. * Runtime helper for SFC's CSS variable injection feature.
  697. * @private
  698. */
  699. function useCssVars(getter) {
  700. return;
  701. }
  702. const TRANSITION = 'transition';
  703. const ANIMATION = 'animation';
  704. // DOM Transition is a higher-order-component based on the platform-agnostic
  705. // base Transition component, with DOM-specific logic.
  706. const Transition = (props, { slots }) => runtimeCore.h(runtimeCore.BaseTransition, resolveTransitionProps(props), slots);
  707. Transition.displayName = 'Transition';
  708. const DOMTransitionPropsValidators = {
  709. name: String,
  710. type: String,
  711. css: {
  712. type: Boolean,
  713. default: true
  714. },
  715. duration: [String, Number, Object],
  716. enterFromClass: String,
  717. enterActiveClass: String,
  718. enterToClass: String,
  719. appearFromClass: String,
  720. appearActiveClass: String,
  721. appearToClass: String,
  722. leaveFromClass: String,
  723. leaveActiveClass: String,
  724. leaveToClass: String
  725. };
  726. const TransitionPropsValidators = (Transition.props =
  727. /*#__PURE__*/ shared.extend({}, runtimeCore.BaseTransition.props, DOMTransitionPropsValidators));
  728. /**
  729. * #3227 Incoming hooks may be merged into arrays when wrapping Transition
  730. * with custom HOCs.
  731. */
  732. const callHook = (hook, args = []) => {
  733. if (shared.isArray(hook)) {
  734. hook.forEach(h => h(...args));
  735. }
  736. else if (hook) {
  737. hook(...args);
  738. }
  739. };
  740. /**
  741. * Check if a hook expects a callback (2nd arg), which means the user
  742. * intends to explicitly control the end of the transition.
  743. */
  744. const hasExplicitCallback = (hook) => {
  745. return hook
  746. ? shared.isArray(hook)
  747. ? hook.some(h => h.length > 1)
  748. : hook.length > 1
  749. : false;
  750. };
  751. function resolveTransitionProps(rawProps) {
  752. const baseProps = {};
  753. for (const key in rawProps) {
  754. if (!(key in DOMTransitionPropsValidators)) {
  755. baseProps[key] = rawProps[key];
  756. }
  757. }
  758. if (rawProps.css === false) {
  759. return baseProps;
  760. }
  761. const { name = 'v', type, duration, enterFromClass = `${name}-enter-from`, enterActiveClass = `${name}-enter-active`, enterToClass = `${name}-enter-to`, appearFromClass = enterFromClass, appearActiveClass = enterActiveClass, appearToClass = enterToClass, leaveFromClass = `${name}-leave-from`, leaveActiveClass = `${name}-leave-active`, leaveToClass = `${name}-leave-to` } = rawProps;
  762. const durations = normalizeDuration(duration);
  763. const enterDuration = durations && durations[0];
  764. const leaveDuration = durations && durations[1];
  765. const { onBeforeEnter, onEnter, onEnterCancelled, onLeave, onLeaveCancelled, onBeforeAppear = onBeforeEnter, onAppear = onEnter, onAppearCancelled = onEnterCancelled } = baseProps;
  766. const finishEnter = (el, isAppear, done) => {
  767. removeTransitionClass(el, isAppear ? appearToClass : enterToClass);
  768. removeTransitionClass(el, isAppear ? appearActiveClass : enterActiveClass);
  769. done && done();
  770. };
  771. const finishLeave = (el, done) => {
  772. removeTransitionClass(el, leaveToClass);
  773. removeTransitionClass(el, leaveActiveClass);
  774. done && done();
  775. };
  776. const makeEnterHook = (isAppear) => {
  777. return (el, done) => {
  778. const hook = isAppear ? onAppear : onEnter;
  779. const resolve = () => finishEnter(el, isAppear, done);
  780. callHook(hook, [el, resolve]);
  781. nextFrame(() => {
  782. removeTransitionClass(el, isAppear ? appearFromClass : enterFromClass);
  783. addTransitionClass(el, isAppear ? appearToClass : enterToClass);
  784. if (!hasExplicitCallback(hook)) {
  785. whenTransitionEnds(el, type, enterDuration, resolve);
  786. }
  787. });
  788. };
  789. };
  790. return shared.extend(baseProps, {
  791. onBeforeEnter(el) {
  792. callHook(onBeforeEnter, [el]);
  793. addTransitionClass(el, enterFromClass);
  794. addTransitionClass(el, enterActiveClass);
  795. },
  796. onBeforeAppear(el) {
  797. callHook(onBeforeAppear, [el]);
  798. addTransitionClass(el, appearFromClass);
  799. addTransitionClass(el, appearActiveClass);
  800. },
  801. onEnter: makeEnterHook(false),
  802. onAppear: makeEnterHook(true),
  803. onLeave(el, done) {
  804. const resolve = () => finishLeave(el, done);
  805. addTransitionClass(el, leaveFromClass);
  806. // force reflow so *-leave-from classes immediately take effect (#2593)
  807. forceReflow();
  808. addTransitionClass(el, leaveActiveClass);
  809. nextFrame(() => {
  810. removeTransitionClass(el, leaveFromClass);
  811. addTransitionClass(el, leaveToClass);
  812. if (!hasExplicitCallback(onLeave)) {
  813. whenTransitionEnds(el, type, leaveDuration, resolve);
  814. }
  815. });
  816. callHook(onLeave, [el, resolve]);
  817. },
  818. onEnterCancelled(el) {
  819. finishEnter(el, false);
  820. callHook(onEnterCancelled, [el]);
  821. },
  822. onAppearCancelled(el) {
  823. finishEnter(el, true);
  824. callHook(onAppearCancelled, [el]);
  825. },
  826. onLeaveCancelled(el) {
  827. finishLeave(el);
  828. callHook(onLeaveCancelled, [el]);
  829. }
  830. });
  831. }
  832. function normalizeDuration(duration) {
  833. if (duration == null) {
  834. return null;
  835. }
  836. else if (shared.isObject(duration)) {
  837. return [NumberOf(duration.enter), NumberOf(duration.leave)];
  838. }
  839. else {
  840. const n = NumberOf(duration);
  841. return [n, n];
  842. }
  843. }
  844. function NumberOf(val) {
  845. const res = shared.toNumber(val);
  846. validateDuration(res);
  847. return res;
  848. }
  849. function validateDuration(val) {
  850. if (typeof val !== 'number') {
  851. runtimeCore.warn(`<transition> explicit duration is not a valid number - ` +
  852. `got ${JSON.stringify(val)}.`);
  853. }
  854. else if (isNaN(val)) {
  855. runtimeCore.warn(`<transition> explicit duration is NaN - ` +
  856. 'the duration expression might be incorrect.');
  857. }
  858. }
  859. function addTransitionClass(el, cls) {
  860. cls.split(/\s+/).forEach(c => c && el.classList.add(c));
  861. (el._vtc ||
  862. (el._vtc = new Set())).add(cls);
  863. }
  864. function removeTransitionClass(el, cls) {
  865. cls.split(/\s+/).forEach(c => c && el.classList.remove(c));
  866. const { _vtc } = el;
  867. if (_vtc) {
  868. _vtc.delete(cls);
  869. if (!_vtc.size) {
  870. el._vtc = undefined;
  871. }
  872. }
  873. }
  874. function nextFrame(cb) {
  875. requestAnimationFrame(() => {
  876. requestAnimationFrame(cb);
  877. });
  878. }
  879. let endId = 0;
  880. function whenTransitionEnds(el, expectedType, explicitTimeout, resolve) {
  881. const id = (el._endId = ++endId);
  882. const resolveIfNotStale = () => {
  883. if (id === el._endId) {
  884. resolve();
  885. }
  886. };
  887. if (explicitTimeout) {
  888. return setTimeout(resolveIfNotStale, explicitTimeout);
  889. }
  890. const { type, timeout, propCount } = getTransitionInfo(el, expectedType);
  891. if (!type) {
  892. return resolve();
  893. }
  894. const endEvent = type + 'end';
  895. let ended = 0;
  896. const end = () => {
  897. el.removeEventListener(endEvent, onEnd);
  898. resolveIfNotStale();
  899. };
  900. const onEnd = (e) => {
  901. if (e.target === el && ++ended >= propCount) {
  902. end();
  903. }
  904. };
  905. setTimeout(() => {
  906. if (ended < propCount) {
  907. end();
  908. }
  909. }, timeout + 1);
  910. el.addEventListener(endEvent, onEnd);
  911. }
  912. function getTransitionInfo(el, expectedType) {
  913. const styles = window.getComputedStyle(el);
  914. // JSDOM may return undefined for transition properties
  915. const getStyleProperties = (key) => (styles[key] || '').split(', ');
  916. const transitionDelays = getStyleProperties(TRANSITION + 'Delay');
  917. const transitionDurations = getStyleProperties(TRANSITION + 'Duration');
  918. const transitionTimeout = getTimeout(transitionDelays, transitionDurations);
  919. const animationDelays = getStyleProperties(ANIMATION + 'Delay');
  920. const animationDurations = getStyleProperties(ANIMATION + 'Duration');
  921. const animationTimeout = getTimeout(animationDelays, animationDurations);
  922. let type = null;
  923. let timeout = 0;
  924. let propCount = 0;
  925. /* istanbul ignore if */
  926. if (expectedType === TRANSITION) {
  927. if (transitionTimeout > 0) {
  928. type = TRANSITION;
  929. timeout = transitionTimeout;
  930. propCount = transitionDurations.length;
  931. }
  932. }
  933. else if (expectedType === ANIMATION) {
  934. if (animationTimeout > 0) {
  935. type = ANIMATION;
  936. timeout = animationTimeout;
  937. propCount = animationDurations.length;
  938. }
  939. }
  940. else {
  941. timeout = Math.max(transitionTimeout, animationTimeout);
  942. type =
  943. timeout > 0
  944. ? transitionTimeout > animationTimeout
  945. ? TRANSITION
  946. : ANIMATION
  947. : null;
  948. propCount = type
  949. ? type === TRANSITION
  950. ? transitionDurations.length
  951. : animationDurations.length
  952. : 0;
  953. }
  954. const hasTransform = type === TRANSITION &&
  955. /\b(transform|all)(,|$)/.test(styles[TRANSITION + 'Property']);
  956. return {
  957. type,
  958. timeout,
  959. propCount,
  960. hasTransform
  961. };
  962. }
  963. function getTimeout(delays, durations) {
  964. while (delays.length < durations.length) {
  965. delays = delays.concat(delays);
  966. }
  967. return Math.max(...durations.map((d, i) => toMs(d) + toMs(delays[i])));
  968. }
  969. // Old versions of Chromium (below 61.0.3163.100) formats floating pointer
  970. // numbers in a locale-dependent way, using a comma instead of a dot.
  971. // If comma is not replaced with a dot, the input will be rounded down
  972. // (i.e. acting as a floor function) causing unexpected behaviors
  973. function toMs(s) {
  974. return Number(s.slice(0, -1).replace(',', '.')) * 1000;
  975. }
  976. // synchronously force layout to put elements into a certain state
  977. function forceReflow() {
  978. return document.body.offsetHeight;
  979. }
  980. const positionMap = new WeakMap();
  981. const newPositionMap = new WeakMap();
  982. const TransitionGroupImpl = {
  983. name: 'TransitionGroup',
  984. props: /*#__PURE__*/ shared.extend({}, TransitionPropsValidators, {
  985. tag: String,
  986. moveClass: String
  987. }),
  988. setup(props, { slots }) {
  989. const instance = runtimeCore.getCurrentInstance();
  990. const state = runtimeCore.useTransitionState();
  991. let prevChildren;
  992. let children;
  993. runtimeCore.onUpdated(() => {
  994. // children is guaranteed to exist after initial render
  995. if (!prevChildren.length) {
  996. return;
  997. }
  998. const moveClass = props.moveClass || `${props.name || 'v'}-move`;
  999. if (!hasCSSTransform(prevChildren[0].el, instance.vnode.el, moveClass)) {
  1000. return;
  1001. }
  1002. // we divide the work into three loops to avoid mixing DOM reads and writes
  1003. // in each iteration - which helps prevent layout thrashing.
  1004. prevChildren.forEach(callPendingCbs);
  1005. prevChildren.forEach(recordPosition);
  1006. const movedChildren = prevChildren.filter(applyTranslation);
  1007. // force reflow to put everything in position
  1008. forceReflow();
  1009. movedChildren.forEach(c => {
  1010. const el = c.el;
  1011. const style = el.style;
  1012. addTransitionClass(el, moveClass);
  1013. style.transform = style.webkitTransform = style.transitionDuration = '';
  1014. const cb = (el._moveCb = (e) => {
  1015. if (e && e.target !== el) {
  1016. return;
  1017. }
  1018. if (!e || /transform$/.test(e.propertyName)) {
  1019. el.removeEventListener('transitionend', cb);
  1020. el._moveCb = null;
  1021. removeTransitionClass(el, moveClass);
  1022. }
  1023. });
  1024. el.addEventListener('transitionend', cb);
  1025. });
  1026. });
  1027. return () => {
  1028. const rawProps = runtimeCore.toRaw(props);
  1029. const cssTransitionProps = resolveTransitionProps(rawProps);
  1030. let tag = rawProps.tag || runtimeCore.Fragment;
  1031. prevChildren = children;
  1032. children = slots.default ? runtimeCore.getTransitionRawChildren(slots.default()) : [];
  1033. for (let i = 0; i < children.length; i++) {
  1034. const child = children[i];
  1035. if (child.key != null) {
  1036. runtimeCore.setTransitionHooks(child, runtimeCore.resolveTransitionHooks(child, cssTransitionProps, state, instance));
  1037. }
  1038. else {
  1039. runtimeCore.warn(`<TransitionGroup> children must be keyed.`);
  1040. }
  1041. }
  1042. if (prevChildren) {
  1043. for (let i = 0; i < prevChildren.length; i++) {
  1044. const child = prevChildren[i];
  1045. runtimeCore.setTransitionHooks(child, runtimeCore.resolveTransitionHooks(child, cssTransitionProps, state, instance));
  1046. positionMap.set(child, child.el.getBoundingClientRect());
  1047. }
  1048. }
  1049. return runtimeCore.createVNode(tag, null, children);
  1050. };
  1051. }
  1052. };
  1053. const TransitionGroup = TransitionGroupImpl;
  1054. function callPendingCbs(c) {
  1055. const el = c.el;
  1056. if (el._moveCb) {
  1057. el._moveCb();
  1058. }
  1059. if (el._enterCb) {
  1060. el._enterCb();
  1061. }
  1062. }
  1063. function recordPosition(c) {
  1064. newPositionMap.set(c, c.el.getBoundingClientRect());
  1065. }
  1066. function applyTranslation(c) {
  1067. const oldPos = positionMap.get(c);
  1068. const newPos = newPositionMap.get(c);
  1069. const dx = oldPos.left - newPos.left;
  1070. const dy = oldPos.top - newPos.top;
  1071. if (dx || dy) {
  1072. const s = c.el.style;
  1073. s.transform = s.webkitTransform = `translate(${dx}px,${dy}px)`;
  1074. s.transitionDuration = '0s';
  1075. return c;
  1076. }
  1077. }
  1078. function hasCSSTransform(el, root, moveClass) {
  1079. // Detect whether an element with the move class applied has
  1080. // CSS transitions. Since the element may be inside an entering
  1081. // transition at this very moment, we make a clone of it and remove
  1082. // all other transition classes applied to ensure only the move class
  1083. // is applied.
  1084. const clone = el.cloneNode();
  1085. if (el._vtc) {
  1086. el._vtc.forEach(cls => {
  1087. cls.split(/\s+/).forEach(c => c && clone.classList.remove(c));
  1088. });
  1089. }
  1090. moveClass.split(/\s+/).forEach(c => c && clone.classList.add(c));
  1091. clone.style.display = 'none';
  1092. const container = (root.nodeType === 1 ? root : root.parentNode);
  1093. container.appendChild(clone);
  1094. const { hasTransform } = getTransitionInfo(clone);
  1095. container.removeChild(clone);
  1096. return hasTransform;
  1097. }
  1098. const getModelAssigner = (vnode) => {
  1099. const fn = vnode.props['onUpdate:modelValue'];
  1100. return shared.isArray(fn) ? value => shared.invokeArrayFns(fn, value) : fn;
  1101. };
  1102. function onCompositionStart(e) {
  1103. e.target.composing = true;
  1104. }
  1105. function onCompositionEnd(e) {
  1106. const target = e.target;
  1107. if (target.composing) {
  1108. target.composing = false;
  1109. trigger(target, 'input');
  1110. }
  1111. }
  1112. function trigger(el, type) {
  1113. const e = document.createEvent('HTMLEvents');
  1114. e.initEvent(type, true, true);
  1115. el.dispatchEvent(e);
  1116. }
  1117. // We are exporting the v-model runtime directly as vnode hooks so that it can
  1118. // be tree-shaken in case v-model is never used.
  1119. const vModelText = {
  1120. created(el, { modifiers: { lazy, trim, number } }, vnode) {
  1121. el._assign = getModelAssigner(vnode);
  1122. const castToNumber = number || (vnode.props && vnode.props.type === 'number');
  1123. addEventListener(el, lazy ? 'change' : 'input', e => {
  1124. if (e.target.composing)
  1125. return;
  1126. let domValue = el.value;
  1127. if (trim) {
  1128. domValue = domValue.trim();
  1129. }
  1130. else if (castToNumber) {
  1131. domValue = shared.toNumber(domValue);
  1132. }
  1133. el._assign(domValue);
  1134. });
  1135. if (trim) {
  1136. addEventListener(el, 'change', () => {
  1137. el.value = el.value.trim();
  1138. });
  1139. }
  1140. if (!lazy) {
  1141. addEventListener(el, 'compositionstart', onCompositionStart);
  1142. addEventListener(el, 'compositionend', onCompositionEnd);
  1143. // Safari < 10.2 & UIWebView doesn't fire compositionend when
  1144. // switching focus before confirming composition choice
  1145. // this also fixes the issue where some browsers e.g. iOS Chrome
  1146. // fires "change" instead of "input" on autocomplete.
  1147. addEventListener(el, 'change', onCompositionEnd);
  1148. }
  1149. },
  1150. // set value on mounted so it's after min/max for type="range"
  1151. mounted(el, { value }) {
  1152. el.value = value == null ? '' : value;
  1153. },
  1154. beforeUpdate(el, { value, modifiers: { lazy, trim, number } }, vnode) {
  1155. el._assign = getModelAssigner(vnode);
  1156. // avoid clearing unresolved text. #2302
  1157. if (el.composing)
  1158. return;
  1159. if (document.activeElement === el) {
  1160. if (lazy) {
  1161. return;
  1162. }
  1163. if (trim && el.value.trim() === value) {
  1164. return;
  1165. }
  1166. if ((number || el.type === 'number') && shared.toNumber(el.value) === value) {
  1167. return;
  1168. }
  1169. }
  1170. const newValue = value == null ? '' : value;
  1171. if (el.value !== newValue) {
  1172. el.value = newValue;
  1173. }
  1174. }
  1175. };
  1176. const vModelCheckbox = {
  1177. // #4096 array checkboxes need to be deep traversed
  1178. deep: true,
  1179. created(el, _, vnode) {
  1180. el._assign = getModelAssigner(vnode);
  1181. addEventListener(el, 'change', () => {
  1182. const modelValue = el._modelValue;
  1183. const elementValue = getValue(el);
  1184. const checked = el.checked;
  1185. const assign = el._assign;
  1186. if (shared.isArray(modelValue)) {
  1187. const index = shared.looseIndexOf(modelValue, elementValue);
  1188. const found = index !== -1;
  1189. if (checked && !found) {
  1190. assign(modelValue.concat(elementValue));
  1191. }
  1192. else if (!checked && found) {
  1193. const filtered = [...modelValue];
  1194. filtered.splice(index, 1);
  1195. assign(filtered);
  1196. }
  1197. }
  1198. else if (shared.isSet(modelValue)) {
  1199. const cloned = new Set(modelValue);
  1200. if (checked) {
  1201. cloned.add(elementValue);
  1202. }
  1203. else {
  1204. cloned.delete(elementValue);
  1205. }
  1206. assign(cloned);
  1207. }
  1208. else {
  1209. assign(getCheckboxValue(el, checked));
  1210. }
  1211. });
  1212. },
  1213. // set initial checked on mount to wait for true-value/false-value
  1214. mounted: setChecked,
  1215. beforeUpdate(el, binding, vnode) {
  1216. el._assign = getModelAssigner(vnode);
  1217. setChecked(el, binding, vnode);
  1218. }
  1219. };
  1220. function setChecked(el, { value, oldValue }, vnode) {
  1221. el._modelValue = value;
  1222. if (shared.isArray(value)) {
  1223. el.checked = shared.looseIndexOf(value, vnode.props.value) > -1;
  1224. }
  1225. else if (shared.isSet(value)) {
  1226. el.checked = value.has(vnode.props.value);
  1227. }
  1228. else if (value !== oldValue) {
  1229. el.checked = shared.looseEqual(value, getCheckboxValue(el, true));
  1230. }
  1231. }
  1232. const vModelRadio = {
  1233. created(el, { value }, vnode) {
  1234. el.checked = shared.looseEqual(value, vnode.props.value);
  1235. el._assign = getModelAssigner(vnode);
  1236. addEventListener(el, 'change', () => {
  1237. el._assign(getValue(el));
  1238. });
  1239. },
  1240. beforeUpdate(el, { value, oldValue }, vnode) {
  1241. el._assign = getModelAssigner(vnode);
  1242. if (value !== oldValue) {
  1243. el.checked = shared.looseEqual(value, vnode.props.value);
  1244. }
  1245. }
  1246. };
  1247. const vModelSelect = {
  1248. // <select multiple> value need to be deep traversed
  1249. deep: true,
  1250. created(el, { value, modifiers: { number } }, vnode) {
  1251. const isSetModel = shared.isSet(value);
  1252. addEventListener(el, 'change', () => {
  1253. const selectedVal = Array.prototype.filter
  1254. .call(el.options, (o) => o.selected)
  1255. .map((o) => number ? shared.toNumber(getValue(o)) : getValue(o));
  1256. el._assign(el.multiple
  1257. ? isSetModel
  1258. ? new Set(selectedVal)
  1259. : selectedVal
  1260. : selectedVal[0]);
  1261. });
  1262. el._assign = getModelAssigner(vnode);
  1263. },
  1264. // set value in mounted & updated because <select> relies on its children
  1265. // <option>s.
  1266. mounted(el, { value }) {
  1267. setSelected(el, value);
  1268. },
  1269. beforeUpdate(el, _binding, vnode) {
  1270. el._assign = getModelAssigner(vnode);
  1271. },
  1272. updated(el, { value }) {
  1273. setSelected(el, value);
  1274. }
  1275. };
  1276. function setSelected(el, value) {
  1277. const isMultiple = el.multiple;
  1278. if (isMultiple && !shared.isArray(value) && !shared.isSet(value)) {
  1279. runtimeCore.warn(`<select multiple v-model> expects an Array or Set value for its binding, ` +
  1280. `but got ${Object.prototype.toString.call(value).slice(8, -1)}.`);
  1281. return;
  1282. }
  1283. for (let i = 0, l = el.options.length; i < l; i++) {
  1284. const option = el.options[i];
  1285. const optionValue = getValue(option);
  1286. if (isMultiple) {
  1287. if (shared.isArray(value)) {
  1288. option.selected = shared.looseIndexOf(value, optionValue) > -1;
  1289. }
  1290. else {
  1291. option.selected = value.has(optionValue);
  1292. }
  1293. }
  1294. else {
  1295. if (shared.looseEqual(getValue(option), value)) {
  1296. if (el.selectedIndex !== i)
  1297. el.selectedIndex = i;
  1298. return;
  1299. }
  1300. }
  1301. }
  1302. if (!isMultiple && el.selectedIndex !== -1) {
  1303. el.selectedIndex = -1;
  1304. }
  1305. }
  1306. // retrieve raw value set via :value bindings
  1307. function getValue(el) {
  1308. return '_value' in el ? el._value : el.value;
  1309. }
  1310. // retrieve raw value for true-value and false-value set via :true-value or :false-value bindings
  1311. function getCheckboxValue(el, checked) {
  1312. const key = checked ? '_trueValue' : '_falseValue';
  1313. return key in el ? el[key] : checked;
  1314. }
  1315. const vModelDynamic = {
  1316. created(el, binding, vnode) {
  1317. callModelHook(el, binding, vnode, null, 'created');
  1318. },
  1319. mounted(el, binding, vnode) {
  1320. callModelHook(el, binding, vnode, null, 'mounted');
  1321. },
  1322. beforeUpdate(el, binding, vnode, prevVNode) {
  1323. callModelHook(el, binding, vnode, prevVNode, 'beforeUpdate');
  1324. },
  1325. updated(el, binding, vnode, prevVNode) {
  1326. callModelHook(el, binding, vnode, prevVNode, 'updated');
  1327. }
  1328. };
  1329. function callModelHook(el, binding, vnode, prevVNode, hook) {
  1330. let modelToUse;
  1331. switch (el.tagName) {
  1332. case 'SELECT':
  1333. modelToUse = vModelSelect;
  1334. break;
  1335. case 'TEXTAREA':
  1336. modelToUse = vModelText;
  1337. break;
  1338. default:
  1339. switch (vnode.props && vnode.props.type) {
  1340. case 'checkbox':
  1341. modelToUse = vModelCheckbox;
  1342. break;
  1343. case 'radio':
  1344. modelToUse = vModelRadio;
  1345. break;
  1346. default:
  1347. modelToUse = vModelText;
  1348. }
  1349. }
  1350. const fn = modelToUse[hook];
  1351. fn && fn(el, binding, vnode, prevVNode);
  1352. }
  1353. // SSR vnode transforms, only used when user includes client-oriented render
  1354. // function in SSR
  1355. function initVModelForSSR() {
  1356. vModelText.getSSRProps = ({ value }) => ({ value });
  1357. vModelRadio.getSSRProps = ({ value }, vnode) => {
  1358. if (vnode.props && shared.looseEqual(vnode.props.value, value)) {
  1359. return { checked: true };
  1360. }
  1361. };
  1362. vModelCheckbox.getSSRProps = ({ value }, vnode) => {
  1363. if (shared.isArray(value)) {
  1364. if (vnode.props && shared.looseIndexOf(value, vnode.props.value) > -1) {
  1365. return { checked: true };
  1366. }
  1367. }
  1368. else if (shared.isSet(value)) {
  1369. if (vnode.props && value.has(vnode.props.value)) {
  1370. return { checked: true };
  1371. }
  1372. }
  1373. else if (value) {
  1374. return { checked: true };
  1375. }
  1376. };
  1377. }
  1378. const systemModifiers = ['ctrl', 'shift', 'alt', 'meta'];
  1379. const modifierGuards = {
  1380. stop: e => e.stopPropagation(),
  1381. prevent: e => e.preventDefault(),
  1382. self: e => e.target !== e.currentTarget,
  1383. ctrl: e => !e.ctrlKey,
  1384. shift: e => !e.shiftKey,
  1385. alt: e => !e.altKey,
  1386. meta: e => !e.metaKey,
  1387. left: e => 'button' in e && e.button !== 0,
  1388. middle: e => 'button' in e && e.button !== 1,
  1389. right: e => 'button' in e && e.button !== 2,
  1390. exact: (e, modifiers) => systemModifiers.some(m => e[`${m}Key`] && !modifiers.includes(m))
  1391. };
  1392. /**
  1393. * @private
  1394. */
  1395. const withModifiers = (fn, modifiers) => {
  1396. return (event, ...args) => {
  1397. for (let i = 0; i < modifiers.length; i++) {
  1398. const guard = modifierGuards[modifiers[i]];
  1399. if (guard && guard(event, modifiers))
  1400. return;
  1401. }
  1402. return fn(event, ...args);
  1403. };
  1404. };
  1405. // Kept for 2.x compat.
  1406. // Note: IE11 compat for `spacebar` and `del` is removed for now.
  1407. const keyNames = {
  1408. esc: 'escape',
  1409. space: ' ',
  1410. up: 'arrow-up',
  1411. left: 'arrow-left',
  1412. right: 'arrow-right',
  1413. down: 'arrow-down',
  1414. delete: 'backspace'
  1415. };
  1416. /**
  1417. * @private
  1418. */
  1419. const withKeys = (fn, modifiers) => {
  1420. return (event) => {
  1421. if (!('key' in event)) {
  1422. return;
  1423. }
  1424. const eventKey = shared.hyphenate(event.key);
  1425. if (modifiers.some(k => k === eventKey || keyNames[k] === eventKey)) {
  1426. return fn(event);
  1427. }
  1428. };
  1429. };
  1430. const vShow = {
  1431. beforeMount(el, { value }, { transition }) {
  1432. el._vod = el.style.display === 'none' ? '' : el.style.display;
  1433. if (transition && value) {
  1434. transition.beforeEnter(el);
  1435. }
  1436. else {
  1437. setDisplay(el, value);
  1438. }
  1439. },
  1440. mounted(el, { value }, { transition }) {
  1441. if (transition && value) {
  1442. transition.enter(el);
  1443. }
  1444. },
  1445. updated(el, { value, oldValue }, { transition }) {
  1446. if (!value === !oldValue)
  1447. return;
  1448. if (transition) {
  1449. if (value) {
  1450. transition.beforeEnter(el);
  1451. setDisplay(el, true);
  1452. transition.enter(el);
  1453. }
  1454. else {
  1455. transition.leave(el, () => {
  1456. setDisplay(el, false);
  1457. });
  1458. }
  1459. }
  1460. else {
  1461. setDisplay(el, value);
  1462. }
  1463. },
  1464. beforeUnmount(el, { value }) {
  1465. setDisplay(el, value);
  1466. }
  1467. };
  1468. function setDisplay(el, value) {
  1469. el.style.display = value ? el._vod : 'none';
  1470. }
  1471. // SSR vnode transforms, only used when user includes client-oriented render
  1472. // function in SSR
  1473. function initVShowForSSR() {
  1474. vShow.getSSRProps = ({ value }) => {
  1475. if (!value) {
  1476. return { style: { display: 'none' } };
  1477. }
  1478. };
  1479. }
  1480. const rendererOptions = /*#__PURE__*/ shared.extend({ patchProp }, nodeOps);
  1481. // lazy create the renderer - this makes core renderer logic tree-shakable
  1482. // in case the user only imports reactivity utilities from Vue.
  1483. let renderer;
  1484. let enabledHydration = false;
  1485. function ensureRenderer() {
  1486. return (renderer ||
  1487. (renderer = runtimeCore.createRenderer(rendererOptions)));
  1488. }
  1489. function ensureHydrationRenderer() {
  1490. renderer = enabledHydration
  1491. ? renderer
  1492. : runtimeCore.createHydrationRenderer(rendererOptions);
  1493. enabledHydration = true;
  1494. return renderer;
  1495. }
  1496. // use explicit type casts here to avoid import() calls in rolled-up d.ts
  1497. const render = ((...args) => {
  1498. ensureRenderer().render(...args);
  1499. });
  1500. const hydrate = ((...args) => {
  1501. ensureHydrationRenderer().hydrate(...args);
  1502. });
  1503. const createApp = ((...args) => {
  1504. const app = ensureRenderer().createApp(...args);
  1505. {
  1506. injectNativeTagCheck(app);
  1507. injectCompilerOptionsCheck(app);
  1508. }
  1509. const { mount } = app;
  1510. app.mount = (containerOrSelector) => {
  1511. const container = normalizeContainer(containerOrSelector);
  1512. if (!container)
  1513. return;
  1514. const component = app._component;
  1515. if (!shared.isFunction(component) && !component.render && !component.template) {
  1516. // __UNSAFE__
  1517. // Reason: potential execution of JS expressions in in-DOM template.
  1518. // The user must make sure the in-DOM template is trusted. If it's
  1519. // rendered by the server, the template should not contain any user data.
  1520. component.template = container.innerHTML;
  1521. }
  1522. // clear content before mounting
  1523. container.innerHTML = '';
  1524. const proxy = mount(container, false, container instanceof SVGElement);
  1525. if (container instanceof Element) {
  1526. container.removeAttribute('v-cloak');
  1527. container.setAttribute('data-v-app', '');
  1528. }
  1529. return proxy;
  1530. };
  1531. return app;
  1532. });
  1533. const createSSRApp = ((...args) => {
  1534. const app = ensureHydrationRenderer().createApp(...args);
  1535. {
  1536. injectNativeTagCheck(app);
  1537. injectCompilerOptionsCheck(app);
  1538. }
  1539. const { mount } = app;
  1540. app.mount = (containerOrSelector) => {
  1541. const container = normalizeContainer(containerOrSelector);
  1542. if (container) {
  1543. return mount(container, true, container instanceof SVGElement);
  1544. }
  1545. };
  1546. return app;
  1547. });
  1548. function injectNativeTagCheck(app) {
  1549. // Inject `isNativeTag`
  1550. // this is used for component name validation (dev only)
  1551. Object.defineProperty(app.config, 'isNativeTag', {
  1552. value: (tag) => shared.isHTMLTag(tag) || shared.isSVGTag(tag),
  1553. writable: false
  1554. });
  1555. }
  1556. // dev only
  1557. function injectCompilerOptionsCheck(app) {
  1558. if (runtimeCore.isRuntimeOnly()) {
  1559. const isCustomElement = app.config.isCustomElement;
  1560. Object.defineProperty(app.config, 'isCustomElement', {
  1561. get() {
  1562. return isCustomElement;
  1563. },
  1564. set() {
  1565. runtimeCore.warn(`The \`isCustomElement\` config option is deprecated. Use ` +
  1566. `\`compilerOptions.isCustomElement\` instead.`);
  1567. }
  1568. });
  1569. const compilerOptions = app.config.compilerOptions;
  1570. const msg = `The \`compilerOptions\` config option is only respected when using ` +
  1571. `a build of Vue.js that includes the runtime compiler (aka "full build"). ` +
  1572. `Since you are using the runtime-only build, \`compilerOptions\` ` +
  1573. `must be passed to \`@vue/compiler-dom\` in the build setup instead.\n` +
  1574. `- For vue-loader: pass it via vue-loader's \`compilerOptions\` loader option.\n` +
  1575. `- For vue-cli: see https://cli.vuejs.org/guide/webpack.html#modifying-options-of-a-loader\n` +
  1576. `- For vite: pass it via @vitejs/plugin-vue options. See https://github.com/vitejs/vite/tree/main/packages/plugin-vue#example-for-passing-options-to-vuecompiler-dom`;
  1577. Object.defineProperty(app.config, 'compilerOptions', {
  1578. get() {
  1579. runtimeCore.warn(msg);
  1580. return compilerOptions;
  1581. },
  1582. set() {
  1583. runtimeCore.warn(msg);
  1584. }
  1585. });
  1586. }
  1587. }
  1588. function normalizeContainer(container) {
  1589. if (shared.isString(container)) {
  1590. const res = document.querySelector(container);
  1591. if (!res) {
  1592. runtimeCore.warn(`Failed to mount app: mount target selector "${container}" returned null.`);
  1593. }
  1594. return res;
  1595. }
  1596. if (window.ShadowRoot &&
  1597. container instanceof window.ShadowRoot &&
  1598. container.mode === 'closed') {
  1599. runtimeCore.warn(`mounting on a ShadowRoot with \`{mode: "closed"}\` may lead to unpredictable bugs`);
  1600. }
  1601. return container;
  1602. }
  1603. let ssrDirectiveInitialized = false;
  1604. /**
  1605. * @internal
  1606. */
  1607. const initDirectivesForSSR = () => {
  1608. if (!ssrDirectiveInitialized) {
  1609. ssrDirectiveInitialized = true;
  1610. initVModelForSSR();
  1611. initVShowForSSR();
  1612. }
  1613. }
  1614. ;
  1615. Object.keys(runtimeCore).forEach(function (k) {
  1616. if (k !== 'default') exports[k] = runtimeCore[k];
  1617. });
  1618. exports.Transition = Transition;
  1619. exports.TransitionGroup = TransitionGroup;
  1620. exports.VueElement = VueElement;
  1621. exports.createApp = createApp;
  1622. exports.createSSRApp = createSSRApp;
  1623. exports.defineCustomElement = defineCustomElement;
  1624. exports.defineSSRCustomElement = defineSSRCustomElement;
  1625. exports.hydrate = hydrate;
  1626. exports.initDirectivesForSSR = initDirectivesForSSR;
  1627. exports.render = render;
  1628. exports.useCssModule = useCssModule;
  1629. exports.useCssVars = useCssVars;
  1630. exports.vModelCheckbox = vModelCheckbox;
  1631. exports.vModelDynamic = vModelDynamic;
  1632. exports.vModelRadio = vModelRadio;
  1633. exports.vModelSelect = vModelSelect;
  1634. exports.vModelText = vModelText;
  1635. exports.vShow = vShow;
  1636. exports.withKeys = withKeys;
  1637. exports.withModifiers = withModifiers;