Skip to content

Commit

Permalink
Merge pull request #1581 from arminyahya/pr/createHTMLMediaHook-typing
Browse files Browse the repository at this point in the history
fix: add generic parameter to createHTMLMediaHook. no typecheck problem with ref anymore
  • Loading branch information
xobotyi authored Apr 6, 2021
2 parents d170dea + 1f547ef commit a91c1f1
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 19 deletions.
27 changes: 11 additions & 16 deletions src/factory/createHTMLMediaHook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,25 +27,20 @@ export interface HTMLMediaControls {
seek: (time: number) => void;
}

type createHTMLMediaHookReturn = [
React.ReactElement<HTMLMediaProps>,
HTMLMediaState,
HTMLMediaControls,
{ current: HTMLAudioElement | null }
];

export default function createHTMLMediaHook(tag: 'audio' | 'video') {
type MediaPropsWithRef<T> = HTMLMediaProps & { ref?: React.MutableRefObject<T | null> };

export default function createHTMLMediaHook<T extends HTMLAudioElement | HTMLVideoElement>(tag: 'audio' | 'video') {
return (
elOrProps: HTMLMediaProps | React.ReactElement<HTMLMediaProps>
): createHTMLMediaHookReturn => {
let element: React.ReactElement<any> | undefined;
let props: HTMLMediaProps;
) => {
let element: React.ReactElement<MediaPropsWithRef<T>> | undefined;
let props: MediaPropsWithRef<T>;

if (React.isValidElement(elOrProps)) {
element = elOrProps;
props = element.props;
} else {
props = elOrProps as HTMLMediaProps;
props = elOrProps;
}

const [state, setState] = useSetState<HTMLMediaState>({
Expand All @@ -56,7 +51,7 @@ export default function createHTMLMediaHook(tag: 'audio' | 'video') {
muted: false,
volume: 1,
});
const ref = useRef<HTMLAudioElement | null>(null);
const ref = useRef<T | null>(null);

const wrapEvent = (userEvent, proxyEvent?) => {
return (event) => {
Expand Down Expand Up @@ -234,6 +229,6 @@ export default function createHTMLMediaHook(tag: 'audio' | 'video') {
}
}, [props.src]);

return [element, state, controls, ref];
};
}
return [element, state, controls, ref] as const;
}
};
3 changes: 1 addition & 2 deletions src/useAudio.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import createHTMLMediaHook from './factory/createHTMLMediaHook';

const useAudio = createHTMLMediaHook('audio');

const useAudio = createHTMLMediaHook<HTMLAudioElement>('audio');
export default useAudio;
2 changes: 1 addition & 1 deletion src/useVideo.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import createHTMLMediaHook from './factory/createHTMLMediaHook';

const useVideo = createHTMLMediaHook('video');
const useVideo = createHTMLMediaHook<HTMLVideoElement>('video');

export default useVideo;

0 comments on commit a91c1f1

Please sign in to comment.