Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[CARE-5168] Fix Video not working after switching languages #82

Merged
Merged
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: 27 additions & 18 deletions src/components/HtmlInjection.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
'use client';

import type { HTMLAttributes, ScriptHTMLAttributes } from 'react';
import { useEffect, useMemo, useRef } from 'react';
import type { ForwardedRef, HTMLAttributes, ScriptHTMLAttributes } from 'react';
import { forwardRef, memo, useEffect, useMemo, useRef } from 'react';

interface Props extends HTMLAttributes<HTMLDivElement> {
html: string;
Expand All @@ -18,27 +18,36 @@ export function HtmlInjection(props: Props) {
const strippedHtml = useScripts(html, onError);

useEffect(() => {
if (containerRef.current) {
containerRef.current.innerHTML = strippedHtml;

if (onPlay) {
import('player.js').then((playerjs) => {
const nodes = containerRef.current?.getElementsByTagName('iframe');
const iframes = Array.from(nodes ?? []);
iframes.forEach((iframe) => {
iframe.addEventListener('load', () => {
const player = new playerjs.Player(iframe);
player.on('play', onPlay);
});
});
});
}
if (!containerRef.current || !onPlay) {
return;
}

import('player.js').then((playerjs) => {
const nodes = containerRef.current?.getElementsByTagName('iframe');
const iframes = Array.from(nodes ?? []);
iframes.forEach((iframe) => {
iframe.addEventListener('load', () => {
const player = new playerjs.Player(iframe);
player.on('play', onPlay);
});
});
});
}, [onPlay, strippedHtml]);

return <div {...attrs} ref={containerRef} />;
return <MemoHtml ref={containerRef} {...attrs} html={strippedHtml} />;
}

const MemoHtml = memo(
forwardRef(
(
{ html, ...restProps }: HTMLAttributes<HTMLDivElement> & { html: string },
ref: ForwardedRef<HTMLDivElement>,
) => <div ref={ref} {...restProps} dangerouslySetInnerHTML={{ __html: html }} />,
),
);

MemoHtml.displayName = 'MemoHtml';
Comment on lines +40 to +49
Copy link
Contributor Author

Choose a reason for hiding this comment

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

We've used memo() here to avoid re-rendering and erasing the modified div innerHTML content.


function useScripts(html: Props['html'], onError: Props['onError']) {
const [strippedHtml, scriptsAttributes] = useMemo(() => {
if (typeof document === 'undefined') {
Expand Down
Loading