web-component-wrapper
Version:
Generic web-component base class and framework specific wrapper.
454 lines (441 loc) • 101 kB
JavaScript
if(typeof window==='undefined'||window===null)var window=(typeof globalThis==='undefined'||globalThis===null)?{}:globalThis;import { flushSync as __WEBPACK_EXTERNAL_MODULE_react_dom_c0b5c364_flushSync__ } from "react-dom";
import { createRoot as __WEBPACK_EXTERNAL_MODULE_react_dom_client_82ef521c_createRoot__ } from "react-dom/client";
import * as __WEBPACK_EXTERNAL_MODULE_clientnode__ from "clientnode";
import * as __WEBPACK_EXTERNAL_MODULE_clientnode_property_types_4789ebe2__ from "clientnode/property-types";
import * as __WEBPACK_EXTERNAL_MODULE_react__ from "react";
/******/ var __webpack_modules__ = ([
/* 0 */
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
const x = (y) => {
const x = {}; __webpack_require__.d(x, y); return x
}
const y = (x) => (() => (x))
module.exports = x({ ["Logger"]: () => (__WEBPACK_EXTERNAL_MODULE_clientnode__.Logger), ["NOOP"]: () => (__WEBPACK_EXTERNAL_MODULE_clientnode__.NOOP), ["UTILITY_SCOPE"]: () => (__WEBPACK_EXTERNAL_MODULE_clientnode__.UTILITY_SCOPE), ["UTILITY_SCOPE_NAMES"]: () => (__WEBPACK_EXTERNAL_MODULE_clientnode__.UTILITY_SCOPE_NAMES), ["camelCaseToDelimited"]: () => (__WEBPACK_EXTERNAL_MODULE_clientnode__.camelCaseToDelimited), ["compile"]: () => (__WEBPACK_EXTERNAL_MODULE_clientnode__.compile), ["convertPlainObjectToMap"]: () => (__WEBPACK_EXTERNAL_MODULE_clientnode__.convertPlainObjectToMap), ["copy"]: () => (__WEBPACK_EXTERNAL_MODULE_clientnode__.copy), ["delimitedToCamelCase"]: () => (__WEBPACK_EXTERNAL_MODULE_clientnode__.delimitedToCamelCase), ["evaluate"]: () => (__WEBPACK_EXTERNAL_MODULE_clientnode__.evaluate), ["extend"]: () => (__WEBPACK_EXTERNAL_MODULE_clientnode__.extend), ["isFunction"]: () => (__WEBPACK_EXTERNAL_MODULE_clientnode__.isFunction), ["isObject"]: () => (__WEBPACK_EXTERNAL_MODULE_clientnode__.isObject), ["lowerCase"]: () => (__WEBPACK_EXTERNAL_MODULE_clientnode__.lowerCase), ["replace"]: () => (__WEBPACK_EXTERNAL_MODULE_clientnode__.replace), ["represent"]: () => (__WEBPACK_EXTERNAL_MODULE_clientnode__.represent), ["timeout"]: () => (__WEBPACK_EXTERNAL_MODULE_clientnode__.timeout), ["unique"]: () => (__WEBPACK_EXTERNAL_MODULE_clientnode__.unique), ["unwrap"]: () => (__WEBPACK_EXTERNAL_MODULE_clientnode__.unwrap) });
/***/ }),
/* 1 */
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
const x = (y) => {
const x = {}; __webpack_require__.d(x, y); return x
}
const y = (x) => (() => (x))
module.exports = x({ ["NullSymbol"]: () => (__WEBPACK_EXTERNAL_MODULE_clientnode_property_types_4789ebe2__.NullSymbol), ["UndefinedSymbol"]: () => (__WEBPACK_EXTERNAL_MODULE_clientnode_property_types_4789ebe2__.UndefinedSymbol), ["any"]: () => (__WEBPACK_EXTERNAL_MODULE_clientnode_property_types_4789ebe2__.any), ["array"]: () => (__WEBPACK_EXTERNAL_MODULE_clientnode_property_types_4789ebe2__.array), ["arrayOf"]: () => (__WEBPACK_EXTERNAL_MODULE_clientnode_property_types_4789ebe2__.arrayOf), ["boolean"]: () => (__WEBPACK_EXTERNAL_MODULE_clientnode_property_types_4789ebe2__.boolean), ["element"]: () => (__WEBPACK_EXTERNAL_MODULE_clientnode_property_types_4789ebe2__.element), ["elementType"]: () => (__WEBPACK_EXTERNAL_MODULE_clientnode_property_types_4789ebe2__.elementType), ["exact"]: () => (__WEBPACK_EXTERNAL_MODULE_clientnode_property_types_4789ebe2__.exact), ["func"]: () => (__WEBPACK_EXTERNAL_MODULE_clientnode_property_types_4789ebe2__.func), ["instanceOf"]: () => (__WEBPACK_EXTERNAL_MODULE_clientnode_property_types_4789ebe2__.instanceOf), ["node"]: () => (__WEBPACK_EXTERNAL_MODULE_clientnode_property_types_4789ebe2__.node), ["number"]: () => (__WEBPACK_EXTERNAL_MODULE_clientnode_property_types_4789ebe2__.number), ["object"]: () => (__WEBPACK_EXTERNAL_MODULE_clientnode_property_types_4789ebe2__.object), ["objectOf"]: () => (__WEBPACK_EXTERNAL_MODULE_clientnode_property_types_4789ebe2__.objectOf), ["oneOf"]: () => (__WEBPACK_EXTERNAL_MODULE_clientnode_property_types_4789ebe2__.oneOf), ["oneOfType"]: () => (__WEBPACK_EXTERNAL_MODULE_clientnode_property_types_4789ebe2__.oneOfType), ["shape"]: () => (__WEBPACK_EXTERNAL_MODULE_clientnode_property_types_4789ebe2__.shape), ["string"]: () => (__WEBPACK_EXTERNAL_MODULE_clientnode_property_types_4789ebe2__.string), ["symbol"]: () => (__WEBPACK_EXTERNAL_MODULE_clientnode_property_types_4789ebe2__.symbol) });
/***/ }),
/* 2 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* unused harmony export property */
/* harmony import */ var clientnode__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var clientnode_property_types__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1);
// #!/usr/bin/env babel-node
// -*- coding: utf-8 -*-
/** @module decorator *//* !
region header
[Project page](https://torben.website/web-component-wrapper)
Copyright Torben Sickert (info["~at~"]torben.website) 16.12.2012
License
-------
This library written by Torben Sickert stands under a creative commons
naming 3.0 unported license.
See https://creativecommons.org/licenses/by/3.0/deed.de
endregion
*/// region imports
// endregion
/**
* Generates a decorator based on given configuration.
* @param options - Property configuration to define how to transfer attributes
* and properties into each other.
* @param options.alias - Alternate property name.
* @param options.readAttribute - Indicates whether to read from existing
* attribute also.
* @param options.type - Value type to parse value.
* @param options.update - Indicates whether to overwrite already existing
* property configurations.
* @param options.writeAttribute - Indicates whether to sync attribute
* representation back into dom.
* @returns Generated decorator.
*/function property(options={}){options={readAttribute:true,type:clientnode_property_types__WEBPACK_IMPORTED_MODULE_1__.string,...options};/**
* Registers given property to different property / attribute conversion
* data structures.
* NOTE: It is important to set static configuration properties on its
* "own" properties instead of some inherited one. So we have to check via
* "hasOwnProperty" for existence in this decorator.
* @param target - Instance to apply given property to.
* @param name - Field name to apply.
*/return function(target,name){if(typeof name!=="string")return;const self=target.self||target.constructor;if(options.readAttribute){if(!Object.prototype.hasOwnProperty.call(self,"observedAttributes"))self.observedAttributes=self.observedAttributes?[...self.observedAttributes]:[];const attributeName=(0,clientnode__WEBPACK_IMPORTED_MODULE_0__.camelCaseToDelimited)(name);if(self.observedAttributes&&!self.observedAttributes.includes(attributeName))self.observedAttributes.push(attributeName)}if(options.type){if(!Object.prototype.hasOwnProperty.call(self,"propertyTypes"))self.propertyTypes=self.propertyTypes?{...self.propertyTypes}:{};if(self.propertyTypes&&(options.update||!Object.prototype.hasOwnProperty.call(self,name)))self.propertyTypes[name]=options.type}if(options.writeAttribute){if(!Object.prototype.hasOwnProperty.call(self,"propertiesToReflectAsAttributes"))self.propertiesToReflectAsAttributes=self.propertiesToReflectAsAttributes?(0,clientnode__WEBPACK_IMPORTED_MODULE_0__.copy)(self.propertiesToReflectAsAttributes):[];if(options.update||self.propertiesToReflectAsAttributes instanceof Map&&!self.propertiesToReflectAsAttributes.has(name)||Array.isArray(self.propertiesToReflectAsAttributes)&&!self.propertiesToReflectAsAttributes.includes(name)||typeof self.propertiesToReflectAsAttributes==="object"&&!Object.prototype.hasOwnProperty.call(self.propertiesToReflectAsAttributes,name)){let result;if(typeof options.writeAttribute==="boolean"){if(options.writeAttribute&&self.propertyTypes&&Object.prototype.hasOwnProperty.call(self.propertyTypes,name))result=self.propertyTypes[name]}else result=options.writeAttribute;if(result!==undefined){if(Array.isArray(self.propertiesToReflectAsAttributes))if(options.writeAttribute===true)self.propertiesToReflectAsAttributes.push(name);else if(self.normalizePropertyTypeList)self.propertiesToReflectAsAttributes=self.normalizePropertyTypeList(self.propertiesToReflectAsAttributes);if(self.propertiesToReflectAsAttributes instanceof Map)self.propertiesToReflectAsAttributes.set(name,result);if(typeof self.propertiesToReflectAsAttributes==="object")self.propertiesToReflectAsAttributes[name]=result}}}if(options.alias){if(!Object.prototype.hasOwnProperty.call(self,"propertyAliases"))self.propertyAliases=self.propertyAliases?{...self.propertyAliases}:{};if(self.propertyAliases&&(options.update||!Object.prototype.hasOwnProperty.call(self,name)))self.propertyAliases[name]=options.alias}}}/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (property);
/***/ }),
/* 3 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ Ay: () => (__WEBPACK_DEFAULT_EXPORT__),
/* harmony export */ FH: () => (/* binding */ api)
/* harmony export */ });
/* unused harmony exports log, GenericHTMLElement, Web */
/* harmony import */ var clientnode__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var clientnode_property_types__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1);
/* harmony import */ var _decorator_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
// #!/usr/bin/env babel-node
// -*- coding: utf-8 -*-
/** @module web *//* !
region header
[Project page](https://torben.website/web-component-wrapper)
Copyright Torben Sickert (info["~at~"]torben.website) 16.12.2012
License
-------
This library written by Torben Sickert stands under a creative commons
naming 3.0 unported license.
See https://creativecommons.org/licenses/by/3.0/deed.de
endregion
*/// region imports
var _dec,_class,_descriptor,_Web;function _initializerDefineProperty(e,i,r,l){r&&Object.defineProperty(e,i,{enumerable:r.enumerable,configurable:r.configurable,writable:r.writable,value:r.initializer?r.initializer.call(l):void 0})}function _defineProperty(e,r,t){return(r=_toPropertyKey(r))in e?Object.defineProperty(e,r,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[r]=t,e}function _toPropertyKey(t){var i=_toPrimitive(t,"string");return"symbol"==typeof i?i:i+""}function _toPrimitive(t,r){if("object"!=typeof t||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var i=e.call(t,r||"default");if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===r?String:Number)(t)}function _applyDecoratedDescriptor(i,e,r,n,l){var a={};return Object.keys(n).forEach(function(i){a[i]=n[i]}),a.enumerable=!!a.enumerable,a.configurable=!!a.configurable,("value"in a||a.initializer)&&(a.writable=!0),a=r.slice().reverse().reduce(function(r,n){return n(i,e,r)||r},a),l&&void 0!==a.initializer&&(a.value=a.initializer?a.initializer.call(l):void 0,a.initializer=void 0),void 0===a.initializer?(Object.defineProperty(i,e,a),null):a}function _initializerWarningHelper(r,e){throw Error("Decorating class property failed. Please ensure that transform-class-properties is enabled and runs after the decorators transform.")};// endregion
const log=new clientnode__WEBPACK_IMPORTED_MODULE_0__.Logger({name:"web-component-wrapper.web"});/*
NOTE: We mock HTMLElement to be able to load this class and derived one
into node environments.
*/const GenericHTMLElement=typeof HTMLElement==="undefined"?// eslint-disable-next-line @typescript-eslint/no-extraneous-class
class HTMLElement{}:HTMLElement;/**
* Generic web component to render a content against instance-specific values.
* @property applyRootBinding - If determined itself as root declarative event
* and property bindings will be applied to itself.
* @property content - Content to render when changes happened.
* @property determineRootBinding - If checked this component determines if it
* is a root component (not wrapped by another web-component).
* @property shadowDOM - Configures if a shadow dom should be used during
* web-component instantiation. Can hold initialize configuration.
* @property observedAttributes - Attribute names to observe for changes.
* @property controllableProperties - A list of controllable property names.
* @property eventToPropertyMapping - Explicitly defined output events (a
* mapping of event names to a potential parameter to properties-transformer).
* @property propertyAliases - A mapping of property names to be treated as
* equal.
* @property propertyTypes - Configuration defining how to convert attributes
* into properties and reflect property changes back to attributes.
* @property propertiesToReflectAsAttributes - An Item, List, or Mapping of
* properties to reflect as attributes.
* @property renderProperties - List of known render properties.
* @property cloneSlots - Indicates whether to clone slot before to transclude
* content into them. If a slot should be used multiple times (for example,
* when it works as a template node.) they should be copied to avoid unexpected
* mutations.
* @property doRender - Configures whether this component instance should
* evaluate its given body content.
* @property evaluateSlots - Indicates whether to evaluate slot content when
* before rendering them.
* @property renderSlots - Indicates whether determined slots should be
* rendered into root node.
* @property trimSlots - Ignore empty text nodes while applying slots.
* @property renderUnsafe - Defines default render behavior.
* @property _name - Name to access instance-evaluated content or used
* to derive default component name. This is also useful for logging.
* @property _propertyAliasIndex - Internal alias index to quickly match
* properties in both directions.
* @property _propertiesToReflectAsAttributes - A mapping of property names to
* set as attributes when they are set/updated. Uses a map to hold order and
* determine if a property exists in constant runtime.
* @property renderState - Holds data about currently running render state.
* @property renderState.promise - Promise resolving when next rendering has
* been finished.
* @property renderState.pending - Indicates whether a rendering task is
* performing.
* @property renderState.resolve - Callback to trigger when rendering has been
* finished.
* @property childComponentInstances - List of direct child components (needed
* to wait for them to finish dom manipulation).
* @property batchAttributeUpdates - Indicates whether to directly update dom
* after each attribute mutation or to wait and batch mutations after current
* queue has been finished.
* @property batchPropertyUpdates - Indicates whether to directly update dom
* after each property mutation or to wait and batch mutations after current
* queue has been finished.
* @property batchUpdates - Indicates whether to directly perform a
* re-rendering after changes on properties have been made.
* @property batchedAttributeUpdateRunning - A boolean indicator to identify if
* an attribute update is currently batched.
* @property batchedPropertyUpdateRunning - A boolean indicator to identify if
* a property update is currently batched.
* @property batchedUpdateRunning - Indicates whether a batched render update
* is currently running.
* @param connectionRegistered - Indicates whether this component is connected
* to DOM and could run its connectedCallback.
* @param pendingAttributeUpdates - Holds pending attribute updates which
* should be performed when the component is connected to DOM.
* @property parentInstance - Parent component instance.
* @property rootInstance - Root component instance.
* @property scope - Render scope.
* @property domNodeEventBindings - Holds a mapping from nodes with registered
* event handlers mapped to their deregistration function.
* @property domNodeTemplateCache - Caches template compilation results.
* @property externalProperties - Holds currently evaluated or seen properties.
* @property ignoreAttributeUpdateObservations - Indicates whether attribute
* updates should be considered (usually only needed internally).
* @property internalProperties - Holds currently evaluated properties which
* are owned by this instance and should always be delegated.
* @property outputEventNames - Set of determined output event names.
* @property instance - Wrapped component instance.
* @property isRoot - Indicates whether their exists another web-derived
* component up the tree or not.
* @property root - Hosting dom node.
* @property runDomConnectionAndRenderingInSameEventQueue - Indicates whether
* we should render initial dom immediately after the component is connected to
* dom. Deactivating this allows wrapped components to detect their parents
* since their parent-connected callback will be called before the children's
* render method.
* @property self - Back-reference to this class.
* @property slots - Grabbed slots that where present in the connecting phase.
*/let Web=(_dec=(0,_decorator_js__WEBPACK_IMPORTED_MODULE_2__/* ["default"] */ .A)({type:clientnode_property_types__WEBPACK_IMPORTED_MODULE_1__.boolean,writeAttribute:true}),_class=(_Web=class Web extends GenericHTMLElement{// endregion
// region live cycle hooks
/**
* Initializes host dom content and properties.
* @returns Nothing.
*/constructor(){super();_defineProperty(this,"renderState",{promise:Promise.resolve(""),pending:false,resolve:clientnode__WEBPACK_IMPORTED_MODULE_0__.NOOP});// Constructor might be executed when accessed via child components.
_defineProperty(this,"childComponentInstances",[]);_defineProperty(this,"batchAttributeUpdates",true);_defineProperty(this,"batchPropertyUpdates",true);_defineProperty(this,"batchUpdates",true);/*
NOTE: We set these properties to true initially since we want to
prevent any updates until the component is connected to dom.
*/_defineProperty(this,"batchedAttributeUpdateRunning",true);_defineProperty(this,"batchedPropertyUpdateRunning",true);_defineProperty(this,"batchedUpdateRunning",true);_defineProperty(this,"connectionRegistered",false);_defineProperty(this,"pendingAttributeUpdates",[]);_defineProperty(this,"parentInstance",null);_defineProperty(this,"rootInstance",void 0);_defineProperty(this,"hostDomNode",void 0);_defineProperty(this,"scope",{...clientnode__WEBPACK_IMPORTED_MODULE_0__.UTILITY_SCOPE});_defineProperty(this,"domNodeEventBindings",new Map);_defineProperty(this,"domNodeTemplateCache",new Map);_defineProperty(this,"externalProperties",{});_defineProperty(this,"ignoreAttributeUpdateObservations",false);_defineProperty(this,"internalProperties",{});_defineProperty(this,"outputEventNames",new Set);_defineProperty(this,"instance",null);_initializerDefineProperty(this,"isRoot",_descriptor,this);_defineProperty(this,"runDomConnectionAndRenderingInSameEventQueue",false);_defineProperty(this,"self",Web);_defineProperty(this,"slots",{});this.prepareNewRenderingPromise();/*
NOTE: We cannot use something like "this." e.g. "this.self" to
determine class properties since instance properties like "self"
may not set properly yet because this method is called during
constructing this instance itself.
*/this.self=this.constructor;if(!this.self._propertiesToReflectAsAttributes)this.self._propertiesToReflectAsAttributes=this.self.normalizePropertyTypeList(this.self.propertiesToReflectAsAttributes);this.generateAliasIndex();// NOTE: Shadow root will be applied when rendering the first time.
this.hostDomNode=this;this.rootInstance=this;/*
NOTE: We define getter and setter at the end to avoid shadowing
existing property names.
*/this.defineGetterAndSetterInterface()}/**
* Triggered when ever a given attribute has changed and triggers to update
* configured dom content.
* @param name - Attribute name which was updates.
* @param oldValue - Old attribute value.
* @param newValue - New updated value.
*/attributeChangedCallback(name,oldValue,newValue){if(this.ignoreAttributeUpdateObservations||oldValue===newValue)return;void this.onUpdateAttribute(name,newValue)}/**
* Updates given attribute representation.
* @param name - Attribute name which was updates.
* @param newValue - New updated value.
* @returns Promise resolving when attribute has been updated.
*/onUpdateAttribute(name,newValue){const promise=new Promise(resolve=>this.pendingAttributeUpdates.push(()=>{this.evaluateStringOrNullAndSetAsProperty(name,newValue);if(this.batchAttributeUpdates){if(!(this.batchedAttributeUpdateRunning||this.batchedUpdateRunning)){this.batchedAttributeUpdateRunning=true;this.batchedUpdateRunning=true;void (0,clientnode__WEBPACK_IMPORTED_MODULE_0__.timeout)(()=>{this.batchedAttributeUpdateRunning=false;this.batchedUpdateRunning=false;void this.render("attributeChanged")})}}else void this.render("attributeChanged");resolve()}));if(this.connectionRegistered)while(this.pendingAttributeUpdates.length)this.pendingAttributeUpdates.shift()();return promise}/**
* Triggered when this component is mounted into the document.
* Attaches event handler, grabs given slots, reflects external properties,
* and enqueues first rendering.
*/connectedCallback(){// NOTE: Hack to support IE 11 here.
try{this.isConnected=true}catch{// Ignore error.
}this.connectionRegistered=true;// NOTE: Can be overwritten during optional root determining.
this.parentInstance=this;this.rootInstance=this;this.attachEventHandler();if(this.self.determineRootBinding){this.determineRootBinding();if(this.parentInstance!==this&&this.parentInstance.childComponentInstances)this.parentInstance.childComponentInstances.push(this)}if(this.self.applyRootBinding&&this.isRoot){this.determineRenderScope();this.applyBinding(this,this.scope)}while(this.pendingAttributeUpdates.length)this.pendingAttributeUpdates.shift()();this.batchedAttributeUpdateRunning=false;this.batchedPropertyUpdateRunning=false;this.batchedUpdateRunning=false;this.grabGivenSlots();this.reflectExternalProperties(this.externalProperties);if(this.runDomConnectionAndRenderingInSameEventQueue)void this.render("connected");else void (0,clientnode__WEBPACK_IMPORTED_MODULE_0__.timeout)(()=>{void this.render("connected")})}/**
* Triggered when this component is unmounted from the document. Event
* handlers will be removed and state updated accordingly.
*/disconnectedCallback(){this.unRender("disconnected");this.unregisterConnectionState()}// endregion
// region getter/setter
/**
* Registers needed getter and setter to get notified about changes and
* reflect them.
*/defineGetterAndSetterInterface(){const allPropertyNames=(0,clientnode__WEBPACK_IMPORTED_MODULE_0__.unique)(Object.keys(this.self.propertyTypes).concat(this.self._propertyAliasIndex?Object.keys(this.self._propertyAliasIndex):[]));for(const propertyName of allPropertyNames){// If there already exists a local value, use them.
if(Object.prototype.hasOwnProperty.call(this,propertyName))this.setPropertyValue(/* eslint-disable @typescript-eslint/unbound-method */propertyName,this[propertyName]/* eslint-enable @typescript-eslint/unbound-method */);Object.defineProperty(this,propertyName,{configurable:true,get:()=>this.getPropertyValue(propertyName),set:value=>{this.setPropertyValue(propertyName,value);this.triggerPropertySpecificRendering(propertyName,value)}})}}/**
* Creates an index to match alias source and target against each other on
* constant runtime.
* @param name - Name to search an alternate name for.
* @returns Found alias or "null".
*/getPropertyAlias(name){if(this.self._propertyAliasIndex&&Object.prototype.hasOwnProperty.call(this.self._propertyAliasIndex,name))return this.self._propertyAliasIndex[name];return null}/**
* Generic property getter. Forwards properties from the "properties"
* field.
* @param name - Property name to retrieve.
* @returns Retrieved property value.
*/getPropertyValue(name){const result=this.instance?.current?.properties&&(// NOTE: Base properties should not be shadowed.
Object.prototype.hasOwnProperty.call(!Web.propertyTypes,name)||Object.prototype.hasOwnProperty.call(this.instance.current.properties,name))?this.instance.current.properties[name]:this.internalProperties[name]??this.externalProperties[name];if(this.instance?.current?.state&&Object.prototype.hasOwnProperty.call(this.instance.current.state,name))return this.instance.current.state[name];return result}/**
* External property setter. Respects configured aliases.
* @param name - Property name to write.
* @param value - New value to write.
*/setExternalPropertyValue(name,value){this.externalProperties[name]=value;const alias=this.getPropertyAlias(name);if(alias)this.externalProperties[alias]=value}/**
* Internal property setter. Respects configured aliases.
* @param name - Property name to write.
* @param value - New value to write.
*/setInternalPropertyValue(name,value){this.internalProperties[name]=value;const alias=this.getPropertyAlias(name);if(alias)this.internalProperties[alias]=value}/**
* Generic property setter. Forwards field writes into internal and
* external property representations.
* @param name - Property name to write.
* @param value - New value to write.
*/setPropertyValue(name,value){this.reflectProperties({[name]:value});this.setInternalPropertyValue(name,value)}/**
* Triggers a new rendering cycle and respects property-specific state
* connection.
* @param name - Property name to write.
* @param value - New value to write.
*/triggerPropertySpecificRendering(name,value){if(this.batchPropertyUpdates){if(!(this.batchedPropertyUpdateRunning||this.batchedUpdateRunning)){this.batchedPropertyUpdateRunning=true;this.batchedUpdateRunning=true;void (0,clientnode__WEBPACK_IMPORTED_MODULE_0__.timeout)(()=>{if(value!==undefined&&this.isStateProperty(name)){void this.render("preStatePropertyChanged");void (0,clientnode__WEBPACK_IMPORTED_MODULE_0__.timeout)(()=>{this.setInternalPropertyValue(name,undefined);this.batchedPropertyUpdateRunning=false;this.batchedUpdateRunning=false;void this.render("postStatePropertyChanged");this.triggerOutputEvents()})}else{this.batchedPropertyUpdateRunning=false;this.batchedUpdateRunning=false;void this.render("propertyChanged");this.triggerOutputEvents()}})}}else{const isStateProperty=this.isStateProperty(name);void this.render(isStateProperty?"preStatePropertyChanged":"propertyChanged");if(value!==undefined&&isStateProperty){this.setInternalPropertyValue(name,undefined);void this.render("postStatePropertyChanged")}this.triggerOutputEvents()}}// endregion
// region helper
/// region utility
unregisterConnectionState(){// NOTE: Hack to support IE 11 here.
try{this.isConnected=false}catch{// Ignore error.
}this.connectionRegistered=false;this.slots={}}unregisterDomNodeEventBindings(){for(const map of this.domNodeEventBindings.values())for(const deregister of map.values())deregister()}//// region dom nodes
/**
* Binds properties and event handler to the given dom node.
* @param domNode - Node to start traversing from.
* @param scope - Scope to render property value again.
*/applyBinding(domNode,scope){if(!domNode.getAttributeNames)return;for(const attributeName of domNode.getAttributeNames()){let name;if(attributeName.startsWith("data-bind-"))name=attributeName.substring("data-bind-".length);else if(attributeName.startsWith("bind-"))name=attributeName.substring("bind-".length);if(name){const value=domNode.getAttribute(attributeName);if(value===null)continue;if(name.startsWith("attribute-")||name.startsWith("property-")){const evaluated=(0,clientnode__WEBPACK_IMPORTED_MODULE_0__.evaluate)(value,scope,false,true,domNode);if(evaluated.error){log.warn("Error occurred during processing given",`attribute binding "${attributeName}" on node:`,domNode,evaluated.error);continue}if(name.startsWith("attribute-"))domNode.setAttribute(name.substring("attribute-".length),evaluated.result);else/*
NOTE: Cast to "textContent" to have a writable
property here.
*/domNode[(0,clientnode__WEBPACK_IMPORTED_MODULE_0__.delimitedToCamelCase)(name.substring("property-".length))]=evaluated.result}else if(name.startsWith("on-")){name=(0,clientnode__WEBPACK_IMPORTED_MODULE_0__.delimitedToCamelCase)(name.substring("on-".length));scope={log,event:undefined,parameters:undefined,...scope};/*
NOTE: We pre-compile event listener since they should
usually be called more often than binded.
*/const compilation=(0,clientnode__WEBPACK_IMPORTED_MODULE_0__.compile)(value,scope,true,true,domNode);if(compilation.error)log.warn("Error occurred during compiling given event",`binding "${attributeName}" on node:`,domNode,compilation.error);else this.addSecureEventListener(domNode,name,(...parameters)=>{scope.event=parameters[0];scope.parameters=parameters;try{compilation.templateFunction(/*
NOTE: We want to be sure to have
the same ordering as we have for
the scope names and to call
internal registered getter by
retrieving values. So simple using
"...Object.values(scope)" is not
appreciate here.
*/...compilation.originalScopeNames.map(name=>scope[name]))}catch(error){log.warn("Error occurred during processing","given event binding",`"${attributeName}" on node:`,domNode,`Given expression "${value}" could`,"not be evaluated with given scope","names \""+compilation.scopeNames.join("\", \"")+`": ${(0,clientnode__WEBPACK_IMPORTED_MODULE_0__.represent)(error)}`)}})}}}}/**
* Binds properties and event handler to given, sibling, and nested nodes.
* @param domNode - Node to start traversing from.
* @param scope - Scope to render property value again.
* @param renderSlots - Indicates whether to render nested elements of
* slots (determined by an existing corresponding attribute).
*/applyBindings(domNode,scope,renderSlots=true){while(domNode){if(domNode.attributes?.length&&(renderSlots||!domNode.getAttribute("slot")))this.applyBinding(domNode,scope);/*
NOTE: Slots of nested custom components (recognized by their
dash in name) should be rendered by their own.
*/if(!domNode.nodeName.toLowerCase().includes("-"))this.applyBindings(domNode.firstChild,scope);domNode=domNode.nextSibling}}/**
* Compiles given node content and their children. Provides a corresponding
* map of compiled template functions connected to their (sub) nodes and
* expected scope names.
* @param domNode - Node to compile.
* @param scope - Scope to extract names from.
* @param options - Additional compile options.
* @param options.filter - Callback to exclude some node from being
* compiled.
* @param options.ignoreComponents - Indicates if component properties
* should be traversed or not.
* @param options.ignoreNestedComponents - Indicates if nested components
* should be traversed or not.
* @param options.unsafe - Indicates if full HTML generation should be
* allowed.
* @returns Map of compiled templates.
*/compileDomNodeTemplate(domNode,scope=[],options={}){options={ignoreComponents:true,ignoreNestedComponents:true,unsafe:this.self.renderUnsafe,...options};const nodeName=domNode.nodeName.toLowerCase();/*
NOTE: Slots of nested custom components (recognized by their dash
in name) should be rendered / controlled by them on their own.
*/if(options.ignoreComponents&&nodeName.includes("-"))return null;if(options.unsafe){let template=domNode.innerHTML;if(!template&&domNode.template)template=domNode.template;if(this.self.hasCode(template)){const result=(0,clientnode__WEBPACK_IMPORTED_MODULE_0__.compile)(`\`${template}\``,scope);return{domNode,children:[],error:result.error,scopeNames:result.scopeNames,template,templateFunction:result.templateFunction}}return null}let template=null;if(nodeName==="#text"){const content=domNode.textContent;if(content&&this.self.hasCode(content))template=content.replace(/ /g," ").trim()}const children=[];const result={children,domNode};if(template){const compilationResult=(0,clientnode__WEBPACK_IMPORTED_MODULE_0__.compile)(`\`${template}\``,scope);result.error=compilationResult.error;result.scopeNames=compilationResult.scopeNames;result.template=template;result.templateFunction=compilationResult.templateFunction}// Compile content of each nested node.
let currentDomNode=domNode.firstChild;while(currentDomNode){if(!options.filter||options.filter(currentDomNode)){const result=this.compileDomNodeTemplate(currentDomNode,scope,{...options,ignoreComponents:options.ignoreNestedComponents});if(result)children.push(result)}currentDomNode=currentDomNode.nextSibling}return result}/**
* @param options - Evaluation options.
* @param scope - Scope to evaluate against.
* @returns Evaluated string result or null.
*/evaluateCompiledDomNodeTemplate(options,scope){const{domNode,error,templateFunction,scopeNames}=options;if(!(templateFunction&&scopeNames))return null;if(error){log.warn("Error occurred during compiling node content:",error);return null}let output=null;try{output=templateFunction(...scopeNames.map(name=>scope[name]))}catch(error){log.warn(`Error occurred when "${this.self._name}" is running`,`"${String(templateFunction)}": with bound`,`names "${scopeNames.join("\", \"")}":`,`"${error}". Rendering node:`,domNode)}return output}/**
* Compiles and evaluates given node content and their children. Replaces
* each node content with their evaluated representation.
* @param domNode - Node to evaluate.
* @param scope - Scope to render against.
* @param options - Compile options.
* @param options.applyBindings - Indicates whether to apply bindings to
* given dom nodes.
* @param options.filter - Callback to exclude some node from being
* compiled.
* @param options.ignoreComponents - Indicates if component properties
* should be traversed or not.
* @param options.ignoreNestedComponents - Indicates if nested components
* should be traversed or not.
* @param options.domNodeTemplateCache - Yet compiled dom nodes to just
* reference instead of recompiling.
* @param options.unsafe - Indicates if full HTML generation should be
* allowed.
*/evaluateDomNodeTemplate(domNode,scope={},options={}){options={domNodeTemplateCache:this.domNodeTemplateCache,ignoreComponents:true,ignoreNestedComponents:true,unsafe:this.self.renderUnsafe,...options};const domNodeTemplateCache=options.domNodeTemplateCache;if(!domNodeTemplateCache.has(domNode)){const compilerOptions={filter:options.filter,ignoreComponents:options.ignoreComponents,ignoreNestedComponents:options.ignoreNestedComponents,unsafe:options.unsafe};const compiledDomNode=this.compileDomNodeTemplate(domNode,scope,compilerOptions);if(compiledDomNode)domNodeTemplateCache.set(domNode,compiledDomNode)}if(domNodeTemplateCache.has(domNode)){const compiledDomNode=domNodeTemplateCache.get(domNode);const output=this.evaluateCompiledDomNodeTemplate(compiledDomNode,scope);if(output!==null)if(options.unsafe&&domNode.innerHTML)domNode.innerHTML=output;else domNode.textContent=output;if(compiledDomNode.children.length){const evaluateChildDomNode=children=>{for(const childCompiledDomNode of children){const output=this.evaluateCompiledDomNodeTemplate(childCompiledDomNode,scope);if(output!==null)childCompiledDomNode.domNode.textContent=output;if(childCompiledDomNode.children.length)evaluateChildDomNode(childCompiledDomNode.children)}};evaluateChildDomNode(compiledDomNode.children)}}if(options.applyBindings)this.applyBindings(domNode,scope)}/**
* Adds an event listener to the given dom node so that it will be
* deregistered when the component instance is destroyed.
* @param domNode - Node to assign event handler to.
* @param name - Event name.
* @param handler - Callback to trigger when given event occurs.
* @param options - Add event listener options.
* @param removeOptions - Remove event listener options.
* @returns Deregister function.
*/addSecureEventListener(domNode,name,handler,options,removeOptions){if(!this.domNodeEventBindings.has(domNode))this.domNodeEventBindings.set(// eslint-disable-next-line func-call-spacing
domNode,new Map);const eventMap=this.domNodeEventBindings.get(domNode);const oldHandler=eventMap.get(name);if(oldHandler&&oldHandler!==handler)oldHandler();const deregister=()=>{domNode.removeEventListener(name,handler,removeOptions);eventMap.delete(name);if(eventMap.size===0)this.domNodeEventBindings.delete(domNode)};eventMap.set(name,deregister);domNode.addEventListener(name,handler,options);return deregister}//// endregion
/**
* Determines initial root which initializes rendering digest.
*/determineRootBinding(){/*
If this component is the root component, we have to trigger
nested event handler by our own in global context since there is no
parent doing that for us.
*/let currentElement=this.parentNode;while(currentElement){const isComponent=currentElement instanceof Web||currentElement.nodeName.includes("-")&¤tElement.nodeName!=="#document-fragment";const isInShadowDOM=currentElement.parentNode===null&&/* eslint-disable @typescript-eslint/no-base-to-string */currentElement.toString()==="[object ShadowRoot]";/* eslint-enable @typescript-eslint/no-base-to-string */if(isComponent){// Check whether we found the first parent component.
if(this.rootInstance===this){this.parentInstance=currentElement;/*
NOTE: There is at least one parent, so we can set
"isRoot" to "false".
*/this.setPropertyValue("isRoot",false)}this.rootInstance=currentElement}else if(isInShadowDOM)/*
NOTE: Assume none root if determined a wrapped closed
shadow DOM.
*/this.setPropertyValue("isRoot",false);currentElement=currentElement.parentNode}}/**
* Checks if given content hast code (to compile and render).
* @param content - Potential string with code inside.
* @returns A boolean indicating whether given content has code.
*/static hasCode(content){return(// NOTE: First three conditions are only for performance.
typeof content==="string"&&content.includes("${")&&content.includes("}")&&/\${[\s\S]+}/.test(content))}/**
* Converts given the list, item, or map to a map (with ordering).
* @param value - Attribute reflection configuration.
* @returns Generated map.
*/static normalizePropertyTypeList(value){if(typeof value==="string")value=[value];if(Array.isArray(value)){const givenValue=value;const newValue=new Map;for(const name of givenValue)if(Object.prototype.hasOwnProperty.call(Web.propertyTypes,name))newValue.set(name,Web.propertyTypes[name]);return newValue}return (0,clientnode__WEBPACK_IMPORTED_MODULE_0__.convertPlainObjectToMap)(value)}/// endregion
/// region events
/**
* Attaches event handler to keep in sync with nested components properties
* states.
*/attachEventHandler(){if(this.self.eventToPropertyMapping===null)return;/*
NOTE: We only reflect properties by implicit determined events if
their where no explicitly defined.
*/const somethingDefined=this.attachExplicitDefinedOutputEventHandler();this.attachImplicitDefinedOutputEventHandler(!somethingDefined)}/**
* Attach explicitly defined event handler to synchronize internal and
* external property states.
* @returns Returns "true" if there are some defined and "false" otherwise.
*/attachExplicitDefinedOutputEventHandler(){if(!this.self.eventToPropertyMapping)return false;// Grab all existing output to property definitions
let result=false;for(const name of Object.keys(this.self.eventToPropertyMapping))if(!Object.prototype.hasOwnProperty.call(this.internalProperties,name)){result=true;this.outputEventNames.add(name);this.setInternalPropertyValue(name,async(...parameters)=>{const result=await this.reflectEventToProperties(name,parameters);if(result)parameters[0]=result;this.forwardEvent(name,parameters)})}return result}/**
* Attach implicitly defined event handler to synchronize internal and
* external property states.
* @param reflectProperties - Indicates whether implicitly determined
* properties should be reflected.
*/attachImplicitDefinedOutputEventHandler(reflectProperties=true){// Determine all event handlers to inject
for(const[name,type]of Object.entries(this.self.propertyTypes))if(!Object.prototype.hasOwnProperty.call(this.internalProperties,name)&&[clientnode_property_types__WEBPACK_IMPORTED_MODULE_1__.func,"function"].includes(type)&&!this.self.renderProperties.includes(name)){this.outputEventNames.add(name);this.setInternalPropertyValue(name,(...parameters)=>{if(reflectProperties)void this.reflectEventToProperties(name,parameters);this.forwardEvent(name,parameters)})}}/**
* Triggers all identified events to communicate internal property / state
* changes.
*/triggerOutputEvents(){for(const name of this.outputEventNames)this.forwardEvent(name,[this.externalProperties])}/**
* Forwards given event as the native web event.
* @param name - Event name.
* @param parameters - Event parameters.
* @returns False if event is cancelable, and at least one of the event
* handlers which received event called "Event.preventDefault()",
* otherwise true will be returned.
*/forwardEvent(name,parameters){if(name.length>"onX".length&&name.startsWith("on"))name=(0,clientnode__WEBPACK_IMPORTED_MODULE_0__.lowerCase)(name.substring(2));return this.dispatchEvent(new CustomEvent(name,{detail:{parameters}}))}/// endregion
/// region slots
/**
* Renders component given slot contents into the given dom node. If
* expected slots are not given but a fallback is specified, they will be
* loaded into internal slot mapping.
* @param targetDomNode - Target dom node to render slots into.
* @param scope - Environment to render slots again if specified.
*/applySlots(targetDomNode,scope){for(const domNode of Array.from(targetDomNode.querySelectorAll("slot"))){const name=domNode.getAttribute("name");if(name===null||name==="default"){if(this.slots.default){if(this.self.renderSlots){if(this.self.evaluateSlots)for(const domNode of this.slots.default)this.evaluateDomNodeTemplate(domNode,scope);(0,clientnode__WEBPACK_IMPORTED_MODULE_0__.replace)(domNode,this.slots.default,Web.trimSlots)}}else this.slots.default=(0,clientnode__WEBPACK_IMPORTED_MODULE_0__.unwrap)(domNode).map(domNode=>this.grabSlotContent(domNode));}else if(this.slots[name]){if(this.self.renderSlots){if(this.self.evaluateSlots)this.evaluateDomNodeTemplate(this.slots[name],scope);(0,clientnode__WEBPACK_IMPORTED_MODULE_0__.replace)(domNode,this.slots[name],Web.trimSlots)}}else this.slots[name]=this.grabSlotContent((0,clientnode__WEBPACK_IMPORTED_MODULE_0__.unwrap)(domNode).filter(domNode=>domNode.nodeName.toLowerCase()!=="#text")[0])}}/**
* Determines slot content from the given node.
* @param slot - Node to grab slot content from.
* @returns Determined slot.
*/grabSlotContent(slot){/*
If real (template) code is wrapped in a "textarea" tag, unwrap it
now. This extra wrapping can be used to avoid first dom rendering
before template code has been evaluated.
*/const element=clientnode_property_types__WEBPACK_IMPORTED_MODULE_1__.node.firstElementChild?slot:null;if(element&&element.firstElementChild?.nodeName.toLowerCase()==="textarea"&&(!element.firstElementChild.hasAttribute("data-no-template")||element.firstElementChild.getAttribute("data-no-template")==="false")){const content=element.firstElementChild.value;/*
NOTE: These kinds of slots are always used as a template and
should therefore be copied in every case.
NOTE: A flat copy should suffice since we will replace nested
content.
NOTE: Remove template content in copied node to avoid rendering
them before being evaluated. We cannot remove template code
from the source node since this would make it impossible to
re-instantiate this slot during whole component
re-instantiation.
*/element.classList.remove("web-component-template");const newSlot=element.cloneNode();element.classList.add("web-component-template");newSlot.innerHTML="";newSlot.template=content;return newSlot}return this.self.cloneSlots?slot.cloneNode(true):slot}/**
* Saves given slots.
*/grabGivenSlots(){this.slots={};for(const slot of Array.from(this.querySelectorAll("[slot]"))){// NOTE: This is how we avoid grabbing slots from nested components.
let currentElement=slot.parentNode;let skip=true;while(currentElement){if(currentElement.nodeName.includes("-")){if(currentElement===this)skip=false;break}currentElement=currentElement.parentNode}if(skip)continue;const slotValue=slot.getAttribute("slot")?.trim();this.slots[slotValue??slot.nodeName.toLowerCase()]=this.grabSlotContent(slot)}if(this.slots.default)this.slots.default=[].concat(this.slots.default);else if(this.childNodes.length>0)this.slots.default=Array.from(this.childNodes).map(domNode=>this.grabSlotContent(domNode));else this.slots.default=[]}/// endregion
/// region properties
/**
* Determines if a given property name exists in wrapped component state.
* @param name - Property name to check if exists in state.
* @returns Boolean result.
*/isStateProperty(name){return Boolean(this.instance?.current?.state&&(Object.prototype.hasOwnProperty.call(this.instance.current.state,name)||this.instance.current.state.modelState&&Object.prototype.hasOwnProperty.call(this.instance.current.state.modelState,name)))}/**
* Generates an alias to name and the other way around mapping if not
* exists.
*/generateAliasIndex(){if(!this.self._propertyAliasIndex){this.self._propertyAliasIndex={...this.self.propertyAliases};// Align alias mapping for better performance while mapping them.
for(const[name,value]of Object.entries(this.self._propertyAliasIndex))if(!Object.prototype.hasOwnProperty.call(this.self._propertyAliasIndex,value))this.self._propertyAliasIndex[value]=name}}/**
* Reflects wrapped component state back to web-component's attributes.
* @param properties - Properties to update in reflected attribute state.
*/reflectExternalProperties(properties){/*
NOTE: We can avoid an additional attribute parsing for
reflections.
*/this.ignoreAttributeUpdateObservations=true;for(const[name,value]of Object.entries(properties)){this.setExternalPropertyValue(name,value);if(!this.isConnected)continue;const attributeName=(0,clientnode__WEBPACK_IMPORTED_MODULE_0__.camelCaseToDelimited)(name);if(this.self._propertiesToReflectAsAttributes?.has(name))switch(this.self._propertiesToReflectAsAttributes.get(name)){case clientnode_property_types__WEBPACK_IMPORTED_MODULE_1__.boolean:case"boolean":if(value){if(this.getAttribute(attributeName)!=="")this.setAttribute(attributeName,"")}else if(this.hasAttribute(attributeName))this.removeAttribute(attributeName);break;case clientnode_property_types__WEBPACK_IMPORTED_MODULE_1__.func:case"function":break;case"json":if(value){const representation=JSON.stringify(value);if(representation&&this.getAttribute(attributeName)!==representation){this.setAttribute(attributeName,representation);break}}if(this.hasAttribute(attributeName))this.removeAttribute(attributeName);break;case clientnode_property_types__WEBPACK_IMPORTED_MODULE_1__.number:case"number":if(typeof value==="number"&&!isNaN(value)){const valueAsString=String(value);if(this.getAttribute(attributeName)!==valueAsString)this.setAttribute(attributeName,valueAsString)}else if(this.hasAttribute(attributeName))this.removeAttribute(attributeName);break;case clientnode_property_types__WEBPACK_IMPORTED_MODULE_1__.string:case"string":if(value){if(this.getAttribute(attributeName)!==value)this.setAttribute(attributeName,value)}else if(this.hasAttribute(attributeName))this.removeAttribute(attributeName);break;case clientnode_property_types__WEBPACK_IMPORTED_MODULE_1__.any:case clientnode_property_types__WEBPACK_IMPORTED_MODULE_1__.array:case clientnode_property_types__WEBPACK_IMPORTED_MODULE_1__.arrayOf:case clientnode_property_types__WEBPACK_IMPORTED_MODULE_1__.element:case clientnode_property_types__WEBPACK_IMPORTED_MODULE_1__.elementType:case clientnode_property_types__WEBPACK_IMPORTED_MODULE_1__.instanceOf:case clientnode_property_types__WEBPACK_IMPORTED_MODULE_1__.node:case clientnode_property_types__WEBPACK_IMPORTED_MODULE_1__.object:case"object":case clientnode_property_types__WEBPACK_IMPORTED_MODULE_1__.objectOf:case clientnode_property_types__WEBPACK_IMPORTED_MODULE_1__.shape:case clientnode_property_types__WEBPACK_IMPO