Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions packages/community-cli-plugin/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,14 @@
"@react-native/dev-middleware": "0.77.0-main",
"@react-native/metro-babel-transformer": "0.77.0-main",
"chalk": "^4.0.0",
"execa": "^5.1.1",
"debug": "^2.2.0",
"invariant": "^2.2.4",
"metro": "^0.81.0-alpha.2",
"metro-config": "^0.81.0-alpha.2",
"metro-core": "^0.81.0-alpha.2",
"node-fetch": "^2.2.0",
"readline": "^1.3.0"
"readline": "^1.3.0",
"semver": "^7.1.3"
},
"devDependencies": {
"metro-resolver": "^0.81.0-alpha.2"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import type {ConfigT} from 'metro-config';
import type {RequestOptions} from 'metro/src/shared/types.flow';

import loadMetroConfig from '../../utils/loadMetroConfig';
import {logger} from '../../utils/logger';
import parseKeyValueParamArray from '../../utils/parseKeyValueParamArray';
import saveAssets from './saveAssets';
import chalk from 'chalk';
Expand Down Expand Up @@ -72,13 +71,13 @@ async function buildBundleWithConfig(
);

if (config.resolver.platforms.indexOf(args.platform) === -1) {
logger.error(
`Invalid platform ${
console.error(
`${chalk.red('error')}: Invalid platform ${
args.platform ? `"${chalk.bold(args.platform)}" ` : ''
}selected.`,
);

logger.info(
console.info(
`Available platforms are: ${config.resolver.platforms
.map(x => `"${chalk.bold(x)}"`)
.join(
Expand Down Expand Up @@ -123,7 +122,7 @@ async function buildBundleWithConfig(
// $FlowIgnore[incompatible-call]
// $FlowIgnore[prop-missing]
// $FlowIgnore[incompatible-exact]
await bundleImpl.save(bundle, args, logger.info);
await bundleImpl.save(bundle, args, console.info);

// Save the assets of the bundle
const outputAssets = await server.getAssets({
Expand Down
16 changes: 8 additions & 8 deletions packages/community-cli-plugin/src/commands/bundle/saveAssets.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@

import type {AssetData} from 'metro/src/Assets';

import {logger} from '../../utils/logger';
import {
cleanAssetCatalog,
getImageSet,
Expand All @@ -21,6 +20,7 @@ import {
import filterPlatformAssetScales from './filterPlatformAssetScales';
import getAssetDestPathAndroid from './getAssetDestPathAndroid';
import getAssetDestPathIOS from './getAssetDestPathIOS';
import chalk from 'chalk';
import fs from 'fs';
import path from 'path';

Expand All @@ -35,7 +35,7 @@ async function saveAssets(
assetCatalogDest?: string,
): Promise<void> {
if (assetsDest == null) {
logger.warn('Assets destination folder is not set, skipping...');
console.warn('Warning: Assets destination folder is not set, skipping...');
return;
}

Expand Down Expand Up @@ -64,13 +64,13 @@ async function saveAssets(
// remove unused scales from the optimized bundle.
const catalogDir = path.join(assetCatalogDest, 'RNAssets.xcassets');
if (!fs.existsSync(catalogDir)) {
logger.error(
`Could not find asset catalog 'RNAssets.xcassets' in ${assetCatalogDest}. Make sure to create it if it does not exist.`,
console.error(
`${chalk.red('error')}: Could not find asset catalog 'RNAssets.xcassets' in ${assetCatalogDest}. Make sure to create it if it does not exist.`,
);
return;
}

logger.info('Adding images to asset catalog', catalogDir);
console.info('Adding images to asset catalog', catalogDir);
cleanAssetCatalog(catalogDir);
for (const asset of assets) {
if (isCatalogAsset(asset)) {
Expand All @@ -84,7 +84,7 @@ async function saveAssets(
addAssetToCopy(asset);
}
}
logger.info('Done adding images to asset catalog');
console.info('Done adding images to asset catalog');
} else {
assets.forEach(addAssetToCopy);
}
Expand All @@ -98,15 +98,15 @@ function copyAll(filesToCopy: CopiedFiles) {
return Promise.resolve();
}

logger.info(`Copying ${queue.length} asset files`);
console.info(`Copying ${queue.length} asset files`);
return new Promise<void>((resolve, reject) => {
const copyNext = (error?: Error) => {
if (error) {
reject(error);
return;
}
if (queue.length === 0) {
logger.info('Done copying assets');
console.info('Done copying assets');
resolve();
} else {
// queue.length === 0 is checked in previous branch, so this is string
Expand Down
113 changes: 78 additions & 35 deletions packages/community-cli-plugin/src/commands/start/attachKeyHandlers.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,12 @@
import type {Config} from '@react-native-community/cli-types';
import type TerminalReporter from 'metro/src/lib/TerminalReporter';

import {KeyPressHandler} from '../../utils/KeyPressHandler';
import {logger} from '../../utils/logger';
import OpenDebuggerKeyboardHandler from './OpenDebuggerKeyboardHandler';
import chalk from 'chalk';
import execa from 'execa';
import {spawn} from 'child_process';
import invariant from 'invariant';
import readline from 'readline';
import {ReadStream} from 'tty';

const CTRL_C = '\u0003';
const CTRL_D = '\u0004';
Expand All @@ -33,6 +34,18 @@ const throttle = (callback: () => void, timeout: number) => {
};
};

type KeyEvent = {
sequence: string,
name: string,
ctrl: boolean,
meta: boolean,
shift: boolean,
};

const spawnOptions = {
env: {...process.env, FORCE_COLOR: chalk.supportsColor ? 'true' : 'false'},
};

export default function attachKeyHandlers({
cliConfig,
devServerUrl,
Expand All @@ -48,16 +61,23 @@ export default function attachKeyHandlers({
reporter: TerminalReporter,
}) {
if (process.stdin.isTTY !== true) {
logger.debug('Interactive mode is not supported in this environment');
reporter.update({
type: 'unstable_server_log',
level: 'info',
data: 'Interactive mode is not supported in this environment',
});
return;
}

const execaOptions = {
env: {FORCE_COLOR: chalk.supportsColor ? 'true' : 'false'},
};
readline.emitKeypressEvents(process.stdin);
setRawMode(true);

const reload = throttle(() => {
logger.info('Reloading connected app(s)...');
reporter.update({
type: 'unstable_server_log',
level: 'info',
data: 'Reloading connected app(s)...',
});
messageSocket.broadcast('reload', null);
}, RELOAD_TIMEOUT);

Expand All @@ -66,69 +86,92 @@ export default function attachKeyHandlers({
devServerUrl,
});

const onPress = async (key: string) => {
if (openDebuggerKeyboardHandler.maybeHandleTargetSelection(key)) {
process.stdin.on('keypress', (str: string, key: KeyEvent) => {
if (openDebuggerKeyboardHandler.maybeHandleTargetSelection(key.name)) {
return;
}

switch (key.toLowerCase()) {
switch (key.sequence) {
case 'r':
reload();
break;
case 'd':
logger.info('Opening Dev Menu...');
reporter.update({
type: 'unstable_server_log',
level: 'info',
data: 'Opening Dev Menu...',
});
messageSocket.broadcast('devMenu', null);
break;
case 'i':
logger.info('Opening app on iOS...');
execa(
reporter.update({
type: 'unstable_server_log',
level: 'info',
data: 'Opening app on iOS...',
});
spawn(
'npx',
[
'react-native',
'run-ios',
...(cliConfig.project.ios?.watchModeCommandParams ?? []),
],
execaOptions,
spawnOptions,
).stdout?.pipe(process.stdout);
break;
case 'a':
logger.info('Opening app on Android...');
execa(
reporter.update({
type: 'unstable_server_log',
level: 'info',
data: 'Opening app on Android...',
});
spawn(
'npx',
[
'react-native',
'run-android',
...(cliConfig.project.android?.watchModeCommandParams ?? []),
],
execaOptions,
spawnOptions,
).stdout?.pipe(process.stdout);
break;
case 'j':
await openDebuggerKeyboardHandler.handleOpenDebugger();
// eslint-disable-next-line no-void
void openDebuggerKeyboardHandler.handleOpenDebugger();
break;
case CTRL_C:
case CTRL_D:
openDebuggerKeyboardHandler.dismiss();
logger.info('Stopping server');
keyPressHandler.stopInterceptingKeyStrokes();
reporter.update({
type: 'unstable_server_log',
level: 'info',
data: 'Stopping server',
});
setRawMode(false);
process.stdin.pause();
process.emit('SIGINT');
process.exit();
}
};
});

reporter.update({
type: 'unstable_server_log',
level: 'info',
data: `Key commands available:

const keyPressHandler = new KeyPressHandler(onPress);
keyPressHandler.createInteractionListener();
keyPressHandler.startInterceptingKeyStrokes();
${chalk.bold('i')} - run on iOS
${chalk.bold('a')} - run on Android
${chalk.bold('r')} - reload app(s)
${chalk.bold('d')} - open Dev Menu
${chalk.bold('j')} - open DevTools
`,
});
}

logger.log(
[
'',
`${chalk.bold('i')} - run on iOS`,
`${chalk.bold('a')} - run on Android`,
`${chalk.bold('r')} - reload app`,
`${chalk.bold('d')} - open Dev Menu`,
`${chalk.bold('j')} - open DevTools`,
'',
].join('\n'),
function setRawMode(enable: boolean) {
invariant(
process.stdin instanceof ReadStream,
'process.stdin must be a readable stream to modify raw mode',
);
process.stdin.setRawMode(enable);
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
import type {NextHandleFunction, Server} from 'connect';
import type {TerminalReportableEvent} from 'metro/src/lib/TerminalReporter';

import {logger} from '../../utils/logger';
const debug = require('debug')('ReactNative:CommunityCliPlugin');

type MiddlewareReturn = {
middleware: Server,
Expand Down Expand Up @@ -71,7 +71,7 @@ try {
communityMiddlewareFallback.createDevServerMiddleware =
community.createDevServerMiddleware;
} catch {
logger.debug(`⚠️ Unable to find @react-native-community/cli-server-api
debug(`⚠️ Unable to find @react-native-community/cli-server-api
Starting the server without the community middleware.`);
}

Expand Down
Loading