Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 14 additions & 2 deletions core/src/utils/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,23 @@ import { Side } from '../interface';
declare const __zone_symbol__requestAnimationFrame: any;
declare const requestAnimationFrame: any;

/**
* Waits for a component to be ready for
* both custom element and non-custom element builds.
* If non-custom element build, el.componentOnReady
* will be used.
* For custom element builds, we wait a frame
* so that the inner contents of the component
* have a chance to render.
*
* Use this utility rather than calling
* el.componentOnReady yourself.
*/
export const componentOnReady = (el: any, callback: any) => {
if (el.componentOnReady) {
el.componentOnReady().then(callback);
el.componentOnReady().then((resolvedEl: any) => callback(resolvedEl));
} else {
callback();
raf(() => callback(el));
}
}

Expand Down
42 changes: 42 additions & 0 deletions core/src/utils/test/ready.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { componentOnReady } from '../helpers';

describe('componentOnReady()', () => {
it('should correctly call callback for a custom element', (done) => {
customElements.define('hello-world', class extends HTMLElement {
constructor() {
super();
}
});

const component = document.createElement('hello-world');
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: use "eager-component" / "lazy-component" instead of "hello-world" ?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The lazy vs non lazy difference is already noted in the name of the test, so not sure this change would make much of a difference.

componentOnReady(component, (el) => {
expect(el).toBe(component);
done();
})
});

it('should correctly call callback for a lazy loaded component', (done) => {
const cb = jest.fn((el) => {
return new Promise((resolve) => {
setTimeout(() => resolve(el), 250);
});
});

customElements.define('hello-world', class extends HTMLElement {
constructor() {
super();
}

componentOnReady() {
return cb(this);
}
});

const component = document.createElement('hello-world');
componentOnReady(component, (el) => {
expect(el).toBe(component);
expect(cb).toHaveBeenCalledTimes(1);
done();
})
});
});