Skip to content
Open
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
45 changes: 45 additions & 0 deletions __tests__/api/client.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,51 @@ describe('onChangeClientState', () => {
});
});

describe('Callbacks', () => {
it('Verify that callback onload is triggered', async () => {
const onChange = vi.fn();
let obj = { nested: { loaded: false, error: false } };

let onLoad = () => {
obj.nested.loaded = true;
};

const onError = () => {
obj.nested.error = true;
};

render(
<div>
<Helmet onChangeClientState={onChange}>
<title>Main Title</title>
<script
src="http://localhost/test.js"
type="text/javascript"
onload={onLoad} // eslint-disable-line
onError={onError}
/>
</Helmet>
</div>
);

const newState = onChange.mock.calls[0][0];
expect(onChange).toHaveBeenCalled();
expect(onChange.mock.calls).toHaveLength(1);
expect(newState).toEqual(expect.objectContaining({ title: 'Main Title' }));
expect(typeof newState.scriptTags[0].onload).toEqual('function');
await new Promise(resolve =>
setInterval(() => {
// Simulate script load
newState.scriptTags[0].onload();
if (obj.nested.loaded) {
resolve(true);
}
}, 100)
);
expect(obj.nested).toEqual({ loaded: true, error: false });
});
});

// it('calls the deepest defined callback with the deepest state', () => {
// const onChange = vi.fn();
// render(
Expand Down
10 changes: 9 additions & 1 deletion src/client.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { HELMET_ATTRIBUTE, TAG_NAMES, TAG_PROPERTIES } from './constants';
import { HELMET_ATTRIBUTE, TAG_EVENTS, TAG_NAMES, TAG_PROPERTIES } from './constants';
import type { Attributes, StateUpdate, TagList } from './types';
import { flattenArray } from './utils';

Expand Down Expand Up @@ -36,6 +36,14 @@ const updateTags = (type: string, tags: HTMLElement[]) => {
// @ts-ignore
newElement.appendChild(document.createTextNode(tag.cssText));
}
} else if (
(TAG_EVENTS.ON_LOAD === attribute || TAG_EVENTS.ON_ERROR === attribute) &&
typeof tag[attribute] === 'function' &&
newElement instanceof HTMLScriptElement
) {
const attr = attribute as keyof HTMLElement;
const value = typeof tag[attr] === 'undefined' ? '' : tag[attr];
newElement[attribute] = value as any;
} else {
const attr = attribute as keyof HTMLElement;
const value = typeof tag[attr] === 'undefined' ? '' : tag[attr];
Expand Down
5 changes: 5 additions & 0 deletions src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@ export enum ATTRIBUTE_NAMES {
TITLE = 'titleAttributes',
}

export enum TAG_EVENTS {
ON_LOAD = 'onload',
ON_ERROR = 'onerror',
}

export enum TAG_NAMES {
BASE = 'base',
BODY = 'body',
Expand Down