UNPKG

ember-source

Version:

A JavaScript framework for creating ambitious web applications

1,543 lines (1,361 loc) 95 kB
import { meta, peekMeta } from '../@ember/-internals/meta/lib/meta.js'; import { d as setListeners, f as setupMandatorySetter, e as isObject, h as setWithMandatorySetter } from './mandatory-setter-1UQhiJOb.js'; import { isDevelopingApp } from '@embroider/macros'; import { a as assert, b as inspect, w as warn, c as debug } from './index-DTxy4Zgx.js'; import { registerDestructor, isDestroyed } from '../@glimmer/destroyable/index.js'; import { tagMetaFor, valueForTag, CURRENT_TAG, validateTag, tagFor, CONSTANT_TAG, dirtyTagFor, combine, updateTag as UPDATE_TAG, createUpdatableTag, untrack, ALLOW_CYCLES, consumeTag, track, isTracking, trackedData } from '../@glimmer/validator/index.js'; import { getCustomTagFor } from '../@glimmer/manager/index.js'; import { E as ENV } from './env-BJLX2Arx.js'; import { onErrorTarget } from '../@ember/-internals/error-handling/index.js'; import { t as toString, s as symbol } from './to-string-D8i3mjEU.js'; import { s as setProxy } from './is_proxy-Dmis-70B.js'; import { isEmberArray } from '../@ember/array/-internals.js'; import { C as Cache } from './cache-qDyqAcpg.js'; import Version from '../ember/version.js'; import { getOwner } from '../@ember/-internals/owner/index.js'; import Backburner from '../backburner.js/index.js'; /** @module @ember/object */ function addListener(obj, eventName, target, method, once, sync = true) { (isDevelopingApp() && !(Boolean(obj) && Boolean(eventName)) && assert('You must pass at least an object and event name to addListener', Boolean(obj) && Boolean(eventName))); if (!method && 'function' === typeof target) { method = target; target = null; } meta(obj).addToListeners(eventName, target, method, once === true, sync); } /** Remove an event listener Arguments should match those passed to `addListener`. @method removeListener @static @for @ember/object/events @param obj @param {String} eventName @param {Object|Function} target A target object or a function @param {Function|String} method A function or the name of a function to be called on `target` @public */ function removeListener(obj, eventName, targetOrFunction, functionOrName) { (isDevelopingApp() && !(Boolean(obj) && Boolean(eventName) && (typeof targetOrFunction === 'function' || typeof targetOrFunction === 'object' && Boolean(functionOrName))) && assert('You must pass at least an object, event name, and method or target and method/method name to removeListener', Boolean(obj) && Boolean(eventName) && (typeof targetOrFunction === 'function' || typeof targetOrFunction === 'object' && Boolean(functionOrName)))); let target, method; if (typeof targetOrFunction === 'object') { target = targetOrFunction; method = functionOrName; } else { target = null; method = targetOrFunction; } let m = meta(obj); m.removeFromListeners(eventName, target, method); } /** Send an event. The execution of suspended listeners is skipped, and once listeners are removed. A listener without a target is executed on the passed object. If an array of actions is not passed, the actions stored on the passed object are invoked. @method sendEvent @static @for @ember/object/events @param obj @param {String} eventName @param {Array} params Optional parameters for each listener. @return {Boolean} if the event was delivered to one or more actions @public */ function sendEvent(obj, eventName, params, actions, _meta) { if (actions === undefined) { let meta = _meta === undefined ? peekMeta(obj) : _meta; actions = meta !== null ? meta.matchingListeners(eventName) : undefined; } if (actions === undefined || actions.length === 0) { return false; } for (let i = actions.length - 3; i >= 0; i -= 3) { // looping in reverse for once listeners let target = actions[i]; let method = actions[i + 1]; let once = actions[i + 2]; if (!method) { continue; } if (once) { removeListener(obj, eventName, target, method); } if (!target) { target = obj; } let type = typeof method; if (type === 'string' || type === 'symbol') { method = target[method]; } method.apply(target, params); } return true; } /** @public @method hasListeners @static @for @ember/object/events @param obj @param {String} eventName @return {Boolean} if `obj` has listeners for event `eventName` */ function hasListeners(obj, eventName) { let meta = peekMeta(obj); if (meta === null) { return false; } let matched = meta.matchingListeners(eventName); return matched !== undefined && matched.length > 0; } /** Define a property as a function that should be executed when a specified event or events are triggered. ``` javascript import EmberObject from '@ember/object'; import { on } from '@ember/object/evented'; import { sendEvent } from '@ember/object/events'; let Job = EmberObject.extend({ logCompleted: on('completed', function() { console.log('Job completed!'); }) }); let job = Job.create(); sendEvent(job, 'completed'); // Logs 'Job completed!' ``` @method on @static @for @ember/object/evented @param {String} eventNames* @param {Function} func @return {Function} the listener function, passed as last argument to on(...) @public */ function on(...args) { let func = args.pop(); let events = args; (isDevelopingApp() && !(typeof func === 'function') && assert('on expects function as last argument', typeof func === 'function')); (isDevelopingApp() && !(events.length > 0 && events.every(p => typeof p === 'string' && p.length > 0)) && assert('on called without valid event names', events.length > 0 && events.every(p => typeof p === 'string' && p.length > 0))); setListeners(func, events); return func; } let currentRunLoop = null; function _getCurrentRunLoop() { return currentRunLoop; } function onBegin(current) { currentRunLoop = current; } function onEnd(_current, next) { currentRunLoop = next; flushAsyncObservers(); } function flush(queueName, next) { if (queueName === 'render' || queueName === _rsvpErrorQueue) { flushAsyncObservers(); } next(); } const _rsvpErrorQueue = `${Math.random()}${Date.now()}`.replace('.', ''); /** Array of named queues. This array determines the order in which queues are flushed at the end of the RunLoop. You can define your own queues by simply adding the queue name to this array. Normally you should not need to inspect or modify this property. @property queues @type Array @default ['actions', 'destroy'] @private */ const _queues = ['actions', // used in router transitions to prevent unnecessary loading state entry // if all context promises resolve on the 'actions' queue first 'routerTransitions', 'render', 'afterRender', 'destroy', // used to re-throw unhandled RSVP rejection errors specifically in this // position to avoid breaking anything rendered in the other sections _rsvpErrorQueue]; /** * @internal * @private */ const _backburner = new Backburner(_queues, { defaultQueue: 'actions', onBegin, onEnd, onErrorTarget, onErrorMethod: 'onerror', flush }); /** @module @ember/runloop */ // .......................................................... // run - this is ideally the only public API the dev sees // /** Runs the passed target and method inside of a RunLoop, ensuring any deferred actions including bindings and views updates are flushed at the end. Normally you should not need to invoke this method yourself. However if you are implementing raw event handlers when interfacing with other libraries or plugins, you should probably wrap all of your code inside this call. ```javascript import { run } from '@ember/runloop'; run(function() { // code to be executed within a RunLoop }); ``` @method run @for @ember/runloop @static @param {Object} [target] target of method to call @param {Function|String} method Method to invoke. May be a function or a string. If you pass a string then it will be looked up on the passed target. @param {Object} [args*] Any additional arguments you wish to pass to the method. @return {Object} return value from invoking the passed function. @public */ function run(...args) { // @ts-expect-error TS doesn't like our spread args return _backburner.run(...args); } /** If no run-loop is present, it creates a new one. If a run loop is present it will queue itself to run on the existing run-loops action queue. Please note: This is not for normal usage, and should be used sparingly. If invoked when not within a run loop: ```javascript import { join } from '@ember/runloop'; join(function() { // creates a new run-loop }); ``` Alternatively, if called within an existing run loop: ```javascript import { run, join } from '@ember/runloop'; run(function() { // creates a new run-loop join(function() { // joins with the existing run-loop, and queues for invocation on // the existing run-loops action queue. }); }); ``` @method join @static @for @ember/runloop @param {Object} [target] target of method to call @param {Function|String} method Method to invoke. May be a function or a string. If you pass a string then it will be looked up on the passed target. @param {Object} [args*] Any additional arguments you wish to pass to the method. @return {Object} Return value from invoking the passed function. Please note, when called within an existing loop, no return value is possible. @public */ function join(methodOrTarget, methodOrArg, ...additionalArgs) { return _backburner.join(methodOrTarget, methodOrArg, ...additionalArgs); } /** Allows you to specify which context to call the specified function in while adding the execution of that function to the Ember run loop. This ability makes this method a great way to asynchronously integrate third-party libraries into your Ember application. `bind` takes two main arguments, the desired context and the function to invoke in that context. Any additional arguments will be supplied as arguments to the function that is passed in. Let's use the creation of a TinyMCE component as an example. Currently, TinyMCE provides a setup configuration option we can use to do some processing after the TinyMCE instance is initialized but before it is actually rendered. We can use that setup option to do some additional setup for our component. The component itself could look something like the following: ```app/components/rich-text-editor.js import Component from '@ember/component'; import { on } from '@ember/object/evented'; import { bind } from '@ember/runloop'; export default Component.extend({ initializeTinyMCE: on('didInsertElement', function() { tinymce.init({ selector: '#' + this.$().prop('id'), setup: bind(this, this.setupEditor) }); }), didInsertElement() { tinymce.init({ selector: '#' + this.$().prop('id'), setup: bind(this, this.setupEditor) }); } setupEditor(editor) { this.set('editor', editor); editor.on('change', function() { console.log('content changed!'); }); } }); ``` In this example, we use `bind` to bind the setupEditor method to the context of the RichTextEditor component and to have the invocation of that method be safely handled and executed by the Ember run loop. @method bind @static @for @ember/runloop @param {Object} [target] target of method to call @param {Function|String} method Method to invoke. May be a function or a string. If you pass a string then it will be looked up on the passed target. @param {Object} [args*] Any additional arguments you wish to pass to the method. @return {Function} returns a new function that will always have a particular context @since 1.4.0 @public */ // This final fallback is the equivalent of the (quite unsafe!) type for `bind` // from TS' defs for `Function.prototype.bind`. In general, it means we have a // loss of safety if we do not function bind(...curried) { (isDevelopingApp() && !(function (methodOrTarget, methodOrArg) { // Applies the same logic as backburner parseArgs for detecting if a method // is actually being passed. let length = arguments.length; if (length === 0) { return false; } else if (length === 1) { return typeof methodOrTarget === 'function'; } else { return typeof methodOrArg === 'function' || // second argument is a function methodOrTarget !== null && typeof methodOrArg === 'string' && methodOrArg in methodOrTarget || // second argument is the name of a method in first argument typeof methodOrTarget === 'function' //first argument is a function ; } // @ts-expect-error TS doesn't like our spread args }(...curried)) && assert('could not find a suitable method to bind', function (methodOrTarget, methodOrArg) { let length = arguments.length; if (length === 0) { return false; } else if (length === 1) { return typeof methodOrTarget === 'function'; } else { return typeof methodOrArg === 'function' || methodOrTarget !== null && typeof methodOrArg === 'string' && methodOrArg in methodOrTarget || typeof methodOrTarget === 'function'; } }(...curried))); // @ts-expect-error TS doesn't like our spread args return (...args) => join(...curried.concat(args)); } /** Begins a new RunLoop. Any deferred actions invoked after the begin will be buffered until you invoke a matching call to `end()`. This is a lower-level way to use a RunLoop instead of using `run()`. ```javascript import { begin, end } from '@ember/runloop'; begin(); // code to be executed within a RunLoop end(); ``` @method begin @static @for @ember/runloop @return {void} @public */ function begin() { _backburner.begin(); } /** Ends a RunLoop. This must be called sometime after you call `begin()` to flush any deferred actions. This is a lower-level way to use a RunLoop instead of using `run()`. ```javascript import { begin, end } from '@ember/runloop'; begin(); // code to be executed within a RunLoop end(); ``` @method end @static @for @ember/runloop @return {void} @public */ function end() { _backburner.end(); } /** Adds the passed target/method and any optional arguments to the named queue to be executed at the end of the RunLoop. If you have not already started a RunLoop when calling this method one will be started for you automatically. At the end of a RunLoop, any methods scheduled in this way will be invoked. Methods will be invoked in an order matching the named queues defined in the `queues` property. ```javascript import { schedule } from '@ember/runloop'; schedule('afterRender', this, function() { // this will be executed in the 'afterRender' queue console.log('scheduled on afterRender queue'); }); schedule('actions', this, function() { // this will be executed in the 'actions' queue console.log('scheduled on actions queue'); }); // Note the functions will be run in order based on the run queues order. // Output would be: // scheduled on actions queue // scheduled on afterRender queue ``` @method schedule @static @for @ember/runloop @param {String} queue The name of the queue to schedule against. Default queues is 'actions' @param {Object} [target] target object to use as the context when invoking a method. @param {String|Function} method The method to invoke. If you pass a string it will be resolved on the target object at the time the scheduled item is invoked allowing you to change the target function. @param {Object} [arguments*] Optional arguments to be passed to the queued method. @return {*} Timer information for use in canceling, see `cancel`. @public */ function schedule(...args) { // @ts-expect-error TS doesn't like the rest args here return _backburner.schedule(...args); } // Used by global test teardown function _hasScheduledTimers() { return _backburner.hasTimers(); } // Used by global test teardown function _cancelTimers() { _backburner.cancelTimers(); } /** Invokes the passed target/method and optional arguments after a specified period of time. The last parameter of this method must always be a number of milliseconds. You should use this method whenever you need to run some action after a period of time instead of using `setTimeout()`. This method will ensure that items that expire during the same script execution cycle all execute together, which is often more efficient than using a real setTimeout. ```javascript import { later } from '@ember/runloop'; later(myContext, function() { // code here will execute within a RunLoop in about 500ms with this == myContext }, 500); ``` @method later @static @for @ember/runloop @param {Object} [target] target of method to invoke @param {Function|String} method The method to invoke. If you pass a string it will be resolved on the target at the time the method is invoked. @param {Object} [args*] Optional arguments to pass to the timeout. @param {Number} wait Number of milliseconds to wait. @return {*} Timer information for use in canceling, see `cancel`. @public */ function later(...args) { return _backburner.later(...args); } /** Schedule a function to run one time during the current RunLoop. This is equivalent to calling `scheduleOnce` with the "actions" queue. @method once @static @for @ember/runloop @param {Object} [target] The target of the method to invoke. @param {Function|String} method The method to invoke. If you pass a string it will be resolved on the target at the time the method is invoked. @param {Object} [args*] Optional arguments to pass to the timeout. @return {Object} Timer information for use in canceling, see `cancel`. @public */ function once(...args) { // @ts-expect-error TS doesn't like the rest args here return _backburner.scheduleOnce('actions', ...args); } /** Schedules a function to run one time in a given queue of the current RunLoop. Calling this method with the same queue/target/method combination will have no effect (past the initial call). Note that although you can pass optional arguments these will not be considered when looking for duplicates. New arguments will replace previous calls. ```javascript import { run, scheduleOnce } from '@ember/runloop'; function sayHi() { console.log('hi'); } run(function() { scheduleOnce('afterRender', myContext, sayHi); scheduleOnce('afterRender', myContext, sayHi); // sayHi will only be executed once, in the afterRender queue of the RunLoop }); ``` Also note that for `scheduleOnce` to prevent additional calls, you need to pass the same function instance. The following case works as expected: ```javascript function log() { console.log('Logging only once'); } function scheduleIt() { scheduleOnce('actions', myContext, log); } scheduleIt(); scheduleIt(); ``` But this other case will schedule the function multiple times: ```javascript import { scheduleOnce } from '@ember/runloop'; function scheduleIt() { scheduleOnce('actions', myContext, function() { console.log('Closure'); }); } scheduleIt(); scheduleIt(); // "Closure" will print twice, even though we're using `scheduleOnce`, // because the function we pass to it won't match the // previously scheduled operation. ``` Available queues, and their order, can be found at `queues` @method scheduleOnce @static @for @ember/runloop @param {String} [queue] The name of the queue to schedule against. Default queues is 'actions'. @param {Object} [target] The target of the method to invoke. @param {Function|String} method The method to invoke. If you pass a string it will be resolved on the target at the time the method is invoked. @param {Object} [args*] Optional arguments to pass to the timeout. @return {Object} Timer information for use in canceling, see `cancel`. @public */ function scheduleOnce(...args) { // @ts-expect-error TS doesn't like the rest args here return _backburner.scheduleOnce(...args); } /** Schedules an item to run from within a separate run loop, after control has been returned to the system. This is equivalent to calling `later` with a wait time of 1ms. ```javascript import { next } from '@ember/runloop'; next(myContext, function() { // code to be executed in the next run loop, // which will be scheduled after the current one }); ``` Multiple operations scheduled with `next` will coalesce into the same later run loop, along with any other operations scheduled by `later` that expire right around the same time that `next` operations will fire. Note that there are often alternatives to using `next`. For instance, if you'd like to schedule an operation to happen after all DOM element operations have completed within the current run loop, you can make use of the `afterRender` run loop queue (added by the `ember-views` package, along with the preceding `render` queue where all the DOM element operations happen). Example: ```app/components/my-component.js import Component from '@ember/component'; import { scheduleOnce } from '@ember/runloop'; export Component.extend({ didInsertElement() { this._super(...arguments); scheduleOnce('afterRender', this, 'processChildElements'); }, processChildElements() { // ... do something with component's child component // elements after they've finished rendering, which // can't be done within this component's // `didInsertElement` hook because that gets run // before the child elements have been added to the DOM. } }); ``` One benefit of the above approach compared to using `next` is that you will be able to perform DOM/CSS operations before unprocessed elements are rendered to the screen, which may prevent flickering or other artifacts caused by delaying processing until after rendering. The other major benefit to the above approach is that `next` introduces an element of non-determinism, which can make things much harder to test, due to its reliance on `setTimeout`; it's much harder to guarantee the order of scheduled operations when they are scheduled outside of the current run loop, i.e. with `next`. @method next @static @for @ember/runloop @param {Object} [target] target of method to invoke @param {Function|String} method The method to invoke. If you pass a string it will be resolved on the target at the time the method is invoked. @param {Object} [args*] Optional arguments to pass to the timeout. @return {Object} Timer information for use in canceling, see `cancel`. @public */ function next(...args) { return _backburner.later(...args, 1); } /** Cancels a scheduled item. Must be a value returned by `later()`, `once()`, `scheduleOnce()`, `next()`, `debounce()`, or `throttle()`. ```javascript import { next, cancel, later, scheduleOnce, once, throttle, debounce } from '@ember/runloop'; let runNext = next(myContext, function() { // will not be executed }); cancel(runNext); let runLater = later(myContext, function() { // will not be executed }, 500); cancel(runLater); let runScheduleOnce = scheduleOnce('afterRender', myContext, function() { // will not be executed }); cancel(runScheduleOnce); let runOnce = once(myContext, function() { // will not be executed }); cancel(runOnce); let throttle = throttle(myContext, function() { // will not be executed }, 1, false); cancel(throttle); let debounce = debounce(myContext, function() { // will not be executed }, 1); cancel(debounce); let debounceImmediate = debounce(myContext, function() { // will be executed since we passed in true (immediate) }, 100, true); // the 100ms delay until this method can be called again will be canceled cancel(debounceImmediate); ``` @method cancel @static @for @ember/runloop @param {Object} [timer] Timer object to cancel @return {Boolean} true if canceled or false/undefined if it wasn't found @public */ function cancel(timer) { return _backburner.cancel(timer); } /** Delay calling the target method until the debounce period has elapsed with no additional debounce calls. If `debounce` is called again before the specified time has elapsed, the timer is reset and the entire period must pass again before the target method is called. This method should be used when an event may be called multiple times but the action should only be called once when the event is done firing. A common example is for scroll events where you only want updates to happen once scrolling has ceased. ```javascript import { debounce } from '@ember/runloop'; function whoRan() { console.log(this.name + ' ran.'); } let myContext = { name: 'debounce' }; debounce(myContext, whoRan, 150); // less than 150ms passes debounce(myContext, whoRan, 150); // 150ms passes // whoRan is invoked with context myContext // console logs 'debounce ran.' one time. ``` Immediate allows you to run the function immediately, but debounce other calls for this function until the wait time has elapsed. If `debounce` is called again before the specified time has elapsed, the timer is reset and the entire period must pass again before the method can be called again. ```javascript import { debounce } from '@ember/runloop'; function whoRan() { console.log(this.name + ' ran.'); } let myContext = { name: 'debounce' }; debounce(myContext, whoRan, 150, true); // console logs 'debounce ran.' one time immediately. // 100ms passes debounce(myContext, whoRan, 150, true); // 150ms passes and nothing else is logged to the console and // the debouncee is no longer being watched debounce(myContext, whoRan, 150, true); // console logs 'debounce ran.' one time immediately. // 150ms passes and nothing else is logged to the console and // the debouncee is no longer being watched ``` @method debounce @static @for @ember/runloop @param {Object} [target] target of method to invoke @param {Function|String} method The method to invoke. May be a function or a string. If you pass a string then it will be looked up on the passed target. @param {Object} [args*] Optional arguments to pass to the timeout. @param {Number} wait Number of milliseconds to wait. @param {Boolean} immediate Trigger the function on the leading instead of the trailing edge of the wait interval. Defaults to false. @return {Array} Timer information for use in canceling, see `cancel`. @public */ function debounce(...args) { // @ts-expect-error TS doesn't like the rest args here return _backburner.debounce(...args); } /** Ensure that the target method is never called more frequently than the specified spacing period. The target method is called immediately. ```javascript import { throttle } from '@ember/runloop'; function whoRan() { console.log(this.name + ' ran.'); } let myContext = { name: 'throttle' }; throttle(myContext, whoRan, 150); // whoRan is invoked with context myContext // console logs 'throttle ran.' // 50ms passes throttle(myContext, whoRan, 150); // 50ms passes throttle(myContext, whoRan, 150); // 150ms passes throttle(myContext, whoRan, 150); // whoRan is invoked with context myContext // console logs 'throttle ran.' ``` @method throttle @static @for @ember/runloop @param {Object} [target] target of method to invoke @param {Function|String} method The method to invoke. May be a function or a string. If you pass a string then it will be looked up on the passed target. @param {Object} [args*] Optional arguments to pass to the timeout. @param {Number} spacing Number of milliseconds to space out requests. @param {Boolean} immediate Trigger the function on the leading instead of the trailing edge of the wait interval. Defaults to true. @return {Array} Timer information for use in canceling, see `cancel`. @public */ function throttle(...args) { // @ts-expect-error TS doesn't like the rest args here return _backburner.throttle(...args); } const AFTER_OBSERVERS = ':change'; function changeEvent(keyName) { return keyName + AFTER_OBSERVERS; } const SYNC_DEFAULT = !ENV._DEFAULT_ASYNC_OBSERVERS; const SYNC_OBSERVERS = new Map(); const ASYNC_OBSERVERS = new Map(); /** @module @ember/object */ /** @method addObserver @static @for @ember/object/observers @param obj @param {String} path @param {Object|Function} target @param {Function|String} [method] @public */ function addObserver(obj, path, target, method, sync = SYNC_DEFAULT) { let eventName = changeEvent(path); addListener(obj, eventName, target, method, false, sync); let meta = peekMeta(obj); if (meta === null || !(meta.isPrototypeMeta(obj) || meta.isInitializing())) { activateObserver(obj, eventName, sync); } } /** @method removeObserver @static @for @ember/object/observers @param obj @param {String} path @param {Object|Function} target @param {Function|String} [method] @public */ function removeObserver(obj, path, target, method, sync = SYNC_DEFAULT) { let eventName = changeEvent(path); let meta = peekMeta(obj); if (meta === null || !(meta.isPrototypeMeta(obj) || meta.isInitializing())) { deactivateObserver(obj, eventName, sync); } removeListener(obj, eventName, target, method); } function getOrCreateActiveObserversFor(target, sync) { let observerMap = sync === true ? SYNC_OBSERVERS : ASYNC_OBSERVERS; if (!observerMap.has(target)) { observerMap.set(target, new Map()); registerDestructor(target, () => destroyObservers(target), true); } return observerMap.get(target); } function activateObserver(target, eventName, sync = false) { let activeObservers = getOrCreateActiveObserversFor(target, sync); if (activeObservers.has(eventName)) { activeObservers.get(eventName).count++; } else { let path = eventName.substring(0, eventName.lastIndexOf(':')); let tag = getChainTagsForKey(target, path, tagMetaFor(target), peekMeta(target)); activeObservers.set(eventName, { count: 1, path, tag, lastRevision: valueForTag(tag), suspended: false }); } } let DEACTIVATE_SUSPENDED = false; let SCHEDULED_DEACTIVATE = []; function deactivateObserver(target, eventName, sync = false) { if (DEACTIVATE_SUSPENDED === true) { SCHEDULED_DEACTIVATE.push([target, eventName, sync]); return; } let observerMap = sync === true ? SYNC_OBSERVERS : ASYNC_OBSERVERS; let activeObservers = observerMap.get(target); if (activeObservers !== undefined) { let observer = activeObservers.get(eventName); observer.count--; if (observer.count === 0) { activeObservers.delete(eventName); if (activeObservers.size === 0) { observerMap.delete(target); } } } } function suspendedObserverDeactivation() { DEACTIVATE_SUSPENDED = true; } function resumeObserverDeactivation() { DEACTIVATE_SUSPENDED = false; for (let [target, eventName, sync] of SCHEDULED_DEACTIVATE) { deactivateObserver(target, eventName, sync); } SCHEDULED_DEACTIVATE = []; } /** * Primarily used for cases where we are redefining a class, e.g. mixins/reopen * being applied later. Revalidates all the observers, resetting their tags. * * @private * @param target */ function revalidateObservers(target) { if (ASYNC_OBSERVERS.has(target)) { ASYNC_OBSERVERS.get(target).forEach(observer => { observer.tag = getChainTagsForKey(target, observer.path, tagMetaFor(target), peekMeta(target)); observer.lastRevision = valueForTag(observer.tag); }); } if (SYNC_OBSERVERS.has(target)) { SYNC_OBSERVERS.get(target).forEach(observer => { observer.tag = getChainTagsForKey(target, observer.path, tagMetaFor(target), peekMeta(target)); observer.lastRevision = valueForTag(observer.tag); }); } } let lastKnownRevision = 0; function flushAsyncObservers(shouldSchedule = true) { let currentRevision = valueForTag(CURRENT_TAG); if (lastKnownRevision === currentRevision) { return; } lastKnownRevision = currentRevision; ASYNC_OBSERVERS.forEach((activeObservers, target) => { let meta = peekMeta(target); activeObservers.forEach((observer, eventName) => { if (!validateTag(observer.tag, observer.lastRevision)) { let sendObserver = () => { try { sendEvent(target, eventName, [target, observer.path], undefined, meta); } finally { observer.tag = getChainTagsForKey(target, observer.path, tagMetaFor(target), peekMeta(target)); observer.lastRevision = valueForTag(observer.tag); } }; if (shouldSchedule) { schedule('actions', sendObserver); } else { sendObserver(); } } }); }); } function flushSyncObservers() { // When flushing synchronous observers, we know that something has changed (we // only do this during a notifyPropertyChange), so there's no reason to check // a global revision. SYNC_OBSERVERS.forEach((activeObservers, target) => { let meta = peekMeta(target); activeObservers.forEach((observer, eventName) => { if (!observer.suspended && !validateTag(observer.tag, observer.lastRevision)) { try { observer.suspended = true; sendEvent(target, eventName, [target, observer.path], undefined, meta); } finally { observer.tag = getChainTagsForKey(target, observer.path, tagMetaFor(target), peekMeta(target)); observer.lastRevision = valueForTag(observer.tag); observer.suspended = false; } } }); }); } function setObserverSuspended(target, property, suspended) { let activeObservers = SYNC_OBSERVERS.get(target); if (!activeObservers) { return; } let observer = activeObservers.get(changeEvent(property)); if (observer) { observer.suspended = suspended; } } function destroyObservers(target) { if (SYNC_OBSERVERS.size > 0) SYNC_OBSERVERS.delete(target); if (ASYNC_OBSERVERS.size > 0) ASYNC_OBSERVERS.delete(target); } // This is exported for `@tracked`, but should otherwise be avoided. Use `tagForObject`. const SELF_TAG = symbol('SELF_TAG'); function tagForProperty(obj, propertyKey, addMandatorySetter = false, meta) { let customTagFor = getCustomTagFor(obj); if (customTagFor !== undefined) { return customTagFor(obj, propertyKey, addMandatorySetter); } let tag = tagFor(obj, propertyKey, meta); if (isDevelopingApp() && addMandatorySetter) { setupMandatorySetter(tag, obj, propertyKey); } return tag; } function tagForObject(obj) { if (isObject(obj)) { if (isDevelopingApp()) { (isDevelopingApp() && !(!isDestroyed(obj)) && assert(isDestroyed(obj) ? `Cannot create a new tag for \`${toString(obj)}\` after it has been destroyed.` : '', !isDestroyed(obj))); } return tagFor(obj, SELF_TAG); } return CONSTANT_TAG; } function markObjectAsDirty(obj, propertyKey) { dirtyTagFor(obj, propertyKey); dirtyTagFor(obj, SELF_TAG); } const PROPERTY_DID_CHANGE = Symbol('PROPERTY_DID_CHANGE'); function hasPropertyDidChange(obj) { return obj != null && typeof obj === 'object' && typeof obj[PROPERTY_DID_CHANGE] === 'function'; } let deferred = 0; /** This function is called just after an object property has changed. It will notify any observers and clear caches among other things. Normally you will not need to call this method directly but if for some reason you can't directly watch a property you can invoke this method manually. @method notifyPropertyChange @for @ember/object @param {Object} obj The object with the property that will change @param {String} keyName The property key (or path) that will change. @param {Meta} [_meta] The objects meta. @param {unknown} [value] The new value to set for the property @return {void} @since 3.1.0 @public */ function notifyPropertyChange(obj, keyName, _meta, value) { let meta = _meta === undefined ? peekMeta(obj) : _meta; if (meta !== null && (meta.isInitializing() || meta.isPrototypeMeta(obj))) { return; } markObjectAsDirty(obj, keyName); if (deferred <= 0) { flushSyncObservers(); } if (PROPERTY_DID_CHANGE in obj) { // It's redundant to do this here, but we don't want to check above so we can avoid an extra function call in prod. (isDevelopingApp() && !(hasPropertyDidChange(obj)) && assert('property did change hook is invalid', hasPropertyDidChange(obj))); // we need to check the arguments length here; there's a check in Component's `PROPERTY_DID_CHANGE` // that checks its arguments length, so we have to explicitly not call this with `value` // if it is not passed to `notifyPropertyChange` if (arguments.length === 4) { obj[PROPERTY_DID_CHANGE](keyName, value); } else { obj[PROPERTY_DID_CHANGE](keyName); } } } /** @method beginPropertyChanges @chainable @private */ function beginPropertyChanges() { deferred++; suspendedObserverDeactivation(); } /** @method endPropertyChanges @private */ function endPropertyChanges() { deferred--; if (deferred <= 0) { flushSyncObservers(); resumeObserverDeactivation(); } } /** Make a series of property changes together in an exception-safe way. ```javascript Ember.changeProperties(function() { obj1.set('foo', mayBlowUpWhenSet); obj2.set('bar', baz); }); ``` @method changeProperties @param {Function} callback @private */ function changeProperties(callback) { beginPropertyChanges(); try { callback(); } finally { endPropertyChanges(); } } function arrayContentWillChange(array, startIdx, removeAmt, addAmt) { // if no args are passed assume everything changes if (startIdx === undefined) { startIdx = 0; removeAmt = addAmt = -1; } else { if (removeAmt === undefined) { removeAmt = -1; } if (addAmt === undefined) { addAmt = -1; } } sendEvent(array, '@array:before', [array, startIdx, removeAmt, addAmt]); return array; } function arrayContentDidChange(array, startIdx, removeAmt, addAmt, notify = true) { // if no args are passed assume everything changes if (startIdx === undefined) { startIdx = 0; removeAmt = addAmt = -1; } else { if (removeAmt === undefined) { removeAmt = -1; } if (addAmt === undefined) { addAmt = -1; } } let meta = peekMeta(array); if (notify) { if (addAmt < 0 || removeAmt < 0 || addAmt - removeAmt !== 0) { notifyPropertyChange(array, 'length', meta); } notifyPropertyChange(array, '[]', meta); } sendEvent(array, '@array:change', [array, startIdx, removeAmt, addAmt]); if (meta !== null) { let length = array.length; let addedAmount = addAmt === -1 ? 0 : addAmt; let removedAmount = removeAmt === -1 ? 0 : removeAmt; let delta = addedAmount - removedAmount; let previousLength = length - delta; let normalStartIdx = startIdx < 0 ? previousLength + startIdx : startIdx; if (meta.revisionFor('firstObject') !== undefined && normalStartIdx === 0) { notifyPropertyChange(array, 'firstObject', meta); } if (meta.revisionFor('lastObject') !== undefined) { let previousLastIndex = previousLength - 1; let lastAffectedIndex = normalStartIdx + removedAmount; if (previousLastIndex < lastAffectedIndex) { notifyPropertyChange(array, 'lastObject', meta); } } } return array; } const EMPTY_ARRAY = Object.freeze([]); function objectAt(array, index) { if (Array.isArray(array)) { return array[index]; } else { return array.objectAt(index); } } // Ideally, we'd use MutableArray.detect but for unknown reasons this causes // the node tests to fail strangely. function isMutableArray(obj) { return obj != null && typeof obj.replace === 'function'; } function replace(array, start, deleteCount, items = EMPTY_ARRAY) { if (isMutableArray(array)) { array.replace(start, deleteCount, items); } else { (isDevelopingApp() && !(Array.isArray(array)) && assert('Can only replace content of a native array or MutableArray', Array.isArray(array))); replaceInNativeArray(array, start, deleteCount, items); } } const CHUNK_SIZE = 60000; // To avoid overflowing the stack, we splice up to CHUNK_SIZE items at a time. // See https://code.google.com/p/chromium/issues/detail?id=56588 for more details. function replaceInNativeArray(array, start, deleteCount, items) { arrayContentWillChange(array, start, deleteCount, items.length); if (items.length <= CHUNK_SIZE) { array.splice(start, deleteCount, ...items); } else { array.splice(start, deleteCount); for (let i = 0; i < items.length; i += CHUNK_SIZE) { let chunk = items.slice(i, i + CHUNK_SIZE); array.splice(start + i, 0, ...chunk); } } arrayContentDidChange(array, start, deleteCount, items.length); } function arrayObserversHelper(obj, target, opts, operation) { let { willChange, didChange } = opts; operation(obj, '@array:before', target, willChange); operation(obj, '@array:change', target, didChange); /* * Array proxies have a `_revalidate` method which must be called to set * up their internal array observation systems. */ obj._revalidate?.(); return obj; } function addArrayObserver(array, target, opts) { return arrayObserversHelper(array, target, opts, addListener); } function removeArrayObserver(array, target, opts) { return arrayObserversHelper(array, target, opts, removeListener); } const CHAIN_PASS_THROUGH = new WeakSet(); function finishLazyChains(meta, key, value) { let lazyTags = meta.readableLazyChainsFor(key); if (lazyTags === undefined) { return; } if (isObject(value)) { for (let [tag, deps] of lazyTags) { UPDATE_TAG(tag, getChainTagsForKey(value, deps, tagMetaFor(value), peekMeta(value))); } } lazyTags.length = 0; } function getChainTagsForKeys(obj, keys, tagMeta, meta) { let tags = []; for (let key of keys) { getChainTags(tags, obj, key, tagMeta, meta); } return combine(tags); } function getChainTagsForKey(obj, key, tagMeta, meta) { return combine(getChainTags([], obj, key, tagMeta, meta)); } function getChainTags(chainTags, obj, path, tagMeta, meta$1) { let current = obj; let currentTagMeta = tagMeta; let currentMeta = meta$1; let pathLength = path.length; let segmentEnd = -1; // prevent closures let segment, descriptor; // eslint-disable-next-line no-constant-condition while (true) { let lastSegmentEnd = segmentEnd + 1; segmentEnd = path.indexOf('.', lastSegmentEnd); if (segmentEnd === -1) { segmentEnd = pathLength; } segment = path.slice(lastSegmentEnd, segmentEnd); // If the segment is an @each, we can process it and then break if (segment === '@each' && segmentEnd !== pathLength) { lastSegmentEnd = segmentEnd + 1; segmentEnd = path.indexOf('.', lastSegmentEnd); let arrLength = current.length; if (typeof arrLength !== 'number' || // TODO: should the second test be `isEmberArray` instead? !(Array.isArray(current) || 'objectAt' in current)) { // If the current object isn't an array, there's nothing else to do, // we don't watch individual properties. Break out of the loop. break; } else if (arrLength === 0) { // Fast path for empty arrays chainTags.push(tagForProperty(current, '[]')); break; } if (segmentEnd === -1) { segment = path.slice(lastSegmentEnd); } else { // Deprecated, remove once we turn the deprecation into an assertion segment = path.slice(lastSegmentEnd, segmentEnd); } // Push the tags for each item's property for (let i = 0; i < arrLength; i++) { let item = objectAt(current, i); if (item) { (isDevelopingApp() && !(typeof item === 'object') && assert(`When using @each to observe the array \`${current.toString()}\`, the items in the array must be objects`, typeof item === 'object')); chainTags.push(tagForProperty(item, segment, true)); currentMeta = peekMeta(item); descriptor = currentMeta !== null ? currentMeta.peekDescriptors(segment) : undefined; // If the key is an alias, we need to bootstrap it if (descriptor !== undefined && typeof descriptor.altKey === 'string') { item[segment]; } } } // Push the tag for the array length itself chainTags.push(tagForProperty(current, '[]', true, currentTagMeta)); break; } let propertyTag = tagForProperty(current, segment, true, currentTagMeta); descriptor = currentMeta !== null ? currentMeta.peekDescriptors(segment) : undefined; chainTags.push(propertyTag); // If we're at the end of the path, processing the last segment, and it's // not an alias, we should _not_ get the last value, since we already have // its tag. There's no reason to access it and do more work. if (segmentEnd === pathLength) { // If the key was an alias, we should always get the next value in order to // bootstrap the alias. This is because aliases, unlike other CPs, should // always be in sync with the aliased value. if (CHAIN_PASS_THROUGH.has(descriptor)) { current[segment]; } break; } if (descriptor === undefined) { // If the descriptor is undefined, then its a normal property, so we should // lookup the value to chain off of like normal. if (!(segment in current) && typeof current.unknownProperty === 'function') { current = current.unknownProperty(segment); } else { current = current[segment]; } } else if (CHAIN_PASS_THROUGH.has(descriptor)) { current = current[segment]; } else { // If the descriptor is defined, then its a normal CP (not an alias, which // would have been handled earlier). We get the last revision to check if // the CP is still valid, and if so we use the cached value. If not, then // we create a lazy chain lookup, and the next time the CP is calculated, // it will update that lazy chain. let instanceMeta = currentMeta.source === current ? currentMeta : meta(current); let lastRevision = instanceMeta.revisionFor(segment); if (lastRevision !== undefined && validateTag(propertyTag, lastRevision)) { current = instanceMeta.valueFor(segment); } else { // use metaFor here to ensure we have the meta for the instance let lazyChains = instanceMeta.writableLazyChainsFor(segment); let rest = path.substring(segmentEnd + 1); let placeholderTag = createUpdatableTag(); lazyChains.push([placeholderTag, rest]); chainTags.push(placeholderTag); break; } } if (!isObject(current)) { // we've hit the end of the chain for now, break out break; } currentTagMeta = tagMetaFor(current); currentMeta = peekMeta(current); } return chainTags; } function isElementDescriptor(args) { let [maybeTarget, maybeKey, maybeDesc] = args; return ( // Ensure we have the right number of args args.length === 3 && ( // Make sure the target is a class or object (prototype) typeof maybeTarget === 'function' || typeof maybeTarget === 'object' && maybeTarget !== null) && // Make sure the key is a string typeof maybeKey === 'string' && ( // Make sure the descriptor is the right shape typeof maybeDesc === 'object' && maybeDesc !== null || maybeDesc === undefined) ); } function nativeDescDecorator(propertyDesc) { let decorator = function () { return propertyDesc; }; setClassicDecorator(decorator); return decorator; } /** Objects of this type can implement an interface to respond to requests to get and set. The default implementation handles simple properties. @class Descriptor @private */ class ComputedDescriptor { enumerable = true; configurable = true; _dependentKeys = undefined; _meta = undefined; setup(_obj, keyName, _propertyDesc, meta) { meta.writeDescriptors(keyName, this); } teardown(_obj, keyName, meta) { meta.removeDescriptors(keyName); } } let COMPUTED_GETTERS; if (isDevelopingApp()) { COMPUTED_GETTERS = new WeakSet(); } function DESCRIPTOR_GETTER_FUNCTION(name, descriptor) { function getter() { return descriptor.get(this, name); } if (isDevelopingApp()) { COMPUTED_GETTERS.add(getter); } return getter; } function DESCRIPTOR_SETTER_FUNCTION(name, descriptor) { let set = function CPSETTER_FUNCTION(value) { return descriptor.set(this, name, value); }; COMPUTED_SETTERS.add(set); return set; } const COMPUTED_SETTERS = new WeakSet(); function makeComputedDecorator(desc, DecoratorClass) { let decorator = function COMPUTED_DECORATOR(target, key, propertyDesc, maybeMeta, isClassicDecorator) { (isDevelopingApp() && !(isClassicDecorator || !propertyDesc || !propertyDesc.get || !COMPUTED_GETTERS.has(propertyDesc.get)) && assert(`Only one computed property decorator can be applied to a class field or accessor, but '${key}' was decorated twice. You may have added the decorator to both a getter and se