]> git.localhorst.tv Git - alttp.git/blob - resources/js/helpers/AlttpBaseRomContext.js
some discord bot stuff
[alttp.git] / resources / js / helpers / AlttpBaseRomContext.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 AlttpBaseRomContext = React.createContext(null);
10
11 const AlttpBaseRomProvider = ({ 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 === 0x3322EFFC) {
18                                 setRom(buffer);
19                                 localforage.setItem('alttpBaseRom', buffer);
20                                 toastr.success(i18n.t('alttp.baseRomSet'));
21                         } else {
22                                 toastr.error(i18n.t('alttp.baseRomInvalid'));
23                         }
24                 } else {
25                         setRom(null);
26                         localforage.removeItem('alttpBaseRom');
27                         toastr.success(i18n.t('alttp.baseRomRemoved'));
28                 }
29         }, [setRom]);
30
31         React.useEffect(async () => {
32                 const stored = await localforage.getItem('alttpBaseRom');
33                 if (stored) {
34                         const crc = CRC32.buf(new Uint8Array(stored));
35                         if (crc == 0x3322EFFC) {
36                                 setRom(stored);
37                         }
38                 }
39         }, []);
40
41         return <AlttpBaseRomContext.Provider value={{ rom, setRom: setRomCallback }}>
42                 {children}
43         </AlttpBaseRomContext.Provider>;
44 };
45
46 AlttpBaseRomProvider.propTypes = {
47         children: PropTypes.node,
48 };
49
50 export const useAlttpBaseRom = () => React.useContext(AlttpBaseRomContext);
51
52 export default AlttpBaseRomProvider;