language
stringclasses 1
value | owner
stringlengths 2
15
| repo
stringlengths 2
21
| sha
stringlengths 45
45
| message
stringlengths 7
36.3k
| path
stringlengths 1
199
| patch
stringlengths 15
102k
| is_multipart
bool 2
classes |
---|---|---|---|---|---|---|---|
Other
|
emberjs
|
ember.js
|
daa39359c2b3811d7053e2162a5717dcf40b04a1.json
|
Move objectAt to ember-metal
... and fix some tests that should ahve been testing the
method version of objectAt.
|
packages/ember-runtime/tests/suites/array/objectAt.js
|
@@ -1,5 +1,4 @@
import { SuiteModuleBuilder } from '../suite';
-import { objectAt } from '../../../mixins/array';
const suite = SuiteModuleBuilder.create();
@@ -11,18 +10,18 @@ suite.test('should return object at specified index', function(assert) {
let len = expected.length;
for (let idx = 0; idx < len; idx++) {
- assert.equal(objectAt(obj, idx), expected[idx], `obj.objectAt(${idx}) should match`);
+ assert.equal(obj.objectAt(idx), expected[idx], `obj.objectAt(${idx}) should match`);
}
});
suite.test('should return undefined when requesting objects beyond index', function(assert) {
let obj;
obj = this.newObject(this.newFixture(3));
- assert.equal(objectAt(obj, 5), undefined, 'should return undefined for obj.objectAt(5) when len = 3');
+ assert.equal(obj.objectAt(obj, 5), undefined, 'should return undefined for obj.objectAt(5) when len = 3');
obj = this.newObject([]);
- assert.equal(objectAt(obj, 0), undefined, 'should return undefined for obj.objectAt(0) when len = 0');
+ assert.equal(obj.objectAt(obj, 0), undefined, 'should return undefined for obj.objectAt(0) when len = 0');
});
export default suite;
| true |
Other
|
emberjs
|
ember.js
|
daa39359c2b3811d7053e2162a5717dcf40b04a1.json
|
Move objectAt to ember-metal
... and fix some tests that should ahve been testing the
method version of objectAt.
|
packages/ember-runtime/tests/system/array_proxy/arranged_content_test.js
|
@@ -1,7 +1,6 @@
-import { run, computed } from 'ember-metal';
+import { run, computed, objectAt } from 'ember-metal';
import ArrayProxy from '../../../system/array_proxy';
import { A as emberA } from '../../../mixins/array';
-import { objectAt } from '../../../mixins/array';
let array;
| true |
Other
|
emberjs
|
ember.js
|
7f8f5944417516ffcfd3b6b30179f71d7cdf450b.json
|
Add 3.0.0-beta.6 to CHANGELOG
[ci skip]
(cherry picked from commit 558d800239529672b5dc86e905ba3d5b6d880545)
|
CHANGELOG.md
|
@@ -1,5 +1,10 @@
# Ember Changelog
+### 3.0.0-beta.6 (February 5, 2018)
+
+- [#16199](https://github.com/emberjs/ember.js/pull/16199) [BUGFIX] Mention "computed properties" in the assertion message
+- [#16200](https://github.com/emberjs/ember.js/pull/16200) [BUGFIX] Prevent test error by converting illegal characters
+
### 3.0.0-beta.5 (January 29, 2018)
- [#16179](https://github.com/emberjs/ember.js/pull/16179) [BUGFIX] Fix a few bugs in the caching ArrayProxy implementation
| false |
Other
|
emberjs
|
ember.js
|
c345bfc40317d6d4e93c73ff34f42c431d379c5f.json
|
Make `rsvpAfter` a private randomized queue name.
This queue is _never_ intended to be scheduled into by anyone other than
Ember itself, this change makes that much more likely.
|
packages/ember-metal/lib/run_loop.js
|
@@ -1,3 +1,4 @@
+import { privatize as P } from 'container';
import { assert, deprecate, isTesting } from 'ember-debug';
import {
onErrorTarget
@@ -31,7 +32,7 @@ const backburner = new Backburner(
// used to re-throw unhandled RSVP rejection errors specifically in this
// position to avoid breaking anything rendered in the other sections
- 'rsvpAfter'
+ P`rsvpAfter`
],
{
sync: {
| true |
Other
|
emberjs
|
ember.js
|
c345bfc40317d6d4e93c73ff34f42c431d379c5f.json
|
Make `rsvpAfter` a private randomized queue name.
This queue is _never_ intended to be scheduled into by anyone other than
Ember itself, this change makes that much more likely.
|
packages/ember-runtime/lib/ext/rsvp.js
|
@@ -4,6 +4,7 @@ import {
getDispatchOverride
} from 'ember-metal';
import { assert } from 'ember-debug';
+import { privatize as P } from 'container';
const backburner = run.backburner;
@@ -12,7 +13,7 @@ RSVP.configure('async', (callback, promise) => {
});
RSVP.configure('after', cb => {
- backburner.schedule('rsvpAfter', null, cb);
+ backburner.schedule(P`rsvpAfter`, null, cb);
});
RSVP.on('error', onerrorDefault);
| true |
Other
|
emberjs
|
ember.js
|
0c81a324d99cefb525bf316c8708e5c1e7f435eb.json
|
remove unused `caches` export
|
packages/ember-metal/lib/path_cache.js
|
@@ -2,10 +2,6 @@ import Cache from './cache';
const firstDotIndexCache = new Cache(1000, key => key.indexOf('.'));
-export const caches = {
- firstDotIndexCache
-};
-
export function isPath(path) {
return firstDotIndexCache.get(path) !== -1;
}
| false |
Other
|
emberjs
|
ember.js
|
ddda91699a68c4417c59465e07dd5071f555750c.json
|
remove jquery from component context tests
|
packages/ember/tests/component_context_test.js
|
@@ -79,14 +79,14 @@ moduleFor('Application Lifecycle - Component Context', class extends Application
this.addComponent('my-component', {
ComponentClass: Component.extend({
didInsertElement() {
- this.$().html('Some text inserted by jQuery');
+ this.element.innerHTML = 'Some text inserted';
}
})
});
return this.visit('/').then(() => {
let text = this.$('#wrapper').text().trim();
- assert.equal(text, 'Some text inserted by jQuery', 'The component is composed correctly');
+ assert.equal(text, 'Some text inserted', 'The component is composed correctly');
});
}
@@ -97,19 +97,19 @@ moduleFor('Application Lifecycle - Component Context', class extends Application
this.add('controller:application', Controller.extend({
'text': 'outer',
- 'foo': 'Some text inserted by jQuery'
+ 'foo': 'Some text inserted'
}));
this.addComponent('my-component', {
ComponentClass: Component.extend({
didInsertElement() {
- this.$().html(this.get('data'));
+ this.element.innerHTML = this.get('data');
}
})
});
return this.visit('/').then(() => {
let text = this.$('#wrapper').text().trim();
- assert.equal(text, 'Some text inserted by jQuery', 'The component is composed correctly');
+ assert.equal(text, 'Some text inserted', 'The component is composed correctly');
});
}
@@ -120,20 +120,20 @@ moduleFor('Application Lifecycle - Component Context', class extends Application
this.add('controller:application', Controller.extend({
'text': 'outer',
- 'foo': 'Some text inserted by jQuery'
+ 'foo': 'Some text inserted'
}));
this.addComponent('my-component', {
ComponentClass: Component.extend({
didInsertElement() {
// FIXME: I'm unsure if this is even the right way to access attrs
- this.$().html(this.get('attrs.attrs').value);
+ this.element.innerHTML = this.get('attrs.attrs').value;
}
})
});
return this.visit('/').then(() => {
let text = this.$('#wrapper').text().trim();
- assert.equal(text, 'Some text inserted by jQuery', 'The component is composed correctly');
+ assert.equal(text, 'Some text inserted', 'The component is composed correctly');
});
}
| false |
Other
|
emberjs
|
ember.js
|
872eb97fad1bd7f8f34001182cc9b37d06f82858.json
|
Remove require() for backburner instance
|
packages/ember-metal/lib/tags.js
|
@@ -1,6 +1,6 @@
import { CONSTANT_TAG, DirtyableTag } from '@glimmer/reference';
import { meta as metaFor } from './meta';
-import require from 'require';
+import run from './run_loop';
let hasViews = () => false;
@@ -62,8 +62,7 @@ export function markObjectAsDirty(meta, propertyKey) {
let backburner;
function ensureRunloop() {
if (backburner === undefined) {
- // TODO why does this need to be lazy
- backburner = require('ember-metal').run.backburner;
+ backburner = run.backburner;
}
if (hasViews()) {
| false |
Other
|
emberjs
|
ember.js
|
afedeaae2e7502c6b696d2e433979307c9f4542e.json
|
Add 3.0.0-beta.5 to CHANGELOG
[ci skip]
(cherry picked from commit 9a2a138479265a22bafcdbb8c60942ec080196c7)
|
CHANGELOG.md
|
@@ -1,5 +1,9 @@
# Ember Changelog
+### 3.0.0-beta.5 (January 29, 2018)
+
+- [#16179](https://github.com/emberjs/ember.js/pull/16179) [BUGFIX] Fix a few bugs in the caching ArrayProxy implementation
+
### 3.0.0-beta.4 (January 25, 2018)
- [#16160](https://github.com/emberjs/ember.js/pull/16160) [BUGFIX] Remove humanize() call from generated test descriptions
| false |
Other
|
emberjs
|
ember.js
|
28753cf193ed8fccacc535dc9af09a9d1cb91f09.json
|
Update CHANGELOG for 3.0.0-beta.4
[ci skip]
(cherry picked from commit 233a34e3aec8d77d85f562c7892d37f47105f8da)
|
CHANGELOG.md
|
@@ -1,5 +1,20 @@
# Ember Changelog
+### 3.0.0-beta.4 (January 25, 2018)
+
+- [#16160](https://github.com/emberjs/ember.js/pull/16160) [BUGFIX] Remove humanize() call from generated test descriptions
+- [#16101](https://github.com/emberjs/ember.js/pull/16101) [CLEANUP] Remove legacy ArrayProxy features
+- [#16116](https://github.com/emberjs/ember.js/pull/16116) [CLEANUP] Remove private enumerable observers
+- [#16117](https://github.com/emberjs/ember.js/pull/16117) [BUGFIX] link-to active class applied when params change
+- [#16132](https://github.com/emberjs/ember.js/pull/16132) [BUGFIX] Bring back `sync` queue with deprecation (until: 3.5.0).
+- [#16156](https://github.com/emberjs/ember.js/pull/16156) [BUGFIX] Update to [email protected].
+- [#16157](https://github.com/emberjs/ember.js/pull/16157) [BUGFIX] Mutating an arranged ArrayProxy is not allowed
+- [#16162](https://github.com/emberjs/ember.js/pull/16162) [CLEANUP] Remove unused private listener methods
+- [#16163](https://github.com/emberjs/ember.js/pull/16163) [CLEANUP] Remove unused path caches
+- [#16169](https://github.com/emberjs/ember.js/pull/16169) [BUGFIX] Fix various issues with descriptor trap.
+- [#16174](https://github.com/emberjs/ember.js/pull/16174) [BUGFIX] Enable _some_ recovery of errors thrown during render.
+
+
### 3.0.0-beta.3 (January 15, 2018)
- [#16095](https://github.com/emberjs/ember.js/pull/16095) [CLEANUP] Fix ember-2-legacy support for Ember.Binding.
| false |
Other
|
emberjs
|
ember.js
|
b314d66a911819de88549d3f37866c3ebc191ea2.json
|
remove event flags
|
packages/ember-metal/lib/events.js
|
@@ -5,7 +5,6 @@ import { applyStr } from 'ember-utils';
import { ENV } from 'ember-environment';
import { deprecate, assert } from 'ember-debug';
import { meta as metaFor, peekMeta } from './meta';
-import { ONCE } from './meta_listeners';
/*
The event system uses a series of nested hashes to store listeners on an
@@ -18,7 +17,7 @@ import { ONCE } from './meta_listeners';
{
listeners: { // variable name: `listenerSet`
"foo": [ // variable name: `actions`
- target, method, flags
+ target, method, once
]
}
}
@@ -61,12 +60,7 @@ export function addListener(obj, eventName, target, method, once) {
target = null;
}
- let flags = 0;
- if (once) {
- flags |= ONCE;
- }
-
- metaFor(obj).addToListeners(eventName, target, method, flags);
+ metaFor(obj).addToListeners(eventName, target, method, once);
if ('function' === typeof obj.didAddListener) {
obj.didAddListener(eventName, target, method);
@@ -130,10 +124,10 @@ export function sendEvent(obj, eventName, params, actions, _meta) {
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 flags = actions[i + 2];
+ let once = actions[i + 2];
if (!method) { continue; }
- if (flags & ONCE) { removeListener(obj, eventName, target, method); }
+ if (once) { removeListener(obj, eventName, target, method); }
if (!target) { target = obj; }
if ('string' === typeof method) {
if (params) {
| true |
Other
|
emberjs
|
ember.js
|
b314d66a911819de88549d3f37866c3ebc191ea2.json
|
remove event flags
|
packages/ember-metal/lib/meta_listeners.js
|
@@ -10,14 +10,11 @@
save that for dispatch time, if an event actually happens.
*/
-/* listener flags */
-export const ONCE = 1;
-
export const protoMethods = {
- addToListeners(eventName, target, method, flags) {
+ addToListeners(eventName, target, method, once) {
if (this._listeners === undefined) { this._listeners = []; }
- this._listeners.push(eventName, target, method, flags);
+ this._listeners.push(eventName, target, method, once);
},
_finalizeListeners() {
| true |
Other
|
emberjs
|
ember.js
|
86e9790abd624631944d32b70a2d0aecdb356549.json
|
convert `BucketCache` to es6 class
|
packages/ember-application/lib/system/application.js
|
@@ -1069,7 +1069,7 @@ function commonSetupRegistry(registry) {
registry.register('location:history', HistoryLocation);
registry.register('location:none', NoneLocation);
- registry.register(P`-bucket-cache:main`, BucketCache);
+ registry.register(P`-bucket-cache:main`, { create() { return new BucketCache(); } });
if (EMBER_ROUTING_ROUTER_SERVICE) {
registry.register('service:router', RouterService);
| true |
Other
|
emberjs
|
ember.js
|
86e9790abd624631944d32b70a2d0aecdb356549.json
|
convert `BucketCache` to es6 class
|
packages/ember-routing/lib/index.d.ts
|
@@ -221,9 +221,9 @@ export const RouterService: {
isActive(...args: any[]): boolean;
_extractArguments(routeName: string, ...models: any[]): {routeName: string, models: any[], queryParams: any};
};
-export const BucketCache: {
- init(): void;
+export class BucketCache {
+ constructor();
has(bucketKey: string): boolean;
stash(bucketKey: string, key: string, value: any): void;
lookup(bucketKey: string, prop: any, defaultValue: any): any;
-};
+}
| true |
Other
|
emberjs
|
ember.js
|
86e9790abd624631944d32b70a2d0aecdb356549.json
|
convert `BucketCache` to es6 class
|
packages/ember-routing/lib/system/cache.js
|
@@ -1,42 +1,40 @@
-import { Object as EmberObject } from 'ember-runtime';
-
/**
A two-tiered cache with support for fallback values when doing lookups.
Uses "buckets" and then "keys" to cache values.
@private
@class BucketCache
*/
-export default EmberObject.extend({
- init() {
- this.cache = Object.create(null);
- },
+export default class BucketCache {
+ constructor() {
+ this.cache = new Map();
+ }
has(bucketKey) {
- return !!this.cache[bucketKey];
- },
+ return this.cache.has(bucketKey);
+ }
stash(bucketKey, key, value) {
- let bucket = this.cache[bucketKey];
+ let bucket = this.cache.get(bucketKey);
- if (!bucket) {
- bucket = this.cache[bucketKey] = Object.create(null);
+ if (bucket === undefined) {
+ bucket = new Map();
+ this.cache.set(bucketKey, bucket);
}
- bucket[key] = value;
- },
+ bucket.set(key, value);
+ }
lookup(bucketKey, prop, defaultValue) {
- let cache = this.cache;
if (!this.has(bucketKey)) {
return defaultValue;
}
- let bucket = cache[bucketKey];
- if (prop in bucket && bucket[prop] !== undefined) {
- return bucket[prop];
+ let bucket = this.cache.get(bucketKey);
+ if (bucket.has(prop)) {
+ return bucket.get(prop);
} else {
return defaultValue;
}
}
-});
+}
| true |
Other
|
emberjs
|
ember.js
|
86e9790abd624631944d32b70a2d0aecdb356549.json
|
convert `BucketCache` to es6 class
|
packages/ember-routing/tests/system/cache_test.js
|
@@ -5,7 +5,7 @@ moduleFor('BucketCache', class extends AbstractTestCase {
constructor() {
super();
- this.cache = BucketCache.create();
+ this.cache = new BucketCache();
}
['@test has - returns false when bucket is not in cache'](assert) {
| true |
Other
|
emberjs
|
ember.js
|
56183a1c248bd60a3ec3f92c8fefa0ddf4e423fe.json
|
utilize `Map` and `Set` in `property_events`
|
packages/ember-metal/lib/property_events.js
|
@@ -1,4 +1,4 @@
-import { guidFor, symbol } from 'ember-utils';
+import { symbol } from 'ember-utils';
import {
descriptorFor,
peekMeta
@@ -115,16 +115,16 @@ function notifyPropertyChange(obj, keyName, _meta) {
}
}
-let DID_SEEN;
+let DID_SEEN = null;
// called whenever a property has just changed to update dependent keys
function dependentKeysDidChange(obj, depKey, meta) {
if (meta.isSourceDestroying() || !meta.hasDeps(depKey)) { return; }
let seen = DID_SEEN;
- let top = !seen;
+ let top = seen === null;
if (top) {
- seen = DID_SEEN = {};
+ seen = DID_SEEN = new Map();
}
iterDeps(notifyPropertyChange, obj, depKey, seen, meta);
@@ -135,20 +135,16 @@ function dependentKeysDidChange(obj, depKey, meta) {
}
function iterDeps(method, obj, depKey, seen, meta) {
- let possibleDesc;
- let guid = guidFor(obj);
- let current = seen[guid];
-
- if (!current) {
- current = seen[guid] = {};
- }
+ let current = seen.get(obj);
- if (current[depKey]) {
- return;
+ if (current === undefined) {
+ current = new Set();
+ seen.set(obj, current);
}
- current[depKey] = true;
+ if (current.has(depKey)) { return; }
+ let possibleDesc;
meta.forEachInDeps(depKey, (key, value) => {
if (!value) { return; }
| false |
Other
|
emberjs
|
ember.js
|
b6068455ba1296bb50d1ba5631cb02f9ad84e617.json
|
Avoid extra var in CoreObject during prod builds.
|
packages/ember-runtime/lib/system/core_object.js
|
@@ -68,7 +68,12 @@ function makeCtor() {
initProperties = [arguments[0]];
}
- let beforeInitCalled = true;
+ let beforeInitCalled; // only used in debug builds to enable the proxy trap
+
+ // using DEBUG here to avoid the extraneous variable when not needed
+ if (DEBUG) {
+ beforeInitCalled = true;
+ }
if (DEBUG && MANDATORY_GETTER && EMBER_METAL_ES5_GETTERS && HAS_NATIVE_PROXY && typeof self.unknownProperty === 'function') {
let messageFor = (obj, property) => {
@@ -211,7 +216,11 @@ function makeCtor() {
if (ENV._ENABLE_BINDING_SUPPORT) {
Mixin.finishPartial(self, m);
}
- beforeInitCalled = false;
+
+ // using DEBUG here to avoid the extraneous variable when not needed
+ if (DEBUG) {
+ beforeInitCalled = false;
+ }
self.init(...arguments);
self[POST_INIT]();
| false |
Other
|
emberjs
|
ember.js
|
eeecb9b2c88fb5ec7943bae52950c1e2fa439b42.json
|
Fix backwards compat shim for custom AST plugins.
|
packages/ember-template-compiler/lib/index.js
|
@@ -14,7 +14,8 @@ export { default as precompile } from './system/precompile';
export { default as compile } from './system/compile';
export {
default as compileOptions,
- registerPlugin
+ registerPlugin,
+ unregisterPlugin
} from './system/compile-options';
export { default as defaultPlugins } from './plugins';
| true |
Other
|
emberjs
|
ember.js
|
eeecb9b2c88fb5ec7943bae52950c1e2fa439b42.json
|
Fix backwards compat shim for custom AST plugins.
|
packages/ember-template-compiler/lib/system/compile-options.js
|
@@ -16,27 +16,24 @@ export default function compileOptions(_options) {
options.plugins = { ast: [...USER_PLUGINS, ...PLUGINS] };
} else {
let potententialPugins = [...USER_PLUGINS, ...PLUGINS];
+ let providedPlugins = options.plugins.ast.map(plugin => wrapLegacyPluginIfNeeded(plugin));
let pluginsToAdd = potententialPugins.filter((plugin) => {
return options.plugins.ast.indexOf(plugin) === -1;
});
- options.plugins.ast = options.plugins.ast.slice().concat(pluginsToAdd);
+ options.plugins.ast = providedPlugins.concat(pluginsToAdd);
}
return options;
}
-export function registerPlugin(type, _plugin) {
- if (type !== 'ast') {
- throw new Error(`Attempting to register ${_plugin} as "${type}" which is not a valid Glimmer plugin type.`);
- }
-
- let plugin;
+function wrapLegacyPluginIfNeeded(_plugin) {
+ let plugin = _plugin;
if (_plugin.prototype && _plugin.prototype.transform) {
plugin = (env) => {
return {
name: _plugin.constructor && _plugin.constructor.name,
- visitors: {
+ visitor: {
Program(node) {
let plugin = new _plugin(env);
@@ -45,16 +42,24 @@ export function registerPlugin(type, _plugin) {
return plugin.transform(node);
}
}
- };
+ };
};
- } else {
- plugin = _plugin;
}
+ return plugin;
+}
+
+export function registerPlugin(type, _plugin) {
+ if (type !== 'ast') {
+ throw new Error(`Attempting to register ${_plugin} as "${type}" which is not a valid Glimmer plugin type.`);
+ }
+
+ let plugin = wrapLegacyPluginIfNeeded(_plugin);
+
USER_PLUGINS = [plugin, ...USER_PLUGINS];
}
-export function removePlugin(type, PluginClass) {
+export function unregisterPlugin(type, PluginClass) {
if (type !== 'ast') {
throw new Error(`Attempting to unregister ${PluginClass} as "${type}" which is not a valid Glimmer plugin type.`);
}
| true |
Other
|
emberjs
|
ember.js
|
eeecb9b2c88fb5ec7943bae52950c1e2fa439b42.json
|
Fix backwards compat shim for custom AST plugins.
|
packages/ember-template-compiler/tests/system/compile_options_test.js
|
@@ -1,6 +1,5 @@
-import { compileOptions } from '../../index';
-import { defaultPlugins } from '../../index';
-import { moduleFor, AbstractTestCase } from 'internal-test-helpers';
+import { compile, compileOptions, defaultPlugins, registerPlugin, unregisterPlugin } from '../../index';
+import { moduleFor, AbstractTestCase, RenderingTestCase } from 'internal-test-helpers';
moduleFor('ember-template-compiler: default compile options', class extends AbstractTestCase {
['@test default options are a new copy'](assert) {
@@ -18,3 +17,69 @@ moduleFor('ember-template-compiler: default compile options', class extends Abst
}
}
});
+
+class CustomTransform {
+ constructor(options) {
+ this.options = options;
+ this.syntax = null;
+ }
+
+ transform(ast) {
+ let walker = new this.syntax.Walker();
+
+ walker.visit(ast, node => {
+ if (node.type !== 'ElementNode') {
+ return;
+ }
+
+ for (var i = 0; i < node.attributes.length; i++) {
+ let attribute = node.attributes[i];
+
+ if (attribute.name === 'data-test') {
+ node.attributes.splice(i, 1);
+ }
+ }
+ });
+
+ return ast;
+ }
+}
+
+moduleFor('ember-template-compiler: registerPlugin with a custom plugins', class extends RenderingTestCase {
+ beforeEach() {
+ registerPlugin('ast', CustomTransform);
+ }
+
+ afterEach() {
+ unregisterPlugin('ast', CustomTransform);
+ }
+
+ ['@test custom plugins can be used']() {
+ this.render('<div data-test="foo" data-blah="derp" class="hahaha"></div>');
+ this.assertElement(this.firstChild, {
+ tagName: 'div',
+ attrs: { class: 'hahaha', 'data-blah': 'derp' },
+ content: ''
+ });
+ }
+});
+
+moduleFor('ember-template-compiler: custom plugins passed to compile', class extends RenderingTestCase {
+ // override so that we can provide custom AST plugins to compile
+ compile(templateString) {
+ return compile(templateString, {
+ plugins: {
+ ast: [CustomTransform]
+ }
+ });
+ }
+
+ ['@test custom plugins can be used']() {
+ this.render('<div data-test="foo" data-blah="derp" class="hahaha"></div>');
+ this.assertElement(this.firstChild, {
+ tagName: 'div',
+ attrs: { class: 'hahaha', 'data-blah': 'derp' },
+ content: ''
+ });
+ }
+});
| true |
Other
|
emberjs
|
ember.js
|
17ec6c465938d35ba5106e599067bbfe84766a94.json
|
fix proxy issue
|
packages/ember-glimmer/lib/component-managers/abstract.ts
|
@@ -4,14 +4,14 @@ import {
} from '@glimmer/interfaces';
import { Tag, VersionedPathReference } from '@glimmer/reference';
import {
+ Arguments,
Bounds,
ComponentManager,
DynamicScope,
ElementOperations,
Environment,
PreparedArguments,
} from '@glimmer/runtime';
-import { Arguments } from '@glimmer/runtime';
import {
Destroyable,
Opaque,
| true |
Other
|
emberjs
|
ember.js
|
17ec6c465938d35ba5106e599067bbfe84766a94.json
|
fix proxy issue
|
packages/ember-runtime/lib/system/core_object.js
|
@@ -60,6 +60,14 @@ function makeCtor() {
constructor() {
let self = this;
+ if (!wasApplied) {
+ Class.proto(); // prepare prototype...
+ }
+
+ if (arguments.length > 0) {
+ initProperties = [arguments[0]];
+ }
+
if (MANDATORY_GETTER && EMBER_METAL_ES5_GETTERS && HAS_NATIVE_PROXY && typeof self.unknownProperty === 'function') {
let messageFor = (obj, property) => {
return `You attempted to access the \`${String(property)}\` property (of ${obj}).\n` +
@@ -76,7 +84,7 @@ function makeCtor() {
/* globals Proxy Reflect */
self = new Proxy(this, {
get(target, property, receiver) {
- if (property === PROXY_CONTENT) {
+ if (property === PROXY_CONTENT || property === 'didDefineProperty') {
return target;
} else if (typeof property === 'symbol' || property in target) {
return Reflect.get(target, property, receiver);
@@ -89,14 +97,6 @@ function makeCtor() {
});
}
- if (!wasApplied) {
- Class.proto(); // prepare prototype...
- }
-
- if (arguments.length > 0) {
- initProperties = [arguments[0]];
- }
-
self.__defineNonEnumerable(GUID_KEY_PROPERTY);
let m = meta(self);
let proto = m.proto;
| true |
Other
|
emberjs
|
ember.js
|
06e86935339148ecc18d91fd76484d3b3a90100f.json
|
blueprints/controller-test: Use dasherizedModuleName for test description
|
blueprints/controller-test/index.js
|
@@ -1,7 +1,6 @@
'use strict';
const stringUtil = require('ember-cli-string-utils');
-const testInfo = require('ember-cli-test-info');
const useTestFrameworkDetector = require('../test-framework-detector');
@@ -12,7 +11,7 @@ module.exports = useTestFrameworkDetector({
let controllerPathName = dasherizedModuleName;
return {
controllerPathName: controllerPathName,
- friendlyTestDescription: testInfo.description(options.entity.name, 'Unit', 'Controller')
+ friendlyTestDescription: ['Unit', 'Controller', dasherizedModuleName].join(' | ')
};
}
});
| false |
Other
|
emberjs
|
ember.js
|
461988481aa50eda4ede938308e42a061584afff.json
|
blueprints/component-test: Use dasherizedModuleName for test description
|
blueprints/component-test/index.js
|
@@ -1,7 +1,6 @@
'use strict';
const path = require('path');
-const testInfo = require('ember-cli-test-info');
const stringUtil = require('ember-cli-string-utils');
const isPackageMissing = require('ember-cli-is-package-missing');
const getPathOption = require('ember-cli-get-component-path-option');
@@ -42,16 +41,17 @@ module.exports = useTestFrameworkDetector({
let dasherizedModuleName = stringUtil.dasherize(options.entity.name);
let componentPathName = dasherizedModuleName;
let testType = options.testType || 'integration';
- let friendlyTestDescription = testInfo.description(options.entity.name, 'Integration', 'Component');
+
+ let friendlyTestDescription = [
+ testType === 'unit' ? 'Unit' : 'Integration',
+ 'Component',
+ dasherizedModuleName,
+ ].join(' | ');
if (options.pod && options.path !== 'components' && options.path !== '') {
componentPathName = [options.path, dasherizedModuleName].filter(Boolean).join('/');
}
- if (options.testType === 'unit') {
- friendlyTestDescription = testInfo.description(options.entity.name, 'Unit', 'Component');
- }
-
return {
path: getPathOption(options),
testType: testType,
| true |
Other
|
emberjs
|
ember.js
|
461988481aa50eda4ede938308e42a061584afff.json
|
blueprints/component-test: Use dasherizedModuleName for test description
|
node-tests/fixtures/component-test/default.js
|
@@ -1,7 +1,7 @@
import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';
-moduleForComponent('x-foo', 'Integration | Component | x foo', {
+moduleForComponent('x-foo', 'Integration | Component | x-foo', {
integration: true
});
| true |
Other
|
emberjs
|
ember.js
|
461988481aa50eda4ede938308e42a061584afff.json
|
blueprints/component-test: Use dasherizedModuleName for test description
|
node-tests/fixtures/component-test/mocha-0.12-unit.js
|
@@ -2,7 +2,7 @@ import { expect } from 'chai';
import { describe, it } from 'mocha';
import { setupComponentTest } from 'ember-mocha';
-describe('Unit | Component | x foo', function() {
+describe('Unit | Component | x-foo', function() {
setupComponentTest('x-foo', {
// Specify the other units that are required for this test
// needs: ['component:foo', 'helper:bar'],
| true |
Other
|
emberjs
|
ember.js
|
461988481aa50eda4ede938308e42a061584afff.json
|
blueprints/component-test: Use dasherizedModuleName for test description
|
node-tests/fixtures/component-test/mocha-0.12.js
|
@@ -3,7 +3,7 @@ import { describe, it } from 'mocha';
import { setupComponentTest } from 'ember-mocha';
import hbs from 'htmlbars-inline-precompile';
-describe('Integration | Component | x foo', function() {
+describe('Integration | Component | x-foo', function() {
setupComponentTest('x-foo', {
integration: true
});
| true |
Other
|
emberjs
|
ember.js
|
461988481aa50eda4ede938308e42a061584afff.json
|
blueprints/component-test: Use dasherizedModuleName for test description
|
node-tests/fixtures/component-test/mocha-unit.js
|
@@ -1,7 +1,7 @@
import { expect } from 'chai';
import { describeComponent, it } from 'ember-mocha';
-describeComponent('x-foo', 'Unit | Component | x foo',
+describeComponent('x-foo', 'Unit | Component | x-foo',
{
// Specify the other units that are required for this test
// needs: ['component:foo', 'helper:bar'],
| true |
Other
|
emberjs
|
ember.js
|
461988481aa50eda4ede938308e42a061584afff.json
|
blueprints/component-test: Use dasherizedModuleName for test description
|
node-tests/fixtures/component-test/mocha.js
|
@@ -2,7 +2,7 @@ import { expect } from 'chai';
import { describeComponent, it } from 'ember-mocha';
import hbs from 'htmlbars-inline-precompile';
-describeComponent('x-foo', 'Integration | Component | x foo',
+describeComponent('x-foo', 'Integration | Component | x-foo',
{
integration: true
},
| true |
Other
|
emberjs
|
ember.js
|
461988481aa50eda4ede938308e42a061584afff.json
|
blueprints/component-test: Use dasherizedModuleName for test description
|
node-tests/fixtures/component-test/rfc232-unit.js
|
@@ -1,7 +1,7 @@
import { module, test } from 'qunit';
import { setupTest } from 'ember-qunit';
-module('Unit | Component | x foo', function(hooks) {
+module('Unit | Component | x-foo', function(hooks) {
setupTest(hooks);
test('it exists', function(assert) {
| true |
Other
|
emberjs
|
ember.js
|
461988481aa50eda4ede938308e42a061584afff.json
|
blueprints/component-test: Use dasherizedModuleName for test description
|
node-tests/fixtures/component-test/rfc232.js
|
@@ -3,7 +3,7 @@ import { setupRenderingTest } from 'ember-qunit';
import { render } from '@ember/test-helpers';
import hbs from 'htmlbars-inline-precompile';
-module('Integration | Component | x foo', function(hooks) {
+module('Integration | Component | x-foo', function(hooks) {
setupRenderingTest(hooks);
test('it renders', async function(assert) {
| true |
Other
|
emberjs
|
ember.js
|
461988481aa50eda4ede938308e42a061584afff.json
|
blueprints/component-test: Use dasherizedModuleName for test description
|
node-tests/fixtures/component-test/unit.js
|
@@ -1,6 +1,6 @@
import { moduleForComponent, test } from 'ember-qunit';
-moduleForComponent('x-foo', 'Unit | Component | x foo', {
+moduleForComponent('x-foo', 'Unit | Component | x-foo', {
// Specify the other units that are required for this test
// needs: ['component:foo', 'helper:bar'],
unit: true
| true |
Other
|
emberjs
|
ember.js
|
8910a0dc8a1693b907d358e002d08a77101baa5a.json
|
Increase browser start and total run timeout times.
|
testem.dist.js
|
@@ -50,38 +50,38 @@ module.exports = {
test_page: "dist/tests/index.html?hidepassed&hideskipped&timeout=60000",
timeout: 540,
reporter: FailureOnlyPerBrowserReporter,
- browser_start_timeout: 600,
+ browser_start_timeout: 1200,
parallel: 4,
disable_watching: true,
launchers: {
BS_Chrome_Current: {
exe: "node_modules/.bin/browserstack-launch",
- args: ["--os", "Windows", "--osv", "10", "--b", "chrome", "--bv", "latest", "-t", "600", "--u", "<url>"],
+ args: ["--os", "Windows", "--osv", "10", "--b", "chrome", "--bv", "latest", "-t", "1200", "--u", "<url>"],
protocol: "browser"
},
BS_Firefox_Current: {
exe: "node_modules/.bin/browserstack-launch",
- args: ["--os", "Windows", "--osv", "10", "--b", "firefox", "--bv", "latest", "-t", "600", "--u", "<url>"],
+ args: ["--os", "Windows", "--osv", "10", "--b", "firefox", "--bv", "latest", "-t", "1200", "--u", "<url>"],
protocol: "browser"
},
BS_Safari_Current: {
exe: "node_modules/.bin/browserstack-launch",
- args: ["--os", "OS X", "--osv", "High Sierra", "--b", "safari", "--bv", "11", "-t", "600", "--u", "<url>"],
+ args: ["--os", "OS X", "--osv", "High Sierra", "--b", "safari", "--bv", "11", "-t", "1200", "--u", "<url>"],
protocol: "browser"
},
BS_Safari_Last: {
exe: "node_modules/.bin/browserstack-launch",
- args: ["--os", "OS X", "--osv", "Sierra", "--b", "safari", "--bv", "10.1", "-t", "600", "--u", "<url>"],
+ args: ["--os", "OS X", "--osv", "Sierra", "--b", "safari", "--bv", "10.1", "-t", "1200", "--u", "<url>"],
protocol: "browser"
},
BS_MS_Edge: {
exe: "node_modules/.bin/browserstack-launch",
- args: ["--os", "Windows", "--osv", "10", "--b", "edge", "--bv", "latest", "-t", "600", "--u", "<url>"],
+ args: ["--os", "Windows", "--osv", "10", "--b", "edge", "--bv", "latest", "-t", "1200", "--u", "<url>"],
protocol: "browser"
},
BS_IE_11: {
exe: "node_modules/.bin/browserstack-launch",
- args: ["--os", "Windows", "--osv", "10", "--b", "ie", "--bv", "11.0", "-t", "600", "--u", "<url>"],
+ args: ["--os", "Windows", "--osv", "10", "--b", "ie", "--bv", "11.0", "-t", "1200", "--u", "<url>"],
protocol: "browser"
}
},
| false |
Other
|
emberjs
|
ember.js
|
96265b11c58b933b87be2a77f99069e3f1a1e699.json
|
fix Object.assign issues
|
packages/ember-glimmer/lib/component-managers/outlet.ts
|
@@ -1,5 +1,4 @@
import { ComponentCapabilities, Option, Unique } from '@glimmer/interfaces';
-import { ParsedLayout, WrappedBuilder } from '@glimmer/opcode-compiler';
import {
CONSTANT_TAG, Tag, VersionedPathReference
} from '@glimmer/reference';
@@ -16,7 +15,7 @@ import {
import { Destroyable } from '@glimmer/util/dist/types';
import { DEBUG } from 'ember-env-flags';
import { _instrumentStart } from 'ember-metal';
-import { guidFor } from 'ember-utils';
+import { assign, guidFor } from 'ember-utils';
import { OwnedTemplateMeta } from 'ember-views';
import {
EMBER_GLIMMER_REMOVE_APPLICATION_TEMPLATE_WRAPPER,
@@ -133,7 +132,7 @@ let createRootOutlet: (outletView: OutletView) => OutletComponentDefinition;
if (EMBER_GLIMMER_REMOVE_APPLICATION_TEMPLATE_WRAPPER) {
createRootOutlet = (outletView: OutletView) => new OutletComponentDefinition(outletView.state);
} else {
- const WRAPPED_CAPABILITIES = Object.assign({}, CAPABILITIES, {
+ const WRAPPED_CAPABILITIES = assign({}, CAPABILITIES, {
dynamicTag: true,
elementHook: true,
});
@@ -148,16 +147,7 @@ if (EMBER_GLIMMER_REMOVE_APPLICATION_TEMPLATE_WRAPPER) {
getLayout(state: OutletDefinitionState, resolver: RuntimeResolver): Invocation {
// The router has already resolved the template
const template = state.template;
- const compileOptions = Object.assign({},
- resolver.templateOptions,
- { asPartial: false, referrer: template.referrer});
- // TODO fix this getting private
- const parsed: ParsedLayout<OwnedTemplateMeta> = (template as any).parsedLayout;
- const layout = new WrappedBuilder(
- compileOptions,
- parsed,
- WRAPPED_CAPABILITIES,
- );
+ const layout = resolver.getWrappedLayout(template, WRAPPED_CAPABILITIES);
return {
handle: layout.compile(),
symbolTable: layout.symbolTable
| true |
Other
|
emberjs
|
ember.js
|
96265b11c58b933b87be2a77f99069e3f1a1e699.json
|
fix Object.assign issues
|
packages/ember-glimmer/lib/component-managers/root.ts
|
@@ -5,10 +5,7 @@ import {
} from '@glimmer/runtime';
import { FACTORY_FOR } from 'container';
import { DEBUG } from 'ember-env-flags';
-import {
- _instrumentStart,
- peekMeta,
-} from 'ember-metal';
+import { _instrumentStart } from 'ember-metal';
import { DIRTY_TAG } from '../component';
import Environment from '../environment';
import { DynamicScope } from '../renderer';
| true |
Other
|
emberjs
|
ember.js
|
96265b11c58b933b87be2a77f99069e3f1a1e699.json
|
fix Object.assign issues
|
packages/ember-glimmer/lib/resolver.ts
|
@@ -17,7 +17,7 @@ import {
import { privatize as P } from 'container';
import { assert } from 'ember-debug';
import { _instrumentStart } from 'ember-metal';
-import { LookupOptions, Owner, setOwner } from 'ember-utils';
+import { assign, LookupOptions, Owner, setOwner } from 'ember-utils';
import {
lookupComponent,
lookupPartial,
@@ -220,8 +220,7 @@ export default class RuntimeResolver implements IRuntimeResolver<OwnedTemplateMe
}
let wrapper = cache.get(capabilities);
if (wrapper === undefined) {
- const compileOptions = Object.assign({},
- this.templateOptions, { asPartial: false, referrer: template.referrer});
+ const compileOptions = assign({}, this.templateOptions, { asPartial: false, referrer: template.referrer});
// TODO fix this getting private
const parsed: ParsedLayout<OwnedTemplateMeta> = (template as any).parsedLayout;
wrapper = new WrappedBuilder(compileOptions, parsed, capabilities);
| true |
Other
|
emberjs
|
ember.js
|
f616b3bdd941f653438cb99c9e276fc161f3e732.json
|
Reduce flakiness with IE11 test runs.
Under some circumstances (e.g. under heavy load) IE11 triggers the
`focusin` event twice. The only way I was able to reproduce this was by
severely restricting the resources available to my local VM when
testing.
The changes here are not ideal (I would much prefer to expect _exact_
event ordering and counts like these tests originally had), but the main
intent of the tests is still satisified in all cases.
🤞
|
packages/ember-glimmer/tests/integration/helpers/input-test.js
|
@@ -318,17 +318,19 @@ moduleFor('Helpers test: {{input}}', class extends InputRenderingTest {
}
['@test triggers `focus-in` when focused'](assert) {
- assert.expect(1);
+ let wasFocused = false;
this.render(`{{input focus-in='foo'}}`, {
actions: {
foo() {
- assert.ok(true, 'action was triggered');
+ wasFocused = true;
}
}
});
this.runTask(() => { this.$input().focus(); });
+
+ assert.ok(wasFocused, 'action was triggered');
}
['@test sends `insert-newline` when <enter> is pressed'](assert) {
| true |
Other
|
emberjs
|
ember.js
|
f616b3bdd941f653438cb99c9e276fc161f3e732.json
|
Reduce flakiness with IE11 test runs.
Under some circumstances (e.g. under heavy load) IE11 triggers the
`focusin` event twice. The only way I was able to reproduce this was by
severely restricting the resources available to my local VM when
testing.
The changes here are not ideal (I would much prefer to expect _exact_
event ordering and counts like these tests originally had), but the main
intent of the tests is still satisified in all cases.
🤞
|
packages/ember-testing/tests/helpers_test.js
|
@@ -1,6 +1,7 @@
import {
moduleFor,
- AutobootApplicationTestCase
+ AutobootApplicationTestCase,
+ isIE11
} from 'internal-test-helpers';
import { Route } from 'ember-routing';
@@ -361,7 +362,20 @@ if (!jQueryDisabled) {
wrapper.addEventListener('mousedown', e => events.push(e.type));
wrapper.addEventListener('mouseup', e => events.push(e.type));
wrapper.addEventListener('click', e => events.push(e.type));
- wrapper.addEventListener('focusin', e => events.push(e.type));
+ wrapper.addEventListener('focusin', e => {
+ // IE11 _sometimes_ triggers focusin **twice** in a row
+ // (we believe this is when it is under higher load)
+ //
+ // the goal here is to only push a single focusin when running on
+ // IE11
+ if (isIE11) {
+ if (events[events.length - 1] !== 'focusin') {
+ events.push(e.type);
+ }
+ } else {
+ events.push(e.type);
+ }
+ });
}
}));
@@ -739,12 +753,12 @@ if (!jQueryDisabled) {
}
[`@test 'fillIn' focuses on the element`](assert) {
- assert.expect(2);
+ let wasFocused = false;
this.add('route:application', Route.extend({
actions: {
wasFocused() {
- assert.ok(true, 'focusIn event was triggered');
+ wasFocused = true;
}
}
}));
@@ -763,6 +777,8 @@ if (!jQueryDisabled) {
visit('/');
fillIn('#first', 'current value');
andThen(() => {
+ assert.ok(wasFocused, 'focusIn event was triggered');
+
assert.equal(
find('#first')[0].value,'current value'
);
@@ -1232,4 +1248,4 @@ if (!jQueryDisabled) {
}
});
-}
\ No newline at end of file
+}
| true |
Other
|
emberjs
|
ember.js
|
f616b3bdd941f653438cb99c9e276fc161f3e732.json
|
Reduce flakiness with IE11 test runs.
Under some circumstances (e.g. under heavy load) IE11 triggers the
`focusin` event twice. The only way I was able to reproduce this was by
severely restricting the resources available to my local VM when
testing.
The changes here are not ideal (I would much prefer to expect _exact_
event ordering and counts like these tests originally had), but the main
intent of the tests is still satisified in all cases.
🤞
|
packages/internal-test-helpers/lib/browser-detect.js
|
@@ -0,0 +1,4 @@
+// `window.ActiveXObject` is "falsey" in IE11 (but not `undefined` or `false`)
+// `"ActiveXObject" in window` returns `true` in all IE versions
+// only IE11 will pass _both_ of these conditions
+export const isIE11 = !window.ActiveXObject && 'ActiveXObject' in window;
| true |
Other
|
emberjs
|
ember.js
|
f616b3bdd941f653438cb99c9e276fc161f3e732.json
|
Reduce flakiness with IE11 test runs.
Under some circumstances (e.g. under heavy load) IE11 triggers the
`focusin` event twice. The only way I was able to reproduce this was by
severely restricting the resources available to my local VM when
testing.
The changes here are not ideal (I would much prefer to expect _exact_
event ordering and counts like these tests originally had), but the main
intent of the tests is still satisified in all cases.
🤞
|
packages/internal-test-helpers/lib/index.js
|
@@ -35,3 +35,5 @@ export {
default as TestResolver,
ModuleBasedResolver as ModuleBasedTestResolver
} from './test-resolver';
+
+export { isIE11 } from './browser-detect';
| true |
Other
|
emberjs
|
ember.js
|
5d01bb0de2b0457995f348861c455bc7638e4b3f.json
|
Add a resolver setter to local lookup test case
Since RenderingTestCase is setting `resolver` in its constructor, a
setter is necessary, even if it doesn't do anything.
|
packages/ember-glimmer/tests/integration/components/local-lookup-test.js
|
@@ -258,6 +258,10 @@ if (EMBER_MODULE_UNIFICATION) {
get resolver() {
return this.owner.__registry__.fallback.resolver;
}
+ set resolver(resolver) {
+ // `resolver` needs a setter because RenderingTestCase sets `resolver` in
+ // its constructor
+ }
getResolver() {
return new LocalLookupTestResolver();
| false |
Other
|
emberjs
|
ember.js
|
670d490146e04577ac8799ba2c7f3d5d9f8a76a6.json
|
Get everything that needs to be cached into place
|
packages/ember-glimmer/lib/component-managers/curly.ts
|
@@ -5,7 +5,6 @@ import {
Simple,
VMHandle
} from '@glimmer/interfaces';
-import { ParsedLayout, TemplateOptions, WrappedBuilder } from '@glimmer/opcode-compiler';
import {
combine,
Tag,
@@ -37,7 +36,6 @@ import { String as StringUtils } from 'ember-runtime';
import {
getOwner,
guidFor,
- setOwner
} from 'ember-utils';
import { OwnedTemplateMeta, setViewElement } from 'ember-views';
import {
@@ -52,7 +50,6 @@ import { DynamicScope } from '../renderer';
import RuntimeResolver from '../resolver';
import {
Factory as TemplateFactory,
- Injections,
OwnedTemplate
} from '../template';
import {
@@ -123,17 +120,15 @@ export default class CurlyComponentManager extends AbstractManager<ComponentStat
};
}
- templateFor(component: Component, options: TemplateOptions<OwnedTemplateMeta>): OwnedTemplate {
- let Template = get(component, 'layout') as TemplateFactory | OwnedTemplate | undefined;
- if (Template !== undefined) {
+ templateFor(component: Component, resolver: RuntimeResolver): OwnedTemplate {
+ let layout = get(component, 'layout') as TemplateFactory | OwnedTemplate | undefined;
+ if (layout !== undefined) {
// This needs to be cached by template.id
- if (isTemplateFactory(Template)) {
- const injections: Injections = { options };
- setOwner(injections, getOwner(component));
- return Template.create(injections);
+ if (isTemplateFactory(layout)) {
+ return resolver.createTemplate(layout, getOwner(component));
} else {
// we were provided an instance already
- return Template;
+ return layout;
}
}
let owner = getOwner(component);
@@ -148,17 +143,8 @@ export default class CurlyComponentManager extends AbstractManager<ComponentStat
}
compileDynamicLayout(component: Component, resolver: RuntimeResolver): Invocation {
- const template = this.templateFor(component, resolver.templateOptions);
- const compileOptions = Object.assign({},
- resolver.templateOptions,
- { asPartial: false, referrer: template.referrer});
- // TODO fix this getting private
- const parsed: ParsedLayout<OwnedTemplateMeta> = (template as any).parsedLayout;
- const layout = new WrappedBuilder(
- compileOptions,
- parsed,
- CURLY_CAPABILITIES,
- );
+ const template = this.templateFor(component, resolver);
+ const layout = resolver.getWrappedLayout(template, CURLY_CAPABILITIES);
// NEEDS TO BE CACHED
return {
handle: layout.compile(),
| true |
Other
|
emberjs
|
ember.js
|
670d490146e04577ac8799ba2c7f3d5d9f8a76a6.json
|
Get everything that needs to be cached into place
|
packages/ember-glimmer/lib/resolver.ts
|
@@ -3,9 +3,10 @@ import {
Opaque,
Option,
RuntimeResolver as IRuntimeResolver,
- VMHandle
+ VMHandle,
+ ComponentCapabilities
} from '@glimmer/interfaces';
-import { LazyOpcodeBuilder, Macros, OpcodeBuilderConstructor, TemplateOptions } from '@glimmer/opcode-compiler';
+import { LazyOpcodeBuilder, Macros, OpcodeBuilderConstructor, ParsedLayout, TemplateOptions, WrappedBuilder } from '@glimmer/opcode-compiler';
import { LazyConstants, Program } from '@glimmer/program';
import {
getDynamicVar,
@@ -16,15 +17,15 @@ import {
import { privatize as P } from 'container';
import { assert } from 'ember-debug';
import { _instrumentStart } from 'ember-metal';
-import { LookupOptions } from 'ember-utils';
+import { LookupOptions, Owner, setOwner } from 'ember-utils';
import {
lookupComponent,
lookupPartial,
OwnedTemplateMeta,
} from 'ember-views';
import { EMBER_GLIMMER_TEMPLATE_ONLY_COMPONENTS, GLIMMER_CUSTOM_COMPONENT_MANAGER } from 'ember/features';
import CompileTimeLookup from './compile-time-lookup';
-import { CurlyComponentDefinition } from './component-managers/curly';
+import { CURLY_CAPABILITIES, CurlyComponentDefinition } from './component-managers/curly';
import { TemplateOnlyComponentDefinition } from './component-managers/template-only';
import { isHelperFactory, isSimpleHelper } from './helper';
import { default as classHelper } from './helpers/-class';
@@ -47,6 +48,7 @@ import { populateMacros } from './syntax';
import { mountHelper } from './syntax/mount';
import { outletHelper } from './syntax/outlet';
import { renderHelper } from './syntax/render';
+import { Factory as TemplateFactory, Injections, OwnedTemplate } from './template';
import { ClassBasedHelperReference, SimpleHelperReference } from './utils/references';
function instrumentationPayload(name: string) {
@@ -92,12 +94,9 @@ export default class RuntimeResolver implements IRuntimeResolver<OwnedTemplateMe
Builder: LazyOpcodeBuilder as OpcodeBuilderConstructor,
};
- // creates compileOptions for DI
- public static create() {
- return new this().templateOptions;
- }
-
- private handles: any[] = [undefined];
+ private handles: any[] = [
+ undefined, // ensure no falsy handle
+ ];
private objToHandle = new WeakMap<any, number>();
private builtInHelpers: {
@@ -126,11 +125,6 @@ export default class RuntimeResolver implements IRuntimeResolver<OwnedTemplateMe
return this.resolve(handle);
}
- lookupPartial(name: string, meta: OwnedTemplateMeta): Option<number> {
- let partial = this._lookupPartial(name, meta);
- return this.handle(partial);
- }
-
/**
* Called by RuntimeConstants to lookup unresolved handles.
*/
@@ -163,9 +157,45 @@ export default class RuntimeResolver implements IRuntimeResolver<OwnedTemplateMe
lookupModifier(name: string, _meta: OwnedTemplateMeta): Option<number> {
return this.handle(this._lookupModifier(name));
}
+
+ /**
+ * Called by CompileTimeLookup to lookup partial
+ */
+ lookupPartial(name: string, meta: OwnedTemplateMeta): Option<number> {
+ let partial = this._lookupPartial(name, meta);
+ return this.handle(partial);
+ }
+
// end CompileTimeLookup
- // needed for latebound
+ // TODO implement caching for the follow hooks
+
+ /**
+ * Creates a directly imported template with injections.
+ * @param templateFactory the direct imported template factory
+ * @param owner the owner to set
+ */
+ createTemplate(factory: TemplateFactory, owner: Owner) {
+ const injections: Injections = { options: this.templateOptions };
+ setOwner(injections, owner);
+ // TODO cache by owner and template.id
+ return factory.create(injections);
+ }
+
+ /**
+ * Returns a wrapped layout for the specified layout.
+ * @param template the layout to wrap.
+ */
+ getWrappedLayout(template: OwnedTemplate, capabilities: ComponentCapabilities) {
+ const compileOptions = Object.assign({},
+ this.templateOptions, { asPartial: false, referrer: template.referrer});
+ // TODO fix this getting private
+ const parsed: ParsedLayout<OwnedTemplateMeta> = (template as any).parsedLayout;
+ // TODO cache by template instance and capabilities
+ return new WrappedBuilder(compileOptions, parsed, capabilities);
+ }
+
+ // needed for lazy compile time lookup
private handle(obj: any | null | undefined) {
if (obj === undefined || obj === null) {
return null;
| true |
Other
|
emberjs
|
ember.js
|
21e2eae7903eab8fbfa90cd92a58db301e922973.json
|
fix experimental syntax
|
packages/ember-glimmer/tests/integration/syntax/experimental-syntax-test.js
|
@@ -1,16 +1,15 @@
import { moduleFor, RenderingTest } from '../../utils/test-case';
import { strip } from '../../utils/abstract-test-case';
import { _registerMacros, _experimentalMacros } from 'ember-glimmer';
-import { compileExpression } from '@glimmer/runtime';
moduleFor('registerMacros', class extends RenderingTest {
constructor() {
let originalMacros = _experimentalMacros.slice();
_registerMacros(blocks => {
blocks.add('-let', (params, hash, _default, inverse, builder) => {
- compileExpression(params[0], builder);
- builder.invokeStatic(_default, 1);
+ builder.compileParams(params);
+ builder.invokeStaticBlock(_default, params.length);
});
});
| false |
Other
|
emberjs
|
ember.js
|
db1717b34dc92a266ae54c687bc350b7dcb07de2.json
|
Simplify implementation of some array methods
|
packages/ember-runtime/lib/mixins/array.js
|
@@ -160,17 +160,6 @@ export function isEmberArray(obj) {
return obj && obj[EMBER_ARRAY];
}
-const contexts = [];
-
-function popCtx() {
- return contexts.length === 0 ? {} : contexts.pop();
-}
-
-function pushCtx(ctx) {
- contexts.push(ctx);
- return null;
-}
-
function iter(key, value) {
let valueProvided = arguments.length === 2;
@@ -589,26 +578,16 @@ const ArrayMixin = Mixin.create(Enumerable, {
@return {Object} receiver
@public
*/
- forEach(callback, target) {
+ forEach(callback, target = null) {
assert('forEach expects a function as first argument.', typeof callback === 'function');
- let context = popCtx();
- let len = get(this, 'length');
- let last = null;
-
- if (target === undefined) {
- target = null;
- }
+ let length = get(this, 'length');
- for (let idx = 0; idx < len; idx++) {
- let next = this.nextObject(idx, last, context);
- callback.call(target, next, idx, this);
- last = next;
+ for (let index = 0; index < length; index++) {
+ let item = this.objectAt(index);
+ callback.call(target, item, index, this);
}
- last = null;
- context = pushCtx(context);
-
return this;
},
@@ -802,8 +781,7 @@ const ArrayMixin = Mixin.create(Enumerable, {
/**
Returns the first item in the array for which the callback returns true.
- This method works similar to the `filter()` method defined in JavaScript 1.6
- except that it will stop working on the array once a match is found.
+ This method is similar to the `find()` method defined in ECMAScript 2015.
The callback method you provide should have the following signature (all
parameters are optional):
@@ -829,35 +807,18 @@ const ArrayMixin = Mixin.create(Enumerable, {
@return {Object} Found item or `undefined`.
@public
*/
- find(callback, target) {
+ find(callback, target = null) {
assert('find expects a function as first argument.', typeof callback === 'function');
- let len = get(this, 'length');
-
- if (target === undefined) {
- target = null;
- }
-
- let context = popCtx();
- let found = false;
- let last = null;
- let next, ret;
+ let length = get(this, 'length');
- for (let idx = 0; idx < len && !found; idx++) {
- next = this.nextObject(idx, last, context);
+ for (let index = 0; index < length; index++) {
+ let item = this.objectAt(index);
- found = callback.call(target, next, idx, this);
- if (found) {
- ret = next;
+ if (callback.call(target, item, index, this)) {
+ return item;
}
-
- last = next;
}
-
- next = last = null;
- context = pushCtx(context);
-
- return ret;
},
/**
@@ -974,28 +935,20 @@ const ArrayMixin = Mixin.create(Enumerable, {
@return {Boolean} `true` if the passed function returns `true` for any item
@public
*/
- any(callback, target) {
+ any(callback, target = null) {
assert('any expects a function as first argument.', typeof callback === 'function');
- let len = get(this, 'length');
- let context = popCtx();
- let found = false;
- let last = null;
- let next;
+ let length = get(this, 'length');
- if (target === undefined) {
- target = null;
- }
+ for (let index = 0; index < length; index++) {
+ let item = this.objectAt(index);
- for (let idx = 0; idx < len && !found; idx++) {
- next = this.nextObject(idx, last, context);
- found = callback.call(target, next, idx, this);
- last = next;
+ if (callback.call(target, item, index, this)) {
+ return true;
+ }
}
- next = last = null;
- context = pushCtx(context);
- return found;
+ return false;
},
/**
| false |
Other
|
emberjs
|
ember.js
|
764b8a71c87785478d0ffa44f095c3762e5ff9d0.json
|
Remove Enumerable.detect checks
|
packages/ember-runtime/lib/mixins/mutable_array.js
|
@@ -8,7 +8,6 @@ import {
beginPropertyChanges,
endPropertyChanges
} from 'ember-metal';
-import Enumerable from './enumerable';
import MutableEnumerable from './mutable_enumerable';
import EmberArray, { objectAt } from './array';
import { Error as EmberError } from 'ember-debug';
@@ -187,7 +186,7 @@ export default Mixin.create(EmberArray, MutableEnumerable, {
@public
*/
pushObjects(objects) {
- if (!(Enumerable.detect(objects) || Array.isArray(objects))) {
+ if (!Array.isArray(objects)) {
throw new TypeError('Must pass Enumerable to MutableArray#pushObjects');
}
this.replace(get(this, 'length'), 0, objects);
| true |
Other
|
emberjs
|
ember.js
|
764b8a71c87785478d0ffa44f095c3762e5ff9d0.json
|
Remove Enumerable.detect checks
|
packages/ember-runtime/lib/system/array_proxy.js
|
@@ -12,7 +12,6 @@ import {
} from '../utils';
import EmberObject from './object';
import MutableArray from '../mixins/mutable_array';
-import Enumerable from '../mixins/enumerable';
import {
addArrayObserver,
removeArrayObserver,
@@ -257,7 +256,7 @@ export default EmberObject.extend(MutableArray, {
},
pushObjects(objects) {
- if (!(Enumerable.detect(objects) || isArray(objects))) {
+ if (!isArray(objects)) {
throw new TypeError('Must pass Enumerable to MutableArray#pushObjects');
}
this._replace(get(this, 'length'), 0, objects);
| true |
Other
|
emberjs
|
ember.js
|
bb626b6b15479c477f3c46c86d38d6581b8455d6.json
|
Remove private enumerableContent{Will,Did}Change
|
packages/ember-runtime/lib/mixins/array.js
|
@@ -90,7 +90,11 @@ export function arrayContentWillChange(array, startIdx, removeAmt, addAmt) {
sendEvent(array, '@array:before', [array, startIdx, removeAmt, addAmt]);
- array.enumerableContentWillChange(removeAmt, addAmt);
+ propertyWillChange(array, '[]');
+
+ if (addAmt < 0 || removeAmt < 0 || addAmt - removeAmt !== 0) {
+ propertyWillChange(array, 'length');
+ }
return array;
}
@@ -110,7 +114,11 @@ export function arrayContentDidChange(array, startIdx, removeAmt, addAmt) {
}
}
- array.enumerableContentDidChange(removeAmt, addAmt);
+ if (addAmt < 0 || removeAmt < 0 || addAmt - removeAmt !== 0) {
+ propertyDidChange(array, 'length');
+ }
+
+ propertyDidChange(array, '[]');
if (array.__each) {
array.__each.arrayDidChange(array, startIdx, removeAmt, addAmt);
@@ -560,111 +568,6 @@ const ArrayMixin = Mixin.create(Enumerable, {
return arrayContentDidChange(this, startIdx, removeAmt, addAmt);
},
- /**
- Invoke this method just before the contents of your enumerable will
- change. You can either omit the parameters completely or pass the objects
- to be removed or added if available or just a count.
-
- @method enumerableContentWillChange
- @param {Enumerable|Number} removing An enumerable of the objects to
- be removed or the number of items to be removed.
- @param {Enumerable|Number} adding An enumerable of the objects to be
- added or the number of items to be added.
- @chainable
- @private
- */
- enumerableContentWillChange(removing, adding) {
- let removeCnt, addCnt, hasDelta;
-
- if ('number' === typeof removing) {
- removeCnt = removing;
- } else if (removing) {
- removeCnt = get(removing, 'length');
- } else {
- removeCnt = removing = -1;
- }
-
- if ('number' === typeof adding) {
- addCnt = adding;
- } else if (adding) {
- addCnt = get(adding, 'length');
- } else {
- addCnt = adding = -1;
- }
-
- hasDelta = addCnt < 0 || removeCnt < 0 || addCnt - removeCnt !== 0;
-
- if (removing === -1) {
- removing = null;
- }
-
- if (adding === -1) {
- adding = null;
- }
-
- propertyWillChange(this, '[]');
-
- if (hasDelta) {
- propertyWillChange(this, 'length');
- }
-
- return this;
- },
-
- /**
- Invoke this method when the contents of your enumerable has changed.
- This will notify any observers watching for content changes. If you are
- implementing an ordered enumerable (such as an array), also pass the
- start and end values where the content changed so that it can be used to
- notify range observers.
-
- @method enumerableContentDidChange
- @param {Enumerable|Number} removing An enumerable of the objects to
- be removed or the number of items to be removed.
- @param {Enumerable|Number} adding An enumerable of the objects to
- be added or the number of items to be added.
- @chainable
- @private
- */
- enumerableContentDidChange(removing, adding) {
- let removeCnt, addCnt, hasDelta;
-
- if ('number' === typeof removing) {
- removeCnt = removing;
- } else if (removing) {
- removeCnt = get(removing, 'length');
- } else {
- removeCnt = removing = -1;
- }
-
- if ('number' === typeof adding) {
- addCnt = adding;
- } else if (adding) {
- addCnt = get(adding, 'length');
- } else {
- addCnt = adding = -1;
- }
-
- hasDelta = addCnt < 0 || removeCnt < 0 || addCnt - removeCnt !== 0;
-
- if (removing === -1) {
- removing = null;
- }
-
- if (adding === -1) {
- adding = null;
- }
-
- if (hasDelta) {
- propertyDidChange(this, 'length');
- }
-
- propertyDidChange(this, '[]');
-
- return this;
- },
-
-
/**
Iterates through the enumerable, calling the passed function on each
item. This method corresponds to the `forEach()` method defined in
| false |
Other
|
emberjs
|
ember.js
|
1a29eb96a49e642ad8a7b8d07a96ffc0f3f2a6a4.json
|
Move enumerable mixin methods into array mixins
|
packages/ember-runtime/lib/mixins/array.js
|
@@ -2,14 +2,13 @@
@module @ember/array
*/
-// ..........................................................
-// HELPERS
-//
import { symbol, toString } from 'ember-utils';
-import Ember, { // ES6TODO: Ember.A
+import {
get,
+ set,
computed,
isNone,
+ aliasMethod,
Mixin,
propertyWillChange,
propertyDidChange,
@@ -26,6 +25,18 @@ import Ember, { // ES6TODO: Ember.A
} from 'ember-metal';
import { assert } from 'ember-debug';
import Enumerable from './enumerable';
+import compare from '../compare';
+import require from 'require';
+
+
+// Required to break a module cycle
+let _A;
+function A() {
+ if (_A === undefined) {
+ _A = require('ember-runtime/system/native_array').A;
+ }
+ return _A();
+}
function arrayObserversHelper(obj, target, opts, operation, notify) {
let willChange = (opts && opts.willChange) || 'arrayWillChange';
@@ -141,6 +152,25 @@ export function isEmberArray(obj) {
return obj && obj[EMBER_ARRAY];
}
+const contexts = [];
+
+function popCtx() {
+ return contexts.length === 0 ? {} : contexts.pop();
+}
+
+function pushCtx(ctx) {
+ contexts.push(ctx);
+ return null;
+}
+
+function iter(key, value) {
+ let valueProvided = arguments.length === 2;
+
+ return valueProvided ?
+ (item)=> value === get(item, key) :
+ (item)=> !!get(item, key);
+}
+
// ..........................................................
// ARRAY
//
@@ -246,7 +276,15 @@ const ArrayMixin = Mixin.create(Enumerable, {
return indexes.map(idx => objectAt(this, idx));
},
- // overrides Enumerable version
+ /**
+ @method nextObject
+ @param {Number} index the current index of the iteration
+ @param {Object} previousObject the value returned by the last call to
+ `nextObject`.
+ @param {Object} context a context object you can use to maintain state.
+ @return {Object} the next object in the iteration or undefined
+ @private
+ */
nextObject(idx) {
return objectAt(this, idx);
},
@@ -272,10 +310,24 @@ const ArrayMixin = Mixin.create(Enumerable, {
}
}),
+ /**
+ The first object in the array, or `undefined` if the array is empty.
+
+ @property firstObject
+ @return {Object | undefined} The first object in the array
+ @public
+ */
firstObject: computed(function() {
return objectAt(this, 0);
}).readOnly(),
+ /**
+ The last object in the array, or `undefined` if the array is empty.
+
+ @property lastObject
+ @return {Object | undefined} The last object in the array
+ @public
+ */
lastObject: computed(function() {
return objectAt(this, get(this, 'length') - 1);
}).readOnly(),
@@ -301,7 +353,7 @@ const ArrayMixin = Mixin.create(Enumerable, {
@public
*/
slice(beginIndex, endIndex) {
- let ret = Ember.A();
+ let ret = A();
let length = get(this, 'length');
if (isNone(beginIndex)) {
@@ -508,6 +560,665 @@ const ArrayMixin = Mixin.create(Enumerable, {
return arrayContentDidChange(this, startIdx, removeAmt, addAmt);
},
+ /**
+ Invoke this method just before the contents of your enumerable will
+ change. You can either omit the parameters completely or pass the objects
+ to be removed or added if available or just a count.
+
+ @method enumerableContentWillChange
+ @param {Enumerable|Number} removing An enumerable of the objects to
+ be removed or the number of items to be removed.
+ @param {Enumerable|Number} adding An enumerable of the objects to be
+ added or the number of items to be added.
+ @chainable
+ @private
+ */
+ enumerableContentWillChange(removing, adding) {
+ let removeCnt, addCnt, hasDelta;
+
+ if ('number' === typeof removing) {
+ removeCnt = removing;
+ } else if (removing) {
+ removeCnt = get(removing, 'length');
+ } else {
+ removeCnt = removing = -1;
+ }
+
+ if ('number' === typeof adding) {
+ addCnt = adding;
+ } else if (adding) {
+ addCnt = get(adding, 'length');
+ } else {
+ addCnt = adding = -1;
+ }
+
+ hasDelta = addCnt < 0 || removeCnt < 0 || addCnt - removeCnt !== 0;
+
+ if (removing === -1) {
+ removing = null;
+ }
+
+ if (adding === -1) {
+ adding = null;
+ }
+
+ propertyWillChange(this, '[]');
+
+ if (hasDelta) {
+ propertyWillChange(this, 'length');
+ }
+
+ return this;
+ },
+
+ /**
+ Invoke this method when the contents of your enumerable has changed.
+ This will notify any observers watching for content changes. If you are
+ implementing an ordered enumerable (such as an array), also pass the
+ start and end values where the content changed so that it can be used to
+ notify range observers.
+
+ @method enumerableContentDidChange
+ @param {Enumerable|Number} removing An enumerable of the objects to
+ be removed or the number of items to be removed.
+ @param {Enumerable|Number} adding An enumerable of the objects to
+ be added or the number of items to be added.
+ @chainable
+ @private
+ */
+ enumerableContentDidChange(removing, adding) {
+ let removeCnt, addCnt, hasDelta;
+
+ if ('number' === typeof removing) {
+ removeCnt = removing;
+ } else if (removing) {
+ removeCnt = get(removing, 'length');
+ } else {
+ removeCnt = removing = -1;
+ }
+
+ if ('number' === typeof adding) {
+ addCnt = adding;
+ } else if (adding) {
+ addCnt = get(adding, 'length');
+ } else {
+ addCnt = adding = -1;
+ }
+
+ hasDelta = addCnt < 0 || removeCnt < 0 || addCnt - removeCnt !== 0;
+
+ if (removing === -1) {
+ removing = null;
+ }
+
+ if (adding === -1) {
+ adding = null;
+ }
+
+ if (hasDelta) {
+ propertyDidChange(this, 'length');
+ }
+
+ propertyDidChange(this, '[]');
+
+ return this;
+ },
+
+
+ /**
+ Iterates through the enumerable, calling the passed function on each
+ item. This method corresponds to the `forEach()` method defined in
+ JavaScript 1.6.
+
+ The callback method you provide should have the following signature (all
+ parameters are optional):
+
+ ```javascript
+ function(item, index, enumerable);
+ ```
+
+ - `item` is the current item in the iteration.
+ - `index` is the current index in the iteration.
+ - `enumerable` is the enumerable object itself.
+
+ Note that in addition to a callback, you can also pass an optional target
+ object that will be set as `this` on the context. This is a good way
+ to give your iterator function access to the current object.
+
+ @method forEach
+ @param {Function} callback The callback to execute
+ @param {Object} [target] The target object to use
+ @return {Object} receiver
+ @public
+ */
+ forEach(callback, target) {
+ assert('Enumerable#forEach expects a function as first argument.', typeof callback === 'function');
+
+ let context = popCtx();
+ let len = get(this, 'length');
+ let last = null;
+
+ if (target === undefined) {
+ target = null;
+ }
+
+ for (let idx = 0; idx < len; idx++) {
+ let next = this.nextObject(idx, last, context);
+ callback.call(target, next, idx, this);
+ last = next;
+ }
+
+ last = null;
+ context = pushCtx(context);
+
+ return this;
+ },
+
+ /**
+ Alias for `mapBy`
+
+ @method getEach
+ @param {String} key name of the property
+ @return {Array} The mapped array.
+ @public
+ */
+ getEach: aliasMethod('mapBy'),
+
+ /**
+ Sets the value on the named property for each member. This is more
+ ergonomic than using other methods defined on this helper. If the object
+ implements Observable, the value will be changed to `set(),` otherwise
+ it will be set directly. `null` objects are skipped.
+
+ @method setEach
+ @param {String} key The key to set
+ @param {Object} value The object to set
+ @return {Object} receiver
+ @public
+ */
+ setEach(key, value) {
+ return this.forEach(item => set(item, key, value));
+ },
+
+ /**
+ Maps all of the items in the enumeration to another value, returning
+ a new array. This method corresponds to `map()` defined in JavaScript 1.6.
+
+ The callback method you provide should have the following signature (all
+ parameters are optional):
+
+ ```javascript
+ function(item, index, enumerable);
+ ```
+
+ - `item` is the current item in the iteration.
+ - `index` is the current index in the iteration.
+ - `enumerable` is the enumerable object itself.
+
+ It should return the mapped value.
+
+ Note that in addition to a callback, you can also pass an optional target
+ object that will be set as `this` on the context. This is a good way
+ to give your iterator function access to the current object.
+
+ @method map
+ @param {Function} callback The callback to execute
+ @param {Object} [target] The target object to use
+ @return {Array} The mapped array.
+ @public
+ */
+ map(callback, target) {
+ assert('Enumerable#map expects a function as first argument.', typeof callback === 'function');
+
+ let ret = A();
+
+ this.forEach((x, idx, i) => ret[idx] = callback.call(target, x, idx, i));
+
+ return ret;
+ },
+
+ /**
+ Similar to map, this specialized function returns the value of the named
+ property on all items in the enumeration.
+
+ @method mapBy
+ @param {String} key name of the property
+ @return {Array} The mapped array.
+ @public
+ */
+ mapBy(key) {
+ return this.map(next => get(next, key));
+ },
+
+ /**
+ Returns an array with all of the items in the enumeration that the passed
+ function returns true for. This method corresponds to `filter()` defined in
+ JavaScript 1.6.
+
+ The callback method you provide should have the following signature (all
+ parameters are optional):
+
+ ```javascript
+ function(item, index, enumerable);
+ ```
+
+ - `item` is the current item in the iteration.
+ - `index` is the current index in the iteration.
+ - `enumerable` is the enumerable object itself.
+
+ It should return `true` to include the item in the results, `false`
+ otherwise.
+
+ Note that in addition to a callback, you can also pass an optional target
+ object that will be set as `this` on the context. This is a good way
+ to give your iterator function access to the current object.
+
+ @method filter
+ @param {Function} callback The callback to execute
+ @param {Object} [target] The target object to use
+ @return {Array} A filtered array.
+ @public
+ */
+ filter(callback, target) {
+ assert('Enumerable#filter expects a function as first argument.', typeof callback === 'function');
+
+ let ret = A();
+
+ this.forEach((x, idx, i) => {
+ if (callback.call(target, x, idx, i)) {
+ ret.push(x);
+ }
+ });
+
+ return ret;
+ },
+
+ /**
+ Returns an array with all of the items in the enumeration where the passed
+ function returns false. This method is the inverse of filter().
+
+ The callback method you provide should have the following signature (all
+ parameters are optional):
+
+ ```javascript
+ function(item, index, enumerable);
+ ```
+
+ - *item* is the current item in the iteration.
+ - *index* is the current index in the iteration
+ - *enumerable* is the enumerable object itself.
+
+ It should return a falsey value to include the item in the results.
+
+ Note that in addition to a callback, you can also pass an optional target
+ object that will be set as "this" on the context. This is a good way
+ to give your iterator function access to the current object.
+
+ @method reject
+ @param {Function} callback The callback to execute
+ @param {Object} [target] The target object to use
+ @return {Array} A rejected array.
+ @public
+ */
+ reject(callback, target) {
+ assert('Enumerable#reject expects a function as first argument.', typeof callback === 'function');
+
+ return this.filter(function() {
+ return !(callback.apply(target, arguments));
+ });
+ },
+
+ /**
+ Returns an array with just the items with the matched property. You
+ can pass an optional second argument with the target value. Otherwise
+ this will match any property that evaluates to `true`.
+
+ @method filterBy
+ @param {String} key the property to test
+ @param {*} [value] optional value to test against.
+ @return {Array} filtered array
+ @public
+ */
+ filterBy(key, value) { // eslint-disable-line no-unused-vars
+ return this.filter(iter.apply(this, arguments));
+ },
+
+ /**
+ Returns an array with the items that do not have truthy values for
+ key. You can pass an optional second argument with the target value. Otherwise
+ this will match any property that evaluates to false.
+
+ @method rejectBy
+ @param {String} key the property to test
+ @param {String} [value] optional value to test against.
+ @return {Array} rejected array
+ @public
+ */
+ rejectBy(key, value) {
+ let exactValue = item => get(item, key) === value;
+ let hasValue = item => !!get(item, key);
+ let use = (arguments.length === 2 ? exactValue : hasValue);
+
+ return this.reject(use);
+ },
+
+ /**
+ Returns the first item in the array for which the callback returns true.
+ This method works similar to the `filter()` method defined in JavaScript 1.6
+ except that it will stop working on the array once a match is found.
+
+ The callback method you provide should have the following signature (all
+ parameters are optional):
+
+ ```javascript
+ function(item, index, enumerable);
+ ```
+
+ - `item` is the current item in the iteration.
+ - `index` is the current index in the iteration.
+ - `enumerable` is the enumerable object itself.
+
+ It should return the `true` to include the item in the results, `false`
+ otherwise.
+
+ Note that in addition to a callback, you can also pass an optional target
+ object that will be set as `this` on the context. This is a good way
+ to give your iterator function access to the current object.
+
+ @method find
+ @param {Function} callback The callback to execute
+ @param {Object} [target] The target object to use
+ @return {Object} Found item or `undefined`.
+ @public
+ */
+ find(callback, target) {
+ assert('Enumerable#find expects a function as first argument.', typeof callback === 'function');
+
+ let len = get(this, 'length');
+
+ if (target === undefined) {
+ target = null;
+ }
+
+ let context = popCtx();
+ let found = false;
+ let last = null;
+ let next, ret;
+
+ for (let idx = 0; idx < len && !found; idx++) {
+ next = this.nextObject(idx, last, context);
+
+ found = callback.call(target, next, idx, this);
+ if (found) {
+ ret = next;
+ }
+
+ last = next;
+ }
+
+ next = last = null;
+ context = pushCtx(context);
+
+ return ret;
+ },
+
+ /**
+ Returns the first item with a property matching the passed value. You
+ can pass an optional second argument with the target value. Otherwise
+ this will match any property that evaluates to `true`.
+
+ This method works much like the more generic `find()` method.
+
+ @method findBy
+ @param {String} key the property to test
+ @param {String} [value] optional value to test against.
+ @return {Object} found item or `undefined`
+ @public
+ */
+ findBy(key, value) { // eslint-disable-line no-unused-vars
+ return this.find(iter.apply(this, arguments));
+ },
+
+ /**
+ Returns `true` if the passed function returns true for every item in the
+ enumeration. This corresponds with the `every()` method in JavaScript 1.6.
+
+ The callback method you provide should have the following signature (all
+ parameters are optional):
+
+ ```javascript
+ function(item, index, enumerable);
+ ```
+
+ - `item` is the current item in the iteration.
+ - `index` is the current index in the iteration.
+ - `enumerable` is the enumerable object itself.
+
+ It should return the `true` or `false`.
+
+ Note that in addition to a callback, you can also pass an optional target
+ object that will be set as `this` on the context. This is a good way
+ to give your iterator function access to the current object.
+
+ Example Usage:
+
+ ```javascript
+ if (people.every(isEngineer)) {
+ Paychecks.addBigBonus();
+ }
+ ```
+
+ @method every
+ @param {Function} callback The callback to execute
+ @param {Object} [target] The target object to use
+ @return {Boolean}
+ @public
+ */
+ every(callback, target) {
+ assert('Enumerable#every expects a function as first argument.', typeof callback === 'function');
+
+ return !this.find((x, idx, i) => !callback.call(target, x, idx, i));
+ },
+
+ /**
+ Returns `true` if the passed property resolves to the value of the second
+ argument for all items in the enumerable. This method is often simpler/faster
+ than using a callback.
+
+ Note that like the native `Array.every`, `isEvery` will return true when called
+ on any empty enumerable.
+
+ @method isEvery
+ @param {String} key the property to test
+ @param {String} [value] optional value to test against. Defaults to `true`
+ @return {Boolean}
+ @since 1.3.0
+ @public
+ */
+ isEvery(key, value) { // eslint-disable-line no-unused-vars
+ return this.every(iter.apply(this, arguments));
+ },
+
+ /**
+ Returns `true` if the passed function returns true for any item in the
+ enumeration.
+
+ The callback method you provide should have the following signature (all
+ parameters are optional):
+
+ ```javascript
+ function(item, index, enumerable);
+ ```
+
+ - `item` is the current item in the iteration.
+ - `index` is the current index in the iteration.
+ - `enumerable` is the enumerable object itself.
+
+ It must return a truthy value (i.e. `true`) to include an item in the
+ results. Any non-truthy return value will discard the item from the
+ results.
+
+ Note that in addition to a callback, you can also pass an optional target
+ object that will be set as `this` on the context. This is a good way
+ to give your iterator function access to the current object.
+
+ Usage Example:
+
+ ```javascript
+ if (people.any(isManager)) {
+ Paychecks.addBiggerBonus();
+ }
+ ```
+
+ @method any
+ @param {Function} callback The callback to execute
+ @param {Object} [target] The target object to use
+ @return {Boolean} `true` if the passed function returns `true` for any item
+ @public
+ */
+ any(callback, target) {
+ assert('Enumerable#any expects a function as first argument.', typeof callback === 'function');
+
+ let len = get(this, 'length');
+ let context = popCtx();
+ let found = false;
+ let last = null;
+ let next;
+
+ if (target === undefined) {
+ target = null;
+ }
+
+ for (let idx = 0; idx < len && !found; idx++) {
+ next = this.nextObject(idx, last, context);
+ found = callback.call(target, next, idx, this);
+ last = next;
+ }
+
+ next = last = null;
+ context = pushCtx(context);
+ return found;
+ },
+
+ /**
+ Returns `true` if the passed property resolves to the value of the second
+ argument for any item in the enumerable. This method is often simpler/faster
+ than using a callback.
+
+ @method isAny
+ @param {String} key the property to test
+ @param {String} [value] optional value to test against. Defaults to `true`
+ @return {Boolean}
+ @since 1.3.0
+ @public
+ */
+ isAny(key, value) { // eslint-disable-line no-unused-vars
+ return this.any(iter.apply(this, arguments));
+ },
+
+ /**
+ This will combine the values of the enumerator into a single value. It
+ is a useful way to collect a summary value from an enumeration. This
+ corresponds to the `reduce()` method defined in JavaScript 1.8.
+
+ The callback method you provide should have the following signature (all
+ parameters are optional):
+
+ ```javascript
+ function(previousValue, item, index, enumerable);
+ ```
+
+ - `previousValue` is the value returned by the last call to the iterator.
+ - `item` is the current item in the iteration.
+ - `index` is the current index in the iteration.
+ - `enumerable` is the enumerable object itself.
+
+ Return the new cumulative value.
+
+ In addition to the callback you can also pass an `initialValue`. An error
+ will be raised if you do not pass an initial value and the enumerator is
+ empty.
+
+ Note that unlike the other methods, this method does not allow you to
+ pass a target object to set as this for the callback. It's part of the
+ spec. Sorry.
+
+ @method reduce
+ @param {Function} callback The callback to execute
+ @param {Object} initialValue Initial value for the reduce
+ @param {String} reducerProperty internal use only.
+ @return {Object} The reduced value.
+ @public
+ */
+ reduce(callback, initialValue, reducerProperty) {
+ assert('Enumerable#reduce expects a function as first argument.', typeof callback === 'function');
+
+ let ret = initialValue;
+
+ this.forEach(function(item, i) {
+ ret = callback(ret, item, i, this, reducerProperty);
+ }, this);
+
+ return ret;
+ },
+
+ /**
+ Invokes the named method on every object in the receiver that
+ implements it. This method corresponds to the implementation in
+ Prototype 1.6.
+
+ @method invoke
+ @param {String} methodName the name of the method
+ @param {Object...} args optional arguments to pass as well.
+ @return {Array} return values from calling invoke.
+ @public
+ */
+ invoke(methodName, ...args) {
+ let ret = A();
+
+ this.forEach((x, idx) => {
+ let method = x && x[methodName];
+
+ if ('function' === typeof method) {
+ ret[idx] = args.length ? method.apply(x, args) : x[methodName]();
+ }
+ }, this);
+
+ return ret;
+ },
+
+ /**
+ Simply converts the enumerable into a genuine array. The order is not
+ guaranteed. Corresponds to the method implemented by Prototype.
+
+ @method toArray
+ @return {Array} the enumerable as an array.
+ @public
+ */
+ toArray() {
+ let ret = A();
+
+ this.forEach((o, idx) => ret[idx] = o);
+
+ return ret;
+ },
+
+ /**
+ Returns a copy of the array with all `null` and `undefined` elements removed.
+
+ ```javascript
+ let arr = ['a', null, 'c', undefined];
+ arr.compact(); // ['a', 'c']
+ ```
+
+ @method compact
+ @return {Array} the array without null and undefined elements.
+ @public
+ */
+ compact() {
+ return this.filter(value => value != null);
+ },
+
/**
Returns `true` if the passed object can be found in the array.
This method is a Polyfill for ES 2016 Array.includes.
@@ -555,6 +1266,127 @@ const ArrayMixin = Mixin.create(Enumerable, {
return false;
},
+ /**
+ Converts the enumerable into an array and sorts by the keys
+ specified in the argument.
+
+ You may provide multiple arguments to sort by multiple properties.
+
+ @method sortBy
+ @param {String} property name(s) to sort on
+ @return {Array} The sorted array.
+ @since 1.2.0
+ @public
+ */
+ sortBy() {
+ let sortKeys = arguments;
+
+ return this.toArray().sort((a, b) => {
+ for (let i = 0; i < sortKeys.length; i++) {
+ let key = sortKeys[i];
+ let propA = get(a, key);
+ let propB = get(b, key);
+ // return 1 or -1 else continue to the next sortKey
+ let compareValue = compare(propA, propB);
+
+ if (compareValue) {
+ return compareValue;
+ }
+ }
+ return 0;
+ });
+ },
+
+ /**
+ Returns a new enumerable that contains only unique values. The default
+ implementation returns an array regardless of the receiver type.
+
+ ```javascript
+ let arr = ['a', 'a', 'b', 'b'];
+ arr.uniq(); // ['a', 'b']
+ ```
+
+ This only works on primitive data types, e.g. Strings, Numbers, etc.
+
+ @method uniq
+ @return {Enumerable}
+ @public
+ */
+ uniq() {
+ let ret = A();
+
+ let seen = new Set();
+ this.forEach(item => {
+ if (!seen.has(item)) {
+ seen.add(item);
+ ret.push(item);
+ }
+ });
+
+ return ret;
+ },
+
+ /**
+ Returns a new enumerable that contains only items containing a unique property value.
+ The default implementation returns an array regardless of the receiver type.
+
+ ```javascript
+ let arr = [{ value: 'a' }, { value: 'a' }, { value: 'b' }, { value: 'b' }];
+ arr.uniqBy('value'); // [{ value: 'a' }, { value: 'b' }]
+ ```
+
+ @method uniqBy
+ @return {Enumerable}
+ @public
+ */
+
+ uniqBy(key) {
+ let ret = A();
+ let seen = new Set();
+
+ this.forEach((item) => {
+ let val = get(item, key);
+ if (!seen.has(val)) {
+ seen.add(val);
+ ret.push(item);
+ }
+ });
+
+ return ret;
+ },
+
+ /**
+ Returns a new enumerable that excludes the passed value. The default
+ implementation returns an array regardless of the receiver type.
+ If the receiver does not contain the value it returns the original enumerable.
+
+ ```javascript
+ let arr = ['a', 'b', 'a', 'c'];
+ arr.without('a'); // ['b', 'c']
+ ```
+
+ @method without
+ @param {Object} value
+ @return {Enumerable}
+ @public
+ */
+ without(value) {
+ if (!this.includes(value)) {
+ return this; // nothing to do
+ }
+
+ let ret = A();
+
+ this.forEach(k => {
+ // SameValueZero comparison (NaN !== NaN)
+ if (!(k === value || k !== k && value !== value)) {
+ ret[ret.length] = k;
+ }
+ });
+
+ return ret;
+ },
+
/**
Returns a special object that can be used to observe individual properties
on the array. Just get an equivalent property on this object and it will
| true |
Other
|
emberjs
|
ember.js
|
1a29eb96a49e642ad8a7b8d07a96ffc0f3f2a6a4.json
|
Move enumerable mixin methods into array mixins
|
packages/ember-runtime/lib/mixins/enumerable.js
|
@@ -1,1046 +1,16 @@
+import { Mixin } from 'ember-metal';
+
/**
-@module @ember/enumerable
-@private
+@module ember
*/
-// ..........................................................
-// HELPERS
-//
-
-import {
- get,
- set,
- Mixin,
- aliasMethod,
- computed,
- propertyWillChange,
- propertyDidChange
-} from 'ember-metal';
-import { assert } from 'ember-debug';
-import compare from '../compare';
-import require from 'require';
-
-let _emberA;
-
-function emberA() {
- if (_emberA === undefined) {
- _emberA = require('ember-runtime/system/native_array').A;
- }
- return _emberA();
-}
-
-const contexts = [];
-
-function popCtx() {
- return contexts.length === 0 ? {} : contexts.pop();
-}
-
-function pushCtx(ctx) {
- contexts.push(ctx);
- return null;
-}
-
-function iter(key, value) {
- let valueProvided = arguments.length === 2;
-
- return valueProvided ?
- (item)=> value === get(item, key) :
- (item)=> !!get(item, key);
-}
-
/**
- This mixin defines the common interface implemented by enumerable objects
- in Ember. Most of these methods follow the standard Array iteration
- API defined up to JavaScript 1.8 (excluding language-specific features that
- cannot be emulated in older versions of JavaScript).
-
- This mixin is applied automatically to the Array class on page load, so you
- can use any of these methods on simple arrays. If Array already implements
- one of these methods, the mixin will not override them.
-
- ## Writing Your Own Enumerable
-
- To make your own custom class enumerable, you need two items:
-
- 1. You must have a length property. This property should change whenever
- the number of items in your enumerable object changes. If you use this
- with an `EmberObject` subclass, you should be sure to change the length
- property using `set().`
-
- 2. You must implement `nextObject().` See documentation.
-
- Once you have these two methods implemented, apply the `Enumerable` mixin
- to your class and you will be able to enumerate the contents of your object
- like any other collection.
-
- ## Using Ember Enumeration with Other Libraries
-
- Many other libraries provide some kind of iterator or enumeration like
- facility. This is often where the most common API conflicts occur.
- Ember's API is designed to be as friendly as possible with other
- libraries by implementing only methods that mostly correspond to the
- JavaScript 1.8 API.
+ The methods in this mixin have been moved to MutableArray. This mixin has
+ been intentionally preserved to avoid breaking Enumerable.detect checks
+ until the community migrates away from them.
@class Enumerable
- @since Ember 0.9
+ @namespace Ember
@private
*/
-const Enumerable = Mixin.create({
-
- /**
- __Required.__ You must implement this method to apply this mixin.
-
- Implement this method to make your class enumerable.
-
- This method will be called repeatedly during enumeration. The index value
- will always begin with 0 and increment monotonically. You don't have to
- rely on the index value to determine what object to return, but you should
- always check the value and start from the beginning when you see the
- requested index is 0.
-
- The `previousObject` is the object that was returned from the last call
- to `nextObject` for the current iteration. This is a useful way to
- manage iteration if you are tracing a linked list, for example.
-
- Finally the context parameter will always contain a hash you can use as
- a "scratchpad" to maintain any other state you need in order to iterate
- properly. The context object is reused and is not reset between
- iterations so make sure you setup the context with a fresh state whenever
- the index parameter is 0.
-
- Generally iterators will continue to call `nextObject` until the index
- reaches the current length-1. If you run out of data before this
- time for some reason, you should simply return undefined.
-
- The default implementation of this method simply looks up the index.
- This works great on any Array-like objects.
-
- @method nextObject
- @param {Number} index the current index of the iteration
- @param {Object} previousObject the value returned by the last call to
- `nextObject`.
- @param {Object} context a context object you can use to maintain state.
- @return {Object} the next object in the iteration or undefined
- @private
- */
- nextObject: null,
-
- /**
- Helper method returns the first object from a collection. This is usually
- used by bindings and other parts of the framework to extract a single
- object if the enumerable contains only one item.
-
- If you override this method, you should implement it so that it will
- always return the same value each time it is called. If your enumerable
- contains only one object, this method should always return that object.
- If your enumerable is empty, this method should return `undefined`.
-
- ```javascript
- let arr = ['a', 'b', 'c'];
- arr.get('firstObject'); // 'a'
-
- let arr = [];
- arr.get('firstObject'); // undefined
- ```
-
- @property firstObject
- @return {Object} the object or undefined
- @readOnly
- @public
- */
- firstObject: computed('[]', function() {
- if (get(this, 'length') === 0) {
- return undefined;
- }
-
- // handle generic enumerables
- let context = popCtx();
- let ret = this.nextObject(0, null, context);
-
- pushCtx(context);
-
- return ret;
- }).readOnly(),
-
- /**
- Helper method returns the last object from a collection. If your enumerable
- contains only one object, this method should always return that object.
- If your enumerable is empty, this method should return `undefined`.
-
- ```javascript
- let arr = ['a', 'b', 'c'];
- arr.get('lastObject'); // 'c'
-
- let arr = [];
- arr.get('lastObject'); // undefined
- ```
-
- @property lastObject
- @return {Object} the last object or undefined
- @readOnly
- @public
- */
- lastObject: computed('[]', function() {
- let len = get(this, 'length');
-
- if (len === 0) {
- return undefined;
- }
-
- let context = popCtx();
- let idx = 0;
- let last = null;
- let cur;
-
- do {
- last = cur;
- cur = this.nextObject(idx++, last, context);
- } while (cur !== undefined);
-
- pushCtx(context);
-
- return last;
- }).readOnly(),
-
- /**
- Iterates through the enumerable, calling the passed function on each
- item. This method corresponds to the `forEach()` method defined in
- JavaScript 1.6.
-
- The callback method you provide should have the following signature (all
- parameters are optional):
-
- ```javascript
- function(item, index, enumerable);
- ```
-
- - `item` is the current item in the iteration.
- - `index` is the current index in the iteration.
- - `enumerable` is the enumerable object itself.
-
- Note that in addition to a callback, you can also pass an optional target
- object that will be set as `this` on the context. This is a good way
- to give your iterator function access to the current object.
-
- @method forEach
- @param {Function} callback The callback to execute
- @param {Object} [target] The target object to use
- @return {Object} receiver
- @public
- */
- forEach(callback, target) {
- assert('Enumerable#forEach expects a function as first argument.', typeof callback === 'function');
-
- let context = popCtx();
- let len = get(this, 'length');
- let last = null;
-
- if (target === undefined) {
- target = null;
- }
-
- for (let idx = 0; idx < len; idx++) {
- let next = this.nextObject(idx, last, context);
- callback.call(target, next, idx, this);
- last = next;
- }
-
- last = null;
- context = pushCtx(context);
-
- return this;
- },
-
- /**
- Alias for `mapBy`
-
- @method getEach
- @param {String} key name of the property
- @return {Array} The mapped array.
- @public
- */
- getEach: aliasMethod('mapBy'),
-
- /**
- Sets the value on the named property for each member. This is more
- ergonomic than using other methods defined on this helper. If the object
- implements Observable, the value will be changed to `set(),` otherwise
- it will be set directly. `null` objects are skipped.
-
- @method setEach
- @param {String} key The key to set
- @param {Object} value The object to set
- @return {Object} receiver
- @public
- */
- setEach(key, value) {
- return this.forEach(item => set(item, key, value));
- },
-
- /**
- Maps all of the items in the enumeration to another value, returning
- a new array. This method corresponds to `map()` defined in JavaScript 1.6.
-
- The callback method you provide should have the following signature (all
- parameters are optional):
-
- ```javascript
- function(item, index, enumerable);
- ```
-
- - `item` is the current item in the iteration.
- - `index` is the current index in the iteration.
- - `enumerable` is the enumerable object itself.
-
- It should return the mapped value.
-
- Note that in addition to a callback, you can also pass an optional target
- object that will be set as `this` on the context. This is a good way
- to give your iterator function access to the current object.
-
- @method map
- @param {Function} callback The callback to execute
- @param {Object} [target] The target object to use
- @return {Array} The mapped array.
- @public
- */
- map(callback, target) {
- assert('Enumerable#map expects a function as first argument.', typeof callback === 'function');
-
- let ret = emberA();
-
- this.forEach((x, idx, i) => ret[idx] = callback.call(target, x, idx, i));
-
- return ret;
- },
-
- /**
- Similar to map, this specialized function returns the value of the named
- property on all items in the enumeration.
-
- @method mapBy
- @param {String} key name of the property
- @return {Array} The mapped array.
- @public
- */
- mapBy(key) {
- return this.map(next => get(next, key));
- },
-
- /**
- Returns an array with all of the items in the enumeration that the passed
- function returns true for. This method corresponds to `filter()` defined in
- JavaScript 1.6.
-
- The callback method you provide should have the following signature (all
- parameters are optional):
-
- ```javascript
- function(item, index, enumerable);
- ```
-
- - `item` is the current item in the iteration.
- - `index` is the current index in the iteration.
- - `enumerable` is the enumerable object itself.
-
- It should return `true` to include the item in the results, `false`
- otherwise.
-
- Note that in addition to a callback, you can also pass an optional target
- object that will be set as `this` on the context. This is a good way
- to give your iterator function access to the current object.
-
- @method filter
- @param {Function} callback The callback to execute
- @param {Object} [target] The target object to use
- @return {Array} A filtered array.
- @public
- */
- filter(callback, target) {
- assert('Enumerable#filter expects a function as first argument.', typeof callback === 'function');
-
- let ret = emberA();
-
- this.forEach((x, idx, i) => {
- if (callback.call(target, x, idx, i)) {
- ret.push(x);
- }
- });
-
- return ret;
- },
-
- /**
- Returns an array with all of the items in the enumeration where the passed
- function returns false. This method is the inverse of filter().
-
- The callback method you provide should have the following signature (all
- parameters are optional):
-
- ```javascript
- function(item, index, enumerable);
- ```
-
- - *item* is the current item in the iteration.
- - *index* is the current index in the iteration
- - *enumerable* is the enumerable object itself.
-
- It should return a falsey value to include the item in the results.
-
- Note that in addition to a callback, you can also pass an optional target
- object that will be set as "this" on the context. This is a good way
- to give your iterator function access to the current object.
-
- @method reject
- @param {Function} callback The callback to execute
- @param {Object} [target] The target object to use
- @return {Array} A rejected array.
- @public
- */
- reject(callback, target) {
- assert('Enumerable#reject expects a function as first argument.', typeof callback === 'function');
-
- return this.filter(function() {
- return !(callback.apply(target, arguments));
- });
- },
-
- /**
- Returns an array with just the items with the matched property. You
- can pass an optional second argument with the target value. Otherwise
- this will match any property that evaluates to `true`.
-
- @method filterBy
- @param {String} key the property to test
- @param {*} [value] optional value to test against.
- @return {Array} filtered array
- @public
- */
- filterBy(key, value) { // eslint-disable-line no-unused-vars
- return this.filter(iter.apply(this, arguments));
- },
-
- /**
- Returns an array with the items that do not have truthy values for
- key. You can pass an optional second argument with the target value. Otherwise
- this will match any property that evaluates to false.
-
- @method rejectBy
- @param {String} key the property to test
- @param {String} [value] optional value to test against.
- @return {Array} rejected array
- @public
- */
- rejectBy(key, value) {
- let exactValue = item => get(item, key) === value;
- let hasValue = item => !!get(item, key);
- let use = (arguments.length === 2 ? exactValue : hasValue);
-
- return this.reject(use);
- },
-
- /**
- Returns the first item in the array for which the callback returns true.
- This method works similar to the `filter()` method defined in JavaScript 1.6
- except that it will stop working on the array once a match is found.
-
- The callback method you provide should have the following signature (all
- parameters are optional):
-
- ```javascript
- function(item, index, enumerable);
- ```
-
- - `item` is the current item in the iteration.
- - `index` is the current index in the iteration.
- - `enumerable` is the enumerable object itself.
-
- It should return the `true` to include the item in the results, `false`
- otherwise.
-
- Note that in addition to a callback, you can also pass an optional target
- object that will be set as `this` on the context. This is a good way
- to give your iterator function access to the current object.
-
- @method find
- @param {Function} callback The callback to execute
- @param {Object} [target] The target object to use
- @return {Object} Found item or `undefined`.
- @public
- */
- find(callback, target) {
- assert('Enumerable#find expects a function as first argument.', typeof callback === 'function');
-
- let len = get(this, 'length');
-
- if (target === undefined) {
- target = null;
- }
-
- let context = popCtx();
- let found = false;
- let last = null;
- let next, ret;
-
- for (let idx = 0; idx < len && !found; idx++) {
- next = this.nextObject(idx, last, context);
-
- found = callback.call(target, next, idx, this);
- if (found) {
- ret = next;
- }
-
- last = next;
- }
-
- next = last = null;
- context = pushCtx(context);
-
- return ret;
- },
-
- /**
- Returns the first item with a property matching the passed value. You
- can pass an optional second argument with the target value. Otherwise
- this will match any property that evaluates to `true`.
-
- This method works much like the more generic `find()` method.
-
- @method findBy
- @param {String} key the property to test
- @param {String} [value] optional value to test against.
- @return {Object} found item or `undefined`
- @public
- */
- findBy(key, value) { // eslint-disable-line no-unused-vars
- return this.find(iter.apply(this, arguments));
- },
-
- /**
- Returns `true` if the passed function returns true for every item in the
- enumeration. This corresponds with the `every()` method in JavaScript 1.6.
-
- The callback method you provide should have the following signature (all
- parameters are optional):
-
- ```javascript
- function(item, index, enumerable);
- ```
-
- - `item` is the current item in the iteration.
- - `index` is the current index in the iteration.
- - `enumerable` is the enumerable object itself.
-
- It should return the `true` or `false`.
-
- Note that in addition to a callback, you can also pass an optional target
- object that will be set as `this` on the context. This is a good way
- to give your iterator function access to the current object.
-
- Example Usage:
-
- ```javascript
- if (people.every(isEngineer)) {
- Paychecks.addBigBonus();
- }
- ```
-
- @method every
- @param {Function} callback The callback to execute
- @param {Object} [target] The target object to use
- @return {Boolean}
- @public
- */
- every(callback, target) {
- assert('Enumerable#every expects a function as first argument.', typeof callback === 'function');
-
- return !this.find((x, idx, i) => !callback.call(target, x, idx, i));
- },
-
- /**
- Returns `true` if the passed property resolves to the value of the second
- argument for all items in the enumerable. This method is often simpler/faster
- than using a callback.
-
- Note that like the native `Array.every`, `isEvery` will return true when called
- on any empty enumerable.
-
- @method isEvery
- @param {String} key the property to test
- @param {String} [value] optional value to test against. Defaults to `true`
- @return {Boolean}
- @since 1.3.0
- @public
- */
- isEvery(key, value) { // eslint-disable-line no-unused-vars
- return this.every(iter.apply(this, arguments));
- },
-
- /**
- Returns `true` if the passed function returns true for any item in the
- enumeration.
-
- The callback method you provide should have the following signature (all
- parameters are optional):
-
- ```javascript
- function(item, index, enumerable);
- ```
-
- - `item` is the current item in the iteration.
- - `index` is the current index in the iteration.
- - `enumerable` is the enumerable object itself.
-
- It must return a truthy value (i.e. `true`) to include an item in the
- results. Any non-truthy return value will discard the item from the
- results.
-
- Note that in addition to a callback, you can also pass an optional target
- object that will be set as `this` on the context. This is a good way
- to give your iterator function access to the current object.
-
- Usage Example:
-
- ```javascript
- if (people.any(isManager)) {
- Paychecks.addBiggerBonus();
- }
- ```
-
- @method any
- @param {Function} callback The callback to execute
- @param {Object} [target] The target object to use
- @return {Boolean} `true` if the passed function returns `true` for any item
- @public
- */
- any(callback, target) {
- assert('Enumerable#any expects a function as first argument.', typeof callback === 'function');
-
- let len = get(this, 'length');
- let context = popCtx();
- let found = false;
- let last = null;
- let next;
-
- if (target === undefined) {
- target = null;
- }
-
- for (let idx = 0; idx < len && !found; idx++) {
- next = this.nextObject(idx, last, context);
- found = callback.call(target, next, idx, this);
- last = next;
- }
-
- next = last = null;
- context = pushCtx(context);
- return found;
- },
-
- /**
- Returns `true` if the passed property resolves to the value of the second
- argument for any item in the enumerable. This method is often simpler/faster
- than using a callback.
-
- @method isAny
- @param {String} key the property to test
- @param {String} [value] optional value to test against. Defaults to `true`
- @return {Boolean}
- @since 1.3.0
- @public
- */
- isAny(key, value) { // eslint-disable-line no-unused-vars
- return this.any(iter.apply(this, arguments));
- },
-
- /**
- This will combine the values of the enumerator into a single value. It
- is a useful way to collect a summary value from an enumeration. This
- corresponds to the `reduce()` method defined in JavaScript 1.8.
-
- The callback method you provide should have the following signature (all
- parameters are optional):
-
- ```javascript
- function(previousValue, item, index, enumerable);
- ```
-
- - `previousValue` is the value returned by the last call to the iterator.
- - `item` is the current item in the iteration.
- - `index` is the current index in the iteration.
- - `enumerable` is the enumerable object itself.
-
- Return the new cumulative value.
-
- In addition to the callback you can also pass an `initialValue`. An error
- will be raised if you do not pass an initial value and the enumerator is
- empty.
-
- Note that unlike the other methods, this method does not allow you to
- pass a target object to set as this for the callback. It's part of the
- spec. Sorry.
-
- @method reduce
- @param {Function} callback The callback to execute
- @param {Object} initialValue Initial value for the reduce
- @param {String} reducerProperty internal use only.
- @return {Object} The reduced value.
- @public
- */
- reduce(callback, initialValue, reducerProperty) {
- assert('Enumerable#reduce expects a function as first argument.', typeof callback === 'function');
-
- let ret = initialValue;
-
- this.forEach(function(item, i) {
- ret = callback(ret, item, i, this, reducerProperty);
- }, this);
-
- return ret;
- },
-
- /**
- Invokes the named method on every object in the receiver that
- implements it. This method corresponds to the implementation in
- Prototype 1.6.
-
- @method invoke
- @param {String} methodName the name of the method
- @param {Object...} args optional arguments to pass as well.
- @return {Array} return values from calling invoke.
- @public
- */
- invoke(methodName, ...args) {
- let ret = emberA();
-
- this.forEach((x, idx) => {
- let method = x && x[methodName];
-
- if ('function' === typeof method) {
- ret[idx] = args.length ? method.apply(x, args) : x[methodName]();
- }
- }, this);
-
- return ret;
- },
-
- /**
- Simply converts the enumerable into a genuine array. The order is not
- guaranteed. Corresponds to the method implemented by Prototype.
-
- @method toArray
- @return {Array} the enumerable as an array.
- @public
- */
- toArray() {
- let ret = emberA();
-
- this.forEach((o, idx) => ret[idx] = o);
-
- return ret;
- },
-
- /**
- Returns a copy of the array with all `null` and `undefined` elements removed.
-
- ```javascript
- let arr = ['a', null, 'c', undefined];
- arr.compact(); // ['a', 'c']
- ```
-
- @method compact
- @return {Array} the array without null and undefined elements.
- @public
- */
- compact() {
- return this.filter(value => value != null);
- },
-
- /**
- Returns a new enumerable that excludes the passed value. The default
- implementation returns an array regardless of the receiver type.
- If the receiver does not contain the value it returns the original enumerable.
-
- ```javascript
- let arr = ['a', 'b', 'a', 'c'];
- arr.without('a'); // ['b', 'c']
- ```
-
- @method without
- @param {Object} value
- @return {Enumerable}
- @public
- */
- without(value) {
- if (!this.includes(value)) {
- return this; // nothing to do
- }
-
- let ret = emberA();
-
- this.forEach(k => {
- // SameValueZero comparison (NaN !== NaN)
- if (!(k === value || k !== k && value !== value)) {
- ret[ret.length] = k;
- }
- });
-
- return ret;
- },
-
- /**
- Returns a new enumerable that contains only unique values. The default
- implementation returns an array regardless of the receiver type.
-
- ```javascript
- let arr = ['a', 'a', 'b', 'b'];
- arr.uniq(); // ['a', 'b']
- ```
-
- This only works on primitive data types, e.g. Strings, Numbers, etc.
-
- @method uniq
- @return {Enumerable}
- @public
- */
- uniq() {
- let ret = emberA();
-
- let seen = new Set();
- this.forEach(item => {
- if (!seen.has(item)) {
- seen.add(item);
- ret.push(item);
- }
- });
-
- return ret;
- },
-
- /**
- This property will trigger anytime the enumerable's content changes.
- You can observe this property to be notified of changes to the enumerable's
- content.
-
- For plain enumerables, this property is read only. `Array` overrides
- this method.
-
- @property []
- @type Array
- @return this
- @private
- */
- '[]': computed({
- get(key) { return this; } // eslint-disable-line no-unused-vars
- }),
-
- // ..........................................................
- // ENUMERABLE OBSERVERS
- //
-
- /**
- Invoke this method just before the contents of your enumerable will
- change. You can either omit the parameters completely or pass the objects
- to be removed or added if available or just a count.
-
- @method enumerableContentWillChange
- @param {Enumerable|Number} removing An enumerable of the objects to
- be removed or the number of items to be removed.
- @param {Enumerable|Number} adding An enumerable of the objects to be
- added or the number of items to be added.
- @chainable
- @private
- */
- enumerableContentWillChange(removing, adding) {
- let removeCnt, addCnt, hasDelta;
-
- if ('number' === typeof removing) {
- removeCnt = removing;
- } else if (removing) {
- removeCnt = get(removing, 'length');
- } else {
- removeCnt = removing = -1;
- }
-
- if ('number' === typeof adding) {
- addCnt = adding;
- } else if (adding) {
- addCnt = get(adding, 'length');
- } else {
- addCnt = adding = -1;
- }
-
- hasDelta = addCnt < 0 || removeCnt < 0 || addCnt - removeCnt !== 0;
-
- if (removing === -1) {
- removing = null;
- }
-
- if (adding === -1) {
- adding = null;
- }
-
- propertyWillChange(this, '[]');
-
- if (hasDelta) {
- propertyWillChange(this, 'length');
- }
-
- return this;
- },
-
- /**
- Invoke this method when the contents of your enumerable has changed.
- This will notify any observers watching for content changes. If you are
- implementing an ordered enumerable (such as an array), also pass the
- start and end values where the content changed so that it can be used to
- notify range observers.
-
- @method enumerableContentDidChange
- @param {Enumerable|Number} removing An enumerable of the objects to
- be removed or the number of items to be removed.
- @param {Enumerable|Number} adding An enumerable of the objects to
- be added or the number of items to be added.
- @chainable
- @private
- */
- enumerableContentDidChange(removing, adding) {
- let removeCnt, addCnt, hasDelta;
-
- if ('number' === typeof removing) {
- removeCnt = removing;
- } else if (removing) {
- removeCnt = get(removing, 'length');
- } else {
- removeCnt = removing = -1;
- }
-
- if ('number' === typeof adding) {
- addCnt = adding;
- } else if (adding) {
- addCnt = get(adding, 'length');
- } else {
- addCnt = adding = -1;
- }
-
- hasDelta = addCnt < 0 || removeCnt < 0 || addCnt - removeCnt !== 0;
-
- if (removing === -1) {
- removing = null;
- }
-
- if (adding === -1) {
- adding = null;
- }
-
- if (hasDelta) {
- propertyDidChange(this, 'length');
- }
-
- propertyDidChange(this, '[]');
-
- return this;
- },
-
- /**
- Converts the enumerable into an array and sorts by the keys
- specified in the argument.
-
- You may provide multiple arguments to sort by multiple properties.
-
- @method sortBy
- @param {String} property name(s) to sort on
- @return {Array} The sorted array.
- @since 1.2.0
- @public
- */
- sortBy() {
- let sortKeys = arguments;
-
- return this.toArray().sort((a, b) => {
- for (let i = 0; i < sortKeys.length; i++) {
- let key = sortKeys[i];
- let propA = get(a, key);
- let propB = get(b, key);
- // return 1 or -1 else continue to the next sortKey
- let compareValue = compare(propA, propB);
-
- if (compareValue) {
- return compareValue;
- }
- }
- return 0;
- });
- },
-
- /**
- Returns a new enumerable that contains only items containing a unique property value.
- The default implementation returns an array regardless of the receiver type.
-
- ```javascript
- let arr = [{ value: 'a' }, { value: 'a' }, { value: 'b' }, { value: 'b' }];
- arr.uniqBy('value'); // [{ value: 'a' }, { value: 'b' }]
- ```
-
- @method uniqBy
- @return {Enumerable}
- @public
- */
-
- uniqBy(key) {
- let ret = emberA();
- let seen = new Set();
-
- this.forEach((item) => {
- let val = get(item, key);
- if (!seen.has(val)) {
- seen.add(val);
- ret.push(item);
- }
- });
-
- return ret;
- },
-
- /**
- Returns `true` if the passed object can be found in the enumerable.
-
- ```javascript
- [1, 2, 3].includes(2); // true
- [1, 2, 3].includes(4); // false
- [1, 2, undefined].includes(undefined); // true
- [1, 2, null].includes(null); // true
- [1, 2, NaN].includes(NaN); // true
- ```
-
- @method includes
- @param {Object} obj The object to search for.
- @return {Boolean} `true` if object is found in the enumerable.
- @public
- */
- includes(obj) {
- assert('Enumerable#includes cannot accept a second argument "startAt" as enumerable items are unordered.', arguments.length === 1);
-
- let len = get(this, 'length');
- let idx, next;
- let last = null;
- let found = false;
-
- let context = popCtx();
-
- for (idx = 0; idx < len && !found; idx++) {
- next = this.nextObject(idx, last, context);
-
- found = obj === next || (obj !== obj && next !== next);
-
- last = next;
- }
-
- next = last = null;
- context = pushCtx(context);
-
- return found;
- }
-});
-
-export default Enumerable;
+export default Mixin.create();
| true |
Other
|
emberjs
|
ember.js
|
1a29eb96a49e642ad8a7b8d07a96ffc0f3f2a6a4.json
|
Move enumerable mixin methods into array mixins
|
packages/ember-runtime/lib/mixins/mutable_array.js
|
@@ -2,23 +2,20 @@
@module @ember/array
*/
-
-const OUT_OF_RANGE_EXCEPTION = 'Index out of range';
-const EMPTY = [];
-
-// ..........................................................
-// HELPERS
-//
-
import {
get,
- Mixin
+ Mixin,
+ beginPropertyChanges,
+ endPropertyChanges
} from 'ember-metal';
-import EmberArray, { objectAt } from './array';
-import MutableEnumerable from './mutable_enumerable';
import Enumerable from './enumerable';
+import MutableEnumerable from './mutable_enumerable';
+import EmberArray, { objectAt } from './array';
import { Error as EmberError } from 'ember-debug';
+const OUT_OF_RANGE_EXCEPTION = 'Index out of range';
+const EMPTY = [];
+
export function removeAt(array, start, len) {
if ('number' === typeof start) {
if ((start < 0) || (start >= get(array, 'length'))) {
@@ -53,7 +50,7 @@ export function removeAt(array, start, len) {
@class MutableArray
@uses EmberArray
- @uses Ember.MutableEnumerable
+ @uses MutableEnumerable
@public
*/
export default Mixin.create(EmberArray, MutableEnumerable, {
@@ -368,6 +365,23 @@ export default Mixin.create(EmberArray, MutableEnumerable, {
return this;
},
+ /**
+ Removes each object in the passed array from the receiver.
+
+ @method removeObjects
+ @param {EmberArray} objects the objects to remove
+ @return {EmberArray} receiver
+ @public
+ */
+ removeObjects(objects) {
+ beginPropertyChanges(this);
+ for (let i = objects.length - 1; i >= 0; i--) {
+ this.removeObject(objects[i]);
+ }
+ endPropertyChanges(this);
+ return this;
+ },
+
/**
Push the object onto the end of the array if it is not already
present in the array.
@@ -391,6 +405,21 @@ export default Mixin.create(EmberArray, MutableEnumerable, {
this.pushObject(obj);
}
+ return this;
+ },
+
+ /**
+ Adds each object in the passed array to the receiver.
+
+ @method addObjects
+ @param {EmberArray} objects the objects to add.
+ @return {EmberArray} receiver
+ @public
+ */
+ addObjects(objects) {
+ beginPropertyChanges(this);
+ objects.forEach(obj => this.addObject(obj));
+ endPropertyChanges(this);
return this;
}
});
| true |
Other
|
emberjs
|
ember.js
|
1a29eb96a49e642ad8a7b8d07a96ffc0f3f2a6a4.json
|
Move enumerable mixin methods into array mixins
|
packages/ember-runtime/lib/mixins/mutable_enumerable.js
|
@@ -1,120 +1,18 @@
import Enumerable from './enumerable';
-import {
- Mixin,
- beginPropertyChanges,
- endPropertyChanges
-} from 'ember-metal';
+import { Mixin } from 'ember-metal';
/**
@module ember
*/
/**
- This mixin defines the API for modifying generic enumerables. These methods
- can be applied to an object regardless of whether it is ordered or
- unordered.
-
- Note that an Enumerable can change even if it does not implement this mixin.
- For example, a MappedEnumerable cannot be directly modified but if its
- underlying enumerable changes, it will change also.
-
- ## Adding Objects
-
- To add an object to an enumerable, use the `addObject()` method. This
- method will only add the object to the enumerable if the object is not
- already present and is of a type supported by the enumerable.
-
- ```javascript
- set.addObject(contact);
- ```
-
- ## Removing Objects
-
- To remove an object from an enumerable, use the `removeObject()` method. This
- will only remove the object if it is present in the enumerable, otherwise
- this method has no effect.
-
- ```javascript
- set.removeObject(contact);
- ```
-
- ## Implementing In Your Own Code
-
- If you are implementing an object and want to support this API, just include
- this mixin in your class and implement the required methods. In your unit
- tests, be sure to apply the MutableEnumerableTests to your object.
+ The methods in this mixin have been moved to MutableArray. This mixin has
+ been intentionally preserved to avoid breaking MutableEnumerable.detect
+ checks until the community migrates away from them.
@class MutableEnumerable
@namespace Ember
@uses Enumerable
@private
*/
-export default Mixin.create(Enumerable, {
-
- /**
- __Required.__ You must implement this method to apply this mixin.
-
- Attempts to add the passed object to the receiver if the object is not
- already present in the collection. If the object is present, this method
- has no effect.
-
- If the passed object is of a type not supported by the receiver,
- then this method should raise an exception.
-
- @method addObject
- @param {Object} object The object to add to the enumerable.
- @return {Object} the passed object
- @public
- */
- addObject: null,
-
- /**
- Adds each object in the passed enumerable to the receiver.
-
- @method addObjects
- @param {Enumerable} objects the objects to add.
- @return {Object} receiver
- @public
- */
- addObjects(objects) {
- beginPropertyChanges(this);
- objects.forEach(obj => this.addObject(obj));
- endPropertyChanges(this);
- return this;
- },
-
- /**
- __Required.__ You must implement this method to apply this mixin.
-
- Attempts to remove the passed object from the receiver collection if the
- object is present in the collection. If the object is not present,
- this method has no effect.
-
- If the passed object is of a type not supported by the receiver,
- then this method should raise an exception.
-
- @method removeObject
- @param {Object} object The object to remove from the enumerable.
- @return {Object} the passed object
- @public
- */
- removeObject: null,
-
-
- /**
- Removes each object in the passed enumerable from the receiver.
-
- @method removeObjects
- @param {Enumerable} objects the objects to remove
- @return {Object} receiver
- @public
- */
- removeObjects(objects) {
- beginPropertyChanges(this);
- for (let i = objects.length - 1; i >= 0; i--) {
- this.removeObject(objects[i]);
- }
- endPropertyChanges(this);
- return this;
- }
-});
+export default Mixin.create(Enumerable);
| true |
Other
|
emberjs
|
ember.js
|
d190957863dc95e2cdde88ca70d56992278c61e1.json
|
Add v3.0.0-beta.3 to CHANGELOG
[ci skip]
(cherry picked from commit 6b81acc9a6182594f3bc43e74c4cae543ace00fd)
|
CHANGELOG.md
|
@@ -1,5 +1,12 @@
# Ember Changelog
+### 3.0.0-beta.3 (January 15, 2018)
+
+- [#16095](https://github.com/emberjs/ember.js/pull/16095) [CLEANUP] Fix ember-2-legacy support for Ember.Binding.
+- [#16117](https://github.com/emberjs/ember.js/pull/16117) [BUGFIX] link-to active class applied when params change
+- [#16097](https://github.com/emberjs/ember.js/pull/16097) / [#16110](https://github.com/emberjs/ember.js/pull/16110) [CLEANUP] Remove `sync` runloop queue.
+- [#16099](https://github.com/emberjs/ember.js/pull/16099) [CLEANUP] Remove custom eventManager support.
+
### 3.0.0-beta.2 (January 8, 2018)
- [#16067](https://github.com/emberjs/ember.js/pull/16067) [BUGFIX] Fix issues with `run.debounce` with only method and wait.
| false |
Other
|
emberjs
|
ember.js
|
60331387c366d9a4f08486ffab8056e72a84702f.json
|
Simplify npm publishing.
Rely on auto-dist-tag to do its magic...
|
bin/build-for-publishing.js
|
@@ -39,6 +39,8 @@ function updateDocumentationVersion() {
}
updatePackageJSONVersion();
+// ensures that we tag this correctly
+execSync('auto-dist-tag -w');
// do a production build
execSync('yarn build');
| true |
Other
|
emberjs
|
ember.js
|
60331387c366d9a4f08486ffab8056e72a84702f.json
|
Simplify npm publishing.
Rely on auto-dist-tag to do its magic...
|
bin/publish_builds
|
@@ -8,5 +8,18 @@ if [ "$TRAVIS_PULL_REQUEST" == "false" ] && [ "$PUBLISH" == "true" ]; then
./bin/build-for-publishing.js
./bin/publish_to_s3.js
- ./bin/publish_npm
+
+ #### NPM PUBLISHING
+ if [[ "$TRAVIS_TAG" =~ ^v[0-9.]+ ]]; then
+ echo -e "CURRENT_TAG: ${TRAVIS_TAG}\n"
+ echo $NPM_AUTH_TOKEN > ~/.npmrc
+
+ NPM_USER=`npm whoami`
+ echo -e "Publishing to npm as $NPM_USER...\n"
+
+ # auto-dist-tag is ran by bin/build-for-publishing.js
+ # this ensures that the `publishConfig` object in the `package.json`
+ # indicates the correct tag to be published
+ npm publish
+ fi
fi
| true |
Other
|
emberjs
|
ember.js
|
60331387c366d9a4f08486ffab8056e72a84702f.json
|
Simplify npm publishing.
Rely on auto-dist-tag to do its magic...
|
bin/publish_npm
|
@@ -1,61 +0,0 @@
-#!/usr/bin/env bash
-
-git config --global user.email "[email protected]"
-git config --global user.name "Tomster"
-
-echo -e "CURRENT_BRANCH: ${TRAVIS_BRANCH}\n"
-echo -e "CURRENT_TAG: ${TRAVIS_TAG}\n"
-
-if [[ $TRAVIS_PULL_REQUEST != "false" ]]; then
- echo "not publishing because this is a pull request."
- exit 0
-fi
-
-# Set channel to publish to. If no suitable branch is found, exit successfully.
-case $TRAVIS_BRANCH in
- "master" )
- CHANNEL="canary" ;;
- "beta" )
- CHANNEL="beta" ;;
- "release" )
- CHANNEL="release" ;;
- "lts-2-4" )
- CHANNEL="lts-2-4" ;;
- "release-1-13" )
- CHANNEL="release-1-13" ;;
- * )
- if [[ "$TRAVIS_TAG" != "" ]]; then
- case "$TRAVIS_TAG" in
- *alpha* )
- CHANNEL="canary" ;;
- *beta* )
- CHANNEL="beta" ;;
- * )
- CHANNEL="release" ;;
- esac
- else
- echo "Not a bower release branch or tag. Exiting!"
- exit 0
- fi
-esac
-echo -e "CHANNEL: ${CHANNEL}\n"
-
-if [[ -n $BUILD_TYPE ]]; then
- CHANNEL=$BUILD_TYPE
- echo -e "CHANNEL OVERRIDE: ${CHANNEL}\n"
-fi
-
-#### NPM PUBLISHING
-
-if [[ "$TRAVIS_TAG" =~ ^v[0-9.]+ ]]; then
- echo $NPM_AUTH_TOKEN > ~/.npmrc
-
- NPM_USER=`npm whoami`
- echo -e "Publishing to npm as $NPM_USER...\n"
-
- if [[ "$CHANNEL" == "release" ]]; then
- npm publish
- else
- npm publish --tag $CHANNEL
- fi
-fi
| true |
Other
|
emberjs
|
ember.js
|
c09fa056a31552a34ae29a76e341e422d7c15837.json
|
Remove remaining (unused) ruby files.
🔚😭
|
scripts/list_file_sizes.rb
|
@@ -1,43 +0,0 @@
-files = Dir["packages/ember-*/lib/**/*.js"] - Dir["packages/ember-runtime/**/*.js"]
-files = Dir["packages/ember-{metal,views,handlebars}/lib/**/*.js"]
-
-def uglify(string)
- IO.popen("uglifyjs", "r+") do |io|
- io.puts string
- io.close_write
- return io.read
- end
-end
-
-def gzip(string)
- IO.popen("gzip -f", "r+") do |io|
- io.puts string
- io.close_write
- return io.read
- end
-end
-
-
-all_files = ""
-sizes = []
-
-files.each do |file|
- this_file = File.read(file)
- all_files += this_file
- size = this_file.size
- uglified = uglify(this_file)
- gzipped = gzip(uglified)
- sizes << [size, uglified.size, gzipped.size, file]
-end
-
-# HEADER
-puts " RAW MIN MIN+GZ"
-
-sizes.sort{|a,b| b[2] <=> a[2] }.each do |size|
- puts "%8d %8d %8d - %s" % size
-end
-
-uglified = uglify(all_files)
-gzipped = gzip(uglified)
-
-puts "%8d %8d %8d" % [all_files.size, uglified.size, gzipped.size]
| false |
Other
|
emberjs
|
ember.js
|
abf7bd3727cd1ce12d06b68a2410c44d5404d998.json
|
Fix model with model param
|
packages/ember-glimmer/lib/component-managers/mount.ts
|
@@ -25,7 +25,6 @@ import { EMBER_ENGINES_MOUNT_PARAMS } from 'ember/features';
import Environment from '../environment';
import RuntimeResolver from '../resolver';
import { OwnedTemplate } from '../template';
-import { Component } from '../utils/curly-component-state-bucket';
import { RootReference } from '../utils/references';
import AbstractManager from './abstract';
@@ -37,23 +36,36 @@ interface Engine {
factoryFor(name: string): any;
}
-interface EngineBucket {
+interface EngineState {
engine: Engine;
- component?: Component;
- controller?: any;
- modelReference?: any;
- modelRevision?: any;
+ controller: any;
+ self: RootReference<any>;
+ tag: Tag;
+}
+
+interface EngineWithModelState extends EngineState {
+ modelRef: VersionedPathReference<Opaque>;
+ modelRev: number;
}
interface EngineDefinitionState {
name: string;
- capabilities: ComponentCapabilities;
+ modelRef: VersionedPathReference<Opaque> | undefined;
}
-class MountManager extends AbstractManager<EngineBucket, EngineDefinitionState>
- implements WithDynamicLayout<EngineBucket, OwnedTemplateMeta, RuntimeResolver> {
+const CAPABILITIES = {
+ dynamicLayout: true,
+ dynamicTag: false,
+ prepareArgs: false,
+ createArgs: false,
+ attributeHook: false,
+ elementHook: false
+};
+
+class MountManager extends AbstractManager<EngineState | EngineWithModelState, EngineDefinitionState>
+ implements WithDynamicLayout<EngineState | EngineWithModelState, OwnedTemplateMeta, RuntimeResolver> {
- getDynamicLayout(state: EngineBucket, _: RuntimeResolver): Invocation {
+ getDynamicLayout(state: EngineState, _: RuntimeResolver): Invocation {
let template = state.engine.lookup('template:application') as OwnedTemplate;
let layout = template.asLayout();
return {
@@ -62,49 +74,63 @@ class MountManager extends AbstractManager<EngineBucket, EngineDefinitionState>
};
}
- getCapabilities(state: EngineDefinitionState): ComponentCapabilities {
- return state.capabilities;
+ getCapabilities(): ComponentCapabilities {
+ return CAPABILITIES;
}
- create(environment: Environment, { name }: EngineDefinitionState, args: Arguments) {
+ create(environment: Environment, state: EngineDefinitionState) {
if (DEBUG) {
- this._pushEngineToDebugStack(`engine:${name}`, environment);
+ this._pushEngineToDebugStack(`engine:${state.name}`, environment);
}
- let engine = environment.owner.buildChildEngineInstance<Engine>(name);
-
- engine.boot();
-
- let bucket: EngineBucket = { engine };
+ // TODO
+ // mount is a runtime helper, this shouldn't use dynamic layout
+ // we should resolve the engine app template in the helper
+ // it also should use the owner that looked up the mount helper.
- if (EMBER_ENGINES_MOUNT_PARAMS) {
- bucket.modelReference = args.named.get('model');
- }
+ let engine = environment.owner.buildChildEngineInstance<Engine>(state.name);
- return bucket;
- }
-
- getSelf(bucket: EngineBucket): VersionedPathReference<Opaque> {
- let { engine, modelReference } = bucket;
+ engine.boot();
let applicationFactory = engine.factoryFor(`controller:application`);
let controllerFactory = applicationFactory || generateControllerFactory(engine, 'application');
- let controller = bucket.controller = controllerFactory.create();
-
+ let controller: any;
+ let self: RootReference<any>;
+ let bucket: EngineState | EngineWithModelState;
+ let tag: Tag;
if (EMBER_ENGINES_MOUNT_PARAMS) {
- let model = modelReference.value();
- bucket.modelRevision = modelReference.tag.value();
- controller.set('model', model);
+ let modelRef = state.modelRef;
+ if (modelRef === undefined) {
+ controller = controllerFactory.create();
+ self = new RootReference(controller);
+ tag = CONSTANT_TAG;
+ bucket = { engine, controller, self, tag };
+ } else {
+ let model = modelRef.value();
+ let modelRev = modelRef.tag.value();
+ controller = controllerFactory.create({ model });
+ self = new RootReference(controller);
+ tag = modelRef.tag;
+ bucket = { engine, controller, self, tag, modelRef, modelRev };
+ }
+ } else {
+ controller = controllerFactory.create();
+ self = new RootReference(controller);
+ tag = CONSTANT_TAG;
+ bucket = { engine, controller, self, tag };
}
+ return bucket;
+ }
- return new RootReference(controller);
+ getSelf({ self }: EngineState): VersionedPathReference<Opaque> {
+ return self;
}
- getTag(): Tag {
- return CONSTANT_TAG;
+ getTag(state: EngineState | EngineWithModelState): Tag {
+ return state.tag;
}
- getDestructor({ engine }: EngineBucket): Option<Destroyable> {
+ getDestructor({ engine }: EngineState): Option<Destroyable> {
return engine;
}
@@ -114,13 +140,12 @@ class MountManager extends AbstractManager<EngineBucket, EngineDefinitionState>
}
}
- update(bucket: EngineBucket): void {
+ update(bucket: EngineWithModelState): void {
if (EMBER_ENGINES_MOUNT_PARAMS) {
- let { controller, modelReference, modelRevision } = bucket;
-
- if (!modelReference.tag.validate(modelRevision)) {
- let model = modelReference.value();
- bucket.modelRevision = modelReference.tag.value();
+ let { controller, modelRef, modelRev } = bucket;
+ if (!modelRef.tag.validate(modelRev!)) {
+ let model = modelRef.value();
+ bucket.modelRev = modelRef.tag.value();
controller.set('model', model);
}
}
@@ -133,17 +158,7 @@ export class MountDefinition implements ComponentDefinition {
public state: EngineDefinitionState;
public manager = MOUNT_MANAGER;
- constructor(public name: string) {
- this.state = {
- name,
- capabilities: {
- dynamicLayout: true,
- dynamicTag: false,
- prepareArgs: false,
- createArgs: true,
- attributeHook: false,
- elementHook: false
- }
- };
+ constructor(name: string, modelRef: VersionedPathReference<Opaque> | undefined) {
+ this.state = { name, modelRef };
}
}
| true |
Other
|
emberjs
|
ember.js
|
abf7bd3727cd1ce12d06b68a2410c44d5404d998.json
|
Fix model with model param
|
packages/ember-glimmer/lib/syntax/mount.ts
|
@@ -1,7 +1,7 @@
/**
@module ember
*/
-import { Option } from '@glimmer/interfaces';
+import { Option, Opaque } from '@glimmer/interfaces';
import { OpcodeBuilder } from '@glimmer/opcode-compiler';
import { Tag, VersionedPathReference } from '@glimmer/reference';
import {
@@ -19,9 +19,10 @@ import { MountDefinition } from '../component-managers/mount';
import Environment from '../environment';
export function mountHelper(vm: VM, args: Arguments): VersionedPathReference<CurriedComponentDefinition | null> {
- let env = vm.env;
+ let env = vm.env as Environment;
let nameRef = args.positional.at(0);
- return new DynamicEngineReference({ nameRef, env });
+ let modelRef = args.named.has('model') ? args.named.get('model') : undefined;
+ return new DynamicEngineReference(nameRef, env, modelRef);
}
/**
@@ -86,19 +87,21 @@ export function mountMacro(_name: string, params: Option<WireFormat.Core.Params>
class DynamicEngineReference {
public tag: Tag;
public nameRef: VersionedPathReference<any | null | undefined>;
+ public modelRef: VersionedPathReference<Opaque> | undefined;
public env: Environment;
private _lastName: string | null;
private _lastDef: CurriedComponentDefinition | null;
- constructor({ nameRef, env }: any) {
+ constructor(nameRef: VersionedPathReference<any | undefined | null>, env: Environment, modelRef: VersionedPathReference<Opaque> | undefined) {
this.tag = nameRef.tag;
this.nameRef = nameRef;
+ this.modelRef = modelRef;
this.env = env;
this._lastName = null;
this._lastDef = null;
}
value() {
- let { env, nameRef } = this;
+ let { env, nameRef, modelRef } = this;
let name = nameRef.value();
if (typeof name === 'string') {
@@ -116,7 +119,7 @@ class DynamicEngineReference {
}
this._lastName = name;
- this._lastDef = curry(new MountDefinition(name));
+ this._lastDef = curry(new MountDefinition(name, modelRef));
return this._lastDef;
} else {
| true |
Other
|
emberjs
|
ember.js
|
1e539dbc8c57a2a90d9db0c0ee703bb8572bfd17.json
|
remove unused thing
|
packages/ember-glimmer/tests/integration/custom-component-manager-test.js
|
@@ -1,32 +1,10 @@
-import {
- PrimitiveReference
-} from '@glimmer/runtime';
import { moduleFor, RenderingTest } from '../utils/test-case';
import {
GLIMMER_CUSTOM_COMPONENT_MANAGER
} from 'ember/features';
import { AbstractComponentManager } from 'ember-glimmer';
if (GLIMMER_CUSTOM_COMPONENT_MANAGER) {
- /*
- Custom layout compiler. Exists mostly to inject
- class and attributes for testing purposes.
- */
- class TestLayoutCompiler {
- constructor(template) {
- this.template = template;
- }
-
- compile(builder) {
- builder.wrapLayout(this.template);
- builder.tag.dynamic(() => {
- return PrimitiveReference.create('p');
- });
- builder.attrs.static('class', 'hey-oh-lets-go');
- builder.attrs.static('manager-id', 'test');
- }
- }
-
/*
Implementation of custom component manager, `ComponentManager` interface
*/
| false |
Other
|
emberjs
|
ember.js
|
135d84b7ad494cc04e34f512b58a117d271d1fd5.json
|
Fix args for model
|
packages/ember-glimmer/lib/syntax/render.ts
|
@@ -58,10 +58,14 @@ export function renderHelper(vm: VM, args: Arguments): VersionedPathReference<Cu
controllerName = templateName;
}
- let manager = args.positional.length === 1 ? SINGLETON_RENDER_MANAGER : NON_SINGLETON_RENDER_MANAGER;
-
- let def = new RenderDefinition(controllerName, template, env, manager);
- return UnboundReference.create(curry(def));
+ if (args.positional.length === 1) {
+ let def = new RenderDefinition(controllerName, template, env, SINGLETON_RENDER_MANAGER);
+ return UnboundReference.create(curry(def));
+ } else {
+ let def = new RenderDefinition(controllerName, template, env, NON_SINGLETON_RENDER_MANAGER);
+ let captured = args.capture();
+ return UnboundReference.create(curry(def, captured));
+ }
}
/**
| false |
Other
|
emberjs
|
ember.js
|
9240931232dc8adb99aaf24dce8739421ae44a44.json
|
Fix helper and part of render
|
packages/ember-glimmer/lib/component-managers/render.ts
|
@@ -63,7 +63,7 @@ const CAPABILITIES = {
dynamicLayout: false,
dynamicTag: false,
prepareArgs: false,
- createArgs: false,
+ createArgs: true,
attributeHook: false,
elementHook: false
};
| true |
Other
|
emberjs
|
ember.js
|
9240931232dc8adb99aaf24dce8739421ae44a44.json
|
Fix helper and part of render
|
packages/ember-glimmer/lib/helper.ts
|
@@ -39,8 +39,7 @@ export interface HelperInstance {
export function isHelperFactory(helper: any | undefined | null): helper is HelperFactory {
return typeof helper === 'object' &&
helper !== null &&
- typeof helper.class === 'function' &&
- helper.class.isHelperFactory;
+ helper.class && helper.class.isHelperFactory;
}
export function isSimpleHelper(helper: HelperFactory): helper is SimpleHelperFactory {
| true |
Other
|
emberjs
|
ember.js
|
c7a7bc7665883fa872ebb423bb08c0aea3bf3be8.json
|
Fix remaining contextual component tests.
Issue deprecation when conflicting named and positional params exist
(changed from per-layer assert to post-merge deprecation).
|
packages/ember-glimmer/lib/component-managers/curly.ts
|
@@ -28,6 +28,7 @@ import { Destroyable, EMPTY_ARRAY, Opaque } from '@glimmer/util';
import { privatize as P } from 'container';
import {
assert,
+ deprecate,
} from 'ember-debug';
import { DEBUG } from 'ember-env-flags';
import {
@@ -223,7 +224,10 @@ export default class CurlyComponentManager extends AbstractManager<ComponentStat
for (let i=0; i<count; i++) {
const name = positionalParams[i];
if (named[name]) {
- assert(`You cannot specify both a positional param (at position ${i}) and the hash argument \`${name}\`.`);
+ deprecate(`You cannot specify both a positional param (at position ${i}) and the hash argument \`${name}\`.`, !named[name], {
+ id: 'ember-glimmer.positional-param-conflict',
+ until: '3.5.0',
+ });
}
named[name] = args.positional.at(i);
| true |
Other
|
emberjs
|
ember.js
|
c7a7bc7665883fa872ebb423bb08c0aea3bf3be8.json
|
Fix remaining contextual component tests.
Issue deprecation when conflicting named and positional params exist
(changed from per-layer assert to post-merge deprecation).
|
packages/ember-glimmer/tests/integration/components/contextual-components-test.js
|
@@ -318,58 +318,57 @@ moduleFor('Components test: contextual components', class extends RenderingTest
this.assertText('Hi Max 9');
}
- ['@test nested components positional parameters are overridden by named parameters']() {
+ ['@test nested components positional parameters override named parameters [DEPRECATED]']() {
this.registerComponent('-looked-up', {
ComponentClass: Component.extend().reopenClass({
positionalParams: ['name', 'age']
}),
template: '{{name}} {{age}}'
});
- this.render('{{component (component (component "-looked-up" "Sergio" 29) name="Marvin" age=21)}}');
+ expectDeprecation(() => {
+ this.render('{{component (component (component "-looked-up" "Sergio" 29) name="Marvin" age=21)}}');
+ }, 'You cannot specify both a positional param (at position 1) and the hash argument `age`.');
- this.assertText('Marvin 21');
+ this.assertText('Sergio 29');
this.runTask(() => this.rerender());
- this.assertText('Marvin 21');
+ this.assertText('Sergio 29');
}
- ['@test nested components with positional params at outer layer are overwriten by hash parameters']() {
+ ['@test nested components with positional params at outer layer are override hash parameters [DEPRECATED]']() {
this.registerComponent('-looked-up', {
ComponentClass: Component.extend().reopenClass({
positionalParams: ['greeting', 'name', 'age']
}),
template: '{{greeting}} {{name}} {{age}}'
});
- this.render(strip`
- {{#with (component "-looked-up" "Hola" "Dolores" 33) as |first|}}
- {{#with (component first greeting="Hej" name="Sigmundur") as |second|}}
- {{component second greeting=model.greeting}}
+ expectDeprecation(() => {
+ this.render(
+ strip`
+ {{#with (component "-looked-up" "Hola" "Dolores" 33) as |first|}}
+ {{#with (component first greeting="Hej" name="Sigmundur") as |second|}}
+ {{component second greeting=model.greeting}}
{{/with}}
- {{/with}}`, {
+ {{/with}}`,
+ {
model: {
greeting: 'Hodi'
}
- });
-
- this.assertText('Hodi Sigmundur 33');
-
- this.runTask(() => this.rerender());
-
- this.assertText('Hodi Sigmundur 33');
-
- this.runTask(() => this.context.set('model.greeting', 'Kaixo'));
+ }
+ );
+ }, 'You cannot specify both a positional param (at position 1) and the hash argument `name`.');
- this.assertText('Kaixo Sigmundur 33');
+ this.assertText('Hola Dolores 33');
- this.runTask(() => this.context.set('model', { greeting: 'Hodi' }));
+ this.runTask(() => this.rerender());
- this.assertText('Hodi Sigmundur 33');
+ this.assertText('Hola Dolores 33');
}
- ['@test nested components with positional params at middle layer are partially overwriten by hash parameters']() {
+ ['@test nested components with positional params at middle layer partially override hash parameters [DEPRECATED]']() {
this.registerComponent('-looked-up', {
ComponentClass: Component.extend().reopenClass({
positionalParams: ['greeting', 'name', 'age']
@@ -378,33 +377,30 @@ moduleFor('Components test: contextual components', class extends RenderingTest
template: '{{greeting}} {{name}} {{age}}'
});
- this.render(strip`
- {{#with (component "-looked-up" greeting="Hola" name="Dolores" age=33) as |first|}}
- {{#with (component first "Hej" "Sigmundur") as |second|}}
- {{component second greeting=model.greeting}}
- {{/with}}
- {{/with}}`, {
- model: {
- greeting: 'Hodi'
- }
- });
+ expectDeprecation(() => {
+ this.render(
+ strip`
+ {{#with (component "-looked-up" greeting="Hola" name="Dolores" age=33) as |first|}}
+ {{#with (component first "Hej" "Sigmundur") as |second|}}
+ {{component second greeting=model.greeting}}
+ {{/with}}
+ {{/with}}`,
+ {
+ model: {
+ greeting: 'Hodi'
+ }
+ }
+ );
+ }, 'You cannot specify both a positional param (at position 0) and the hash argument `greeting`.');
- this.assertText('Hodi Sigmundur 33');
+ this.assertText('Hej Sigmundur 33');
this.runTask(() => this.rerender());
- this.assertText('Hodi Sigmundur 33');
-
- this.runTask(() => this.context.set('model.greeting', 'Kaixo'));
-
- this.assertText('Kaixo Sigmundur 33');
-
- this.runTask(() => this.context.set('model', { greeting: 'Hodi' }));
-
- this.assertText('Hodi Sigmundur 33');
+ this.assertText('Hej Sigmundur 33');
}
- ['@test nested components with positional params at invocation override earlier hash parameters']() {
+ ['@test nested components with positional params at invocation override earlier hash parameters [DEPRECATED]']() {
this.registerComponent('-looked-up', {
ComponentClass: Component.extend().reopenClass({
positionalParams: ['greeting', 'name', 'age']
@@ -413,16 +409,21 @@ moduleFor('Components test: contextual components', class extends RenderingTest
template: '{{greeting}} {{name}} {{age}}'
});
- this.render(strip`
- {{#with (component "-looked-up" greeting="Hola" name="Dolores" age=33) as |first|}}
- {{#with (component first greeting="Hej" name="Sigmundur") as |second|}}
- {{component second model.greeting}}
- {{/with}}
- {{/with}}`, {
- model: {
- greeting: 'Hodi'
- }
- });
+ expectDeprecation(() => {
+ this.render(
+ strip`
+ {{#with (component "-looked-up" greeting="Hola" name="Dolores" age=33) as |first|}}
+ {{#with (component first greeting="Hej" name="Sigmundur") as |second|}}
+ {{component second model.greeting}}
+ {{/with}}
+ {{/with}}`,
+ {
+ model: {
+ greeting: 'Hodi'
+ }
+ }
+ );
+ }, 'You cannot specify both a positional param (at position 0) and the hash argument `greeting`.');
this.assertText('Hodi Sigmundur 33');
@@ -559,32 +560,19 @@ moduleFor('Components test: contextual components', class extends RenderingTest
this.assertText('Inner 28');
}
- ['@test conflicting positional and hash parameters raise an assertion if in the same component context']() {
+ ['@test conflicting positional and hash parameters trigger a deprecation if in the same component context [DEPRECATED]']() {
this.registerComponent('-looked-up', {
ComponentClass: Component.extend().reopenClass({
positionalParams: ['name']
}),
template: '{{greeting}} {{name}}'
});
- expectAssertion(() => {
+ expectDeprecation(() => {
this.render('{{component (component "-looked-up" "Hodari" name="Sergio") "Hodari" greeting="Hodi"}}');
}, 'You cannot specify both a positional param (at position 0) and the hash argument `name`.');
}
- ['@test conflicting positional and hash parameters raise an assertion if in the same component context with prior curried positional params']() {
- this.registerComponent('-looked-up', {
- ComponentClass: Component.extend().reopenClass({
- positionalParams: ['name']
- }),
- template: '{{greeting}} {{name}}'
- });
-
- expectAssertion(() => {
- this.render('{{component (component "-looked-up" "Hodari") "Sergio" name="Hodi"}}');
- }, 'You cannot specify both a positional param (at position 0) and the hash argument `name`.');
- }
-
['@test conflicting positional and hash parameters does not raise an assertion if rerendered']() {
// In some cases, rerendering with a positional param used to cause an
// assertion. This test checks it does not.
@@ -616,21 +604,23 @@ moduleFor('Components test: contextual components', class extends RenderingTest
this.assertText('Hodi Hodari');
}
- ['@test conflicting positional and hash parameters does not raise an assertion if in different component context']() {
+ ['@test conflicting positional and hash parameters trigger a deprecation [DEPRECATED]']() {
this.registerComponent('-looked-up', {
ComponentClass: Component.extend().reopenClass({
positionalParams: ['name']
}),
template: '{{greeting}} {{name}}'
});
- this.render('{{component (component "-looked-up" "Hodari") name="Sergio" greeting="Hodi"}}');
+ expectDeprecation(() => {
+ this.render('{{component (component "-looked-up" "Hodari") name="Sergio" greeting="Hodi"}}');
+ }, 'You cannot specify both a positional param (at position 0) and the hash argument `name`.');
- this.assertText('Hodi Sergio');
+ this.assertText('Hodi Hodari');
this.runTask(() => this.rerender());
- this.assertText('Hodi Sergio');
+ this.assertText('Hodi Hodari');
}
['@skip raises an asserton when component path is null']() {
| true |
Other
|
emberjs
|
ember.js
|
3e005da51f57cf050d36cf919d44fea15525d24f.json
|
remove jquery from ember-testing
|
lib/packages.js
|
@@ -9,7 +9,12 @@ module.exports = function() {
'ember-runtime': { trees: null, vendorRequirements: ['rsvp'], requirements: ['container', 'ember-environment', 'ember-console', 'ember-metal'], requiresJQuery: false },
'ember-views': { trees: null, requirements: ['ember-runtime'], skipTests: true },
'ember-extension-support': { trees: null, requirements: ['ember-application'], requiresJQuery: false },
- 'ember-testing': { trees: null, requirements: ['ember-application', 'ember-routing'], testing: true },
+ 'ember-testing': {
+ trees: null,
+ requiresJQuery: false,
+ requirements: ['ember-application', 'ember-routing'],
+ testing: true
+ },
'ember-template-compiler': {
trees: null,
templateCompilerOnly: true,
| true |
Other
|
emberjs
|
ember.js
|
3e005da51f57cf050d36cf919d44fea15525d24f.json
|
remove jquery from ember-testing
|
packages/ember-testing/lib/events.js
|
@@ -1,25 +1,32 @@
-import { jQuery } from 'ember-views';
import { run } from 'ember-metal';
+import { assign } from 'ember-utils';
+import isFormControl from './helpers/-is-form-control';
const DEFAULT_EVENT_OPTIONS = { canBubble: true, cancelable: true };
const KEYBOARD_EVENT_TYPES = ['keydown', 'keypress', 'keyup'];
const MOUSE_EVENT_TYPES = ['click', 'mousedown', 'mouseup', 'dblclick', 'mouseenter', 'mouseleave', 'mousemove', 'mouseout', 'mouseover'];
export function focus(el) {
if (!el) { return; }
- let $el = jQuery(el);
- if ($el.is(':input, [contenteditable=true]')) {
- let type = $el.prop('type');
+ if (el.isContentEditable || isFormControl(el)) {
+ let type = el.getAttribute('type');
if (type !== 'checkbox' && type !== 'radio' && type !== 'hidden') {
run(null, function() {
- // Firefox does not trigger the `focusin` event if the window
- // does not have focus. If the document doesn't have focus just
- // use trigger('focusin') instead.
+ let browserIsNotFocused = document.hasFocus && !document.hasFocus();
- if (!document.hasFocus || document.hasFocus()) {
- el.focus();
- } else {
- $el.trigger('focusin');
+ // makes `document.activeElement` be `element`. If the browser is focused, it also fires a focus event
+ el.focus();
+
+ // Firefox does not trigger the `focusin` event if the window
+ // does not have focus. If the document does not have focus then
+ // fire `focusin` event as well.
+ if (browserIsNotFocused) {
+ // if the browser is not focused the previous `el.focus()` didn't fire an event, so we simulate it
+ fireEvent(el, 'focus', {
+ bubbles: false,
+ });
+
+ fireEvent(el, 'focusin');
}
});
}
@@ -43,7 +50,7 @@ export function fireEvent(element, type, options = {}) {
clientX: x,
clientY: y
};
- event = buildMouseEvent(type, jQuery.extend(simulatedCoordinates, options));
+ event = buildMouseEvent(type, assign(simulatedCoordinates, options));
} else {
event = buildBasicEvent(type, options);
}
@@ -52,16 +59,24 @@ export function fireEvent(element, type, options = {}) {
function buildBasicEvent(type, options = {}) {
let event = document.createEvent('Events');
- event.initEvent(type, true, true);
- jQuery.extend(event, options);
+
+ // Event.bubbles is read only
+ let bubbles = options.bubbles !== undefined ? options.bubbles : true;
+ let cancelable = options.cancelable !== undefined ? options.cancelable : true;
+
+ delete options.bubbles;
+ delete options.cancelable;
+
+ event.initEvent(type, bubbles, cancelable);
+ assign(event, options);
return event;
}
function buildMouseEvent(type, options = {}) {
let event;
try {
event = document.createEvent('MouseEvents');
- let eventOpts = jQuery.extend({}, DEFAULT_EVENT_OPTIONS, options);
+ let eventOpts = assign({}, DEFAULT_EVENT_OPTIONS, options);
event.initMouseEvent(
type,
eventOpts.canBubble,
@@ -88,7 +103,7 @@ function buildKeyboardEvent(type, options = {}) {
let event;
try {
event = document.createEvent('KeyEvents');
- let eventOpts = jQuery.extend({}, DEFAULT_EVENT_OPTIONS, options);
+ let eventOpts = assign({}, DEFAULT_EVENT_OPTIONS, options);
event.initKeyEvent(
type,
eventOpts.canBubble,
| true |
Other
|
emberjs
|
ember.js
|
3e005da51f57cf050d36cf919d44fea15525d24f.json
|
remove jquery from ember-testing
|
packages/ember-testing/lib/helpers/-is-form-control.js
|
@@ -0,0 +1,16 @@
+const FORM_CONTROL_TAGS = ['INPUT', 'BUTTON', 'SELECT', 'TEXTAREA'];
+
+/**
+ @private
+ @param {Element} element the element to check
+ @returns {boolean} `true` when the element is a form control, `false` otherwise
+*/
+export default function isFormControl(element) {
+ let { tagName, type } = element;
+
+ if (type === 'hidden') {
+ return false;
+ }
+
+ return FORM_CONTROL_TAGS.indexOf(tagName) > -1;
+}
\ No newline at end of file
| true |
Other
|
emberjs
|
ember.js
|
3e005da51f57cf050d36cf919d44fea15525d24f.json
|
remove jquery from ember-testing
|
packages/ember-testing/lib/helpers/fill_in.js
|
@@ -2,6 +2,7 @@
@module ember
*/
import { focus, fireEvent } from '../events';
+import isFormControl from './-is-form-control';
/**
Fills in an input element with some text.
@@ -32,7 +33,12 @@ export default function fillIn(app, selector, contextOrText, text) {
el = $el[0];
focus(el);
- $el.eq(0).val(text);
+ if (isFormControl(el)) {
+ el.value = text;
+ } else {
+ el.innerHTML = text;
+ }
+
fireEvent(el, 'input');
fireEvent(el, 'change');
| true |
Other
|
emberjs
|
ember.js
|
3e005da51f57cf050d36cf919d44fea15525d24f.json
|
remove jquery from ember-testing
|
packages/ember-testing/lib/helpers/find.js
|
@@ -2,6 +2,8 @@
@module ember
*/
import { get } from 'ember-metal';
+import { assert } from 'ember-debug';
+import { jQueryDisabled } from 'ember-views';
/**
Finds an element in the context of the app's container element. A simple alias
@@ -20,13 +22,16 @@ import { get } from 'ember-metal';
```
@method find
- @param {String} selector jQuery string selector for element lookup
+ @param {String} selector jQuery selector for element lookup
@param {String} [context] (optional) jQuery selector that will limit the selector
argument to find only within the context's children
- @return {Object} jQuery object representing the results of the query
+ @return {Object} DOM element representing the results of the query
@public
*/
export default function find(app, selector, context) {
+ if (jQueryDisabled) {
+ assert('If jQuery is disabled, please import and use helpers from @ember/test-helpers [https://github.com/emberjs/ember-test-helpers]. Note: `find` is not an available helper.');
+ }
let $el;
context = context || get(app, 'rootElement');
$el = app.$(selector, context);
| true |
Other
|
emberjs
|
ember.js
|
3e005da51f57cf050d36cf919d44fea15525d24f.json
|
remove jquery from ember-testing
|
packages/ember-testing/lib/helpers/find_with_assert.js
|
@@ -22,7 +22,7 @@
@param {String} [context] (optional) jQuery selector that will limit the
selector argument to find only within the context's children
@return {Object} jQuery object representing the results of the query
- @throws {Error} throws error if jQuery object returned has a length of 0
+ @throws {Error} throws error if object returned has a length of 0
@public
*/
export default function findWithAssert(app, selector, context) {
| true |
Other
|
emberjs
|
ember.js
|
3e005da51f57cf050d36cf919d44fea15525d24f.json
|
remove jquery from ember-testing
|
packages/ember-testing/lib/setup_for_testing.js
|
@@ -1,7 +1,6 @@
/* global self */
import { setTesting } from 'ember-debug';
-import { jQuery } from 'ember-views';
import {
getAdapter,
setAdapter
@@ -35,13 +34,11 @@ export default function setupForTesting() {
setAdapter((typeof self.QUnit === 'undefined') ? new Adapter() : new QUnitAdapter());
}
- if (jQuery) {
- jQuery(document).off('ajaxSend', incrementPendingRequests);
- jQuery(document).off('ajaxComplete', decrementPendingRequests);
+ document.removeEventListener('ajaxSend', incrementPendingRequests);
+ document.removeEventListener('ajaxComplete', decrementPendingRequests);
- clearPendingRequests();
+ clearPendingRequests();
- jQuery(document).on('ajaxSend', incrementPendingRequests);
- jQuery(document).on('ajaxComplete', decrementPendingRequests);
- }
+ document.addEventListener('ajaxSend', incrementPendingRequests);
+ document.addEventListener('ajaxComplete', decrementPendingRequests);
}
| true |
Other
|
emberjs
|
ember.js
|
3e005da51f57cf050d36cf919d44fea15525d24f.json
|
remove jquery from ember-testing
|
packages/ember-testing/lib/support.js
|
@@ -43,7 +43,7 @@ if (environment.hasDOM && !jQueryDisabled) {
$.event.special.click = {
// For checkbox, fire native event so checked state will be right
trigger() {
- if ($.nodeName(this, 'input') && this.type === 'checkbox' && this.click) {
+ if (this.nodeName === 'INPUT' && this.type === 'checkbox' && this.click) {
this.click();
return false;
}
| true |
Other
|
emberjs
|
ember.js
|
3e005da51f57cf050d36cf919d44fea15525d24f.json
|
remove jquery from ember-testing
|
packages/ember-testing/lib/test/pending_requests.js
|
@@ -8,11 +8,13 @@ export function clearPendingRequests() {
requests.length = 0;
}
-export function incrementPendingRequests(_, xhr) {
+export function incrementPendingRequests({ detail } = { detail: { xhr: null }}) {
+ let xhr = detail.xhr;
requests.push(xhr);
}
-export function decrementPendingRequests(_, xhr) {
+export function decrementPendingRequests({ detail } = { detail: { xhr: null }}) {
+ let xhr = detail.xhr;
for (let i = 0; i < requests.length; i++) {
if (xhr === requests[i]) {
requests.splice(i, 1);
| true |
Other
|
emberjs
|
ember.js
|
3e005da51f57cf050d36cf919d44fea15525d24f.json
|
remove jquery from ember-testing
|
packages/ember-testing/tests/acceptance_test.js
|
@@ -8,382 +8,385 @@ import Test from '../test';
import QUnitAdapter from '../adapters/qunit';
import { Route } from 'ember-routing';
import { RSVP } from 'ember-runtime';
+import { jQueryDisabled } from 'ember-views';
-moduleFor('ember-testing Acceptance', class extends AutobootApplicationTestCase {
- constructor() {
- super();
- this._originalAdapter = Test.adapter;
+if (!jQueryDisabled) {
+ moduleFor('ember-testing Acceptance', class extends AutobootApplicationTestCase {
+ constructor() {
+ super();
+ this._originalAdapter = Test.adapter;
- this.runTask(() => {
- this.createApplication();
- this.router.map(function() {
- this.route('posts');
- this.route('comments');
+ this.runTask(() => {
+ this.createApplication();
+ this.router.map(function() {
+ this.route('posts');
+ this.route('comments');
- this.route('abort_transition');
+ this.route('abort_transition');
- this.route('redirect');
- });
+ this.route('redirect');
+ });
- this.indexHitCount = 0;
- this.currentRoute = 'index';
- let testContext = this;
+ this.indexHitCount = 0;
+ this.currentRoute = 'index';
+ let testContext = this;
+
+ this.add('route:index', Route.extend({
+ model() {
+ testContext.indexHitCount += 1;
+ }
+ }));
+
+ this.add('route:posts', Route.extend({
+ renderTemplate() {
+ testContext.currentRoute = 'posts';
+ this._super(...arguments);
+ }
+ }));
+
+ this.addTemplate('posts', `
+ <div class="posts-view">
+ <a class="dummy-link"></a>
+ <div id="comments-link">
+ {{#link-to \'comments\'}}Comments{{/link-to}}
+ </div>
+ </div>
+ `);
- this.add('route:index', Route.extend({
- model() {
- testContext.indexHitCount += 1;
- }
- }));
+ this.add('route:comments', Route.extend({
+ renderTemplate() {
+ testContext.currentRoute = 'comments';
+ this._super(...arguments);
+ }
+ }));
- this.add('route:posts', Route.extend({
- renderTemplate() {
- testContext.currentRoute = 'posts';
- this._super(...arguments);
- }
- }));
+ this.addTemplate('comments', `<div>{{input type="text"}}</div>`);
- this.addTemplate('posts', `
- <div class="posts-view">
- <a class="dummy-link"></a>
- <div id="comments-link">
- {{#link-to \'comments\'}}Comments{{/link-to}}
- </div>
- </div>
- `);
+ this.add('route:abort_transition', Route.extend({
+ beforeModel(transition) {
+ transition.abort();
+ }
+ }));
- this.add('route:comments', Route.extend({
- renderTemplate() {
- testContext.currentRoute = 'comments';
- this._super(...arguments);
- }
- }));
+ this.add('route:redirect', Route.extend({
+ beforeModel() {
+ this.transitionTo('comments');
+ }
+ }));
- this.addTemplate('comments', `<div>{{input type="text"}}</div>`);
+ this.application.setupForTesting();
- this.add('route:abort_transition', Route.extend({
- beforeModel(transition) {
- transition.abort();
- }
- }));
+ Test.registerAsyncHelper('slowHelper', () => {
+ return new RSVP.Promise(resolve => run.later(resolve, 10));
+ });
- this.add('route:redirect', Route.extend({
- beforeModel() {
- this.transitionTo('comments');
- }
- }));
+ this.application.injectTestHelpers();
+ });
+ }
- this.application.setupForTesting();
+ teardown() {
+ Test.adapter = this._originalAdapter;
+ super.teardown();
+ }
- Test.registerAsyncHelper('slowHelper', () => {
- return new RSVP.Promise(resolve => run.later(resolve, 10));
+ [`@test helpers can be chained with then`](assert) {
+ assert.expect(6);
+
+ window.visit('/posts').then(() => {
+ assert.equal(this.currentRoute, 'posts', 'Successfully visited posts route');
+ assert.equal(window.currentURL(), '/posts', 'posts URL is correct');
+ return window.click('a:contains("Comments")');
+ }).then(() => {
+ assert.equal(this.currentRoute, 'comments', 'visit chained with click');
+ return window.fillIn('.ember-text-field', 'yeah');
+ }).then(() => {
+ assert.equal(document.querySelector('.ember-text-field').value, 'yeah', 'chained with fillIn');
+ return window.fillIn('.ember-text-field', '#qunit-fixture', 'context working');
+ }).then(() => {
+ assert.equal(document.querySelector('.ember-text-field').value, 'context working', 'chained with fillIn');
+ return window.click('.does-not-exist');
+ }).catch(e => {
+ assert.equal(e.message, 'Element .does-not-exist not found.', 'Non-existent click exception caught');
});
+ }
- this.application.injectTestHelpers();
- });
- }
-
- teardown() {
- Test.adapter = this._originalAdapter;
- super.teardown();
- }
-
- [`@test helpers can be chained with then`](assert) {
- assert.expect(6);
-
- window.visit('/posts').then(() => {
- assert.equal(this.currentRoute, 'posts', 'Successfully visited posts route');
- assert.equal(window.currentURL(), '/posts', 'posts URL is correct');
- return window.click('a:contains("Comments")');
- }).then(() => {
- assert.equal(this.currentRoute, 'comments', 'visit chained with click');
- return window.fillIn('.ember-text-field', 'yeah');
- }).then(() => {
- assert.equal(this.$('.ember-text-field').val(), 'yeah', 'chained with fillIn');
- return window.fillIn('.ember-text-field', '#qunit-fixture', 'context working');
- }).then(() => {
- assert.equal(this.$('.ember-text-field').val(), 'context working', 'chained with fillIn');
- return window.click('.does-not-exist');
- }).catch(e => {
- assert.equal(e.message, 'Element .does-not-exist not found.', 'Non-existent click exception caught');
- });
- }
-
- [`@test helpers can be chained to each other (legacy)`](assert) {
- assert.expect(7);
-
- window.visit('/posts')
- .click('a:first', '#comments-link')
- .fillIn('.ember-text-field', 'hello')
- .then(() => {
- assert.equal(this.currentRoute, 'comments', 'Successfully visited comments route');
- assert.equal(window.currentURL(), '/comments', 'Comments URL is correct');
- assert.equal(this.$('.ember-text-field').val(), 'hello', 'Fillin successfully works');
- window.find('.ember-text-field').one('keypress', e => {
- assert.equal(e.keyCode, 13, 'keyevent chained with correct keyCode.');
- assert.equal(e.which, 13, 'keyevent chained with correct which.');
+ [`@test helpers can be chained to each other (legacy)`](assert) {
+ assert.expect(7);
+
+ window.visit('/posts')
+ .click('a:first', '#comments-link')
+ .fillIn('.ember-text-field', 'hello')
+ .then(() => {
+ assert.equal(this.currentRoute, 'comments', 'Successfully visited comments route');
+ assert.equal(window.currentURL(), '/comments', 'Comments URL is correct');
+ assert.equal(document.querySelector('.ember-text-field').value, 'hello', 'Fillin successfully works');
+ window.find('.ember-text-field').one('keypress', e => {
+ assert.equal(e.keyCode, 13, 'keyevent chained with correct keyCode.');
+ assert.equal(e.which, 13, 'keyevent chained with correct which.');
+ });
+ })
+ .keyEvent('.ember-text-field', 'keypress', 13)
+ .visit('/posts')
+ .then(() => {
+ assert.equal(this.currentRoute, 'posts', 'Thens can also be chained to helpers');
+ assert.equal(window.currentURL(), '/posts', 'URL is set correct on chained helpers');
});
- })
- .keyEvent('.ember-text-field', 'keypress', 13)
- .visit('/posts')
- .then(() => {
- assert.equal(this.currentRoute, 'posts', 'Thens can also be chained to helpers');
- assert.equal(window.currentURL(), '/posts', 'URL is set correct on chained helpers');
- });
- }
+ }
- [`@test helpers don't need to be chained`](assert) {
- assert.expect(5);
+ [`@test helpers don't need to be chained`](assert) {
+ assert.expect(5);
- window.visit('/posts');
+ window.visit('/posts');
- window.click('a:first', '#comments-link');
+ window.click('a:first', '#comments-link');
- window.fillIn('.ember-text-field', 'hello');
+ window.fillIn('.ember-text-field', 'hello');
- window.andThen(() => {
- assert.equal(this.currentRoute, 'comments', 'Successfully visited comments route');
- assert.equal(window.currentURL(), '/comments', 'Comments URL is correct');
- assert.equal(window.find('.ember-text-field').val(), 'hello', 'Fillin successfully works');
- });
+ window.andThen(() => {
+ assert.equal(this.currentRoute, 'comments', 'Successfully visited comments route');
+ assert.equal(window.currentURL(), '/comments', 'Comments URL is correct');
+ assert.equal(window.find('.ember-text-field').val(), 'hello', 'Fillin successfully works');
+ });
- window.visit('/posts');
+ window.visit('/posts');
- window.andThen(() => {
- assert.equal(this.currentRoute, 'posts');
- assert.equal(window.currentURL(), '/posts');
- });
- }
+ window.andThen(() => {
+ assert.equal(this.currentRoute, 'posts');
+ assert.equal(window.currentURL(), '/posts');
+ });
+ }
- [`@test Nested async helpers`](assert) {
- assert.expect(5);
+ [`@test Nested async helpers`](assert) {
+ assert.expect(5);
- window.visit('/posts');
+ window.visit('/posts');
- window.andThen(() => {
- window.click('a:first', '#comments-link');
- window.fillIn('.ember-text-field', 'hello');
- });
+ window.andThen(() => {
+ window.click('a:first', '#comments-link');
+ window.fillIn('.ember-text-field', 'hello');
+ });
- window.andThen(() => {
- assert.equal(this.currentRoute, 'comments', 'Successfully visited comments route');
- assert.equal(window.currentURL(), '/comments', 'Comments URL is correct');
- assert.equal(window.find('.ember-text-field').val(), 'hello', 'Fillin successfully works');
- });
+ window.andThen(() => {
+ assert.equal(this.currentRoute, 'comments', 'Successfully visited comments route');
+ assert.equal(window.currentURL(), '/comments', 'Comments URL is correct');
+ assert.equal(window.find('.ember-text-field').val(), 'hello', 'Fillin successfully works');
+ });
- window.visit('/posts');
+ window.visit('/posts');
- window.andThen(() => {
- assert.equal(this.currentRoute, 'posts');
- assert.equal(window.currentURL(), '/posts');
- });
- }
+ window.andThen(() => {
+ assert.equal(this.currentRoute, 'posts');
+ assert.equal(window.currentURL(), '/posts');
+ });
+ }
- [`@test Multiple nested async helpers`](assert) {
- assert.expect(3);
+ [`@test Multiple nested async helpers`](assert) {
+ assert.expect(3);
- window.visit('/posts');
+ window.visit('/posts');
- window.andThen(() => {
- window.click('a:first', '#comments-link');
+ window.andThen(() => {
+ window.click('a:first', '#comments-link');
- window.fillIn('.ember-text-field', 'hello');
- window.fillIn('.ember-text-field', 'goodbye');
- });
+ window.fillIn('.ember-text-field', 'hello');
+ window.fillIn('.ember-text-field', 'goodbye');
+ });
- window.andThen(() => {
- assert.equal(window.find('.ember-text-field').val(), 'goodbye', 'Fillin successfully works');
- assert.equal(this.currentRoute, 'comments', 'Successfully visited comments route');
- assert.equal(window.currentURL(), '/comments', 'Comments URL is correct');
- });
- }
+ window.andThen(() => {
+ assert.equal(window.find('.ember-text-field').val(), 'goodbye', 'Fillin successfully works');
+ assert.equal(this.currentRoute, 'comments', 'Successfully visited comments route');
+ assert.equal(window.currentURL(), '/comments', 'Comments URL is correct');
+ });
+ }
- [`@test Helpers nested in thens`](assert) {
- assert.expect(5);
+ [`@test Helpers nested in thens`](assert) {
+ assert.expect(5);
- window.visit('/posts').then(() => {
- window.click('a:first', '#comments-link');
- });
+ window.visit('/posts').then(() => {
+ window.click('a:first', '#comments-link');
+ });
- window.andThen(() => {
- window.fillIn('.ember-text-field', 'hello');
- });
+ window.andThen(() => {
+ window.fillIn('.ember-text-field', 'hello');
+ });
- window.andThen(() => {
- assert.equal(this.currentRoute, 'comments', 'Successfully visited comments route');
- assert.equal(window.currentURL(), '/comments', 'Comments URL is correct');
- assert.equal(window.find('.ember-text-field').val(), 'hello', 'Fillin successfully works');
- });
+ window.andThen(() => {
+ assert.equal(this.currentRoute, 'comments', 'Successfully visited comments route');
+ assert.equal(window.currentURL(), '/comments', 'Comments URL is correct');
+ assert.equal(window.find('.ember-text-field').val(), 'hello', 'Fillin successfully works');
+ });
- window.visit('/posts');
+ window.visit('/posts');
- window.andThen(() => {
- assert.equal(this.currentRoute, 'posts');
- assert.equal(window.currentURL(), '/posts', 'Posts URL is correct');
- });
- }
+ window.andThen(() => {
+ assert.equal(this.currentRoute, 'posts');
+ assert.equal(window.currentURL(), '/posts', 'Posts URL is correct');
+ });
+ }
- [`@test Aborted transitions are not logged via Ember.Test.adapter#exception`](assert) {
- assert.expect(0);
+ [`@test Aborted transitions are not logged via Ember.Test.adapter#exception`](assert) {
+ assert.expect(0);
- Test.adapter = QUnitAdapter.create({
- exception() {
- assert.ok(false, 'aborted transitions are not logged');
- }
- });
+ Test.adapter = QUnitAdapter.create({
+ exception() {
+ assert.ok(false, 'aborted transitions are not logged');
+ }
+ });
+
+ window.visit('/abort_transition');
+ }
- window.visit('/abort_transition');
- }
+ [`@test Unhandled exceptions are logged via Ember.Test.adapter#exception`](assert) {
+ assert.expect(2);
+
+ let asyncHandled;
+ Test.adapter = QUnitAdapter.create({
+ exception(error) {
+ assert.equal(
+ error.message, 'Element .does-not-exist not found.',
+ 'Exception successfully caught and passed to Ember.Test.adapter.exception'
+ );
+ // handle the rejection so it doesn't leak later.
+ asyncHandled.catch(() => { });
+ }
+ });
- [`@test Unhandled exceptions are logged via Ember.Test.adapter#exception`](assert) {
- assert.expect(2);
+ window.visit('/posts');
- let asyncHandled;
- Test.adapter = QUnitAdapter.create({
- exception(error) {
+ window.click('.invalid-element').catch(error => {
assert.equal(
- error.message, 'Element .does-not-exist not found.',
- 'Exception successfully caught and passed to Ember.Test.adapter.exception'
+ error.message, 'Element .invalid-element not found.',
+ 'Exception successfully handled in the rejection handler'
);
- // handle the rejection so it doesn't leak later.
- asyncHandled.catch(() => { });
- }
- });
-
- window.visit('/posts');
-
- window.click('.invalid-element').catch(error => {
- assert.equal(
- error.message, 'Element .invalid-element not found.',
- 'Exception successfully handled in the rejection handler'
- );
- });
+ });
- asyncHandled = window.click('.does-not-exist');
- }
+ asyncHandled = window.click('.does-not-exist');
+ }
- [`@test Unhandled exceptions in 'andThen' are logged via Ember.Test.adapter#exception`](assert) {
- assert.expect(1);
+ [`@test Unhandled exceptions in 'andThen' are logged via Ember.Test.adapter#exception`](assert) {
+ assert.expect(1);
- Test.adapter = QUnitAdapter.create({
- exception(error) {
- assert.equal(
- error.message, 'Catch me',
- 'Exception successfully caught and passed to Ember.Test.adapter.exception'
- );
- }
- });
+ Test.adapter = QUnitAdapter.create({
+ exception(error) {
+ assert.equal(
+ error.message, 'Catch me',
+ 'Exception successfully caught and passed to Ember.Test.adapter.exception'
+ );
+ }
+ });
- window.visit('/posts');
+ window.visit('/posts');
- window.andThen(() => {
- throw new Error('Catch me');
- });
- }
+ window.andThen(() => {
+ throw new Error('Catch me');
+ });
+ }
- [`@test should not start routing on the root URL when visiting another`](assert) {
- assert.expect(4);
+ [`@test should not start routing on the root URL when visiting another`](assert) {
+ assert.expect(4);
- window.visit('/posts');
+ window.visit('/posts');
- window.andThen(() => {
- assert.ok(window.find('#comments-link'), 'found comments-link');
- assert.equal(this.currentRoute, 'posts', 'Successfully visited posts route');
- assert.equal(window.currentURL(), '/posts', 'Posts URL is correct');
- assert.equal(this.indexHitCount, 0, 'should not hit index route when visiting another route');
- });
- }
+ window.andThen(() => {
+ assert.ok(window.find('#comments-link'), 'found comments-link');
+ assert.equal(this.currentRoute, 'posts', 'Successfully visited posts route');
+ assert.equal(window.currentURL(), '/posts', 'Posts URL is correct');
+ assert.equal(this.indexHitCount, 0, 'should not hit index route when visiting another route');
+ });
+ }
- [`@test only enters the index route once when visiting `](assert) {
- assert.expect(1);
+ [`@test only enters the index route once when visiting `](assert) {
+ assert.expect(1);
- window.visit('/');
+ window.visit('/');
- window.andThen(() => {
- assert.equal(this.indexHitCount, 1, 'should hit index once when visiting /');
- });
- }
+ window.andThen(() => {
+ assert.equal(this.indexHitCount, 1, 'should hit index once when visiting /');
+ });
+ }
- [`@test test must not finish while asyncHelpers are pending`](assert) {
- assert.expect(2);
+ [`@test test must not finish while asyncHelpers are pending`](assert) {
+ assert.expect(2);
- let async = 0;
- let innerRan = false;
+ let async = 0;
+ let innerRan = false;
- Test.adapter = QUnitAdapter.extend({
- asyncStart() {
- async++;
- this._super();
- },
- asyncEnd() {
- async--;
- this._super();
- }
- }).create();
+ Test.adapter = QUnitAdapter.extend({
+ asyncStart() {
+ async++;
+ this._super();
+ },
+ asyncEnd() {
+ async--;
+ this._super();
+ }
+ }).create();
- this.application.testHelpers.slowHelper();
+ this.application.testHelpers.slowHelper();
- window.andThen(() => {
- innerRan = true;
- });
+ window.andThen(() => {
+ innerRan = true;
+ });
- assert.equal(innerRan, false, 'should not have run yet');
- assert.ok(async > 0, 'should have told the adapter to pause');
+ assert.equal(innerRan, false, 'should not have run yet');
+ assert.ok(async > 0, 'should have told the adapter to pause');
- if (async === 0) {
- // If we failed the test, prevent zalgo from escaping and breaking
- // our other tests.
- Test.adapter.asyncStart();
- Test.resolve().then(() => {
- Test.adapter.asyncEnd();
- });
+ if (async === 0) {
+ // If we failed the test, prevent zalgo from escaping and breaking
+ // our other tests.
+ Test.adapter.asyncStart();
+ Test.resolve().then(() => {
+ Test.adapter.asyncEnd();
+ });
+ }
}
- }
- [`@test visiting a URL that causes another transition should yield the correct URL`](assert) {
- assert.expect(1);
+ [`@test visiting a URL that causes another transition should yield the correct URL`](assert) {
+ assert.expect(1);
- window.visit('/redirect');
+ window.visit('/redirect');
- window.andThen(() => {
- assert.equal(window.currentURL(), '/comments', 'Redirected to Comments URL');
- });
- }
+ window.andThen(() => {
+ assert.equal(window.currentURL(), '/comments', 'Redirected to Comments URL');
+ });
+ }
- [`@test visiting a URL and then visiting a second URL with a transition should yield the correct URL`](assert) {
- assert.expect(2);
+ [`@test visiting a URL and then visiting a second URL with a transition should yield the correct URL`](assert) {
+ assert.expect(2);
- window.visit('/posts');
+ window.visit('/posts');
- window.andThen(function () {
- assert.equal(window.currentURL(), '/posts', 'First visited URL is correct');
- });
+ window.andThen(function () {
+ assert.equal(window.currentURL(), '/posts', 'First visited URL is correct');
+ });
- window.visit('/redirect');
+ window.visit('/redirect');
- window.andThen(() => {
- assert.equal(window.currentURL(), '/comments', 'Redirected to Comments URL');
- });
- }
+ window.andThen(() => {
+ assert.equal(window.currentURL(), '/comments', 'Redirected to Comments URL');
+ });
+ }
-});
+ });
-moduleFor('ember-testing Acceptance - teardown', class extends AutobootApplicationTestCase {
+ moduleFor('ember-testing Acceptance - teardown', class extends AutobootApplicationTestCase {
- [`@test that the setup/teardown happens correctly`](assert) {
- assert.expect(2);
+ [`@test that the setup/teardown happens correctly`](assert) {
+ assert.expect(2);
- this.runTask(() => {
- this.createApplication();
- });
- this.application.injectTestHelpers();
+ this.runTask(() => {
+ this.createApplication();
+ });
+ this.application.injectTestHelpers();
- assert.ok(typeof Test.Promise.prototype.click === 'function');
+ assert.ok(typeof Test.Promise.prototype.click === 'function');
- this.runTask(() => {
- this.application.destroy();
- });
+ this.runTask(() => {
+ this.application.destroy();
+ });
- assert.equal(Test.Promise.prototype.click, undefined);
- }
+ assert.equal(Test.Promise.prototype.click, undefined);
+ }
-});
+ });
+}
\ No newline at end of file
| true |
Other
|
emberjs
|
ember.js
|
3e005da51f57cf050d36cf919d44fea15525d24f.json
|
remove jquery from ember-testing
|
packages/ember-testing/tests/helpers_test.js
|
@@ -9,18 +9,19 @@ import {
RSVP
} from 'ember-runtime';
import { run } from 'ember-metal';
-import { jQuery } from 'ember-views';
import {
Component,
} from 'ember-glimmer';
+import { jQueryDisabled } from 'ember-views';
import Test from '../test';
import setupForTesting from '../setup_for_testing';
import {
pendingRequests,
incrementPendingRequests,
- clearPendingRequests
+ decrementPendingRequests,
+ clearPendingRequests,
} from '../test/pending_requests';
import {
setAdapter,
@@ -35,6 +36,12 @@ function registerHelper() {
Test.registerHelper('LeakyMcLeakLeak', () => {});
}
+function customEvent(name, xhr) {
+ let event = document.createEvent('CustomEvent');
+ event.initCustomEvent(name, true, true, { xhr });
+ document.dispatchEvent(event);
+}
+
function assertHelpers(assert, application, helperContainer, expected) {
if (!helperContainer) { helperContainer = window; }
if (expected === undefined) { expected = true; }
@@ -74,8 +81,8 @@ class HelpersTestCase extends AutobootApplicationTestCase {
teardown() {
setAdapter(this._originalAdapter);
- jQuery(document).off('ajaxSend');
- jQuery(document).off('ajaxComplete');
+ document.removeEventListener('ajaxSend', incrementPendingRequests);
+ document.removeEventListener('ajaxComplete', decrementPendingRequests);
clearPendingRequests();
if (this.application) {
this.application.removeTestHelpers();
@@ -96,1168 +103,1133 @@ class HelpersApplicationTestCase extends HelpersTestCase {
}
}
-moduleFor('ember-testing: Helper setup', class extends HelpersTestCase {
-
- [`@test Ember.Application#injectTestHelpers/#removeTestHelper`](assert) {
- this.runTask(() => {
- this.createApplication();
- });
+if (!jQueryDisabled) {
+ moduleFor('ember-testing: Helper setup', class extends HelpersTestCase {
- assertNoHelpers(assert, this.application);
+ [`@test Ember.Application#injectTestHelpers/#removeTestHelper`](assert) {
+ this.runTask(() => {
+ this.createApplication();
+ });
- registerHelper();
+ assertNoHelpers(assert, this.application);
- this.application.injectTestHelpers();
+ registerHelper();
- assertHelpers(assert, this.application);
+ this.application.injectTestHelpers();
- assert.ok(
- Test.Promise.prototype.LeakyMcLeakLeak,
- 'helper in question SHOULD be present'
- );
+ assertHelpers(assert, this.application);
- this.application.removeTestHelpers();
+ assert.ok(
+ Test.Promise.prototype.LeakyMcLeakLeak,
+ 'helper in question SHOULD be present'
+ );
- assertNoHelpers(assert, this.application);
+ this.application.removeTestHelpers();
- assert.equal(
- Test.Promise.prototype.LeakyMcLeakLeak, undefined,
- 'should NOT leak test promise extensions'
- );
- }
+ assertNoHelpers(assert, this.application);
- [`@test Ember.Application#setupForTesting`](assert) {
- this.runTask(() => {
- this.createApplication();
- this.application.setupForTesting();
- });
+ assert.equal(
+ Test.Promise.prototype.LeakyMcLeakLeak, undefined,
+ 'should NOT leak test promise extensions'
+ );
+ }
- let routerInstance = this.applicationInstance.lookup('router:main');
- assert.equal(routerInstance.location, 'none');
- }
+ [`@test Ember.Application#setupForTesting`](assert) {
+ this.runTask(() => {
+ this.createApplication();
+ this.application.setupForTesting();
+ });
- [`@test Ember.Application.setupForTesting sets the application to 'testing'`](assert) {
- this.runTask(() => {
- this.createApplication();
- this.application.setupForTesting();
- });
+ let routerInstance = this.applicationInstance.lookup('router:main');
+ assert.equal(routerInstance.location, 'none');
+ }
- assert.equal(
- this.application.testing, true,
- 'Application instance is set to testing.'
- );
- }
+ [`@test Ember.Application.setupForTesting sets the application to 'testing'`](assert) {
+ this.runTask(() => {
+ this.createApplication();
+ this.application.setupForTesting();
+ });
- [`@test Ember.Application.setupForTesting leaves the system in a deferred state.`](assert) {
- this.runTask(() => {
- this.createApplication();
- this.application.setupForTesting();
- });
+ assert.equal(
+ this.application.testing, true,
+ 'Application instance is set to testing.'
+ );
+ }
- assert.equal(
- this.application._readinessDeferrals, 1,
- 'App is in deferred state after setupForTesting.'
- );
- }
+ [`@test Ember.Application.setupForTesting leaves the system in a deferred state.`](assert) {
+ this.runTask(() => {
+ this.createApplication();
+ this.application.setupForTesting();
+ });
- [`@test App.reset() after Application.setupForTesting leaves the system in a deferred state.`](assert) {
- this.runTask(() => {
- this.createApplication();
- this.application.setupForTesting();
- });
+ assert.equal(
+ this.application._readinessDeferrals, 1,
+ 'App is in deferred state after setupForTesting.'
+ );
+ }
- assert.equal(
- this.application._readinessDeferrals, 1,
- 'App is in deferred state after setupForTesting.'
- );
+ [`@test App.reset() after Application.setupForTesting leaves the system in a deferred state.`](assert) {
+ this.runTask(() => {
+ this.createApplication();
+ this.application.setupForTesting();
+ });
- this.application.reset();
+ assert.equal(
+ this.application._readinessDeferrals, 1,
+ 'App is in deferred state after setupForTesting.'
+ );
- assert.equal(
- this.application._readinessDeferrals, 1,
- 'App is in deferred state after setupForTesting.'
- );
- }
+ this.application.reset();
- [`@test #setupForTesting attaches ajax listeners`](assert) {
- let documentEvents = jQuery._data(document, 'events') || {};
+ assert.equal(
+ this.application._readinessDeferrals, 1,
+ 'App is in deferred state after setupForTesting.'
+ );
+ }
- assert.ok(
- documentEvents['ajaxSend'] === undefined,
- 'there are no ajaxSend listers setup prior to calling injectTestHelpers'
- );
- assert.ok(
- documentEvents['ajaxComplete'] === undefined,
- 'there are no ajaxComplete listers setup prior to calling injectTestHelpers'
- );
+ [`@test Ember.Application#injectTestHelpers calls callbacks registered with onInjectHelpers`](assert) {
+ let injected = 0;
- setupForTesting();
+ Test.onInjectHelpers(() => {
+ injected++;
+ });
- documentEvents = jQuery._data(document, 'events');
+ this.runTask(() => {
+ this.createApplication();
+ this.application.setupForTesting();
+ });
- assert.equal(
- documentEvents['ajaxSend'].length, 1,
- 'calling injectTestHelpers registers an ajaxSend handler'
- );
- assert.equal(
- documentEvents['ajaxComplete'].length, 1,
- 'calling injectTestHelpers registers an ajaxComplete handler'
- );
- }
+ assert.equal(
+ injected, 0,
+ 'onInjectHelpers are not called before injectTestHelpers'
+ );
- [`@test #setupForTesting attaches ajax listeners only once`](assert) {
- let documentEvents = jQuery._data(document, 'events') || {};
+ this.application.injectTestHelpers();
- assert.ok(
- documentEvents['ajaxSend'] === undefined,
- 'there are no ajaxSend listeners setup prior to calling injectTestHelpers'
- );
- assert.ok(
- documentEvents['ajaxComplete'] === undefined,
- 'there are no ajaxComplete listeners setup prior to calling injectTestHelpers'
- );
+ assert.equal(
+ injected, 1,
+ 'onInjectHelpers are called after injectTestHelpers'
+ );
+ }
- setupForTesting();
- setupForTesting();
+ [`@test Ember.Application#injectTestHelpers adds helpers to provided object.`](assert) {
+ let helpers = {};
- documentEvents = jQuery._data(document, 'events');
+ this.runTask(() => {
+ this.createApplication();
+ this.application.setupForTesting();
+ });
- assert.equal(
- documentEvents['ajaxSend'].length, 1,
- 'calling injectTestHelpers registers an ajaxSend handler'
- );
- assert.equal(
- documentEvents['ajaxComplete'].length, 1,
- 'calling injectTestHelpers registers an ajaxComplete handler'
- );
- }
+ this.application.injectTestHelpers(helpers);
- [`@test Ember.Application#injectTestHelpers calls callbacks registered with onInjectHelpers`](assert) {
- let injected = 0;
+ assertHelpers(assert, this.application, helpers);
- Test.onInjectHelpers(() => {
- injected++;
- });
+ this.application.removeTestHelpers();
- this.runTask(() => {
- this.createApplication();
- this.application.setupForTesting();
- });
+ assertNoHelpers(assert, this.application, helpers);
+ }
- assert.equal(
- injected, 0,
- 'onInjectHelpers are not called before injectTestHelpers'
- );
+ [`@test Ember.Application#removeTestHelpers resets the helperContainer\'s original values`](assert) {
+ let helpers = { visit: 'snazzleflabber' };
- this.application.injectTestHelpers();
+ this.runTask(() => {
+ this.createApplication();
+ this.application.setupForTesting();
+ });
- assert.equal(
- injected, 1,
- 'onInjectHelpers are called after injectTestHelpers'
- );
- }
+ this.application.injectTestHelpers(helpers);
- [`@test Ember.Application#injectTestHelpers adds helpers to provided object.`](assert) {
- let helpers = {};
+ assert.notEqual(
+ helpers.visit, 'snazzleflabber',
+ 'helper added to container'
+ );
+ this.application.removeTestHelpers();
- this.runTask(() => {
- this.createApplication();
- this.application.setupForTesting();
- });
+ assert.equal(
+ helpers.visit, 'snazzleflabber',
+ 'original value added back to container'
+ );
+ }
- this.application.injectTestHelpers(helpers);
+ });
- assertHelpers(assert, this.application, helpers);
+ moduleFor('ember-testing: Helper methods', class extends HelpersApplicationTestCase {
- this.application.removeTestHelpers();
+ [`@test 'wait' respects registerWaiters`](assert) {
+ assert.expect(3);
- assertNoHelpers(assert, this.application, helpers);
- }
+ let counter = 0;
+ function waiter() {
+ return ++counter > 2;
+ }
- [`@test Ember.Application#removeTestHelpers resets the helperContainer\'s original values`](assert) {
- let helpers = { visit: 'snazzleflabber' };
+ let other = 0;
+ function otherWaiter() {
+ return ++other > 2;
+ }
- this.runTask(() => {
- this.createApplication();
- this.application.setupForTesting();
- });
+ this.runTask(() => {
+ this.application.advanceReadiness();
+ });
- this.application.injectTestHelpers(helpers);
+ registerWaiter(waiter);
+ registerWaiter(otherWaiter);
- assert.notEqual(
- helpers.visit, 'snazzleflabber',
- 'helper added to container'
- );
- this.application.removeTestHelpers();
+ let {application: {testHelpers}} = this;
+ return testHelpers.wait().then(() => {
+ assert.equal(
+ waiter(), true,
+ 'should not resolve until our waiter is ready'
+ );
+ unregisterWaiter(waiter);
+ counter = 0;
+ return testHelpers.wait();
+ }).then(() => {
+ assert.equal(
+ counter, 0,
+ 'unregistered waiter was not checked'
+ );
+ assert.equal(
+ otherWaiter(), true,
+ 'other waiter is still registered'
+ );
+ }).finally(() => {
+ unregisterWaiter(otherWaiter);
+ });
+ }
- assert.equal(
- helpers.visit, 'snazzleflabber',
- 'original value added back to container'
- );
- }
+ [`@test 'visit' advances readiness.`](assert) {
+ assert.expect(2);
-});
+ assert.equal(
+ this.application._readinessDeferrals, 1,
+ 'App is in deferred state after setupForTesting.'
+ );
-moduleFor('ember-testing: Helper methods', class extends HelpersApplicationTestCase {
+ return this.application.testHelpers.visit('/').then(() => {
+ assert.equal(
+ this.application._readinessDeferrals, 0,
+ `App's readiness was advanced by visit.`
+ );
+ });
+ }
- [`@test 'wait' respects registerWaiters`](assert) {
- assert.expect(3);
+ [`@test 'wait' helper can be passed a resolution value`](assert) {
+ assert.expect(4);
- let counter = 0;
- function waiter() {
- return ++counter > 2;
- }
+ this.runTask(() => {
+ this.application.advanceReadiness();
+ });
- let other = 0;
- function otherWaiter() {
- return ++other > 2;
+ let promiseObjectValue = {};
+ let objectValue = {};
+ let {application: {testHelpers}} = this;
+ return testHelpers.wait('text').then(val => {
+ assert.equal(
+ val, 'text',
+ 'can resolve to a string'
+ );
+ return testHelpers.wait(1);
+ }).then(val => {
+ assert.equal(
+ val, 1,
+ 'can resolve to an integer'
+ );
+ return testHelpers.wait(objectValue);
+ }).then(val => {
+ assert.equal(
+ val, objectValue,
+ 'can resolve to an object'
+ );
+ return testHelpers.wait(RSVP.resolve(promiseObjectValue));
+ }).then(val => {
+ assert.equal(
+ val, promiseObjectValue,
+ 'can resolve to a promise resolution value'
+ );
+ });
}
- this.runTask(() => {
- this.application.advanceReadiness();
- });
+ [`@test 'click' triggers appropriate events in order`](assert) {
+ assert.expect(5);
- registerWaiter(waiter);
- registerWaiter(otherWaiter);
+ this.add('component:index-wrapper', Component.extend({
+ classNames: 'index-wrapper',
- let {application: {testHelpers}} = this;
- return testHelpers.wait().then(() => {
- assert.equal(
- waiter(), true,
- 'should not resolve until our waiter is ready'
- );
- unregisterWaiter(waiter);
- counter = 0;
- return testHelpers.wait();
- }).then(() => {
- assert.equal(
- counter, 0,
- 'unregistered waiter was not checked'
- );
- assert.equal(
- otherWaiter(), true,
- 'other waiter is still registered'
- );
- }).finally(() => {
- unregisterWaiter(otherWaiter);
- });
- }
+ didInsertElement() {
+ let wrapper = document.querySelector('.index-wrapper');
+ wrapper.addEventListener('mousedown', e => events.push(e.type));
+ wrapper.addEventListener('mouseup', e => events.push(e.type));
+ wrapper.addEventListener('click', e => events.push(e.type));
+ wrapper.addEventListener('focusin', e => events.push(e.type));
+ }
+ }));
- [`@test 'visit' advances readiness.`](assert) {
- assert.expect(2);
+ this.add('component:x-checkbox', Component.extend({
+ tagName: 'input',
+ attributeBindings: ['type'],
+ type: 'checkbox',
+ click() {
+ events.push('click:' + this.get('checked'));
+ },
+ change() {
+ events.push('change:' + this.get('checked'));
+ }
+ }));
- assert.equal(
- this.application._readinessDeferrals, 1,
- 'App is in deferred state after setupForTesting.'
- );
+ this.addTemplate('index', `
+ {{#index-wrapper}}
+ {{input type="text"}}
+ {{x-checkbox type="checkbox"}}
+ {{textarea}}
+ <div contenteditable="true"> </div>
+ {{/index-wrapper}}'));
+ `);
+
+ this.runTask(() => {
+ this.application.advanceReadiness();
+ });
- return this.application.testHelpers.visit('/').then(() => {
- assert.equal(
- this.application._readinessDeferrals, 0,
- `App's readiness was advanced by visit.`
- );
- });
- }
+ let events;
+ let {application: {testHelpers}} = this;
+ return testHelpers.wait().then(() => {
+ events = [];
+ return testHelpers.click('.index-wrapper');
+ }).then(() => {
+ assert.deepEqual(
+ events, ['mousedown', 'mouseup', 'click'],
+ 'fires events in order'
+ );
+ }).then(() => {
+ events = [];
+ return testHelpers.click('.index-wrapper input[type=text]');
+ }).then(() => {
+ assert.deepEqual(
+ events, ['mousedown', 'focusin', 'mouseup', 'click'],
+ 'fires focus events on inputs'
+ );
+ }).then(() => {
+ events = [];
+ return testHelpers.click('.index-wrapper textarea');
+ }).then(() => {
+ assert.deepEqual(
+ events, ['mousedown', 'focusin', 'mouseup', 'click'],
+ 'fires focus events on textareas'
+ );
+ }).then(() => {
+ events = [];
+ return testHelpers.click('.index-wrapper div');
+ }).then(() => {
+ assert.deepEqual(
+ events, ['mousedown', 'focusin', 'mouseup', 'click'],
+ 'fires focus events on contenteditable'
+ );
+ }).then(() => {
+ events = [];
+ return testHelpers.click('.index-wrapper input[type=checkbox]');
+ }).then(() => {
+ // i.e. mousedown, mouseup, change:true, click, click:true
+ // Firefox differs so we can't assert the exact ordering here.
+ // See https://bugzilla.mozilla.org/show_bug.cgi?id=843554.
+ assert.equal(
+ events.length, 5,
+ 'fires click and change on checkboxes'
+ );
+ });
+ }
- [`@test 'wait' helper can be passed a resolution value`](assert) {
- assert.expect(4);
+ [`@test 'click' triggers native events with simulated X/Y coordinates`](assert) {
+ assert.expect(15);
- this.runTask(() => {
- this.application.advanceReadiness();
- });
+ this.add('component:index-wrapper', Component.extend({
+ classNames: 'index-wrapper',
- let promiseObjectValue = {};
- let objectValue = {};
- let {application: {testHelpers}} = this;
- return testHelpers.wait('text').then(val => {
- assert.equal(
- val, 'text',
- 'can resolve to a string'
- );
- return testHelpers.wait(1);
- }).then(val => {
- assert.equal(
- val, 1,
- 'can resolve to an integer'
- );
- return testHelpers.wait(objectValue);
- }).then(val => {
- assert.equal(
- val, objectValue,
- 'can resolve to an object'
- );
- return testHelpers.wait(RSVP.resolve(promiseObjectValue));
- }).then(val => {
- assert.equal(
- val, promiseObjectValue,
- 'can resolve to a promise resolution value'
- );
- });
- }
+ didInsertElement() {
+ let pushEvent = e => events.push(e);
+ this.element.addEventListener('mousedown', pushEvent);
+ this.element.addEventListener('mouseup', pushEvent);
+ this.element.addEventListener('click', pushEvent);
+ }
+ }));
- [`@test 'click' triggers appropriate events in order`](assert) {
- assert.expect(5);
+ this.addTemplate('index', `
+ {{#index-wrapper}}some text{{/index-wrapper}}
+ `);
- this.add('component:index-wrapper', Component.extend({
- classNames: 'index-wrapper',
+ this.runTask(() => {
+ this.application.advanceReadiness();
+ });
- didInsertElement() {
- this.$().on('mousedown focusin mouseup click', e => {
- events.push(e.type);
+ let events;
+ let {application: {testHelpers: {wait, click}}} = this;
+ return wait().then(() => {
+ events = [];
+ return click('.index-wrapper');
+ }).then(() => {
+ events.forEach(e => {
+ assert.ok(
+ e instanceof window.Event,
+ 'The event is an instance of MouseEvent'
+ );
+ assert.ok(
+ typeof e.screenX === 'number',
+ 'screenX is correct'
+ );
+ assert.ok(
+ typeof e.screenY === 'number',
+ 'screenY is correct'
+ );
+ assert.ok(
+ typeof e.clientX === 'number',
+ 'clientX is correct'
+ );
+ assert.ok(
+ typeof e.clientY === 'number',
+ 'clientY is correct'
+ );
});
- }
- }));
-
- this.add('component:x-checkbox', Component.extend({
- tagName: 'input',
- attributeBindings: ['type'],
- type: 'checkbox',
- click() {
- events.push('click:' + this.get('checked'));
- },
- change() {
- events.push('change:' + this.get('checked'));
- }
- }));
-
- this.addTemplate('index', `
- {{#index-wrapper}}
- {{input type="text"}}
- {{x-checkbox type="checkbox"}}
- {{textarea}}
- <div contenteditable="true"> </div>
- {{/index-wrapper}}'));
- `);
-
- this.runTask(() => {
- this.application.advanceReadiness();
- });
-
- let events;
- let {application: {testHelpers}} = this;
- return testHelpers.wait().then(() => {
- events = [];
- return testHelpers.click('.index-wrapper');
- }).then(() => {
- assert.deepEqual(
- events, ['mousedown', 'mouseup', 'click'],
- 'fires events in order'
- );
- }).then(() => {
- events = [];
- return testHelpers.click('.index-wrapper input[type=text]');
- }).then(() => {
- assert.deepEqual(
- events, ['mousedown', 'focusin', 'mouseup', 'click'],
- 'fires focus events on inputs'
- );
- }).then(() => {
- events = [];
- return testHelpers.click('.index-wrapper textarea');
- }).then(() => {
- assert.deepEqual(
- events, ['mousedown', 'focusin', 'mouseup', 'click'],
- 'fires focus events on textareas'
- );
- }).then(() => {
- events = [];
- return testHelpers.click('.index-wrapper div');
- }).then(() => {
- assert.deepEqual(
- events, ['mousedown', 'focusin', 'mouseup', 'click'],
- 'fires focus events on contenteditable'
- );
- }).then(() => {
- events = [];
- return testHelpers.click('.index-wrapper input[type=checkbox]');
- }).then(() => {
- // i.e. mousedown, mouseup, change:true, click, click:true
- // Firefox differs so we can't assert the exact ordering here.
- // See https://bugzilla.mozilla.org/show_bug.cgi?id=843554.
- assert.equal(
- events.length, 5,
- 'fires click and change on checkboxes'
- );
- });
- }
-
- [`@test 'click' triggers native events with simulated X/Y coordinates`](assert) {
- assert.expect(15);
+ });
+ }
- this.add('component:index-wrapper', Component.extend({
- classNames: 'index-wrapper',
+ [`@test 'triggerEvent' with mouseenter triggers native events with simulated X/Y coordinates`](assert) {
+ assert.expect(5);
- didInsertElement() {
- let pushEvent = e => events.push(e);
- this.element.addEventListener('mousedown', pushEvent);
- this.element.addEventListener('mouseup', pushEvent);
- this.element.addEventListener('click', pushEvent);
- }
- }));
+ let evt;
+ this.add('component:index-wrapper', Component.extend({
+ classNames: 'index-wrapper',
+ didInsertElement() {
+ this.element.addEventListener('mouseenter', e => evt = e);
+ }
+ }));
- this.addTemplate('index', `
- {{#index-wrapper}}some text{{/index-wrapper}}
- `);
+ this.addTemplate('index', `{{#index-wrapper}}some text{{/index-wrapper}}`);
- this.runTask(() => {
- this.application.advanceReadiness();
- });
+ this.runTask(() => {
+ this.application.advanceReadiness();
+ });
- let events;
- let {application: {testHelpers: {wait, click}}} = this;
- return wait().then(() => {
- events = [];
- return click('.index-wrapper');
- }).then(() => {
- events.forEach(e => {
+ let {application: {testHelpers: {wait, triggerEvent}}} = this;
+ return wait().then(() => {
+ return triggerEvent('.index-wrapper', 'mouseenter');
+ }).then(() => {
assert.ok(
- e instanceof window.Event,
+ evt instanceof window.Event,
'The event is an instance of MouseEvent'
);
assert.ok(
- typeof e.screenX === 'number',
+ typeof evt.screenX === 'number',
'screenX is correct'
);
assert.ok(
- typeof e.screenY === 'number',
+ typeof evt.screenY === 'number',
'screenY is correct'
);
assert.ok(
- typeof e.clientX === 'number',
+ typeof evt.clientX === 'number',
'clientX is correct'
);
assert.ok(
- typeof e.clientY === 'number',
+ typeof evt.clientY === 'number',
'clientY is correct'
);
});
- });
- }
+ }
- [`@test 'triggerEvent' with mouseenter triggers native events with simulated X/Y coordinates`](assert) {
- assert.expect(5);
+ [`@test 'wait' waits for outstanding timers`](assert) {
+ assert.expect(1);
- let evt;
- this.add('component:index-wrapper', Component.extend({
- classNames: 'index-wrapper',
- didInsertElement() {
- this.element.addEventListener('mouseenter', e => evt = e);
- }
- }));
+ this.runTask(() => {
+ this.application.advanceReadiness();
+ });
- this.addTemplate('index', `{{#index-wrapper}}some text{{/index-wrapper}}`);
+ let waitDone = false;
+ run.later(() => {
+ waitDone = true;
+ }, 20);
- this.runTask(() => {
- this.application.advanceReadiness();
- });
+ return this.application.testHelpers.wait().then(() => {
+ assert.equal(waitDone, true, 'should wait for the timer to be fired.');
+ });
+ }
- let {application: {testHelpers: {wait, triggerEvent}}} = this;
- return wait().then(() => {
- return triggerEvent('.index-wrapper', 'mouseenter');
- }).then(() => {
- assert.ok(
- evt instanceof window.Event,
- 'The event is an instance of MouseEvent'
- );
- assert.ok(
- typeof evt.screenX === 'number',
- 'screenX is correct'
- );
- assert.ok(
- typeof evt.screenY === 'number',
- 'screenY is correct'
- );
- assert.ok(
- typeof evt.clientX === 'number',
- 'clientX is correct'
- );
- assert.ok(
- typeof evt.clientY === 'number',
- 'clientY is correct'
- );
- });
- }
+ [`@test 'wait' respects registerWaiters with optional context`](assert) {
+ assert.expect(3);
- [`@test 'wait' waits for outstanding timers`](assert) {
- assert.expect(1);
+ let obj = {
+ counter: 0,
+ ready() {
+ return ++this.counter > 2;
+ }
+ };
- this.runTask(() => {
- this.application.advanceReadiness();
- });
+ let other = 0;
+ function otherWaiter() {
+ return ++other > 2;
+ }
- let waitDone = false;
- run.later(() => {
- waitDone = true;
- }, 20);
+ this.runTask(() => {
+ this.application.advanceReadiness();
+ });
- return this.application.testHelpers.wait().then(() => {
- assert.equal(waitDone, true, 'should wait for the timer to be fired.');
- });
- }
+ registerWaiter(obj, obj.ready);
+ registerWaiter(otherWaiter);
- [`@test 'wait' respects registerWaiters with optional context`](assert) {
- assert.expect(3);
+ let {application: {testHelpers: {wait}}} = this;
+ return wait().then(() => {
+ assert.equal(
+ obj.ready(), true,
+ 'should not resolve until our waiter is ready'
+ );
+ unregisterWaiter(obj, obj.ready);
+ obj.counter = 0;
+ return wait();
+ }).then(() => {
+ assert.equal(
+ obj.counter, 0,
+ 'the unregistered waiter should still be at 0'
+ );
+ assert.equal(
+ otherWaiter(), true,
+ 'other waiter should still be registered'
+ );
+ }).finally(() => {
+ unregisterWaiter(otherWaiter);
+ });
+ }
- let obj = {
- counter: 0,
- ready() {
- return ++this.counter > 2;
- }
- };
+ [`@test 'wait' does not error if routing has not begun`](assert) {
+ assert.expect(1);
- let other = 0;
- function otherWaiter() {
- return ++other > 2;
+ return this.application.testHelpers.wait().then(() => {
+ assert.ok(true, 'should not error without `visit`');
+ });
}
- this.runTask(() => {
- this.application.advanceReadiness();
- });
+ [`@test 'triggerEvent' accepts an optional options hash without context`](assert) {
+ assert.expect(3);
- registerWaiter(obj, obj.ready);
- registerWaiter(otherWaiter);
+ let event;
+ this.add('component:index-wrapper', Component.extend({
+ didInsertElement() {
+ let domElem = document.querySelector('.input');
+ domElem.addEventListener('change', e => event = e);
+ domElem.addEventListener('keydown', e => event = e);
+ }
+ }));
- let {application: {testHelpers: {wait}}} = this;
- return wait().then(() => {
- assert.equal(
- obj.ready(), true,
- 'should not resolve until our waiter is ready'
- );
- unregisterWaiter(obj, obj.ready);
- obj.counter = 0;
- return wait();
- }).then(() => {
- assert.equal(
- obj.counter, 0,
- 'the unregistered waiter should still be at 0'
- );
- assert.equal(
- otherWaiter(), true,
- 'other waiter should still be registered'
- );
- }).finally(() => {
- unregisterWaiter(otherWaiter);
- });
- }
+ this.addTemplate('index', `{{index-wrapper}}`);
+ this.addTemplate('components/index-wrapper', `
+ {{input type="text" id="scope" class="input"}}
+ `);
- [`@test 'wait' does not error if routing has not begun`](assert) {
- assert.expect(1);
+ this.runTask(() => {
+ this.application.advanceReadiness();
+ });
- return this.application.testHelpers.wait().then(() => {
- assert.ok(true, 'should not error without `visit`');
- });
- }
+ let {application: {testHelpers: {wait, triggerEvent}}} = this;
+ return wait().then(() => {
+ return triggerEvent('.input', 'keydown', { keyCode: 13 });
+ }).then(() => {
+ assert.equal(event.keyCode, 13, 'options were passed');
+ assert.equal(event.type, 'keydown', 'correct event was triggered');
+ assert.equal(event.target.getAttribute('id'), 'scope', 'triggered on the correct element');
+ });
+ }
- [`@test 'triggerEvent' accepts an optional options hash without context`](assert) {
- assert.expect(3);
+ [`@test 'triggerEvent' can limit searching for a selector to a scope`](assert) {
+ assert.expect(2);
+
+ let event;
+ this.add('component:index-wrapper', Component.extend({
+ didInsertElement() {
+ let firstInput = document.querySelector('.input');
+ firstInput.addEventListener('blur', e => event = e);
+ firstInput.addEventListener('change', e => event = e);
+ let secondInput = document.querySelector('#limited .input');
+ secondInput.addEventListener('blur', e => event = e);
+ secondInput.addEventListener('change', e => event = e);
+ }
+ }));
- let event;
- this.add('component:index-wrapper', Component.extend({
- didInsertElement() {
- this.$('.input').on('keydown change', e => event = e);
- }
- }));
+ this.addTemplate('components/index-wrapper', `
+ {{input type="text" id="outside-scope" class="input"}}
+ <div id="limited">
+ {{input type="text" id="inside-scope" class="input"}}
+ </div>
+ `);
+ this.addTemplate('index', `{{index-wrapper}}`);
- this.addTemplate('index', `{{index-wrapper}}`);
- this.addTemplate('components/index-wrapper', `
- {{input type="text" id="scope" class="input"}}
- `);
+ this.runTask(() => {
+ this.application.advanceReadiness();
+ });
- this.runTask(() => {
- this.application.advanceReadiness();
- });
-
- let {application: {testHelpers: {wait, triggerEvent}}} = this;
- return wait().then(() => {
- return triggerEvent('.input', 'keydown', { keyCode: 13 });
- }).then(() => {
- assert.equal(event.keyCode, 13, 'options were passed');
- assert.equal(event.type, 'keydown', 'correct event was triggered');
- assert.equal(event.target.getAttribute('id'), 'scope', 'triggered on the correct element');
- });
- }
+ let {application: {testHelpers: {wait, triggerEvent}}} = this;
+ return wait().then(() => {
+ return triggerEvent('.input', '#limited', 'blur');
+ }).then(() => {
+ assert.equal(
+ event.type, 'blur',
+ 'correct event was triggered'
+ );
+ assert.equal(
+ event.target.getAttribute('id'), 'inside-scope',
+ 'triggered on the correct element'
+ );
+ });
+ }
- [`@test 'triggerEvent' can limit searching for a selector to a scope`](assert) {
- assert.expect(2);
+ [`@test 'triggerEvent' can be used to trigger arbitrary events`](assert) {
+ assert.expect(2);
- let event;
- this.add('component:index-wrapper', Component.extend({
- didInsertElement() {
- this.$('.input').on('blur change', e => event = e);
- }
- }));
+ let event;
+ this.add('component:index-wrapper', Component.extend({
+ didInsertElement() {
+ let foo = document.getElementById('foo');
+ foo.addEventListener('blur', e => event = e);
+ foo.addEventListener('change', e => event = e);
+ }
+ }));
- this.addTemplate('components/index-wrapper', `
- {{input type="text" id="outside-scope" class="input"}}
- <div id="limited">
- {{input type="text" id="inside-scope" class="input"}}
- </div>
- `);
- this.addTemplate('index', `{{index-wrapper}}`);
+ this.addTemplate('components/index-wrapper', `
+ {{input type="text" id="foo"}}
+ `);
+ this.addTemplate('index', `{{index-wrapper}}`);
- this.runTask(() => {
- this.application.advanceReadiness();
- });
+ this.runTask(() => {
+ this.application.advanceReadiness();
+ });
- let {application: {testHelpers: {wait, triggerEvent}}} = this;
- return wait().then(() => {
- return triggerEvent('.input', '#limited', 'blur');
- }).then(() => {
- assert.equal(
- event.type, 'blur',
- 'correct event was triggered'
- );
- assert.equal(
- event.target.getAttribute('id'), 'inside-scope',
- 'triggered on the correct element'
- );
- });
- }
+ let {application: {testHelpers: {wait, triggerEvent}}} = this;
+ return wait().then(() => {
+ return triggerEvent('#foo', 'blur');
+ }).then(() => {
+ assert.equal(
+ event.type, 'blur',
+ 'correct event was triggered'
+ );
+ assert.equal(
+ event.target.getAttribute('id'), 'foo',
+ 'triggered on the correct element'
+ );
+ });
+ }
- [`@test 'triggerEvent' can be used to trigger arbitrary events`](assert) {
- assert.expect(2);
+ [`@test 'fillIn' takes context into consideration`](assert) {
+ assert.expect(2);
- let event;
- this.add('component:index-wrapper', Component.extend({
- didInsertElement() {
- this.$('#foo').on('blur change', e => event = e);
- }
- }));
+ this.addTemplate('index', `
+ <div id="parent">
+ {{input type="text" id="first" class="current"}}
+ </div>
+ {{input type="text" id="second" class="current"}}
+ `);
- this.addTemplate('components/index-wrapper', `
- {{input type="text" id="foo"}}
- `);
- this.addTemplate('index', `{{index-wrapper}}`);
+ this.runTask(() => {
+ this.application.advanceReadiness();
+ });
- this.runTask(() => {
- this.application.advanceReadiness();
- });
+ let {application: {testHelpers: {visit, fillIn, andThen, find}}} = this;
+ visit('/');
+ fillIn('.current', '#parent', 'current value');
- let {application: {testHelpers: {wait, triggerEvent}}} = this;
- return wait().then(() => {
- return triggerEvent('#foo', 'blur');
- }).then(() => {
- assert.equal(
- event.type, 'blur',
- 'correct event was triggered'
- );
- assert.equal(
- event.target.getAttribute('id'), 'foo',
- 'triggered on the correct element'
- );
- });
- }
+ return andThen(() => {
+ assert.equal(find('#first')[0].value, 'current value');
+ assert.equal(find('#second')[0].value, '');
+ });
+ }
- [`@test 'fillIn' takes context into consideration`](assert) {
- assert.expect(2);
+ [`@test 'fillIn' focuses on the element`](assert) {
+ assert.expect(2);
- this.addTemplate('index', `
- <div id="parent">
- {{input type="text" id="first" class="current"}}
- </div>
- {{input type="text" id="second" class="current"}}
- `);
+ this.add('route:application', Route.extend({
+ actions: {
+ wasFocused() {
+ assert.ok(true, 'focusIn event was triggered');
+ }
+ }
+ }));
- this.runTask(() => {
- this.application.advanceReadiness();
- });
+ this.addTemplate('index', `
+ <div id="parent">
+ {{input type="text" id="first" focus-in="wasFocused"}}
+ </div>'
+ `);
- let {application: {testHelpers: {visit, fillIn, andThen, find}}} = this;
- visit('/');
- fillIn('.current', '#parent', 'current value');
+ this.runTask(() => {
+ this.application.advanceReadiness();
+ });
- return andThen(() => {
- assert.equal(find('#first').val(), 'current value');
- assert.equal(find('#second').val(), '');
- });
- }
+ let {application: {testHelpers: {visit, fillIn, andThen, find, wait}}} = this;
+ visit('/');
+ fillIn('#first', 'current value');
+ andThen(() => {
+ assert.equal(
+ find('#first')[0].value,'current value'
+ );
+ });
- [`@test 'fillIn' focuses on the element`](assert) {
- assert.expect(2);
+ return wait();
+ }
- this.add('route:application', Route.extend({
- actions: {
- wasFocused() {
- assert.ok(true, 'focusIn event was triggered');
+ [`@test 'fillIn' fires 'input' and 'change' events in the proper order`](assert) {
+ assert.expect(1);
+
+ let events = [];
+ this.add('controller:index', Controller.extend({
+ actions: {
+ oninputHandler(e) {
+ events.push(e.type);
+ },
+ onchangeHandler(e) {
+ events.push(e.type);
+ }
}
- }
- }));
-
- this.addTemplate('index', `
- <div id="parent">
- {{input type="text" id="first" focus-in="wasFocused"}}
- </div>'
- `);
-
- this.runTask(() => {
- this.application.advanceReadiness();
- });
+ }));
- let {application: {testHelpers: {visit, fillIn, andThen, find, wait}}} = this;
- visit('/');
- fillIn('#first', 'current value');
- andThen(() => {
- assert.equal(
- find('#first').val(),'current value'
- );
- });
+ this.addTemplate('index', `
+ <input type="text" id="first"
+ oninput={{action "oninputHandler"}}
+ onchange={{action "onchangeHandler"}}>
+ `);
- return wait();
- }
+ this.runTask(() => {
+ this.application.advanceReadiness();
+ });
- [`@test 'fillIn' fires 'input' and 'change' events in the proper order`](assert) {
- assert.expect(1);
+ let {application: {testHelpers: {visit, fillIn, andThen, wait}}} = this;
- let events = [];
- this.add('controller:index', Controller.extend({
- actions: {
- oninputHandler(e) {
- events.push(e.type);
- },
- onchangeHandler(e) {
- events.push(e.type);
- }
- }
- }));
+ visit('/');
+ fillIn('#first', 'current value');
+ andThen(() => {
+ assert.deepEqual(events, ['input', 'change'], '`input` and `change` events are fired in the proper order');
+ });
- this.addTemplate('index', `
- <input type="text" id="first"
- oninput={{action "oninputHandler"}}
- onchange={{action "onchangeHandler"}}>
- `);
+ return wait();
+ }
- this.runTask(() => {
- this.application.advanceReadiness();
- });
+ [`@test 'fillIn' only sets the value in the first matched element`](assert) {
+ this.addTemplate('index', `
+ <input type="text" id="first" class="in-test">
+ <input type="text" id="second" class="in-test">
+ `);
- let {application: {testHelpers: {visit, fillIn, andThen, wait}}} = this;
+ this.runTask(() => {
+ this.application.advanceReadiness();
+ });
- visit('/');
- fillIn('#first', 'current value');
- andThen(() => {
- assert.deepEqual(events, ['input', 'change'], '`input` and `change` events are fired in the proper order');
- });
+ let {application: {testHelpers: {visit, fillIn, find, andThen, wait}}} = this;
- return wait();
- }
+ visit('/');
+ fillIn('input.in-test', 'new value');
+ andThen(() => {
+ assert.equal(
+ find('#first')[0].value, 'new value'
+ );
+ assert.equal(
+ find('#second')[0].value, ''
+ );
+ });
- [`@test 'fillIn' only sets the value in the first matched element`](assert) {
- this.addTemplate('index', `
- <input type="text" id="first" class="in-test">
- <input type="text" id="second" class="in-test">
- `);
+ return wait();
+ }
- this.runTask(() => {
- this.application.advanceReadiness();
- });
+ [`@test 'triggerEvent' accepts an optional options hash and context`](assert) {
+ assert.expect(3);
+
+ let event;
+ this.add('component:index-wrapper', Component.extend({
+ didInsertElement() {
+ let firstInput = document.querySelector('.input');
+ firstInput.addEventListener('keydown', e => event = e, false);
+ firstInput.addEventListener('change', e => event = e, false);
+ let secondInput = document.querySelector('#limited .input');
+ secondInput.addEventListener('keydown', e => event = e, false);
+ secondInput.addEventListener('change', e => event = e, false);
+ }
+ }));
- let {application: {testHelpers: {visit, fillIn, find, andThen, wait}}} = this;
+ this.addTemplate('components/index-wrapper', `
+ {{input type="text" id="outside-scope" class="input"}}
+ <div id="limited">
+ {{input type="text" id="inside-scope" class="input"}}
+ </div>
+ `);
+ this.addTemplate('index', `{{index-wrapper}}`);
- visit('/');
- fillIn('input.in-test', 'new value');
- andThen(() => {
- assert.equal(
- find('#first').val(), 'new value'
- );
- assert.equal(
- find('#second').val(), ''
- );
- });
+ this.runTask(() => {
+ this.application.advanceReadiness();
+ });
- return wait();
- }
+ let {application: {testHelpers: {wait, triggerEvent}}} = this;
+ return wait().then(() => {
+ return triggerEvent('.input', '#limited', 'keydown', { keyCode: 13 });
+ }).then(() => {
+ assert.equal(event.keyCode, 13, 'options were passed');
+ assert.equal(event.type, 'keydown', 'correct event was triggered');
+ assert.equal(event.target.getAttribute('id'), 'inside-scope', 'triggered on the correct element');
+ });
+ }
- [`@test 'triggerEvent' accepts an optional options hash and context`](assert) {
- assert.expect(3);
+ });
- let event;
- this.add('component:index-wrapper', Component.extend({
- didInsertElement() {
- this.$('.input').on('keydown change', e => event = e);
- }
- }));
+ moduleFor('ember-testing: debugging helpers', class extends HelpersApplicationTestCase {
- this.addTemplate('components/index-wrapper', `
- {{input type="text" id="outside-scope" class="input"}}
- <div id="limited">
- {{input type="text" id="inside-scope" class="input"}}
- </div>
- `);
- this.addTemplate('index', `{{index-wrapper}}`);
+ constructor() {
+ super();
+ this.runTask(() => {
+ this.application.advanceReadiness();
+ });
+ }
- this.runTask(() => {
- this.application.advanceReadiness();
- });
+ [`@test pauseTest pauses`](assert) {
+ assert.expect(1);
+
+ let {application: {testHelpers: {andThen, pauseTest}}} = this;
+ andThen(() => {
+ Test.adapter.asyncStart = () => {
+ assert.ok(
+ true,
+ 'Async start should be called after waiting for other helpers'
+ );
+ };
+ });
- let {application: {testHelpers: {wait, triggerEvent}}} = this;
- return wait().then(() => {
- return triggerEvent('.input', '#limited', 'keydown', { keyCode: 13 });
- }).then(() => {
- assert.equal(event.keyCode, 13, 'options were passed');
- assert.equal(event.type, 'keydown', 'correct event was triggered');
- assert.equal(event.target.getAttribute('id'), 'inside-scope', 'triggered on the correct element');
- });
- }
+ pauseTest();
+ }
-});
+ [`@test resumeTest resumes paused tests`](assert) {
+ assert.expect(1);
-moduleFor('ember-testing: debugging helpers', class extends HelpersApplicationTestCase {
+ let {application: {testHelpers: {pauseTest, resumeTest}}} = this;
- constructor() {
- super();
- this.runTask(() => {
- this.application.advanceReadiness();
- });
- }
+ run.later(() => resumeTest(), 20);
+ return pauseTest().then(() => {
+ assert.ok(true, 'pauseTest promise was resolved');
+ });
+ }
- [`@test pauseTest pauses`](assert) {
- assert.expect(1);
+ [`@test resumeTest throws if nothing to resume`](assert) {
+ assert.expect(1);
- let {application: {testHelpers: {andThen, pauseTest}}} = this;
- andThen(() => {
- Test.adapter.asyncStart = () => {
- assert.ok(
- true,
- 'Async start should be called after waiting for other helpers'
- );
- };
- });
+ assert.throws(() => {
+ this.application.testHelpers.resumeTest();
+ }, /Testing has not been paused. There is nothing to resume./);
+ }
- pauseTest();
- }
+ });
+
+ moduleFor('ember-testing: routing helpers', class extends HelpersTestCase {
+
+ constructor() {
+ super();
+ this.runTask(() => {
+ this.createApplication();
+ this.application.setupForTesting();
+ this.application.injectTestHelpers();
+ this.router.map(function() {
+ this.route('posts', {resetNamespace: true}, function() {
+ this.route('new');
+ this.route('edit', { resetNamespace: true });
+ });
+ });
+ });
+ this.runTask(() => {
+ this.application.advanceReadiness();
+ });
+ }
- [`@test resumeTest resumes paused tests`](assert) {
- assert.expect(1);
+ [`@test currentRouteName for '/'`](assert) {
+ assert.expect(3);
- let {application: {testHelpers: {pauseTest, resumeTest}}} = this;
+ let {application: {testHelpers}} = this;
+ return testHelpers.visit('/').then(() => {
+ assert.equal(
+ testHelpers.currentRouteName(), 'index',
+ `should equal 'index'.`
+ );
+ assert.equal(
+ testHelpers.currentPath(), 'index',
+ `should equal 'index'.`
+ );
+ assert.equal(
+ testHelpers.currentURL(), '/',
+ `should equal '/'.`
+ );
+ });
+ }
- run.later(() => resumeTest(), 20);
- return pauseTest().then(() => {
- assert.ok(true, 'pauseTest promise was resolved');
- });
- }
+ [`@test currentRouteName for '/posts'`](assert) {
+ assert.expect(3);
- [`@test resumeTest throws if nothing to resume`](assert) {
- assert.expect(1);
+ let {application: {testHelpers}} = this;
+ return testHelpers.visit('/posts').then(() => {
+ assert.equal(
+ testHelpers.currentRouteName(), 'posts.index',
+ `should equal 'posts.index'.`
+ );
+ assert.equal(
+ testHelpers.currentPath(), 'posts.index',
+ `should equal 'posts.index'.`
+ );
+ assert.equal(
+ testHelpers.currentURL(), '/posts',
+ `should equal '/posts'.`
+ );
+ });
+ }
- assert.throws(() => {
- this.application.testHelpers.resumeTest();
- }, /Testing has not been paused. There is nothing to resume./);
- }
+ [`@test currentRouteName for '/posts/new'`](assert) {
+ assert.expect(3);
-});
+ let {application: {testHelpers}} = this;
+ return testHelpers.visit('/posts/new').then(() => {
+ assert.equal(
+ testHelpers.currentRouteName(), 'posts.new',
+ `should equal 'posts.new'.`
+ );
+ assert.equal(
+ testHelpers.currentPath(), 'posts.new',
+ `should equal 'posts.new'.`
+ );
+ assert.equal(
+ testHelpers.currentURL(), '/posts/new',
+ `should equal '/posts/new'.`
+ );
+ });
+ }
-moduleFor('ember-testing: routing helpers', class extends HelpersTestCase {
+ [`@test currentRouteName for '/posts/edit'`](assert) {
+ assert.expect(3);
- constructor() {
- super();
- this.runTask(() => {
- this.createApplication();
- this.application.setupForTesting();
- this.application.injectTestHelpers();
- this.router.map(function() {
- this.route('posts', {resetNamespace: true}, function() {
- this.route('new');
- this.route('edit', { resetNamespace: true });
- });
+ let {application: {testHelpers}} = this;
+ return testHelpers.visit('/posts/edit').then(() => {
+ assert.equal(
+ testHelpers.currentRouteName(), 'edit',
+ `should equal 'edit'.`
+ );
+ assert.equal(
+ testHelpers.currentPath(), 'posts.edit',
+ `should equal 'posts.edit'.`
+ );
+ assert.equal(
+ testHelpers.currentURL(), '/posts/edit',
+ `should equal '/posts/edit'.`
+ );
});
- });
- this.runTask(() => {
- this.application.advanceReadiness();
- });
- }
+ }
- [`@test currentRouteName for '/'`](assert) {
- assert.expect(3);
+ });
- let {application: {testHelpers}} = this;
- return testHelpers.visit('/').then(() => {
- assert.equal(
- testHelpers.currentRouteName(), 'index',
- `should equal 'index'.`
- );
- assert.equal(
- testHelpers.currentPath(), 'index',
- `should equal 'index'.`
- );
+ moduleFor('ember-testing: pendingRequests', class extends HelpersApplicationTestCase {
+
+ [`@test pendingRequests is maintained for ajaxSend and ajaxComplete events`](assert) {
assert.equal(
- testHelpers.currentURL(), '/',
- `should equal '/'.`
+ pendingRequests(), 0
);
- });
- }
- [`@test currentRouteName for '/posts'`](assert) {
- assert.expect(3);
+ let xhr = { some: 'xhr' };
- let {application: {testHelpers}} = this;
- return testHelpers.visit('/posts').then(() => {
+ customEvent('ajaxSend', xhr);
assert.equal(
- testHelpers.currentRouteName(), 'posts.index',
- `should equal 'posts.index'.`
+ pendingRequests(), 1,
+ 'Ember.Test.pendingRequests was incremented'
);
+
+ customEvent('ajaxComplete', xhr);
assert.equal(
- testHelpers.currentPath(), 'posts.index',
- `should equal 'posts.index'.`
+ pendingRequests(), 0,
+ 'Ember.Test.pendingRequests was decremented'
);
+ }
+
+ [`@test pendingRequests is ignores ajaxComplete events from past setupForTesting calls`](assert) {
assert.equal(
- testHelpers.currentURL(), '/posts',
- `should equal '/posts'.`
+ pendingRequests(), 0
);
- });
- }
- [`@test currentRouteName for '/posts/new'`](assert) {
- assert.expect(3);
+ let xhr = { some: 'xhr' };
- let {application: {testHelpers}} = this;
- return testHelpers.visit('/posts/new').then(() => {
+ customEvent('ajaxSend', xhr);
assert.equal(
- testHelpers.currentRouteName(), 'posts.new',
- `should equal 'posts.new'.`
+ pendingRequests(), 1,
+ 'Ember.Test.pendingRequests was incremented'
);
- assert.equal(
- testHelpers.currentPath(), 'posts.new',
- `should equal 'posts.new'.`
- );
- assert.equal(
- testHelpers.currentURL(), '/posts/new',
- `should equal '/posts/new'.`
- );
- });
- }
- [`@test currentRouteName for '/posts/edit'`](assert) {
- assert.expect(3);
+ setupForTesting();
- let {application: {testHelpers}} = this;
- return testHelpers.visit('/posts/edit').then(() => {
assert.equal(
- testHelpers.currentRouteName(), 'edit',
- `should equal 'edit'.`
+ pendingRequests(), 0,
+ 'Ember.Test.pendingRequests was reset'
);
+
+ let altXhr = { some: 'more xhr' };
+
+ customEvent('ajaxSend', altXhr);
assert.equal(
- testHelpers.currentPath(), 'posts.edit',
- `should equal 'posts.edit'.`
+ pendingRequests(), 1,
+ 'Ember.Test.pendingRequests was incremented'
);
+
+ customEvent('ajaxComplete', xhr);
assert.equal(
- testHelpers.currentURL(), '/posts/edit',
- `should equal '/posts/edit'.`
+ pendingRequests(), 1,
+ 'Ember.Test.pendingRequests is not impressed with your unexpected complete'
);
- });
- }
-
-});
-
-moduleFor('ember-testing: pendingRequests', class extends HelpersApplicationTestCase {
-
- [`@test pendingRequests is maintained for ajaxSend and ajaxComplete events`](assert) {
- assert.equal(
- pendingRequests(), 0
- );
-
- let xhr = { some: 'xhr' };
-
- jQuery(document).trigger('ajaxSend', xhr);
- assert.equal(
- pendingRequests(), 1,
- 'Ember.Test.pendingRequests was incremented'
- );
-
- jQuery(document).trigger('ajaxComplete', xhr);
- assert.equal(
- pendingRequests(), 0,
- 'Ember.Test.pendingRequests was decremented'
- );
- }
-
- [`@test pendingRequests is ignores ajaxComplete events from past setupForTesting calls`](assert) {
- assert.equal(
- pendingRequests(), 0
- );
-
- let xhr = { some: 'xhr' };
-
- jQuery(document).trigger('ajaxSend', xhr);
- assert.equal(
- pendingRequests(), 1,
- 'Ember.Test.pendingRequests was incremented'
- );
-
- setupForTesting();
+ }
- assert.equal(
- pendingRequests(), 0,
- 'Ember.Test.pendingRequests was reset'
- );
+ [`@test pendingRequests is reset by setupForTesting`](assert) {
+ incrementPendingRequests();
- let altXhr = { some: 'more xhr' };
+ setupForTesting();
- jQuery(document).trigger('ajaxSend', altXhr);
- assert.equal(
- pendingRequests(), 1,
- 'Ember.Test.pendingRequests was incremented'
- );
+ assert.equal(
+ pendingRequests(), 0,
+ 'pendingRequests is reset'
+ );
+ }
- jQuery(document).trigger('ajaxComplete', xhr);
- assert.equal(
- pendingRequests(), 1,
- 'Ember.Test.pendingRequests is not impressed with your unexpected complete'
- );
- }
+ });
- [`@test pendingRequests is reset by setupForTesting`](assert) {
- incrementPendingRequests();
+ moduleFor('ember-testing: async router', class extends HelpersTestCase {
+ constructor() {
+ super();
- setupForTesting();
+ this.runTask(() => {
+ this.createApplication();
- assert.equal(
- pendingRequests(), 0,
- 'pendingRequests is reset'
- );
- }
+ this.router.map(function() {
+ this.route('user', { resetNamespace: true }, function() {
+ this.route('profile');
+ this.route('edit');
+ });
+ });
-});
+ // Emulate a long-running unscheduled async operation.
+ let resolveLater = () => new RSVP.Promise(resolve => {
+ /*
+ * The wait() helper has a 10ms tick. We should resolve() after
+ * at least one tick to test whether wait() held off while the
+ * async router was still loading. 20ms should be enough.
+ */
+ run.later(resolve, {firstName: 'Tom'}, 20);
+ });
-moduleFor('ember-testing: async router', class extends HelpersTestCase {
- constructor() {
- super();
+ this.add('route:user', Route.extend({
+ model() {
+ return resolveLater();
+ }
+ }));
- this.runTask(() => {
- this.createApplication();
+ this.add('route:user.profile', Route.extend({
+ beforeModel() {
+ return resolveLater().then(() => this.transitionTo('user.edit'));
+ }
+ }));
- this.router.map(function() {
- this.route('user', { resetNamespace: true }, function() {
- this.route('profile');
- this.route('edit');
- });
+ this.application.setupForTesting();
});
- // Emulate a long-running unscheduled async operation.
- let resolveLater = () => new RSVP.Promise(resolve => {
- /*
- * The wait() helper has a 10ms tick. We should resolve() after
- * at least one tick to test whether wait() held off while the
- * async router was still loading. 20ms should be enough.
- */
- run.later(resolve, {firstName: 'Tom'}, 20);
+ this.application.injectTestHelpers();
+ this.runTask(() => {
+ this.application.advanceReadiness();
});
+ }
- this.add('route:user', Route.extend({
- model() {
- return resolveLater();
- }
- }));
-
- this.add('route:user.profile', Route.extend({
- beforeModel() {
- return resolveLater().then(() => this.transitionTo('user.edit'));
- }
- }));
-
- this.application.setupForTesting();
- });
-
- this.application.injectTestHelpers();
- this.runTask(() => {
- this.application.advanceReadiness();
- });
- }
-
- [`@test currentRouteName for '/user'`](assert) {
- assert.expect(4);
+ [`@test currentRouteName for '/user'`](assert) {
+ assert.expect(4);
- let {application: {testHelpers}} = this;
- return testHelpers.visit('/user').then(() => {
- assert.equal(
- testHelpers.currentRouteName(), 'user.index',
- `should equal 'user.index'.`
- );
- assert.equal(
- testHelpers.currentPath(), 'user.index',
- `should equal 'user.index'.`
- );
- assert.equal(
- testHelpers.currentURL(), '/user',
- `should equal '/user'.`
- );
- let userRoute = this.applicationInstance.lookup('route:user');
- assert.equal(
- userRoute.get('controller.model.firstName'), 'Tom',
- `should equal 'Tom'.`
- );
- });
- }
+ let {application: {testHelpers}} = this;
+ return testHelpers.visit('/user').then(() => {
+ assert.equal(
+ testHelpers.currentRouteName(), 'user.index',
+ `should equal 'user.index'.`
+ );
+ assert.equal(
+ testHelpers.currentPath(), 'user.index',
+ `should equal 'user.index'.`
+ );
+ assert.equal(
+ testHelpers.currentURL(), '/user',
+ `should equal '/user'.`
+ );
+ let userRoute = this.applicationInstance.lookup('route:user');
+ assert.equal(
+ userRoute.get('controller.model.firstName'), 'Tom',
+ `should equal 'Tom'.`
+ );
+ });
+ }
- [`@test currentRouteName for '/user/profile'`](assert) {
- assert.expect(4);
+ [`@test currentRouteName for '/user/profile'`](assert) {
+ assert.expect(4);
- let {application: {testHelpers}} = this;
- return testHelpers.visit('/user/profile').then(() => {
- assert.equal(
- testHelpers.currentRouteName(), 'user.edit',
- `should equal 'user.edit'.`
- );
- assert.equal(
- testHelpers.currentPath(), 'user.edit',
- `should equal 'user.edit'.`
- );
- assert.equal(
- testHelpers.currentURL(), '/user/edit',
- `should equal '/user/edit'.`
- );
- let userRoute = this.applicationInstance.lookup('route:user');
- assert.equal(
- userRoute.get('controller.model.firstName'), 'Tom',
- `should equal 'Tom'.`
- );
- });
- }
+ let {application: {testHelpers}} = this;
+ return testHelpers.visit('/user/profile').then(() => {
+ assert.equal(
+ testHelpers.currentRouteName(), 'user.edit',
+ `should equal 'user.edit'.`
+ );
+ assert.equal(
+ testHelpers.currentPath(), 'user.edit',
+ `should equal 'user.edit'.`
+ );
+ assert.equal(
+ testHelpers.currentURL(), '/user/edit',
+ `should equal '/user/edit'.`
+ );
+ let userRoute = this.applicationInstance.lookup('route:user');
+ assert.equal(
+ userRoute.get('controller.model.firstName'), 'Tom',
+ `should equal 'Tom'.`
+ );
+ });
+ }
-});
+ });
-moduleFor('ember-testing: can override built-in helpers', class extends HelpersTestCase {
+ moduleFor('ember-testing: can override built-in helpers', class extends HelpersTestCase {
- constructor() {
- super();
- this.runTask(() => {
- this.createApplication();
- this.application.setupForTesting();
- });
- this._originalVisitHelper = Test._helpers.visit;
- this._originalFindHelper = Test._helpers.find;
- }
+ constructor() {
+ super();
+ this.runTask(() => {
+ this.createApplication();
+ this.application.setupForTesting();
+ });
+ this._originalVisitHelper = Test._helpers.visit;
+ this._originalFindHelper = Test._helpers.find;
+ }
- teardown() {
- Test._helpers.visit = this._originalVisitHelper;
- Test._helpers.find = this._originalFindHelper;
- super.teardown();
- }
+ teardown() {
+ Test._helpers.visit = this._originalVisitHelper;
+ Test._helpers.find = this._originalFindHelper;
+ super.teardown();
+ }
- [`@test can override visit helper`](assert) {
- assert.expect(1);
+ [`@test can override visit helper`](assert) {
+ assert.expect(1);
- Test.registerHelper('visit', () => {
- assert.ok(true, 'custom visit helper was called');
- });
+ Test.registerHelper('visit', () => {
+ assert.ok(true, 'custom visit helper was called');
+ });
- this.application.injectTestHelpers();
+ this.application.injectTestHelpers();
- return this.application.testHelpers.visit();
- }
+ return this.application.testHelpers.visit();
+ }
- [`@test can override find helper`](assert) {
- assert.expect(1);
+ [`@test can override find helper`](assert) {
+ assert.expect(1);
- Test.registerHelper('find', () => {
- assert.ok(true, 'custom find helper was called');
+ Test.registerHelper('find', () => {
+ assert.ok(true, 'custom find helper was called');
- return ['not empty array'];
- });
+ return ['not empty array'];
+ });
- this.application.injectTestHelpers();
+ this.application.injectTestHelpers();
- return this.application.testHelpers.findWithAssert('.who-cares');
- }
+ return this.application.testHelpers.findWithAssert('.who-cares');
+ }
-});
+ });
+}
\ No newline at end of file
| true |
Other
|
emberjs
|
ember.js
|
3e005da51f57cf050d36cf919d44fea15525d24f.json
|
remove jquery from ember-testing
|
packages/ember-testing/tests/integration_test.js
|
@@ -8,6 +8,7 @@ import {
A as emberA
} from 'ember-runtime';
import { Route } from 'ember-routing';
+import { jQueryDisabled } from 'ember-views';
moduleFor('ember-testing Integration tests of acceptance', class extends AutobootApplicationTestCase {
@@ -52,39 +53,56 @@ moduleFor('ember-testing Integration tests of acceptance', class extends Autoboo
}
[`@test template is bound to empty array of people`](assert) {
- this.runTask(() => this.application.advanceReadiness());
- window.visit('/').then(() => {
- let rows = window.find('.name').length;
- assert.equal(
- rows, 0,
- 'successfully stubbed an empty array of people'
- );
- });
+ if (!jQueryDisabled) {
+ this.runTask(() => this.application.advanceReadiness());
+ window.visit('/').then(() => {
+ let rows = window.find('.name').length;
+ assert.equal(
+ rows, 0,
+ 'successfully stubbed an empty array of people'
+ );
+ });
+ } else {
+ this.runTask(() => this.application.advanceReadiness());
+ window.visit('/').then(() => {
+ expectAssertion(() => window.find('.name'),
+ 'If jQuery is disabled, please import and use helpers from @ember/test-helpers [https://github.com/emberjs/ember-test-helpers]. Note: `find` is not an available helper.'
+ );
+ });
+ }
}
[`@test template is bound to array of 2 people`](assert) {
- this.modelContent = emberA([]);
- this.modelContent.pushObject({ firstName: 'x' });
- this.modelContent.pushObject({ firstName: 'y' });
-
- this.runTask(() => this.application.advanceReadiness());
- window.visit('/').then(() => {
- let rows = window.find('.name').length;
- assert.equal(
- rows, 2,
- 'successfully stubbed a non empty array of people'
- );
- });
+ if (!jQueryDisabled) {
+ this.modelContent = emberA([]);
+ this.modelContent.pushObject({ firstName: 'x' });
+ this.modelContent.pushObject({ firstName: 'y' });
+
+ this.runTask(() => this.application.advanceReadiness());
+ window.visit('/').then(() => {
+ let rows = window.find('.name').length;
+ assert.equal(
+ rows, 2,
+ 'successfully stubbed a non empty array of people'
+ );
+ });
+ } else {
+ assert.expect(0);
+ }
}
[`@test 'visit' can be called without advanceReadiness.`](assert) {
- window.visit('/').then(() => {
- let rows = window.find('.name').length;
- assert.equal(
- rows, 0,
- 'stubbed an empty array of people without calling advanceReadiness.'
- );
- });
+ if (!jQueryDisabled) {
+ window.visit('/').then(() => {
+ let rows = window.find('.name').length;
+ assert.equal(
+ rows, 0,
+ 'stubbed an empty array of people without calling advanceReadiness.'
+ );
+ });
+ } else {
+ assert.expect(0);
+ }
}
});
| true |
Other
|
emberjs
|
ember.js
|
d342a2a1dc89200a941040e7eefaaede161a39bb.json
|
Remove private enumerable observers
|
packages/ember-runtime/lib/mixins/array.js
|
@@ -59,8 +59,6 @@ export function objectAt(content, idx) {
}
export function arrayContentWillChange(array, startIdx, removeAmt, addAmt) {
- let removing, lim;
-
// if no args are passed assume everything changes
if (startIdx === undefined) {
startIdx = 0;
@@ -81,18 +79,7 @@ export function arrayContentWillChange(array, startIdx, removeAmt, addAmt) {
sendEvent(array, '@array:before', [array, startIdx, removeAmt, addAmt]);
- if (startIdx >= 0 && removeAmt >= 0 && get(array, 'hasEnumerableObservers')) {
- removing = [];
- lim = startIdx + removeAmt;
-
- for (let idx = startIdx; idx < lim; idx++) {
- removing.push(objectAt(array, idx));
- }
- } else {
- removing = removeAmt;
- }
-
- array.enumerableContentWillChange(removing, addAmt);
+ array.enumerableContentWillChange(removeAmt, addAmt);
return array;
}
@@ -112,19 +99,7 @@ export function arrayContentDidChange(array, startIdx, removeAmt, addAmt) {
}
}
- let adding;
- if (startIdx >= 0 && addAmt >= 0 && get(array, 'hasEnumerableObservers')) {
- adding = [];
- let lim = startIdx + addAmt;
-
- for (let idx = startIdx; idx < lim; idx++) {
- adding.push(objectAt(array, idx));
- }
- } else {
- adding = addAmt;
- }
-
- array.enumerableContentDidChange(removeAmt, adding);
+ array.enumerableContentDidChange(removeAmt, addAmt);
if (array.__each) {
array.__each.arrayDidChange(array, startIdx, removeAmt, addAmt);
| true |
Other
|
emberjs
|
ember.js
|
d342a2a1dc89200a941040e7eefaaede161a39bb.json
|
Remove private enumerable observers
|
packages/ember-runtime/lib/mixins/enumerable.js
|
@@ -14,11 +14,7 @@ import {
aliasMethod,
computed,
propertyWillChange,
- propertyDidChange,
- addListener,
- removeListener,
- sendEvent,
- hasListeners
+ propertyDidChange
} from 'ember-metal';
import { assert } from 'ember-debug';
import compare from '../compare';
@@ -842,76 +838,6 @@ const Enumerable = Mixin.create({
// ENUMERABLE OBSERVERS
//
- /**
- Registers an enumerable observer. Must implement `Ember.EnumerableObserver`
- mixin.
-
- @method addEnumerableObserver
- @param {Object} target
- @param {Object} [opts]
- @return this
- @private
- */
- addEnumerableObserver(target, opts) {
- let willChange = (opts && opts.willChange) || 'enumerableWillChange';
- let didChange = (opts && opts.didChange) || 'enumerableDidChange';
- let hasObservers = get(this, 'hasEnumerableObservers');
-
- if (!hasObservers) {
- propertyWillChange(this, 'hasEnumerableObservers');
- }
-
- addListener(this, '@enumerable:before', target, willChange);
- addListener(this, '@enumerable:change', target, didChange);
-
- if (!hasObservers) {
- propertyDidChange(this, 'hasEnumerableObservers');
- }
-
- return this;
- },
-
- /**
- Removes a registered enumerable observer.
-
- @method removeEnumerableObserver
- @param {Object} target
- @param {Object} [opts]
- @return this
- @private
- */
- removeEnumerableObserver(target, opts) {
- let willChange = (opts && opts.willChange) || 'enumerableWillChange';
- let didChange = (opts && opts.didChange) || 'enumerableDidChange';
- let hasObservers = get(this, 'hasEnumerableObservers');
-
- if (hasObservers) {
- propertyWillChange(this, 'hasEnumerableObservers');
- }
-
- removeListener(this, '@enumerable:before', target, willChange);
- removeListener(this, '@enumerable:change', target, didChange);
-
- if (hasObservers) {
- propertyDidChange(this, 'hasEnumerableObservers');
- }
-
- return this;
- },
-
- /**
- Becomes true whenever the array currently has observers watching changes
- on the array.
-
- @property hasEnumerableObservers
- @type Boolean
- @private
- */
- hasEnumerableObservers: computed(function() {
- return hasListeners(this, '@enumerable:change') || hasListeners(this, '@enumerable:before');
- }),
-
-
/**
Invoke this method just before the contents of your enumerable will
change. You can either omit the parameters completely or pass the objects
@@ -960,8 +886,6 @@ const Enumerable = Mixin.create({
propertyWillChange(this, 'length');
}
- sendEvent(this, '@enumerable:before', [this, removing, adding]);
-
return this;
},
@@ -1009,8 +933,6 @@ const Enumerable = Mixin.create({
adding = null;
}
- sendEvent(this, '@enumerable:change', [this, removing, adding]);
-
if (hasDelta) {
propertyDidChange(this, 'length');
}
| true |
Other
|
emberjs
|
ember.js
|
d342a2a1dc89200a941040e7eefaaede161a39bb.json
|
Remove private enumerable observers
|
packages/ember-runtime/tests/mixins/array_test.js
|
@@ -213,7 +213,7 @@ QUnit.module('notify array observers', {
}
});
-QUnit.test('should notify enumerable observers when called with no params', function(assert) {
+QUnit.test('should notify array observers when called with no params', function(assert) {
arrayContentWillChange(obj);
assert.deepEqual(observer._before, [obj, 0, -1, -1]);
@@ -238,7 +238,7 @@ QUnit.test('should notify when called with diff length items', function(assert)
assert.deepEqual(observer._after, [obj, 0, 2, 1]);
});
-QUnit.test('removing enumerable observer should disable', function(assert) {
+QUnit.test('removing array observer should disable', function(assert) {
removeArrayObserver(obj, observer);
arrayContentWillChange(obj);
assert.deepEqual(observer._before, null);
@@ -247,71 +247,6 @@ QUnit.test('removing enumerable observer should disable', function(assert) {
assert.deepEqual(observer._after, null);
});
-// ..........................................................
-// NOTIFY ENUMERABLE OBSERVER
-//
-
-QUnit.module('notify enumerable observers as well', {
- beforeEach(assert) {
- obj = DummyArray.create();
-
- observer = EmberObject.extend({
- enumerableWillChange() {
- assert.equal(this._before, null); // should only call once
- this._before = Array.prototype.slice.call(arguments);
- },
-
- enumerableDidChange() {
- assert.equal(this._after, null); // should only call once
- this._after = Array.prototype.slice.call(arguments);
- }
- }).create({
- _before: null,
- _after: null
- });
-
- obj.addEnumerableObserver(observer);
- },
-
- afterEach() {
- obj = observer = null;
- }
-});
-
-QUnit.test('should notify enumerable observers when called with no params', function(assert) {
- arrayContentWillChange(obj);
- assert.deepEqual(observer._before, [obj, null, null], 'before');
-
- arrayContentDidChange(obj);
- assert.deepEqual(observer._after, [obj, null, null], 'after');
-});
-
-// API variation that included items only
-QUnit.test('should notify when called with same length items', function(assert) {
- arrayContentWillChange(obj, 0, 1, 1);
- assert.deepEqual(observer._before, [obj, ['ITEM-0'], 1], 'before');
-
- arrayContentDidChange(obj, 0, 1, 1);
- assert.deepEqual(observer._after, [obj, 1, ['ITEM-0']], 'after');
-});
-
-QUnit.test('should notify when called with diff length items', function(assert) {
- arrayContentWillChange(obj, 0, 2, 1);
- assert.deepEqual(observer._before, [obj, ['ITEM-0', 'ITEM-1'], 1], 'before');
-
- arrayContentDidChange(obj, 0, 2, 1);
- assert.deepEqual(observer._after, [obj, 2, ['ITEM-0']], 'after');
-});
-
-QUnit.test('removing enumerable observer should disable', function(assert) {
- obj.removeEnumerableObserver(observer);
- arrayContentWillChange(obj);
- assert.deepEqual(observer._before, null, 'before');
-
- arrayContentDidChange(obj);
- assert.deepEqual(observer._after, null, 'after');
-});
-
// ..........................................................
// @each
//
| true |
Other
|
emberjs
|
ember.js
|
d342a2a1dc89200a941040e7eefaaede161a39bb.json
|
Remove private enumerable observers
|
packages/ember-runtime/tests/mixins/enumerable_test.js
|
@@ -184,7 +184,7 @@ let DummyEnum = EmberObject.extend(Enumerable, {
length: 0
});
-let obj, observer;
+let obj;
// ..........................................................
// NOTIFY ENUMERABLE PROPERTY
@@ -278,82 +278,3 @@ QUnit.test('should notify when passed old index API with delta', function(assert
obj.enumerableContentDidChange(1, 2);
assert.equal(obj._after, 1);
});
-
-// ..........................................................
-// NOTIFY ENUMERABLE OBSERVER
-//
-
-QUnit.module('notify enumerable observers', {
- beforeEach(assert) {
- obj = DummyEnum.create();
-
- observer = EmberObject.extend({
- enumerableWillChange() {
- assert.equal(this._before, null); // should only call once
- this._before = Array.prototype.slice.call(arguments);
- },
-
- enumerableDidChange() {
- assert.equal(this._after, null); // should only call once
- this._after = Array.prototype.slice.call(arguments);
- }
- }).create({
- _before: null,
- _after: null
- });
-
- obj.addEnumerableObserver(observer);
- },
-
- afterEach() {
- obj = observer = null;
- }
-});
-
-QUnit.test('should notify enumerable observers when called with no params', function(assert) {
- obj.enumerableContentWillChange();
- assert.deepEqual(observer._before, [obj, null, null]);
-
- obj.enumerableContentDidChange();
- assert.deepEqual(observer._after, [obj, null, null]);
-});
-
-// API variation that included items only
-QUnit.test('should notify when called with same length items', function(assert) {
- let added = ['foo'];
- let removed = ['bar'];
-
- obj.enumerableContentWillChange(removed, added);
- assert.deepEqual(observer._before, [obj, removed, added]);
-
- obj.enumerableContentDidChange(removed, added);
- assert.deepEqual(observer._after, [obj, removed, added]);
-});
-
-QUnit.test('should notify when called with diff length items', function(assert) {
- let added = ['foo', 'baz'];
- let removed = ['bar'];
-
- obj.enumerableContentWillChange(removed, added);
- assert.deepEqual(observer._before, [obj, removed, added]);
-
- obj.enumerableContentDidChange(removed, added);
- assert.deepEqual(observer._after, [obj, removed, added]);
-});
-
-QUnit.test('should not notify when passed with indexes only', function(assert) {
- obj.enumerableContentWillChange(1, 2);
- assert.deepEqual(observer._before, [obj, 1, 2]);
-
- obj.enumerableContentDidChange(1, 2);
- assert.deepEqual(observer._after, [obj, 1, 2]);
-});
-
-QUnit.test('removing enumerable observer should disable', function(assert) {
- obj.removeEnumerableObserver(observer);
- obj.enumerableContentWillChange();
- assert.deepEqual(observer._before, null);
-
- obj.enumerableContentDidChange();
- assert.deepEqual(observer._after, null);
-});
| true |
Other
|
emberjs
|
ember.js
|
d342a2a1dc89200a941040e7eefaaede161a39bb.json
|
Remove private enumerable observers
|
packages/ember-runtime/tests/suites/enumerable.js
|
@@ -130,29 +130,6 @@ const ObserverClass = EmberObject.extend({
*/
timesCalled(key) {
return this._keys[key] || 0;
- },
-
- /*
- begins acting as an enumerable observer.
- */
- observeEnumerable(obj) {
- obj.addEnumerableObserver(this);
- return this;
- },
-
- stopObserveEnumerable(obj) {
- obj.removeEnumerableObserver(this);
- return this;
- },
-
- enumerableWillChange() {
- QUnit.config.current.assert.equal(this._before, null, 'should only call once');
- this._before = Array.prototype.slice.call(arguments);
- },
-
- enumerableDidChange() {
- QUnit.config.current.assert.equal(this._after, null, 'should only call once');
- this._after = Array.prototype.slice.call(arguments);
}
});
| true |
Other
|
emberjs
|
ember.js
|
d342a2a1dc89200a941040e7eefaaede161a39bb.json
|
Remove private enumerable observers
|
packages/ember-runtime/tests/suites/mutable_array/replace.js
|
@@ -147,18 +147,6 @@ suite.test('[A,B,C,D].replace(-1,1) => [A,B,C] + notify', function(assert) {
assert.equal(observer.validate('firstObject'), false, 'should NOT have notified firstObject once');
});
-suite.test('Adding object should notify enumerable observer', function(assert) {
- let fixtures = this.newFixture(4);
- let obj = this.newObject(fixtures);
- let observer = this.newObserver(obj).observeEnumerable(obj);
- let item = this.newFixture(1)[0];
-
- obj.replace(2, 2, [item]);
-
- assert.deepEqual(observer._before, [obj, [fixtures[2], fixtures[3]], 1], 'before');
- assert.deepEqual(observer._after, [obj, 2, [item]], 'after');
-});
-
suite.test('Adding object should notify array observer', function(assert) {
let fixtures = this.newFixture(4);
let obj = this.newObject(fixtures);
| true |
Other
|
emberjs
|
ember.js
|
d342a2a1dc89200a941040e7eefaaede161a39bb.json
|
Remove private enumerable observers
|
packages/ember-runtime/tests/suites/mutable_enumerable/addObject.js
|
@@ -56,15 +56,4 @@ suite.test('[A,B,C].addObject(A) => [A,B,C] + NO notify', function(assert) {
}
});
-suite.test('Adding object should notify enumerable observer', function(assert) {
- let obj = this.newObject(this.newFixture(3));
- let observer = this.newObserver(obj).observeEnumerable(obj);
- let item = this.newFixture(1)[0];
-
- obj.addObject(item);
-
- assert.deepEqual(observer._before, [obj, null, [item]]);
- assert.deepEqual(observer._after, [obj, null, [item]]);
-});
-
export default suite;
| true |
Other
|
emberjs
|
ember.js
|
d342a2a1dc89200a941040e7eefaaede161a39bb.json
|
Remove private enumerable observers
|
packages/ember-runtime/tests/suites/mutable_enumerable/removeObject.js
|
@@ -58,16 +58,4 @@ suite.test('[A,B,C].removeObject(D) => [A,B,C]', function(assert) {
}
});
-suite.test('Removing object should notify enumerable observer', function(assert) {
- let fixtures = this.newFixture(3);
- let obj = this.newObject(fixtures);
- let observer = this.newObserver(obj).observeEnumerable(obj);
- let item = fixtures[1];
-
- obj.removeObject(item);
-
- assert.deepEqual(observer._before, [obj, [item], null]);
- assert.deepEqual(observer._after, [obj, [item], null]);
-});
-
export default suite;
| true |
Other
|
emberjs
|
ember.js
|
d342a2a1dc89200a941040e7eefaaede161a39bb.json
|
Remove private enumerable observers
|
packages/ember-runtime/tests/suites/mutable_enumerable/removeObjects.js
|
@@ -168,16 +168,4 @@ suite.test('[A,B,C].removeObjects([D]) => [A,B,C]', function(assert) {
}
});
-suite.test('Removing objects should notify enumerable observer', function(assert) {
- let fixtures = this.newFixture(3);
- let obj = this.newObject(fixtures);
- let observer = this.newObserver(obj).observeEnumerable(obj);
- let item = fixtures[1];
-
- obj.removeObjects([item]);
-
- assert.deepEqual(observer._before, [obj, [item], null]);
- assert.deepEqual(observer._after, [obj, [item], null]);
-});
-
export default suite;
| true |
Other
|
emberjs
|
ember.js
|
41985bda1ab20b62fbad46aaf2abc406e570bd19.json
|
Publish metadata file to S3.
Remove publishing tarball to `/${channel}.tgz` due to npm and yarn
caching issues.
Publishes a new `/${channel}.json` file (in a stable location) that can
be used by tooling to determine the correct asset path for the current
channel build SHA.
|
bin/build-for-publishing.js
|
@@ -4,14 +4,14 @@
const fs = require('fs');
const path = require('path');
const execSync = require('child_process').execSync;
+const VERSION = require('../broccoli/version').VERSION;
/*
Updates the `package.json`'s `version` string to be the same value that
the built assets will have as `Ember.VERSION`.
*/
function updatePackageJSONVersion() {
let packageJSONPath = path.join(__dirname, '..', 'package.json');
- let VERSION = require('../broccoli/version').VERSION;
let pkgContents = fs.readFileSync(packageJSONPath, { encoding: 'utf-8' });
let pkg = JSON.parse(pkgContents);
@@ -31,7 +31,6 @@ function updatePackageJSONVersion() {
*/
function updateDocumentationVersion() {
let docsPath = path.join(__dirname, '..', 'docs', 'data.json');
- let VERSION = require('../broccoli/version').VERSION;
let contents = fs.readFileSync(docsPath, { encoding: 'utf-8' });
let docs = JSON.parse(contents);
@@ -51,3 +50,12 @@ updateDocumentationVersion();
// using npm pack here because `yarn pack` does not honor the `package.json`'s `files`
// property properly, and therefore the tarball generated is quite large (~7MB).
execSync('npm pack');
+
+// generate build-metadata.json
+const metadata = {
+ version: VERSION,
+ buildType: process.env.BUILD_TYPE,
+ SHA: process.env.TRAVIS_COMMIT,
+ assetPath: `/${process.env.BUILD_TYPE}/shas/${process.env.TRAVIS_COMMIT}.tgz`,
+};
+fs.writeFileSync('build-metadata.json', JSON.stringify(metadata, null, 2), { encoding: 'utf-8' });
| true |
Other
|
emberjs
|
ember.js
|
41985bda1ab20b62fbad46aaf2abc406e570bd19.json
|
Publish metadata file to S3.
Remove publishing tarball to `/${channel}.tgz` due to npm and yarn
caching issues.
Publishes a new `/${channel}.json` file (in a stable location) that can
be used by tooling to determine the correct asset path for the current
channel build SHA.
|
config/s3ProjectConfig.js
|
@@ -26,27 +26,40 @@ function fileMap(revision, tag, date) {
contentType: 'application/x-gzip',
destinations: {
'alpha': [
- `alpha.tgz`,
`alpha/daily/${date}.tgz`,
`alpha/shas/${revision}.tgz`,
],
'canary': [
- `canary.tgz`,
`canary/daily/${date}.tgz`,
`canary/shas/${revision}.tgz`,
],
'beta': [
- `beta.tgz`,
`beta/daily/${date}.tgz`,
`beta/shas/${revision}.tgz`,
],
'release': [
- `release.tgz`,
`release/daily/${date}.tgz`,
`release/shas/${revision}.tgz`,
],
}
};
+ filesToPublish['../build-metadata.json'] = {
+ contentType: 'application/json',
+ destinations: {
+ 'alpha': [
+ 'alpha.json',
+ ],
+ 'canary': [
+ 'canary.json',
+ ],
+ 'beta': [
+ 'beta.json',
+ ],
+ 'release': [
+ 'release.json',
+ ],
+ }
+ };
return filesToPublish;
}
| true |
Other
|
emberjs
|
ember.js
|
abf3db1b78a708515c5b3ee58e9c1756dd527cef.json
|
Simplify outlet and fix stability.
|
packages/ember-glimmer/lib/component-managers/outlet.ts
|
@@ -26,32 +26,35 @@ import RuntimeResolver from '../resolver';
import {
OwnedTemplate,
} from '../template';
+import { OutletState } from '../utils/outlet';
import { RootReference } from '../utils/references';
-import { default as OutletView, OutletState } from '../views/outlet';
+import OutletView from '../views/outlet';
import AbstractManager from './abstract';
-function instrumentationPayload({ render: { name, outlet } }: {render: {name: string, outlet: string}}) {
- return { object: `${name}:${outlet}` };
+function instrumentationPayload(def: OutletDefinitionState) {
+ return { object: `${def.name}:${def.outlet}` };
}
-function NOOP() {/**/}
-
-class OutletInstanceState {
- public finalizer: () => void;
-
- constructor(public outletState: VersionedPathReference<OutletState>) {
- this.instrument();
- }
+interface OutletInstanceState {
+ tag: Tag;
+ controller: any | undefined;
+ finalize: () => void;
+}
- instrument() {
- this.finalizer = _instrumentStart('render.outlet', instrumentationPayload, this.outletState.value());
- }
+function createInstanceState(definition: OutletDefinitionState): OutletInstanceState {
+ return {
+ tag: definition.ref.tag,
+ controller: definition.controller,
+ finalize: _instrumentStart('render.outlet', instrumentationPayload, definition),
+ };
+}
- finalize() {
- let { finalizer } = this;
- finalizer();
- this.finalizer = NOOP;
- }
+export interface OutletDefinitionState {
+ ref: VersionedPathReference<OutletState | undefined>;
+ name: string;
+ outlet: string;
+ template: OwnedTemplate;
+ controller: any | undefined;
}
export const CAPABILITIES: ComponentCapabilities = {
@@ -63,27 +66,25 @@ export const CAPABILITIES: ComponentCapabilities = {
elementHook: false
};
-class OutletComponentManager extends AbstractManager<OutletInstanceState, OutletComponentDefinitionState>
- implements WithStaticLayout<OutletInstanceState, OutletComponentDefinitionState, OwnedTemplateMeta, RuntimeResolver> {
+class OutletComponentManager extends AbstractManager<OutletInstanceState, OutletDefinitionState>
+ implements WithStaticLayout<OutletInstanceState, OutletDefinitionState, OwnedTemplateMeta, RuntimeResolver> {
create(environment: Environment,
- definition: OutletComponentDefinitionState,
+ definition: OutletDefinitionState,
_args: Arguments,
dynamicScope: DynamicScope) {
if (DEBUG) {
this._pushToDebugStack(`template:${definition.template.referrer.moduleName}`, environment);
}
- // TODO revisit missing outletName
- let outletStateReference = dynamicScope.outletState =
- dynamicScope.outletState.get('outlets').get(definition.outletName!) as VersionedPathReference<OutletState>;
- return new OutletInstanceState(outletStateReference);
+ dynamicScope.outletState = definition.ref;
+ return createInstanceState(definition);
}
- layoutFor(_state: OutletComponentDefinitionState, _component: OutletInstanceState, _env: Environment): Unique<'Handle'> {
+ layoutFor(_state: OutletDefinitionState, _component: OutletInstanceState, _env: Environment): Unique<'Handle'> {
throw new Error('Method not implemented.');
}
- getLayout(state: OutletComponentDefinitionState, _resolver: RuntimeResolver): Invocation {
+ getLayout(state: OutletDefinitionState, _resolver: RuntimeResolver): Invocation {
// The router has already resolved the template
const layout = state.template.asLayout();
return {
@@ -96,22 +97,20 @@ class OutletComponentManager extends AbstractManager<OutletInstanceState, Outlet
return CAPABILITIES;
}
- getSelf({ outletState }: OutletInstanceState) {
+ getSelf({ controller }: OutletInstanceState) {
// RootReference initializes the object dirtyable tag state
// basically the entry point from Ember to Glimmer.
// So even though outletState is a path reference, it is not
// the correct Tag to support self here.
- const { render } = outletState.value();
- return new RootReference(render!.controller);
+ return new RootReference(controller);
}
- getTag({ outletState }: OutletInstanceState): Tag {
- // TODO: is this the right tag?
- return outletState.tag;
+ getTag(state: OutletInstanceState): Tag {
+ return state.tag;
}
- didRenderLayout(bucket: OutletInstanceState) {
- bucket.finalize();
+ didRenderLayout(state: OutletInstanceState) {
+ state.finalize();
if (DEBUG) {
this.debugStack.pop();
@@ -135,7 +134,7 @@ class TopLevelOutletComponentManager extends OutletComponentManager
return 'div';
}
- getLayout(state: OutletComponentDefinitionState, resolver: RuntimeResolver): Invocation {
+ getLayout(state: OutletDefinitionState, resolver: RuntimeResolver): Invocation {
// The router has already resolved the template
const template = state.template;
let layout: TopLevelSyntax;
@@ -159,14 +158,6 @@ class TopLevelOutletComponentManager extends OutletComponentManager
};
}
- create(environment: Environment, definition: TopOutletComponentDefinitionState, _args: Arguments, dynamicScope: DynamicScope) {
- if (DEBUG) {
- this._pushToDebugStack(`template:${definition.template.referrer.moduleName}`, environment);
- }
- // TODO: top level outlet should always have outletState, assert
- return new OutletInstanceState(dynamicScope.outletState as VersionedPathReference<OutletState>);
- }
-
getCapabilities(): ComponentCapabilities {
if (EMBER_GLIMMER_REMOVE_APPLICATION_TEMPLATE_WRAPPER) {
return CAPABILITIES;
@@ -183,33 +174,20 @@ class TopLevelOutletComponentManager extends OutletComponentManager
const TOP_MANAGER = new TopLevelOutletComponentManager();
-export interface TopOutletComponentDefinitionState {
- template: OwnedTemplate;
-}
-
-export class TopLevelOutletComponentDefinition implements ComponentDefinition<TopOutletComponentDefinitionState, TopLevelOutletComponentManager> {
- public state: TopOutletComponentDefinitionState;
+export class TopLevelOutletComponentDefinition implements ComponentDefinition<OutletDefinitionState, TopLevelOutletComponentManager> {
+ public state: OutletDefinitionState;
public manager: TopLevelOutletComponentManager = TOP_MANAGER;
constructor(instance: OutletView) {
- this.state = {
- template: instance.template as OwnedTemplate,
- };
+ this.state = instance.state;
}
}
const OUTLET_MANAGER = new OutletComponentManager();
-export interface OutletComponentDefinitionState {
- outletName: string;
- template: OwnedTemplate;
-}
-
-export class OutletComponentDefinition implements ComponentDefinition<OutletComponentDefinitionState, OutletComponentManager> {
- public state: OutletComponentDefinitionState;
+export class OutletComponentDefinition implements ComponentDefinition<OutletDefinitionState, OutletComponentManager> {
public manager: OutletComponentManager = OUTLET_MANAGER;
- constructor(outletName: string, template: OwnedTemplate) {
- this.state = { outletName, template };
+ constructor(public state: OutletDefinitionState) {
}
}
| true |
Other
|
emberjs
|
ember.js
|
abf3db1b78a708515c5b3ee58e9c1756dd527cef.json
|
Simplify outlet and fix stability.
|
packages/ember-glimmer/lib/helpers/outlet.ts
|
@@ -1,56 +1,79 @@
-import { combine, ConstReference, Reference, RevisionTag, TagWrapper, UpdatableTag, VersionedPathReference } from '@glimmer/reference';
+import { ConstReference, Reference, Tag, VersionedPathReference } from '@glimmer/reference';
import {
Arguments,
CurriedComponentDefinition,
curry,
UNDEFINED_REFERENCE,
VM,
} from '@glimmer/runtime';
-import { OutletComponentDefinition } from '../component-managers/outlet';
+import { OutletComponentDefinition, OutletDefinitionState } from '../component-managers/outlet';
import { DynamicScope } from '../renderer';
-import { OutletState } from '../views/outlet';
+import { OutletReference, OutletState } from '../utils/outlet';
export default function outlet(vm: VM, args: Arguments) {
let scope = vm.dynamicScope() as DynamicScope;
- let outletNameRef: Reference<string>;
+ let nameRef: Reference<string>;
if (args.positional.length === 0) {
- outletNameRef = new ConstReference('main');
+ nameRef = new ConstReference('main');
} else {
- outletNameRef = args.positional.at<VersionedPathReference<string>>(0);
+ nameRef = args.positional.at<VersionedPathReference<string>>(0);
}
- return new OutletComponentReference(outletNameRef, scope.outletState);
+ return new OutletComponentReference(new OutletReference(scope.outletState, nameRef));
}
class OutletComponentReference implements VersionedPathReference<CurriedComponentDefinition | null> {
- public tag: TagWrapper<RevisionTag | null>;
- private outletStateTag: TagWrapper<UpdatableTag>;
- private definition: any | null;
- private lastState: any | null;
+ public tag: Tag;
+ private definition: CurriedComponentDefinition | null;
+ private lastState: OutletDefinitionState | null;
- constructor(private outletNameRef: Reference<string>,
- private parentOutletStateRef: VersionedPathReference<OutletState | null>) {
- this.outletNameRef = outletNameRef;
- this.parentOutletStateRef = parentOutletStateRef;
+ constructor(private outletRef: VersionedPathReference<OutletState | undefined>) {
this.definition = null;
this.lastState = null;
- let outletStateTag = this.outletStateTag = UpdatableTag.create(parentOutletStateRef.tag);
- this.tag = combine([outletStateTag, outletNameRef.tag]);
+ // The router always dirties the root state.
+ this.tag = outletRef.tag;
}
value(): CurriedComponentDefinition | null {
- let outletName = this.outletNameRef.value();
- let parentState = this.parentOutletStateRef.value();
- if (!parentState) return null;
- let outletState = parentState.outlets[outletName];
- if (!outletState) return null;
- let renderState = outletState.render;
- if (!renderState) return null;
- let template = renderState.template;
- if (!template) return null;
- return curry(new OutletComponentDefinition(outletName, template));
+ let state = stateFor(this.outletRef);
+ if (validate(state, this.lastState)) {
+ return this.definition;
+ }
+ this.lastState = state;
+ let definition = null;
+ if (state !== null) {
+ definition = curry(new OutletComponentDefinition(state));
+ }
+ return this.definition = definition;
}
get(_key: string) {
return UNDEFINED_REFERENCE;
}
-}
\ No newline at end of file
+}
+
+function stateFor(ref: VersionedPathReference<OutletState | undefined>): OutletDefinitionState | null {
+ let outlet = ref.value();
+ if (outlet === undefined) return null;
+ let render = outlet.render;
+ if (render === undefined) return null;
+ let template = render.template;
+ if (template === undefined) return null;
+ return {
+ ref,
+ name: render.name,
+ outlet: render.outlet,
+ template,
+ controller: render.controller,
+ };
+}
+
+function validate(state: OutletDefinitionState | null, lastState: OutletDefinitionState | null) {
+ if (state === null) {
+ return lastState === null;
+ }
+ if (lastState === null) {
+ return false;
+ }
+ return state.template === lastState.template &&
+ state.controller === lastState.controller;
+}
| true |
Other
|
emberjs
|
ember.js
|
abf3db1b78a708515c5b3ee58e9c1756dd527cef.json
|
Simplify outlet and fix stability.
|
packages/ember-glimmer/lib/renderer.ts
|
@@ -1,13 +1,13 @@
-import { Option, Simple } from '@glimmer/interfaces';
+import { Simple } from '@glimmer/interfaces';
import { CURRENT_TAG, VersionedPathReference } from '@glimmer/reference';
import {
clientBuilder,
CurriedComponentDefinition,
curry,
DynamicScope as GlimmerDynamicScope,
IteratorResult,
- NULL_REFERENCE,
RenderResult,
+ UNDEFINED_REFERENCE,
} from '@glimmer/runtime';
import { Opaque } from '@glimmer/util';
import { assert } from 'ember-debug';
@@ -29,36 +29,30 @@ import { RootComponentDefinition } from './component-managers/root';
import Environment from './environment';
import { OwnedTemplate } from './template';
import { Component } from './utils/curly-component-state-bucket';
+import { OutletState } from './utils/outlet';
import { UnboundReference } from './utils/references';
-import OutletView, { OutletState, RootOutletStateReference } from './views/outlet';
+import OutletView from './views/outlet';
const { backburner } = run;
export class DynamicScope implements GlimmerDynamicScope {
- outletState: VersionedPathReference<Option<OutletState>>;
- rootOutletState: RootOutletStateReference | undefined;
-
constructor(
public view: Component | null,
- outletState: VersionedPathReference<Option<OutletState>>,
- rootOutletState?: RootOutletStateReference) {
- this.outletState = outletState;
- this.rootOutletState = rootOutletState;
+ public outletState: VersionedPathReference<OutletState | undefined>,
+ public rootOutletState: VersionedPathReference<OutletState | undefined>) {
}
child() {
- return new DynamicScope(
- this.view, this.outletState, this.rootOutletState,
- );
+ return new DynamicScope(this.view, this.outletState, this.rootOutletState);
}
- get(key: 'outletState'): VersionedPathReference<Option<OutletState>> {
+ get(key: 'outletState'): VersionedPathReference<OutletState | undefined> {
// tslint:disable-next-line:max-line-length
assert(`Using \`-get-dynamic-scope\` is only supported for \`outletState\` (you used \`${key}\`).`, key === 'outletState');
return this.outletState;
}
- set(key: 'outletState', value: VersionedPathReference<Option<OutletState>>) {
+ set(key: 'outletState', value: VersionedPathReference<OutletState | undefined>) {
// tslint:disable-next-line:max-line-length
assert(`Using \`-with-dynamic-scope\` is only supported for \`outletState\` (you used \`${key}\`).`, key === 'outletState');
this.outletState = value;
@@ -269,25 +263,21 @@ export abstract class Renderer {
appendOutletView(view: OutletView, target: Simple.Element) {
let definition = new TopLevelOutletComponentDefinition(view);
- let outletStateReference = view.toReference();
-
- this._appendDefinition(view, curry(definition), target, outletStateReference);
+ this._appendDefinition(view, curry(definition), target);
}
appendTo(view: Component, target: Simple.Element) {
- let def = new RootComponentDefinition(view);
- this._appendDefinition(view, curry(def), target);
+ let definition = new RootComponentDefinition(view);
+ this._appendDefinition(view, curry(definition), target);
}
_appendDefinition(
root: OutletView | Component,
definition: CurriedComponentDefinition,
- target: Simple.Element,
- outletStateReference?: RootOutletStateReference) {
+ target: Simple.Element) {
let self = new UnboundReference(definition);
- let dynamicScope = new DynamicScope(null, outletStateReference || NULL_REFERENCE, outletStateReference);
+ let dynamicScope = new DynamicScope(null, UNDEFINED_REFERENCE, UNDEFINED_REFERENCE);
let rootState = new RootState(root, this._env, this._rootTemplate, self, target, dynamicScope);
-
this._renderRoot(rootState);
}
| true |
Other
|
emberjs
|
ember.js
|
abf3db1b78a708515c5b3ee58e9c1756dd527cef.json
|
Simplify outlet and fix stability.
|
packages/ember-glimmer/lib/utils/outlet.ts
|
@@ -0,0 +1,170 @@
+import { Opaque } from '@glimmer/interfaces';
+import { combine, DirtyableTag, Reference, Tag, VersionedPathReference } from '@glimmer/reference';
+import { Owner } from 'ember-utils';
+import { OwnedTemplate } from '../template';
+
+export interface RenderState {
+ /**
+ * Not sure why this is here, we use the owner of the template for lookups.
+ *
+ * Maybe this is for the render helper?
+ */
+ owner: Owner;
+
+ /**
+ * The name of the parent outlet state.
+ */
+ into: string | undefined;
+
+ /*
+ * The outlet name in the parent outlet state's outlets.
+ */
+ outlet: string;
+
+ /**
+ * The name of the route/template
+ */
+ name: string;
+
+ /**
+ * The controller (the self of the outlet component)
+ */
+ controller: any | undefined;
+
+ /**
+ * template (the layout of the outlet component)
+ */
+ template: OwnedTemplate | undefined;
+}
+
+export interface Outlets {
+ [name: string]: OutletState | undefined;
+}
+
+export interface OutletState {
+ /**
+ * Nested outlet connections.
+ */
+ outlets: Outlets;
+
+ /**
+ * Represents what was rendered into this outlet.
+ */
+ render: RenderState | undefined;
+
+ /**
+ * Has to do with render helper and orphan outlets.
+ * Whether outlet state was rendered.
+ */
+ wasUsed?: boolean;
+}
+
+/**
+ * Represents the root outlet.
+ */
+export class RootOutletReference implements VersionedPathReference<OutletState> {
+ tag = DirtyableTag.create();
+
+ constructor(public outletState: OutletState) {
+ }
+
+ get(key: string): VersionedPathReference<Opaque> {
+ return new PathReference(this, key);
+ }
+
+ value(): OutletState {
+ return this.outletState;
+ }
+
+ update(state: OutletState) {
+ this.outletState.outlets.main = state;
+ this.tag.inner.dirty();
+ }
+}
+
+/**
+ * Represents the connected outlet.
+ */
+export class OutletReference implements VersionedPathReference<OutletState | undefined> {
+ tag: Tag;
+
+ constructor(public parentStateRef: VersionedPathReference<OutletState | undefined>,
+ public outletNameRef: Reference<string>) {
+ this.tag = combine([parentStateRef.tag, outletNameRef.tag]);
+ }
+
+ value(): OutletState | undefined {
+ let outletState = this.parentStateRef.value();
+ let outlets = outletState === undefined ? undefined : outletState.outlets;
+ return outlets === undefined ? undefined : outlets[this.outletNameRef.value()];
+ }
+
+ get(key: string): VersionedPathReference<Opaque> {
+ return new PathReference(this, key);
+ }
+}
+
+/**
+ * Outlet state is dirtied from root.
+ * This just using the parent tag for dirtiness.
+ */
+class PathReference implements VersionedPathReference<Opaque> {
+ public parent: VersionedPathReference<Opaque>;
+ public key: string;
+ public tag: Tag;
+
+ constructor(parent: VersionedPathReference<Opaque>, key: string) {
+ this.parent = parent;
+ this.key = key;
+ this.tag = parent.tag;
+ }
+
+ get(key: string): VersionedPathReference<Opaque> {
+ return new PathReference(this, key);
+ }
+
+ value(): Opaque {
+ let parent = this.parent.value();
+ return parent && parent[this.key];
+ }
+}
+
+/**
+ * So this is a relic of the past that SHOULD go away
+ * in 3.0. Preferably it is deprecated in the release that
+ * follows the Glimmer release.
+ */
+export class OrphanedOutletReference implements VersionedPathReference<OutletState | undefined> {
+ public tag: Tag;
+
+ constructor(public root: VersionedPathReference<OutletState | undefined>, public name: string) {
+ this.tag = root.tag;
+ }
+
+ value(): OutletState | undefined {
+ let rootState = this.root.value();
+ let outletState = rootState && rootState.outlets.main;
+ let outlets = outletState && outletState.outlets;
+ outletState = outlets && outlets.__ember_orphans__;
+ outlets = outletState && outletState.outlets;
+
+ if (outlets === undefined) {
+ return;
+ }
+
+ let matched = outlets[this.name];
+
+ if (matched === undefined || matched.render === undefined) {
+ return;
+ }
+
+ let state = Object.create(null);
+ state[matched.render.outlet] = matched;
+ matched.wasUsed = true;
+ return { outlets: state, render: undefined };
+ }
+
+ get(key: string): VersionedPathReference<Opaque> {
+ return new PathReference(this, key);
+ }
+}
| true |
Other
|
emberjs
|
ember.js
|
abf3db1b78a708515c5b3ee58e9c1756dd527cef.json
|
Simplify outlet and fix stability.
|
packages/ember-glimmer/lib/views/outlet.ts
|
@@ -1,122 +1,22 @@
import { Simple } from '@glimmer/interfaces';
-import { DirtyableTag, Tag, TagWrapper, VersionedPathReference } from '@glimmer/reference';
-import { Opaque, Option } from '@glimmer/util';
import { environment } from 'ember-environment';
import { run } from 'ember-metal';
import { assign, OWNER, Owner } from 'ember-utils';
+import { OutletDefinitionState } from '../component-managers/outlet';
import { Renderer } from '../renderer';
import { OwnedTemplate } from '../template';
-
-export class RootOutletStateReference implements VersionedPathReference<Option<OutletState>> {
- tag: Tag;
-
- constructor(public outletView: OutletView) {
- this.tag = outletView._tag;
- }
-
- get(key: string): VersionedPathReference<any> {
- return new ChildOutletStateReference(this, key);
- }
-
- value(): Option<OutletState> {
- return this.outletView.outletState;
- }
-
- getOrphan(name: string): VersionedPathReference<Option<OutletState>> {
- return new OrphanedOutletStateReference(this, name);
- }
-
- update(state: OutletState) {
- this.outletView.setOutletState(state);
- }
-}
-
-// So this is a relic of the past that SHOULD go away
-// in 3.0. Preferably it is deprecated in the release that
-// follows the Glimmer release.
-class OrphanedOutletStateReference extends RootOutletStateReference {
- public root: any;
- public name: string;
-
- constructor(root: RootOutletStateReference, name: string) {
- super(root.outletView);
- this.root = root;
- this.name = name;
- }
-
- value(): Option<OutletState> {
- let rootState = this.root.value();
-
- let orphans = rootState.outlets.main.outlets.__ember_orphans__;
-
- if (!orphans) {
- return null;
- }
-
- let matched = orphans.outlets[this.name];
-
- if (!matched) {
- return null;
- }
-
- let state = Object.create(null);
- state[matched.render.outlet] = matched;
- matched.wasUsed = true;
- return { outlets: state, render: undefined };
- }
-}
-
-class ChildOutletStateReference implements VersionedPathReference<any> {
- public parent: VersionedPathReference<any>;
- public key: string;
- public tag: Tag;
-
- constructor(parent: VersionedPathReference<any>, key: string) {
- this.parent = parent;
- this.key = key;
- this.tag = parent.tag;
- }
-
- get(key: string): VersionedPathReference<any> {
- return new ChildOutletStateReference(this, key);
- }
-
- value(): any {
- let parent = this.parent.value();
- return parent && parent[this.key];
- }
-}
-
-export interface RenderState {
- owner: Owner | undefined;
- into: string | undefined;
- outlet: string;
- name: string;
- controller: Opaque;
- template: OwnedTemplate | undefined;
-}
-
-export interface OutletState {
- outlets: {
- [name: string]: OutletState | undefined;
- };
- render: RenderState | undefined;
-}
+import { OutletState, RootOutletReference } from '../utils/outlet';
export interface BootEnvironment {
hasDOM: boolean;
isInteractive: boolean;
options: any;
}
-export default class OutletView {
- private _environment: BootEnvironment;
- public renderer: Renderer;
- public owner: Owner;
- public template: OwnedTemplate;
- public outletState: Option<OutletState>;
- public _tag: TagWrapper<DirtyableTag>;
+const TOP_LEVEL_NAME = '-top-level';
+const TOP_LEVEL_OUTLET = 'main';
+export default class OutletView {
static extend(injections: any) {
return class extends OutletView {
static create(options: any) {
@@ -139,13 +39,28 @@ export default class OutletView {
return new OutletView(_environment, renderer, owner, template);
}
- constructor(_environment: BootEnvironment, renderer: Renderer, owner: Owner, template: OwnedTemplate) {
- this._environment = _environment;
- this.renderer = renderer;
- this.owner = owner;
- this.template = template;
- this.outletState = null;
- this._tag = DirtyableTag.create();
+ public ref: RootOutletReference;
+ public state: OutletDefinitionState;
+
+ constructor(private _environment: BootEnvironment, public renderer: Renderer, public owner: Owner, public template: OwnedTemplate) {
+ let ref = this.ref = new RootOutletReference({
+ outlets: { main: undefined },
+ render: {
+ owner: owner,
+ into: undefined,
+ outlet: TOP_LEVEL_OUTLET,
+ name: TOP_LEVEL_NAME,
+ controller: undefined,
+ template,
+ },
+ });
+ this.state = {
+ ref,
+ name: TOP_LEVEL_NAME,
+ outlet: TOP_LEVEL_OUTLET,
+ template,
+ controller: undefined
+ };
}
appendTo(selector: string | Simple.Element) {
@@ -164,24 +79,7 @@ export default class OutletView {
rerender() { /**/ }
setOutletState(state: OutletState) {
- this.outletState = {
- outlets: {
- main: state,
- },
- render: {
- owner: undefined,
- into: undefined,
- outlet: 'main',
- name: '-top-level',
- controller: undefined,
- template: undefined,
- },
- };
- this._tag.inner.dirty();
- }
-
- toReference() {
- return new RootOutletStateReference(this);
+ this.ref.update(state);
}
destroy() { /**/ }
| true |
Other
|
emberjs
|
ember.js
|
abf3db1b78a708515c5b3ee58e9c1756dd527cef.json
|
Simplify outlet and fix stability.
|
tests/node/helpers/component-module.js
|
@@ -107,7 +107,6 @@ function render(_template) {
name: 'index',
controller: this,
template: this.owner.lookup(templateFullName),
- outlets: { }
};
stateToRender.name = 'index';
| true |
Other
|
emberjs
|
ember.js
|
f3ed85359760121ce71ab8f61d9167857f4b24bc.json
|
Add the rest of the tests from #15287
|
packages/ember-glimmer/tests/integration/components/contextual-components-test.js
|
@@ -369,6 +369,76 @@ moduleFor('Components test: contextual components', class extends RenderingTest
this.assertText('Hodi Sigmundur 33');
}
+ ['@test nested components with positional params at middle layer are partially overwriten by hash parameters']() {
+ this.registerComponent('-looked-up', {
+ ComponentClass: Component.extend().reopenClass({
+ positionalParams: ['greeting', 'name', 'age']
+ }),
+
+ template: '{{greeting}} {{name}} {{age}}'
+ });
+
+ this.render(strip`
+ {{#with (component "-looked-up" greeting="Hola" name="Dolores" age=33) as |first|}}
+ {{#with (component first "Hej" "Sigmundur") as |second|}}
+ {{component second greeting=model.greeting}}
+ {{/with}}
+ {{/with}}`, {
+ model: {
+ greeting: 'Hodi'
+ }
+ });
+
+ this.assertText('Hodi Sigmundur 33');
+
+ this.runTask(() => this.rerender());
+
+ this.assertText('Hodi Sigmundur 33');
+
+ this.runTask(() => this.context.set('model.greeting', 'Kaixo'));
+
+ this.assertText('Kaixo Sigmundur 33');
+
+ this.runTask(() => this.context.set('model', { greeting: 'Hodi' }));
+
+ this.assertText('Hodi Sigmundur 33');
+ }
+
+ ['@test nested components with positional params at invocation override earlier hash parameters']() {
+ this.registerComponent('-looked-up', {
+ ComponentClass: Component.extend().reopenClass({
+ positionalParams: ['greeting', 'name', 'age']
+ }),
+
+ template: '{{greeting}} {{name}} {{age}}'
+ });
+
+ this.render(strip`
+ {{#with (component "-looked-up" greeting="Hola" name="Dolores" age=33) as |first|}}
+ {{#with (component first greeting="Hej" name="Sigmundur") as |second|}}
+ {{component second model.greeting}}
+ {{/with}}
+ {{/with}}`, {
+ model: {
+ greeting: 'Hodi'
+ }
+ });
+
+ this.assertText('Hodi Sigmundur 33');
+
+ this.runTask(() => this.rerender());
+
+ this.assertText('Hodi Sigmundur 33');
+
+ this.runTask(() => this.context.set('model.greeting', 'Kaixo'));
+
+ this.assertText('Kaixo Sigmundur 33');
+
+ this.runTask(() => this.context.set('model', { greeting: 'Hodi' }));
+
+ this.assertText('Hodi Sigmundur 33');
+ }
+
['@test nested components overwrite hash parameters']() {
this.registerComponent('-looked-up', {
template: '{{greeting}} {{name}} {{age}}'
@@ -502,7 +572,7 @@ moduleFor('Components test: contextual components', class extends RenderingTest
}, 'You cannot specify both a positional param (at position 0) and the hash argument `name`.');
}
- ['@test conflicting positional and hash parameters raise and assertion if in the same component context with prior curried positional params']() {
+ ['@test conflicting positional and hash parameters raise an assertion if in the same component context with prior curried positional params']() {
this.registerComponent('-looked-up', {
ComponentClass: Component.extend().reopenClass({
positionalParams: ['name']
| false |
Other
|
emberjs
|
ember.js
|
2f135f97081443881bd063cd26ace65ab9f94a6e.json
|
Remove hasHelper method used only in assertion
|
packages/ember-glimmer/lib/resolver.ts
|
@@ -164,14 +164,6 @@ export default class RuntimeResolver implements IRuntimeResolver<OwnedTemplateMe
}
// end CompileTimeLookup
- hasHelper(name: string, {owner, moduleName}: OwnedTemplateMeta): boolean {
- if (name === 'component' || this.builtInHelpers[name]) {
- return true;
- }
- let options = { source: `template:${moduleName}` };
- return owner.hasRegistration(`helper:${name}`, options) || owner.hasRegistration(`helper:${name}`);
- }
-
// needed for latebound
private handle(obj: any | null | undefined) {
if (obj === undefined || obj === null) {
| true |
Other
|
emberjs
|
ember.js
|
2f135f97081443881bd063cd26ace65ab9f94a6e.json
|
Remove hasHelper method used only in assertion
|
packages/ember-glimmer/lib/syntax.ts
|
@@ -15,7 +15,6 @@ import { hashToArgs } from './syntax/utils';
import { wrapComponentClassAttribute } from './utils/bindings';
function refineInlineSyntax(name: string, params: Option<Core.Params>, hash: Option<Core.Hash>, builder: OpcodeBuilder<OwnedTemplateMeta>): boolean {
- console.log('fail');
assert(
`You attempted to overwrite the built-in helper "${name}" which is not allowed. Please rename the helper.`,
!(
@@ -54,7 +53,15 @@ function refineBlockSyntax(name: string, params: Core.Params, hash: Core.Hash, t
assert(
`Helpers may not be used in the block form, for example {{#${name}}}{{/${name}}}. Please use a component, or alternatively use the helper in combination with a built-in Ember helper, for example {{#if (${name})}}{{/if}}.`,
- !builder.resolver.resolver.hasHelper(name, builder.referrer)
+ !(() => {
+ const { resolver } = builder.resolver;
+ const { owner, moduleName } = builder.referrer;
+ if (name === 'component' || resolver.builtInHelpers[name]) {
+ return true;
+ }
+ let options = { source: `template:${moduleName}` };
+ return owner.hasRegistration(`helper:${name}`, options) || owner.hasRegistration(`helper:${name}`);
+ })()
);
return false;
| true |
Other
|
emberjs
|
ember.js
|
d26676cab6a1e60ae5cd7985675f8314c89cb2f4.json
|
remove unused jQueryDisabled flag
|
packages/ember-glimmer/tests/integration/event-dispatcher-test.js
|
@@ -6,7 +6,6 @@ import {
run
} from 'ember-metal';
import { EMBER_IMPROVED_INSTRUMENTATION } from 'ember/features';
-import { jQueryDisabled } from 'ember-views';
let canDataTransfer = !!document.createEvent('HTMLEvents').dataTransfer;
| false |
Other
|
emberjs
|
ember.js
|
c27f2cd20a16fca45094e6e81fd14042ac8a01d9.json
|
Fix style warning tests
|
packages/ember-glimmer/lib/environment.ts
|
@@ -1,13 +1,11 @@
-import {
- Simple,
-} from '@glimmer/interfaces';
import {
Reference,
} from '@glimmer/reference';
import {
DynamicAttributeFactory,
Environment as GlimmerEnvironment,
PrimitiveReference,
+ SafeString
} from '@glimmer/runtime';
import {
Destroyable, Opaque,
@@ -36,6 +34,10 @@ import {
} from 'ember/features';
import { OwnedTemplate } from './template';
+function isSafeString(value: Opaque): value is SafeString {
+ return typeof value === 'object' && value !== null && typeof (value as any).toHTML === 'function';
+}
+
export interface CompilerFactory {
id: string;
new (template: OwnedTemplate): any;
@@ -217,7 +219,10 @@ export default class Environment extends GlimmerEnvironment {
if (DEBUG) {
class StyleAttributeManager implements DynamicAttributeFactory {
- setAttribute(_dom: Environment, _element: Simple.Element, value: Opaque) {
+
+ constructor() { }
+
+ set(_dom: Environment, value: Opaque) {
warn(constructStyleDeprecationMessage(value), (() => {
if (value === null || value === undefined || isSafeString(value)) {
return true;
@@ -226,7 +231,7 @@ if (DEBUG) {
})(), { id: 'ember-htmlbars.style-xss-warning' });
}
- updateAttribute(_dom: Environment, _element: Element, value: Opaque) {
+ update(_dom: Environment, value: Opaque) {
warn(constructStyleDeprecationMessage(value), (() => {
if (value === null || value === undefined || isSafeString(value)) {
return true;
@@ -236,12 +241,11 @@ if (DEBUG) {
}
}
- // let STYLE_ATTRIBUTE_MANANGER = new StyleAttributeManager();
Environment.prototype.attributeFor = function (element, attribute, isTrusting) {
- // if (attribute === 'style' && !isTrusting) {
- // return STYLE_ATTRIBUTE_MANANGER;
- // }
+ if (attribute === 'style' && !isTrusting) {
+ return StyleAttributeManager;
+ }
return GlimmerEnvironment.prototype.attributeFor.call(this, element, attribute, isTrusting);
};
| false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.