UNPKG

ember-source

Version:

A JavaScript framework for creating ambitious web applications

1,580 lines (1,436 loc) 78.2 kB
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-DzAfcWFj.js'; import { v as valueForRef, U as UNDEFINED_REFERENCE, a as createComputeRef, i as isConstRef, c 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-BoPB2LfI.js'; import { c as clientBuilder } from './element-builder--iTIJyCB.js'; import { E as EMPTY_ARGS, c as createCapturedArgs, b as EMPTY_POSITIONAL, d as curry } from './untouchable-this-B3DVwpHS.js'; import { g as runtimeOptions, i as inTransaction, r as renderComponent$1, d as renderMain } from './render-CpKaO-BO.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-BBzF_bI8.js'; import { b as CONSTANT_TAG, k as consumeTag, u as isTracking, o as debug, D as DIRTY_TAG$1, m as createTag, z as valueForTag, c as CURRENT_TAG, y as validateTag } from './cache-B7dqAS38.js'; import { a as RSVP } from './rsvp-CnCSY930.js'; import { h as hasDOM } from './index-BGP1rw3B.js'; import EngineInstance from '../@ember/engine/instance.js'; import { _instrumentStart } from '../@ember/instrumentation/index.js'; import { c as capabilityFlagsFrom } from './capabilities-CZkuOqqC.js'; import { t as templateFactory } from './index-CyZiGiEI.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-CIBS9umw.js'; import { _ as _setProp, s as set } from './property_set-D3PKyisF.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-D6tuFUj_.js'; import { isEmberArray } from '../@ember/array/-internals.js'; import { i as isObject } from './spec-BXl1reqK.js'; import { t as tagFor } from './meta-BmRXesrk.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-Ez7zbEIa.js'; import { i as isHTMLSafe } from './index-D-xTBV4B.js'; import { isArray } from '../@ember/array/index.js'; import { g as getComponentTemplate } from './template-R_5UMHhb.js'; import { c as hasInternalComponentManager, j as setInternalHelperManager, g as getInternalComponentManager } from './api-BawZUDYD.js'; import { h as hash, f as fn, a as array } from './hash-BTwOuDGQ.js'; import { g as get$1, c as concat } from './get-BehtPmsu.js'; import { o as on } from './on-BQii6ILK.js'; import { T as TEMPLATE_ONLY_COMPONENT_MANAGER, t as templateOnlyComponent } from './template-only-BqOt8bDl.js'; import { i as isClassicHelper, C as CLASSIC_HELPER_MANAGER } from './helper-BubrhyuN.js'; import { dasherize } from '../@ember/-internals/string/index.js'; import { a as uniqueId } from './unique-id-CgmHQiwi.js'; import '../route-recognizer/index.js'; import './unrecognized-url-error-B3wUTorp.js'; import '../@ember/routing/lib/routing-service.js'; import { generateControllerFactory } from '../@ember/routing/lib/generate_controller.js'; import { E as EvaluationContextImpl } from './program-context-CadjldRr.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 instanceof EngineInstance) && assert('Expected currentOwner to be an EngineInstance', currentOwner instanceof EngineInstance)); let { mountPoint } = currentOwner; if (mountPoint) { state.engine = { mountPoint, instance: currentOwner }; } } } 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 */ /** 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. Assuming the `@developers` argument contains this array: ```javascript [{ name: 'Yehuda' },{ name: 'Tom' }, { name: 'Paul' }]; ``` ```handlebars <ul> {{#each @developers as |person|}} <li>Hello, {{person.name}}!</li> {{/each}} </ul> ``` The same rules apply to arrays of primitives. ```javascript ['Yehuda', 'Tom', 'Paul'] ``` ```handlebars <ul> {{#each @developerNames as |name|}} <li>Hello, {{name}}!</li> {{/each}} </ul> ``` During iteration, the index of each item in the array is provided as a second block parameter. ```handlebars <ul> {{#each @developers as |person index|}} <li>Hello, {{person.name}}! You're number {{index}} in line</li> {{/each}} </ul> ``` `#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: ```javascript people.map(person => { return { ...person, type: 'developer' }; }); ``` In this case, each time the `people` array is `map`-ed over, it will produce an new array with completely different objects between renders. In these cases, you can help Ember determine how these objects related to each other with the `key` option: ```handlebars <ul> {{#each @developers key="name" as |person|}} <li>Hello, {{person.name}}!</li> {{/each}} </ul> ``` 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. ```handlebars <ul> {{#each @developers as |person|}} <li>{{person.name}} is available!</li> {{else}} <li>Sorry, nobody is available for this task.</li> {{/each}} </ul> ``` @method each @for Ember.Templates.helpers @public */ /** The `{{#each-in}}` keyword loops over properties on an object. For example, given this component definition: ```app/components/developer-details.gjs import Component from '@glimmer/component'; import { tracked } from '@glimmer/tracking'; export default class 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> ``` `#each-in` is a keyword and does not need to be imported. @method each-in @for Ember.Templates.helpers @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 */ /** 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: ```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. @for Ember.Templates.helpers @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 */ /** 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 Ember.Templates.helpers @private */ const readonly = internalHelper(({ positional }) => { let firstArg = positional[0]; (!(firstArg) && assert('has first arg', firstArg)); return createReadOnlyRef(firstArg); }); /** @module ember */ /** 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. @method unbound @for Ember.Templates.helpers @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. (!(owner instanceof EngineInstance) && assert('Expected owner to be an EngineInstance', owner instanceof EngineInstance)); 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 */ /** 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: ```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 Ember.Templates.helpers @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); } /** 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: ```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 Ember.Templates.helpers @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(compo