Best JavaScript code snippet using playwright-internal
entity.js
Source:entity.js  
...343                // NOTE: Although this checks the prototype chain on EVERY add, it only344                // checks on the class object, which should NOT have a chain.345                if (!('create' in componentType))346                {347                    throw new Error(`Instanced component class '${getComponentTypeName(componentType)}' must at least have a static create() function.`);348                }349                component = componentType.create(this);350            }351            else if (type === 'function')352            {353                // HACK: This is a hack debugging tool to stop wrong use.354                if (componentType.prototype instanceof EntityComponent$1)355                {356                    throw new Error('This component cannot be added to an existing entity; it can only initialize itself.');357                }358                component = new componentType(this);359            }360            else if (type === 'symbol')361            {362                // NOTE: Symbols lose their immutability when converted into a component363                // (their equality is checked by their toString() when computing its key)364                throw new Error('Symbols are not yet supported as components.');365            }366            else367            {368                // NOTE: This means that these can be numbers and strings.369                // HOWEVER, I caution against using numbers. Numbers can often be confused370                // with other operations (particularly when computation is involved).371                component = componentType;372            }373            // Initialize the component...374            if (initialValues)375            {376                this.copyComponent(componentType, component, initialValues);377            }378            379            return component;380        }381        putComponent(entityId, componentType, component = componentType, initialValues = undefined)382        {383            let componentInstanceMap;384            if (this.componentTypeInstanceMap.has(componentType))385            {386                componentInstanceMap = this.componentTypeInstanceMap.get(componentType);387            }388            else389            {390                this.componentTypeInstanceMap.set(componentType, componentInstanceMap = new Map());391            }392            if (componentInstanceMap.has(entityId))393            {394                throw new Error(`Cannot add more than one instance of component class '${getComponentTypeName(componentType)}' for entity '${entityId}'.`);395            }396            componentInstanceMap.set(entityId, component);397            this._entityHandler.dispatchEntityEvent(entityId, 'componentadd', [entityId, componentType, component, initialValues]);398        }399        deleteComponent(entityId, componentType, component)400        {401            this.componentTypeInstanceMap.get(componentType).delete(entityId);402        403            let reusable;404            // It's a tag. No reuse.405            if (componentType === component)406            {407                reusable = false;408            }409            // Try user-defined static reset...410            else if ('reset' in componentType)411            {412                reusable = componentType.reset(component);413            }414            // Try user-defined instance reset...415            else if ('reset' in component)416            {417                reusable = component.reset();418            }419            // Try default reset...420            else421            {422                // Do nothing. It cannot be reset.423                reusable = false;424            }425            this._entityHandler.dispatchEntityEvent(entityId, 'componentremove', [entityId, componentType, component]);426            return component;427        }428        copyComponent(componentType, component, targetValues)429        {430            // It's a tag. No need to copy.431            if (componentType === component)432            {433                return;434            }435            // Try user-defined static copy...436            else if ('copy' in componentType)437            {438                componentType.copy(component, targetValues);439            }440            // Try user-defined instance copy...441            else if ('copy' in component)442            {443                component.copy(targetValues);444            }445            // Try default copy...446            else447            {448                for(let key of Object.getOwnPropertyNames(targetValues))449                {450                    component[key] = targetValues[key];451                }452            }453        }454        hasComponentType(componentType)455        {456            return this.componentTypeInstanceMap.has(componentType);457        }458        getComponentTypes()459        {460            return this.componentTypeInstanceMap.keys();461        }462        getComponentInstanceMapByType(componentType)463        {464            return this.componentTypeInstanceMap.get(componentType);465        }466        getComponentInstanceMaps()467        {468            return this.componentTypeInstanceMap.values();469        }470    }471    /**472     * @typedef EntityId473     * The unique id for every entity in a world.474     */475    /**476     * Manages all entities.477     */478    class EntityManager479    {480        constructor()481        {482            this.entityHandler = new EntityHandler();483            this.componentHandler = new ComponentHandler(this.entityHandler);484        }485        clear()486        {487            for(let entityId of this.entityHandler.getEntityIds())488            {489                this.destroyEntity(entityId);490            }491        }492        /** Creates a unique entity with passed-in components (without initial values). */493        createEntity(...components)494        {495            const entityId = this.entityHandler.getNextAvailableEntityId();496            this.entityHandler.addEntityId(entityId);497            for(let component of components)498            {499                this.addComponent(entityId, component);500            }501            return entityId;502        }503        /** Destroys the passed-in entity (and its components). */504        destroyEntity(entityId)505        {506            // Remove entity components from world507            for(let componentType of this.componentHandler.getComponentTypes())508            {509                if (this.componentHandler.getComponentInstanceMapByType(componentType).has(entityId))510                {511                    this.removeComponent(entityId, componentType);512                }513            }514            // Remove entity from world515            this.entityHandler.deleteEntityId(entityId);516        }517        hasEntity(entityId)518        {519            return this.entityHandler.hasEntityId(entityId);520        }521        getEntityIds()522        {523            return this.entityHandler.getEntityIds();524        }525        526        /**527         * 528         * @param {import('./Entity.js').EntityId} entityId The id of the entity to add to.529         * @param {FunctionConstructor|import('./Component.js').ComponentFactory|String|Number} componentType The component type.530         * Can either be a component class or a component factory.531         * @param {Object} [initialValues] The initial values for the component. Can be an object532         * map of all defined key-value pairs or another instance of the same component. This533         * must be undefined for tag-like components.534         */535        addComponent(entityId, componentType, initialValues = undefined)536        {537            try538            {539                let component = this.componentHandler.createComponent(componentType, initialValues);540                this.componentHandler.putComponent(entityId, componentType, component, initialValues);541                return component;542            }543            catch(e)544            {545                console.error(`Failed to add component '${getComponentTypeName$1(componentType)}' to entity '${entityId}'.`);546                console.error(e);547            }548        }549        addTagComponent(entityId, componentType)550        {551            try552            {553                let type = typeof componentType;554                if (type === 'symbol')555                {556                    throw new Error('Symbols are not yet supported as tag components.');557                }558                else if (type === 'number')559                {560                    throw new Error('Numbers are not yet supported as tag components.');561                }562                else if (type === 'string')563                {564                    this.componentHandler.putComponent(entityId, componentType);565                }566                else567                {568                    throw new Error(`Component of type '${type}' cannot be a tag component.`);569                }570                return componentType;571            }572            catch(e)573            {574                console.error(`Failed to add tag component '${getComponentTypeName$1(componentType)}' to entity '${entityId}'.`);575                console.error(e);576            }577        }578        579        removeComponent(entityId, componentType)580        {581            try582            {583                let component = this.getComponent(entityId, componentType);584                this.componentHandler.deleteComponent(entityId, componentType, component);585                return component;586            }587            catch(e)588            {589                console.error(`Failed to remove component '${getComponentTypeName$1(componentType)}' from entity '${entityId}'.`);590                console.error(e);591            }592        }593        clearComponents(entityId)594        {595            for(let componentInstanceMap of this.componentHandler.getComponentInstanceMaps())596            {597                if (componentInstanceMap.has(entityId))598                {599                    let component = componentInstanceMap.get(entityId);600                    this.componentHandler.deleteComponent(entityId, componentType, component);601                }602            }603        }604        getComponentTypesByEntityId(entityId)605        {606            let dst = [];607            for(let componentType of this.componentHandler.getComponentTypes())608            {609                let componentInstanceMap = this.componentHandler.getComponentInstanceMapByType(componentType);610                if (componentInstanceMap.has(entityId))611                {612                    dst.push(componentType);613                }614            }615            return dst;616        }617        getComponent(entityId, componentType)618        {619            return this.componentHandler.getComponentInstanceMapByType(componentType).get(entityId);620        }621        hasComponent(entityId, ...componentTypes)622        {623            for(let componentType of componentTypes)624            {625                if (!this.componentHandler.hasComponentType(componentType)) return false;626                if (!this.componentHandler.getComponentInstanceMapByType(componentType).has(entityId)) return false;627            }628            return true;629        }630        countComponents(entityId)631        {632            let count = 0;633            for(let componentInstanceMap of this.componentHandler.getComponentInstanceMaps())634            {635                if (componentInstanceMap.has(entityId))636                {637                    ++count;638                }639            }640            return count;641        }642        /**643         * Immediately find entity ids by its components. This is simply an alias for Query.select().644         * @param {Array<Component>} components The component list to match entities to.645         * @returns {Iterable<EntityId>} A collection of all matching entity ids.646         */647        find(components)648        {649            return EntityQuery.select(this, components);650        }651        [Symbol.iterator]()652        {653            return this.getEntityIds()[Symbol.iterator]();654        }655    }656    function createQueryOperator(handler, key = Symbol(handler.name))657    {658        let result = function(componentType) {659            return { [OPERATOR]: key, [HANDLER]: handler, component: componentType };660        };661        // Dynamic renaming of function for debugging purposes662        // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name663        Object.defineProperty(result, 'name', {664            value: name,665            configurable: true,666        });667        return result;668    }669    const Not = createQueryOperator(670        function NotOperator(world, entityId, componentTypees)671        {672            return !(world.hasComponent(entityId, ...componentTypees));673        },674        Symbol('!')675    );676    var QueryOperator = /*#__PURE__*/Object.freeze({677        __proto__: null,678        createQueryOperator: createQueryOperator,679        Not: Not680    });681    /**682     * Creates a new component instance for this component type.683     * @callback create684     * @param {import('../World.js').World} world The world the component will be added to.685     * @param {import('../entity/Entity.js').EntityId} entityId The id of the entity this component is added to.686     */687    /**688     * Copies a component instance from values.689     * @callback copy690     * @param {Object} dst The target component instance to modify.691     * @param {Object} values The source values to copy from.692     */693    /**694     * Resets a component instance to be re-used or deleted.695     * @callback reset696     * @param {Object} dst The target component instance to reset.697     */698    /**699     * @typedef ComponentFactory700     * A component factory handles the creation, modification, and deletion of component instances.701     * 702     * @property {create} create Creates a new component instance for this type.703     * @property {copy} [copy] Copies a component instance from values.704     * @property {reset} [reset] Resets a component instance to be re-used or deleted.705     */706    /**707     * Creates a component factory given the passed-in handlers. This is not required708     * to create a component factory; any object with create(), copy(), and reset() can709     * be considered a component factory and used as is without this function. This710     * function is mostly for ease of use and readability.711     * 712     * @param {String} name The name of the component. This should be unique; it is used as its hash key.713     * @param {create} [create=defaultCreate] The function to create new components.714     * @param {copy} [copy=defaultCopy] The function to copy new components from values.715     * @param {reset} [reset=defaultReset] The function to reset a component to be re-used or deleted.716     * @returns {ComponentFactory} The created component factory.717     */718    function createComponentFactory(name, create = defaultCreate, copy = defaultCopy, reset = defaultReset)719    {720        return {721            name,722            create,723            copy,724            reset725        };726    }727    function defaultCreate(world, entityId) { return {}; }728    function defaultCopy(dst, values) { Object.assign(dst, values); }729    function defaultReset(dst) { Object.getOwnPropertyNames(dst).forEach(value => delete dst[value]); }730    var ComponentFactory = /*#__PURE__*/Object.freeze({731        __proto__: null,732        createComponentFactory: createComponentFactory733    });734    /**735     * A class to represent a component. This class is not required to736     * create a component; any class can be considered a component. To737     * override reset or copy behavior, simply implement the reset()738     * or copy() functions respectively for that class.739     * 740     * This class serves mostly as a quick and dirty default fallback. It741     * has defaults for all functionality except its properties (which are742     * usually unique to each component type).743     * 744     * Usually, you will use this class like so:745     * @example746     * class MyComponent extends ComponentBase747     * {748     *   constructor()749     *   {750     *     super();751     *     this.myValue = true;752     *     this.myString = 'Hello World';753     *   }754     * 755     *   // Feel free to override any default functionality when needed...756     * }757     */758    const DEFAULT_UNDEFINED = Symbol('defaultUndefined');759    class ComponentBase760    {761        static get defaultValues() { return null; }762        constructor(world, entityId, resetAsSelfConstructor = true)763        {764            if (!('defaultValues' in this.constructor))765            {766                if (resetAsSelfConstructor)767                {768                    // NOTE: Must make sure 'defaultValues' exists before recursing into the constructor.769                    this.constructor.defaultValues = null;770                    this.constructor.defaultValues = new (this.constructor)();771                }772                else773                {774                    this.constructor.defaultValues = DEFAULT_UNDEFINED;775                }776            }777        }778        779        copy(values)780        {781            for(let key of Object.getOwnPropertyNames(values))782            {783                this[key] = values[key];784            }785        }786        reset()787        {788            if ('defaultValues' in this.constructor)789            {790                let defaultValues = this.constructor.defaultValues;791                if (defaultValues === DEFAULT_UNDEFINED)792                {793                    for(let key of Object.getOwnPropertyNames(this))794                    {795                        this[key] = undefined;796                    }797                    return true;798                }799                else if (defaultValues)800                {801                    this.copy(this, this.constructor.defaultValues);802                    return true;803                }804                else805                {806                    return false;807                }808            }809            else810            {811                return false;812            }813        }814    }815    /**816     * A class to represent a component with no data, also known as a tag.817     * This class is not required to create a tag component; any class is818     * considered a tag, if:819     * 820     * - It does not implement reset() or reset() always returns false.821     * - And its instances do not own any properties.822     * 823     * This class is mostly for ease of use and readability.824     */825    class TagComponent {}826    class EntityBase extends EntityComponent$1827    {828        constructor(entityManager)829        {830            super(entityManager);831            this.entityManager = entityManager;832        }833        destroy()834        {835            this.entityManager.destroyEntity(this.id);836        }837        addComponent(componentType, initialValues = undefined)838        {839            this.entityManager.addComponent(this.id, componentType, initialValues);840            return this;841        }842        addTagComponent(componentType)843        {844            this.entityManager.addTagComponent(this.id, componentType);845            return this;846        }847        removeComponent(componentType)848        {849            this.entityManager.removeComponent(this.id, componentType);850            return this;851        }852        hasComponent(componentType)853        {854            return this.entityManager.hasComponent(this.id, componentType);855        }856        getComponent(componentType)857        {858            return this.entityManager.getComponent(this.id, componentType);859        }860    }861    class ReflexiveEntity extends EntityBase862    {863        constructor(entityManager)864        {865            super(entityManager);866            this.onComponentAdd = this.onComponentAdd.bind(this);867            this.onComponentRemove = this.onComponentRemove.bind(this);868            this.entityManager.entityHandler.addEntityListener(this.id, 'componentadd', this.onComponentAdd);869            this.entityManager.entityHandler.addEntityListener(this.id, 'componentremove', this.onComponentRemove);870        }871        872        /** @abstract */873        onDestroy() {}874        onComponentAdd(entityId, componentType, component, initialValues)875        {876            if (this.id !== entityId) return;877            // NOTE: Since this callback is connected only AFTER EntityComponent has been added878            // we can safely assume that it cannot be added again.879            addComponentProperties(this, componentType, component);880        }881        onComponentRemove(entityId, componentType, component)882        {883            if (this.id !== entityId) return;884            885            if (componentType === EntityComponent$1)886            {887                this.entityManager.entityHandler.removeEntityListener(this.id, 'componentadd', this.onComponentAdd);888                this.entityManager.entityHandler.removeEntityListener(this.id, 'componentremove', this.onComponentRemove);889                890                this.onDestroy();891            }892            else893            {894                removeComponentProperties(this, componentType, component);895            }896        }897    }898    function addComponentProperties(target, componentType, component)899    {900        if (typeof component === 'object')901        {902            let ownProps = Object.getOwnPropertyNames(target);903            let newProps = {};904            for(let prop of Object.getOwnPropertyNames(component))905            {906                if (ownProps.includes(prop))907                {908                    throw new Error(`Conflicting property names in entity for component '${getComponentTypeName(componentType)}'.`);909                }910                newProps[prop] = {911                    get() { return component[prop]; },912                    set(value) { component[prop] = value; },913                    configurable: true,914                };915            }916            Object.defineProperties(target, newProps);917        }918    }919    function removeComponentProperties(target, componentType, component)920    {921        if (typeof component === 'object')922        {...EntityManager.js
Source:EntityManager.js  
...153  add(componentType, entityId, props = undefined) {154    if (this.strictMode) {155      if (!componentType) {156        throw new Error(157          `Cannot add null or undefined component type ${getComponentTypeName(158            componentType159          )}`160        );161      }162      if (typeof componentType !== 'string' && !('name' in componentType)) {163        throw new Error(164          `Unnamed component types are not supported - ${JSON.stringify(165            componentType166          )}`167        );168      }169      if (!this.components.has(componentType)) {170        if (typeof componentType === 'string') {171          throw new Error(172            `Found unregistered tag component ${getComponentTypeName(173              componentType174            )}.`175          );176        } else {177          throw new Error(178            `Missing component factory for ${getComponentTypeName(179              componentType180            )}.`181          );182        }183      }184      if (typeof entityId !== 'string') {185        throw new Error(186          `Invalid entity id type; expected string but found ${typeof entityId} instead.`187        );188      }189      if (!this.entities.has(entityId)) {190        throw new Error(`Entity '${entityId}' does not exist.`);191      }192    }193    let factory = this.components.get(componentType);194    let component = factory.add(entityId, props || DEFAULT_PROPS);195    return component;196  }197  /**198   * Removes the associated instance of the given component type from199   * the entity and destroys it using its own factory.200   *201   * If the component is non-singular, it will remove one instance by202   * insertion order.203   *204   * @param {ComponentType} componentType The component type to remove for.205   * @param {EntityId} entityId The entity id to remove the component from.206   * @returns {Boolean} Whether a component was removed by this call.207   */208  remove(componentType, entityId) {209    if (this.strictMode) {210      if (!this.components.has(componentType)) {211        throw new Error(212          `Missing component factory for ${getComponentTypeName(213            componentType214          )}.`215        );216      }217    }218    let factory = this.components.get(componentType);219    let component = factory.get(entityId);220    if (component) {221      factory.delete(entityId);222      return true;223    }224    return false;225  }226  /**227   * Finds the component for the given entity. Assumes the component228   * exists for the entity.229   *230   * If the component is non-singular, it will return the first,231   * non-removed instance.232   *233   * @param {ComponentType} componentType The target component type.234   * @param {EntityId} entityId The id of the entity to look in.235   * @returns {Object} The component found. If it does not exist, null236   * is returned instead.237   */238  get(componentType, entityId) {239    if (this.strictMode) {240      if (!this.components.has(componentType)) {241        throw new Error(242          `Missing component factory for ${getComponentTypeName(243            componentType244          )}.`245        );246      }247    }248    let factory = this.components.get(componentType);249    return factory.get(entityId);250  }251  /**252   * Finds all the components for the given entity. Assumes the component253   * type exists for the entity.254   *255   * If the component is non-multiple, it will return an array of the only256   * associated instance.257   *258   * @param {ComponentType} componentType The target component type.259   * @param {EntityId} entityId The id of the entity to look in.260   * @returns {Object} The component found. If it does not exist, null261   * is returned instead.262   */263  getAll(componentType, entityId) {264    if (this.strictMode) {265      if (!this.components.has(componentType)) {266        throw new Error(267          `Missing component factory for ${getComponentTypeName(268            componentType269          )}.`270        );271      }272    }273    let factory = this.components.get(componentType);274    return factory.getAll(entityId);275  }276  /**277   * Checks whether the entity has the component.278   *279   * @param {ComponentType} componentType The target component type.280   * @param {EntityId} entityId The id of the entity to look in.281   * @returns {Boolean} Whether the component exists for the entity.282   */283  has(componentType, entityId) {284    let factory = this.components.get(componentType);285    return factory && Boolean(factory.get(entityId));286  }287  clear(componentType = undefined) {288    if (this.strictMode) {289      if (!this.components.has(componentType)) {290        throw new Error(291          `Missing component factory for ${getComponentTypeName(292            componentType293          )}.`294        );295      }296    }297    if (!componentType) {298      for (let componentType of this.components.keys()) {299        this.clear(componentType);300      }301    } else {302      let factory = this.components.get(componentType);303      factory.clear();304    }305  }306  /**307   * Gets all the entity ids.308   *309   * @returns {Set<EntityId>} The set of entity ids.310   */311  getEntityIds() {312    return this.entities;313  }314  /**315   * @param {ComponentType} componentType316   * @returns {import('./ComponentFactory.js').ComponentFactory} The component factory for the given component type.317   */318  getComponentFactory(componentType) {319    return this.components.get(componentType);320  }321  getComponentTypes() {322    return this.components.keys();323  }324  /**325   * Gets all the current entity ids of the given component type.326   *327   * @param {ComponentType} componentType The component type to get entity ids for.328   * @returns {Array<EntityId>} The list of all entity ids for the component type.329   */330  getComponentEntityIds(componentType) {331    if (this.strictMode) {332      if (!this.components.has(componentType)) {333        throw new Error(334          `Missing component factory for ${getComponentTypeName(335            componentType336          )}.`337        );338      }339    }340    let factory = this.components.get(componentType);341    return factory.keys();342  }343  /**344   * Gets all the current instances of the given component type.345   *346   * @param {ComponentType} componentType The component type to get instances for.347   * @returns {Array<Object>} The list of all instances, or instance lists, for348   * the component type.349   */350  getComponentInstances(componentType) {351    if (this.strictMode) {352      if (!this.components.has(componentType)) {353        throw new Error(354          `Missing component factory for ${getComponentTypeName(355            componentType356          )}.`357        );358      }359    }360    let factory = this.components.get(componentType);361    return factory.values();362  }363}364/**365 * @param {*} componentType The component type.366 * @returns {String} The name of the component type.367 */368function getComponentTypeName(componentType) {369  switch (typeof componentType) {370    case 'string':371      return `'${componentType}'`;372    case 'object':373    case 'function':374      return componentType.name || componentType;375    default:376      return componentType;377  }...EntityQuery.js
Source:EntityQuery.js  
...16        for(let component of components)17        {18            if (typeof component === 'object' && OPERATOR in component)19            {20                result.push(component[OPERATOR].toString() + getComponentTypeName(component));21            }22            else23            {24                result.push(getComponentTypeName(component));25            }26        }27        return result.sort().join('-');28    }29    constructor(components, persistent = true)30    {31        this._included = [];32        this._operated = {};33        for(let component of components)34        {35            if (typeof component === 'object' && OPERATOR in component)36            {37                const operator = component[OPERATOR];38                if (operator in this._operated)...ComponentHandler.js
Source:ComponentHandler.js  
...20            // NOTE: Although this checks the prototype chain on EVERY add, it only21            // checks on the class object, which should NOT have a chain.22            if (!('create' in componentType))23            {24                throw new Error(`Instanced component class '${getComponentTypeName(componentType)}' must at least have a static create() function.`);25            }26            component = componentType.create(this);27        }28        else if (type === 'function')29        {30            // HACK: This is a hack debugging tool to stop wrong use.31            if (componentType.prototype instanceof EntityComponent)32            {33                throw new Error('This component cannot be added to an existing entity; it can only initialize itself.');34            }35            component = new componentType(this);36        }37        else if (type === 'symbol')38        {39            // NOTE: Symbols lose their immutability when converted into a component40            // (their equality is checked by their toString() when computing its key)41            throw new Error('Symbols are not yet supported as components.');42        }43        else44        {45            // NOTE: This means that these can be numbers and strings.46            // HOWEVER, I caution against using numbers. Numbers can often be confused47            // with other operations (particularly when computation is involved).48            component = componentType;49        }50        // Initialize the component...51        if (initialValues)52        {53            this.copyComponent(componentType, component, initialValues);54        }55        56        return component;57    }58    putComponent(entityId, componentType, component = componentType, initialValues = undefined)59    {60        let componentInstanceMap;61        if (this.componentTypeInstanceMap.has(componentType))62        {63            componentInstanceMap = this.componentTypeInstanceMap.get(componentType);64        }65        else66        {67            this.componentTypeInstanceMap.set(componentType, componentInstanceMap = new Map());68        }69        if (componentInstanceMap.has(entityId))70        {71            throw new Error(`Cannot add more than one instance of component class '${getComponentTypeName(componentType)}' for entity '${entityId}'.`);72        }73        componentInstanceMap.set(entityId, component);74        this._entityHandler.dispatchEntityEvent(entityId, 'componentadd', [entityId, componentType, component, initialValues]);75    }76    deleteComponent(entityId, componentType, component)77    {78        this.componentTypeInstanceMap.get(componentType).delete(entityId);79    80        let reusable;81        // It's a tag. No reuse.82        if (componentType === component)83        {84            reusable = false;85        }...array_reference.js
Source:array_reference.js  
...107    }108    const setValues = [];109    const arrayType = await this.getType();110    const componentType = await arrayType.componentType();111    const componentTypeName = await arrayType.getComponentTypeName();112    const componentSignature = await arrayType.getComponentSignature();113    for (let i = 0; i < length; i++) {114      const value = values[0];115      setValues.push(await Value.prepareForAssignment(value, {116        signature: componentSignature,117        typeName: componentTypeName,118        type: componentType,119      }));120    }121    await this.vm.send(new SetValues({122      arrayObject: this.ref,123      firstIndex: index,124      values: setValues,125    }));...array_type.js
Source:array_type.js  
...11  async getComponentSignature() {12    const signature = await this.getSignature();13    return signature.slice(1); // Just skip the leading '['14  }15  async getComponentTypeName() {16    const parser = new JNITypeParser(await this.getComponentSignature());17    return parser.typeName;18  }19  async findComponentType(signature) {20    const tag = signature.charCodeAt(0);21    if (isObjectTag(tag)) {22      const parser = new JNITypeParser(await this.getComponentSignature());23      const list = await this.vm.classesByName(parser.typeName);24      const cl1 = await this.getClassLoader();25      for (const type of list) {26        const cl2 = await type.getClassLoader();27        if (cl2) {28          if (cl2.equals(cl1)) return type;29        } else {30          if (!cl1) return type;31        }32      }33      throw new Error(await this.getComponentTypeName() + ' class not loaded');34    }35    return this.vm.primitiveType(tag);36  }37  async componentType() {38    return await this.findComponentType(await this.getComponentSignature());39  }40  async newInstance(length) {41    const { newArray } = await this.vm.send(new NewInstance({42      arrType: this.ref,43      length,44    }));45    return this.vm.objectMirror(newArray.objectId, newArray.tag);46  }47  async isComponentAssignable(destination, source) {...components.js
Source:components.js  
...10 * Get the name of a component TYPE11 * @param {React.ComponentType} component12 * @returns {string}13 */14export function getComponentTypeName(component) {15  return component.displayName || component.name || 'Component'...ComponentHelper.js
Source:ComponentHelper.js  
1export function getComponentTypeName(componentType)2{3    return componentType.name || componentType.toString();...Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3  const browser = await chromium.launch({ headless: false });4  const context = await browser.newContext();5  const page = await context.newPage();6  const userAgent = await page.evaluate(() => navigator.userAgent);7  console.log(userAgent);8  await browser.close();9})();Using AI Code Generation
1const { getComponentTypeName } = require('@playwright/test/lib/server/frames');2const { chromium } = require('playwright');3(async () => {4  const browser = await chromium.launch();5  const context = await browser.newContext();6  const page = await context.newPage();7  const handle = await page.$('text="Get started"');8  const componentName = await getComponentTypeName(handle);9  console.log(componentName);10  await browser.close();11})();12const { chromium } = require('playwright');13(async () => {14  const browser = await chromium.launch();15  const context = await browser.newContext();16  const page = await context.newPage();17  const handle = await page.$('text="Get started"');18  const componentName = await handle.evaluate((node) => {19    return node.getAttribute('data-component-name');20  });21  console.log(componentName);22  await browser.close();23})();24### `getComponentTypeName(handle)`Using AI Code Generation
1const { getComponentTypeName } = require('@playwright/test/lib/server/frames');2const { Page } = require('@playwright/test/lib/server/page');3const { Frame } = require('@playwright/test/lib/server/frame');4const { getComponentTypeName } = require('@playwright/test/lib/server/frames');5const { Page } = require('@playwright/test/lib/server/page');6const { Frame } = require('@playwright/test/lib/server/frame');7const { getComponentTypeName } = require('@playwright/test/lib/server/frames');8const { Page } = require('@playwright/test/lib/server/page');9const { Frame } = require('@playwright/test/lib/server/frame');10const { getComponentTypeName } = require('@playwright/test/lib/server/frames');11const { Page } = require('@playwright/test/lib/server/page');12const { Frame } = require('@playwright/test/lib/server/frame');13const { getComponentTypeName } = require('@playwright/test/lib/server/frames');14const { Page } = require('@playwright/test/lib/server/page');15const { Frame } = require('@playwright/test/lib/server/frame');16const { getComponentTypeName } = require('@playwright/test/lib/server/frames');17const { Page } = require('@playwright/test/lib/server/page');18const { Frame } = require('@playwright/test/lib/server/frame');19const { getComponentTypeName } = require('@playwright/test/lib/server/frames');20const { Page } = require('@playwright/test/lib/server/page');21const { Frame } = require('@playwright/test/lib/server/frame');22const { getComponentTypeName } = require('@playwright/test/lib/server/frames');23const { Page } = require('@playwright/test/lib/server/page');24const { Frame } = require('@playwright/test/lib/server/frame');25const { getComponentTypeName } = require('@playwright/test/lib/server/frames');26const { Page } = require('@playUsing AI Code Generation
1const { getComponentTypeName } = require('@playwright/test/lib/utils/internal');2const { test } = require('@playwright/test');3test('test', async ({ page }) => {4  const elementHandle = await page.$('css=selector');5  const componentType = getComponentTypeName(elementHandle);6  console.log(componentType);7});8const { test } = require('@playwright/test');9test('test', async ({ page }) => {10  const elementHandle = await page.$('css=selector');11  const componentType = await elementHandle.getAttribute('componentType');12  console.log(componentType);13});14import { test, expect } from '@playwright/test';15import { ElementHandle } from 'playwright';16test('test', async ({ page }) => {17  const elementHandle = await page.$('css=selector');18  const componentType = await elementHandle.getAttribute('componentType');19  expect(componentType).toBe('Button');20});21import { test, expect } from '@playwright/test';22import { ElementHandle } from 'playwright';23type CustomElementHandle = ElementHandle & {24  getAttribute: (name: string) => Promise<string | null>;25};26test('test', async ({ page }) => {27  const elementHandle = await page.$('css=selector');28  const customElementHandle = elementHandle as CustomElementHandle;29  const componentType = await customElementHandle.getAttribute('componentType');30  expect(componentType).toBe('Button');31});32import { test, expect } from '@playwright/test';33import { ElementHandle } from 'playwright';Using AI Code Generation
1const { getComponentTypeName } = require('@playwright/test/lib/autotools');2const { expect } = require('chai');3describe('getComponentTypeName', () => {4  it('should return the component type name', () => {5    expect(getComponentTypeName({ name: 'foo', displayName: 'Foo' })).to.equal('foo');6  });7});8[MIT](Using AI Code Generation
1const { getComponentTypeName } = require("playwright");2const { test, expect } = require("@playwright/test");3test("basic test", async ({ page }) => {4  const title = page.locator(".navbar__inner .navbar__title");5  await expect(title).toHaveText("Playwright");6});Using AI Code Generation
1const { getComponentTypeName } = require('playwright/lib/internal');2console.log(getComponentTypeName('button'));3console.log(getComponentTypeName('input'));4console.log(getComponentTypeName('div'));5const { getComponentTypeName } = require('playwright/lib/internal');6console.log(getComponentTypeName('button'));7console.log(getComponentTypeName('input'));8console.log(getComponentTypeName('div'));9const { getComponentTypeName } = require('playwright/lib/internal');10console.log(getComponentTypeName('button'));11console.log(getComponentTypeName('input'));12console.log(getComponentTypeName('div'));13const { getComponentTypeName } = require('playwright/lib/internal');14console.log(getComponentTypeName('button'));15console.log(getComponentTypeName('input'));16console.log(getComponentTypeName('div'));17const { getComponentTypeName } = require('playwright/lib/internal');18console.log(getComponentTypeName('button'));19console.log(getComponentTypeName('input'));20console.log(getComponentTypeName('div'));21const { getComponentTypeName } = require('playwright/lib/internal');22console.log(getComponentTypeName('button'));23console.log(getComponentTypeName('input'));24console.log(getComponentTypeName('div'));LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!
