language
stringclasses
6 values
original_string
stringlengths
25
887k
text
stringlengths
25
887k
JavaScript
function runMethodEffect(inst, property, props, oldProps, info) { // Instances can optionally have a _methodHost which allows redirecting where // to find methods. Currently used by `templatize`. let context = inst._methodHost || inst; let fn = context[info.methodName]; if (fn) { let args = marshalArgs(inst.__data, info.args, property, props); return fn.apply(context, args); } else if (!info.dynamicFn) { console.warn('method `' + info.methodName + '` not defined'); } }
function runMethodEffect(inst, property, props, oldProps, info) { // Instances can optionally have a _methodHost which allows redirecting where // to find methods. Currently used by `templatize`. let context = inst._methodHost || inst; let fn = context[info.methodName]; if (fn) { let args = marshalArgs(inst.__data, info.args, property, props); return fn.apply(context, args); } else if (!info.dynamicFn) { console.warn('method `' + info.methodName + '` not defined'); } }
JavaScript
function literalFromParts(parts) { let s = ''; for (let i=0; i<parts.length; i++) { let literal = parts[i].literal; s += literal || ''; } return s; }
function literalFromParts(parts) { let s = ''; for (let i=0; i<parts.length; i++) { let literal = parts[i].literal; s += literal || ''; } return s; }
JavaScript
function parseArgs(argList, sig) { sig.args = argList.map(function(rawArg) { let arg = parseArg(rawArg); if (!arg.literal) { sig.static = false; } return arg; }, this); return sig; }
function parseArgs(argList, sig) { sig.args = argList.map(function(rawArg) { let arg = parseArg(rawArg); if (!arg.literal) { sig.static = false; } return arg; }, this); return sig; }
JavaScript
function parseArg(rawArg) { // clean up whitespace let arg = rawArg.trim() // replace comma entity with comma .replace(/&comma;/g, ',') // repair extra escape sequences; note only commas strictly need // escaping, but we allow any other char to be escaped since its // likely users will do this .replace(/\\(.)/g, '\$1') ; // basic argument descriptor let a = { name: arg, value: '', literal: false }; // detect literal value (must be String or Number) let fc = arg[0]; if (fc === '-') { fc = arg[1]; } if (fc >= '0' && fc <= '9') { fc = '#'; } switch(fc) { case "'": case '"': a.value = arg.slice(1, -1); a.literal = true; break; case '#': a.value = Number(arg); a.literal = true; break; } // if not literal, look for structured path if (!a.literal) { a.rootProperty = root(arg); // detect structured path (has dots) a.structured = isPath(arg); if (a.structured) { a.wildcard = (arg.slice(-2) == '.*'); if (a.wildcard) { a.name = arg.slice(0, -2); } } } return a; }
function parseArg(rawArg) { // clean up whitespace let arg = rawArg.trim() // replace comma entity with comma .replace(/&comma;/g, ',') // repair extra escape sequences; note only commas strictly need // escaping, but we allow any other char to be escaped since its // likely users will do this .replace(/\\(.)/g, '\$1') ; // basic argument descriptor let a = { name: arg, value: '', literal: false }; // detect literal value (must be String or Number) let fc = arg[0]; if (fc === '-') { fc = arg[1]; } if (fc >= '0' && fc <= '9') { fc = '#'; } switch(fc) { case "'": case '"': a.value = arg.slice(1, -1); a.literal = true; break; case '#': a.value = Number(arg); a.literal = true; break; } // if not literal, look for structured path if (!a.literal) { a.rootProperty = root(arg); // detect structured path (has dots) a.structured = isPath(arg); if (a.structured) { a.wildcard = (arg.slice(-2) == '.*'); if (a.wildcard) { a.name = arg.slice(0, -2); } } } return a; }
JavaScript
function marshalArgs(data, args, path, props) { let values = []; for (let i=0, l=args.length; i<l; i++) { let arg = args[i]; let name = arg.name; let v; if (arg.literal) { v = arg.value; } else { if (arg.structured) { v = get(data, name); // when data is not stored e.g. `splices` if (v === undefined) { v = props[name]; } } else { v = data[name]; } } if (arg.wildcard) { // Only send the actual path changed info if the change that // caused the observer to run matched the wildcard let baseChanged = (name.indexOf(path + '.') === 0); let matches$$1 = (path.indexOf(name) === 0 && !baseChanged); values[i] = { path: matches$$1 ? path : name, value: matches$$1 ? props[path] : v, base: v }; } else { values[i] = v; } } return values; }
function marshalArgs(data, args, path, props) { let values = []; for (let i=0, l=args.length; i<l; i++) { let arg = args[i]; let name = arg.name; let v; if (arg.literal) { v = arg.value; } else { if (arg.structured) { v = get(data, name); // when data is not stored e.g. `splices` if (v === undefined) { v = props[name]; } } else { v = data[name]; } } if (arg.wildcard) { // Only send the actual path changed info if the change that // caused the observer to run matched the wildcard let baseChanged = (name.indexOf(path + '.') === 0); let matches$$1 = (path.indexOf(name) === 0 && !baseChanged); values[i] = { path: matches$$1 ? path : name, value: matches$$1 ? props[path] : v, base: v }; } else { values[i] = v; } } return values; }
JavaScript
function notifySplice(inst, array, path, index, addedCount, removed) { notifySplices(inst, array, path, [{ index: index, addedCount: addedCount, removed: removed, object: array, type: 'splice' }]); }
function notifySplice(inst, array, path, index, addedCount, removed) { notifySplices(inst, array, path, [{ index: index, addedCount: addedCount, removed: removed, object: array, type: 'splice' }]); }
JavaScript
_initializeProtoProperties(props) { this.__data = Object.create(props); this.__dataPending = Object.create(props); this.__dataOld = {}; }
_initializeProtoProperties(props) { this.__data = Object.create(props); this.__dataPending = Object.create(props); this.__dataOld = {}; }
JavaScript
_addPropertyEffect(property, type, effect) { this._createPropertyAccessor(property, type == TYPES.READ_ONLY); // effects are accumulated into arrays per property based on type let effects = ensureOwnEffectMap(this, type)[property]; if (!effects) { effects = this[type][property] = []; } effects.push(effect); }
_addPropertyEffect(property, type, effect) { this._createPropertyAccessor(property, type == TYPES.READ_ONLY); // effects are accumulated into arrays per property based on type let effects = ensureOwnEffectMap(this, type)[property]; if (!effects) { effects = this[type][property] = []; } effects.push(effect); }
JavaScript
_setPendingPropertyOrPath(path, value, shouldNotify, isPathNotification) { if (isPathNotification || root(Array.isArray(path) ? path[0] : path) !== path) { // Dirty check changes being set to a path against the actual object, // since this is the entry point for paths into the system; from here // the only dirty checks are against the `__dataTemp` cache to prevent // duplicate work in the same turn only. Note, if this was a notification // of a change already set to a path (isPathNotification: true), // we always let the change through and skip the `set` since it was // already dirty checked at the point of entry and the underlying // object has already been updated if (!isPathNotification) { let old = get(this, path); path = /** @type {string} */ (set(this, path, value)); // Use property-accessor's simpler dirty check if (!path || !super._shouldPropertyChange(path, value, old)) { return false; } } this.__dataHasPaths = true; if (this._setPendingProperty(/**@type{string}*/(path), value, shouldNotify)) { computeLinkedPaths(this, path, value); return true; } } else { if (this.__dataHasAccessor && this.__dataHasAccessor[path]) { return this._setPendingProperty(/**@type{string}*/(path), value, shouldNotify); } else { this[path] = value; } } return false; }
_setPendingPropertyOrPath(path, value, shouldNotify, isPathNotification) { if (isPathNotification || root(Array.isArray(path) ? path[0] : path) !== path) { // Dirty check changes being set to a path against the actual object, // since this is the entry point for paths into the system; from here // the only dirty checks are against the `__dataTemp` cache to prevent // duplicate work in the same turn only. Note, if this was a notification // of a change already set to a path (isPathNotification: true), // we always let the change through and skip the `set` since it was // already dirty checked at the point of entry and the underlying // object has already been updated if (!isPathNotification) { let old = get(this, path); path = /** @type {string} */ (set(this, path, value)); // Use property-accessor's simpler dirty check if (!path || !super._shouldPropertyChange(path, value, old)) { return false; } } this.__dataHasPaths = true; if (this._setPendingProperty(/**@type{string}*/(path), value, shouldNotify)) { computeLinkedPaths(this, path, value); return true; } } else { if (this.__dataHasAccessor && this.__dataHasAccessor[path]) { return this._setPendingProperty(/**@type{string}*/(path), value, shouldNotify); } else { this[path] = value; } } return false; }
JavaScript
_setUnmanagedPropertyToNode(node, prop, value) { // It is a judgment call that resetting primitives is // "bad" and resettings objects is also "good"; alternatively we could // implement a whitelist of tag & property values that should never // be reset (e.g. <input>.value && <select>.value) if (value !== node[prop] || typeof value == 'object') { node[prop] = value; } }
_setUnmanagedPropertyToNode(node, prop, value) { // It is a judgment call that resetting primitives is // "bad" and resettings objects is also "good"; alternatively we could // implement a whitelist of tag & property values that should never // be reset (e.g. <input>.value && <select>.value) if (value !== node[prop] || typeof value == 'object') { node[prop] = value; } }
JavaScript
_setPendingProperty(property, value, shouldNotify) { let isPath$$1 = this.__dataHasPaths && isPath(property); let prevProps = isPath$$1 ? this.__dataTemp : this.__data; if (this._shouldPropertyChange(property, value, prevProps[property])) { if (!this.__dataPending) { this.__dataPending = {}; this.__dataOld = {}; } // Ensure old is captured from the last turn if (!(property in this.__dataOld)) { this.__dataOld[property] = this.__data[property]; } // Paths are stored in temporary cache (cleared at end of turn), // which is used for dirty-checking, all others stored in __data if (isPath$$1) { this.__dataTemp[property] = value; } else { this.__data[property] = value; } // All changes go into pending property bag, passed to _propertiesChanged this.__dataPending[property] = value; // Track properties that should notify separately if (isPath$$1 || (this[TYPES.NOTIFY] && this[TYPES.NOTIFY][property])) { this.__dataToNotify = this.__dataToNotify || {}; this.__dataToNotify[property] = shouldNotify; } return true; } return false; }
_setPendingProperty(property, value, shouldNotify) { let isPath$$1 = this.__dataHasPaths && isPath(property); let prevProps = isPath$$1 ? this.__dataTemp : this.__data; if (this._shouldPropertyChange(property, value, prevProps[property])) { if (!this.__dataPending) { this.__dataPending = {}; this.__dataOld = {}; } // Ensure old is captured from the last turn if (!(property in this.__dataOld)) { this.__dataOld[property] = this.__data[property]; } // Paths are stored in temporary cache (cleared at end of turn), // which is used for dirty-checking, all others stored in __data if (isPath$$1) { this.__dataTemp[property] = value; } else { this.__data[property] = value; } // All changes go into pending property bag, passed to _propertiesChanged this.__dataPending[property] = value; // Track properties that should notify separately if (isPath$$1 || (this[TYPES.NOTIFY] && this[TYPES.NOTIFY][property])) { this.__dataToNotify = this.__dataToNotify || {}; this.__dataToNotify[property] = shouldNotify; } return true; } return false; }
JavaScript
_enqueueClient(client) { this.__dataPendingClients = this.__dataPendingClients || []; if (client !== this) { this.__dataPendingClients.push(client); } }
_enqueueClient(client) { this.__dataPendingClients = this.__dataPendingClients || []; if (client !== this) { this.__dataPendingClients.push(client); } }
JavaScript
ready() { // It is important that `super.ready()` is not called here as it // immediately turns on accessors. Instead, we wait until `readyClients` // to enable accessors to provide a guarantee that clients are ready // before processing any accessors side effects. this._flushProperties(); // If no data was pending, `_flushProperties` will not `flushClients` // so ensure this is done. if (!this.__dataClientsReady) { this._flushClients(); } // Before ready, client notifications do not trigger _flushProperties. // Therefore a flush is necessary here if data has been set. if (this.__dataPending) { this._flushProperties(); } }
ready() { // It is important that `super.ready()` is not called here as it // immediately turns on accessors. Instead, we wait until `readyClients` // to enable accessors to provide a guarantee that clients are ready // before processing any accessors side effects. this._flushProperties(); // If no data was pending, `_flushProperties` will not `flushClients` // so ensure this is done. if (!this.__dataClientsReady) { this._flushClients(); } // Before ready, client notifications do not trigger _flushProperties. // Therefore a flush is necessary here if data has been set. if (this.__dataPending) { this._flushProperties(); } }
JavaScript
_propertiesChanged(currentProps, changedProps, oldProps) { // ---------------------------- // let c = Object.getOwnPropertyNames(changedProps || {}); // window.debug && console.group(this.localName + '#' + this.id + ': ' + c); // if (window.debug) { debugger; } // ---------------------------- let hasPaths = this.__dataHasPaths; this.__dataHasPaths = false; // Compute properties runComputedEffects(this, changedProps, oldProps, hasPaths); // Clear notify properties prior to possible reentry (propagate, observe), // but after computing effects have a chance to add to them let notifyProps = this.__dataToNotify; this.__dataToNotify = null; // Propagate properties to clients this._propagatePropertyChanges(changedProps, oldProps, hasPaths); // Flush clients this._flushClients(); // Reflect properties runEffects(this, this[TYPES.REFLECT], changedProps, oldProps, hasPaths); // Observe properties runEffects(this, this[TYPES.OBSERVE], changedProps, oldProps, hasPaths); // Notify properties to host if (notifyProps) { runNotifyEffects(this, notifyProps, changedProps, oldProps, hasPaths); } // Clear temporary cache at end of turn if (this.__dataCounter == 1) { this.__dataTemp = {}; } // ---------------------------- // window.debug && console.groupEnd(this.localName + '#' + this.id + ': ' + c); // ---------------------------- }
_propertiesChanged(currentProps, changedProps, oldProps) { // ---------------------------- // let c = Object.getOwnPropertyNames(changedProps || {}); // window.debug && console.group(this.localName + '#' + this.id + ': ' + c); // if (window.debug) { debugger; } // ---------------------------- let hasPaths = this.__dataHasPaths; this.__dataHasPaths = false; // Compute properties runComputedEffects(this, changedProps, oldProps, hasPaths); // Clear notify properties prior to possible reentry (propagate, observe), // but after computing effects have a chance to add to them let notifyProps = this.__dataToNotify; this.__dataToNotify = null; // Propagate properties to clients this._propagatePropertyChanges(changedProps, oldProps, hasPaths); // Flush clients this._flushClients(); // Reflect properties runEffects(this, this[TYPES.REFLECT], changedProps, oldProps, hasPaths); // Observe properties runEffects(this, this[TYPES.OBSERVE], changedProps, oldProps, hasPaths); // Notify properties to host if (notifyProps) { runNotifyEffects(this, notifyProps, changedProps, oldProps, hasPaths); } // Clear temporary cache at end of turn if (this.__dataCounter == 1) { this.__dataTemp = {}; } // ---------------------------- // window.debug && console.groupEnd(this.localName + '#' + this.id + ': ' + c); // ---------------------------- }
JavaScript
_propagatePropertyChanges(changedProps, oldProps, hasPaths) { if (this[TYPES.PROPAGATE]) { runEffects(this, this[TYPES.PROPAGATE], changedProps, oldProps, hasPaths); } let templateInfo = this.__templateInfo; while (templateInfo) { runEffects(this, templateInfo.propertyEffects, changedProps, oldProps, hasPaths, templateInfo.nodeList); templateInfo = templateInfo.nextTemplateInfo; } }
_propagatePropertyChanges(changedProps, oldProps, hasPaths) { if (this[TYPES.PROPAGATE]) { runEffects(this, this[TYPES.PROPAGATE], changedProps, oldProps, hasPaths); } let templateInfo = this.__templateInfo; while (templateInfo) { runEffects(this, templateInfo.propertyEffects, changedProps, oldProps, hasPaths, templateInfo.nodeList); templateInfo = templateInfo.nextTemplateInfo; } }
JavaScript
_createPropertyObserver(property, method, dynamicFn) { let info = { property, method, dynamicFn: Boolean(dynamicFn) }; this._addPropertyEffect(property, TYPES.OBSERVE, { fn: runObserverEffect, info, trigger: {name: property} }); if (dynamicFn) { this._addPropertyEffect(/** @type {string} */(method), TYPES.OBSERVE, { fn: runObserverEffect, info, trigger: {name: method} }); } }
_createPropertyObserver(property, method, dynamicFn) { let info = { property, method, dynamicFn: Boolean(dynamicFn) }; this._addPropertyEffect(property, TYPES.OBSERVE, { fn: runObserverEffect, info, trigger: {name: property} }); if (dynamicFn) { this._addPropertyEffect(/** @type {string} */(method), TYPES.OBSERVE, { fn: runObserverEffect, info, trigger: {name: method} }); } }
JavaScript
_createMethodObserver(expression, dynamicFn) { let sig = parseMethod(expression); if (!sig) { throw new Error("Malformed observer expression '" + expression + "'"); } createMethodEffect(this, sig, TYPES.OBSERVE, runMethodEffect, null, dynamicFn); }
_createMethodObserver(expression, dynamicFn) { let sig = parseMethod(expression); if (!sig) { throw new Error("Malformed observer expression '" + expression + "'"); } createMethodEffect(this, sig, TYPES.OBSERVE, runMethodEffect, null, dynamicFn); }
JavaScript
_createNotifyingProperty(property) { this._addPropertyEffect(property, TYPES.NOTIFY, { fn: runNotifyEffect, info: { eventName: CaseMap.camelToDashCase(property) + '-changed', property: property } }); }
_createNotifyingProperty(property) { this._addPropertyEffect(property, TYPES.NOTIFY, { fn: runNotifyEffect, info: { eventName: CaseMap.camelToDashCase(property) + '-changed', property: property } }); }
JavaScript
_createReflectedProperty(property) { let attr = this.constructor.attributeNameForProperty(property); if (attr[0] === '-') { console.warn('Property ' + property + ' cannot be reflected to attribute ' + attr + ' because "-" is not a valid starting attribute name. Use a lowercase first letter for the property instead.'); } else { this._addPropertyEffect(property, TYPES.REFLECT, { fn: runReflectEffect, info: { attrName: attr } }); } }
_createReflectedProperty(property) { let attr = this.constructor.attributeNameForProperty(property); if (attr[0] === '-') { console.warn('Property ' + property + ' cannot be reflected to attribute ' + attr + ' because "-" is not a valid starting attribute name. Use a lowercase first letter for the property instead.'); } else { this._addPropertyEffect(property, TYPES.REFLECT, { fn: runReflectEffect, info: { attrName: attr } }); } }
JavaScript
_createComputedProperty(property, expression, dynamicFn) { let sig = parseMethod(expression); if (!sig) { throw new Error("Malformed computed expression '" + expression + "'"); } createMethodEffect(this, sig, TYPES.COMPUTE, runComputedEffect, property, dynamicFn); }
_createComputedProperty(property, expression, dynamicFn) { let sig = parseMethod(expression); if (!sig) { throw new Error("Malformed computed expression '" + expression + "'"); } createMethodEffect(this, sig, TYPES.COMPUTE, runComputedEffect, property, dynamicFn); }
JavaScript
_bindTemplate(template, instanceBinding) { let templateInfo = this.constructor._parseTemplate(template); let wasPreBound = this.__templateInfo == templateInfo; // Optimization: since this is called twice for proto-bound templates, // don't attempt to recreate accessors if this template was pre-bound if (!wasPreBound) { for (let prop in templateInfo.propertyEffects) { this._createPropertyAccessor(prop); } } if (instanceBinding) { // For instance-time binding, create instance of template metadata // and link into list of templates if necessary templateInfo = /** @type {!TemplateInfo} */(Object.create(templateInfo)); templateInfo.wasPreBound = wasPreBound; if (!wasPreBound && this.__templateInfo) { let last = this.__templateInfoLast || this.__templateInfo; this.__templateInfoLast = last.nextTemplateInfo = templateInfo; templateInfo.previousTemplateInfo = last; return templateInfo; } } return this.__templateInfo = templateInfo; }
_bindTemplate(template, instanceBinding) { let templateInfo = this.constructor._parseTemplate(template); let wasPreBound = this.__templateInfo == templateInfo; // Optimization: since this is called twice for proto-bound templates, // don't attempt to recreate accessors if this template was pre-bound if (!wasPreBound) { for (let prop in templateInfo.propertyEffects) { this._createPropertyAccessor(prop); } } if (instanceBinding) { // For instance-time binding, create instance of template metadata // and link into list of templates if necessary templateInfo = /** @type {!TemplateInfo} */(Object.create(templateInfo)); templateInfo.wasPreBound = wasPreBound; if (!wasPreBound && this.__templateInfo) { let last = this.__templateInfoLast || this.__templateInfo; this.__templateInfoLast = last.nextTemplateInfo = templateInfo; templateInfo.previousTemplateInfo = last; return templateInfo; } } return this.__templateInfo = templateInfo; }
JavaScript
static _addTemplatePropertyEffect(templateInfo, prop, effect) { let hostProps = templateInfo.hostProps = templateInfo.hostProps || {}; hostProps[prop] = true; let effects = templateInfo.propertyEffects = templateInfo.propertyEffects || {}; let propEffects = effects[prop] = effects[prop] || []; propEffects.push(effect); }
static _addTemplatePropertyEffect(templateInfo, prop, effect) { let hostProps = templateInfo.hostProps = templateInfo.hostProps || {}; hostProps[prop] = true; let effects = templateInfo.propertyEffects = templateInfo.propertyEffects || {}; let propEffects = effects[prop] = effects[prop] || []; propEffects.push(effect); }
JavaScript
_stampTemplate(template) { // Ensures that created dom is `_enqueueClient`'d to this element so // that it can be flushed on next call to `_flushProperties` hostStack.beginHosting(this); let dom = super._stampTemplate(template); hostStack.endHosting(this); let templateInfo = /** @type {!TemplateInfo} */(this._bindTemplate(template, true)); // Add template-instance-specific data to instanced templateInfo templateInfo.nodeList = dom.nodeList; // Capture child nodes to allow unstamping of non-prototypical templates if (!templateInfo.wasPreBound) { let nodes = templateInfo.childNodes = []; for (let n=dom.firstChild; n; n=n.nextSibling) { nodes.push(n); } } dom.templateInfo = templateInfo; // Setup compound storage, 2-way listeners, and dataHost for bindings setupBindings(this, templateInfo); // Flush properties into template nodes if already booted if (this.__dataReady) { runEffects(this, templateInfo.propertyEffects, this.__data, null, false, templateInfo.nodeList); } return dom; }
_stampTemplate(template) { // Ensures that created dom is `_enqueueClient`'d to this element so // that it can be flushed on next call to `_flushProperties` hostStack.beginHosting(this); let dom = super._stampTemplate(template); hostStack.endHosting(this); let templateInfo = /** @type {!TemplateInfo} */(this._bindTemplate(template, true)); // Add template-instance-specific data to instanced templateInfo templateInfo.nodeList = dom.nodeList; // Capture child nodes to allow unstamping of non-prototypical templates if (!templateInfo.wasPreBound) { let nodes = templateInfo.childNodes = []; for (let n=dom.firstChild; n; n=n.nextSibling) { nodes.push(n); } } dom.templateInfo = templateInfo; // Setup compound storage, 2-way listeners, and dataHost for bindings setupBindings(this, templateInfo); // Flush properties into template nodes if already booted if (this.__dataReady) { runEffects(this, templateInfo.propertyEffects, this.__data, null, false, templateInfo.nodeList); } return dom; }
JavaScript
_removeBoundDom(dom) { // Unlink template info let templateInfo = dom.templateInfo; if (templateInfo.previousTemplateInfo) { templateInfo.previousTemplateInfo.nextTemplateInfo = templateInfo.nextTemplateInfo; } if (templateInfo.nextTemplateInfo) { templateInfo.nextTemplateInfo.previousTemplateInfo = templateInfo.previousTemplateInfo; } if (this.__templateInfoLast == templateInfo) { this.__templateInfoLast = templateInfo.previousTemplateInfo; } templateInfo.previousTemplateInfo = templateInfo.nextTemplateInfo = null; // Remove stamped nodes let nodes = templateInfo.childNodes; for (let i=0; i<nodes.length; i++) { let node = nodes[i]; node.parentNode.removeChild(node); } }
_removeBoundDom(dom) { // Unlink template info let templateInfo = dom.templateInfo; if (templateInfo.previousTemplateInfo) { templateInfo.previousTemplateInfo.nextTemplateInfo = templateInfo.nextTemplateInfo; } if (templateInfo.nextTemplateInfo) { templateInfo.nextTemplateInfo.previousTemplateInfo = templateInfo.previousTemplateInfo; } if (this.__templateInfoLast == templateInfo) { this.__templateInfoLast = templateInfo.previousTemplateInfo; } templateInfo.previousTemplateInfo = templateInfo.nextTemplateInfo = null; // Remove stamped nodes let nodes = templateInfo.childNodes; for (let i=0; i<nodes.length; i++) { let node = nodes[i]; node.parentNode.removeChild(node); } }
JavaScript
static _parseTemplateNodeAttribute(node, templateInfo, nodeInfo, name, value) { let parts = this._parseBindings(value, templateInfo); if (parts) { // Attribute or property let origName = name; let kind = 'property'; // The only way we see a capital letter here is if the attr has // a capital letter in it per spec. In this case, to make sure // this binding works, we go ahead and make the binding to the attribute. if (capitalAttributeRegex.test(name)) { kind = 'attribute'; } else if (name[name.length-1] == '$') { name = name.slice(0, -1); kind = 'attribute'; } // Initialize attribute bindings with any literal parts let literal = literalFromParts(parts); if (literal && kind == 'attribute') { node.setAttribute(name, literal); } // Clear attribute before removing, since IE won't allow removing // `value` attribute if it previously had a value (can't // unconditionally set '' before removing since attributes with `$` // can't be set using setAttribute) if (node.localName === 'input' && origName === 'value') { node.setAttribute(origName, ''); } // Remove annotation node.removeAttribute(origName); // Case hackery: attributes are lower-case, but bind targets // (properties) are case sensitive. Gambit is to map dash-case to // camel-case: `foo-bar` becomes `fooBar`. // Attribute bindings are excepted. if (kind === 'property') { name = dashToCamelCase(name); } addBinding(this, templateInfo, nodeInfo, kind, name, parts, literal); return true; } else { return super._parseTemplateNodeAttribute(node, templateInfo, nodeInfo, name, value); } }
static _parseTemplateNodeAttribute(node, templateInfo, nodeInfo, name, value) { let parts = this._parseBindings(value, templateInfo); if (parts) { // Attribute or property let origName = name; let kind = 'property'; // The only way we see a capital letter here is if the attr has // a capital letter in it per spec. In this case, to make sure // this binding works, we go ahead and make the binding to the attribute. if (capitalAttributeRegex.test(name)) { kind = 'attribute'; } else if (name[name.length-1] == '$') { name = name.slice(0, -1); kind = 'attribute'; } // Initialize attribute bindings with any literal parts let literal = literalFromParts(parts); if (literal && kind == 'attribute') { node.setAttribute(name, literal); } // Clear attribute before removing, since IE won't allow removing // `value` attribute if it previously had a value (can't // unconditionally set '' before removing since attributes with `$` // can't be set using setAttribute) if (node.localName === 'input' && origName === 'value') { node.setAttribute(origName, ''); } // Remove annotation node.removeAttribute(origName); // Case hackery: attributes are lower-case, but bind targets // (properties) are case sensitive. Gambit is to map dash-case to // camel-case: `foo-bar` becomes `fooBar`. // Attribute bindings are excepted. if (kind === 'property') { name = dashToCamelCase(name); } addBinding(this, templateInfo, nodeInfo, kind, name, parts, literal); return true; } else { return super._parseTemplateNodeAttribute(node, templateInfo, nodeInfo, name, value); } }
JavaScript
static _parseTemplateNestedTemplate(node, templateInfo, nodeInfo) { let noted = super._parseTemplateNestedTemplate(node, templateInfo, nodeInfo); // Merge host props into outer template and add bindings let hostProps = nodeInfo.templateInfo.hostProps; let mode = '{'; for (let source in hostProps) { let parts = [{ mode, source, dependencies: [source] }]; addBinding(this, templateInfo, nodeInfo, 'property', '_host_' + source, parts); } return noted; }
static _parseTemplateNestedTemplate(node, templateInfo, nodeInfo) { let noted = super._parseTemplateNestedTemplate(node, templateInfo, nodeInfo); // Merge host props into outer template and add bindings let hostProps = nodeInfo.templateInfo.hostProps; let mode = '{'; for (let source in hostProps) { let parts = [{ mode, source, dependencies: [source] }]; addBinding(this, templateInfo, nodeInfo, 'property', '_host_' + source, parts); } return noted; }
JavaScript
static _parseBindings(text, templateInfo) { let parts = []; let lastIndex = 0; let m; // Example: "literal1{{prop}}literal2[[!compute(foo,bar)]]final" // Regex matches: // Iteration 1: Iteration 2: // m[1]: '{{' '[[' // m[2]: '' '!' // m[3]: 'prop' 'compute(foo,bar)' while ((m = bindingRegex.exec(text)) !== null) { // Add literal part if (m.index > lastIndex) { parts.push({literal: text.slice(lastIndex, m.index)}); } // Add binding part let mode = m[1][0]; let negate = Boolean(m[2]); let source = m[3].trim(); let customEvent = false, notifyEvent = '', colon = -1; if (mode == '{' && (colon = source.indexOf('::')) > 0) { notifyEvent = source.substring(colon + 2); source = source.substring(0, colon); customEvent = true; } let signature = parseMethod(source); let dependencies = []; if (signature) { // Inline computed function let {args, methodName} = signature; for (let i=0; i<args.length; i++) { let arg = args[i]; if (!arg.literal) { dependencies.push(arg); } } let dynamicFns = templateInfo.dynamicFns; if (dynamicFns && dynamicFns[methodName] || signature.static) { dependencies.push(methodName); signature.dynamicFn = true; } } else { // Property or path dependencies.push(source); } parts.push({ source, mode, negate, customEvent, signature, dependencies, event: notifyEvent }); lastIndex = bindingRegex.lastIndex; } // Add a final literal part if (lastIndex && lastIndex < text.length) { let literal = text.substring(lastIndex); if (literal) { parts.push({ literal: literal }); } } if (parts.length) { return parts; } else { return null; } }
static _parseBindings(text, templateInfo) { let parts = []; let lastIndex = 0; let m; // Example: "literal1{{prop}}literal2[[!compute(foo,bar)]]final" // Regex matches: // Iteration 1: Iteration 2: // m[1]: '{{' '[[' // m[2]: '' '!' // m[3]: 'prop' 'compute(foo,bar)' while ((m = bindingRegex.exec(text)) !== null) { // Add literal part if (m.index > lastIndex) { parts.push({literal: text.slice(lastIndex, m.index)}); } // Add binding part let mode = m[1][0]; let negate = Boolean(m[2]); let source = m[3].trim(); let customEvent = false, notifyEvent = '', colon = -1; if (mode == '{' && (colon = source.indexOf('::')) > 0) { notifyEvent = source.substring(colon + 2); source = source.substring(0, colon); customEvent = true; } let signature = parseMethod(source); let dependencies = []; if (signature) { // Inline computed function let {args, methodName} = signature; for (let i=0; i<args.length; i++) { let arg = args[i]; if (!arg.literal) { dependencies.push(arg); } } let dynamicFns = templateInfo.dynamicFns; if (dynamicFns && dynamicFns[methodName] || signature.static) { dependencies.push(methodName); signature.dynamicFn = true; } } else { // Property or path dependencies.push(source); } parts.push({ source, mode, negate, customEvent, signature, dependencies, event: notifyEvent }); lastIndex = bindingRegex.lastIndex; } // Add a final literal part if (lastIndex && lastIndex < text.length) { let literal = text.substring(lastIndex); if (literal) { parts.push({ literal: literal }); } } if (parts.length) { return parts; } else { return null; } }
JavaScript
static _evaluateBinding(inst, part, path, props, oldProps, hasPaths) { let value; if (part.signature) { value = runMethodEffect(inst, path, props, oldProps, part.signature); } else if (path != part.source) { value = get(inst, part.source); } else { if (hasPaths && isPath(path)) { value = get(inst, path); } else { value = inst.__data[path]; } } if (part.negate) { value = !value; } return value; }
static _evaluateBinding(inst, part, path, props, oldProps, hasPaths) { let value; if (part.signature) { value = runMethodEffect(inst, path, props, oldProps, part.signature); } else if (path != part.source) { value = get(inst, part.source); } else { if (hasPaths && isPath(path)) { value = get(inst, path); } else { value = inst.__data[path]; } } if (part.negate) { value = !value; } return value; }
JavaScript
function normalizeProperties(props) { const output = {}; for (let p in props) { const o = props[p]; output[p] = (typeof o === 'function') ? {type: o} : o; } return output; }
function normalizeProperties(props) { const output = {}; for (let p in props) { const o = props[p]; output[p] = (typeof o === 'function') ? {type: o} : o; } return output; }
JavaScript
function superPropertiesClass(constructor) { const superCtor = Object.getPrototypeOf(constructor); // Note, the `PropertiesMixin` class below only refers to the class // generated by this call to the mixin; the instanceof test only works // because the mixin is deduped and guaranteed only to apply once, hence // all constructors in a proto chain will see the same `PropertiesMixin` return (superCtor.prototype instanceof PropertiesMixin) ? /** @type {!PropertiesMixinConstructor} */ (superCtor) : null; }
function superPropertiesClass(constructor) { const superCtor = Object.getPrototypeOf(constructor); // Note, the `PropertiesMixin` class below only refers to the class // generated by this call to the mixin; the instanceof test only works // because the mixin is deduped and guaranteed only to apply once, hence // all constructors in a proto chain will see the same `PropertiesMixin` return (superCtor.prototype instanceof PropertiesMixin) ? /** @type {!PropertiesMixinConstructor} */ (superCtor) : null; }
JavaScript
function ownProperties(constructor) { if (!constructor.hasOwnProperty(JSCompiler_renameProperty('__ownProperties', constructor))) { let props = null; if (constructor.hasOwnProperty(JSCompiler_renameProperty('properties', constructor)) && constructor.properties) { props = normalizeProperties(constructor.properties); } constructor.__ownProperties = props; } return constructor.__ownProperties; }
function ownProperties(constructor) { if (!constructor.hasOwnProperty(JSCompiler_renameProperty('__ownProperties', constructor))) { let props = null; if (constructor.hasOwnProperty(JSCompiler_renameProperty('properties', constructor)) && constructor.properties) { props = normalizeProperties(constructor.properties); } constructor.__ownProperties = props; } return constructor.__ownProperties; }
JavaScript
static finalize() { if (!this.hasOwnProperty(JSCompiler_renameProperty('__finalized', this))) { const superCtor = superPropertiesClass(/** @type {!PropertiesMixinConstructor} */(this)); if (superCtor) { superCtor.finalize(); } this.__finalized = true; this._finalizeClass(); } }
static finalize() { if (!this.hasOwnProperty(JSCompiler_renameProperty('__finalized', this))) { const superCtor = superPropertiesClass(/** @type {!PropertiesMixinConstructor} */(this)); if (superCtor) { superCtor.finalize(); } this.__finalized = true; this._finalizeClass(); } }
JavaScript
static _finalizeClass() { const props = ownProperties(/** @type {!PropertiesMixinConstructor} */(this)); if (props) { this.createProperties(props); } }
static _finalizeClass() { const props = ownProperties(/** @type {!PropertiesMixinConstructor} */(this)); if (props) { this.createProperties(props); } }
JavaScript
static get _properties() { if (!this.hasOwnProperty( JSCompiler_renameProperty('__properties', this))) { const superCtor = superPropertiesClass(/** @type {!PropertiesMixinConstructor} */(this)); this.__properties = Object.assign({}, superCtor && superCtor._properties, ownProperties(/** @type {PropertiesMixinConstructor} */(this))); } return this.__properties; }
static get _properties() { if (!this.hasOwnProperty( JSCompiler_renameProperty('__properties', this))) { const superCtor = superPropertiesClass(/** @type {!PropertiesMixinConstructor} */(this)); this.__properties = Object.assign({}, superCtor && superCtor._properties, ownProperties(/** @type {PropertiesMixinConstructor} */(this))); } return this.__properties; }
JavaScript
connectedCallback() { if (super.connectedCallback) { super.connectedCallback(); } this._enableProperties(); }
connectedCallback() { if (super.connectedCallback) { super.connectedCallback(); } this._enableProperties(); }
JavaScript
disconnectedCallback() { if (super.disconnectedCallback) { super.disconnectedCallback(); } }
disconnectedCallback() { if (super.disconnectedCallback) { super.disconnectedCallback(); } }
JavaScript
function propertyDefaults(constructor) { if (!constructor.hasOwnProperty( JSCompiler_renameProperty('__propertyDefaults', constructor))) { constructor.__propertyDefaults = null; let props = constructor._properties; for (let p in props) { let info = props[p]; if ('value' in info) { constructor.__propertyDefaults = constructor.__propertyDefaults || {}; constructor.__propertyDefaults[p] = info; } } } return constructor.__propertyDefaults; }
function propertyDefaults(constructor) { if (!constructor.hasOwnProperty( JSCompiler_renameProperty('__propertyDefaults', constructor))) { constructor.__propertyDefaults = null; let props = constructor._properties; for (let p in props) { let info = props[p]; if ('value' in info) { constructor.__propertyDefaults = constructor.__propertyDefaults || {}; constructor.__propertyDefaults[p] = info; } } } return constructor.__propertyDefaults; }
JavaScript
function ownObservers(constructor) { if (!constructor.hasOwnProperty( JSCompiler_renameProperty('__ownObservers', constructor))) { constructor.__ownObservers = constructor.hasOwnProperty(JSCompiler_renameProperty('observers', constructor)) ? /** @type {PolymerElementConstructor} */ (constructor).observers : null; } return constructor.__ownObservers; }
function ownObservers(constructor) { if (!constructor.hasOwnProperty( JSCompiler_renameProperty('__ownObservers', constructor))) { constructor.__ownObservers = constructor.hasOwnProperty(JSCompiler_renameProperty('observers', constructor)) ? /** @type {PolymerElementConstructor} */ (constructor).observers : null; } return constructor.__ownObservers; }
JavaScript
function createPropertyFromConfig(proto, name, info, allProps) { // computed forces readOnly... if (info.computed) { info.readOnly = true; } // Note, since all computed properties are readOnly, this prevents // adding additional computed property effects (which leads to a confusing // setup where multiple triggers for setting a property) // While we do have `hasComputedEffect` this is set on the property's // dependencies rather than itself. if (info.computed && !proto._hasReadOnlyEffect(name)) { proto._createComputedProperty(name, info.computed, allProps); } if (info.readOnly && !proto._hasReadOnlyEffect(name)) { proto._createReadOnlyProperty(name, !info.computed); } if (info.reflectToAttribute && !proto._hasReflectEffect(name)) { proto._createReflectedProperty(name); } if (info.notify && !proto._hasNotifyEffect(name)) { proto._createNotifyingProperty(name); } // always add observer if (info.observer) { proto._createPropertyObserver(name, info.observer, allProps[info.observer]); } // always create the mapping from attribute back to property for deserialization. proto._addPropertyToAttributeMap(name); }
function createPropertyFromConfig(proto, name, info, allProps) { // computed forces readOnly... if (info.computed) { info.readOnly = true; } // Note, since all computed properties are readOnly, this prevents // adding additional computed property effects (which leads to a confusing // setup where multiple triggers for setting a property) // While we do have `hasComputedEffect` this is set on the property's // dependencies rather than itself. if (info.computed && !proto._hasReadOnlyEffect(name)) { proto._createComputedProperty(name, info.computed, allProps); } if (info.readOnly && !proto._hasReadOnlyEffect(name)) { proto._createReadOnlyProperty(name, !info.computed); } if (info.reflectToAttribute && !proto._hasReflectEffect(name)) { proto._createReflectedProperty(name); } if (info.notify && !proto._hasNotifyEffect(name)) { proto._createNotifyingProperty(name); } // always add observer if (info.observer) { proto._createPropertyObserver(name, info.observer, allProps[info.observer]); } // always create the mapping from attribute back to property for deserialization. proto._addPropertyToAttributeMap(name); }
JavaScript
function processElementStyles(klass, template, is, baseURI) { const templateStyles = template.content.querySelectorAll('style'); const stylesWithImports = stylesFromTemplate(template); // insert styles from <link rel="import" type="css"> at the top of the template const linkedStyles = stylesFromModuleImports(is); const firstTemplateChild = template.content.firstElementChild; for (let idx = 0; idx < linkedStyles.length; idx++) { let s = linkedStyles[idx]; s.textContent = klass._processStyleText(s.textContent, baseURI); template.content.insertBefore(s, firstTemplateChild); } // keep track of the last "concrete" style in the template we have encountered let templateStyleIndex = 0; // ensure all gathered styles are actually in this template. for (let i = 0; i < stylesWithImports.length; i++) { let s = stylesWithImports[i]; let templateStyle = templateStyles[templateStyleIndex]; // if the style is not in this template, it's been "included" and // we put a clone of it in the template before the style that included it if (templateStyle !== s) { s = s.cloneNode(true); templateStyle.parentNode.insertBefore(s, templateStyle); } else { templateStyleIndex++; } s.textContent = klass._processStyleText(s.textContent, baseURI); } if (window.ShadyCSS) { window.ShadyCSS.prepareTemplate(template, is); } }
function processElementStyles(klass, template, is, baseURI) { const templateStyles = template.content.querySelectorAll('style'); const stylesWithImports = stylesFromTemplate(template); // insert styles from <link rel="import" type="css"> at the top of the template const linkedStyles = stylesFromModuleImports(is); const firstTemplateChild = template.content.firstElementChild; for (let idx = 0; idx < linkedStyles.length; idx++) { let s = linkedStyles[idx]; s.textContent = klass._processStyleText(s.textContent, baseURI); template.content.insertBefore(s, firstTemplateChild); } // keep track of the last "concrete" style in the template we have encountered let templateStyleIndex = 0; // ensure all gathered styles are actually in this template. for (let i = 0; i < stylesWithImports.length; i++) { let s = stylesWithImports[i]; let templateStyle = templateStyles[templateStyleIndex]; // if the style is not in this template, it's been "included" and // we put a clone of it in the template before the style that included it if (templateStyle !== s) { s = s.cloneNode(true); templateStyle.parentNode.insertBefore(s, templateStyle); } else { templateStyleIndex++; } s.textContent = klass._processStyleText(s.textContent, baseURI); } if (window.ShadyCSS) { window.ShadyCSS.prepareTemplate(template, is); } }
JavaScript
static _finalizeClass() { super._finalizeClass(); if (this.hasOwnProperty( JSCompiler_renameProperty('is', this)) && this.is) { register(this.prototype); } const observers = ownObservers(this); if (observers) { this.createObservers(observers, this._properties); } // note: create "working" template that is finalized at instance time let template = /** @type {PolymerElementConstructor} */ (this).template; if (template) { if (typeof template === 'string') { console.error('template getter must return HTMLTemplateElement'); template = null; } else { template = template.cloneNode(true); } } this.prototype._template = template; }
static _finalizeClass() { super._finalizeClass(); if (this.hasOwnProperty( JSCompiler_renameProperty('is', this)) && this.is) { register(this.prototype); } const observers = ownObservers(this); if (observers) { this.createObservers(observers, this._properties); } // note: create "working" template that is finalized at instance time let template = /** @type {PolymerElementConstructor} */ (this).template; if (template) { if (typeof template === 'string') { console.error('template getter must return HTMLTemplateElement'); template = null; } else { template = template.cloneNode(true); } } this.prototype._template = template; }
JavaScript
static createProperties(props) { for (let p in props) { createPropertyFromConfig(this.prototype, p, props[p], props); } }
static createProperties(props) { for (let p in props) { createPropertyFromConfig(this.prototype, p, props[p], props); } }
JavaScript
static createObservers(observers, dynamicFns) { const proto = this.prototype; for (let i=0; i < observers.length; i++) { proto._createMethodObserver(observers[i], dynamicFns); } }
static createObservers(observers, dynamicFns) { const proto = this.prototype; for (let i=0; i < observers.length; i++) { proto._createMethodObserver(observers[i], dynamicFns); } }
JavaScript
static get template() { if (!this.hasOwnProperty(JSCompiler_renameProperty('_template', this))) { this._template = DomModule && DomModule.import( /** @type {PolymerElementConstructor}*/ (this).is, 'template') || // note: implemented so a subclass can retrieve the super // template; call the super impl this way so that `this` points // to the superclass. Object.getPrototypeOf(/** @type {PolymerElementConstructor}*/ (this).prototype).constructor.template; } return this._template; }
static get template() { if (!this.hasOwnProperty(JSCompiler_renameProperty('_template', this))) { this._template = DomModule && DomModule.import( /** @type {PolymerElementConstructor}*/ (this).is, 'template') || // note: implemented so a subclass can retrieve the super // template; call the super impl this way so that `this` points // to the superclass. Object.getPrototypeOf(/** @type {PolymerElementConstructor}*/ (this).prototype).constructor.template; } return this._template; }
JavaScript
static get importPath() { if (!this.hasOwnProperty(JSCompiler_renameProperty('_importPath', this))) { const meta = this.importMeta; if (meta) { this._importPath = pathFromUrl(meta.url); } else { const module = DomModule && DomModule.import(/** @type {PolymerElementConstructor} */ (this).is); this._importPath = (module && module.assetpath) || Object.getPrototypeOf(/** @type {PolymerElementConstructor}*/ (this).prototype).constructor.importPath; } } return this._importPath; }
static get importPath() { if (!this.hasOwnProperty(JSCompiler_renameProperty('_importPath', this))) { const meta = this.importMeta; if (meta) { this._importPath = pathFromUrl(meta.url); } else { const module = DomModule && DomModule.import(/** @type {PolymerElementConstructor} */ (this).is); this._importPath = (module && module.assetpath) || Object.getPrototypeOf(/** @type {PolymerElementConstructor}*/ (this).prototype).constructor.importPath; } } return this._importPath; }
JavaScript
connectedCallback() { if (window.ShadyCSS && this._template) { window.ShadyCSS.styleElement(/** @type {!HTMLElement} */(this)); } super.connectedCallback(); }
connectedCallback() { if (window.ShadyCSS && this._template) { window.ShadyCSS.styleElement(/** @type {!HTMLElement} */(this)); } super.connectedCallback(); }
JavaScript
_attachDom(dom) { if (this.attachShadow) { if (dom) { if (!this.shadowRoot) { this.attachShadow({mode: 'open'}); } this.shadowRoot.appendChild(dom); return this.shadowRoot; } return null; } else { throw new Error('ShadowDOM not available. ' + // TODO(sorvell): move to compile-time conditional when supported 'PolymerElement can create dom as children instead of in ' + 'ShadowDOM by setting `this.root = this;\` before \`ready\`.'); } }
_attachDom(dom) { if (this.attachShadow) { if (dom) { if (!this.shadowRoot) { this.attachShadow({mode: 'open'}); } this.shadowRoot.appendChild(dom); return this.shadowRoot; } return null; } else { throw new Error('ShadowDOM not available. ' + // TODO(sorvell): move to compile-time conditional when supported 'PolymerElement can create dom as children instead of in ' + 'ShadowDOM by setting `this.root = this;\` before \`ready\`.'); } }
JavaScript
updateStyles(properties) { if (window.ShadyCSS) { window.ShadyCSS.styleSubtree(/** @type {!HTMLElement} */(this), properties); } }
updateStyles(properties) { if (window.ShadyCSS) { window.ShadyCSS.styleSubtree(/** @type {!HTMLElement} */(this), properties); } }
JavaScript
resolveUrl(url, base) { if (!base && this.importPath) { base = resolveUrl(this.importPath); } return resolveUrl(url, base); }
resolveUrl(url, base) { if (!base && this.importPath) { base = resolveUrl(this.importPath); } return resolveUrl(url, base); }
JavaScript
function processUnscopedStyle(style) { const text = style.textContent; if (!styleTextSet.has(text)) { styleTextSet.add(text); const newStyle = style.cloneNode(true); document.head.appendChild(newStyle); } }
function processUnscopedStyle(style) { const text = style.textContent; if (!styleTextSet.has(text)) { styleTextSet.add(text); const newStyle = style.cloneNode(true); document.head.appendChild(newStyle); } }
JavaScript
gatherStyles(template) { const styleText = gatherStyleText(template.content); if (styleText) { const style = /** @type {!HTMLStyleElement} */(document.createElement('style')); style.textContent = styleText; template.content.insertBefore(style, template.content.firstChild); return style; } return null; }
gatherStyles(template) { const styleText = gatherStyleText(template.content); if (styleText) { const style = /** @type {!HTMLStyleElement} */(document.createElement('style')); style.textContent = styleText; template.content.insertBefore(style, template.content.firstChild); return style; } return null; }
JavaScript
function invalidateTemplate(template) { // default the current version to 0 template[CURRENT_VERSION] = template[CURRENT_VERSION] || 0; // ensure the "validating for" flag exists template[VALIDATING_VERSION] = template[VALIDATING_VERSION] || 0; // increment the next version template[NEXT_VERSION] = (template[NEXT_VERSION] || 0) + 1; }
function invalidateTemplate(template) { // default the current version to 0 template[CURRENT_VERSION] = template[CURRENT_VERSION] || 0; // ensure the "validating for" flag exists template[VALIDATING_VERSION] = template[VALIDATING_VERSION] || 0; // increment the next version template[NEXT_VERSION] = (template[NEXT_VERSION] || 0) + 1; }
JavaScript
function startValidatingTemplate(template) { // remember that the current "next version" is the reason for this validation cycle template[VALIDATING_VERSION] = template[NEXT_VERSION]; // however, there only needs to be one async task to clear the counters if (!template._validating) { template._validating = true; promise.then(function() { // sync the current version to let future invalidations cause a refresh cycle template[CURRENT_VERSION] = template[NEXT_VERSION]; template._validating = false; }); } }
function startValidatingTemplate(template) { // remember that the current "next version" is the reason for this validation cycle template[VALIDATING_VERSION] = template[NEXT_VERSION]; // however, there only needs to be one async task to clear the counters if (!template._validating) { template._validating = true; promise.then(function() { // sync the current version to let future invalidations cause a refresh cycle template[CURRENT_VERSION] = template[NEXT_VERSION]; template._validating = false; }); } }
JavaScript
enqueueDocumentValidation() { if (this['enqueued'] || !validateFn) { return; } this['enqueued'] = true; documentWait(validateFn); }
enqueueDocumentValidation() { if (this['enqueued'] || !validateFn) { return; } this['enqueued'] = true; documentWait(validateFn); }
JavaScript
cancel() { if (this.isActive()) { this._asyncModule.cancel(this._timer); this._timer = null; } }
cancel() { if (this.isActive()) { this._asyncModule.cancel(this._timer); this._timer = null; } }
JavaScript
flush() { if (this.isActive()) { this.cancel(); this._callback(); } }
flush() { if (this.isActive()) { this.cancel(); this._callback(); } }
JavaScript
static debounce(debouncer, asyncModule, callback) { if (debouncer instanceof Debouncer) { debouncer.cancel(); } else { debouncer = new Debouncer(); } debouncer.setConfig(asyncModule, callback); return debouncer; }
static debounce(debouncer, asyncModule, callback) { if (debouncer instanceof Debouncer) { debouncer.cancel(); } else { debouncer = new Debouncer(); } debouncer.setConfig(asyncModule, callback); return debouncer; }
JavaScript
function PASSIVE_TOUCH(eventName) { if (isMouseEvent(eventName) || eventName === 'touchend') { return; } if (HAS_NATIVE_TA && SUPPORTS_PASSIVE && passiveTouchGestures) { return {passive: true}; } else { return; } }
function PASSIVE_TOUCH(eventName) { if (isMouseEvent(eventName) || eventName === 'touchend') { return; } if (HAS_NATIVE_TA && SUPPORTS_PASSIVE && passiveTouchGestures) { return {passive: true}; } else { return; } }
JavaScript
function hasLeftMouseButton(ev) { let type = ev.type; // exit early if the event is not a mouse event if (!isMouseEvent(type)) { return false; } // ev.button is not reliable for mousemove (0 is overloaded as both left button and no buttons) // instead we use ev.buttons (bitmask of buttons) or fall back to ev.which (deprecated, 0 for no buttons, 1 for left button) if (type === 'mousemove') { // allow undefined for testing events let buttons = ev.buttons === undefined ? 1 : ev.buttons; if ((ev instanceof window.MouseEvent) && !MOUSE_HAS_BUTTONS) { buttons = MOUSE_WHICH_TO_BUTTONS[ev.which] || 0; } // buttons is a bitmask, check that the left button bit is set (1) return Boolean(buttons & 1); } else { // allow undefined for testing events let button = ev.button === undefined ? 0 : ev.button; // ev.button is 0 in mousedown/mouseup/click for left button activation return button === 0; } }
function hasLeftMouseButton(ev) { let type = ev.type; // exit early if the event is not a mouse event if (!isMouseEvent(type)) { return false; } // ev.button is not reliable for mousemove (0 is overloaded as both left button and no buttons) // instead we use ev.buttons (bitmask of buttons) or fall back to ev.which (deprecated, 0 for no buttons, 1 for left button) if (type === 'mousemove') { // allow undefined for testing events let buttons = ev.buttons === undefined ? 1 : ev.buttons; if ((ev instanceof window.MouseEvent) && !MOUSE_HAS_BUTTONS) { buttons = MOUSE_WHICH_TO_BUTTONS[ev.which] || 0; } // buttons is a bitmask, check that the left button bit is set (1) return Boolean(buttons & 1); } else { // allow undefined for testing events let button = ev.button === undefined ? 0 : ev.button; // ev.button is 0 in mousedown/mouseup/click for left button activation return button === 0; } }
JavaScript
function deepTargetFind(x, y) { let node = document.elementFromPoint(x, y); let next = node; // this code path is only taken when native ShadowDOM is used // if there is a shadowroot, it may have a node at x/y // if there is not a shadowroot, exit the loop while (next && next.shadowRoot && !window.ShadyDOM) { // if there is a node at x/y in the shadowroot, look deeper let oldNext = next; next = next.shadowRoot.elementFromPoint(x, y); // on Safari, elementFromPoint may return the shadowRoot host if (oldNext === next) { break; } if (next) { node = next; } } return node; }
function deepTargetFind(x, y) { let node = document.elementFromPoint(x, y); let next = node; // this code path is only taken when native ShadowDOM is used // if there is a shadowroot, it may have a node at x/y // if there is not a shadowroot, exit the loop while (next && next.shadowRoot && !window.ShadyDOM) { // if there is a node at x/y in the shadowroot, look deeper let oldNext = next; next = next.shadowRoot.elementFromPoint(x, y); // on Safari, elementFromPoint may return the shadowRoot host if (oldNext === next) { break; } if (next) { node = next; } } return node; }
JavaScript
function addListener(node, evType, handler) { if (gestures[evType]) { _add(node, evType, handler); return true; } return false; }
function addListener(node, evType, handler) { if (gestures[evType]) { _add(node, evType, handler); return true; } return false; }
JavaScript
function removeListener(node, evType, handler) { if (gestures[evType]) { _remove(node, evType, handler); return true; } return false; }
function removeListener(node, evType, handler) { if (gestures[evType]) { _remove(node, evType, handler); return true; } return false; }
JavaScript
function register$1(recog) { recognizers.push(recog); for (let i = 0; i < recog.emits.length; i++) { gestures[recog.emits[i]] = recog; } }
function register$1(recog) { recognizers.push(recog); for (let i = 0; i < recog.emits.length; i++) { gestures[recog.emits[i]] = recog; } }
JavaScript
function resetMouseCanceller() { if (POINTERSTATE.mouse.mouseIgnoreJob) { POINTERSTATE.mouse.mouseIgnoreJob.flush(); } }
function resetMouseCanceller() { if (POINTERSTATE.mouse.mouseIgnoreJob) { POINTERSTATE.mouse.mouseIgnoreJob.flush(); } }
JavaScript
_addEventListenerToNode(node, eventName, handler) { if (!gestures$1.addListener(node, eventName, handler)) { super._addEventListenerToNode(node, eventName, handler); } }
_addEventListenerToNode(node, eventName, handler) { if (!gestures$1.addListener(node, eventName, handler)) { super._addEventListenerToNode(node, eventName, handler); } }
JavaScript
_removeEventListenerFromNode(node, eventName, handler) { if (!gestures$1.removeListener(node, eventName, handler)) { super._removeEventListenerFromNode(node, eventName, handler); } }
_removeEventListenerFromNode(node, eventName, handler) { if (!gestures$1.removeListener(node, eventName, handler)) { super._removeEventListenerFromNode(node, eventName, handler); } }
JavaScript
function calcSplices(current, currentStart, currentEnd, old, oldStart, oldEnd) { let prefixCount = 0; let suffixCount = 0; let splice; let minLength = Math.min(currentEnd - currentStart, oldEnd - oldStart); if (currentStart == 0 && oldStart == 0) prefixCount = sharedPrefix(current, old, minLength); if (currentEnd == current.length && oldEnd == old.length) suffixCount = sharedSuffix(current, old, minLength - prefixCount); currentStart += prefixCount; oldStart += prefixCount; currentEnd -= suffixCount; oldEnd -= suffixCount; if (currentEnd - currentStart == 0 && oldEnd - oldStart == 0) return []; if (currentStart == currentEnd) { splice = newSplice(currentStart, [], 0); while (oldStart < oldEnd) splice.removed.push(old[oldStart++]); return [ splice ]; } else if (oldStart == oldEnd) return [ newSplice(currentStart, [], currentEnd - currentStart) ]; let ops = spliceOperationsFromEditDistances( calcEditDistances(current, currentStart, currentEnd, old, oldStart, oldEnd)); splice = undefined; let splices = []; let index = currentStart; let oldIndex = oldStart; for (let i = 0; i < ops.length; i++) { switch(ops[i]) { case EDIT_LEAVE: if (splice) { splices.push(splice); splice = undefined; } index++; oldIndex++; break; case EDIT_UPDATE: if (!splice) splice = newSplice(index, [], 0); splice.addedCount++; index++; splice.removed.push(old[oldIndex]); oldIndex++; break; case EDIT_ADD: if (!splice) splice = newSplice(index, [], 0); splice.addedCount++; index++; break; case EDIT_DELETE: if (!splice) splice = newSplice(index, [], 0); splice.removed.push(old[oldIndex]); oldIndex++; break; } } if (splice) { splices.push(splice); } return splices; }
function calcSplices(current, currentStart, currentEnd, old, oldStart, oldEnd) { let prefixCount = 0; let suffixCount = 0; let splice; let minLength = Math.min(currentEnd - currentStart, oldEnd - oldStart); if (currentStart == 0 && oldStart == 0) prefixCount = sharedPrefix(current, old, minLength); if (currentEnd == current.length && oldEnd == old.length) suffixCount = sharedSuffix(current, old, minLength - prefixCount); currentStart += prefixCount; oldStart += prefixCount; currentEnd -= suffixCount; oldEnd -= suffixCount; if (currentEnd - currentStart == 0 && oldEnd - oldStart == 0) return []; if (currentStart == currentEnd) { splice = newSplice(currentStart, [], 0); while (oldStart < oldEnd) splice.removed.push(old[oldStart++]); return [ splice ]; } else if (oldStart == oldEnd) return [ newSplice(currentStart, [], currentEnd - currentStart) ]; let ops = spliceOperationsFromEditDistances( calcEditDistances(current, currentStart, currentEnd, old, oldStart, oldEnd)); splice = undefined; let splices = []; let index = currentStart; let oldIndex = oldStart; for (let i = 0; i < ops.length; i++) { switch(ops[i]) { case EDIT_LEAVE: if (splice) { splices.push(splice); splice = undefined; } index++; oldIndex++; break; case EDIT_UPDATE: if (!splice) splice = newSplice(index, [], 0); splice.addedCount++; index++; splice.removed.push(old[oldIndex]); oldIndex++; break; case EDIT_ADD: if (!splice) splice = newSplice(index, [], 0); splice.addedCount++; index++; break; case EDIT_DELETE: if (!splice) splice = newSplice(index, [], 0); splice.removed.push(old[oldIndex]); oldIndex++; break; } } if (splice) { splices.push(splice); } return splices; }
JavaScript
connect() { if (isSlot(this._target)) { this._listenSlots([this._target]); } else if (this._target.children) { this._listenSlots(this._target.children); if (window.ShadyDOM) { this._shadyChildrenObserver = ShadyDOM.observeChildren(this._target, (mutations) => { this._processMutations(mutations); }); } else { this._nativeChildrenObserver = new MutationObserver((mutations) => { this._processMutations(mutations); }); this._nativeChildrenObserver.observe(this._target, {childList: true}); } } this._connected = true; }
connect() { if (isSlot(this._target)) { this._listenSlots([this._target]); } else if (this._target.children) { this._listenSlots(this._target.children); if (window.ShadyDOM) { this._shadyChildrenObserver = ShadyDOM.observeChildren(this._target, (mutations) => { this._processMutations(mutations); }); } else { this._nativeChildrenObserver = new MutationObserver((mutations) => { this._processMutations(mutations); }); this._nativeChildrenObserver.observe(this._target, {childList: true}); } } this._connected = true; }
JavaScript
disconnect() { if (isSlot(this._target)) { this._unlistenSlots([this._target]); } else if (this._target.children) { this._unlistenSlots(this._target.children); if (window.ShadyDOM && this._shadyChildrenObserver) { ShadyDOM.unobserveChildren(this._shadyChildrenObserver); this._shadyChildrenObserver = null; } else if (this._nativeChildrenObserver) { this._nativeChildrenObserver.disconnect(); this._nativeChildrenObserver = null; } } this._connected = false; }
disconnect() { if (isSlot(this._target)) { this._unlistenSlots([this._target]); } else if (this._target.children) { this._unlistenSlots(this._target.children); if (window.ShadyDOM && this._shadyChildrenObserver) { ShadyDOM.unobserveChildren(this._shadyChildrenObserver); this._shadyChildrenObserver = null; } else if (this._nativeChildrenObserver) { this._nativeChildrenObserver.disconnect(); this._nativeChildrenObserver = null; } } this._connected = false; }
JavaScript
flush() { if (!this._connected) { return false; } if (window.ShadyDOM) { ShadyDOM.flush(); } if (this._nativeChildrenObserver) { this._processSlotMutations(this._nativeChildrenObserver.takeRecords()); } else if (this._shadyChildrenObserver) { this._processSlotMutations(this._shadyChildrenObserver.takeRecords()); } this._scheduled = false; let info = { target: this._target, addedNodes: [], removedNodes: [] }; let newNodes = this.constructor.getFlattenedNodes(this._target); let splices = calculateSplices(newNodes, this._effectiveNodes); // process removals for (let i=0, s; (i<splices.length) && (s=splices[i]); i++) { for (let j=0, n; (j < s.removed.length) && (n=s.removed[j]); j++) { info.removedNodes.push(n); } } // process adds for (let i=0, s; (i<splices.length) && (s=splices[i]); i++) { for (let j=s.index; j < s.index + s.addedCount; j++) { info.addedNodes.push(newNodes[j]); } } // update cache this._effectiveNodes = newNodes; let didFlush = false; if (info.addedNodes.length || info.removedNodes.length) { didFlush = true; this.callback.call(this._target, info); } return didFlush; }
flush() { if (!this._connected) { return false; } if (window.ShadyDOM) { ShadyDOM.flush(); } if (this._nativeChildrenObserver) { this._processSlotMutations(this._nativeChildrenObserver.takeRecords()); } else if (this._shadyChildrenObserver) { this._processSlotMutations(this._shadyChildrenObserver.takeRecords()); } this._scheduled = false; let info = { target: this._target, addedNodes: [], removedNodes: [] }; let newNodes = this.constructor.getFlattenedNodes(this._target); let splices = calculateSplices(newNodes, this._effectiveNodes); // process removals for (let i=0, s; (i<splices.length) && (s=splices[i]); i++) { for (let j=0, n; (j < s.removed.length) && (n=s.removed[j]); j++) { info.removedNodes.push(n); } } // process adds for (let i=0, s; (i<splices.length) && (s=splices[i]); i++) { for (let j=s.index; j < s.index + s.addedCount; j++) { info.addedNodes.push(newNodes[j]); } } // update cache this._effectiveNodes = newNodes; let didFlush = false; if (info.addedNodes.length || info.removedNodes.length) { didFlush = true; this.callback.call(this._target, info); } return didFlush; }
JavaScript
deepContains(node) { if (this.node.contains(node)) { return true; } let n = node; let doc = node.ownerDocument; // walk from node to `this` or `document` while (n && n !== doc && n !== this.node) { // use logical parentnode, or native ShadowRoot host n = n.parentNode || n.host; } return n === this.node; }
deepContains(node) { if (this.node.contains(node)) { return true; } let n = node; let doc = node.ownerDocument; // walk from node to `this` or `document` while (n && n !== doc && n !== this.node) { // use logical parentnode, or native ShadowRoot host n = n.parentNode || n.host; } return n === this.node; }
JavaScript
importNode(node, deep) { let doc = this.node instanceof Document ? this.node : this.node.ownerDocument; return doc.importNode(node, deep); }
importNode(node, deep) { let doc = this.node instanceof Document ? this.node : this.node.ownerDocument; return doc.importNode(node, deep); }
JavaScript
queryDistributedElements(selector) { let c$ = this.getEffectiveChildNodes(); let list = []; for (let i=0, l=c$.length, c; (i<l) && (c=c$[i]); i++) { if ((c.nodeType === Node.ELEMENT_NODE) && matchesSelector(c, selector)) { list.push(c); } } return list; }
queryDistributedElements(selector) { let c$ = this.getEffectiveChildNodes(); let list = []; for (let i=0, l=c$.length, c; (i<l) && (c=c$[i]); i++) { if ((c.nodeType === Node.ELEMENT_NODE) && matchesSelector(c, selector)) { list.push(c); } } return list; }
JavaScript
_initializeProperties() { let proto = Object.getPrototypeOf(this); if (!proto.hasOwnProperty('__hasRegisterFinished')) { proto.__hasRegisterFinished = true; this._registered(); } super._initializeProperties(); this.root = /** @type {HTMLElement} */(this); this.created(); }
_initializeProperties() { let proto = Object.getPrototypeOf(this); if (!proto.hasOwnProperty('__hasRegisterFinished')) { proto.__hasRegisterFinished = true; this._registered(); } super._initializeProperties(); this.root = /** @type {HTMLElement} */(this); this.created(); }
JavaScript
extend(prototype, api) { if (!(prototype && api)) { return prototype || api; } let n$ = Object.getOwnPropertyNames(api); for (let i=0, n; (i<n$.length) && (n=n$[i]); i++) { let pd = Object.getOwnPropertyDescriptor(api, n); if (pd) { Object.defineProperty(prototype, n, pd); } } return prototype; }
extend(prototype, api) { if (!(prototype && api)) { return prototype || api; } let n$ = Object.getOwnPropertyNames(api); for (let i=0, n; (i<n$.length) && (n=n$[i]); i++) { let pd = Object.getOwnPropertyDescriptor(api, n); if (pd) { Object.defineProperty(prototype, n, pd); } } return prototype; }
JavaScript
mixin(target, source) { for (let i in source) { target[i] = source[i]; } return target; }
mixin(target, source) { for (let i in source) { target[i] = source[i]; } return target; }
JavaScript
chainObject(object, prototype) { if (object && prototype && object !== prototype) { object.__proto__ = prototype; } return object; }
chainObject(object, prototype) { if (object && prototype && object !== prototype) { object.__proto__ = prototype; } return object; }
JavaScript
instanceTemplate(template) { let content = this.constructor._contentForTemplate(template); let dom$$1 = /** @type {!DocumentFragment} */ (document.importNode(content, true)); return dom$$1; }
instanceTemplate(template) { let content = this.constructor._contentForTemplate(template); let dom$$1 = /** @type {!DocumentFragment} */ (document.importNode(content, true)); return dom$$1; }
JavaScript
listen(node, eventName, methodName) { node = /** @type {!Element} */ (node || this); let hbl = this.__boundListeners || (this.__boundListeners = new WeakMap()); let bl = hbl.get(node); if (!bl) { bl = {}; hbl.set(node, bl); } let key = eventName + methodName; if (!bl[key]) { bl[key] = this._addMethodEventListenerToNode( node, eventName, methodName, this); } }
listen(node, eventName, methodName) { node = /** @type {!Element} */ (node || this); let hbl = this.__boundListeners || (this.__boundListeners = new WeakMap()); let bl = hbl.get(node); if (!bl) { bl = {}; hbl.set(node, bl); } let key = eventName + methodName; if (!bl[key]) { bl[key] = this._addMethodEventListenerToNode( node, eventName, methodName, this); } }
JavaScript
unlisten(node, eventName, methodName) { node = /** @type {!Element} */ (node || this); let bl = this.__boundListeners && this.__boundListeners.get(node); let key = eventName + methodName; let handler = bl && bl[key]; if (handler) { this._removeEventListenerFromNode(node, eventName, handler); bl[key] = null; } }
unlisten(node, eventName, methodName) { node = /** @type {!Element} */ (node || this); let bl = this.__boundListeners && this.__boundListeners.get(node); let key = eventName + methodName; let handler = bl && bl[key]; if (handler) { this._removeEventListenerFromNode(node, eventName, handler); bl[key] = null; } }
JavaScript
distributeContent() { if (window.ShadyDOM && this.shadowRoot) { ShadyDOM.flush(); } }
distributeContent() { if (window.ShadyDOM && this.shadowRoot) { ShadyDOM.flush(); } }
JavaScript
queryDistributedElements(selector) { const thisEl = /** @type {Element} */ (this); const domApi = /** @type {DomApi} */(dom(thisEl)); return domApi.queryDistributedElements(selector); }
queryDistributedElements(selector) { const thisEl = /** @type {Element} */ (this); const domApi = /** @type {DomApi} */(dom(thisEl)); return domApi.queryDistributedElements(selector); }
JavaScript
isLightDescendant(node) { const thisNode = /** @type {Node} */ (this); return thisNode !== node && thisNode.contains(node) && thisNode.getRootNode() === node.getRootNode(); }
isLightDescendant(node) { const thisNode = /** @type {Node} */ (this); return thisNode !== node && thisNode.contains(node) && thisNode.getRootNode() === node.getRootNode(); }
JavaScript
isDebouncerActive(jobName) { this._debouncers = this._debouncers || {}; let debouncer = this._debouncers[jobName]; return !!(debouncer && debouncer.isActive()); }
isDebouncerActive(jobName) { this._debouncers = this._debouncers || {}; let debouncer = this._debouncers[jobName]; return !!(debouncer && debouncer.isActive()); }
JavaScript
flushDebouncer(jobName) { this._debouncers = this._debouncers || {}; let debouncer = this._debouncers[jobName]; if (debouncer) { debouncer.flush(); } }
flushDebouncer(jobName) { this._debouncers = this._debouncers || {}; let debouncer = this._debouncers[jobName]; if (debouncer) { debouncer.flush(); } }
JavaScript
create(tag, props) { let elt = document.createElement(tag); if (props) { if (elt.setProperties) { elt.setProperties(props); } else { for (let n in props) { elt[n] = props[n]; } } } return elt; }
create(tag, props) { let elt = document.createElement(tag); if (props) { if (elt.setProperties) { elt.setProperties(props); } else { for (let n in props) { elt[n] = props[n]; } } } return elt; }
JavaScript
static get template() { // get template first from any imperative set in `info._template` return info._template || // next look in dom-module associated with this element's is. DomModule && DomModule.import(this.is, 'template') || // next look for superclass template (note: use superclass symbol // to ensure correct `this.is`) Base.template || // finally fall back to `_template` in element's prototype. this.prototype._template || null; }
static get template() { // get template first from any imperative set in `info._template` return info._template || // next look in dom-module associated with this element's is. DomModule && DomModule.import(this.is, 'template') || // next look for superclass template (note: use superclass symbol // to ensure correct `this.is`) Base.template || // finally fall back to `_template` in element's prototype. this.prototype._template || null; }
JavaScript
function mutablePropertyChange(inst, property, value, old, mutableData) { let isObject; if (mutableData) { isObject = (typeof value === 'object' && value !== null); // Pull `old` for Objects from temp cache, but treat `null` as a primitive if (isObject) { old = inst.__dataTemp[property]; } } // Strict equality check, but return false for NaN===NaN let shouldChange = (old !== value && (old === old || value === value)); // Objects are stored in temporary cache (cleared at end of // turn), which is used for dirty-checking if (isObject && shouldChange) { inst.__dataTemp[property] = value; } return shouldChange; }
function mutablePropertyChange(inst, property, value, old, mutableData) { let isObject; if (mutableData) { isObject = (typeof value === 'object' && value !== null); // Pull `old` for Objects from temp cache, but treat `null` as a primitive if (isObject) { old = inst.__dataTemp[property]; } } // Strict equality check, but return false for NaN===NaN let shouldChange = (old !== value && (old === old || value === value)); // Objects are stored in temporary cache (cleared at end of // turn), which is used for dirty-checking if (isObject && shouldChange) { inst.__dataTemp[property] = value; } return shouldChange; }
JavaScript
function upgradeTemplate(template, constructor) { newInstance = template; Object.setPrototypeOf(template, constructor.prototype); new constructor(); newInstance = null; }
function upgradeTemplate(template, constructor) { newInstance = template; Object.setPrototypeOf(template, constructor.prototype); new constructor(); newInstance = null; }
JavaScript
forwardHostProp(prop, value) { if (this._setPendingPropertyOrPath(prop, value, false, true)) { this.__dataHost._enqueueClient(this); } }
forwardHostProp(prop, value) { if (this._setPendingPropertyOrPath(prop, value, false, true)) { this.__dataHost._enqueueClient(this); } }
JavaScript
_setUnmanagedPropertyToNode(node, prop, value) { if (node.__hideTemplateChildren__ && node.nodeType == Node.TEXT_NODE && prop == 'textContent') { node.__polymerTextContent__ = value; } else { super._setUnmanagedPropertyToNode(node, prop, value); } }
_setUnmanagedPropertyToNode(node, prop, value) { if (node.__hideTemplateChildren__ && node.nodeType == Node.TEXT_NODE && prop == 'textContent') { node.__polymerTextContent__ = value; } else { super._setUnmanagedPropertyToNode(node, prop, value); } }
JavaScript
get parentModel() { let model = this.__parentModel; if (!model) { let options; model = this; do { // A template instance's `__dataHost` is a <template> // `model.__dataHost.__dataHost` is the template's host model = model.__dataHost.__dataHost; } while ((options = model.__templatizeOptions) && !options.parentModel); this.__parentModel = model; } return model; }
get parentModel() { let model = this.__parentModel; if (!model) { let options; model = this; do { // A template instance's `__dataHost` is a <template> // `model.__dataHost.__dataHost` is the template's host model = model.__dataHost.__dataHost; } while ((options = model.__templatizeOptions) && !options.parentModel); this.__parentModel = model; } return model; }
JavaScript
function createTemplatizerClass(template, templateInfo, options) { // Anonymous class created by the templatize let base = options.mutableData ? MutableTemplateInstanceBase : TemplateInstanceBase; /** * @constructor * @extends {base} * @private */ let klass = class extends base { }; klass.prototype.__templatizeOptions = options; klass.prototype._bindTemplate(template); addNotifyEffects(klass, template, templateInfo, options); return klass; }
function createTemplatizerClass(template, templateInfo, options) { // Anonymous class created by the templatize let base = options.mutableData ? MutableTemplateInstanceBase : TemplateInstanceBase; /** * @constructor * @extends {base} * @private */ let klass = class extends base { }; klass.prototype.__templatizeOptions = options; klass.prototype._bindTemplate(template); addNotifyEffects(klass, template, templateInfo, options); return klass; }
JavaScript
function addPropagateEffects(template, templateInfo, options) { let userForwardHostProp = options.forwardHostProp; if (userForwardHostProp) { // Provide data API and property effects on memoized template class let klass = templateInfo.templatizeTemplateClass; if (!klass) { let base = options.mutableData ? MutableDataTemplate : DataTemplate; /** @private */ klass = templateInfo.templatizeTemplateClass = class TemplatizedTemplate extends base {}; // Add template - >instances effects // and host <- template effects let hostProps = templateInfo.hostProps; for (let prop in hostProps) { klass.prototype._addPropertyEffect('_host_' + prop, klass.prototype.PROPERTY_EFFECT_TYPES.PROPAGATE, {fn: createForwardHostPropEffect(prop, userForwardHostProp)}); klass.prototype._createNotifyingProperty('_host_' + prop); } } upgradeTemplate(template, klass); // Mix any pre-bound data into __data; no need to flush this to // instances since they pull from the template at instance-time if (template.__dataProto) { // Note, generally `__dataProto` could be chained, but it's guaranteed // to not be since this is a vanilla template we just added effects to Object.assign(template.__data, template.__dataProto); } // Clear any pending data for performance template.__dataTemp = {}; template.__dataPending = null; template.__dataOld = null; template._enableProperties(); } }
function addPropagateEffects(template, templateInfo, options) { let userForwardHostProp = options.forwardHostProp; if (userForwardHostProp) { // Provide data API and property effects on memoized template class let klass = templateInfo.templatizeTemplateClass; if (!klass) { let base = options.mutableData ? MutableDataTemplate : DataTemplate; /** @private */ klass = templateInfo.templatizeTemplateClass = class TemplatizedTemplate extends base {}; // Add template - >instances effects // and host <- template effects let hostProps = templateInfo.hostProps; for (let prop in hostProps) { klass.prototype._addPropertyEffect('_host_' + prop, klass.prototype.PROPERTY_EFFECT_TYPES.PROPAGATE, {fn: createForwardHostPropEffect(prop, userForwardHostProp)}); klass.prototype._createNotifyingProperty('_host_' + prop); } } upgradeTemplate(template, klass); // Mix any pre-bound data into __data; no need to flush this to // instances since they pull from the template at instance-time if (template.__dataProto) { // Note, generally `__dataProto` could be chained, but it's guaranteed // to not be since this is a vanilla template we just added effects to Object.assign(template.__data, template.__dataProto); } // Clear any pending data for performance template.__dataTemp = {}; template.__dataPending = null; template.__dataOld = null; template._enableProperties(); } }
JavaScript
function modelForElement(template, node) { let model; while (node) { // An element with a __templatizeInstance marks the top boundary // of a scope; walk up until we find one, and then ensure that // its __dataHost matches `this`, meaning this dom-repeat stamped it if ((model = node.__templatizeInstance)) { // Found an element stamped by another template; keep walking up // from its __dataHost if (model.__dataHost != template) { node = model.__dataHost; } else { return model; } } else { // Still in a template scope, keep going up until // a __templatizeInstance is found node = node.parentNode; } } return null; }
function modelForElement(template, node) { let model; while (node) { // An element with a __templatizeInstance marks the top boundary // of a scope; walk up until we find one, and then ensure that // its __dataHost matches `this`, meaning this dom-repeat stamped it if ((model = node.__templatizeInstance)) { // Found an element stamped by another template; keep walking up // from its __dataHost if (model.__dataHost != template) { node = model.__dataHost; } else { return model; } } else { // Still in a template scope, keep going up until // a __templatizeInstance is found node = node.parentNode; } } return null; }
JavaScript
render() { let template; if (!this.__children) { template = /** @type {HTMLTemplateElement} */(template || this.querySelector('template')); if (!template) { // Wait until childList changes and template should be there by then let observer = new MutationObserver(() => { template = /** @type {HTMLTemplateElement} */(this.querySelector('template')); if (template) { observer.disconnect(); this.render(); } else { throw new Error('dom-bind requires a <template> child'); } }); observer.observe(this, {childList: true}); return; } this.root = this._stampTemplate(template); this.$ = this.root.$; this.__children = []; for (let n=this.root.firstChild; n; n=n.nextSibling) { this.__children[this.__children.length] = n; } this._enableProperties(); } this.__insertChildren(); this.dispatchEvent(new CustomEvent('dom-change', { bubbles: true, composed: true })); }
render() { let template; if (!this.__children) { template = /** @type {HTMLTemplateElement} */(template || this.querySelector('template')); if (!template) { // Wait until childList changes and template should be there by then let observer = new MutationObserver(() => { template = /** @type {HTMLTemplateElement} */(this.querySelector('template')); if (template) { observer.disconnect(); this.render(); } else { throw new Error('dom-bind requires a <template> child'); } }); observer.observe(this, {childList: true}); return; } this.root = this._stampTemplate(template); this.$ = this.root.$; this.__children = []; for (let n=this.root.firstChild; n; n=n.nextSibling) { this.__children[this.__children.length] = n; } this._enableProperties(); } this.__insertChildren(); this.dispatchEvent(new CustomEvent('dom-change', { bubbles: true, composed: true })); }
JavaScript
render() { // Queue this repeater, then flush all in order this.__debounceRender(this.__render); flush$1(); }
render() { // Queue this repeater, then flush all in order this.__debounceRender(this.__render); flush$1(); }
JavaScript
__handleItemPath(path, value) { let itemsPath = path.slice(6); // 'items.'.length == 6 let dot = itemsPath.indexOf('.'); let itemsIdx = dot < 0 ? itemsPath : itemsPath.substring(0, dot); // If path was index into array... if (itemsIdx == parseInt(itemsIdx, 10)) { let itemSubPath = dot < 0 ? '' : itemsPath.substring(dot+1); // If the path is observed, it will trigger a full refresh this.__handleObservedPaths(itemSubPath); // Note, even if a rull refresh is triggered, always do the path // notification because unless mutableData is used for dom-repeat // and all elements in the instance subtree, a full refresh may // not trigger the proper update. let instIdx = this.__itemsIdxToInstIdx[itemsIdx]; let inst = this.__instances[instIdx]; if (inst) { let itemPath = this.as + (itemSubPath ? '.' + itemSubPath : ''); // This is effectively `notifyPath`, but avoids some of the overhead // of the public API inst._setPendingPropertyOrPath(itemPath, value, false, true); inst._flushProperties(); } return true; } }
__handleItemPath(path, value) { let itemsPath = path.slice(6); // 'items.'.length == 6 let dot = itemsPath.indexOf('.'); let itemsIdx = dot < 0 ? itemsPath : itemsPath.substring(0, dot); // If path was index into array... if (itemsIdx == parseInt(itemsIdx, 10)) { let itemSubPath = dot < 0 ? '' : itemsPath.substring(dot+1); // If the path is observed, it will trigger a full refresh this.__handleObservedPaths(itemSubPath); // Note, even if a rull refresh is triggered, always do the path // notification because unless mutableData is used for dom-repeat // and all elements in the instance subtree, a full refresh may // not trigger the proper update. let instIdx = this.__itemsIdxToInstIdx[itemsIdx]; let inst = this.__instances[instIdx]; if (inst) { let itemPath = this.as + (itemSubPath ? '.' + itemSubPath : ''); // This is effectively `notifyPath`, but avoids some of the overhead // of the public API inst._setPendingPropertyOrPath(itemPath, value, false, true); inst._flushProperties(); } return true; } }
JavaScript
function normalizedKeyForEvent(keyEvent, noSpecialChars) { // Fall back from .key, to .detail.key for artifical keyboard events, // and then to deprecated .keyIdentifier and .keyCode. if (keyEvent.key) { return transformKey(keyEvent.key, noSpecialChars); } if (keyEvent.detail && keyEvent.detail.key) { return transformKey(keyEvent.detail.key, noSpecialChars); } return transformKeyIdentifier(keyEvent.keyIdentifier) || transformKeyCode(keyEvent.keyCode) || ''; }
function normalizedKeyForEvent(keyEvent, noSpecialChars) { // Fall back from .key, to .detail.key for artifical keyboard events, // and then to deprecated .keyIdentifier and .keyCode. if (keyEvent.key) { return transformKey(keyEvent.key, noSpecialChars); } if (keyEvent.detail && keyEvent.detail.key) { return transformKey(keyEvent.detail.key, noSpecialChars); } return transformKeyIdentifier(keyEvent.keyIdentifier) || transformKeyCode(keyEvent.keyCode) || ''; }
JavaScript
get inputElement() { // Chrome generates audit errors if an <input type="password"> has a // duplicate ID, which is almost always true in Shady DOM. Generate // a unique ID instead. if (!this.$) { this.$ = {}; } if (!this.$.input) { this._generateInputId(); this.$.input = this.$$('#' + this._inputId); } return this.$.input; }
get inputElement() { // Chrome generates audit errors if an <input type="password"> has a // duplicate ID, which is almost always true in Shady DOM. Generate // a unique ID instead. if (!this.$) { this.$ = {}; } if (!this.$.input) { this._generateInputId(); this.$.input = this.$$('#' + this._inputId); } return this.$.input; }