forked from pybricks/pybricks-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhooks.ts
More file actions
223 lines (184 loc) · 6.89 KB
/
hooks.ts
File metadata and controls
223 lines (184 loc) · 6.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
// SPDX-License-Identifier: MIT
// Copyright (c) 2022-2025 The Pybricks Authors
// based on https://usehooks-ts.com/react-hook/use-fetch
import { FirmwareMetadata, FirmwareReader } from '@pybricks/firmware';
import cityHubZip from '@pybricks/firmware/build/cityhub.zip';
import essentialHubZip from '@pybricks/firmware/build/essentialhub.zip';
import moveHubZip from '@pybricks/firmware/build/movehub.zip';
import primeHubZip from '@pybricks/firmware/build/primehub.zip';
import technicHubZip from '@pybricks/firmware/build/technichub.zip';
import { useEffect, useMemo, useReducer, useRef } from 'react';
import { useDispatch } from 'react-redux';
import { useIsMounted } from 'usehooks-ts';
import { alertsShowAlert } from '../../alerts/actions';
import { Hub } from '../../components/hubPicker';
import { ensureError } from '../../utils';
import { validateMetadata } from './';
export type FirmwareData = {
firmwareZip: ArrayBuffer;
licenseText: string;
metadata: FirmwareMetadata;
};
interface State {
/** The firmware.zip data or undefined if `fetch()` is not complete or on error. */
firmwareData?: FirmwareData;
/** Undefined `fetch()` is not complete yet or was successful, otherwise the error. */
firmwareError?: Error;
}
type Cache = { [url: string]: FirmwareData };
// discriminated union type
type Action =
| { type: 'loading' }
| { type: 'fetched'; payload: FirmwareData }
| { type: 'error'; payload: Error };
const firmwareZipMap = new Map<Hub, string>([
[Hub.Move, moveHubZip],
[Hub.City, cityHubZip],
[Hub.Technic, technicHubZip],
[Hub.Prime, primeHubZip],
[Hub.Essential, essentialHubZip],
[Hub.Inventor, primeHubZip],
]);
/**
* Gets Pybricks firmware .zip file for the specified hub type.
* @param hubType The hub type.
* @returns The current state.
*/
export function useFirmware(hubType: Hub): State {
const url = firmwareZipMap.get(hubType);
const cache = useRef<Cache>({});
const isMounted = useIsMounted();
const initialState: State = {
firmwareError: undefined,
firmwareData: undefined,
};
// Keep state logic separated
const fetchReducer = (state: State, action: Action): State => {
switch (action.type) {
case 'loading':
return { ...initialState };
case 'fetched':
return { ...initialState, firmwareData: action.payload };
case 'error':
return { ...initialState, firmwareError: action.payload };
default:
return state;
}
};
const [state, dispatch] = useReducer(fetchReducer, initialState);
useEffect(() => {
// Raise error if the url is not given, to show that something is wrong
// instead of a misleading intermediate state.
if (!url) {
dispatch({ type: 'error', payload: new Error('No URL for this hub type') });
return;
}
const fetchData = async () => {
dispatch({ type: 'loading' });
// If a cache exists for this url, return it
if (cache.current[url]) {
dispatch({ type: 'fetched', payload: cache.current[url] });
return;
}
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(response.statusText);
}
const firmwareZip = await response.arrayBuffer();
const reader = await FirmwareReader.load(firmwareZip);
const licenseText = await reader.readReadMeOss();
const metadata = await reader.readMetadata();
const data = { firmwareZip, licenseText, metadata };
cache.current[url] = data;
if (!isMounted()) {
return;
}
dispatch({ type: 'fetched', payload: data });
} catch (error) {
if (process.env.NODE_ENV !== 'test') {
console.error(error);
}
if (!isMounted()) {
return;
}
dispatch({ type: 'error', payload: ensureError(error) });
}
};
void fetchData();
}, [url, isMounted]);
return state;
}
/**
* Gets the data from the user-provided firmware file, if any.
* @param zipFile The user-provided zip file.
* @returns State consisting of unzipped data or error.
*/
export function useCustomFirmware(zipFile: File | undefined) {
const reduxDispatch = useDispatch();
const isMounted = useIsMounted();
const initialState: State = {
firmwareError: undefined,
firmwareData: undefined,
};
// Keep state logic separated
const fetchReducer = (state: State, action: Action): State => {
switch (action.type) {
case 'loading':
return { ...initialState };
case 'fetched':
return { ...initialState, firmwareData: action.payload };
case 'error':
return { ...initialState, firmwareError: action.payload };
default:
return state;
}
};
const [state, dispatch] = useReducer(fetchReducer, initialState);
useEffect(() => {
if (!zipFile) {
dispatch({ type: 'loading' });
return;
}
// REVISIT: with no cache, we end up unzipping the same file multiple times.
const readFile = async () => {
dispatch({ type: 'loading' });
try {
const firmwareZip = await zipFile.arrayBuffer();
const reader = await FirmwareReader.load(firmwareZip);
const licenseText = await reader.readReadMeOss();
const metadata = await reader.readMetadata();
validateMetadata(metadata);
const data = {
firmwareZip,
licenseText,
metadata,
};
if (!isMounted()) {
return;
}
dispatch({ type: 'fetched', payload: data });
} catch (err) {
if (process.env.NODE_ENV !== 'test') {
console.error(err);
}
if (!isMounted()) {
return;
}
const error = ensureError(err);
dispatch({ type: 'error', payload: error });
reduxDispatch(alertsShowAlert('alerts', 'unexpectedError', { error }));
}
};
readFile();
}, [zipFile, isMounted, reduxDispatch]);
const isCustomFirmwareRequested = useMemo(
() => state.firmwareData !== undefined,
[state.firmwareData],
);
return {
isCustomFirmwareRequested,
customFirmwareData: state.firmwareData,
customFirmwareError: state.firmwareError,
};
}