Skip to content
Merged
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
2 changes: 2 additions & 0 deletions Examples/RN0840/.bundle/config
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
BUNDLE_PATH: "vendor/bundle"
BUNDLE_FORCE_RUBY_PLATFORM: 1
4 changes: 4 additions & 0 deletions Examples/RN0840/.eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
module.exports = {
root: true,
extends: '@react-native',
};
75 changes: 75 additions & 0 deletions Examples/RN0840/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
# OSX
#
.DS_Store

# Xcode
#
build/
*.pbxuser
!default.pbxuser
*.mode1v3
!default.mode1v3
*.mode2v3
!default.mode2v3
*.perspectivev3
!default.perspectivev3
xcuserdata
*.xccheckout
*.moved-aside
DerivedData
*.hmap
*.ipa
*.xcuserstate
**/.xcode.env.local

# Android/IntelliJ
#
build/
.idea
.gradle
local.properties
*.iml
*.hprof
.cxx/
*.keystore
!debug.keystore
.kotlin/

# node.js
#
node_modules/
npm-debug.log
yarn-error.log

# fastlane
#
# It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the
# screenshots whenever they are needed.
# For more information about the recommended setup visit:
# https://docs.fastlane.tools/best-practices/source-control/

**/fastlane/report.xml
**/fastlane/Preview.html
**/fastlane/screenshots
**/fastlane/test_output

# Bundle artifact
*.jsbundle

# Ruby / CocoaPods
**/Pods/
/vendor/bundle/

# Temporary files created by Metro to check the health of the file watcher
.metro-health-check*

# testing
/coverage

# Yarn
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/sdks
!.yarn/versions
5 changes: 5 additions & 0 deletions Examples/RN0840/.prettierrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
module.exports = {
arrowParens: 'avoid',
singleQuote: true,
trailingComma: 'all',
};
1 change: 1 addition & 0 deletions Examples/RN0840/.watchmanconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{}
188 changes: 188 additions & 0 deletions Examples/RN0840/App.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,188 @@
import React, { useCallback, useState } from 'react';
import {
Button,
Platform,
ScrollView,
StatusBar,
Text,
TextInput,
View,
} from 'react-native';
import CodePush, {
ReleaseHistoryInterface,
UpdateCheckRequest,
} from '@bravemobile/react-native-code-push';
import axios from 'axios';
import { SafeAreaProvider, useSafeAreaInsets } from 'react-native-safe-area-context';

// Set this to true before run `npx code-push release` to release a new bundle
const IS_RELEASING_BUNDLE = false;

const REACT_NATIVE_VERSION = (() => {
const { major, minor, patch, prerelease } = Platform.constants.reactNativeVersion;
return `${major}.${minor}.${patch}` + (prerelease ? `-${prerelease}` : '');
})();

function App() {
const { top } = useSafeAreaInsets();
const [syncResult, setSyncResult] = useState('');
const [progress, setProgress] = useState(0);
const [runningMetadata, setRunningMetadata] = useState('');
const [pendingMetadata, setPendingMetadata] = useState('');
const [latestMetadata, setLatestMetadata] = useState('');

const handleSync = useCallback(() => {
CodePush.sync(
{},
status => {
setSyncResult(findKeyByValue(CodePush.SyncStatus, status) ?? '');
},
({ receivedBytes, totalBytes }) => {
setProgress(Math.round((receivedBytes / totalBytes) * 100));
},
mismatch => {
console.log('CodePush mismatch', JSON.stringify(mismatch, null, 2));
},
).catch(error => {
console.error(error);
console.log('Sync failed', error.message ?? 'Unknown error');
});
}, []);

const handleMetadata = useCallback(async () => {
const [running, pending, latest] = await Promise.all([
CodePush.getUpdateMetadata(CodePush.UpdateState.RUNNING),
CodePush.getUpdateMetadata(CodePush.UpdateState.PENDING),
CodePush.getUpdateMetadata(CodePush.UpdateState.LATEST),
]);
setRunningMetadata(JSON.stringify(running ?? null, null, 2));
setPendingMetadata(JSON.stringify(pending ?? null, null, 2));
setLatestMetadata(JSON.stringify(latest ?? null, null, 2));
}, []);

return (
<View style={{ flex: 1, paddingTop: top, backgroundColor: 'white' }}>
<Text style={{ fontSize: 20, fontWeight: '600' }}>
{`React Native ${REACT_NATIVE_VERSION}`}
</Text>
{IS_RELEASING_BUNDLE && <Text style={{ fontSize: 20, fontWeight: '600' }}>
{'UPDATED!'}
</Text>}

<ScrollView contentContainerStyle={{ padding: 16, gap: 16 }}>
<View style={{ gap: 8 }}>
<Button title="Check for updates" onPress={handleSync} />
<Text>{`Result: ${syncResult}`}</Text>
<Text>{`Progress: ${progress > 0 ? `${progress}%` : ''}`}</Text>
</View>

<View style={{ gap: 8 }}>
<Button
title="Clear updates"
onPress={() => {
CodePush.clearUpdates();
setSyncResult('');
setProgress(0);
}}
/>
<Button title="Restart app" onPress={() => CodePush.restartApp()} />
<Button title="Get update metadata" onPress={handleMetadata} />
<Text>{runningMetadata === '' ? 'METADATA_IDLE' : runningMetadata === 'null' ? 'METADATA_NULL' : `METADATA_V${JSON.parse(runningMetadata).label}`}</Text>
<MetadataBlock label="Running" value={runningMetadata} />
<MetadataBlock label="Pending" value={pendingMetadata} />
<MetadataBlock label="Latest" value={latestMetadata} />
</View>
</ScrollView>
</View>
);
}

function MetadataBlock({
label,
value,
}: {
label: string;
value: string | null | undefined;
}) {
return (
<View style={{ gap: 4 }}>
<Text style={{ fontWeight: '600' }}>{label}</Text>
<TextInput
value={String(value)}
multiline
style={{ borderWidth: 1, borderRadius: 4, padding: 8, minHeight: 60, color: 'black' }}
/>
</View>
);
}

const CODEPUSH_HOST = 'PLACEHOLDER';
const IDENTIFIER = 'RN0840';

async function releaseHistoryFetcher(
updateRequest: UpdateCheckRequest,
): Promise<ReleaseHistoryInterface> {
const jsonFileName = `${updateRequest.app_version}.json`;
const releaseHistoryUrl = `${CODEPUSH_HOST}/histories/${getPlatform()}/${IDENTIFIER}/${jsonFileName}`;

try {
const { data } = await axios.get<ReleaseHistoryInterface>(releaseHistoryUrl, {
headers: {
Accept: 'application/json',
'Cache-Control': 'no-cache',
},
});
return data;
} catch (error) {
console.error(error);
throw error;
}
}

function WithSafeAreaProvider() {
return (
<SafeAreaProvider>
<StatusBar barStyle="dark-content" />
<App />
</SafeAreaProvider>
);
}

export default CodePush({
checkFrequency: CodePush.CheckFrequency.MANUAL,
releaseHistoryFetcher,
onUpdateSuccess: label => {
console.log('Update success', label);
},
onUpdateRollback: label => {
console.log('Update rolled back', label);
},
onSyncError: (label, error) => {
console.error(error);
console.log('Sync error', label);
},
onDownloadStart: label => {
console.log('Download start', label);
},
onDownloadSuccess: label => {
console.log('Download success', label);
},
})(WithSafeAreaProvider);

function getPlatform() {
switch (Platform.OS) {
case 'ios':
return 'ios';
case 'android':
return 'android';
default:
throw new Error('Unsupported platform');
}
}

function findKeyByValue(
object: Record<string, unknown>,
value: unknown,
) {
return Object.keys(object).find(key => object[key] === value);
}
16 changes: 16 additions & 0 deletions Examples/RN0840/Gemfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
source 'https://rubygems.org'

# You may use http://rbenv.org/ or https://rvm.io/ to install and use this version
ruby ">= 2.6.10"

# Exclude problematic versions of cocoapods and activesupport that causes build failures.
gem 'cocoapods', '>= 1.13', '!= 1.15.0', '!= 1.15.1'
gem 'activesupport', '>= 6.1.7.5', '!= 7.1.0'
gem 'xcodeproj', '< 1.26.0'
gem 'concurrent-ruby', '< 1.3.4'

# Ruby 3.4.0 has removed some libraries from the standard library.
gem 'bigdecimal'
gem 'logger'
gem 'benchmark'
gem 'mutex_m'
97 changes: 97 additions & 0 deletions Examples/RN0840/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
This is a new [**React Native**](https://reactnative.dev) project, bootstrapped using [`@react-native-community/cli`](https://github.com/react-native-community/cli).

# Getting Started

> **Note**: Make sure you have completed the [Set Up Your Environment](https://reactnative.dev/docs/set-up-your-environment) guide before proceeding.
## Step 1: Start Metro

First, you will need to run **Metro**, the JavaScript build tool for React Native.

To start the Metro dev server, run the following command from the root of your React Native project:

```sh
# Using npm
npm start

# OR using Yarn
yarn start
```

## Step 2: Build and run your app

With Metro running, open a new terminal window/pane from the root of your React Native project, and use one of the following commands to build and run your Android or iOS app:

### Android

```sh
# Using npm
npm run android

# OR using Yarn
yarn android
```

### iOS

For iOS, remember to install CocoaPods dependencies (this only needs to be run on first clone or after updating native deps).

The first time you create a new project, run the Ruby bundler to install CocoaPods itself:

```sh
bundle install
```

Then, and every time you update your native dependencies, run:

```sh
bundle exec pod install
```

For more information, please visit [CocoaPods Getting Started guide](https://guides.cocoapods.org/using/getting-started.html).

```sh
# Using npm
npm run ios

# OR using Yarn
yarn ios
```

If everything is set up correctly, you should see your new app running in the Android Emulator, iOS Simulator, or your connected device.

This is one way to run your app — you can also build it directly from Android Studio or Xcode.

## Step 3: Modify your app

Now that you have successfully run the app, let's make changes!

Open `App.tsx` in your text editor of choice and make some changes. When you save, your app will automatically update and reflect these changes — this is powered by [Fast Refresh](https://reactnative.dev/docs/fast-refresh).

When you want to forcefully reload, for example to reset the state of your app, you can perform a full reload:

- **Android**: Press the <kbd>R</kbd> key twice or select **"Reload"** from the **Dev Menu**, accessed via <kbd>Ctrl</kbd> + <kbd>M</kbd> (Windows/Linux) or <kbd>Cmd ⌘</kbd> + <kbd>M</kbd> (macOS).
- **iOS**: Press <kbd>R</kbd> in iOS Simulator.

## Congratulations! :tada:

You've successfully run and modified your React Native App. :partying_face:

### Now what?

- If you want to add this new React Native code to an existing application, check out the [Integration guide](https://reactnative.dev/docs/integration-with-existing-apps).
- If you're curious to learn more about React Native, check out the [docs](https://reactnative.dev/docs/getting-started).

# Troubleshooting

If you're having issues getting the above steps to work, see the [Troubleshooting](https://reactnative.dev/docs/troubleshooting) page.

# Learn More

To learn more about React Native, take a look at the following resources:

- [React Native Website](https://reactnative.dev) - learn more about React Native.
- [Getting Started](https://reactnative.dev/docs/environment-setup) - an **overview** of React Native and how setup your environment.
- [Learn the Basics](https://reactnative.dev/docs/getting-started) - a **guided tour** of the React Native **basics**.
- [Blog](https://reactnative.dev/blog) - read the latest official React Native **Blog** posts.
- [`@facebook/react-native`](https://github.com/facebook/react-native) - the Open Source; GitHub **repository** for React Native.
Loading