reactivity.esm-browser.js 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238
  1. /**
  2. * Make a map and return a function for checking if a key
  3. * is in that map.
  4. * IMPORTANT: all calls of this function must be prefixed with
  5. * \/\*#\_\_PURE\_\_\*\/
  6. * So that rollup can tree-shake them if necessary.
  7. */
  8. function makeMap(str, expectsLowerCase) {
  9. const map = Object.create(null);
  10. const list = str.split(',');
  11. for (let i = 0; i < list.length; i++) {
  12. map[list[i]] = true;
  13. }
  14. return expectsLowerCase ? val => !!map[val.toLowerCase()] : val => !!map[val];
  15. }
  16. Object.freeze({})
  17. ;
  18. Object.freeze([]) ;
  19. const extend = Object.assign;
  20. const hasOwnProperty = Object.prototype.hasOwnProperty;
  21. const hasOwn = (val, key) => hasOwnProperty.call(val, key);
  22. const isArray = Array.isArray;
  23. const isMap = (val) => toTypeString(val) === '[object Map]';
  24. const isFunction = (val) => typeof val === 'function';
  25. const isString = (val) => typeof val === 'string';
  26. const isSymbol = (val) => typeof val === 'symbol';
  27. const isObject = (val) => val !== null && typeof val === 'object';
  28. const objectToString = Object.prototype.toString;
  29. const toTypeString = (value) => objectToString.call(value);
  30. const toRawType = (value) => {
  31. // extract "RawType" from strings like "[object RawType]"
  32. return toTypeString(value).slice(8, -1);
  33. };
  34. const isIntegerKey = (key) => isString(key) &&
  35. key !== 'NaN' &&
  36. key[0] !== '-' &&
  37. '' + parseInt(key, 10) === key;
  38. const cacheStringFunction = (fn) => {
  39. const cache = Object.create(null);
  40. return ((str) => {
  41. const hit = cache[str];
  42. return hit || (cache[str] = fn(str));
  43. });
  44. };
  45. /**
  46. * @private
  47. */
  48. const capitalize = cacheStringFunction((str) => str.charAt(0).toUpperCase() + str.slice(1));
  49. // compare whether a value has changed, accounting for NaN.
  50. const hasChanged = (value, oldValue) => !Object.is(value, oldValue);
  51. const def = (obj, key, value) => {
  52. Object.defineProperty(obj, key, {
  53. configurable: true,
  54. enumerable: false,
  55. value
  56. });
  57. };
  58. function warn(msg, ...args) {
  59. console.warn(`[Vue warn] ${msg}`, ...args);
  60. }
  61. let activeEffectScope;
  62. const effectScopeStack = [];
  63. class EffectScope {
  64. constructor(detached = false) {
  65. this.active = true;
  66. this.effects = [];
  67. this.cleanups = [];
  68. if (!detached && activeEffectScope) {
  69. this.parent = activeEffectScope;
  70. this.index =
  71. (activeEffectScope.scopes || (activeEffectScope.scopes = [])).push(this) - 1;
  72. }
  73. }
  74. run(fn) {
  75. if (this.active) {
  76. try {
  77. this.on();
  78. return fn();
  79. }
  80. finally {
  81. this.off();
  82. }
  83. }
  84. else {
  85. warn(`cannot run an inactive effect scope.`);
  86. }
  87. }
  88. on() {
  89. if (this.active) {
  90. effectScopeStack.push(this);
  91. activeEffectScope = this;
  92. }
  93. }
  94. off() {
  95. if (this.active) {
  96. effectScopeStack.pop();
  97. activeEffectScope = effectScopeStack[effectScopeStack.length - 1];
  98. }
  99. }
  100. stop(fromParent) {
  101. if (this.active) {
  102. this.effects.forEach(e => e.stop());
  103. this.cleanups.forEach(cleanup => cleanup());
  104. if (this.scopes) {
  105. this.scopes.forEach(e => e.stop(true));
  106. }
  107. // nested scope, dereference from parent to avoid memory leaks
  108. if (this.parent && !fromParent) {
  109. // optimized O(1) removal
  110. const last = this.parent.scopes.pop();
  111. if (last && last !== this) {
  112. this.parent.scopes[this.index] = last;
  113. last.index = this.index;
  114. }
  115. }
  116. this.active = false;
  117. }
  118. }
  119. }
  120. function effectScope(detached) {
  121. return new EffectScope(detached);
  122. }
  123. function recordEffectScope(effect, scope) {
  124. scope = scope || activeEffectScope;
  125. if (scope && scope.active) {
  126. scope.effects.push(effect);
  127. }
  128. }
  129. function getCurrentScope() {
  130. return activeEffectScope;
  131. }
  132. function onScopeDispose(fn) {
  133. if (activeEffectScope) {
  134. activeEffectScope.cleanups.push(fn);
  135. }
  136. else {
  137. warn(`onScopeDispose() is called when there is no active effect scope` +
  138. ` to be associated with.`);
  139. }
  140. }
  141. const createDep = (effects) => {
  142. const dep = new Set(effects);
  143. dep.w = 0;
  144. dep.n = 0;
  145. return dep;
  146. };
  147. const wasTracked = (dep) => (dep.w & trackOpBit) > 0;
  148. const newTracked = (dep) => (dep.n & trackOpBit) > 0;
  149. const initDepMarkers = ({ deps }) => {
  150. if (deps.length) {
  151. for (let i = 0; i < deps.length; i++) {
  152. deps[i].w |= trackOpBit; // set was tracked
  153. }
  154. }
  155. };
  156. const finalizeDepMarkers = (effect) => {
  157. const { deps } = effect;
  158. if (deps.length) {
  159. let ptr = 0;
  160. for (let i = 0; i < deps.length; i++) {
  161. const dep = deps[i];
  162. if (wasTracked(dep) && !newTracked(dep)) {
  163. dep.delete(effect);
  164. }
  165. else {
  166. deps[ptr++] = dep;
  167. }
  168. // clear bits
  169. dep.w &= ~trackOpBit;
  170. dep.n &= ~trackOpBit;
  171. }
  172. deps.length = ptr;
  173. }
  174. };
  175. const targetMap = new WeakMap();
  176. // The number of effects currently being tracked recursively.
  177. let effectTrackDepth = 0;
  178. let trackOpBit = 1;
  179. /**
  180. * The bitwise track markers support at most 30 levels of recursion.
  181. * This value is chosen to enable modern JS engines to use a SMI on all platforms.
  182. * When recursion depth is greater, fall back to using a full cleanup.
  183. */
  184. const maxMarkerBits = 30;
  185. const effectStack = [];
  186. let activeEffect;
  187. const ITERATE_KEY = Symbol('iterate' );
  188. const MAP_KEY_ITERATE_KEY = Symbol('Map key iterate' );
  189. class ReactiveEffect {
  190. constructor(fn, scheduler = null, scope) {
  191. this.fn = fn;
  192. this.scheduler = scheduler;
  193. this.active = true;
  194. this.deps = [];
  195. recordEffectScope(this, scope);
  196. }
  197. run() {
  198. if (!this.active) {
  199. return this.fn();
  200. }
  201. if (!effectStack.includes(this)) {
  202. try {
  203. effectStack.push((activeEffect = this));
  204. enableTracking();
  205. trackOpBit = 1 << ++effectTrackDepth;
  206. if (effectTrackDepth <= maxMarkerBits) {
  207. initDepMarkers(this);
  208. }
  209. else {
  210. cleanupEffect(this);
  211. }
  212. return this.fn();
  213. }
  214. finally {
  215. if (effectTrackDepth <= maxMarkerBits) {
  216. finalizeDepMarkers(this);
  217. }
  218. trackOpBit = 1 << --effectTrackDepth;
  219. resetTracking();
  220. effectStack.pop();
  221. const n = effectStack.length;
  222. activeEffect = n > 0 ? effectStack[n - 1] : undefined;
  223. }
  224. }
  225. }
  226. stop() {
  227. if (this.active) {
  228. cleanupEffect(this);
  229. if (this.onStop) {
  230. this.onStop();
  231. }
  232. this.active = false;
  233. }
  234. }
  235. }
  236. function cleanupEffect(effect) {
  237. const { deps } = effect;
  238. if (deps.length) {
  239. for (let i = 0; i < deps.length; i++) {
  240. deps[i].delete(effect);
  241. }
  242. deps.length = 0;
  243. }
  244. }
  245. function effect(fn, options) {
  246. if (fn.effect) {
  247. fn = fn.effect.fn;
  248. }
  249. const _effect = new ReactiveEffect(fn);
  250. if (options) {
  251. extend(_effect, options);
  252. if (options.scope)
  253. recordEffectScope(_effect, options.scope);
  254. }
  255. if (!options || !options.lazy) {
  256. _effect.run();
  257. }
  258. const runner = _effect.run.bind(_effect);
  259. runner.effect = _effect;
  260. return runner;
  261. }
  262. function stop(runner) {
  263. runner.effect.stop();
  264. }
  265. let shouldTrack = true;
  266. const trackStack = [];
  267. function pauseTracking() {
  268. trackStack.push(shouldTrack);
  269. shouldTrack = false;
  270. }
  271. function enableTracking() {
  272. trackStack.push(shouldTrack);
  273. shouldTrack = true;
  274. }
  275. function resetTracking() {
  276. const last = trackStack.pop();
  277. shouldTrack = last === undefined ? true : last;
  278. }
  279. function track(target, type, key) {
  280. if (!isTracking()) {
  281. return;
  282. }
  283. let depsMap = targetMap.get(target);
  284. if (!depsMap) {
  285. targetMap.set(target, (depsMap = new Map()));
  286. }
  287. let dep = depsMap.get(key);
  288. if (!dep) {
  289. depsMap.set(key, (dep = createDep()));
  290. }
  291. const eventInfo = { effect: activeEffect, target, type, key }
  292. ;
  293. trackEffects(dep, eventInfo);
  294. }
  295. function isTracking() {
  296. return shouldTrack && activeEffect !== undefined;
  297. }
  298. function trackEffects(dep, debuggerEventExtraInfo) {
  299. let shouldTrack = false;
  300. if (effectTrackDepth <= maxMarkerBits) {
  301. if (!newTracked(dep)) {
  302. dep.n |= trackOpBit; // set newly tracked
  303. shouldTrack = !wasTracked(dep);
  304. }
  305. }
  306. else {
  307. // Full cleanup mode.
  308. shouldTrack = !dep.has(activeEffect);
  309. }
  310. if (shouldTrack) {
  311. dep.add(activeEffect);
  312. activeEffect.deps.push(dep);
  313. if (activeEffect.onTrack) {
  314. activeEffect.onTrack(Object.assign({
  315. effect: activeEffect
  316. }, debuggerEventExtraInfo));
  317. }
  318. }
  319. }
  320. function trigger(target, type, key, newValue, oldValue, oldTarget) {
  321. const depsMap = targetMap.get(target);
  322. if (!depsMap) {
  323. // never been tracked
  324. return;
  325. }
  326. let deps = [];
  327. if (type === "clear" /* CLEAR */) {
  328. // collection being cleared
  329. // trigger all effects for target
  330. deps = [...depsMap.values()];
  331. }
  332. else if (key === 'length' && isArray(target)) {
  333. depsMap.forEach((dep, key) => {
  334. if (key === 'length' || key >= newValue) {
  335. deps.push(dep);
  336. }
  337. });
  338. }
  339. else {
  340. // schedule runs for SET | ADD | DELETE
  341. if (key !== void 0) {
  342. deps.push(depsMap.get(key));
  343. }
  344. // also run for iteration key on ADD | DELETE | Map.SET
  345. switch (type) {
  346. case "add" /* ADD */:
  347. if (!isArray(target)) {
  348. deps.push(depsMap.get(ITERATE_KEY));
  349. if (isMap(target)) {
  350. deps.push(depsMap.get(MAP_KEY_ITERATE_KEY));
  351. }
  352. }
  353. else if (isIntegerKey(key)) {
  354. // new index added to array -> length changes
  355. deps.push(depsMap.get('length'));
  356. }
  357. break;
  358. case "delete" /* DELETE */:
  359. if (!isArray(target)) {
  360. deps.push(depsMap.get(ITERATE_KEY));
  361. if (isMap(target)) {
  362. deps.push(depsMap.get(MAP_KEY_ITERATE_KEY));
  363. }
  364. }
  365. break;
  366. case "set" /* SET */:
  367. if (isMap(target)) {
  368. deps.push(depsMap.get(ITERATE_KEY));
  369. }
  370. break;
  371. }
  372. }
  373. const eventInfo = { target, type, key, newValue, oldValue, oldTarget }
  374. ;
  375. if (deps.length === 1) {
  376. if (deps[0]) {
  377. {
  378. triggerEffects(deps[0], eventInfo);
  379. }
  380. }
  381. }
  382. else {
  383. const effects = [];
  384. for (const dep of deps) {
  385. if (dep) {
  386. effects.push(...dep);
  387. }
  388. }
  389. {
  390. triggerEffects(createDep(effects), eventInfo);
  391. }
  392. }
  393. }
  394. function triggerEffects(dep, debuggerEventExtraInfo) {
  395. // spread into array for stabilization
  396. for (const effect of isArray(dep) ? dep : [...dep]) {
  397. if (effect !== activeEffect || effect.allowRecurse) {
  398. if (effect.onTrigger) {
  399. effect.onTrigger(extend({ effect }, debuggerEventExtraInfo));
  400. }
  401. if (effect.scheduler) {
  402. effect.scheduler();
  403. }
  404. else {
  405. effect.run();
  406. }
  407. }
  408. }
  409. }
  410. const isNonTrackableKeys = /*#__PURE__*/ makeMap(`__proto__,__v_isRef,__isVue`);
  411. const builtInSymbols = new Set(Object.getOwnPropertyNames(Symbol)
  412. .map(key => Symbol[key])
  413. .filter(isSymbol));
  414. const get = /*#__PURE__*/ createGetter();
  415. const shallowGet = /*#__PURE__*/ createGetter(false, true);
  416. const readonlyGet = /*#__PURE__*/ createGetter(true);
  417. const shallowReadonlyGet = /*#__PURE__*/ createGetter(true, true);
  418. const arrayInstrumentations = /*#__PURE__*/ createArrayInstrumentations();
  419. function createArrayInstrumentations() {
  420. const instrumentations = {};
  421. ['includes', 'indexOf', 'lastIndexOf'].forEach(key => {
  422. instrumentations[key] = function (...args) {
  423. const arr = toRaw(this);
  424. for (let i = 0, l = this.length; i < l; i++) {
  425. track(arr, "get" /* GET */, i + '');
  426. }
  427. // we run the method using the original args first (which may be reactive)
  428. const res = arr[key](...args);
  429. if (res === -1 || res === false) {
  430. // if that didn't work, run it again using raw values.
  431. return arr[key](...args.map(toRaw));
  432. }
  433. else {
  434. return res;
  435. }
  436. };
  437. });
  438. ['push', 'pop', 'shift', 'unshift', 'splice'].forEach(key => {
  439. instrumentations[key] = function (...args) {
  440. pauseTracking();
  441. const res = toRaw(this)[key].apply(this, args);
  442. resetTracking();
  443. return res;
  444. };
  445. });
  446. return instrumentations;
  447. }
  448. function createGetter(isReadonly = false, shallow = false) {
  449. return function get(target, key, receiver) {
  450. if (key === "__v_isReactive" /* IS_REACTIVE */) {
  451. return !isReadonly;
  452. }
  453. else if (key === "__v_isReadonly" /* IS_READONLY */) {
  454. return isReadonly;
  455. }
  456. else if (key === "__v_raw" /* RAW */ &&
  457. receiver ===
  458. (isReadonly
  459. ? shallow
  460. ? shallowReadonlyMap
  461. : readonlyMap
  462. : shallow
  463. ? shallowReactiveMap
  464. : reactiveMap).get(target)) {
  465. return target;
  466. }
  467. const targetIsArray = isArray(target);
  468. if (!isReadonly && targetIsArray && hasOwn(arrayInstrumentations, key)) {
  469. return Reflect.get(arrayInstrumentations, key, receiver);
  470. }
  471. const res = Reflect.get(target, key, receiver);
  472. if (isSymbol(key) ? builtInSymbols.has(key) : isNonTrackableKeys(key)) {
  473. return res;
  474. }
  475. if (!isReadonly) {
  476. track(target, "get" /* GET */, key);
  477. }
  478. if (shallow) {
  479. return res;
  480. }
  481. if (isRef(res)) {
  482. // ref unwrapping - does not apply for Array + integer key.
  483. const shouldUnwrap = !targetIsArray || !isIntegerKey(key);
  484. return shouldUnwrap ? res.value : res;
  485. }
  486. if (isObject(res)) {
  487. // Convert returned value into a proxy as well. we do the isObject check
  488. // here to avoid invalid value warning. Also need to lazy access readonly
  489. // and reactive here to avoid circular dependency.
  490. return isReadonly ? readonly(res) : reactive(res);
  491. }
  492. return res;
  493. };
  494. }
  495. const set = /*#__PURE__*/ createSetter();
  496. const shallowSet = /*#__PURE__*/ createSetter(true);
  497. function createSetter(shallow = false) {
  498. return function set(target, key, value, receiver) {
  499. let oldValue = target[key];
  500. if (!shallow && !isReadonly(value)) {
  501. value = toRaw(value);
  502. oldValue = toRaw(oldValue);
  503. if (!isArray(target) && isRef(oldValue) && !isRef(value)) {
  504. oldValue.value = value;
  505. return true;
  506. }
  507. }
  508. const hadKey = isArray(target) && isIntegerKey(key)
  509. ? Number(key) < target.length
  510. : hasOwn(target, key);
  511. const result = Reflect.set(target, key, value, receiver);
  512. // don't trigger if target is something up in the prototype chain of original
  513. if (target === toRaw(receiver)) {
  514. if (!hadKey) {
  515. trigger(target, "add" /* ADD */, key, value);
  516. }
  517. else if (hasChanged(value, oldValue)) {
  518. trigger(target, "set" /* SET */, key, value, oldValue);
  519. }
  520. }
  521. return result;
  522. };
  523. }
  524. function deleteProperty(target, key) {
  525. const hadKey = hasOwn(target, key);
  526. const oldValue = target[key];
  527. const result = Reflect.deleteProperty(target, key);
  528. if (result && hadKey) {
  529. trigger(target, "delete" /* DELETE */, key, undefined, oldValue);
  530. }
  531. return result;
  532. }
  533. function has(target, key) {
  534. const result = Reflect.has(target, key);
  535. if (!isSymbol(key) || !builtInSymbols.has(key)) {
  536. track(target, "has" /* HAS */, key);
  537. }
  538. return result;
  539. }
  540. function ownKeys(target) {
  541. track(target, "iterate" /* ITERATE */, isArray(target) ? 'length' : ITERATE_KEY);
  542. return Reflect.ownKeys(target);
  543. }
  544. const mutableHandlers = {
  545. get,
  546. set,
  547. deleteProperty,
  548. has,
  549. ownKeys
  550. };
  551. const readonlyHandlers = {
  552. get: readonlyGet,
  553. set(target, key) {
  554. {
  555. console.warn(`Set operation on key "${String(key)}" failed: target is readonly.`, target);
  556. }
  557. return true;
  558. },
  559. deleteProperty(target, key) {
  560. {
  561. console.warn(`Delete operation on key "${String(key)}" failed: target is readonly.`, target);
  562. }
  563. return true;
  564. }
  565. };
  566. const shallowReactiveHandlers = /*#__PURE__*/ extend({}, mutableHandlers, {
  567. get: shallowGet,
  568. set: shallowSet
  569. });
  570. // Props handlers are special in the sense that it should not unwrap top-level
  571. // refs (in order to allow refs to be explicitly passed down), but should
  572. // retain the reactivity of the normal readonly object.
  573. const shallowReadonlyHandlers = /*#__PURE__*/ extend({}, readonlyHandlers, {
  574. get: shallowReadonlyGet
  575. });
  576. const toShallow = (value) => value;
  577. const getProto = (v) => Reflect.getPrototypeOf(v);
  578. function get$1(target, key, isReadonly = false, isShallow = false) {
  579. // #1772: readonly(reactive(Map)) should return readonly + reactive version
  580. // of the value
  581. target = target["__v_raw" /* RAW */];
  582. const rawTarget = toRaw(target);
  583. const rawKey = toRaw(key);
  584. if (key !== rawKey) {
  585. !isReadonly && track(rawTarget, "get" /* GET */, key);
  586. }
  587. !isReadonly && track(rawTarget, "get" /* GET */, rawKey);
  588. const { has } = getProto(rawTarget);
  589. const wrap = isShallow ? toShallow : isReadonly ? toReadonly : toReactive;
  590. if (has.call(rawTarget, key)) {
  591. return wrap(target.get(key));
  592. }
  593. else if (has.call(rawTarget, rawKey)) {
  594. return wrap(target.get(rawKey));
  595. }
  596. else if (target !== rawTarget) {
  597. // #3602 readonly(reactive(Map))
  598. // ensure that the nested reactive `Map` can do tracking for itself
  599. target.get(key);
  600. }
  601. }
  602. function has$1(key, isReadonly = false) {
  603. const target = this["__v_raw" /* RAW */];
  604. const rawTarget = toRaw(target);
  605. const rawKey = toRaw(key);
  606. if (key !== rawKey) {
  607. !isReadonly && track(rawTarget, "has" /* HAS */, key);
  608. }
  609. !isReadonly && track(rawTarget, "has" /* HAS */, rawKey);
  610. return key === rawKey
  611. ? target.has(key)
  612. : target.has(key) || target.has(rawKey);
  613. }
  614. function size(target, isReadonly = false) {
  615. target = target["__v_raw" /* RAW */];
  616. !isReadonly && track(toRaw(target), "iterate" /* ITERATE */, ITERATE_KEY);
  617. return Reflect.get(target, 'size', target);
  618. }
  619. function add(value) {
  620. value = toRaw(value);
  621. const target = toRaw(this);
  622. const proto = getProto(target);
  623. const hadKey = proto.has.call(target, value);
  624. if (!hadKey) {
  625. target.add(value);
  626. trigger(target, "add" /* ADD */, value, value);
  627. }
  628. return this;
  629. }
  630. function set$1(key, value) {
  631. value = toRaw(value);
  632. const target = toRaw(this);
  633. const { has, get } = getProto(target);
  634. let hadKey = has.call(target, key);
  635. if (!hadKey) {
  636. key = toRaw(key);
  637. hadKey = has.call(target, key);
  638. }
  639. else {
  640. checkIdentityKeys(target, has, key);
  641. }
  642. const oldValue = get.call(target, key);
  643. target.set(key, value);
  644. if (!hadKey) {
  645. trigger(target, "add" /* ADD */, key, value);
  646. }
  647. else if (hasChanged(value, oldValue)) {
  648. trigger(target, "set" /* SET */, key, value, oldValue);
  649. }
  650. return this;
  651. }
  652. function deleteEntry(key) {
  653. const target = toRaw(this);
  654. const { has, get } = getProto(target);
  655. let hadKey = has.call(target, key);
  656. if (!hadKey) {
  657. key = toRaw(key);
  658. hadKey = has.call(target, key);
  659. }
  660. else {
  661. checkIdentityKeys(target, has, key);
  662. }
  663. const oldValue = get ? get.call(target, key) : undefined;
  664. // forward the operation before queueing reactions
  665. const result = target.delete(key);
  666. if (hadKey) {
  667. trigger(target, "delete" /* DELETE */, key, undefined, oldValue);
  668. }
  669. return result;
  670. }
  671. function clear() {
  672. const target = toRaw(this);
  673. const hadItems = target.size !== 0;
  674. const oldTarget = isMap(target)
  675. ? new Map(target)
  676. : new Set(target)
  677. ;
  678. // forward the operation before queueing reactions
  679. const result = target.clear();
  680. if (hadItems) {
  681. trigger(target, "clear" /* CLEAR */, undefined, undefined, oldTarget);
  682. }
  683. return result;
  684. }
  685. function createForEach(isReadonly, isShallow) {
  686. return function forEach(callback, thisArg) {
  687. const observed = this;
  688. const target = observed["__v_raw" /* RAW */];
  689. const rawTarget = toRaw(target);
  690. const wrap = isShallow ? toShallow : isReadonly ? toReadonly : toReactive;
  691. !isReadonly && track(rawTarget, "iterate" /* ITERATE */, ITERATE_KEY);
  692. return target.forEach((value, key) => {
  693. // important: make sure the callback is
  694. // 1. invoked with the reactive map as `this` and 3rd arg
  695. // 2. the value received should be a corresponding reactive/readonly.
  696. return callback.call(thisArg, wrap(value), wrap(key), observed);
  697. });
  698. };
  699. }
  700. function createIterableMethod(method, isReadonly, isShallow) {
  701. return function (...args) {
  702. const target = this["__v_raw" /* RAW */];
  703. const rawTarget = toRaw(target);
  704. const targetIsMap = isMap(rawTarget);
  705. const isPair = method === 'entries' || (method === Symbol.iterator && targetIsMap);
  706. const isKeyOnly = method === 'keys' && targetIsMap;
  707. const innerIterator = target[method](...args);
  708. const wrap = isShallow ? toShallow : isReadonly ? toReadonly : toReactive;
  709. !isReadonly &&
  710. track(rawTarget, "iterate" /* ITERATE */, isKeyOnly ? MAP_KEY_ITERATE_KEY : ITERATE_KEY);
  711. // return a wrapped iterator which returns observed versions of the
  712. // values emitted from the real iterator
  713. return {
  714. // iterator protocol
  715. next() {
  716. const { value, done } = innerIterator.next();
  717. return done
  718. ? { value, done }
  719. : {
  720. value: isPair ? [wrap(value[0]), wrap(value[1])] : wrap(value),
  721. done
  722. };
  723. },
  724. // iterable protocol
  725. [Symbol.iterator]() {
  726. return this;
  727. }
  728. };
  729. };
  730. }
  731. function createReadonlyMethod(type) {
  732. return function (...args) {
  733. {
  734. const key = args[0] ? `on key "${args[0]}" ` : ``;
  735. console.warn(`${capitalize(type)} operation ${key}failed: target is readonly.`, toRaw(this));
  736. }
  737. return type === "delete" /* DELETE */ ? false : this;
  738. };
  739. }
  740. function createInstrumentations() {
  741. const mutableInstrumentations = {
  742. get(key) {
  743. return get$1(this, key);
  744. },
  745. get size() {
  746. return size(this);
  747. },
  748. has: has$1,
  749. add,
  750. set: set$1,
  751. delete: deleteEntry,
  752. clear,
  753. forEach: createForEach(false, false)
  754. };
  755. const shallowInstrumentations = {
  756. get(key) {
  757. return get$1(this, key, false, true);
  758. },
  759. get size() {
  760. return size(this);
  761. },
  762. has: has$1,
  763. add,
  764. set: set$1,
  765. delete: deleteEntry,
  766. clear,
  767. forEach: createForEach(false, true)
  768. };
  769. const readonlyInstrumentations = {
  770. get(key) {
  771. return get$1(this, key, true);
  772. },
  773. get size() {
  774. return size(this, true);
  775. },
  776. has(key) {
  777. return has$1.call(this, key, true);
  778. },
  779. add: createReadonlyMethod("add" /* ADD */),
  780. set: createReadonlyMethod("set" /* SET */),
  781. delete: createReadonlyMethod("delete" /* DELETE */),
  782. clear: createReadonlyMethod("clear" /* CLEAR */),
  783. forEach: createForEach(true, false)
  784. };
  785. const shallowReadonlyInstrumentations = {
  786. get(key) {
  787. return get$1(this, key, true, true);
  788. },
  789. get size() {
  790. return size(this, true);
  791. },
  792. has(key) {
  793. return has$1.call(this, key, true);
  794. },
  795. add: createReadonlyMethod("add" /* ADD */),
  796. set: createReadonlyMethod("set" /* SET */),
  797. delete: createReadonlyMethod("delete" /* DELETE */),
  798. clear: createReadonlyMethod("clear" /* CLEAR */),
  799. forEach: createForEach(true, true)
  800. };
  801. const iteratorMethods = ['keys', 'values', 'entries', Symbol.iterator];
  802. iteratorMethods.forEach(method => {
  803. mutableInstrumentations[method] = createIterableMethod(method, false, false);
  804. readonlyInstrumentations[method] = createIterableMethod(method, true, false);
  805. shallowInstrumentations[method] = createIterableMethod(method, false, true);
  806. shallowReadonlyInstrumentations[method] = createIterableMethod(method, true, true);
  807. });
  808. return [
  809. mutableInstrumentations,
  810. readonlyInstrumentations,
  811. shallowInstrumentations,
  812. shallowReadonlyInstrumentations
  813. ];
  814. }
  815. const [mutableInstrumentations, readonlyInstrumentations, shallowInstrumentations, shallowReadonlyInstrumentations] = /* #__PURE__*/ createInstrumentations();
  816. function createInstrumentationGetter(isReadonly, shallow) {
  817. const instrumentations = shallow
  818. ? isReadonly
  819. ? shallowReadonlyInstrumentations
  820. : shallowInstrumentations
  821. : isReadonly
  822. ? readonlyInstrumentations
  823. : mutableInstrumentations;
  824. return (target, key, receiver) => {
  825. if (key === "__v_isReactive" /* IS_REACTIVE */) {
  826. return !isReadonly;
  827. }
  828. else if (key === "__v_isReadonly" /* IS_READONLY */) {
  829. return isReadonly;
  830. }
  831. else if (key === "__v_raw" /* RAW */) {
  832. return target;
  833. }
  834. return Reflect.get(hasOwn(instrumentations, key) && key in target
  835. ? instrumentations
  836. : target, key, receiver);
  837. };
  838. }
  839. const mutableCollectionHandlers = {
  840. get: /*#__PURE__*/ createInstrumentationGetter(false, false)
  841. };
  842. const shallowCollectionHandlers = {
  843. get: /*#__PURE__*/ createInstrumentationGetter(false, true)
  844. };
  845. const readonlyCollectionHandlers = {
  846. get: /*#__PURE__*/ createInstrumentationGetter(true, false)
  847. };
  848. const shallowReadonlyCollectionHandlers = {
  849. get: /*#__PURE__*/ createInstrumentationGetter(true, true)
  850. };
  851. function checkIdentityKeys(target, has, key) {
  852. const rawKey = toRaw(key);
  853. if (rawKey !== key && has.call(target, rawKey)) {
  854. const type = toRawType(target);
  855. console.warn(`Reactive ${type} contains both the raw and reactive ` +
  856. `versions of the same object${type === `Map` ? ` as keys` : ``}, ` +
  857. `which can lead to inconsistencies. ` +
  858. `Avoid differentiating between the raw and reactive versions ` +
  859. `of an object and only use the reactive version if possible.`);
  860. }
  861. }
  862. const reactiveMap = new WeakMap();
  863. const shallowReactiveMap = new WeakMap();
  864. const readonlyMap = new WeakMap();
  865. const shallowReadonlyMap = new WeakMap();
  866. function targetTypeMap(rawType) {
  867. switch (rawType) {
  868. case 'Object':
  869. case 'Array':
  870. return 1 /* COMMON */;
  871. case 'Map':
  872. case 'Set':
  873. case 'WeakMap':
  874. case 'WeakSet':
  875. return 2 /* COLLECTION */;
  876. default:
  877. return 0 /* INVALID */;
  878. }
  879. }
  880. function getTargetType(value) {
  881. return value["__v_skip" /* SKIP */] || !Object.isExtensible(value)
  882. ? 0 /* INVALID */
  883. : targetTypeMap(toRawType(value));
  884. }
  885. function reactive(target) {
  886. // if trying to observe a readonly proxy, return the readonly version.
  887. if (target && target["__v_isReadonly" /* IS_READONLY */]) {
  888. return target;
  889. }
  890. return createReactiveObject(target, false, mutableHandlers, mutableCollectionHandlers, reactiveMap);
  891. }
  892. /**
  893. * Return a shallowly-reactive copy of the original object, where only the root
  894. * level properties are reactive. It also does not auto-unwrap refs (even at the
  895. * root level).
  896. */
  897. function shallowReactive(target) {
  898. return createReactiveObject(target, false, shallowReactiveHandlers, shallowCollectionHandlers, shallowReactiveMap);
  899. }
  900. /**
  901. * Creates a readonly copy of the original object. Note the returned copy is not
  902. * made reactive, but `readonly` can be called on an already reactive object.
  903. */
  904. function readonly(target) {
  905. return createReactiveObject(target, true, readonlyHandlers, readonlyCollectionHandlers, readonlyMap);
  906. }
  907. /**
  908. * Returns a reactive-copy of the original object, where only the root level
  909. * properties are readonly, and does NOT unwrap refs nor recursively convert
  910. * returned properties.
  911. * This is used for creating the props proxy object for stateful components.
  912. */
  913. function shallowReadonly(target) {
  914. return createReactiveObject(target, true, shallowReadonlyHandlers, shallowReadonlyCollectionHandlers, shallowReadonlyMap);
  915. }
  916. function createReactiveObject(target, isReadonly, baseHandlers, collectionHandlers, proxyMap) {
  917. if (!isObject(target)) {
  918. {
  919. console.warn(`value cannot be made reactive: ${String(target)}`);
  920. }
  921. return target;
  922. }
  923. // target is already a Proxy, return it.
  924. // exception: calling readonly() on a reactive object
  925. if (target["__v_raw" /* RAW */] &&
  926. !(isReadonly && target["__v_isReactive" /* IS_REACTIVE */])) {
  927. return target;
  928. }
  929. // target already has corresponding Proxy
  930. const existingProxy = proxyMap.get(target);
  931. if (existingProxy) {
  932. return existingProxy;
  933. }
  934. // only a whitelist of value types can be observed.
  935. const targetType = getTargetType(target);
  936. if (targetType === 0 /* INVALID */) {
  937. return target;
  938. }
  939. const proxy = new Proxy(target, targetType === 2 /* COLLECTION */ ? collectionHandlers : baseHandlers);
  940. proxyMap.set(target, proxy);
  941. return proxy;
  942. }
  943. function isReactive(value) {
  944. if (isReadonly(value)) {
  945. return isReactive(value["__v_raw" /* RAW */]);
  946. }
  947. return !!(value && value["__v_isReactive" /* IS_REACTIVE */]);
  948. }
  949. function isReadonly(value) {
  950. return !!(value && value["__v_isReadonly" /* IS_READONLY */]);
  951. }
  952. function isProxy(value) {
  953. return isReactive(value) || isReadonly(value);
  954. }
  955. function toRaw(observed) {
  956. const raw = observed && observed["__v_raw" /* RAW */];
  957. return raw ? toRaw(raw) : observed;
  958. }
  959. function markRaw(value) {
  960. def(value, "__v_skip" /* SKIP */, true);
  961. return value;
  962. }
  963. const toReactive = (value) => isObject(value) ? reactive(value) : value;
  964. const toReadonly = (value) => isObject(value) ? readonly(value) : value;
  965. function trackRefValue(ref) {
  966. if (isTracking()) {
  967. ref = toRaw(ref);
  968. if (!ref.dep) {
  969. ref.dep = createDep();
  970. }
  971. {
  972. trackEffects(ref.dep, {
  973. target: ref,
  974. type: "get" /* GET */,
  975. key: 'value'
  976. });
  977. }
  978. }
  979. }
  980. function triggerRefValue(ref, newVal) {
  981. ref = toRaw(ref);
  982. if (ref.dep) {
  983. {
  984. triggerEffects(ref.dep, {
  985. target: ref,
  986. type: "set" /* SET */,
  987. key: 'value',
  988. newValue: newVal
  989. });
  990. }
  991. }
  992. }
  993. function isRef(r) {
  994. return Boolean(r && r.__v_isRef === true);
  995. }
  996. function ref(value) {
  997. return createRef(value, false);
  998. }
  999. function shallowRef(value) {
  1000. return createRef(value, true);
  1001. }
  1002. function createRef(rawValue, shallow) {
  1003. if (isRef(rawValue)) {
  1004. return rawValue;
  1005. }
  1006. return new RefImpl(rawValue, shallow);
  1007. }
  1008. class RefImpl {
  1009. constructor(value, _shallow) {
  1010. this._shallow = _shallow;
  1011. this.dep = undefined;
  1012. this.__v_isRef = true;
  1013. this._rawValue = _shallow ? value : toRaw(value);
  1014. this._value = _shallow ? value : toReactive(value);
  1015. }
  1016. get value() {
  1017. trackRefValue(this);
  1018. return this._value;
  1019. }
  1020. set value(newVal) {
  1021. newVal = this._shallow ? newVal : toRaw(newVal);
  1022. if (hasChanged(newVal, this._rawValue)) {
  1023. this._rawValue = newVal;
  1024. this._value = this._shallow ? newVal : toReactive(newVal);
  1025. triggerRefValue(this, newVal);
  1026. }
  1027. }
  1028. }
  1029. function triggerRef(ref) {
  1030. triggerRefValue(ref, ref.value );
  1031. }
  1032. function unref(ref) {
  1033. return isRef(ref) ? ref.value : ref;
  1034. }
  1035. const shallowUnwrapHandlers = {
  1036. get: (target, key, receiver) => unref(Reflect.get(target, key, receiver)),
  1037. set: (target, key, value, receiver) => {
  1038. const oldValue = target[key];
  1039. if (isRef(oldValue) && !isRef(value)) {
  1040. oldValue.value = value;
  1041. return true;
  1042. }
  1043. else {
  1044. return Reflect.set(target, key, value, receiver);
  1045. }
  1046. }
  1047. };
  1048. function proxyRefs(objectWithRefs) {
  1049. return isReactive(objectWithRefs)
  1050. ? objectWithRefs
  1051. : new Proxy(objectWithRefs, shallowUnwrapHandlers);
  1052. }
  1053. class CustomRefImpl {
  1054. constructor(factory) {
  1055. this.dep = undefined;
  1056. this.__v_isRef = true;
  1057. const { get, set } = factory(() => trackRefValue(this), () => triggerRefValue(this));
  1058. this._get = get;
  1059. this._set = set;
  1060. }
  1061. get value() {
  1062. return this._get();
  1063. }
  1064. set value(newVal) {
  1065. this._set(newVal);
  1066. }
  1067. }
  1068. function customRef(factory) {
  1069. return new CustomRefImpl(factory);
  1070. }
  1071. function toRefs(object) {
  1072. if (!isProxy(object)) {
  1073. console.warn(`toRefs() expects a reactive object but received a plain one.`);
  1074. }
  1075. const ret = isArray(object) ? new Array(object.length) : {};
  1076. for (const key in object) {
  1077. ret[key] = toRef(object, key);
  1078. }
  1079. return ret;
  1080. }
  1081. class ObjectRefImpl {
  1082. constructor(_object, _key, _defaultValue) {
  1083. this._object = _object;
  1084. this._key = _key;
  1085. this._defaultValue = _defaultValue;
  1086. this.__v_isRef = true;
  1087. }
  1088. get value() {
  1089. const val = this._object[this._key];
  1090. return val === undefined ? this._defaultValue : val;
  1091. }
  1092. set value(newVal) {
  1093. this._object[this._key] = newVal;
  1094. }
  1095. }
  1096. function toRef(object, key, defaultValue) {
  1097. const val = object[key];
  1098. return isRef(val)
  1099. ? val
  1100. : new ObjectRefImpl(object, key, defaultValue);
  1101. }
  1102. class ComputedRefImpl {
  1103. constructor(getter, _setter, isReadonly) {
  1104. this._setter = _setter;
  1105. this.dep = undefined;
  1106. this._dirty = true;
  1107. this.__v_isRef = true;
  1108. this.effect = new ReactiveEffect(getter, () => {
  1109. if (!this._dirty) {
  1110. this._dirty = true;
  1111. triggerRefValue(this);
  1112. }
  1113. });
  1114. this["__v_isReadonly" /* IS_READONLY */] = isReadonly;
  1115. }
  1116. get value() {
  1117. // the computed ref may get wrapped by other proxies e.g. readonly() #3376
  1118. const self = toRaw(this);
  1119. trackRefValue(self);
  1120. if (self._dirty) {
  1121. self._dirty = false;
  1122. self._value = self.effect.run();
  1123. }
  1124. return self._value;
  1125. }
  1126. set value(newValue) {
  1127. this._setter(newValue);
  1128. }
  1129. }
  1130. function computed(getterOrOptions, debugOptions) {
  1131. let getter;
  1132. let setter;
  1133. const onlyGetter = isFunction(getterOrOptions);
  1134. if (onlyGetter) {
  1135. getter = getterOrOptions;
  1136. setter = () => {
  1137. console.warn('Write operation failed: computed value is readonly');
  1138. }
  1139. ;
  1140. }
  1141. else {
  1142. getter = getterOrOptions.get;
  1143. setter = getterOrOptions.set;
  1144. }
  1145. const cRef = new ComputedRefImpl(getter, setter, onlyGetter || !setter);
  1146. if (debugOptions) {
  1147. cRef.effect.onTrack = debugOptions.onTrack;
  1148. cRef.effect.onTrigger = debugOptions.onTrigger;
  1149. }
  1150. return cRef;
  1151. }
  1152. var _a;
  1153. const tick = Promise.resolve();
  1154. const queue = [];
  1155. let queued = false;
  1156. const scheduler = (fn) => {
  1157. queue.push(fn);
  1158. if (!queued) {
  1159. queued = true;
  1160. tick.then(flush);
  1161. }
  1162. };
  1163. const flush = () => {
  1164. for (let i = 0; i < queue.length; i++) {
  1165. queue[i]();
  1166. }
  1167. queue.length = 0;
  1168. queued = false;
  1169. };
  1170. class DeferredComputedRefImpl {
  1171. constructor(getter) {
  1172. this.dep = undefined;
  1173. this._dirty = true;
  1174. this.__v_isRef = true;
  1175. this[_a] = true;
  1176. let compareTarget;
  1177. let hasCompareTarget = false;
  1178. let scheduled = false;
  1179. this.effect = new ReactiveEffect(getter, (computedTrigger) => {
  1180. if (this.dep) {
  1181. if (computedTrigger) {
  1182. compareTarget = this._value;
  1183. hasCompareTarget = true;
  1184. }
  1185. else if (!scheduled) {
  1186. const valueToCompare = hasCompareTarget ? compareTarget : this._value;
  1187. scheduled = true;
  1188. hasCompareTarget = false;
  1189. scheduler(() => {
  1190. if (this.effect.active && this._get() !== valueToCompare) {
  1191. triggerRefValue(this);
  1192. }
  1193. scheduled = false;
  1194. });
  1195. }
  1196. // chained upstream computeds are notified synchronously to ensure
  1197. // value invalidation in case of sync access; normal effects are
  1198. // deferred to be triggered in scheduler.
  1199. for (const e of this.dep) {
  1200. if (e.computed) {
  1201. e.scheduler(true /* computedTrigger */);
  1202. }
  1203. }
  1204. }
  1205. this._dirty = true;
  1206. });
  1207. this.effect.computed = true;
  1208. }
  1209. _get() {
  1210. if (this._dirty) {
  1211. this._dirty = false;
  1212. return (this._value = this.effect.run());
  1213. }
  1214. return this._value;
  1215. }
  1216. get value() {
  1217. trackRefValue(this);
  1218. // the computed ref may get wrapped by other proxies e.g. readonly() #3376
  1219. return toRaw(this)._get();
  1220. }
  1221. }
  1222. _a = "__v_isReadonly" /* IS_READONLY */;
  1223. function deferredComputed(getter) {
  1224. return new DeferredComputedRefImpl(getter);
  1225. }
  1226. export { EffectScope, ITERATE_KEY, ReactiveEffect, computed, customRef, deferredComputed, effect, effectScope, enableTracking, getCurrentScope, isProxy, isReactive, isReadonly, isRef, markRaw, onScopeDispose, pauseTracking, proxyRefs, reactive, readonly, ref, resetTracking, shallowReactive, shallowReadonly, shallowRef, stop, toRaw, toRef, toRefs, track, trigger, triggerRef, unref };