]> git.localhorst.tv Git - alttp.git/blob - resources/js/helpers/AosBaseRomContext.js
client side aos base rom select
[alttp.git] / resources / js / helpers / AosBaseRomContext.js
1 import CRC32 from 'crc-32';
2 import localforage from 'localforage';
3 import PropTypes from 'prop-types';
4 import React from 'react';
5 import toastr from 'toastr';
6
7 import i18n from '../i18n';
8
9 const AosBaseRomContext = React.createContext(null);
10
11 const AosBaseRomProvider = ({ children }) => {
12         const [rom, setRom] = React.useState(null);
13
14         const setRomCallback = React.useCallback(buffer => {
15                 if (buffer) {
16                         const crc = CRC32.buf(new Uint8Array(buffer));
17                         if (crc === 0x35536183) {
18                                 setRom(buffer);
19                                 localforage.setItem('aosBaseRom', buffer);
20                                 toastr.success(i18n.t('aos.baseRomSet'));
21                         } else {
22                                 toastr.error(i18n.t('aos.baseRomInvalid'));
23                         }
24                 } else {
25                         setRom(null);
26                         localforage.removeItem('aosBaseRom');
27                         toastr.success(i18n.t('aos.baseRomRemoved'));
28                 }
29         }, [setRom]);
30
31         React.useEffect(async () => {
32                 const stored = await localforage.getItem('aosBaseRom');
33                 if (stored) {
34                         const crc = CRC32.buf(new Uint8Array(stored));
35                         if (crc == 0x35536183) {
36                                 setRom(stored);
37                         }
38                 }
39         }, []);
40
41         return <AosBaseRomContext.Provider value={{ rom, setRom: setRomCallback }}>
42                 {children}
43         </AosBaseRomContext.Provider>;
44 };
45
46 AosBaseRomProvider.propTypes = {
47         children: PropTypes.node,
48 };
49
50 export const useAosBaseRom = () => React.useContext(AosBaseRomContext);
51
52 export default AosBaseRomProvider;