runtime-dom.esm-bundler.js 60 KB

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