ember-source
Version:
A JavaScript framework for creating ambitious web applications
2,604 lines • 81.3 kB
JavaScript
import { privatize } from '../@ember/-internals/container/index.js';
import { E as ENV } from './env-g-kaAFLN.js';
import { isFactory, getOwner } from '../@ember/-internals/owner/index.js';
import { g as guidFor } from './guid-Cbq2sNV_.js';
import { constructStyleDeprecationMessage, getViewId, getViewElement } from '../@ember/-internals/views/lib/system/utils.js';
import { deprecate, warn } from '../@ember/debug/index.js';
import { schedule, _backburner, _getCurrentRunLoop } from '../@ember/runloop/index.js';
import { associateDestroyableChild, isDestroyed, destroy, registerDestructor, isDestroying } from '../@glimmer/destroyable/index.js';
import { artifacts } from '../@glimmer/program/index.js';
import { R as RuntimeOpImpl } from './program-DlgjqLa6.js';
import { v as valueForRef, U as UNDEFINED_REFERENCE, c as createComputeRef, i as isConstRef, a as createConstRef, d as isUpdatableRef, j as createInvokableRef, k as createReadOnlyRef, l as createUnboundRef, h as createDebugAliasRef, g as childRefFromParts, u as updateRef } from './reference-BqOLhKFy.js';
import { c as clientBuilder } from './api-C0PAtEgQ.js';
import { E as EMPTY_ARGS, c as createCapturedArgs, b as EMPTY_POSITIONAL, d as curry } from './arguments-CDkbOqTS.js';
import { g as runtimeOptions, i as inTransaction, r as renderComponent$1, d as renderMain } from './render-87_sKZ_k.js';
import { d as dict } from './collections-DPkjqeA3.js';
import { u as unwrapTemplate, a as CurlyComponentManager, i as initialRenderInstrumentDetails, p as processComponentInitializationAssertions, b as ComponentStateBucket, D as DIRTY_TAG, c as isCurlyManager, B as BOUNDS } from './curly-Ei5G8jhk.js';
import { C as CONSTANT_TAG, c as consumeTag, z as isTracking, e as debug, D as DIRTY_TAG$1, r as createTag, a as valueForTag, k as CURRENT_TAG, v as validateTag } from './cache-DGDPVCpC.js';
import { h as hasDOM } from './index-BGP1rw3B.js';
import { _instrumentStart } from '../@ember/instrumentation/index.js';
import { c as capabilityFlagsFrom } from './capabilities-CajW4QjE.js';
import { t as templateFactory } from './index-DaFzpTIE.js';
import { assert } from '../@ember/debug/lib/assert.js';
import { g as getFactoryFor } from './container-BzzHmCNj.js';
import { g as get, b as _getProp } from './property_get-CRP7MFz_.js';
import { _ as _setProp, s as set } from './property_set-qCUylPEK.js';
import { g as getDebugName } from './get-debug-name-CSniHBsn.js';
import setGlobalContext from '../@glimmer/global-context/index.js';
import { t as tagForObject, o as objectAt, a as tagForProperty } from './chain-tags-uWSImHzB.js';
import { isEmberArray } from '../@ember/array/-internals.js';
import { i as isObject } from './spec-BXl1reqK.js';
import { t as tagFor } from './meta-BqC7f9Ia.js';
import { contentFor } from '../@ember/-internals/runtime/lib/mixins/-proxy.js';
import { i as isProxy } from './is_proxy-Bzg0d4m4.js';
import { i as internalHelper } from './internal-helper-CKrni0b_.js';
import { i as isHTMLSafe } from './index-D-xTBV4B.js';
import isArray from '../@ember/array/lib/is-array.js';
import { g as getComponentTemplate } from './template-R_5UMHhb.js';
import { c as hasInternalComponentManager, j as setInternalHelperManager, g as getInternalComponentManager } from './api-DuLOZMO_.js';
import { h as hash, f as fn, a as array } from './hash-Bg4r3CU4.js';
import { g as get$1, c as concat } from './get-B4o_4OLA.js';
import { o as on } from './on-CQqC2-wL.js';
import { T as TEMPLATE_ONLY_COMPONENT_MANAGER, t as templateOnlyComponent } from './template-only-Cu639ICT.js';
import { i as isClassicHelper, C as CLASSIC_HELPER_MANAGER } from './helper--ZiOCQkd.js';
import { dasherize } from '../@ember/-internals/string/index.js';
import { a as uniqueId } from './unique-id-Csxuh1I7.js';
import { generateControllerFactory } from '../@ember/routing/lib/generate_controller.js';
import { E as EvaluationContextImpl } from './program-context-Dq8xN2HI.js';
function instrumentationPayload$1(def) {
// "main" used to be the outlet name, keeping it around for compatibility
return {
object: `${def.name}:main`
};
}
const CAPABILITIES$2 = {
dynamicLayout: false,
dynamicTag: false,
prepareArgs: false,
createArgs: false,
attributeHook: false,
elementHook: false,
createCaller: false,
dynamicScope: true,
updateHook: false,
createInstance: true,
wrapped: false,
willDestroy: false,
hasSubOwner: false
};
const CAPABILITIES_MASK$1 = capabilityFlagsFrom(CAPABILITIES$2);
class OutletComponentManager {
create(_owner, definition, _args, env, dynamicScope) {
let parentStateRef = dynamicScope.get('outletState');
let currentStateRef = definition.ref;
// This is the actual primary responsibility of the outlet component –
// it represents the switching from one route component/template into
// the next. The rest only exists to support the debug render tree and
// the old-school (and unreliable) instrumentation.
dynamicScope.set('outletState', currentStateRef);
let state = {
finalize: _instrumentStart('render.outlet', instrumentationPayload$1, definition)
};
if (env.debugRenderTree !== undefined) {
let parentState = valueForRef(parentStateRef);
let parentOwner = parentState?.render?.owner;
let currentState = valueForRef(currentStateRef);
let currentOwner = currentState?.render?.owner;
if (parentOwner && parentOwner !== currentOwner) {
(!(currentOwner != null && 'buildChildEngineInstance' in currentOwner) && assert('Expected currentOwner to be an EngineInstance', currentOwner != null && 'buildChildEngineInstance' in currentOwner));
let engineInstance = currentOwner;
let {
mountPoint
} = engineInstance;
if (mountPoint) {
state.engine = {
mountPoint,
instance: engineInstance
};
}
}
}
return state;
}
getDebugName({
name
}) {
return `{{outlet}} for ${name}`;
}
getDebugCustomRenderTree(_definition, state) {
let nodes = [];
nodes.push({
bucket: state,
type: 'outlet',
// "main" used to be the outlet name, keeping it around for compatibility
name: 'main',
args: EMPTY_ARGS,
instance: undefined
});
if (state.engine) {
nodes.push({
bucket: state.engine,
type: 'engine',
name: state.engine.mountPoint,
args: EMPTY_ARGS,
instance: state.engine.instance
});
}
return nodes;
}
getCapabilities() {
return CAPABILITIES$2;
}
getSelf() {
return UNDEFINED_REFERENCE;
}
didCreate() {}
didUpdate() {}
didRenderLayout(state) {
state.finalize();
}
didUpdateLayout() {}
getDestroyable() {
return null;
}
}
const OUTLET_MANAGER = new OutletComponentManager();
const OUTLET_COMPONENT_TEMPLATE = templateFactory(
/*
<@Component @controller={{@controller}} @model={{@model}} />
*/
{
"id": null,
"block": "[[[8,[30,1],null,[[\"@controller\",\"@model\"],[[30,2],[30,3]]],null]],[\"@Component\",\"@controller\",\"@model\"],[]]",
"moduleName": "(unknown template module)",
"isStrictMode": true
});
class OutletComponent {
// handle is not used by this custom definition
handle = -1;
resolvedName = null;
manager = OUTLET_MANAGER;
capabilities = CAPABILITIES_MASK$1;
compilable;
constructor(owner, state) {
this.state = state;
this.compilable = unwrapTemplate(OUTLET_COMPONENT_TEMPLATE(owner)).asLayout();
}
}
function createRootOutlet(outletView) {
return new OutletComponent(outletView.owner, outletView.state);
}
class RootComponentManager extends CurlyComponentManager {
component;
constructor(component) {
super();
this.component = component;
}
create(_owner, _state, _args, {
isInteractive
}, dynamicScope) {
let component = this.component;
let finalizer = _instrumentStart('render.component', initialRenderInstrumentDetails, component);
dynamicScope.view = component;
let hasWrappedElement = component.tagName !== '';
// We usually do this in the `didCreateElement`, but that hook doesn't fire for tagless components
if (!hasWrappedElement) {
if (isInteractive) {
component.trigger('willRender');
}
component._transitionTo('hasElement');
if (isInteractive) {
component.trigger('willInsertElement');
}
}
{
processComponentInitializationAssertions(component, {});
}
let bucket = new ComponentStateBucket(component, null, CONSTANT_TAG, finalizer, hasWrappedElement, isInteractive);
consumeTag(component[DIRTY_TAG]);
return bucket;
}
}
// ROOT is the top-level template it has nothing but one yield.
// it is supposed to have a dummy element
const ROOT_CAPABILITIES = {
dynamicLayout: true,
dynamicTag: true,
prepareArgs: false,
createArgs: false,
attributeHook: true,
elementHook: true,
createCaller: true,
dynamicScope: true,
updateHook: true,
createInstance: true,
wrapped: true,
willDestroy: false,
hasSubOwner: false
};
class RootComponentDefinition {
// handle is not used by this custom definition
handle = -1;
resolvedName = '-top-level';
state;
manager;
capabilities = capabilityFlagsFrom(ROOT_CAPABILITIES);
compilable = null;
constructor(component) {
this.manager = new RootComponentManager(component);
let factory = getFactoryFor(component);
(!(factory !== undefined) && assert('missing factory for component', factory !== undefined));
this.state = factory;
}
}
/**
@module @ember/helper
*/
/**
The `{{#each}}` keyword loops over elements in a collection. It is an extension
of the base Handlebars `{{#each}}` helper.
The default behavior of `{{#each}}` is to yield its inner block once for every
item in an array passing the item as the first block parameter.
```gjs {data-filename="app/components/developer-list.gjs"}
import Component from '@glimmer/component';
export default class DeveloperList extends Component {
developers = [
{ name: 'Yehuda' },
{ name: 'Tom' },
{ name: 'Paul' },
];
<template>
<ul>
{{#each this.developers as |person|}}
<li>Hello, {{person.name}}!</li>
{{/each}}
</ul>
</template>
}
```
The same rules apply to arrays of primitives:
```app/components/developer-names.gjs
import Component from '@glimmer/component';
export default class DeveloperNames extends Component {
developerNames = ['Yehuda', 'Tom', 'Paul'];
<template>
<ul>
{{#each this.developerNames as |name|}}
<li>Hello, {{name}}!</li>
{{/each}}
</ul>
</template>
}
```
`{{#each}}` also supports native JavaScript [`Set`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set)
values and other iterables:
```gjs {data-filename="app/components/developer-set.gjs"}
import Component from '@glimmer/component';
export default class DeveloperSet extends Component {
developers = new Set([
{ name: 'Yehuda' },
{ name: 'Tom' },
{ name: 'Paul' },
]);
<template>
<ul>
{{#each this.developers as |person|}}
<li>Hello, {{person.name}}!</li>
{{/each}}
</ul>
</template>
}
```
During iteration, the index of each item in the array is provided as a second
block parameter:
```app/components/developer-list-with-index.gjs
import Component from '@glimmer/component';
export default class DeveloperListWithIndex extends Component {
developers = [
{ name: 'Yehuda' },
{ name: 'Tom' },
{ name: 'Paul' },
];
<template>
<ul>
{{#each this.developers as |person index|}}
<li>Hello, {{person.name}}! You're number {{index}} in line</li>
{{/each}}
</ul>
</template>
}
```
`#each` is a keyword and does not need to be imported.
### Specifying Keys
In order to improve rendering speed, Ember will try to reuse the DOM elements
where possible. Specifically, if the same item is present in the array both
before and after the change, its DOM output will be reused.
The `key` option is used to tell Ember how to determine if the items in the
array being iterated over with `{{#each}}` has changed between renders. By
default the item's object identity is used.
This is usually sufficient, so in most cases, the `key` option is simply not
needed. However, in some rare cases, the objects' identities may change even
though they represent the same underlying data.
For example, mapping over `people` produces a new array of new objects on each
render. Use `key` so Ember can match items across those renders:
```gjs {data-filename="app/components/mapped-developers.gjs"}
import Component from '@glimmer/component';
export default class MappedDevelopers extends Component {
people = [
{ name: 'Yehuda' },
{ name: 'Tom' },
{ name: 'Paul' },
];
get developers() {
return this.people.map((person) => {
return { ...person, type: 'developer' };
});
}
<template>
<ul>
{{#each this.developers key="name" as |person|}}
<li>Hello, {{person.name}}!</li>
{{/each}}
</ul>
</template>
}
```
By doing so, Ember will use the value of the property specified (`person.name`
in the example) to find a "match" from the previous render. That is, if Ember
has previously seen an object from the `developers` array with a matching
name, its DOM elements will be re-used.
There are two special values for `key`:
* `@index` - The index of the item in the array.
* `@identity` - The item in the array itself.
### {{else}} condition
`{{#each}}` can have a matching `{{else}}`. The contents of this block will render
if the collection is empty.
```gjs {data-filename="app/components/available-developers.gjs"}
import Component from '@glimmer/component';
export default class AvailableDevelopers extends Component {
developers = [];
<template>
<ul>
{{#each this.developers as |person|}}
<li>{{person.name}} is available!</li>
{{else}}
<li>Sorry, nobody is available for this task.</li>
{{/each}}
</ul>
</template>
}
```
@method each
@for Keywords
@static
@noimport
@public
*/
/**
The `{{#each-in}}` keyword loops over properties on an object, or entries in a
native JavaScript [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map).
For example, given this component definition:
```gjs {data-filename="app/components/developer-details.gjs"}
import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
export default class DeveloperDetails extends Component {
@tracked developer = {
name: 'Shelly Sails',
age: 42,
};
<template>
<ul>
{{#each-in this.developer as |key value|}}
<li>{{key}}: {{value}}</li>
{{/each-in}}
</ul>
</template>
}
```
This template would display all properties on the `developer`
object in a list, outputting their name and age:
```html
<ul>
<li>name: Shelly Sails</li>
<li>age: 42</li>
</ul>
```
The same pattern works with a `Map`:
```gjs {data-filename="app/components/developer-map.gjs"}
import Component from '@glimmer/component';
export default class DeveloperMap extends Component {
map = new Map([
['name', 'Shelly Sails'],
['age', 42],
]);
<template>
<ul>
{{#each-in this.map as |key value|}}
<li>{{key}}: {{value}}</li>
{{/each-in}}
</ul>
</template>
}
```
When a `Map` uses object keys, you can pass `key="@identity"` to explicitly
track entries across re-renders using the JavaScript identity of each key:
```gjs {data-filename="app/components/object-keyed-map.gjs"}
import Component from '@glimmer/component';
export default class ObjectKeyedMap extends Component {
map = new Map([
[{ name: 'one' }, 'foo'],
[{ name: 'two' }, 'bar'],
]);
<template>
<ul>
{{#each-in this.map key="@identity" as |key value|}}
<li>{{key.name}}: {{value}}</li>
{{/each-in}}
</ul>
</template>
}
```
`#each-in` is a keyword and does not need to be imported.
@method each-in
@static
@noimport
@for Keywords
@public
@since 2.1.0
*/
class EachInWrapper {
constructor(inner) {
this.inner = inner;
}
}
const eachIn = internalHelper(({
positional
}) => {
const inner = positional[0];
(!(inner) && assert('expected at least one positional arg', inner));
return createComputeRef(() => {
let iterable = valueForRef(inner);
consumeTag(tagForObject(iterable));
if (isProxy(iterable)) {
// this is because the each-in doesn't actually get(proxy, 'key') but bypasses it
// and the proxy's tag is lazy updated on access
iterable = contentFor(iterable);
}
return new EachInWrapper(iterable);
});
});
function toIterator(iterable) {
if (iterable instanceof EachInWrapper) {
return toEachInIterator(iterable.inner);
} else {
return toEachIterator(iterable);
}
}
function toEachInIterator(iterable) {
if (!isIndexable(iterable)) {
return null;
}
if (Array.isArray(iterable) || isEmberArray(iterable)) {
return ObjectIterator.fromIndexable(iterable);
} else if (isNativeIterable(iterable)) {
return MapLikeNativeIterator.from(iterable);
} else if (hasForEach(iterable)) {
return ObjectIterator.fromForEachable(iterable);
} else {
return ObjectIterator.fromIndexable(iterable);
}
}
function toEachIterator(iterable) {
if (!isObject(iterable)) {
return null;
}
if (Array.isArray(iterable)) {
return ArrayIterator.from(iterable);
} else if (isEmberArray(iterable)) {
return EmberArrayIterator.from(iterable);
} else if (isNativeIterable(iterable)) {
return ArrayLikeNativeIterator.from(iterable);
} else if (hasForEach(iterable)) {
return ArrayIterator.fromForEachable(iterable);
} else {
return null;
}
}
class BoundedIterator {
position = 0;
constructor(length) {
this.length = length;
}
isEmpty() {
return false;
}
memoFor(position) {
return position;
}
next() {
let {
length,
position
} = this;
if (position >= length) {
return null;
}
let value = this.valueFor(position);
let memo = this.memoFor(position);
this.position++;
return {
value,
memo
};
}
}
class ArrayIterator extends BoundedIterator {
static from(iterable) {
return iterable.length > 0 ? new this(iterable) : null;
}
static fromForEachable(object) {
let array = [];
object.forEach(item => array.push(item));
return this.from(array);
}
constructor(array) {
super(array.length);
this.array = array;
}
valueFor(position) {
return this.array[position];
}
}
class EmberArrayIterator extends BoundedIterator {
static from(iterable) {
return iterable.length > 0 ? new this(iterable) : null;
}
constructor(array) {
super(array.length);
this.array = array;
}
valueFor(position) {
return objectAt(this.array, position);
}
}
class ObjectIterator extends BoundedIterator {
static fromIndexable(obj) {
let keys = Object.keys(obj);
if (keys.length === 0) {
return null;
} else {
let values = [];
for (let key of keys) {
let value;
value = obj[key];
// Add the tag of the returned value if it is an array, since arrays
// should always cause updates if they are consumed and then changed
if (isTracking()) {
consumeTag(tagFor(obj, key));
if (Array.isArray(value)) {
consumeTag(tagFor(value, '[]'));
}
}
values.push(value);
}
return new this(keys, values);
}
}
static fromForEachable(obj) {
let keys = [];
let values = [];
let length = 0;
let isMapLike = false;
// Not using an arrow function here so we can get an accurate `arguments`
obj.forEach(function (value, key) {
isMapLike = isMapLike || arguments.length >= 2;
if (isMapLike) {
keys.push(key);
}
values.push(value);
length++;
});
if (length === 0) {
return null;
} else if (isMapLike) {
return new this(keys, values);
} else {
return new ArrayIterator(values);
}
}
constructor(keys, values) {
super(values.length);
this.keys = keys;
this.values = values;
}
valueFor(position) {
return this.values[position];
}
memoFor(position) {
return this.keys[position];
}
}
class NativeIterator {
static from(iterable) {
let iterator = iterable[Symbol.iterator]();
let result = iterator.next();
let {
done
} = result;
if (done) {
return null;
} else {
return new this(iterator, result);
}
}
position = 0;
constructor(iterable, result) {
this.iterable = iterable;
this.result = result;
}
isEmpty() {
return false;
}
next() {
let {
iterable,
result,
position
} = this;
if (result.done) {
return null;
}
let value = this.valueFor(result, position);
let memo = this.memoFor(result, position);
this.position++;
this.result = iterable.next();
return {
value,
memo
};
}
}
class ArrayLikeNativeIterator extends NativeIterator {
valueFor(result) {
return result.value;
}
memoFor(_result, position) {
return position;
}
}
class MapLikeNativeIterator extends NativeIterator {
valueFor(result) {
return result.value[1];
}
memoFor(result) {
return result.value[0];
}
}
function hasForEach(value) {
return value != null && typeof value['forEach'] === 'function';
}
function isNativeIterable(value) {
return value != null && typeof value[Symbol.iterator] === 'function';
}
function isIndexable(value) {
return value !== null && (typeof value === 'object' || typeof value === 'function');
}
function toBool(predicate) {
if (isProxy(predicate)) {
consumeTag(tagForProperty(predicate, 'content'));
return Boolean(get(predicate, 'isTruthy'));
} else if (isArray(predicate)) {
consumeTag(tagForProperty(predicate, '[]'));
return predicate.length !== 0;
} else if (isHTMLSafe(predicate)) {
return Boolean(predicate.toString());
} else {
return Boolean(predicate);
}
}
///////////
// Setup global context
setGlobalContext({
scheduleRevalidate() {
_backburner.ensureInstance();
},
toBool,
toIterator,
getProp: _getProp,
setProp: _setProp,
getPath: get,
setPath: set,
scheduleDestroy(destroyable, destructor) {
schedule('actions', null, destructor, destroyable);
},
scheduleDestroyed(finalizeDestructor) {
schedule('destroy', null, finalizeDestructor);
},
warnIfStyleNotTrusted(value) {
(warn(constructStyleDeprecationMessage(String(value)), (() => {
if (value === null || value === undefined || isHTMLSafe(value)) {
return true;
}
return false;
})(), {
id: 'ember-htmlbars.style-xss-warning'
}));
},
assert(test, msg, options) {
{
let id = options?.id;
let override = VM_ASSERTION_OVERRIDES.filter(o => o.id === id)[0];
(!(test) && assert(override?.message ?? msg, test));
}
},
deprecate(msg, test, options) {
{
let {
id
} = options;
if (id === 'argument-less-helper-paren-less-invocation') {
throw new Error(`A resolved helper cannot be passed as a named argument as the syntax is ` + `ambiguously a pass-by-reference or invocation. Use the ` + `\`{{helper 'foo-helper}}\` helper to pass by reference or explicitly ` + `invoke the helper with parens: \`{{(fooHelper)}}\`.`);
}
let override = VM_DEPRECATION_OVERRIDES.filter(o => o.id === id)[0];
if (!override) throw new Error(`deprecation override for ${id} not found`);
// allow deprecations to be disabled in the VM_DEPRECATION_OVERRIDES array below
if (!override.disabled) {
(!(Boolean(test)) && deprecate(override.message ?? msg, Boolean(test), override));
}
}
}
});
{
debug?.setTrackingTransactionEnv?.({
debugMessage(obj, keyName) {
let dirtyString = keyName ? `\`${keyName}\` on \`${getDebugName?.(obj)}\`` : `\`${getDebugName?.(obj)}\``;
return `You attempted to update ${dirtyString}, but it had already been used previously in the same computation. Attempting to update a value after using it in a computation can cause logical errors, infinite revalidation bugs, and performance issues, and is not supported.`;
}
});
}
///////////
// VM Assertion/Deprecation overrides
const VM_DEPRECATION_OVERRIDES = [{
id: 'setting-on-hash',
until: '4.4.0',
for: 'ember-source',
since: {
available: '3.28.0',
enabled: '3.28.0'
}
}];
const VM_ASSERTION_OVERRIDES = [];
///////////
// Define environment delegate
class EmberEnvironmentDelegate {
enableDebugTooling = ENV._DEBUG_RENDER_TREE;
constructor(owner, isInteractive) {
this.owner = owner;
this.isInteractive = isInteractive;
}
onTransactionCommit() {}
}
/**
@module ember
*/
const disallowDynamicResolution = internalHelper(({
positional,
named
}) => {
const nameOrValueRef = positional[0];
(!(positional.length === 1 && nameOrValueRef) && assert(`[BUG] wrong number of positional arguments, expecting 1, got ${positional.length}`, positional.length === 1 && nameOrValueRef));
let typeRef = named['type'];
let locRef = named['loc'];
let originalRef = named['original'];
(!(typeRef) && assert(`[BUG] expecting \`type\` named argument`, typeRef));
(!(locRef) && assert(`[BUG] expecting \`loc\` named argument`, locRef));
(!(originalRef) && assert(`[BUG] expecting \`original\` named argument`, originalRef)); // Bug: why do these fail?
// assert('[BUG] expecting a string literal for the `type` argument', isConstRef(typeRef));
// assert('[BUG] expecting a string literal for the `loc` argument', isConstRef(locRef));
// assert('[BUG] expecting a string literal for the `original` argument', isConstRef(originalRef));
const type = valueForRef(typeRef);
const loc = valueForRef(locRef);
const original = valueForRef(originalRef);
(!(typeof type === 'string') && assert('[BUG] expecting a string literal for the `type` argument', typeof type === 'string'));
(!(typeof loc === 'string') && assert('[BUG] expecting a string literal for the `loc` argument', typeof loc === 'string'));
(!(typeof original === 'string') && assert('[BUG] expecting a string literal for the `original` argument', typeof original === 'string'));
return createComputeRef(() => {
let nameOrValue = valueForRef(nameOrValueRef);
(!(typeof nameOrValue !== 'string') && assert(`Passing a dynamic string to the \`(${type})\` keyword is disallowed. ` + `(You specified \`(${type} ${original})\` and \`${original}\` evaluated into "${nameOrValue}".) ` + `This ensures we can statically analyze the template and determine which ${type}s are used. ` + `If the ${type} name is always the same, use a string literal instead, i.e. \`(${type} "${nameOrValue}")\`. ` + `Otherwise, import the ${type}s into JavaScript and pass them directly. ` + 'See https://github.com/emberjs/rfcs/blob/master/text/0496-handlebars-strict-mode.md#4-no-dynamic-resolution for details. ' + loc, typeof nameOrValue !== 'string'));
return nameOrValue;
});
});
let helper;
{
helper = args => {
const inner = args.positional[0];
(!(inner) && assert('expected at least one positional arg', inner));
return createComputeRef(() => {
let value = valueForRef(inner);
(!(value !== null && value !== undefined) && assert('You cannot pass a null or undefined destination element to in-element', value !== null && value !== undefined));
return value;
});
};
}
const inElementNullCheckHelper = internalHelper(helper);
const normalizeClassHelper = internalHelper(({
positional
}) => {
return createComputeRef(() => {
let classNameArg = positional[0];
let valueArg = positional[1];
(!(classNameArg && valueArg) && assert('expected at least two positional args', classNameArg && valueArg));
let classNameParts = valueForRef(classNameArg).split('.');
let className = classNameParts[classNameParts.length - 1];
(!(className) && assert('has className', className)); // Always at least one split result
let value = valueForRef(valueArg);
if (value === true) {
return dasherize(className);
} else if (!value && value !== 0) {
return '';
} else {
return String(value);
}
});
});
/**
@module ember
*/
const resolve = internalHelper(({
positional
}, owner) => {
// why is this allowed to be undefined in the first place?
(!(owner) && assert('[BUG] missing owner', owner));
(!(positional.length === 1) && assert(`[BUG] wrong number of positional arguments, expecting 1, got ${positional.length}`, positional.length === 1));
let fullNameRef = positional[0];
(!(fullNameRef && isConstRef(fullNameRef)) && assert('[BUG] expecting a string literal as argument', fullNameRef && isConstRef(fullNameRef)));
let fullName = valueForRef(fullNameRef);
(!(typeof fullName === 'string') && assert('[BUG] expecting a string literal as argument', typeof fullName === 'string'));
(!((s => s.split(':').length === 2)(fullName)) && assert('[BUG] expecting a valid full name', (s => s.split(':').length === 2)(fullName)));
{
let [type, name] = fullName.split(':');
(!(owner.hasRegistration(fullName)) && assert(`Attempted to invoke \`(-resolve "${fullName}")\`, but ${name} was not a valid ${type} name.`, owner.hasRegistration(fullName)));
}
return createConstRef(owner.factoryFor(fullName)?.class, `(-resolve "${fullName}")`);
});
/**
@module ember
*/
/**
This reference is used to get the `[]` tag of iterables, so we can trigger
updates to `{{each}}` when it changes. It is put into place by a template
transform at build time, similar to the (-each-in) helper
*/
const trackArray = internalHelper(({
positional
}) => {
const inner = positional[0];
(!(inner) && assert('expected at least one positional arg', inner));
return createComputeRef(() => {
let iterable = valueForRef(inner);
if (isObject(iterable)) {
consumeTag(tagForProperty(iterable, '[]'));
}
return iterable;
});
});
/**
@module @ember/helper
*/
/**
The `mut` helper is a shortcut for updating for args.
However, defining update functions on your backing class is preferable to using `mut`.
More directly: Don't use `mut`.
The `mut` helper, when used with `fn`, will return a function that
sets the value passed to `mut` to its first argument. As an example, we can create a
button that increments a value passing the value directly to the `fn`:
```handlebars
<MyChild @childClickCount={{this.totalClicks}} @clickCountChange={{fn (mut this.totalClicks)}} />
```
The child `Component` would invoke the function with the new click count:
```gjs {data-filename="app/components/my-child.gjs"}
import Component from '@glimmer/component';
import { action } from '@ember/object';
export default class MyChild extends Component {
@action
update() {
this.args.clickCountChange(this.args.childClickCount + 1);
}
<template>
<button {{on "click" this.update}}>
Click me!
</button>
</template>
}
```
The `mut` helper changes the `totalClicks` value to what was provided as the `fn` argument.
@method mut
@param {Object} [attr] the "two-way" attribute that can be modified.
@static
@for Keywords
@public
*/
const mut = internalHelper(({
positional
}) => {
let ref = positional[0];
(!(ref) && assert('expected at least one positional arg', ref)); // TODO: Improve this error message. This covers at least two distinct
// cases:
//
// 1. (mut "not a path") – passing a literal, result from a helper
// invocation, etc
//
// 2. (mut receivedValue) – passing a value received from the caller
// that was originally derived from a literal, result from a helper
// invocation, etc
//
// This message is alright for the first case, but could be quite
// confusing for the second case.
(!(isUpdatableRef(ref)) && assert('You can only pass a path to mut', isUpdatableRef(ref)));
return createInvokableRef(ref);
});
/**
@module @ember/helper
*/
/**
The `readonly` helper let's you specify that a binding is one-way only,
instead of two-way.
This is a vestigial helper from the days of `@ember/component` and does not apply to
components extending from `@glimmer/component`.
When you pass a `readonly` binding from an outer context (e.g. parent component),
to to an inner context (e.g. child component), you are saying that changing that
property in the inner context does not change the value in the outer context.
To specify that a binding is read-only, when invoking the child `Component`:
```app/components/my-parent.js
export default class MyParent extends Component {
totalClicks = 3;
}
```
Now, when you update `childClickCount`:
```app/components/my-child.js
export default class MyChild extends Component {
click() {
this.incrementProperty('childClickCount');
}
}
```
The value updates in the child component, but not the parent component:
```app/templates/components/my-child.hbs
{{log childClickCount}} //-> 4
```
```app/templates/components/my-parent.hbs
{{log totalClicks}} //-> 3
<MyChild @childClickCount={{readonly totalClicks}} />
```
or
```app/templates/components/my-parent.hbs
{{log totalClicks}} //-> 3
{{my-child childClickCount=(readonly totalClicks)}}
```
### Objects and Arrays
When passing a property that is a complex object (e.g. object, array) instead of a primitive object (e.g. number, string),
only the reference to the object is protected using the readonly helper.
This means that you can change properties of the object both on the parent component, as well as the child component.
The `readonly` binding behaves similar to the `const` keyword in JavaScript.
Let's look at an example:
First let's set up the parent component:
```app/components/my-parent.js
import Component from '@ember/component';
export default class MyParent extends Component {
clicks: null,
init() {
this._super(...arguments);
this.set('clicks', { total: 3 });
}
}
```
```app/templates/components/my-parent.hbs
{{log clicks.total}} //-> 3
<MyChild @childClicks={{readonly clicks}} />
```
```app/templates/components/my-parent.hbs
{{log clicks.total}} //-> 3
{{my-child childClicks=(readonly clicks)}}
```
Now, if you update the `total` property of `childClicks`:
```app/components/my-child.js
import Component from '@ember/component';
export default class MyChild extends Component {
click() {
this.get('clicks').incrementProperty('total');
}
}
```
You will see the following happen:
```app/templates/components/my-parent.hbs
{{log clicks.total}} //-> 4
<MyChild @childClicks={{readonly clicks}} />
```
or
```app/templates/components/my-parent.hbs
{{log clicks.total}} //-> 4
{{my-child childClicks=(readonly clicks)}}
```
```app/templates/components/my-child.hbs
{{log childClicks.total}} //-> 4
```
@method readonly
@param {Object} [attr] the read-only attribute.
@for Keywords
@noimport
@static
@private
*/
const readonly = internalHelper(({
positional
}) => {
let firstArg = positional[0];
(!(firstArg) && assert('has first arg', firstArg));
return createReadOnlyRef(firstArg);
});
/**
@module @ember/helper
*/
/**
The `{{unbound}}` helper disconnects the one-way binding of a property,
essentially freezing its value at the moment of rendering. For example,
in this example the display of the variable `name` will not change even
if it is set with a new value:
```handlebars
{{unbound this.name}}
```
Like any helper, the `unbound` helper can accept a nested helper expression.
This allows for custom helpers to be rendered unbound:
```handlebars
{{unbound (some-custom-helper)}}
{{unbound (capitalize this.name)}}
{{! You can use any helper, including unbound, in a nested expression }}
{{capitalize (unbound this.name)}}
```
The `unbound` helper only accepts a single argument, and it return an
unbound value.
`unbound` is a template keyword and does not need to be imported.
@method unbound
@static
@noimport
@for Keywords
@public
*/
const unbound = internalHelper(({
positional,
named
}) => {
(!(positional.length === 1 && Object.keys(named).length === 0) && assert('unbound helper cannot be called with multiple params or hash params', positional.length === 1 && Object.keys(named).length === 0));
return createUnboundRef(valueForRef(positional[0]), '(result of an `unbound` helper)');
});
const CAPABILITIES$1 = {
dynamicLayout: true,
dynamicTag: false,
prepareArgs: false,
createArgs: true,
attributeHook: false,
elementHook: false,
createCaller: true,
dynamicScope: true,
updateHook: true,
createInstance: true,
wrapped: false,
willDestroy: false,
hasSubOwner: true
};
class MountManager {
getDynamicLayout(state) {
let templateFactory = state.engine.lookup('template:application');
return unwrapTemplate(templateFactory(state.engine)).asLayout();
}
getCapabilities() {
return CAPABILITIES$1;
}
getOwner(state) {
return state.engine;
}
create(owner, {
name
}, args, env) {
// 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.
(!('buildChildEngineInstance' in owner) && assert('Expected owner to be an EngineInstance', 'buildChildEngineInstance' in owner));
let engine = owner.buildChildEngineInstance(name);
engine.boot();
let applicationFactory = engine.factoryFor(`controller:application`);
let controllerFactory = applicationFactory || generateControllerFactory(engine, 'application');
let controller;
let self;
let bucket;
let modelRef;
if (args.named.has('model')) {
modelRef = args.named.get('model');
}
if (modelRef === undefined) {
controller = controllerFactory.create();
self = createConstRef(controller, 'this');
bucket = {
engine,
controller,
self,
modelRef
};
} else {
let model = valueForRef(modelRef);
controller = controllerFactory.create({
model
});
self = createConstRef(controller, 'this');
bucket = {
engine,
controller,
self,
modelRef
};
}
if (env.debugRenderTree) {
associateDestroyableChild(engine, controller);
}
return bucket;
}
getDebugName({
name
}) {
return name;
}
getDebugCustomRenderTree(definition, state, args) {
return [{
bucket: state.engine,
instance: state.engine,
type: 'engine',
name: definition.name,
args
}, {
bucket: state.controller,
instance: state.controller,
type: 'route-template',
name: 'application',
args
}];
}
getSelf({
self
}) {
return self;
}
getDestroyable(bucket) {
return bucket.engine;
}
didCreate() {}
didUpdate() {}
didRenderLayout() {}
didUpdateLayout() {}
update(bucket) {
let {
controller,
modelRef
} = bucket;
if (modelRef !== undefined) {
controller.set('model', valueForRef(modelRef));
}
}
}
const MOUNT_MANAGER = new MountManager();
class MountDefinition {
// handle is not used by this custom definition
handle = -1;
state;
manager = MOUNT_MANAGER;
compilable = null;
capabilities = capabilityFlagsFrom(CAPABILITIES$1);
constructor(resolvedName) {
this.resolvedName = resolvedName;
this.state = {
name: resolvedName
};
}
}
/**
@module @ember/helper
*/
/**
The `{{mount}}` helper lets you embed a routeless engine in a template.
Mounting an engine will cause an instance to be booted and its `application`
template to be rendered.
For example, the following template mounts the `ember-chat` engine:
```gjs {data-filename="app/templates/application.gjs"}
{{mount "ember-chat"}}
```
Additionally, you can also pass in a `model` argument that will be
set as the engines model. This can be an existing object:
```hbs
<div>
{{mount 'admin' model=userSettings}}
</div>
```
Or an inline `hash`, and you can even pass components:
```gjs
import SignInButton from '../components/sign-in-button';
<template>
<div>
<h1>Application template!</h1>
{{mount 'admin' model=(hash
title='Secret Admin'
signInButton=SignInButton
)}}
</div>
</template>
```
`mount` is built-in and does not need to be imported.
@method mount
@param {String} name Name of the engine to mount.
@param {Object} [model] Object that will be set as
the model of the engine.
@for Keywords
@static
@noimport
@public
*/
const mountHelper = internalHelper((args, owner) => {
(!(owner) && assert('{{mount}} must be used within a component that has an owner', owner));
let nameRef = args.positional[0];
let captured;
(!(args.positional.length === 1) && assert('You can only pass a single positional argument to the {{mount}} helper, e.g. {{mount "chat-engine"}}.', args.positional.length === 1));
if (args.named) {
let keys = Object.keys(args.named);
let extra = keys.filter(k => k !== 'model');
(!(extra.length === 0) && assert('You can only pass a `model` argument to the {{mount}} helper, ' + 'e.g. {{mount "profile-engine" model=this.profile}}. ' + `You passed ${extra.join(',')}.`, extra.length === 0));
}
captured = createCapturedArgs(args.named, EMPTY_POSITIONAL);
let lastName, lastDef;
return createComputeRef(() => {
let name = valueForRef(nameRef);
if (typeof name === 'string') {
if (lastName === name) {
return lastDef;
}
(!(owner.hasRegistration(`engine:${name}`)) && assert(`You used \`{{mount '${name}'}}\`, but the engine '${name}' can not be found.`, owner.hasRegistration(`engine:${name}`)));
lastName = name;
lastDef = curry(0, new MountDefinition(name), owner, captured, true);
return lastDef;
} else {
(!(name === null || name === undefined) && assert(`Invalid engine name '${name}' specified, engine name must be either a string, null or undefined.`, name === null || name === undefined));
lastDef = null;
lastName = null;
return null;
}
});
});
const CAPABILITIES = {
dynamicLayout: false,
dynamicTag: false,
prepareArgs: false,
createArgs: true,
attributeHook: false,
elementHook: false,
createCaller: false,
dynamicScope: false,
updateHook: false,
createInstance: true,
wrapped: false,
willDestroy: false,
hasSubOwner: false
};
const CAPABILITIES_MASK = capabilityFlagsFrom(CAPABILITIES);
class RouteTemplateManager {
create(_owner, _definition, args) {
let self = args.named.get('controller');
{
self = createDebugAliasRef('this', self);
}
let controller = valueForRef(self);
return {
self,
controller
};
}
getSelf({
self
}) {
return self;
}
getDebugName({
name
}) {
return `route-template (${name})`;
}
getDebugCustomRenderTree({
name
}, state, args) {
return [{
bucket: state,
type: 'route-template',
name,
args,
instance: state.controller
}];
}
getCapabilities() {
return CAPABILITIES;
}
didRenderLayout() {}
didUpdateLayout() {}
didCreate() {}
didUpdate() {}
getDestroyable() {
return null;
}
}
const ROUTE_TEMPLATE_MANAGER = new RouteTemplateManager();
/**
* This "upgrades" a route template into a invocable component. Conceptually
* it can be 1:1 for each unique `Template`, but it's also cheap to construct,
* so unless the stability is desirable for other reasons, it's probably not
* worth caching this.
*/
class RouteTemplate {
// handle is not used by this custom definition
handle = -1;
resolvedName;
state;
manager = ROUTE_TEMPLATE_MANAGER;
capabilities = CAPABILITIES_MASK;
compilable;
constructor(name, template) {
let unwrapped = unwrapTemplate(template);
// TODO This actually seems inaccurate – it ultimately came from the
// outlet's name. Also, setting this overrides `getDebugName()` in that
// message. Is that desirable?
this.resolvedName = name;
this.state = {
name
};
this.compilable = unwrapped.asLayout();
}
}
// TODO a lot these fields are copied from the adjacent existing components
// implementation, haven't looked into who cares about `ComponentDefinition`
// and if it is appropriate here. It seems like this version is intended to
// be used with `curry` which probably isn't necessary here. It could be the
// case that we just want to do something more similar to `InternalComponent`
// (the one we used to implement `Input` and `LinkTo`). For now it follows
// the same pattern to get things going.
function makeRouteTemplate(owner, name, template) {
let routeTemplate = new RouteTemplate(name, template);
return curry(0, routeTemplate, owner, null, true);
}
/**
@module @ember/helper
*/
/**
The `{{outlet}}` helper lets you specify where a child route will render in
your template. An important use of the `{{outlet}}` helper is in your
application's `application.gjs` file:
```gjs {data-filename="app/templates/application.gjs"}
import MyHeader from '../components/my-header';
import MyFooter from '../components/my-footer';
<template>
<MyHeader />
<div class="my-dynamic-content">
<!-- this content will change based on the current route, which depends on the current URL -->
{{outlet}}
</div>
<MyFooter />
</template>
```
See the [routing guide](https://guides.emberjs.com/release/routing/rendering-a-template/) for more
information on how your `route` interacts with the `{{outlet}}` helper.
Note: Your content __will not render__ if there isn't an `{{outlet}}` for it.
`outlet` is built-in and does not need to be imported.
@method outlet
@for Keywords
@static
@noimport
@public
*/
const outletHelper = internalHelper((_args, owner, scope) => {
(!(owner) && assert('Expected owner to be present, {{outlet}} requires an owner', owner));
(!(scope) && assert('Expected dynamic scope to be present. You may have attempted to use the {{outlet}} keyword dynamically. This keyword cannot be used dynamically.', scope));
let outletRef = createComputeRef(() => {
let state = valueForRef(scope.get('outletState'));
return state?.outlets?.main;
});
let lastState = null;
let outlet = null;
return createComputeRef(() => {
let outletState = valueForRef(outletRef);
let state = stateFor(outletRef, outletState);
// This code is deliberately using the behavior in glimmer-vm where in
// <@Component />, the component is considered stabled via `===`, and
// will continue to re-render in-place as long as the `===` holds, but
// when it changes to a different object, it teardown the old component
// (running destructors, etc), and render the component in its place (or
// nothing if the new value is nullish. Here we are carefully exploiting
// that fact, and returns the same stable object so long as it is the
// same route, but return a different one when the route changes. On the
// other hand, changing the model only intentionally do not teardown the
// component and instead re-render in-place.
if (!isStable(state, lastState)) {
lastState = state;
if (state !== null) {
// If we are crossing an engine mount point, this is how the owner
// gets switched.
let outletOwner = outletState?.render?.owner ?? owner;
let named = dict();
// Here we either have a raw template that needs to be normalized,
// or a component that we can render as-is. `RouteTemplate` upgrades
// the template into a component so we can have a unified code path.
// We still store the original `template` value, because we rely on
// its identity for the stability check, and the `RouteTemplate`
// wrapper doesn't dedup for us.
let template = state.template;
let component;
if (hasInternalComponentManager(template)) {
component = template;
} else {
{
// We don't appear to have a standard way or a brand to check, but for the
// purpose of avoiding obvious user errors, this probably gets you close
// enough.
let isTemplate = template => {
if (template === null || typeof template !== 'object') {
return false;
} else {
let t = template;
return t.result === 'ok' || t.result === 'error';
}
};
// We made it past the `TemplateFactory` instantiation before
// getting here, so either we got unlucky where the invalid type
// happens to be a function that didn't mind taking owner as an
// argument, or this was directly set by something like test
// helpers.
if (!isTemplate(template)) {
let label;
try {
label = `\`${String(template)}\``;
} catch {
label = 'an unknown object';
}
(assert(`Failed to render the \`${state.name}\` route: expected ` + `a component or Template object, but got ${label}.`));
}
}
component = makeRouteTemplate(outletOwner, state.name, template);
}
// Component is stable for the lifetime of the outlet
named['Component'] = createConstRef(component, '@Component');
// Controller is stable for the lifetime of the outlet
named['controller'] = createConstRef(state.controller, '@controller');
// Create a ref for the model
let modelRef = childRefFromParts(outletRef, ['render', 'model']);
// Store the value of the model
let model = valueForRef(modelRef);
// Create a compute ref which we pass in as the `{{@model}}` reference
// for the outlet. This ref will update and return the value of the
// model _until_ the outlet itself changes. Once the outlet changes,
// dynamic scope also changes, and so the original model ref would not
// provide the correct updated value. So we stop updating and return
// the _last_ model value for that outlet.
named['model'] = createComputeRef(() => {
if (lastState === state) {
model = valueForRef(modelRef);
}
return model;
});
{
named['model'] = createDebugAliasRef('@model', named['model']);
}
let args = createCapturedArgs(named, EMPTY_POSITIONAL);
// Package up everything
outlet = curry(0, new OutletComponent(owner, state), outletOwner, args, true);
} else {
outlet = null;
}
}
return outlet;
});
});
function stateFor(ref, outlet) {
if (outlet === undefined) return null;
let render = outlet.render;
if (render === undefined) return null;
let template = render.template;
// The type doesn't actually allow for `null`, but if we make it past this
// point it is really important that we have _something_ to render. We could
// assert, but that is probably overly strict for very little to gain.
if (template === undefined || template === null) return null;
return {
ref,
name: render.name,
template,
controller: render.controller
};
}
function isStable(state, lastState) {
if (state === null || lastState === null) {
return false;
}
return state.template === lastState.template && state.controller === lastState.controller;
}
function instrumentationPayload(name) {
return {
object: `component:${name}`
};
}
function componentFor(name, owner) {
let fullName = `component:${name}`;
return owner.factoryFor(fullName) || null;
}
function lookupComponentPair(owner, name) {
let component = componentFor(name, owner);
if (isFactory(component) && component.class) {
let layout = getComponentTemplate(component.class);
if (layout !== undefined) {
return {
component,
layout
};
}
}
if (component === null) {
return null;
} else {
return {
component,
layout: null
};
}
}
const BUILTIN_KEYWORD_HELPERS = {
mut,
readonly,
unbound,
'-hash': hash,
'-each-in': eachIn,
'-normalize-class': normalizeClassHelper,
'-resolve': resolve,
'-track-array': trackArray,
'-mount': mountHelper,
'-outlet': outletHelper,
'-in-el-null': inElementNullCheckHelper
};
const BUILTIN_HELPERS = {
...BUILTIN_KEYWORD_HELPERS,
array,
concat,
fn,
get: get$1,
hash,
'unique-id': uniqueId
};
{
BUILTIN_HELPERS['-disallow-dynamic-resolution'] = disallowDynamicResolution;
}
// With the implementation of RFC #1006(https://rfcs.emberjs.com/id/1006-deprecate-action-template-helper), the `action` modifer was removed. It was the
// only built-in keyword modifier, so this object is currently empty.
const BUILTIN_KEYWORD_MODIFIERS = {};
const BUILTIN_MODIFIERS = {
...BUILTIN_KEYWORD_MODIFIERS,
on
};
const CLASSIC_HELPER_MANAGER_ASSOCIATED = new WeakSet();
class ResolverImpl {
componentDefinitionCache = new Map();
lookupPartial() {
return null;
}
lookupHelper(name, owner) {
(!(!(BUILTIN_HELPERS[name] && owner.hasRegistration(`helper:${name}`))) && assert(`You attempted to overwrite the built-in helper "${name}" which is not allowed. Please rename the helper.`, !(BUILTIN_HELPERS[name] && owner.hasRegistration(`helper:${name}`))));
let helper = BUILTIN_HELPERS[name];
if (helper !== undefined) {
return helper;
}
let factory = owner.factoryFor(`helper:${name}`);
if (factory === undefined) {
return null;
}
let definition = factory.class;
if (definition === undefined) {
return null;
}
if (typeof definition === 'function' && isClassicHelper(definition)) {
// For classic class based helpers, we need to pass the factoryFor result itself rather
// than the raw value (`factoryFor(...).class`). This is because injections are already
// bound in the factoryFor result, including type-based injections
{
// In DEBUG we need to only set the associated value once, otherwise
// we'll trigger an assertion
if (!CLASSIC_HELPER_MANAGER_ASSOCIATED.has(factory)) {
CLASSIC_HELPER_MANAGER_ASSOCIATED.add(factory);
setInternalHelperManager(CLASSIC_HELPER_MANAGER, factory);
}
}
return factory;
}
return definition;
}
lookupBuiltInHelper(name) {
return BUILTIN_KEYWORD_HELPERS[name] ?? null;
}
lookupModifier(name, owner) {
let builtin = BUILTIN_MODIFIERS[name];
if (builtin !== undefined) {
return builtin;
}
let modifier = owner.factoryFor(`modifier:${name}`);
if (modifier === undefined) {
return null;
}
return modifier.class || null;
}
lookupBuiltInModifier(name) {
return BUILTIN_KEYWORD_MODIFIERS[name] ?? null;
}
lookupComponent(name, owner) {
let pair = lookupComponentPair(owner, name);
if (pair === null) {
(!(name !== 'text-area') && assert('Could not find component `<TextArea />` (did you mean `<Textarea />`?)', name !== 'text-area'));
return null;
}
let template = null;
let key;
if (pair.component === null) {
key = template = pair.layout(owner);
} else {
key = pair.component;
}
let cachedComponentDefinition = this.componentDefinitionCache.get(key);
if (cachedComponentDefinition !== undefined) {
return cachedComponentDefinition;
}
if (template === null && pair.layout !== null) {
template = pair.layout(owner);
}
let finalizer = _instrumentStart('render.getComponentDefinition', instrumentationPayload, name);
let definition = null;
if (pair.component === null) {
definition = {
state: templateOnlyComponent(undefined, name),
manager: TEMPLATE_ONLY_COMPONENT_MANAGER,
template
};
} else {
let factory = pair.component;
(!(factory.class !== undefined) && assert(`missing component class ${name}`, factory.class !== undefined));
let ComponentClass = factory.class;
let manager = getInternalComponentManager(ComponentClass);
definition = {
state: isCurlyManager(manager) ? factory : ComponentClass,
manager,
template
};
}
finalizer();
this.componentDefinitionCache.set(key, definition);
(!(!(definition === null && name === 'text-area')) && assert('Could not find component `<TextArea />` (did you mean `<Textarea />`?)', !(definition === null && name === 'text-area')));
return definition;
}
}
// We use the `InternalOwner` notion here because we actually need all of its
// API for using with renderers (normally, it will be `EngineInstance`).
// We use `getOwner` from our internal home for it rather than the narrower
// public API for the same reason.
const TOP_LEVEL_NAME = '-top-level';
class OutletView {
static extend(injections) {
return class extends OutletView {
static create(options) {
if (options) {
return super.create(Object.assign({}, injections, options));
} else {
return super.create(injections);
}
}
};
}
static reopenClass(injections) {
Object.assign(this, injections);
}
static create(options) {
let {
environment: _environment,
application: namespace,
template: templateFactory
} = options;
let owner = getOwner(options);
(!(owner) && assert('OutletView is unexpectedly missing an owner', owner));
let template = templateFactory(owner);
return new OutletView(_environment, owner, template, namespace);
}
ref;
state;
constructor(_environment, owner, template, namespace) {
this._environment = _environment;
this.owner = owner;
this.template = template;
this.namespace = namespace;
let outletStateTag = createTag();
let outletState = {
outlets: {
main: undefined
},
render: {
owner: owner,
name: TOP_LEVEL_NAME,
controller: undefined,
model: undefined,
template
}
};
let ref = this.ref = createComputeRef(() => {
consumeTag(outletStateTag);
return outletState;
}, state => {
DIRTY_TAG$1(outletStateTag);
outletState.outlets['main'] = state;
});
this.state = {
ref,
name: TOP_LEVEL_NAME,
template,
controller: undefined
};
}
appendTo(selector) {
let target;
if (this._environment.hasDOM) {
target = typeof selector === 'string' ? document.querySelector(selector) : selector;
} else {
target = selector;
}
let renderer = this.owner.lookup('renderer:-dom');
// SAFETY: It's not clear that this cast is safe.
// The types for appendOutletView may be incorrect or this is a potential bug.
schedule('render', renderer, 'appendOutletView', this, target);
}
rerender() {
/**/
}
setOutletState(state) {
updateRef(this.ref, state);
}
destroy() {
/**/
}
}
class DynamicScope {
constructor(view, outletState) {
this.view = view;
this.outletState = outletState;
}
child() {
return new DynamicScope(this.view, this.outletState);
}
get(key) {
(!(key === 'outletState') && assert(`Using \`-get-dynamic-scope\` is only supported for \`outletState\` (you used \`${key}\`).`, key === 'outletState'));
return this.outletState;
}
set(key, value) {
(!(key === 'outletState') && assert(`Using \`-with-dynamic-scope\` is only supported for \`outletState\` (you used \`${key}\`).`, key === 'outletState'));
this.outletState = value;
return value;
}
}
const NO_OP = () => {};
// This wrapper logic prevents us from rerendering in case of a hard failure
// during render. This prevents infinite revalidation type loops from occuring,
// and ensures that errors are not swallowed by subsequent follow on failures.
function errorLoopTransaction(fn) {
{
return () => {
let didError = true;
try {
fn();
didError = false;
} finally {
if (didError) {
// Noop the function so that we won't keep calling it and causing
// infinite looping failures;
fn = () => {
// eslint-disable-next-line no-console
console.warn('Attempted to rerender, but the Ember application has had an unrecoverable error occur during render. You should reload the application after fixing the cause of the error.');
};
}
}
};
}
}
class ComponentRootState {
type = 'component';
#result;
#render;
constructor(state, definition, options) {
this.#render = errorLoopTransaction(() => {
let iterator = renderComponent$1(state.context, state.builder(state.env, options.into), state.owner, definition, options?.args);
let result = this.#result = iterator.sync();
associateDestroyableChild(this, this.#result);
this.#render = errorLoopTransaction(() => {
if (isDestroying(result) || isDestroyed(result)) return;
return result.rerender({
alwaysRevalidate: false
});
});
});
}
isFor(_component) {
return false;
}
render() {
this.#render();
}
destroy() {
destroy(this);
}
get destroyed() {
return isDestroyed(this);
}
get result() {
return this.#result;
}
}
class ClassicRootState {
type = 'classic';
id;
result;
destroyed;
render;
env;
constructor(root, context, owner, template, self, parentElement, dynamicScope, builder) {
this.root = root;
(!(template !== undefined) && assert(`You cannot render \`${valueForRef(self)}\` without a template.`, template !== undefined));
this.id = root instanceof OutletView ? guidFor(root) : getViewId(root);
this.result = undefined;
this.destroyed = false;
this.env = context.env;
this.render = errorLoopTransaction(() => {
let layout = unwrapTemplate(template).asLayout();
let iterator = renderMain(context, owner, self, builder(context.env, {
element: parentElement,
nextSibling: null
}), layout, dynamicScope);
let result = this.result = iterator.sync();
associateDestroyableChild(this, result);
this.render = errorLoopTransaction(() => {
if (isDestroying(result) || isDestroyed(result)) return;
return result.rerender({
alwaysRevalidate: false
});
});
});
}
isFor(possibleRoot) {
return this.root === possibleRoot;
}
destroy() {
let {
result,
env
} = this;
this.destroyed = true;
this.root = null;
this.result = undefined;
this.render = undefined;
if (result !== undefined) {
/*
Handles these scenarios:
* When roots are removed during standard rendering process, a transaction exists already
`.begin()` / `.commit()` are not needed.
* When roots are being destroyed manually (`component.append(); component.destroy() case), no
transaction exists already.
* When roots are being destroyed during `Renderer#destroy`, no transaction exists
*/
inTransaction(env, () => destroy(result));
}
}
}
const renderers = [];
function _resetRenderers() {
renderers.length = 0;
}
function register(renderer) {
(!(renderers.indexOf(renderer) === -1) && assert('Cannot register the same renderer twice', renderers.indexOf(renderer) === -1));
renderers.push(renderer);
}
function deregister(renderer) {
let index = renderers.indexOf(renderer);
(!(index !== -1) && assert('Cannot deregister unknown unregistered renderer', index !== -1));
renderers.splice(index, 1);
}
function loopBegin() {
for (let renderer of renderers) {
renderer.rerender();
}
}
let renderSettledDeferred = null;
/*
Returns a promise which will resolve when rendering has settled. Settled in
this context is defined as when all of the tags in use are "current" (e.g.
`renderers.every(r => r._isValid())`). When this is checked at the _end_ of
the run loop, this essentially guarantees that all rendering is completed.
@method renderSettled
@returns {Promise<void>} a promise which fulfills when rendering has settled
*/
function renderSettled() {
if (renderSettledDeferred === null) {
let resolve;
let promise = new Promise(r => resolve = r);
renderSettledDeferred = {
promise,
resolve
};
// if there is no current runloop, the promise created above will not have
// a chance to resolve (because its resolved in backburner's "end" event)
if (!_getCurrentRunLoop()) {
// ensure a runloop has been kicked off
_backburner.schedule('actions', null, NO_OP);
}
}
return renderSettledDeferred.promise;
}
function resolveRenderPromise() {
if (renderSettledDeferred !== null) {
let resolve = renderSettledDeferred.resolve;
renderSettledDeferred = null;
_backburner.join(null, resolve);
}
}
let loops = 0;
function loopEnd() {
for (let renderer of renderers) {
if (!renderer.isValid()) {
if (loops > ENV._RERENDER_LOOP_LIMIT) {
loops = 0;
// TODO: do something better
renderer.destroy();
throw new Error('infinite rendering invalidation detected');
}
loops++;
return _backburner.join(null, NO_OP);
}
}
loops = 0;
resolveRenderPromise();
}
_backburner.on('begin', loopBegin);
_backburner.on('end', loopEnd);
class RendererState {
static create(data, renderer) {
const state = new RendererState(data, renderer);
associateDestroyableChild(renderer, state);
return state;
}
#data;
#lastRevision = -1;
#inRenderTransaction = false;
#destroyed = false;
#roots = [];
#removedRoots = [];
constructor(data, renderer) {
this.#data = data;
registerDestructor(this, () => {
this.clearAllRoots(renderer);
});
}
get debug() {
return {
roots: this.#roots,
inRenderTransaction: this.#inRenderTransaction,
isInteractive: this.isInteractive
};
}
get roots() {
return this.#roots;
}
get owner() {
return this.#data.owner;
}
get builder() {
return this.#data.builder;
}
get context() {
return this.#data.context;
}
get env() {
return this.context.env;
}
get isInteractive() {
return this.#data.context.env.isInteractive;
}
renderRoot(root, renderer) {
let roots = this.#roots;
roots.push(root);
associateDestroyableChild(this, root);
if (roots.length === 1) {
register(renderer);
}
this.#renderRootsTransaction(renderer);
return root;
}
#renderRootsTransaction(renderer) {
if (this.#inRenderTransaction) {
// currently rendering roots, a new root was added and will
// be processed by the existing _renderRoots invocation
return;
}
// used to prevent calling _renderRoots again (see above)
// while we are actively rendering roots
this.#inRenderTransaction = true;
let completedWithoutError = false;
try {
this.renderRoots(renderer);
completedWithoutError = true;
} finally {
if (!completedWithoutError) {
this.#lastRevision = valueForTag(CURRENT_TAG);
}
this.#inRenderTransaction = false;
}
}
renderRoots(renderer) {
let roots = this.#roots;
let removedRoots = this.#removedRoots;
let initialRootsLength;
do {
initialRootsLength = roots.length;
inTransaction(this.context.env, () => {
// ensure that for the first iteration of the loop
// each root is processed
for (let i = 0; i < roots.length; i++) {
let root = roots[i];
(true && !(root) && assert('has root', root));
if (root.destroyed) {
// add to the list of roots to be removed
// they will be removed from `this._roots` later
removedRoots.push(root);
// skip over roots that have been marked as destroyed
continue;
}
// when processing non-initial reflush loops,
// do not process more roots than needed
if (i >= initialRootsLength) {
continue;
}
root.render();
}
this.#lastRevision = valueForTag(CURRENT_TAG);
});
} while (roots.length > initialRootsLength);
// remove any roots that were destroyed during this transaction
while (removedRoots.length) {
let root = removedRoots.pop();
let rootIndex = roots.indexOf(root);
roots.splice(rootIndex, 1);
}
if (this.#roots.length === 0) {
deregister(renderer);
}
}
scheduleRevalidate(renderer) {
_backburner.scheduleOnce('render', this, this.revalidate, renderer);
}
isValid() {
return this.#destroyed || this.#roots.length === 0 || validateTag(CURRENT_TAG, this.#lastRevision);
}
revalidate(renderer) {
if (this.isValid()) {
return;
}
this.#renderRootsTransaction(renderer);
}
clearAllRoots(renderer) {
let roots = this.#roots;
for (let root of roots) {
destroy(root);
}
this.#removedRoots.length = 0;
this.#roots = [];
// if roots were present before destroying
// deregister this renderer instance
if (roots.length) {
deregister(renderer);
}
}
}
/**
* The returned object from `renderComponent`
* @public
* @module @ember/renderer
*/
function intoTarget(into) {
if ('element' in into) {
return into;
} else {
return {
element: into,
nextSibling: null
};
}
}
/**
* Render a component into a DOM element.
*
* @method renderComponent
* @static
* @for @ember/renderer
* @param {Object} component The component to render.
* @param {Object} options
* @param {Element} options.into Where to render the component in to.
* @param {Object} [options.owner] Optionally specify the owner to use. This will be used for injections, and overall cleanup.
* @param {Object} [options.env] Optional renderer configuration
* @param {Object} [options.args] Optionally pass args in to the component. These may be reactive as long as it is an object or object-like
* @public
*/
function renderComponent(
/**
* The component definition to render.
*
* Any component that has had its manager registered is valid.
* For the component-types that ship with ember, manager registration
* does not need to be worried about.
*/
component, {
owner = {},
env,
into,
args
}) {
/**
* SAFETY: we should figure out what we need out of a `document` and narrow the API.
* this exercise should also end up beginning to define what we need for CLI rendering (or to other outputs)
*/
let document = env && 'document' in env ? env?.['document'] : globalThis.document;
// Reuse renderer per owner to avoid creating multiple EvaluationContexts
// which can cause tracking frame conflicts
let renderer = RENDERER_CACHE.get(owner);
if (!renderer) {
renderer = BaseRenderer.strict(owner, document, {
...env,
isInteractive: env?.isInteractive ?? true,
hasDOM: env && 'hasDOM' in env ? Boolean(env?.['hasDOM']) : true
});
RENDERER_CACHE.set(owner, renderer);
}
/**
* Replace all contents, if we've rendered multiple times.
*
* https://github.com/emberjs/rfcs/pull/1099/files#diff-2b962105b9083ca84579cdc957f27f49407440f3c5078083fa369ec18cc46da8R365
*
* We could later add an option to not do this behavior
*
* NOTE: destruction is async
*/
let existing = RENDER_CACHE.get(into);
existing?.result.destroy();
/**
* We can only replace the inner HTML the first time.
* Because destruction is async, it won't be safe to
* do this again, and we'll have to rely on the above destroy.
*/
if (!existing && into instanceof Element) {
into.innerHTML = '';
}
/**
* If there's an existing render result with valid bounds, use its
* firstNode as the nextSibling so that new content is inserted at
* the same DOM position. This ensures stable ordering when multiple
* renderComponent calls target the same element and one is re-invoked
* (e.g., due to tracked dependency changes).
*
* The old content's DOM nodes are still present (destruction is async),
* so firstNode() is a valid position reference. The new content is placed
* BEFORE the old content. When the old content is eventually destroyed
* (async clear of bounds), the new content remains in the correct position.
*/
let renderTarget = into;
if (existing?.glimmerResult) {
let parentElement = into instanceof Element ? into : into.element;
let firstNode = existing.glimmerResult.firstNode();
renderTarget = {
element: parentElement,
nextSibling: firstNode
};
}
let innerResult = renderer.render(component, {
into: renderTarget,
args
}).result;
if (innerResult) {
associateDestroyableChild(owner, innerResult);
}
let result = {
destroy() {
if (innerResult) {
destroy(innerResult);
}
}
};
RENDER_CACHE.set(into, {
result,
glimmerResult: innerResult
});
return result;
}
const RENDER_CACHE = new WeakMap();
const RENDERER_CACHE = new WeakMap();
class BaseRenderer {
static strict(owner, document, options) {
return new BaseRenderer(owner, {
hasDOM: hasDOM,
...options
}, document, new ResolverImpl(), clientBuilder);
}
state;
constructor(owner, envOptions, document, resolver, builder) {
let sharedArtifacts = artifacts();
/**
* SAFETY: are there consequences for being looser with *this* owner?
* the public API for `owner` is kinda `Partial<InternalOwner>`
* aka: implement only what you need.
* But for actual ember apps, you *need* to implement everything
* an app needs (which will actually change and become less over time)
*/
let env = new EmberEnvironmentDelegate(owner, envOptions.isInteractive);
let options = runtimeOptions({
document
}, env, sharedArtifacts, resolver);
let context = new EvaluationContextImpl(sharedArtifacts, heap => new RuntimeOpImpl(heap), options);
this.state = RendererState.create({
owner,
context,
builder
}, this);
}
get debugRenderTree() {
let {
debugRenderTree
} = this.state.env;
(!(debugRenderTree) && assert('Attempted to access the DebugRenderTree, but it did not exist. Is the Ember Inspector open?', debugRenderTree));
return debugRenderTree;
}
isValid() {
return this.state.isValid();
}
destroy() {
destroy(this);
}
render(component, options) {
const root = new ComponentRootState(this.state, component, {
args: options.args,
into: intoTarget(options.into)
});
return this.state.renderRoot(root, this);
}
rerender() {
this.state.scheduleRevalidate(this);
}
// render(component: Component, options: { into: Cursor; args?: Record<string, unknown> }): void {
// this.state.renderRoot(component);
// }
}
class Renderer extends BaseRenderer {
static strict(owner, document, options) {
return new BaseRenderer(owner, {
hasDOM: hasDOM,
...options
}, document, new ResolverImpl(), clientBuilder);
}
_rootTemplate;
_viewRegistry;
static create(props) {
let {
_viewRegistry
} = props;
let owner = getOwner(props);
(!(owner) && assert('Renderer is unexpectedly missing an owner', owner));
let document = owner.lookup('service:-document');
let env = owner.lookup('-environment:main');
let rootTemplate = owner.lookup(privatize`template:-root`);
let builder = owner.lookup('service:-dom-builder');
return new this(owner, document, env, rootTemplate, _viewRegistry, builder);
}
constructor(owner, document, env, rootTemplate, viewRegistry, builder = clientBuilder, resolver = new ResolverImpl()) {
super(owner, env, document, resolver, builder);
this._rootTemplate = rootTemplate(owner);
this._viewRegistry = viewRegistry || owner.lookup('-view-registry:main');
}
// renderer HOOKS
appendOutletView(view, target) {
// TODO: This bypasses the {{outlet}} syntax so logically duplicates
// some of the set up code. Since this is all internal (or is it?),
// we can refactor this to do something more direct/less convoluted
// and with less setup, but get it working first
let outlet = createRootOutlet(view);
let {
name,
/* controller, */template
} = view.state;
let named = dict();
named['Component'] = createConstRef(makeRouteTemplate(view.owner, name, template), '@Component');
// TODO: is this guaranteed to be undefined? It seems to be the
// case in the `OutletView` class. Investigate how much that class
// exists as an internal implementation detail only, or if it was
// used outside of core. As far as I can tell, test-helpers uses
// it but only for `setOutletState`.
// named['controller'] = createConstRef(controller, '@controller');
// Update: at least according to the debug render tree tests, we
// appear to always expect this to be undefined. Not a definitive
// source by any means, but is useful evidence
named['controller'] = UNDEFINED_REFERENCE;
named['model'] = UNDEFINED_REFERENCE;
let args = createCapturedArgs(named, EMPTY_POSITIONAL);
this._appendDefinition(view, curry(0, outlet, view.owner, args, true), target);
}
appendTo(view, target) {
let definition = new RootComponentDefinition(view);
this._appendDefinition(view, curry(0, definition, this.state.owner, null, true), target);
}
_appendDefinition(root, definition, target) {
let self = createConstRef(definition, 'this');
let dynamicScope = new DynamicScope(null, UNDEFINED_REFERENCE);
let rootState = new ClassicRootState(root, this.state.context, this.state.owner, this._rootTemplate, self, target, dynamicScope, this.state.builder);
this.state.renderRoot(rootState, this);
}
cleanupRootFor(component) {
// no need to cleanup roots if we have already been destroyed
if (isDestroyed(this)) {
return;
}
let roots = this.state.roots;
// traverse in reverse so we can remove items
// without mucking up the index
let i = roots.length;
while (i--) {
let root = roots[i];
(!(root) && assert('has root', root));
if (root.type === 'classic' && root.isFor(component)) {
root.destroy();
roots.splice(i, 1);
}
}
}
remove(view) {
view._transitionTo('destroying');
this.cleanupRootFor(view);
if (this.state.isInteractive) {
view.trigger('didDestroyElement');
}
}
get _roots() {
return this.state.debug.roots;
}
get _inRenderTransaction() {
return this.state.debug.inRenderTransaction;
}
get _isInteractive() {
return this.state.debug.isInteractive;
}
get _context() {
return this.state.context;
}
register(view) {
let id = getViewId(view);
(!(!this._viewRegistry[id]) && assert('Attempted to register a view with an id already in use: ' + id, !this._viewRegistry[id]));
this._viewRegistry[id] = view;
}
unregister(view) {
delete this._viewRegistry[getViewId(view)];
}
getElement(component) {
if (this._isInteractive) {
return getViewElement(component);
} else {
throw new Error('Accessing `this.element` is not allowed in non-interactive environments (such as FastBoot).');
}
}
getBounds(component) {
let bounds = component[BOUNDS];
(!(bounds) && assert('object passed to getBounds must have the BOUNDS symbol as a property', bounds));
let parentElement = bounds.parentElement();
let firstNode = bounds.firstNode();
let lastNode = bounds.lastNode();
return {
parentElement,
firstNode,
lastNode
};
}
}
export { OutletView as O, Renderer as R, _resetRenderers as _, renderSettled as a, outletHelper as o, renderComponent as r };