Skip to content
Draft
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
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@
"linkify-html": "^4.3.2",
"motion": "^12.23.22",
"radix-ui": "^1.4.2",
"rcheevos": "^0.1",
"react": "^19.2.0",
"react-dom": "^19.2.0",
"react-hook-form": "^7.66.0",
Expand Down
8 changes: 8 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

35 changes: 35 additions & 0 deletions resources/js/common/hooks/useRcheevos.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { renderHook, waitFor } from '@/test';

import { useRcheevos } from './useRcheevos';

const mockRcheevosInstance = vi.hoisted(() => ({ initialized: true }) as any);

vi.mock('rcheevos', () => {
const initialize = vi.fn(() => Promise.resolve(mockRcheevosInstance));

return {
RCheevos: {
initialize,
},
};
});

describe('Hook: useRcheevos', () => {
it('returns a ref initialized to null', () => {
// ARRANGE
const { result } = renderHook(() => useRcheevos());

// ASSERT
expect(result.current.current).toBeNull();
});

it('populates the ref with the initialized RCheevos instance', async () => {
// ARRANGE
const { result } = renderHook(() => useRcheevos());

// ASSERT
await waitFor(() => {
expect(result.current.current).toBe(mockRcheevosInstance);
});
});
});
17 changes: 17 additions & 0 deletions resources/js/common/hooks/useRcheevos.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { RCheevos } from 'rcheevos';
import type { RefObject } from 'react';
import { useEffect, useRef } from 'react';

const promise = RCheevos.initialize();

export function useRcheevos(): RefObject<RCheevos | null> {
const ref = useRef<RCheevos | null>(null);

useEffect(() => {
promise.then((instance) => {
ref.current = instance;
});
}, []);

return ref;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
import userEvent from '@testing-library/user-event';

import { render, screen, waitFor } from '@/test';
import { createGame, createGameHash } from '@/test/factories';

import { HashCheckerSection } from './HashCheckerSection';

const computeHashMock = vi.hoisted(() => vi.fn());

vi.mock('@/common/hooks/useRcheevos', () => ({
useRcheevos: () => ({
current: {
computeHash: computeHashMock,
},
}),
}));

describe('Component: HashCheckerSection', () => {
beforeEach(() => {
computeHashMock.mockReset();
computeHashMock.mockReturnValue('abc123');
});

it('renders without crashing', () => {
// ARRANGE
const { container } = render<App.Platform.Data.GameHashesPageProps>(
<HashCheckerSection systemID={5} />,
{
pageProps: {
can: { manageGameHashes: false },
game: createGame(),
hashes: [createGameHash({ md5: 'abc123' })],
},
},
);

// ASSERT
expect(container).toBeTruthy();
});

it('computes the hash for an uploaded file and shows a success indicator when it matches', async () => {
// ARRANGE
render<App.Platform.Data.GameHashesPageProps>(<HashCheckerSection systemID={5} />, {
pageProps: {
can: { manageGameHashes: false },
game: createGame(),
hashes: [createGameHash({ md5: 'abc123' })],
},
});

const fileInput = screen.getByTestId('hash-file-input') as HTMLInputElement;
const file = new File(['dummy-content'], 'rom.bin', {
type: 'application/octet-stream',
});

// ACT
await userEvent.upload(fileInput, file);

// ASSERT
await waitFor(() => {
expect(computeHashMock).toHaveBeenCalledTimes(1);
});

expect(computeHashMock).toHaveBeenCalledWith(
5,
new TextEncoder().encode('dummy-content').buffer,
);
expect(screen.getByText(/got hash:/i)).toBeVisible();
expect(screen.getByText('abc123')).toBeVisible();
expect(screen.getByText('✅')).toBeVisible();
});

it('shows a failure indicator when the computed hash is not recognized', async () => {
// ARRANGE
computeHashMock.mockReturnValue('deadbeef');

render<App.Platform.Data.GameHashesPageProps>(<HashCheckerSection systemID={3} />, {
pageProps: {
can: { manageGameHashes: false },
game: createGame(),
hashes: [createGameHash({ md5: 'abc123' })],
},
});

const fileInput = screen.getByTestId('hash-file-input') as HTMLInputElement;
const file = new File(['other-content'], 'rom2.bin', {
type: 'application/octet-stream',
});

// ACT
await userEvent.upload(fileInput, file);

// ASSERT
await waitFor(() => {
expect(screen.getByText('deadbeef')).toBeVisible();
});

expect(computeHashMock).toHaveBeenCalledWith(
3,
new TextEncoder().encode('other-content').buffer,
);
expect(screen.getByText('❌')).toBeVisible();
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import type { ChangeEvent, FC } from 'react';
import { memo, useCallback, useRef, useState } from 'react';

import { usePageProps } from '@/common/hooks/usePageProps';
import { useRcheevos } from '@/common/hooks/useRcheevos';

interface HashCheckerSection {
systemID: number;
}

export const HashCheckerSection: FC<HashCheckerSection> = memo(({ systemID }) => {
const hasher = useRcheevos();
const fileRef = useRef<HTMLInputElement>(null);
const [hash, setHash] = useState<string | null>(null);
const { hashes } = usePageProps<App.Platform.Data.GameHashesPageProps>();

const onFileSelected = useCallback(
async (event: ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0];
if (!file || !hasher.current) return;

const result = hasher.current.computeHash(systemID, await file.arrayBuffer());

setHash(result);
},
[hasher, systemID],
);

return (
<div>
<input
max="1"
type="file"
ref={fileRef}
onChange={onFileSelected}
aria-label="Upload game file"
data-testid="hash-file-input"
/>
{hash && (
<div>
<p>
{'Got Hash:'} <code>{hash}</code>
</p>
<p>{hashes.some((h) => h.md5 === hash) ? '✅' : '❌'}</p>
</div>
)}
</div>
);
});
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,16 @@ import { createGame, createGameHash } from '@/test/factories';

import { HashesMainRoot } from './HashesMainRoot';

vi.mock('rcheevos', () => {
const initialize = vi.fn(() => Promise.resolve(() => ({ initialized: true })));

return {
RCheevos: {
initialize,
},
};
});

describe('Component: HashesMainRoot', () => {
it('renders without crashing', () => {
// ARRANGE
Expand Down Expand Up @@ -85,7 +95,9 @@ describe('Component: HashesMainRoot', () => {
});

// ASSERT
const button = screen.queryByRole('button', { name: /other known hashes/i });
const button = screen.queryByRole('button', {
name: /other known hashes/i,
});
expect(button).toBeNull();
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { GameHeading } from '@/common/components/GameHeading/GameHeading';
import { InertiaLink } from '@/common/components/InertiaLink';
import { usePageProps } from '@/common/hooks/usePageProps';

import { HashCheckerSection } from './HashCheckerSection';
import { HashesList } from './HashesList';
import { OtherHashesSection } from './OtherHashesSection';

Expand Down Expand Up @@ -52,7 +53,13 @@ export const HashesMainRoot: FC = memo(() => {
<Trans
i18nKey="Additional information for these hashes may be listed on <1>the game's official forum topic</1>."
components={{
1: <InertiaLink href={route('forum-topic.show', { topic: game.forumTopicId })} />,
1: (
<InertiaLink
href={route('forum-topic.show', {
topic: game.forumTopicId,
})}
/>
),
}}
/>
) : null}{' '}
Expand All @@ -71,6 +78,8 @@ export const HashesMainRoot: FC = memo(() => {
</p>
</Embed>

{game.system && <HashCheckerSection systemID={game.system.id} />}

<div className="flex flex-col gap-1">
<p>
<Trans
Expand Down