Browse Source

feat: add findFirstType method to Component (#6084)

* feat: add getType method to Component

* fix: rename getType into findFirstType for clarity sake

---------

Co-authored-by: Artur Arseniev <artur.catch@hotmail.it>
pull/6088/head
William DA SILVA 1 year ago
committed by GitHub
parent
commit
ecfff9dc88
No known key found for this signature in database GPG Key ID: B5690EEEBB952194
  1. 18
      docs/api/component.md
  2. 15
      src/dom_components/model/Component.ts
  3. 26
      test/specs/dom_components/model/Component.ts

18
docs/api/component.md

@ -187,6 +187,24 @@ console.log(allImages[0]) // prints the first found component
Returns **[Array][5]\<Component>**
## findFirstType
Find the first inner component by component type.
If no component is found, it returns `undefined`.
### Parameters
* `type` **[String][1]** Component type
### Examples
```javascript
const image = component.findFirstType('image');
if (image) console.log(image)
```
Returns **Component** Found component, otherwise `undefined`
## closest
Find the closest parent component by query string.

15
src/dom_components/model/Component.ts

@ -507,6 +507,21 @@ export default class Component extends StyleableModel<ComponentProperties> {
return result;
}
/**
* Find the first inner component by component type.
* If no component is found, it returns `undefined`.
* @param {String} type Component type
* @returns {Component|undefined}
* @example
* const image = component.findFirstType('image');
* if (image) {
* console.log(image);
* }
*/
findFirstType(type: string): Component | undefined {
return this.findType(type).at(0);
}
/**
* Find the closest parent component by query string.
* **ATTENTION**: this method works only with already rendered component

26
test/specs/dom_components/model/Component.ts

@ -273,6 +273,32 @@ describe('Component', () => {
expect(result.class).toEqual(undefined);
});
test('findFirstType returns first component of specified type', () => {
const image1 = new ComponentImage({}, compOpts);
const text = new ComponentText({}, compOpts);
const image2 = new ComponentImage({}, compOpts);
obj.append([image1, text, image2]);
const result = obj.findFirstType('image');
expect(result).toBe(image1);
expect(result instanceof ComponentImage).toBe(true);
});
test('findFirstType returns undefined for non-existent type', () => {
const text = new ComponentText({}, compOpts);
obj.append(text);
const result = obj.findFirstType('image');
expect(result).toBeUndefined();
});
test('findFirstType returns undefined for empty component', () => {
const result = obj.findFirstType('div');
expect(result).toBeUndefined();
});
test('setAttributes', () => {
obj.setAttributes({
id: 'test',

Loading…
Cancel
Save