Gameboy: render the canvas inside a container div

This commit is contained in:
Alex Gleason 2023-11-24 20:54:24 -06:00
parent 33b2d19cd0
commit 5ee2c8a23c
No known key found for this signature in database
GPG Key ID: 7211D1F99744FBB7
2 changed files with 21 additions and 10 deletions

View File

@ -1,14 +1,19 @@
// @ts-ignore No types available // @ts-ignore No types available
import { WasmBoy } from '@soapbox.pub/wasmboy'; import { WasmBoy } from '@soapbox.pub/wasmboy';
import clsx from 'clsx';
import React, { useCallback, useEffect, useRef } from 'react'; import React, { useCallback, useEffect, useRef } from 'react';
interface IGameboy extends React.CanvasHTMLAttributes<HTMLCanvasElement> { interface IGameboy extends Pick<React.CanvasHTMLAttributes<HTMLCanvasElement>, 'onFocus' | 'onBlur'> {
/** Classname of the outer `<div>`. */
className?: string;
/** URL to the ROM. */ /** URL to the ROM. */
src: string; src: string;
/** Aspect ratio of the canvas. */
aspect?: 'normal' | 'stretched';
} }
/** Component to display a playable Gameboy emulator. */ /** Component to display a playable Gameboy emulator. */
const Gameboy: React.FC<IGameboy> = ({ src, onFocus, onBlur, ...rest }) => { const Gameboy: React.FC<IGameboy> = ({ className, src, aspect = 'normal', onFocus, onBlur, ...rest }) => {
const canvas = useRef<HTMLCanvasElement>(null); const canvas = useRef<HTMLCanvasElement>(null);
async function init() { async function init() {
@ -41,13 +46,19 @@ const Gameboy: React.FC<IGameboy> = ({ src, onFocus, onBlur, ...rest }) => {
}, []); }, []);
return ( return (
<canvas <div className={className}>
ref={canvas} <canvas
tabIndex={0} ref={canvas}
onFocus={onFocus ?? handleFocus} tabIndex={0}
onBlur={onBlur ?? handleBlur} className={clsx('h-full w-full bg-black ', {
{...rest} 'object-contain': aspect === 'normal',
/> 'object-cover': aspect === 'stretched',
})}
onFocus={onFocus ?? handleFocus}
onBlur={onBlur ?? handleBlur}
{...rest}
/>
</div>
); );
}; };

View File

@ -156,7 +156,7 @@ const Item: React.FC<IItem> = ({
style={{ position, float, left, top, right, bottom, height, width: `${width}%` }} style={{ position, float, left, top, right, bottom, height, width: `${width}%` }}
> >
<Suspense fallback={<div className='media-gallery__item-thumbnail' />}> <Suspense fallback={<div className='media-gallery__item-thumbnail' />}>
<Gameboy className='media-gallery__item-thumbnail object-contain' src={attachment.url} /> <Gameboy className='media-gallery__item-thumbnail' src={attachment.url} />
</Suspense> </Suspense>
</div> </div>
); );