Skip to content

Commit

Permalink
refactor native module
Browse files Browse the repository at this point in the history
  • Loading branch information
michalziolkowski committed Mar 21, 2024
1 parent 81aca95 commit d5c9f3a
Show file tree
Hide file tree
Showing 16 changed files with 103 additions and 180 deletions.
3 changes: 3 additions & 0 deletions packages/react-native-storybook/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,9 @@
"react": "*",
"react-native": ">=0.57.0"
},
"optionalDependencies": {
"expo-constants": "*"
},
"engines": {
"node": ">=8.0.0"
},
Expand Down
34 changes: 0 additions & 34 deletions packages/react-native-storybook/src/nativeModule/appendFile.ts

This file was deleted.

13 changes: 0 additions & 13 deletions packages/react-native-storybook/src/nativeModule/getModule.ts

This file was deleted.

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import { NativeModules, Platform } from 'react-native';
import base64 from 'base-64';
import utf8 from 'utf8';
import Constants from 'expo-constants';

import { normalizeFilePath } from './utils/normalizeFilePath';

const isExpoGo = Constants.appOwnership === 'expo';

const { RNSherlo } = NativeModules;

interface SherloModule {
mkdir: (path: string) => Promise<void>;
appendFile: (path: string, base64: string) => Promise<void>;
readFile: (path: string) => Promise<string>;
writeFile: (path: string, data: string) => Promise<void>;
}

function getSherloModule(): SherloModule {
if (RNSherlo === null) {
if (isExpoGo) {
return {
mkdir: async () => {},
appendFile: async () => {},
readFile: async () => '',
writeFile: async () => {},
};
}

throw new Error(
'@sherlo/react-natve-storybook: Sherlo native module is not accessible. Rebuild the app to link it on the native side.'
);
}

const basePath =
Platform.OS === 'android'
? RNSherlo.getConstants().RNExternalDirectoryPath
: RNSherlo.getConstants().RNDocumentDirectoryPath;

return {
appendFile: (filepath: string, contents: string) => {
const b64 = base64.encode(utf8.encode(contents));
const normalizedFilePath = normalizeFilePath(`${basePath}/${filepath}`);

return RNSherlo.appendFile(normalizedFilePath, b64);
},
writeFile: (filepath: string, contents: string) => {
const b64 = base64.encode(utf8.encode(contents));
const normalizedFilePath = normalizeFilePath(`${basePath}/${filepath}`);

return RNSherlo.writeFile(normalizedFilePath, b64, { encoding: 'utf8' });
},
readFile: (filepath: string) => {
const normalizedFilePath = normalizeFilePath(`${basePath}/${filepath}`);

return RNSherlo.readFile(normalizedFilePath).then((b64: string) => {
return utf8.decode(base64.decode(b64));
});
},
mkdir: (path: string) => {
const normalizedFilePath = normalizeFilePath(`${basePath}/${path}`);

return RNSherlo.mkdir(normalizedFilePath, {});
},
};
}

export default getSherloModule;
6 changes: 1 addition & 5 deletions packages/react-native-storybook/src/nativeModule/index.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1 @@
export { default as appendFile } from './appendFile';
export { default as mkdir } from './mkdir';
export { default as readFile } from './readFile';
export { default as writeFile } from './writeFile';
export { default as getSherloDirectoryPath } from './getSherloDirectoryPath';
export { default as getSherloModule } from './getSherloModule';
15 changes: 0 additions & 15 deletions packages/react-native-storybook/src/nativeModule/mkdir.ts

This file was deleted.

38 changes: 0 additions & 38 deletions packages/react-native-storybook/src/nativeModule/readFile.ts

This file was deleted.

39 changes: 0 additions & 39 deletions packages/react-native-storybook/src/nativeModule/writeFile.ts

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import { mkdir } from '../../nativeModule';
import { getSherloModule } from '../../nativeModule';
import { LogFn } from '../types';

const sherloModule = getSherloModule();

const create = (path: string, log: LogFn) => async (): Promise<void> => {
await mkdir(path).catch(() => {
await sherloModule.mkdir(path).catch(() => {
log('create:bridgeDirectoryExists', { path });
});
};
Expand Down
Original file line number Diff line number Diff line change
@@ -1,17 +1,19 @@
import { readFile } from '../../nativeModule';
import { getSherloModule } from '../../nativeModule';
import { getGlobalStates, isObject } from '../../utils';
import { LogFn } from '../types';
import { verifySignature } from '../utils';

const sherloModule = getSherloModule();

// TODO: change name to getDeviceConfig? + return type fix
const getConfig = (path: string, log?: LogFn) => async (): Promise<any> => {
if (getGlobalStates().isIntegrationTest) {
return getGlobalStates().testConfig;
}

// TODO: add comment to explain replaceAll code
const configString = (await readFile(path)).replaceAll('\n', '');
const signature = (await readFile(`${path}.sig`)).replaceAll('\n', '');
const configString = (await sherloModule.readFile(path)).replaceAll('\n', '');
const signature = (await sherloModule.readFile(`${path}.sig`)).replaceAll('\n', '');

const isSignatureValid = verifySignature(configString, signature);
if (!isSignatureValid) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
import { readFile } from '../../nativeModule';
import { getSherloModule } from '../../nativeModule';
import { getGlobalStates } from '../../utils';
import { LogFn, RunnerState } from '../types';

const sherloModule = getSherloModule();

const getState = (path: string, log: LogFn) => async (): Promise<RunnerState> => {
if (getGlobalStates().isIntegrationTest) {
throw new Error("We're not using cached state in render test mode");
}

const stateFile = await readFile(path, 'utf8');
const stateFile = await sherloModule.readFile(path);
const state = JSON.parse(stateFile) as RunnerState;

log('getState:response', { state });
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import { appendFile } from '../../nativeModule';
import { getSherloModule } from '../../nativeModule';
import getGlobalStates from '../../utils/getGlobalStates';
import { LogFn } from '../types';

const sherloModule = getSherloModule();

/**
* Creates a log function that logs messages to the console and appends them to a file.
* @param path - The path of the file to append log messages to.
Expand All @@ -19,7 +21,7 @@ const log =
}

if (!getGlobalStates().isIntegrationTest) {
appendFile(path, logMsg);
sherloModule.appendFile(path, logMsg);
}
};

Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import { appendFile, readFile } from '../../nativeModule';
import { getSherloModule } from '../../nativeModule';
import getGlobalStates from '../../utils/getGlobalStates';
import { LogFn, SendFn, RunnerProtocolItem } from '../types';

const sherloModule = getSherloModule();

const ACK_READ_INTERVAL = 500;

const send =
Expand All @@ -15,7 +17,7 @@ const send =

log('appendingToProtocol', { contentString });

await appendFile(path, `${contentString}\n`);
await sherloModule.appendFile(path, `${contentString}\n`);

await new Promise<void>((resolve) => {
let ackReadInterval: NodeJS.Timeout;
Expand All @@ -30,7 +32,7 @@ const send =

ackReadInterval = setInterval(async () => {
try {
const response = await readFile(path);
const response = await sherloModule.readFile(path);
if (response) {
const responseLines = response.split('\n');
const lastLine = responseLines[responseLines.length - 2];
Expand Down
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
import { writeFile } from '../../nativeModule';
import { getSherloModule } from '../../nativeModule';
import { getGlobalStates } from '../../utils';
import { LogFn, SendFn, RunnerState } from '../types';

const sherloModule = getSherloModule();

const updateState =
(path: string, send: SendFn, log: LogFn) =>
async (state: RunnerState, onlyFile?: boolean): Promise<void> => {
if (!getGlobalStates().isIntegrationTest) {
const stateString = JSON.stringify(state);

await Promise.all([
writeFile(path, stateString),
sherloModule.writeFile(path, stateString),
...(onlyFile ? [] : [send({ action: 'UPDATE_STATE', ...state })]),
]);

Expand Down
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
import { Mode } from '../hoc/withSherlo/withSherlo';
import { getSherloDirectoryPath } from '../nativeModule';
import { create, getConfig, getState, log, send, updateState } from './actions';
import { Config, LogFn, RunnerState, SendFn } from './types';

const path = getSherloDirectoryPath();
export const configPath = 'config.sherlo';

const logPath = `${path}/log.sherlo`;
export const configPath = `${path}/config.sherlo`;
const statePath = `${path}/state.sherlo`;
const protocolPath = `${path}/protocol.sherlo`;
const snapshotsDirectory = `${path}/snapshots`;
const logPath = 'log.sherlo';
const statePath = 'state.sherlo';
const protocolPath = 'protocol.sherlo';
const snapshotsDirectory = 'snapshots';

export interface RunnerBridge {
create: () => Promise<void>;
Expand Down

0 comments on commit d5c9f3a

Please sign in to comment.