_buildOptions(defaultOptions = {}) { const owner = getOwner(this); if (owner) { return assign(defaultOptions, owner.lookup('config:in-viewport')); } }
/** * pares the model data and create ModelContainers with ModelProperty * classes * * @private * @method createModelContainer * @param target {class} calling class `this` instance * @param model {object[]} array of model objects * @param metaData {object[]} array of model meta objects * @return {object[]} */ function createModelContainer(target, model, metaData) { assert('model is required for createModelContainer', !isNone(model) && typeof model === 'object'); assert('metaData is required for createModelContainer', !isEmpty(metaData) && Array.isArray(metaData)); // create container const owner = getOwner(model); const container = ModelContainer.create(owner.ownerInjection(), { model }); // create modelProps const modelProps = metaData.map(meta => { const id = get(meta, 'id'); const attrName = get(meta, 'modelAttr'); const opts = { container, id, attrName }; if (get(meta, 'isImage')) { opts.isImage = true; } if (get(meta, 'formatCurrency')) { opts.formatCurrency = true; } if (get(meta, 'formatTime')) { opts.formatTime = true; } return ModelProperty.create(opts); }); // set modelProps on container set(container, 'modelProps', modelProps); // create child containers if (!isEmpty(get(model, get(target, 'childModelPath')))) { set(container, 'children', get(model, get(target, 'childModelPath')).map(child => createModelContainer(child, metaData))); } else { set(container, 'children', []); } return container; }
breadcrumbs: computed('router.currentURL', 'router.currentRouteName', function() { const owner = getOwner(this); const allRoutes = (this.get('router.currentRouteName') || '') .split('.') .without('') .map((segment, index, allSegments) => allSegments.slice(0, index + 1).join('.')); let crumbs = []; allRoutes.forEach(routeName => { const route = owner.lookup(`route:${routeName}`); // Routes can reset the breadcrumb trail to start anew even // if the route is deeply nested. if (route.resetBreadcrumbs) { crumbs = []; } // Breadcrumbs are either an array of static crumbs // or a function that returns breadcrumbs given the current // model for the route's controller. let breadcrumbs = route.breadcrumbs || []; if (typeof breadcrumbs === 'function') { breadcrumbs = breadcrumbs(route.get('controller.model')) || []; } crumbs.push(...breadcrumbs); }); return crumbs; }),
this.beforeModel = function() { const session = getOwner(this).lookup('session:main'); return session.restore().then( () => originalBeforeModel.apply(this, arguments), () => originalBeforeModel.apply(this, arguments) ); };
function createSubject(attrs) { const owner = getOwner(this); owner.resolveRegistration('controller:test-subject').reopen(merge({ date: date(0), shortDate: format('date', 'MM/DD') }, attrs)); return this.subject(); }
controlComponent: computed('controlType', function() { const formComponent = this.get('formComponent'); const controlType = this.get('controlType'); const componentName = `${formComponent}/element/control/${controlType}`; if (getOwner(this).hasRegistration(`component:${componentName}`)) { return componentName; } return `${formComponent}/element/control/input`; }),
function createValidationError(model) { const messageResolver = lookupMessageResolver(getOwner(model)); const errors = model.get('errors'); let message = messageResolver.resolveMessage('error'); if(isEmpty(message)) { message = get(defaultMessages, 'error'); } return new ValidationError(message, errors); }
transform: computed('type', function() { let attributeType = this.get('type'); if (!attributeType) { return null; } let transform = getOwner(this).lookup(`transform:${attributeType}`); assert(`Unable to find transform for '${attributeType}'`, !!transform); return transform; })
columns: computed('model', function() { let adapter = getOwner(this).lookup('data-adapter:main'); let recordType = this.get('recordType'); let type = adapter.getModelTypes().findBy('name', recordType); let { klass } = type; let keys = emberArray(['id']); klass.eachAttribute(function(key) { keys.push(key); }); return keys; }),
context.render = function(template) { if (!template) { throw new Error('in a component integration test you must pass a template to `render()`'); } if (isArray(template)) { template = template.join(''); } if (typeof template === 'string') { template = Ember.Handlebars.compile(template); } var templateFullName = 'template:-undertest-' + ++templateId; this.registry.register(templateFullName, template); var stateToRender = { owner: getOwner ? getOwner(module.container) : undefined, into: undefined, outlet: 'main', name: 'index', controller: module.context, ViewClass: undefined, template: module.container.lookup(templateFullName), outlets: {}, }; if (hasOutletTemplate) { stateToRender.name = 'index'; outletState.outlets.main = { render: stateToRender, outlets: {} }; } else { stateToRender.name = 'application'; outletState = { render: stateToRender, outlets: {} }; } run(() => { toplevelView.setOutletState(outletState); }); if (!hasRendered) { run(module.component, 'appendTo', '#ember-testing'); hasRendered = true; } if (EmberENV._APPLICATION_TEMPLATE_WRAPPER !== false) { // ensure the element is based on the wrapping toplevel view // Ember still wraps the main application template with a // normal tagged view context._element = element = document.querySelector('#ember-testing > .ember-view'); } else { context._element = element = document.querySelector('#ember-testing'); } };
isFastBoot: computed(function() { if (!getOwner) { // Ember.getOwner is available as of Ember 2.3, while FastBoot requires 2.4. So just return false... return false; } let owner = getOwner(this); if (!owner) { return false; } let fastboot = owner.lookup('service:fastboot'); if (!fastboot) { return false; } return get(fastboot, 'isFastBoot'); }),
selectedDidChange: observer('selectedApp', function() { // Change iframe being debugged let url = '/'; let applicationId = this.get('selectedApp'); let list = this.get('port').get('detectedApplications'); let app = getOwner(this).lookup('application:main'); run(app, app.reset); let router = app.__container__.lookup('router:main'); let port = app.__container__.lookup('port:main'); port.set('applicationId', applicationId); port.set('detectedApplications', list); // start app.boot().then(() => { router.location.setURL(url); run(app.__deprecatedInstance__, 'handleURL', url); }); }),
test('it renders', function(assert) { let owner = getOwner(this); // Set any properties with this.set('myProperty', 'value'); // Handle any actions with this.on('myAction', function(val) { ... }); this.set('model', [ EmberObject.create(owner.ownerInjection(), {name: 'Bob Thomas', occupation: 'bullfighter', age: 32}), EmberObject.create(owner.ownerInjection(), {name: 'John Smith', occupation: 'astronaut', age: 39}) ]); this.set('meta', [ {header: 'name', sortable: false}, {header: 'occupation', sortable: false}, {header: 'age', sortable: false} ]); this.render(hbs`{{bc-sortable-list model=model meta=meta}}`); assert.notEqual(this.$().text().trim().length, 0); });
beforeEach(function() { session = { restore() {} }; ApplicationRoute = Route.extend({ beforeModel() { return RSVP.resolve('test'); } }); resolveStub.withArgs('route:application').returns(ApplicationRoute); setupSessionRestoration(registry); route = ApplicationRoute.create({ container: {} }); if (setOwner) { setOwner(route, { lookup() {} }); } const owner = getOwner(route); sinon.stub(owner, 'lookup').withArgs('session:main').returns(session); });
/* ember-container-inject-owner is a new feature in Ember 2.3 that finally provides a public API for looking items up. This function serves as a super simple polyfill to avoid triggering deprecations. */ function getOwner(context) { let owner; if (emberGetOwner) { owner = emberGetOwner(context); } else if (context.container) { owner = context.container; } if (owner && owner.lookupFactory && !owner._lookupFactory) { // `owner` is a container, we are just making this work owner._lookupFactory = function() { return owner.lookupFactory(...arguments); }; owner.register = function() { let registry = owner.registry || owner._registry || owner; return registry.register(...arguments); }; } return owner; }
config: computed(function() { return getOwner(this).resolveRegistration('config:environment'); }),
refreshModel: true, }, }, secretParam() { let { secret } = this.paramsFor(this.routeName); return secret ? normalizePath(secret) : ''; }, enginePathParam() { let { backend } = this.paramsFor('vault.cluster.secrets.backend'); return backend; }, beforeModel() { let owner = getOwner(this); let secret = this.secretParam(); let backend = this.enginePathParam(); let { tab } = this.paramsFor('vault.cluster.secrets.backend'); let secretEngine = this.store.peekRecord('secret-engine', backend); let type = secretEngine && secretEngine.get('engineType'); if (!type || !SUPPORTED_BACKENDS.includes(type)) { return this.transitionTo('vault.cluster.secrets'); } if (this.routeName === 'vault.cluster.secrets.backend.list' && !secret.endsWith('/')) { return this.replaceWith('vault.cluster.secrets.backend.list', secret + '/'); } let modelType = this.getModelType(backend, tab); return this.pathHelp.getNewModel(modelType, owner, backend).then(() => { this.store.unloadAll('capabilities'); });
function createSubject(attrs) { return getOwner(this).resolveRegistration('object:empty').extend($.extend(attrs, { container: this.container, registry: this.registry })).create(); }
if (!this._busy) { this._busy = true; let { authenticator: authenticatorFactory } = (content.authenticated || {}); if (authenticatorFactory) { delete content.authenticated.authenticator; const authenticator = this._lookupAuthenticator(authenticatorFactory); authenticator.restore(content.authenticated).then((authenticatedContent) => { this.set('content', content); this._busy = false; this._setup(authenticatorFactory, authenticatedContent, true); }, (err) => { debug(`The authenticator "${authenticatorFactory}" rejected to restore the session - invalidating…`); if (err) { debug(err); } this._busy = false; this._clearWithContent(content, true); }); } else { this._busy = false; this._clearWithContent(content, true); } } }); }, _lookupAuthenticator(authenticator) { return getOwner(this).lookup(authenticator); } });
'model:diagnosis', 'model:operation-report', 'model:operative-plan', 'model:payment', 'model:price-profile', 'service:i18n', 'service:session', 'util:i18n/compile-template', 'util:i18n/missing-message' ], beforeEach() { // set the locale and the config this.container.lookup('service:i18n').set('locale', 'en'); this.registry.register('locale:en/config', localeConfig); getOwner(this).inject('model', 'i18n', 'service:i18n'); // register t helper this.registry.register('helper:t', tHelper); } }); test('displayAddress', function(assert) { let patient = this.subject({ address: '123 Main St.', address2: 'Apt #2', address4: 'Test' }); assert.strictEqual(patient.get('displayAddress'), '123 Main St., Apt #2, Test'); });
import Route from '@ember/routing/route'; import { getOwner } from '@ember/application'; export default Route.extend({ model() { return getOwner(this).lookup('data-adapter:main').getModelTypes().map(function(type) { return type.name; }); } });
/* global IxMap */ import Route from '@ember/routing/route'; import { getOwner } from '@ember/application'; export default Route.extend({ setupController(controller, model) { this._super(controller, model); let applicationInstance = getOwner(this).application; if(!applicationInstance.exchangesList){ applicationInstance.exchangesList = IxMap.Map.showAllExchanges(); } controller.set("model", applicationInstance.exchangesList); } });
fastboot: computed(function() { return getOwner(this).lookup('service:fastboot'); }),
category, catalogId } }); }, launch(id, onlyAlternate) { if ( onlyAlternate && !isAlternate(event) ) { return false; } this.transitionToRoute(this.get('launchRoute'), id); }, refresh() { let catalogTab = getOwner(this).lookup('route:catalog-tab'); catalogTab.send('refresh'); }, }, catalogId: computed('catalogController.catalogId', 'catalogController.clusterCatalogId', 'catalogController.projectCatalogId', function() { const clusterCatalogId = get(this, 'catalogController.clusterCatalogId') const projectCatalogId = get(this, 'catalogController.projectCatalogId') const catalogId = get(this, 'catalogController.catalogId') let out = '' if (catalogId) { out = catalogId } if (clusterCatalogId) { out = clusterCatalogId.split(':')[1]
refreshModel: true, }, }, getClusterId(params) { const { cluster_name } = params; const cluster = this.modelFor('vault').findBy('name', cluster_name); return cluster ? cluster.get('id') : null; }, clearNonGlobalModels() { // this method clears all of the ember data cached models except // the model types blacklisted in `globalNamespaceModels` let store = this.store; let modelsToKeep = this.get('globalNamespaceModels'); for (let model of getOwner(this) .lookup('data-adapter:main') .getModelTypes()) { let { name } = model; if (modelsToKeep.includes(name)) { return; } store.unloadAll(name); } }, beforeModel() { const params = this.paramsFor(this.routeName); this.clearNonGlobalModels(); this.get('namespaceService').setNamespace(params.namespaceQueryParam); const id = this.getClusterId(params);
isLoading: false, nextPage: null, currentUser: service(), logger: service(), unreadCountWithLimit: computed('model.unreadCount', function () { const count = this.model.unreadCount; return count > 99 ? '99+' : count; }), hasUnread: gt('model.unreadCount', 0), init() { this._super(...arguments); this.set('model', WdsOnSiteNotificationsModel.create(getOwner(this).ownerInjection())); }, loadUnreadNotificationCount() { return this.model .loadUnreadNotificationCount() .catch((err) => { this.logger.warn(`Couldn't load notification count`, err); }); }, loadFirstPage() { if ( this.isLoading === true || this.nextPage !== null || this.firstPageLoaded === true
import { getOwner } from '@ember/application'; import { notEmpty } from '@ember/object/computed'; import { inject as service } from '@ember/service'; import Component from '@ember/component'; import addDays from '../utils/add-days'; import safeComputed from '../computed/safe-computed'; export default Component.extend({ account: service(), pinnedFlights: service(), tagName: '', hasPinned: notEmpty('pinnedFlights.pinned'), prevDate: safeComputed('date', date => addDays(date, -1)), nextDate: safeComputed('date', date => addDays(date, 1)), init() { this._super(...arguments); this.set('router', getOwner(this).lookup('router:main')); }, actions: { dateSelected(date) { this.get('router').transitionTo('flights.date', date); }, }, });
let cursorBottom = cursorTop + cursorHeight; let paddingBottom = 0; let distanceFromViewportBottom = cursorBottom - viewportHeight; let atBottom = false; // if we're at the bottom of the doc we should keep the bottom // padding in view, otherwise just scroll to keep the cursor in view if (this._scrollContainer.scrollTop + this._scrollContainer.offsetHeight + 200 >= this._scrollContainer.scrollHeight) { atBottom = true; paddingBottom = parseFloat(getComputedStyle(this.element.parentNode).getPropertyValue('padding-bottom')); } if (cursorBottom > viewportHeight - offsetBottom - paddingBottom) { if (atBottom) { this._scrollContainer.scrollTop = this._scrollContainer.scrollHeight; } else { this._scrollContainer.scrollTop = scrollTop + offsetBottom + distanceFromViewportBottom + 20; } } } }, // store a reference to the editor for the acceptance test helpers _setExpandoProperty(editor) { let config = getOwner(this).resolveRegistration('config:environment'); if (this.element && config.environment === 'test') { this.element[TESTING_EXPANDO_PROPERTY] = editor; } } });
locale: computed(function(){ return getOwner(this).lookup('validator:locale'); }),
this.set('tooltipsterInstance', componentElement.tooltipster('instance')); }, _getOptions() { const options = this._getStandardOptions(); const pluginOptions = this._getPluginOptions(); for (let option in pluginOptions) { options[option] = pluginOptions[option]; } return options; }, _getStandardOptions() { const options = {}; const addonConfig = getOwner(this).resolveRegistration('config:environment')['ember-cli-tooltipster'] || {}; let content = this.get('content') || this.get('title'); this.get('tooltipsterOptions').forEach(option => { if (!isEmpty(this.get(option))) { options[option] = this.get(option); } }); options.trigger = this.get('triggerEvent'); if (isHTMLSafe(content)) { options.content = content.toString(); } this.get('fnOptions').forEach(fn => (options[fn] = $.proxy(this[fn], this)));