Skip to content

Commit 7a135b9

Browse files
fix: Disable base64 optimization in ReactNative (#3564)
Our base64 encoding optimization does not run in React Native, because React Native doesn't support creating Files/Blobs from buffers. --------- Co-authored-by: Maarten Zuidhoorn <[email protected]>
1 parent fcdb865 commit 7a135b9

File tree

2 files changed

+19
-2
lines changed

2 files changed

+19
-2
lines changed

packages/snaps-utils/src/base64.test.ts

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,21 @@ describe('encodeBase64', () => {
5151
);
5252
expect(await encodeBase64(vfile)).toBe('eyJmb28iOiJiYXIifQ==');
5353
});
54+
55+
it('does not use optimization when running in React Native', async () => {
56+
Object.defineProperty(globalThis, 'FileReader', {
57+
value: MockFileReader,
58+
});
59+
60+
Object.defineProperty(globalThis, 'navigator', {
61+
value: { product: 'ReactNative' },
62+
});
63+
64+
const vfile = new VirtualFile(
65+
stringToBytes(JSON.stringify({ foo: 'bar' })),
66+
);
67+
expect(await encodeBase64(vfile)).toBe('eyJmb28iOiJiYXIifQ==');
68+
});
5469
});
5570

5671
describe('decodeBase64', () => {

packages/snaps-utils/src/base64.ts

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,10 @@ import type { VirtualFile } from './virtual-file';
1111
*/
1212
export async function encodeBase64(input: Uint8Array | VirtualFile | string) {
1313
const bytes = getBytes(input);
14-
// In the browser, FileReader is much faster than bytesToBase64.
15-
if ('FileReader' in globalThis) {
14+
const isReactNative =
15+
typeof navigator !== 'undefined' && navigator.product === 'ReactNative';
16+
// In the browser, FileReader is much faster than bytesToBase64. This is not supported in React Native however.
17+
if ('FileReader' in globalThis && !isReactNative) {
1618
return await new Promise((resolve, reject) => {
1719
const reader = Object.assign(new FileReader(), {
1820
onload: () =>

0 commit comments

Comments
 (0)