├── .editorconfig
├── .github
├── ISSUE_TEMPLATE
│ └── bug_report.md
└── workflows
│ └── workflow.yml
├── .gitignore
├── .netlify
└── state.json
├── .nojekyll
├── .nvmrc
├── .prettierrc
├── .travis.yml
├── .vscode
└── launch.json
├── CHANGELOG.md
├── README.md
├── _config.yml
├── babel.config.js
├── docs
├── assets
│ ├── css
│ │ └── main.css
│ ├── images
│ │ ├── icons.png
│ │ ├── icons@2x.png
│ │ ├── widgets.png
│ │ └── widgets@2x.png
│ └── js
│ │ ├── main.js
│ │ └── search.json
├── globals.html
├── index.html
├── interfaces
│ └── _core_usepresencechannel_.usepresencechannelvalue.html
└── modules
│ ├── _core_pusherprovider_.html
│ ├── _core_usechannel_.html
│ ├── _core_useclienttrigger_.html
│ ├── _core_useevent_.html
│ ├── _core_usepresencechannel_.html
│ ├── _core_usepusher_.html
│ ├── _core_usetrigger_.html
│ ├── _native_pusherprovider_.html
│ ├── _testutils_.html
│ └── _web_pusherprovider_.html
├── examples
├── native-use-pusher-example
│ ├── .buckconfig
│ ├── .gitattributes
│ ├── .gitignore
│ ├── App.js
│ ├── PusherExample.js
│ ├── __tests__
│ │ └── App.js
│ ├── android
│ │ ├── app
│ │ │ ├── BUCK
│ │ │ ├── build.gradle
│ │ │ ├── build_defs.bzl
│ │ │ ├── proguard-rules.pro
│ │ │ └── src
│ │ │ │ ├── debug
│ │ │ │ ├── AndroidManifest.xml
│ │ │ │ └── java
│ │ │ │ │ └── com
│ │ │ │ │ └── nativeusepusherexample
│ │ │ │ │ └── ReactNativeFlipper.java
│ │ │ │ └── main
│ │ │ │ ├── AndroidManifest.xml
│ │ │ │ ├── java
│ │ │ │ └── com
│ │ │ │ │ └── nativeusepusherexample
│ │ │ │ │ ├── MainActivity.java
│ │ │ │ │ ├── MainApplication.java
│ │ │ │ │ └── generated
│ │ │ │ │ └── BasePackageList.java
│ │ │ │ └── res
│ │ │ │ ├── drawable
│ │ │ │ ├── splashscreen.xml
│ │ │ │ └── splashscreen_image.png
│ │ │ │ ├── mipmap-hdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ │ ├── mipmap-mdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ │ ├── mipmap-xhdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ │ ├── mipmap-xxhdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ │ ├── mipmap-xxxhdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ │ └── values
│ │ │ │ ├── colors.xml
│ │ │ │ ├── strings.xml
│ │ │ │ └── styles.xml
│ │ ├── build.gradle
│ │ ├── gradle.properties
│ │ ├── gradle
│ │ │ └── wrapper
│ │ │ │ ├── gradle-wrapper.jar
│ │ │ │ └── gradle-wrapper.properties
│ │ ├── gradlew
│ │ ├── gradlew.bat
│ │ └── settings.gradle
│ ├── app.json
│ ├── babel.config.js
│ ├── index.js
│ ├── ios
│ │ ├── Podfile
│ │ ├── Podfile.lock
│ │ ├── nativeusepusherexample.xcodeproj
│ │ │ ├── project.pbxproj
│ │ │ └── xcshareddata
│ │ │ │ └── xcschemes
│ │ │ │ └── nativeusepusherexample.xcscheme
│ │ ├── nativeusepusherexample.xcworkspace
│ │ │ └── contents.xcworkspacedata
│ │ └── nativeusepusherexample
│ │ │ ├── AppDelegate.h
│ │ │ ├── AppDelegate.m
│ │ │ ├── Base.lproj
│ │ │ └── LaunchScreen.xib
│ │ │ ├── Images.xcassets
│ │ │ ├── AppIcon.appiconset
│ │ │ │ └── Contents.json
│ │ │ ├── Contents.json
│ │ │ ├── SplashScreen.imageset
│ │ │ │ ├── Contents.json
│ │ │ │ └── splashscreen.png
│ │ │ └── SplashScreenBackground.imageset
│ │ │ │ ├── Contents.json
│ │ │ │ └── background.png
│ │ │ ├── Info.plist
│ │ │ ├── SplashScreen.storyboard
│ │ │ ├── Supporting
│ │ │ └── Expo.plist
│ │ │ └── main.m
│ ├── metro.config.js
│ ├── package.json
│ └── use-pusher
│ │ └── native
│ │ ├── index.js
│ │ └── index.js.map
└── web
│ ├── .eslintignore
│ ├── .gitignore
│ ├── README.md
│ ├── package.json
│ ├── public
│ ├── favicon.ico
│ ├── index.html
│ ├── logo192.png
│ ├── logo512.png
│ ├── manifest.json
│ └── robots.txt
│ ├── src
│ ├── App.css
│ ├── App.js
│ ├── index.css
│ ├── index.js
│ ├── logo.svg
│ ├── serviceWorker.js
│ └── setupTests.js
│ └── yarn.lock
├── jest.config.js
├── jest.rn.config.js
├── package.json
├── rn-cli.config.js
├── rollup.config.js
├── setupTests.js
├── setupTests.rn.js
├── src
├── __tests__
│ ├── PusherProvider.test.tsx
│ ├── useChannel.tsx
│ ├── useClientTrigger.tsx
│ ├── useEvent.tsx
│ ├── usePresenceChannel.tsx
│ ├── usePusher.test.tsx
│ └── useTrigger.tsx
├── core
│ ├── ChannelsProvider.tsx
│ ├── PusherProvider.tsx
│ ├── types.d.ts
│ ├── useChannel.ts
│ ├── useChannels.tsx
│ ├── useClientTrigger.ts
│ ├── useEvent.ts
│ ├── usePresenceChannel.ts
│ ├── usePusher.ts
│ └── useTrigger.ts
├── native
│ ├── PusherProvider.tsx
│ └── index.ts
├── react-app-env.d.ts
├── setupTests.js
├── testUtils.tsx
└── web
│ ├── PusherProvider.tsx
│ └── index.ts
├── tsconfig.json
├── tsconfig.rn.json
├── tsconfig.test.json
├── typedoc.js
└── yarn.lock
/.editorconfig:
--------------------------------------------------------------------------------
1 | root = true
2 |
3 | [*]
4 | charset = utf-8
5 | indent_style = space
6 | indent_size = 2
7 | end_of_line = lf
8 | insert_final_newline = true
9 | trim_trailing_whitespace = true
10 | quote_type = double
11 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/bug_report.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Bug report
3 | about: Create a report to help us improve
4 | title: ''
5 | labels: ''
6 | assignees: ''
7 |
8 | ---
9 |
10 | **Describe the bug**
11 | A clear and concise description of what the bug is.
12 |
13 | **To Reproduce**
14 | ### Please provide a codesandbox of your issue or I will not be able to diagnose and fix it.
15 |
--------------------------------------------------------------------------------
/.github/workflows/workflow.yml:
--------------------------------------------------------------------------------
1 | name: "🚀 CI Workflow"
2 |
3 | on:
4 | push:
5 | branches:
6 | - master
7 | workflow_call: {}
8 | pull_request: {}
9 |
10 | jobs:
11 | test:
12 | name: 🃏 Test
13 | runs-on: ubuntu-latest
14 | steps:
15 | - name: 🛑 Cancel Previous Runs
16 | uses: styfle/cancel-workflow-action@0.9.1
17 |
18 | - name: ⬇️ Checkout repo
19 | uses: actions/checkout@v3
20 |
21 | - name: ⎔ Setup node
22 | uses: actions/setup-node@v3
23 | with:
24 | cache: "yarn"
25 | node-version: 16
26 |
27 | - name: 📥 Download deps
28 | run: yarn install
29 |
30 | - name: 🃏 Test
31 | run: yarn test
32 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 |
2 | # See https://help.github.com/ignore-files/ for more about ignoring files.
3 |
4 | # dependencies
5 | node_modules
6 |
7 | # builds
8 | coverage
9 | build
10 | dist
11 | /react-native
12 | .rpt2_cache
13 |
14 | # misc
15 | .DS_Store
16 | .env
17 | .env.local
18 | .env.development.local
19 | .env.test.local
20 | .env.production.local
21 |
22 | # jest artifacts, i.e. cache
23 | .jest
24 |
25 | npm-debug.log*
26 | yarn-debug.log*
27 | yarn-error.log*
28 |
29 | # Local Netlify folder
30 | .netlify
--------------------------------------------------------------------------------
/.netlify/state.json:
--------------------------------------------------------------------------------
1 | {
2 | "siteId": "aa919ed6-b843-411b-b6f7-828ea279b040"
3 | }
--------------------------------------------------------------------------------
/.nojekyll:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mayteio/use-pusher/f9f2389db01d3c102f31b43045325967d96ba342/.nojekyll
--------------------------------------------------------------------------------
/.nvmrc:
--------------------------------------------------------------------------------
1 | v12
2 |
--------------------------------------------------------------------------------
/.prettierrc:
--------------------------------------------------------------------------------
1 | {
2 | "tabWidth": 2,
3 | "useTabs": false,
4 | "jsxSingleQuote": false,
5 | "singleQuote": false,
6 | "arrowParens": "always",
7 | "bracketSpacing": true
8 | }
9 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: node_js
2 | node_js:
3 | - 9
4 | - 8
5 |
--------------------------------------------------------------------------------
/.vscode/launch.json:
--------------------------------------------------------------------------------
1 | {
2 | "version": "0.2.0",
3 | "configurations": [
4 | {
5 | "type": "node",
6 | "request": "launch",
7 | "name": "Jest All",
8 | "program": "${workspaceFolder}/node_modules/.bin/jest",
9 | "args": ["--runInBand"],
10 | "console": "integratedTerminal",
11 | "internalConsoleOptions": "neverOpen",
12 | "disableOptimisticBPs": true,
13 | "windows": {
14 | "program": "${workspaceFolder}/node_modules/jest/bin/jest"
15 | }
16 | },
17 | {
18 | "type": "node",
19 | "request": "launch",
20 | "name": "Jest Current File",
21 | "program": "${workspaceFolder}/node_modules/.bin/jest",
22 | "args": ["${fileBasenameNoExtension}", "--config", "jest.config.js"],
23 | "console": "integratedTerminal",
24 | "internalConsoleOptions": "neverOpen",
25 | "disableOptimisticBPs": true,
26 | "windows": {
27 | "program": "${workspaceFolder}/node_modules/jest/bin/jest"
28 | }
29 | }
30 | ]
31 | }
32 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # `@harelpls/use-pusher`
2 |
3 | > Easy as [React hooks](https://reactjs.org/docs/hooks-intro.html) that integrate with the [`pusher-js`](https://github.com/pusher/pusher-js) library.
4 |
5 | [](https://www.npmjs.com/package/@harelpls/use-pusher) 
6 |
7 |
8 |
9 |
10 | - [Install](#install)
11 | - [Hooks](#hooks)
12 | - [Usage](#usage)
13 | - [`useChannel`](#usechannel)
14 | - [`usePresenceChannel`](#usepresencechannel)
15 | - [`useEvent`](#useevent)
16 | - [`useTrigger`](#usetrigger)
17 | - [`usePusher`](#usepusher)
18 | - [Trigger Server](#trigger-server)
19 | - [`useClientTrigger`](#useclienttrigger)
20 | - [Typescript](#typescript)
21 | - [Testing](#testing)
22 | - [React Native](#react-native)
23 | - [Contributing](#contributing)
24 | - [License](#license)
25 |
26 |
27 |
28 | ## [API Reference/Docs](https://use-pusher-docs.netlify.com/)
29 |
30 | ## Install
31 |
32 | ```bash
33 | yarn add @harelpls/use-pusher
34 | ```
35 |
36 | ## Hooks
37 |
38 | - [`useChannel`](#usechannel)
39 | - [`usePresenceChannel`](#usepresencechannel)
40 | - [`useEvent`](#useevent)
41 | - [`useTrigger`](#usetrigger)
42 | - [`useClientTrigger`](#useclienttrigger)
43 | - [`usePusher`](#usepusher)
44 |
45 | ## Usage
46 |
47 | You must wrap your app with a `PusherProvider` and pass it config props for [`pusher-js`](https://github.com/pusher/pusher-js) initialisation.
48 |
49 | ```typescript
50 | import React from "react";
51 | import { PusherProvider } from "@harelpls/use-pusher";
52 |
53 | const config = {
54 | // required config props
55 | clientKey: "client-key",
56 | cluster: "ap4",
57 |
58 | // optional if you'd like to trigger events. BYO endpoint.
59 | // see "Trigger Server" below for more info
60 | triggerEndpoint: "/pusher/trigger",
61 |
62 | // required for private/presence channels
63 | // also sends auth headers to trigger endpoint
64 | authEndpoint: "/pusher/auth",
65 | auth: {
66 | headers: { Authorization: "Bearer token" },
67 | },
68 | };
69 |
70 | // Wrap app in provider
71 | const App = () => {
72 |
73 |
74 | ;
75 | };
76 | ```
77 |
78 | ## `useChannel`
79 |
80 | Use this hook to subscribe to a channel.
81 |
82 | ```typescript
83 | // returns channel instance.
84 | const channel = useChannel("channel-name");
85 | ```
86 |
87 | ## `usePresenceChannel`
88 |
89 | Augments a regular channel with member functionality.
90 |
91 | ```typescript
92 | const Example = () => {
93 | const { members, myID } = usePresenceChannel('presence-awesome');
94 |
95 | return (
96 |
trigger("client-hello-world", {})}
15 | />
16 | >
17 | );
18 | };
19 |
--------------------------------------------------------------------------------
/examples/native-use-pusher-example/__tests__/App.js:
--------------------------------------------------------------------------------
1 | import 'react-native';
2 | import React from 'react';
3 | import App from '../App';
4 |
5 | // Note: test renderer must be required after react-native.
6 | import renderer from 'react-test-renderer';
7 |
8 | it('renders correctly', () => {
9 | renderer.create( );
10 | });
11 |
--------------------------------------------------------------------------------
/examples/native-use-pusher-example/android/app/BUCK:
--------------------------------------------------------------------------------
1 | # To learn about Buck see [Docs](https://buckbuild.com/).
2 | # To run your application with Buck:
3 | # - install Buck
4 | # - `npm start` - to start the packager
5 | # - `cd android`
6 | # - `keytool -genkey -v -keystore keystores/debug.keystore -storepass android -alias androiddebugkey -keypass android -dname "CN=Android Debug,O=Android,C=US"`
7 | # - `./gradlew :app:copyDownloadableDepsToLibs` - make all Gradle compile dependencies available to Buck
8 | # - `buck install -r android/app` - compile, install and run application
9 | #
10 |
11 | load(":build_defs.bzl", "create_aar_targets", "create_jar_targets")
12 |
13 | lib_deps = []
14 |
15 | create_aar_targets(glob(["libs/*.aar"]))
16 |
17 | create_jar_targets(glob(["libs/*.jar"]))
18 |
19 | android_library(
20 | name = "all-libs",
21 | exported_deps = lib_deps,
22 | )
23 |
24 | android_library(
25 | name = "app-code",
26 | srcs = glob([
27 | "src/main/java/**/*.java",
28 | ]),
29 | deps = [
30 | ":all-libs",
31 | ":build_config",
32 | ":res",
33 | ],
34 | )
35 |
36 | android_build_config(
37 | name = "build_config",
38 | package = "com.nativeusepusherexample",
39 | )
40 |
41 | android_resource(
42 | name = "res",
43 | package = "com.nativeusepusherexample",
44 | res = "src/main/res",
45 | )
46 |
47 | android_binary(
48 | name = "app",
49 | keystore = "//android/keystores:debug",
50 | manifest = "src/main/AndroidManifest.xml",
51 | package_type = "debug",
52 | deps = [
53 | ":app-code",
54 | ],
55 | )
56 |
--------------------------------------------------------------------------------
/examples/native-use-pusher-example/android/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: "com.android.application"
2 |
3 | import com.android.build.OutputFile
4 |
5 | /**
6 | * The react.gradle file registers a task for each build variant (e.g. bundleDebugJsAndAssets
7 | * and bundleReleaseJsAndAssets).
8 | * These basically call `react-native bundle` with the correct arguments during the Android build
9 | * cycle. By default, bundleDebugJsAndAssets is skipped, as in debug/dev mode we prefer to load the
10 | * bundle directly from the development server. Below you can see all the possible configurations
11 | * and their defaults. If you decide to add a configuration block, make sure to add it before the
12 | * `apply from: "../../node_modules/react-native/react.gradle"` line.
13 | *
14 | * project.ext.react = [
15 | * // the name of the generated asset file containing your JS bundle
16 | * bundleAssetName: "index.android.bundle",
17 | *
18 | * // the entry file for bundle generation. If none specified and
19 | * // "index.android.js" exists, it will be used. Otherwise "index.js" is
20 | * // default. Can be overridden with ENTRY_FILE environment variable.
21 | * entryFile: "index.android.js",
22 | *
23 | * // https://facebook.github.io/react-native/docs/performance#enable-the-ram-format
24 | * bundleCommand: "ram-bundle",
25 | *
26 | * // whether to bundle JS and assets in debug mode
27 | * bundleInDebug: false,
28 | *
29 | * // whether to bundle JS and assets in release mode
30 | * bundleInRelease: true,
31 | *
32 | * // whether to bundle JS and assets in another build variant (if configured).
33 | * // See http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Build-Variants
34 | * // The configuration property can be in the following formats
35 | * // 'bundleIn${productFlavor}${buildType}'
36 | * // 'bundleIn${buildType}'
37 | * // bundleInFreeDebug: true,
38 | * // bundleInPaidRelease: true,
39 | * // bundleInBeta: true,
40 | *
41 | * // whether to disable dev mode in custom build variants (by default only disabled in release)
42 | * // for example: to disable dev mode in the staging build type (if configured)
43 | * devDisabledInStaging: true,
44 | * // The configuration property can be in the following formats
45 | * // 'devDisabledIn${productFlavor}${buildType}'
46 | * // 'devDisabledIn${buildType}'
47 | *
48 | * // the root of your project, i.e. where "package.json" lives
49 | * root: "../../",
50 | *
51 | * // where to put the JS bundle asset in debug mode
52 | * jsBundleDirDebug: "$buildDir/intermediates/assets/debug",
53 | *
54 | * // where to put the JS bundle asset in release mode
55 | * jsBundleDirRelease: "$buildDir/intermediates/assets/release",
56 | *
57 | * // where to put drawable resources / React Native assets, e.g. the ones you use via
58 | * // require('./image.png')), in debug mode
59 | * resourcesDirDebug: "$buildDir/intermediates/res/merged/debug",
60 | *
61 | * // where to put drawable resources / React Native assets, e.g. the ones you use via
62 | * // require('./image.png')), in release mode
63 | * resourcesDirRelease: "$buildDir/intermediates/res/merged/release",
64 | *
65 | * // by default the gradle tasks are skipped if none of the JS files or assets change; this means
66 | * // that we don't look at files in android/ or ios/ to determine whether the tasks are up to
67 | * // date; if you have any other folders that you want to ignore for performance reasons (gradle
68 | * // indexes the entire tree), add them here. Alternatively, if you have JS files in android/
69 | * // for example, you might want to remove it from here.
70 | * inputExcludes: ["android/**", "ios/**"],
71 | *
72 | * // override which node gets called and with what additional arguments
73 | * nodeExecutableAndArgs: ["node"],
74 | *
75 | * // supply additional arguments to the packager
76 | * extraPackagerArgs: []
77 | * ]
78 | */
79 |
80 | project.ext.react = [
81 | enableHermes: false
82 | ]
83 |
84 | apply from: '../../node_modules/react-native-unimodules/gradle.groovy'
85 | apply from: "../../node_modules/react-native/react.gradle"
86 | apply from: "../../node_modules/expo-updates/scripts/create-manifest-android.gradle"
87 |
88 | /**
89 | * Set this to true to create two separate APKs instead of one:
90 | * - An APK that only works on ARM devices
91 | * - An APK that only works on x86 devices
92 | * The advantage is the size of the APK is reduced by about 4MB.
93 | * Upload all the APKs to the Play Store and people will download
94 | * the correct one based on the CPU architecture of their device.
95 | */
96 | def enableSeparateBuildPerCPUArchitecture = false
97 |
98 | /**
99 | * Run Proguard to shrink the Java bytecode in release builds.
100 | */
101 | def enableProguardInReleaseBuilds = false
102 |
103 | /**
104 | * The preferred build flavor of JavaScriptCore.
105 | *
106 | * For example, to use the international variant, you can use:
107 | * `def jscFlavor = 'org.webkit:android-jsc-intl:+'`
108 | *
109 | * The international variant includes ICU i18n library and necessary data
110 | * allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that
111 | * give correct results when using with locales other than en-US. Note that
112 | * this variant is about 6MiB larger per architecture than default.
113 | */
114 | def jscFlavor = 'org.webkit:android-jsc:+'
115 |
116 | /**
117 | * Whether to enable the Hermes VM.
118 | *
119 | * This should be set on project.ext.react and mirrored here. If it is not set
120 | * on project.ext.react, JavaScript will not be compiled to Hermes Bytecode
121 | * and the benefits of using Hermes will therefore be sharply reduced.
122 | */
123 | def enableHermes = project.ext.react.get("enableHermes", false);
124 |
125 | android {
126 | compileSdkVersion rootProject.ext.compileSdkVersion
127 |
128 | compileOptions {
129 | sourceCompatibility JavaVersion.VERSION_1_8
130 | targetCompatibility JavaVersion.VERSION_1_8
131 | }
132 |
133 | defaultConfig {
134 | applicationId "com.nativeusepusherexample"
135 | minSdkVersion rootProject.ext.minSdkVersion
136 | targetSdkVersion rootProject.ext.targetSdkVersion
137 | versionCode 1
138 | versionName "1.0"
139 | }
140 | splits {
141 | abi {
142 | reset()
143 | enable enableSeparateBuildPerCPUArchitecture
144 | universalApk false // If true, also generate a universal APK
145 | include "armeabi-v7a", "x86", "arm64-v8a", "x86_64"
146 | }
147 | }
148 | signingConfigs {
149 | debug {
150 | storeFile file('debug.keystore')
151 | storePassword 'android'
152 | keyAlias 'androiddebugkey'
153 | keyPassword 'android'
154 | }
155 | }
156 | buildTypes {
157 | debug {
158 | signingConfig signingConfigs.debug
159 | }
160 | release {
161 | // Caution! In production, you need to generate your own keystore file.
162 | // see https://facebook.github.io/react-native/docs/signed-apk-android.
163 | signingConfig signingConfigs.debug
164 | minifyEnabled enableProguardInReleaseBuilds
165 | proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
166 | }
167 | }
168 |
169 | packagingOptions {
170 | pickFirst "lib/armeabi-v7a/libc++_shared.so"
171 | pickFirst "lib/arm64-v8a/libc++_shared.so"
172 | pickFirst "lib/x86/libc++_shared.so"
173 | pickFirst "lib/x86_64/libc++_shared.so"
174 | }
175 |
176 | // applicationVariants are e.g. debug, release
177 | applicationVariants.all { variant ->
178 | variant.outputs.each { output ->
179 | // For each separate APK per architecture, set a unique version code as described here:
180 | // https://developer.android.com/studio/build/configure-apk-splits.html
181 | def versionCodes = ["armeabi-v7a": 1, "x86": 2, "arm64-v8a": 3, "x86_64": 4]
182 | def abi = output.getFilter(OutputFile.ABI)
183 | if (abi != null) { // null for the universal-debug, universal-release variants
184 | output.versionCodeOverride =
185 | versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
186 | }
187 |
188 | }
189 | }
190 | }
191 |
192 | dependencies {
193 | implementation fileTree(dir: "libs", include: ["*.jar"])
194 | //noinspection GradleDynamicVersion
195 | implementation "com.facebook.react:react-native:+" // From node_modules
196 | implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.0.0"
197 | debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}") {
198 | exclude group:'com.facebook.fbjni'
199 | }
200 | debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") {
201 | exclude group:'com.facebook.flipper'
202 | }
203 | debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}") {
204 | exclude group:'com.facebook.flipper'
205 | }
206 | addUnimodulesDependencies()
207 |
208 | if (enableHermes) {
209 | def hermesPath = "../../node_modules/hermes-engine/android/";
210 | debugImplementation files(hermesPath + "hermes-debug.aar")
211 | releaseImplementation files(hermesPath + "hermes-release.aar")
212 | } else {
213 | implementation jscFlavor
214 | }
215 | }
216 |
217 | // Run this once to be able to run the application with BUCK
218 | // puts all compile dependencies into folder libs for BUCK to use
219 | task copyDownloadableDepsToLibs(type: Copy) {
220 | from configurations.compile
221 | into 'libs'
222 | }
223 |
224 | apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)
225 |
--------------------------------------------------------------------------------
/examples/native-use-pusher-example/android/app/build_defs.bzl:
--------------------------------------------------------------------------------
1 | """Helper definitions to glob .aar and .jar targets"""
2 |
3 | def create_aar_targets(aarfiles):
4 | for aarfile in aarfiles:
5 | name = "aars__" + aarfile[aarfile.rindex("/") + 1:aarfile.rindex(".aar")]
6 | lib_deps.append(":" + name)
7 | android_prebuilt_aar(
8 | name = name,
9 | aar = aarfile,
10 | )
11 |
12 | def create_jar_targets(jarfiles):
13 | for jarfile in jarfiles:
14 | name = "jars__" + jarfile[jarfile.rindex("/") + 1:jarfile.rindex(".jar")]
15 | lib_deps.append(":" + name)
16 | prebuilt_jar(
17 | name = name,
18 | binary_jar = jarfile,
19 | )
20 |
--------------------------------------------------------------------------------
/examples/native-use-pusher-example/android/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /usr/local/Cellar/android-sdk/24.3.3/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
--------------------------------------------------------------------------------
/examples/native-use-pusher-example/android/app/src/debug/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/examples/native-use-pusher-example/android/app/src/debug/java/com/nativeusepusherexample/ReactNativeFlipper.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (c) Facebook, Inc. and its affiliates.
3 | *
4 | * This source code is licensed under the MIT license found in the LICENSE file in the root
5 | * directory of this source tree.
6 | */
7 | package com.nativeusepusherexample;
8 |
9 | import android.content.Context;
10 | import com.facebook.flipper.android.AndroidFlipperClient;
11 | import com.facebook.flipper.android.utils.FlipperUtils;
12 | import com.facebook.flipper.core.FlipperClient;
13 | import com.facebook.flipper.plugins.crashreporter.CrashReporterPlugin;
14 | import com.facebook.flipper.plugins.databases.DatabasesFlipperPlugin;
15 | import com.facebook.flipper.plugins.fresco.FrescoFlipperPlugin;
16 | import com.facebook.flipper.plugins.inspector.DescriptorMapping;
17 | import com.facebook.flipper.plugins.inspector.InspectorFlipperPlugin;
18 | import com.facebook.flipper.plugins.network.FlipperOkhttpInterceptor;
19 | import com.facebook.flipper.plugins.network.NetworkFlipperPlugin;
20 | import com.facebook.flipper.plugins.react.ReactFlipperPlugin;
21 | import com.facebook.flipper.plugins.sharedpreferences.SharedPreferencesFlipperPlugin;
22 | import com.facebook.react.ReactInstanceManager;
23 | import com.facebook.react.bridge.ReactContext;
24 | import com.facebook.react.modules.network.NetworkingModule;
25 | import okhttp3.OkHttpClient;
26 |
27 | public class ReactNativeFlipper {
28 | public static void initializeFlipper(Context context, ReactInstanceManager reactInstanceManager) {
29 | if (FlipperUtils.shouldEnableFlipper(context)) {
30 | final FlipperClient client = AndroidFlipperClient.getInstance(context);
31 | client.addPlugin(new InspectorFlipperPlugin(context, DescriptorMapping.withDefaults()));
32 | client.addPlugin(new ReactFlipperPlugin());
33 | client.addPlugin(new DatabasesFlipperPlugin(context));
34 | client.addPlugin(new SharedPreferencesFlipperPlugin(context));
35 | client.addPlugin(CrashReporterPlugin.getInstance());
36 | NetworkFlipperPlugin networkFlipperPlugin = new NetworkFlipperPlugin();
37 | NetworkingModule.setCustomClientBuilder(
38 | new NetworkingModule.CustomClientBuilder() {
39 | @Override
40 | public void apply(OkHttpClient.Builder builder) {
41 | builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin));
42 | }
43 | });
44 | client.addPlugin(networkFlipperPlugin);
45 | client.start();
46 | // Fresco Plugin needs to ensure that ImagePipelineFactory is initialized
47 | // Hence we run if after all native modules have been initialized
48 | ReactContext reactContext = reactInstanceManager.getCurrentReactContext();
49 | if (reactContext == null) {
50 | reactInstanceManager.addReactInstanceEventListener(
51 | new ReactInstanceManager.ReactInstanceEventListener() {
52 | @Override
53 | public void onReactContextInitialized(ReactContext reactContext) {
54 | reactInstanceManager.removeReactInstanceEventListener(this);
55 | reactContext.runOnNativeModulesQueueThread(
56 | new Runnable() {
57 | @Override
58 | public void run() {
59 | client.addPlugin(new FrescoFlipperPlugin());
60 | }
61 | });
62 | }
63 | });
64 | } else {
65 | client.addPlugin(new FrescoFlipperPlugin());
66 | }
67 | }
68 | }
69 | }
--------------------------------------------------------------------------------
/examples/native-use-pusher-example/android/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
31 |
32 |
33 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
--------------------------------------------------------------------------------
/examples/native-use-pusher-example/android/app/src/main/java/com/nativeusepusherexample/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.nativeusepusherexample;
2 |
3 | import android.os.Bundle;
4 |
5 | import com.facebook.react.ReactActivity;
6 | import com.facebook.react.ReactActivityDelegate;
7 | import com.facebook.react.ReactRootView;
8 | import com.swmansion.gesturehandler.react.RNGestureHandlerEnabledRootView;
9 |
10 | import expo.modules.splashscreen.SplashScreen;
11 | import expo.modules.splashscreen.SplashScreenImageResizeMode;
12 |
13 | public class MainActivity extends ReactActivity {
14 | @Override
15 | protected void onCreate(Bundle savedInstanceState) {
16 | super.onCreate(savedInstanceState);
17 | // SplashScreen.show(...) has to be called after super.onCreate(...)
18 | // Below line is handled by '@expo/configure-splash-screen' command and it's discouraged to modify it manually
19 | SplashScreen.show(this, SplashScreenImageResizeMode.CONTAIN, false);
20 | }
21 |
22 |
23 | /**
24 | * Returns the name of the main component registered from JavaScript.
25 | * This is used to schedule rendering of the component.
26 | */
27 | @Override
28 | protected String getMainComponentName() {
29 | return "main";
30 | }
31 |
32 | @Override
33 | protected ReactActivityDelegate createReactActivityDelegate() {
34 | return new ReactActivityDelegate(this, getMainComponentName()) {
35 | @Override
36 | protected ReactRootView createRootView() {
37 | return new RNGestureHandlerEnabledRootView(MainActivity.this);
38 | }
39 | };
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/examples/native-use-pusher-example/android/app/src/main/java/com/nativeusepusherexample/MainApplication.java:
--------------------------------------------------------------------------------
1 | package com.nativeusepusherexample;
2 |
3 | import android.app.Application;
4 | import android.content.Context;
5 | import android.net.Uri;
6 |
7 | import com.facebook.react.PackageList;
8 | import com.facebook.react.ReactApplication;
9 | import com.reactnativecommunity.netinfo.NetInfoPackage;
10 | import com.facebook.react.ReactInstanceManager;
11 | import com.facebook.react.ReactNativeHost;
12 | import com.facebook.react.ReactPackage;
13 | import com.facebook.react.shell.MainReactPackage;
14 | import com.facebook.soloader.SoLoader;
15 | import com.nativeusepusherexample.generated.BasePackageList;
16 |
17 | import org.unimodules.adapters.react.ReactAdapterPackage;
18 | import org.unimodules.adapters.react.ModuleRegistryAdapter;
19 | import org.unimodules.adapters.react.ReactModuleRegistryProvider;
20 | import org.unimodules.core.interfaces.Package;
21 | import org.unimodules.core.interfaces.SingletonModule;
22 | import expo.modules.constants.ConstantsPackage;
23 | import expo.modules.permissions.PermissionsPackage;
24 | import expo.modules.filesystem.FileSystemPackage;
25 | import expo.modules.updates.UpdatesController;
26 |
27 | import java.lang.reflect.InvocationTargetException;
28 | import java.util.Arrays;
29 | import java.util.List;
30 | import javax.annotation.Nullable;
31 |
32 | public class MainApplication extends Application implements ReactApplication {
33 | private final ReactModuleRegistryProvider mModuleRegistryProvider = new ReactModuleRegistryProvider(
34 | new BasePackageList().getPackageList()
35 | );
36 |
37 | private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
38 | @Override
39 | public boolean getUseDeveloperSupport() {
40 | return BuildConfig.DEBUG;
41 | }
42 |
43 | @Override
44 | protected List getPackages() {
45 | List packages = new PackageList(this).getPackages();
46 | packages.add(new ModuleRegistryAdapter(mModuleRegistryProvider));
47 | return packages;
48 | }
49 |
50 | @Override
51 | protected String getJSMainModuleName() {
52 | return "index";
53 | }
54 |
55 | @Override
56 | protected @Nullable String getJSBundleFile() {
57 | if (BuildConfig.DEBUG) {
58 | return super.getJSBundleFile();
59 | } else {
60 | return UpdatesController.getInstance().getLaunchAssetFile();
61 | }
62 | }
63 |
64 | @Override
65 | protected @Nullable String getBundleAssetName() {
66 | if (BuildConfig.DEBUG) {
67 | return super.getBundleAssetName();
68 | } else {
69 | return UpdatesController.getInstance().getBundleAssetName();
70 | }
71 | }
72 | };
73 |
74 | @Override
75 | public ReactNativeHost getReactNativeHost() {
76 | return mReactNativeHost;
77 | }
78 |
79 | @Override
80 | public void onCreate() {
81 | super.onCreate();
82 | SoLoader.init(this, /* native exopackage */ false);
83 |
84 | if (!BuildConfig.DEBUG) {
85 | UpdatesController.initialize(this);
86 | }
87 |
88 | initializeFlipper(this, getReactNativeHost().getReactInstanceManager());
89 | }
90 |
91 | /**
92 | * Loads Flipper in React Native templates. Call this in the onCreate method with something like
93 | * initializeFlipper(this, getReactNativeHost().getReactInstanceManager());
94 | *
95 | * @param context
96 | * @param reactInstanceManager
97 | */
98 | private static void initializeFlipper(
99 | Context context, ReactInstanceManager reactInstanceManager) {
100 | if (BuildConfig.DEBUG) {
101 | try {
102 | /*
103 | We use reflection here to pick up the class that initializes Flipper,
104 | since Flipper library is not available in release mode
105 | */
106 | Class> aClass = Class.forName("com.rndiffapp.ReactNativeFlipper");
107 | aClass
108 | .getMethod("initializeFlipper", Context.class, ReactInstanceManager.class)
109 | .invoke(null, context, reactInstanceManager);
110 | } catch (ClassNotFoundException e) {
111 | e.printStackTrace();
112 | } catch (NoSuchMethodException e) {
113 | e.printStackTrace();
114 | } catch (IllegalAccessException e) {
115 | e.printStackTrace();
116 | } catch (InvocationTargetException e) {
117 | e.printStackTrace();
118 | }
119 | }
120 | }
121 | }
122 |
--------------------------------------------------------------------------------
/examples/native-use-pusher-example/android/app/src/main/java/com/nativeusepusherexample/generated/BasePackageList.java:
--------------------------------------------------------------------------------
1 | package com.nativeusepusherexample.generated;
2 |
3 | import java.util.Arrays;
4 | import java.util.List;
5 | import org.unimodules.core.interfaces.Package;
6 |
7 | public class BasePackageList {
8 | public List getPackageList() {
9 | return Arrays.asList(
10 | new expo.modules.constants.ConstantsPackage(),
11 | new expo.modules.errorrecovery.ErrorRecoveryPackage(),
12 | new expo.modules.filesystem.FileSystemPackage(),
13 | new expo.modules.font.FontLoaderPackage(),
14 | new expo.modules.imageloader.ImageLoaderPackage(),
15 | new expo.modules.keepawake.KeepAwakePackage(),
16 | new expo.modules.lineargradient.LinearGradientPackage(),
17 | new expo.modules.location.LocationPackage(),
18 | new expo.modules.permissions.PermissionsPackage(),
19 | new expo.modules.splashscreen.SplashScreenPackage(),
20 | new expo.modules.sqlite.SQLitePackage(),
21 | new expo.modules.updates.UpdatesPackage()
22 | );
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/examples/native-use-pusher-example/android/app/src/main/res/drawable/splashscreen.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/examples/native-use-pusher-example/android/app/src/main/res/drawable/splashscreen_image.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mayteio/use-pusher/f9f2389db01d3c102f31b43045325967d96ba342/examples/native-use-pusher-example/android/app/src/main/res/drawable/splashscreen_image.png
--------------------------------------------------------------------------------
/examples/native-use-pusher-example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mayteio/use-pusher/f9f2389db01d3c102f31b43045325967d96ba342/examples/native-use-pusher-example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/examples/native-use-pusher-example/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mayteio/use-pusher/f9f2389db01d3c102f31b43045325967d96ba342/examples/native-use-pusher-example/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/examples/native-use-pusher-example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mayteio/use-pusher/f9f2389db01d3c102f31b43045325967d96ba342/examples/native-use-pusher-example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/examples/native-use-pusher-example/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mayteio/use-pusher/f9f2389db01d3c102f31b43045325967d96ba342/examples/native-use-pusher-example/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/examples/native-use-pusher-example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mayteio/use-pusher/f9f2389db01d3c102f31b43045325967d96ba342/examples/native-use-pusher-example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/examples/native-use-pusher-example/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mayteio/use-pusher/f9f2389db01d3c102f31b43045325967d96ba342/examples/native-use-pusher-example/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/examples/native-use-pusher-example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mayteio/use-pusher/f9f2389db01d3c102f31b43045325967d96ba342/examples/native-use-pusher-example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/examples/native-use-pusher-example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mayteio/use-pusher/f9f2389db01d3c102f31b43045325967d96ba342/examples/native-use-pusher-example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/examples/native-use-pusher-example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mayteio/use-pusher/f9f2389db01d3c102f31b43045325967d96ba342/examples/native-use-pusher-example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/examples/native-use-pusher-example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mayteio/use-pusher/f9f2389db01d3c102f31b43045325967d96ba342/examples/native-use-pusher-example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/examples/native-use-pusher-example/android/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | #FFFFFF
5 |
6 |
--------------------------------------------------------------------------------
/examples/native-use-pusher-example/android/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | native-use-pusher-example
3 |
4 |
--------------------------------------------------------------------------------
/examples/native-use-pusher-example/android/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
7 |
12 |
13 |
--------------------------------------------------------------------------------
/examples/native-use-pusher-example/android/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 |
3 | buildscript {
4 | ext {
5 | buildToolsVersion = "28.0.3"
6 | minSdkVersion = 21
7 | compileSdkVersion = 28
8 | targetSdkVersion = 28
9 | }
10 | repositories {
11 | google()
12 | jcenter()
13 | }
14 | dependencies {
15 | classpath("com.android.tools.build:gradle:3.5.3")
16 |
17 | // NOTE: Do not place your application dependencies here; they belong
18 | // in the individual module build.gradle files
19 | }
20 | }
21 |
22 | allprojects {
23 | repositories {
24 | mavenLocal()
25 | maven {
26 | // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
27 | url("$rootDir/../node_modules/react-native/android")
28 | }
29 | maven {
30 | // Android JSC is installed from npm
31 | url("$rootDir/../node_modules/jsc-android/dist")
32 | }
33 |
34 | google()
35 | jcenter()
36 | maven { url 'https://www.jitpack.io' }
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/examples/native-use-pusher-example/android/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | # Default value: -Xmx10248m -XX:MaxPermSize=256m
13 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
14 |
15 | # When configured, Gradle will run in incubating parallel mode.
16 | # This option should only be used with decoupled projects. More details, visit
17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
18 | # org.gradle.parallel=true
19 |
20 | # AndroidX package structure to make it clearer which packages are bundled with the
21 | # Android operating system, and which are packaged with your app's APK
22 | # https://developer.android.com/topic/libraries/support-library/androidx-rn
23 | android.useAndroidX=true
24 |
25 | # Automatically convert third-party libraries to use AndroidX
26 | android.enableJetifier=true
27 |
28 | # Version of flipper SDK to use with React Native
29 | FLIPPER_VERSION=0.33.1
--------------------------------------------------------------------------------
/examples/native-use-pusher-example/android/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mayteio/use-pusher/f9f2389db01d3c102f31b43045325967d96ba342/examples/native-use-pusher-example/android/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/examples/native-use-pusher-example/android/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionBase=GRADLE_USER_HOME
2 | distributionPath=wrapper/dists
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.0.1-all.zip
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 |
--------------------------------------------------------------------------------
/examples/native-use-pusher-example/android/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | #
4 | # Copyright 2015 the original author or authors.
5 | #
6 | # Licensed under the Apache License, Version 2.0 (the "License");
7 | # you may not use this file except in compliance with the License.
8 | # You may obtain a copy of the License at
9 | #
10 | # https://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 | #
18 |
19 | ##############################################################################
20 | ##
21 | ## Gradle start up script for UN*X
22 | ##
23 | ##############################################################################
24 |
25 | # Attempt to set APP_HOME
26 | # Resolve links: $0 may be a link
27 | PRG="$0"
28 | # Need this for relative symlinks.
29 | while [ -h "$PRG" ] ; do
30 | ls=`ls -ld "$PRG"`
31 | link=`expr "$ls" : '.*-> \(.*\)$'`
32 | if expr "$link" : '/.*' > /dev/null; then
33 | PRG="$link"
34 | else
35 | PRG=`dirname "$PRG"`"/$link"
36 | fi
37 | done
38 | SAVED="`pwd`"
39 | cd "`dirname \"$PRG\"`/" >/dev/null
40 | APP_HOME="`pwd -P`"
41 | cd "$SAVED" >/dev/null
42 |
43 | APP_NAME="Gradle"
44 | APP_BASE_NAME=`basename "$0"`
45 |
46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
48 |
49 | # Use the maximum available, or set MAX_FD != -1 to use that value.
50 | MAX_FD="maximum"
51 |
52 | warn () {
53 | echo "$*"
54 | }
55 |
56 | die () {
57 | echo
58 | echo "$*"
59 | echo
60 | exit 1
61 | }
62 |
63 | # OS specific support (must be 'true' or 'false').
64 | cygwin=false
65 | msys=false
66 | darwin=false
67 | nonstop=false
68 | case "`uname`" in
69 | CYGWIN* )
70 | cygwin=true
71 | ;;
72 | Darwin* )
73 | darwin=true
74 | ;;
75 | MINGW* )
76 | msys=true
77 | ;;
78 | NONSTOP* )
79 | nonstop=true
80 | ;;
81 | esac
82 |
83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
84 |
85 | # Determine the Java command to use to start the JVM.
86 | if [ -n "$JAVA_HOME" ] ; then
87 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
88 | # IBM's JDK on AIX uses strange locations for the executables
89 | JAVACMD="$JAVA_HOME/jre/sh/java"
90 | else
91 | JAVACMD="$JAVA_HOME/bin/java"
92 | fi
93 | if [ ! -x "$JAVACMD" ] ; then
94 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
95 |
96 | Please set the JAVA_HOME variable in your environment to match the
97 | location of your Java installation."
98 | fi
99 | else
100 | JAVACMD="java"
101 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
102 |
103 | Please set the JAVA_HOME variable in your environment to match the
104 | location of your Java installation."
105 | fi
106 |
107 | # Increase the maximum file descriptors if we can.
108 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
109 | MAX_FD_LIMIT=`ulimit -H -n`
110 | if [ $? -eq 0 ] ; then
111 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
112 | MAX_FD="$MAX_FD_LIMIT"
113 | fi
114 | ulimit -n $MAX_FD
115 | if [ $? -ne 0 ] ; then
116 | warn "Could not set maximum file descriptor limit: $MAX_FD"
117 | fi
118 | else
119 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
120 | fi
121 | fi
122 |
123 | # For Darwin, add options to specify how the application appears in the dock
124 | if $darwin; then
125 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
126 | fi
127 |
128 | # For Cygwin or MSYS, switch paths to Windows format before running java
129 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
130 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
131 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
132 | JAVACMD=`cygpath --unix "$JAVACMD"`
133 |
134 | # We build the pattern for arguments to be converted via cygpath
135 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
136 | SEP=""
137 | for dir in $ROOTDIRSRAW ; do
138 | ROOTDIRS="$ROOTDIRS$SEP$dir"
139 | SEP="|"
140 | done
141 | OURCYGPATTERN="(^($ROOTDIRS))"
142 | # Add a user-defined pattern to the cygpath arguments
143 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
144 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
145 | fi
146 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
147 | i=0
148 | for arg in "$@" ; do
149 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
150 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
151 |
152 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
153 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
154 | else
155 | eval `echo args$i`="\"$arg\""
156 | fi
157 | i=$((i+1))
158 | done
159 | case $i in
160 | (0) set -- ;;
161 | (1) set -- "$args0" ;;
162 | (2) set -- "$args0" "$args1" ;;
163 | (3) set -- "$args0" "$args1" "$args2" ;;
164 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
165 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
166 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
167 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
168 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
169 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
170 | esac
171 | fi
172 |
173 | # Escape application args
174 | save () {
175 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
176 | echo " "
177 | }
178 | APP_ARGS=$(save "$@")
179 |
180 | # Collect all arguments for the java command, following the shell quoting and substitution rules
181 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
182 |
183 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
184 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
185 | cd "$(dirname "$0")"
186 | fi
187 |
188 | exec "$JAVACMD" "$@"
189 |
--------------------------------------------------------------------------------
/examples/native-use-pusher-example/android/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem http://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 |
17 | @if "%DEBUG%" == "" @echo off
18 | @rem ##########################################################################
19 | @rem
20 | @rem Gradle startup script for Windows
21 | @rem
22 | @rem ##########################################################################
23 |
24 | @rem Set local scope for the variables with windows NT shell
25 | if "%OS%"=="Windows_NT" setlocal
26 |
27 | set DIRNAME=%~dp0
28 | if "%DIRNAME%" == "" set DIRNAME=.
29 | set APP_BASE_NAME=%~n0
30 | set APP_HOME=%DIRNAME%
31 |
32 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
33 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
34 |
35 | @rem Find java.exe
36 | if defined JAVA_HOME goto findJavaFromJavaHome
37 |
38 | set JAVA_EXE=java.exe
39 | %JAVA_EXE% -version >NUL 2>&1
40 | if "%ERRORLEVEL%" == "0" goto init
41 |
42 | echo.
43 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
44 | echo.
45 | echo Please set the JAVA_HOME variable in your environment to match the
46 | echo location of your Java installation.
47 |
48 | goto fail
49 |
50 | :findJavaFromJavaHome
51 | set JAVA_HOME=%JAVA_HOME:"=%
52 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
53 |
54 | if exist "%JAVA_EXE%" goto init
55 |
56 | echo.
57 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
58 | echo.
59 | echo Please set the JAVA_HOME variable in your environment to match the
60 | echo location of your Java installation.
61 |
62 | goto fail
63 |
64 | :init
65 | @rem Get command-line arguments, handling Windows variants
66 |
67 | if not "%OS%" == "Windows_NT" goto win9xME_args
68 |
69 | :win9xME_args
70 | @rem Slurp the command line arguments.
71 | set CMD_LINE_ARGS=
72 | set _SKIP=2
73 |
74 | :win9xME_args_slurp
75 | if "x%~1" == "x" goto execute
76 |
77 | set CMD_LINE_ARGS=%*
78 |
79 | :execute
80 | @rem Setup the command line
81 |
82 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
83 |
84 | @rem Execute Gradle
85 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
86 |
87 | :end
88 | @rem End local scope for the variables with windows NT shell
89 | if "%ERRORLEVEL%"=="0" goto mainEnd
90 |
91 | :fail
92 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
93 | rem the _cmd.exe /c_ return code!
94 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
95 | exit /b 1
96 |
97 | :mainEnd
98 | if "%OS%"=="Windows_NT" endlocal
99 |
100 | :omega
101 |
--------------------------------------------------------------------------------
/examples/native-use-pusher-example/android/settings.gradle:
--------------------------------------------------------------------------------
1 | rootProject.name = 'nativeusepusherexample'
2 | include ':@react-native-community_netinfo'
3 | project(':@react-native-community_netinfo').projectDir = new File(rootProject.projectDir, '../node_modules/@react-native-community/netinfo/android')
4 |
5 | apply from: '../node_modules/react-native-unimodules/gradle.groovy'
6 | includeUnimodulesProjects()
7 |
8 | apply from: file("../node_modules/@react-native-community/cli-platform-android/native_modules.gradle");
9 | applyNativeModulesSettingsGradle(settings)
10 |
11 | include ':app'
12 |
--------------------------------------------------------------------------------
/examples/native-use-pusher-example/app.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "native-use-pusher-example",
3 | "displayName": "native-use-pusher-example",
4 | "expo": {
5 | "name": "native-use-pusher-example",
6 | "slug": "native-use-pusher-example",
7 | "version": "1.0.0",
8 | "assetBundlePatterns": [
9 | "**/*"
10 | ]
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/examples/native-use-pusher-example/babel.config.js:
--------------------------------------------------------------------------------
1 | module.exports = function(api) {
2 | api.cache(true);
3 | return {
4 | presets: ['babel-preset-expo'],
5 | };
6 | };
7 |
--------------------------------------------------------------------------------
/examples/native-use-pusher-example/index.js:
--------------------------------------------------------------------------------
1 | import { registerRootComponent } from 'expo';
2 |
3 | import App from './App';
4 |
5 | // registerRootComponent calls AppRegistry.registerComponent('main', () => App);
6 | // It also ensures that whether you load the app in the Expo client or in a native build,
7 | // the environment is set up appropriately
8 | registerRootComponent(App);
9 |
--------------------------------------------------------------------------------
/examples/native-use-pusher-example/ios/Podfile:
--------------------------------------------------------------------------------
1 | platform :ios, '10.0'
2 | require_relative '../node_modules/react-native-unimodules/cocoapods.rb'
3 | require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules'
4 |
5 | def add_flipper_pods!(versions = {})
6 | versions['Flipper'] ||= '~> 0.33.1'
7 | versions['DoubleConversion'] ||= '1.1.7'
8 | versions['Flipper-Folly'] ||= '~> 2.1'
9 | versions['Flipper-Glog'] ||= '0.3.6'
10 | versions['Flipper-PeerTalk'] ||= '~> 0.0.4'
11 | versions['Flipper-RSocket'] ||= '~> 1.0'
12 |
13 | pod 'FlipperKit', versions['Flipper'], :configuration => 'Debug'
14 | pod 'FlipperKit/FlipperKitLayoutPlugin', versions['Flipper'], :configuration => 'Debug'
15 | pod 'FlipperKit/SKIOSNetworkPlugin', versions['Flipper'], :configuration => 'Debug'
16 | pod 'FlipperKit/FlipperKitUserDefaultsPlugin', versions['Flipper'], :configuration => 'Debug'
17 | pod 'FlipperKit/FlipperKitReactPlugin', versions['Flipper'], :configuration => 'Debug'
18 |
19 | # List all transitive dependencies for FlipperKit pods
20 | # to avoid them being linked in Release builds
21 | pod 'Flipper', versions['Flipper'], :configuration => 'Debug'
22 | pod 'Flipper-DoubleConversion', versions['DoubleConversion'], :configuration => 'Debug'
23 | pod 'Flipper-Folly', versions['Flipper-Folly'], :configuration => 'Debug'
24 | pod 'Flipper-Glog', versions['Flipper-Glog'], :configuration => 'Debug'
25 | pod 'Flipper-PeerTalk', versions['Flipper-PeerTalk'], :configuration => 'Debug'
26 | pod 'Flipper-RSocket', versions['Flipper-RSocket'], :configuration => 'Debug'
27 | pod 'FlipperKit/Core', versions['Flipper'], :configuration => 'Debug'
28 | pod 'FlipperKit/CppBridge', versions['Flipper'], :configuration => 'Debug'
29 | pod 'FlipperKit/FBCxxFollyDynamicConvert', versions['Flipper'], :configuration => 'Debug'
30 | pod 'FlipperKit/FBDefines', versions['Flipper'], :configuration => 'Debug'
31 | pod 'FlipperKit/FKPortForwarding', versions['Flipper'], :configuration => 'Debug'
32 | pod 'FlipperKit/FlipperKitHighlightOverlay', versions['Flipper'], :configuration => 'Debug'
33 | pod 'FlipperKit/FlipperKitLayoutTextSearchable', versions['Flipper'], :configuration => 'Debug'
34 | pod 'FlipperKit/FlipperKitNetworkPlugin', versions['Flipper'], :configuration => 'Debug'
35 | end
36 |
37 | # Post Install processing for Flipper
38 | def flipper_post_install(installer)
39 | installer.pods_project.targets.each do |target|
40 | if target.name == 'YogaKit'
41 | target.build_configurations.each do |config|
42 | config.build_settings['SWIFT_VERSION'] = '4.1'
43 | end
44 | end
45 | end
46 | end
47 |
48 | target 'nativeusepusherexample' do
49 | # Pods for nativeusepusherexample
50 | pod 'FBLazyVector', :path => "../node_modules/react-native/Libraries/FBLazyVector"
51 | pod 'FBReactNativeSpec', :path => "../node_modules/react-native/Libraries/FBReactNativeSpec"
52 | pod 'RCTRequired', :path => "../node_modules/react-native/Libraries/RCTRequired"
53 | pod 'RCTTypeSafety', :path => "../node_modules/react-native/Libraries/TypeSafety"
54 | pod 'React', :path => '../node_modules/react-native/'
55 | pod 'React-Core', :path => '../node_modules/react-native/'
56 | pod 'React-CoreModules', :path => '../node_modules/react-native/React/CoreModules'
57 | pod 'React-Core/DevSupport', :path => '../node_modules/react-native/'
58 | pod 'React-RCTActionSheet', :path => '../node_modules/react-native/Libraries/ActionSheetIOS'
59 | pod 'React-RCTAnimation', :path => '../node_modules/react-native/Libraries/NativeAnimation'
60 | pod 'React-RCTBlob', :path => '../node_modules/react-native/Libraries/Blob'
61 | pod 'React-RCTImage', :path => '../node_modules/react-native/Libraries/Image'
62 | pod 'React-RCTLinking', :path => '../node_modules/react-native/Libraries/LinkingIOS'
63 | pod 'React-RCTNetwork', :path => '../node_modules/react-native/Libraries/Network'
64 | pod 'React-RCTSettings', :path => '../node_modules/react-native/Libraries/Settings'
65 | pod 'React-RCTText', :path => '../node_modules/react-native/Libraries/Text'
66 | pod 'React-RCTVibration', :path => '../node_modules/react-native/Libraries/Vibration'
67 | pod 'React-Core/RCTWebSocket', :path => '../node_modules/react-native/'
68 |
69 | pod 'React-cxxreact', :path => '../node_modules/react-native/ReactCommon/cxxreact'
70 | pod 'React-jsi', :path => '../node_modules/react-native/ReactCommon/jsi'
71 | pod 'React-jsiexecutor', :path => '../node_modules/react-native/ReactCommon/jsiexecutor'
72 | pod 'React-jsinspector', :path => '../node_modules/react-native/ReactCommon/jsinspector'
73 | pod 'ReactCommon/callinvoker', :path => "../node_modules/react-native/ReactCommon"
74 | pod 'ReactCommon/turbomodule/core', :path => "../node_modules/react-native/ReactCommon"
75 | pod 'Yoga', :path => '../node_modules/react-native/ReactCommon/yoga', :modular_headers => true
76 |
77 | pod 'DoubleConversion', :podspec => '../node_modules/react-native/third-party-podspecs/DoubleConversion.podspec'
78 | pod 'glog', :podspec => '../node_modules/react-native/third-party-podspecs/glog.podspec'
79 | pod 'Folly', :podspec => '../node_modules/react-native/third-party-podspecs/Folly.podspec'
80 |
81 | use_unimodules!
82 | use_native_modules!
83 |
84 | # Enables Flipper.
85 | #
86 | # Note that if you have use_frameworks! enabled, Flipper will not work and
87 | # you should disable these next few lines.
88 | add_flipper_pods!
89 | pod 'react-native-netinfo', :path => '../node_modules/@react-native-community/netinfo'
90 |
91 | post_install do |installer|
92 | flipper_post_install(installer)
93 | end
94 | end
--------------------------------------------------------------------------------
/examples/native-use-pusher-example/ios/nativeusepusherexample.xcodeproj/xcshareddata/xcschemes/nativeusepusherexample.xcscheme:
--------------------------------------------------------------------------------
1 |
2 |
5 |
8 |
9 |
15 |
21 |
22 |
23 |
24 |
25 |
30 |
31 |
33 |
39 |
40 |
41 |
42 |
43 |
53 |
55 |
61 |
62 |
63 |
64 |
70 |
72 |
78 |
79 |
80 |
81 |
83 |
84 |
87 |
88 |
89 |
--------------------------------------------------------------------------------
/examples/native-use-pusher-example/ios/nativeusepusherexample.xcworkspace/contents.xcworkspacedata:
--------------------------------------------------------------------------------
1 |
2 |
4 |
6 |
7 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/examples/native-use-pusher-example/ios/nativeusepusherexample/AppDelegate.h:
--------------------------------------------------------------------------------
1 | #import
2 | #import
3 | #import
4 | #import
5 |
6 | #import
7 |
8 | @interface AppDelegate : UMAppDelegateWrapper
9 |
10 | @end
11 |
--------------------------------------------------------------------------------
/examples/native-use-pusher-example/ios/nativeusepusherexample/AppDelegate.m:
--------------------------------------------------------------------------------
1 | #import "AppDelegate.h"
2 |
3 | #import
4 | #import
5 | #import
6 |
7 | #import
8 | #import
9 | #import
10 | #import
11 | #import
12 |
13 | #if DEBUG
14 | #import
15 | #import
16 | #import
17 | #import
18 | #import
19 | #import
20 |
21 | static void InitializeFlipper(UIApplication *application) {
22 | FlipperClient *client = [FlipperClient sharedClient];
23 | SKDescriptorMapper *layoutDescriptorMapper = [[SKDescriptorMapper alloc] initWithDefaults];
24 | [client addPlugin:[[FlipperKitLayoutPlugin alloc] initWithRootNode:application withDescriptorMapper:layoutDescriptorMapper]];
25 | [client addPlugin:[[FKUserDefaultsPlugin alloc] initWithSuiteName:nil]];
26 | [client addPlugin:[FlipperKitReactPlugin new]];
27 | [client addPlugin:[[FlipperKitNetworkPlugin alloc] initWithNetworkAdapter:[SKIOSNetworkAdapter new]]];
28 | [client start];
29 | }
30 | #endif
31 |
32 | @interface AppDelegate ()
33 |
34 | @property (nonatomic, strong) UMModuleRegistryAdapter *moduleRegistryAdapter;
35 | @property (nonatomic, strong) NSDictionary *launchOptions;
36 |
37 | @end
38 |
39 | @implementation AppDelegate
40 |
41 | - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
42 | {
43 | #if DEBUG
44 | InitializeFlipper(application);
45 | #endif
46 |
47 | self.moduleRegistryAdapter = [[UMModuleRegistryAdapter alloc] initWithModuleRegistryProvider:[[UMModuleRegistryProvider alloc] init]];
48 | self.launchOptions = launchOptions;
49 | self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
50 | #ifdef DEBUG
51 | [self initializeReactNativeApp];
52 | #else
53 | EXUpdatesAppController *controller = [EXUpdatesAppController sharedInstance];
54 | controller.delegate = self;
55 | [controller startAndShowLaunchScreen:self.window];
56 | #endif
57 |
58 | [super application:application didFinishLaunchingWithOptions:launchOptions];
59 |
60 | return YES;
61 | }
62 |
63 | - (RCTBridge *)initializeReactNativeApp
64 | {
65 | RCTBridge *bridge = [[RCTBridge alloc] initWithDelegate:self launchOptions:self.launchOptions];
66 | RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:bridge moduleName:@"main" initialProperties:nil];
67 | rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1];
68 |
69 | self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
70 | UIViewController *rootViewController = [UIViewController new];
71 | rootViewController.view = rootView;
72 | self.window.rootViewController = rootViewController;
73 | [self.window makeKeyAndVisible];
74 |
75 | return bridge;
76 | }
77 |
78 | - (NSArray> *)extraModulesForBridge:(RCTBridge *)bridge
79 | {
80 | NSArray> *extraModules = [_moduleRegistryAdapter extraModulesForBridge:bridge];
81 | // If you'd like to export some custom RCTBridgeModules that are not Expo modules, add them here!
82 | return extraModules;
83 | }
84 |
85 | - (NSURL *)sourceURLForBridge:(RCTBridge *)bridge {
86 | #ifdef DEBUG
87 | return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];
88 | #else
89 | return [[EXUpdatesAppController sharedInstance] launchAssetUrl];
90 | #endif
91 | }
92 |
93 | - (void)appController:(EXUpdatesAppController *)appController didStartWithSuccess:(BOOL)success {
94 | appController.bridge = [self initializeReactNativeApp];
95 | EXSplashScreenService *splashScreenService = (EXSplashScreenService *)[UMModuleRegistryProvider getSingletonModuleForClass:[EXSplashScreenService class]];
96 | [splashScreenService showSplashScreenFor:self.window.rootViewController];
97 | }
98 |
99 | @end
100 |
--------------------------------------------------------------------------------
/examples/native-use-pusher-example/ios/nativeusepusherexample/Base.lproj/LaunchScreen.xib:
--------------------------------------------------------------------------------
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 |
--------------------------------------------------------------------------------
/examples/native-use-pusher-example/ios/nativeusepusherexample/Images.xcassets/AppIcon.appiconset/Contents.json:
--------------------------------------------------------------------------------
1 | {
2 | "images" : [
3 | {
4 | "idiom" : "iphone",
5 | "size" : "29x29",
6 | "scale" : "2x"
7 | },
8 | {
9 | "idiom" : "iphone",
10 | "size" : "29x29",
11 | "scale" : "3x"
12 | },
13 | {
14 | "idiom" : "iphone",
15 | "size" : "40x40",
16 | "scale" : "2x"
17 | },
18 | {
19 | "idiom" : "iphone",
20 | "size" : "40x40",
21 | "scale" : "3x"
22 | },
23 | {
24 | "idiom" : "iphone",
25 | "size" : "60x60",
26 | "scale" : "2x"
27 | },
28 | {
29 | "idiom" : "iphone",
30 | "size" : "60x60",
31 | "scale" : "3x"
32 | }
33 | ],
34 | "info" : {
35 | "version" : 1,
36 | "author" : "xcode"
37 | }
38 | }
--------------------------------------------------------------------------------
/examples/native-use-pusher-example/ios/nativeusepusherexample/Images.xcassets/Contents.json:
--------------------------------------------------------------------------------
1 | {
2 | "info" : {
3 | "version" : 1,
4 | "author" : "xcode"
5 | }
6 | }
7 |
--------------------------------------------------------------------------------
/examples/native-use-pusher-example/ios/nativeusepusherexample/Images.xcassets/SplashScreen.imageset/Contents.json:
--------------------------------------------------------------------------------
1 | {
2 | "images": [
3 | {
4 | "idiom": "universal",
5 | "filename": "splashscreen.png",
6 | "scale": "1x"
7 | },
8 | {
9 | "idiom": "universal",
10 | "scale": "2x"
11 | },
12 | {
13 | "idiom": "universal",
14 | "scale": "3x"
15 | }
16 | ],
17 | "info": {
18 | "version": 1,
19 | "author": "xcode"
20 | }
21 | }
--------------------------------------------------------------------------------
/examples/native-use-pusher-example/ios/nativeusepusherexample/Images.xcassets/SplashScreen.imageset/splashscreen.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mayteio/use-pusher/f9f2389db01d3c102f31b43045325967d96ba342/examples/native-use-pusher-example/ios/nativeusepusherexample/Images.xcassets/SplashScreen.imageset/splashscreen.png
--------------------------------------------------------------------------------
/examples/native-use-pusher-example/ios/nativeusepusherexample/Images.xcassets/SplashScreenBackground.imageset/Contents.json:
--------------------------------------------------------------------------------
1 | {
2 | "images": [
3 | {
4 | "idiom": "universal",
5 | "filename": "background.png",
6 | "scale": "1x"
7 | },
8 | {
9 | "idiom": "universal",
10 | "scale": "2x"
11 | },
12 | {
13 | "idiom": "universal",
14 | "scale": "3x"
15 | }
16 | ],
17 | "info": {
18 | "version": 1,
19 | "author": "xcode"
20 | }
21 | }
--------------------------------------------------------------------------------
/examples/native-use-pusher-example/ios/nativeusepusherexample/Images.xcassets/SplashScreenBackground.imageset/background.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mayteio/use-pusher/f9f2389db01d3c102f31b43045325967d96ba342/examples/native-use-pusher-example/ios/nativeusepusherexample/Images.xcassets/SplashScreenBackground.imageset/background.png
--------------------------------------------------------------------------------
/examples/native-use-pusher-example/ios/nativeusepusherexample/Info.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | CFBundleDevelopmentRegion
6 | en
7 | CFBundleDisplayName
8 | native-use-pusher-example
9 | CFBundleExecutable
10 | $(EXECUTABLE_NAME)
11 | CFBundleIdentifier
12 | $(PRODUCT_BUNDLE_IDENTIFIER)
13 | CFBundleInfoDictionaryVersion
14 | 6.0
15 | CFBundleName
16 | $(PRODUCT_NAME)
17 | CFBundlePackageType
18 | APPL
19 | CFBundleShortVersionString
20 | 1.0
21 | CFBundleSignature
22 | ????
23 | CFBundleVersion
24 | 1
25 | LSRequiresIPhoneOS
26 |
27 | NSAppTransportSecurity
28 |
29 | NSAllowsArbitraryLoads
30 |
31 | NSExceptionDomains
32 |
33 | localhost
34 |
35 | NSExceptionAllowsInsecureHTTPLoads
36 |
37 |
38 |
39 |
40 | NSLocationWhenInUseUsageDescription
41 |
42 | UILaunchStoryboardName
43 | SplashScreen
44 | UIRequiredDeviceCapabilities
45 |
46 | armv7
47 |
48 | UISupportedInterfaceOrientations
49 |
50 | UIInterfaceOrientationPortrait
51 | UIInterfaceOrientationLandscapeLeft
52 | UIInterfaceOrientationLandscapeRight
53 |
54 | UIViewControllerBasedStatusBarAppearance
55 |
56 | UIStatusBarStyle
57 | UIStatusBarStyleDefault
58 |
59 |
60 |
--------------------------------------------------------------------------------
/examples/native-use-pusher-example/ios/nativeusepusherexample/SplashScreen.storyboard:
--------------------------------------------------------------------------------
1 |
2 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
31 |
39 |
40 |
41 |
42 |
53 |
54 |
55 |
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 |
--------------------------------------------------------------------------------
/examples/native-use-pusher-example/ios/nativeusepusherexample/Supporting/Expo.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | EXUpdatesSDKVersion
6 | YOUR-APP-SDK-VERSION-HERE
7 | EXUpdatesURL
8 | YOUR-APP-URL-HERE
9 |
10 |
11 |
--------------------------------------------------------------------------------
/examples/native-use-pusher-example/ios/nativeusepusherexample/main.m:
--------------------------------------------------------------------------------
1 | #import
2 |
3 | #import "AppDelegate.h"
4 |
5 | int main(int argc, char * argv[]) {
6 | @autoreleasepool {
7 | return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
8 | }
9 | }
10 |
11 |
--------------------------------------------------------------------------------
/examples/native-use-pusher-example/metro.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | transformer: {
3 | assetPlugins: ['expo-asset/tools/hashAssetFiles'],
4 | },
5 | };
6 |
--------------------------------------------------------------------------------
/examples/native-use-pusher-example/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "main": "index.js",
3 | "scripts": {
4 | "android": "react-native run-android",
5 | "ios": "react-native run-ios",
6 | "web": "expo start --web",
7 | "start": "react-native start",
8 | "test": "jest"
9 | },
10 | "dependencies": {
11 | "@react-native-community/netinfo": "^5.9.6",
12 | "expo": "~38.0.9",
13 | "expo-splash-screen": "^0.5.0",
14 | "expo-status-bar": "^1.0.0",
15 | "expo-updates": "~0.2.10",
16 | "react": "~16.11.0",
17 | "react-dom": "~16.11.0",
18 | "react-native": "~0.62.2",
19 | "react-native-gesture-handler": "~1.6.1",
20 | "react-native-reanimated": "~1.9.0",
21 | "react-native-screens": "~2.9.0",
22 | "react-native-unimodules": "~0.10.1",
23 | "react-native-web": "~0.11.7"
24 | },
25 | "devDependencies": {
26 | "@babel/core": "~7.9.0",
27 | "babel-jest": "~25.2.6",
28 | "jest": "~25.2.6",
29 | "react-test-renderer": "~16.11.0"
30 | },
31 | "jest": {
32 | "preset": "react-native"
33 | },
34 | "private": true
35 | }
36 |
--------------------------------------------------------------------------------
/examples/web/.eslintignore:
--------------------------------------------------------------------------------
1 | ./src/use-pusher/index.js
--------------------------------------------------------------------------------
/examples/web/.gitignore:
--------------------------------------------------------------------------------
1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
2 |
3 | # dependencies
4 | /node_modules
5 | /.pnp
6 | .pnp.js
7 |
8 | # testing
9 | /coverage
10 |
11 | # production
12 | /build
13 |
14 | src/use-pusher
15 |
16 | # misc
17 | .DS_Store
18 | .env.local
19 | .env.development.local
20 | .env.test.local
21 | .env.production.local
22 |
23 | npm-debug.log*
24 | yarn-debug.log*
25 | yarn-error.log*
26 |
--------------------------------------------------------------------------------
/examples/web/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | **Table of Contents** *generated with [DocToc](https://github.com/thlorenz/doctoc)*
4 |
5 | - [Example app](#example-app)
6 | - [Available Scripts](#available-scripts)
7 | - [`yarn start`](#yarn-start)
8 | - [`yarn test`](#yarn-test)
9 | - [`yarn build`](#yarn-build)
10 | - [`yarn eject`](#yarn-eject)
11 | - [Learn More](#learn-more)
12 | - [Code Splitting](#code-splitting)
13 | - [Analyzing the Bundle Size](#analyzing-the-bundle-size)
14 | - [Making a Progressive Web App](#making-a-progressive-web-app)
15 | - [Advanced Configuration](#advanced-configuration)
16 | - [Deployment](#deployment)
17 | - [`yarn build` fails to minify](#yarn-build-fails-to-minify)
18 |
19 |
20 |
21 | # Example app
22 |
23 | This example app allows you to test the hooks with a real pusher client.
24 |
25 | Important: create a `.env` file in the example root and fill it with the following variables.
26 |
27 | ```
28 | REACT_APP_PUSHER_APP_ID=
29 | REACT_APP_PUSHER_KEY=
30 | REACT_APP_PUSHER_SECRET=
31 | REACT_APP_PUSHER_CLUSTER=
32 | ```
33 |
34 | They are available in your pusher app's dashboard.
35 |
36 | After that, hit yarn start and go for gold.
37 |
38 | ---
39 |
40 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
41 |
42 | ## Available Scripts
43 |
44 | In the project directory, you can run:
45 |
46 | ### `yarn start`
47 |
48 | Runs the app in the development mode.
49 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
50 |
51 | The page will reload if you make edits.
52 | You will also see any lint errors in the console.
53 |
54 | ### `yarn test`
55 |
56 | Launches the test runner in the interactive watch mode.
57 | See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
58 |
59 | ### `yarn build`
60 |
61 | Builds the app for production to the `build` folder.
62 | It correctly bundles React in production mode and optimizes the build for the best performance.
63 |
64 | The build is minified and the filenames include the hashes.
65 | Your app is ready to be deployed!
66 |
67 | See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
68 |
69 | ### `yarn eject`
70 |
71 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!**
72 |
73 | If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
74 |
75 | Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.
76 |
77 | You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.
78 |
79 | ## Learn More
80 |
81 | You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
82 |
83 | To learn React, check out the [React documentation](https://reactjs.org/).
84 |
85 | ### Code Splitting
86 |
87 | This section has moved here: https://facebook.github.io/create-react-app/docs/code-splitting
88 |
89 | ### Analyzing the Bundle Size
90 |
91 | This section has moved here: https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size
92 |
93 | ### Making a Progressive Web App
94 |
95 | This section has moved here: https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app
96 |
97 | ### Advanced Configuration
98 |
99 | This section has moved here: https://facebook.github.io/create-react-app/docs/advanced-configuration
100 |
101 | ### Deployment
102 |
103 | This section has moved here: https://facebook.github.io/create-react-app/docs/deployment
104 |
105 | ### `yarn build` fails to minify
106 |
107 | This section has moved here: https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify
108 |
--------------------------------------------------------------------------------
/examples/web/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "example",
3 | "version": "0.1.0",
4 | "private": true,
5 | "dependencies": {
6 | "@testing-library/jest-dom": "^5.11.3",
7 | "@testing-library/react": "^10.4.8",
8 | "@testing-library/user-event": "^12.1.1",
9 | "pusher": "^3.0.1",
10 | "react": "^16.13.1",
11 | "react-dom": "^16.13.1",
12 | "react-scripts": "3.4.3"
13 | },
14 | "scripts": {
15 | "start": "react-scripts start",
16 | "build": "react-scripts build",
17 | "test": "react-scripts test",
18 | "eject": "react-scripts eject"
19 | },
20 | "eslintConfig": {
21 | "extends": "react-app"
22 | },
23 | "browserslist": {
24 | "production": [
25 | ">0.2%",
26 | "not dead",
27 | "not op_mini all"
28 | ],
29 | "development": [
30 | "last 1 chrome version",
31 | "last 1 firefox version",
32 | "last 1 safari version"
33 | ]
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/examples/web/public/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mayteio/use-pusher/f9f2389db01d3c102f31b43045325967d96ba342/examples/web/public/favicon.ico
--------------------------------------------------------------------------------
/examples/web/public/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
12 |
13 |
17 |
18 |
27 | React App
28 |
29 |
30 | You need to enable JavaScript to run this app.
31 |
32 |
42 |
43 |
44 |
--------------------------------------------------------------------------------
/examples/web/public/logo192.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mayteio/use-pusher/f9f2389db01d3c102f31b43045325967d96ba342/examples/web/public/logo192.png
--------------------------------------------------------------------------------
/examples/web/public/logo512.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mayteio/use-pusher/f9f2389db01d3c102f31b43045325967d96ba342/examples/web/public/logo512.png
--------------------------------------------------------------------------------
/examples/web/public/manifest.json:
--------------------------------------------------------------------------------
1 | {
2 | "short_name": "React App",
3 | "name": "Create React App Sample",
4 | "icons": [
5 | {
6 | "src": "favicon.ico",
7 | "sizes": "64x64 32x32 24x24 16x16",
8 | "type": "image/x-icon"
9 | },
10 | {
11 | "src": "logo192.png",
12 | "type": "image/png",
13 | "sizes": "192x192"
14 | },
15 | {
16 | "src": "logo512.png",
17 | "type": "image/png",
18 | "sizes": "512x512"
19 | }
20 | ],
21 | "start_url": ".",
22 | "display": "standalone",
23 | "theme_color": "#000000",
24 | "background_color": "#ffffff"
25 | }
26 |
--------------------------------------------------------------------------------
/examples/web/public/robots.txt:
--------------------------------------------------------------------------------
1 | # https://www.robotstxt.org/robotstxt.html
2 | User-agent: *
3 | Disallow:
4 |
--------------------------------------------------------------------------------
/examples/web/src/App.css:
--------------------------------------------------------------------------------
1 | .App {
2 | text-align: center;
3 | }
4 |
5 | .App-logo {
6 | height: 40vmin;
7 | pointer-events: none;
8 | }
9 |
10 | @media (prefers-reduced-motion: no-preference) {
11 | .App-logo {
12 | animation: App-logo-spin infinite 20s linear;
13 | }
14 | }
15 |
16 | .App-header {
17 | background-color: #282c34;
18 | min-height: 100vh;
19 | display: flex;
20 | flex-direction: column;
21 | align-items: center;
22 | justify-content: center;
23 | font-size: calc(10px + 2vmin);
24 | color: white;
25 | }
26 |
27 | .App-link {
28 | color: #61dafb;
29 | cursor: pointer;
30 | }
31 |
32 | @keyframes App-logo-spin {
33 | from {
34 | transform: rotate(0deg);
35 | }
36 | to {
37 | transform: rotate(360deg);
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/examples/web/src/App.js:
--------------------------------------------------------------------------------
1 | import "./App.css";
2 |
3 | import { useClientTrigger, usePresenceChannel } from "./use-pusher";
4 |
5 | import React from "react";
6 | import logo from "./logo.svg";
7 |
8 | function App() {
9 | const { channel, ...rest } = usePresenceChannel("presence-my-channel");
10 | const trigger = useClientTrigger(channel);
11 | console.log(rest);
12 |
13 | return (
14 |
30 | );
31 | }
32 |
33 | export default App;
34 |
--------------------------------------------------------------------------------
/examples/web/src/index.css:
--------------------------------------------------------------------------------
1 | body {
2 | margin: 0;
3 | font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
4 | 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
5 | sans-serif;
6 | -webkit-font-smoothing: antialiased;
7 | -moz-osx-font-smoothing: grayscale;
8 | }
9 |
10 | code {
11 | font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
12 | monospace;
13 | }
14 |
--------------------------------------------------------------------------------
/examples/web/src/index.js:
--------------------------------------------------------------------------------
1 | import "./index.css";
2 |
3 | import * as serviceWorker from "./serviceWorker";
4 |
5 | import App from "./App";
6 | import Pusher from "pusher";
7 | import { PusherProvider } from "./use-pusher";
8 | import React from "react";
9 | import ReactDOM from "react-dom";
10 |
11 | const pusher = new Pusher({
12 | appId: process.env.REACT_APP_PUSHER_APP_ID,
13 | key: process.env.REACT_APP_PUSHER_KEY,
14 | secret: process.env.REACT_APP_PUSHER_SECRET,
15 | cluster: process.env.REACT_APP_PUSHER_CLUSTER
16 | });
17 |
18 | ReactDOM.render(
19 | ({
23 | authorize: async (socketId, callback) => {
24 | const auth = pusher.authenticate(socketId, name, {
25 | user_id: Math.random() * 124234,
26 | user_info: {}
27 | });
28 | callback(false, auth);
29 | }
30 | })}
31 | >
32 |
33 | ,
34 | document.getElementById("root")
35 | );
36 |
37 | // If you want your app to work offline and load faster, you can change
38 | // unregister() to register() below. Note this comes with some pitfalls.
39 | // Learn more about service workers: https://bit.ly/CRA-PWA
40 | serviceWorker.unregister();
41 |
--------------------------------------------------------------------------------
/examples/web/src/logo.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/examples/web/src/serviceWorker.js:
--------------------------------------------------------------------------------
1 | // This optional code is used to register a service worker.
2 | // register() is not called by default.
3 |
4 | // This lets the app load faster on subsequent visits in production, and gives
5 | // it offline capabilities. However, it also means that developers (and users)
6 | // will only see deployed updates on subsequent visits to a page, after all the
7 | // existing tabs open on the page have been closed, since previously cached
8 | // resources are updated in the background.
9 |
10 | // To learn more about the benefits of this model and instructions on how to
11 | // opt-in, read https://bit.ly/CRA-PWA
12 |
13 | const isLocalhost = Boolean(
14 | window.location.hostname === 'localhost' ||
15 | // [::1] is the IPv6 localhost address.
16 | window.location.hostname === '[::1]' ||
17 | // 127.0.0.0/8 are considered localhost for IPv4.
18 | window.location.hostname.match(
19 | /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
20 | )
21 | );
22 |
23 | export function register(config) {
24 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
25 | // The URL constructor is available in all browsers that support SW.
26 | const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
27 | if (publicUrl.origin !== window.location.origin) {
28 | // Our service worker won't work if PUBLIC_URL is on a different origin
29 | // from what our page is served on. This might happen if a CDN is used to
30 | // serve assets; see https://github.com/facebook/create-react-app/issues/2374
31 | return;
32 | }
33 |
34 | window.addEventListener('load', () => {
35 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
36 |
37 | if (isLocalhost) {
38 | // This is running on localhost. Let's check if a service worker still exists or not.
39 | checkValidServiceWorker(swUrl, config);
40 |
41 | // Add some additional logging to localhost, pointing developers to the
42 | // service worker/PWA documentation.
43 | navigator.serviceWorker.ready.then(() => {
44 | console.log(
45 | 'This web app is being served cache-first by a service ' +
46 | 'worker. To learn more, visit https://bit.ly/CRA-PWA'
47 | );
48 | });
49 | } else {
50 | // Is not localhost. Just register service worker
51 | registerValidSW(swUrl, config);
52 | }
53 | });
54 | }
55 | }
56 |
57 | function registerValidSW(swUrl, config) {
58 | navigator.serviceWorker
59 | .register(swUrl)
60 | .then(registration => {
61 | registration.onupdatefound = () => {
62 | const installingWorker = registration.installing;
63 | if (installingWorker == null) {
64 | return;
65 | }
66 | installingWorker.onstatechange = () => {
67 | if (installingWorker.state === 'installed') {
68 | if (navigator.serviceWorker.controller) {
69 | // At this point, the updated precached content has been fetched,
70 | // but the previous service worker will still serve the older
71 | // content until all client tabs are closed.
72 | console.log(
73 | 'New content is available and will be used when all ' +
74 | 'tabs for this page are closed. See https://bit.ly/CRA-PWA.'
75 | );
76 |
77 | // Execute callback
78 | if (config && config.onUpdate) {
79 | config.onUpdate(registration);
80 | }
81 | } else {
82 | // At this point, everything has been precached.
83 | // It's the perfect time to display a
84 | // "Content is cached for offline use." message.
85 | console.log('Content is cached for offline use.');
86 |
87 | // Execute callback
88 | if (config && config.onSuccess) {
89 | config.onSuccess(registration);
90 | }
91 | }
92 | }
93 | };
94 | };
95 | })
96 | .catch(error => {
97 | console.error('Error during service worker registration:', error);
98 | });
99 | }
100 |
101 | function checkValidServiceWorker(swUrl, config) {
102 | // Check if the service worker can be found. If it can't reload the page.
103 | fetch(swUrl, {
104 | headers: { 'Service-Worker': 'script' }
105 | })
106 | .then(response => {
107 | // Ensure service worker exists, and that we really are getting a JS file.
108 | const contentType = response.headers.get('content-type');
109 | if (
110 | response.status === 404 ||
111 | (contentType != null && contentType.indexOf('javascript') === -1)
112 | ) {
113 | // No service worker found. Probably a different app. Reload the page.
114 | navigator.serviceWorker.ready.then(registration => {
115 | registration.unregister().then(() => {
116 | window.location.reload();
117 | });
118 | });
119 | } else {
120 | // Service worker found. Proceed as normal.
121 | registerValidSW(swUrl, config);
122 | }
123 | })
124 | .catch(() => {
125 | console.log(
126 | 'No internet connection found. App is running in offline mode.'
127 | );
128 | });
129 | }
130 |
131 | export function unregister() {
132 | if ('serviceWorker' in navigator) {
133 | navigator.serviceWorker.ready
134 | .then(registration => {
135 | registration.unregister();
136 | })
137 | .catch(error => {
138 | console.error(error.message);
139 | });
140 | }
141 | }
142 |
--------------------------------------------------------------------------------
/examples/web/src/setupTests.js:
--------------------------------------------------------------------------------
1 | // jest-dom adds custom jest matchers for asserting on DOM nodes.
2 | // allows you to do things like:
3 | // expect(element).toHaveTextContent(/react/i)
4 | // learn more: https://github.com/testing-library/jest-dom
5 | import '@testing-library/jest-dom/extend-expect';
6 |
--------------------------------------------------------------------------------
/jest.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | collectCoverageFrom: ["src/**/*.{ts,tsx}"],
3 | coveragePathIgnorePatterns: ["./src/index.ts"],
4 | roots: ["/src"],
5 | testMatch: [
6 | "**/__tests__/**/*.+(ts|tsx|js)",
7 | "**/?(*.)+(spec|test).+(ts|tsx|js)",
8 | ],
9 | transform: {
10 | "^.+\\.(ts|tsx)$": "ts-jest",
11 | "^.+\\.js$": "babel-jest",
12 | },
13 | automock: false,
14 | setupFiles: ["./setupTests.js"],
15 | preset: "ts-jest/presets/js-with-babel",
16 | };
17 |
--------------------------------------------------------------------------------
/jest.rn.config.js:
--------------------------------------------------------------------------------
1 | // jest.config.js
2 | const { defaults: tsjPreset } = require("ts-jest/presets");
3 |
4 | module.exports = {
5 | ...tsjPreset,
6 | preset: "react-native",
7 | transform: {
8 | ...tsjPreset.transform,
9 | "\\.js$": "/node_modules/react-native/jest/preprocessor.js",
10 | },
11 | globals: {
12 | "ts-jest": {
13 | babelConfig: true,
14 | },
15 | },
16 | testPathIgnorePatterns: [
17 | "/src/__tests__/useTrigger.tsx",
18 | "/examples/native-use-pusher-example/__tests__/App.js",
19 | ],
20 | // This is the only part which you can keep
21 | // from the above linked tutorial's config:
22 | cacheDirectory: ".jest/cache",
23 | setupFiles: ["/setupTests.rn.js"],
24 | };
25 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "@harelpls/use-pusher",
3 | "version": "7.2.1",
4 | "description": "A wrapper around pusher-js for easy-as hooks in React.",
5 | "author": "@mayteio",
6 | "keywords": [
7 | "react",
8 | "react hooks",
9 | "pusher",
10 | "channels",
11 | "pusher-js",
12 | "websockets",
13 | "realtime messaging",
14 | "typescript"
15 | ],
16 | "license": "MIT",
17 | "repository": "https://github.com/mayteio/use-pusher",
18 | "files": [
19 | "dist",
20 | "react-native"
21 | ],
22 | "main": "dist/index.js",
23 | "module": "dist/index.es.js",
24 | "jsnext:main": "dist/index.es.js",
25 | "types": "dist/index.d.ts",
26 | "engines": {
27 | "node": ">=8",
28 | "npm": ">=5"
29 | },
30 | "scripts": {
31 | "test": "cross-env CI=1 yarn test:web && yarn test:native",
32 | "test:web": "jest --config=jest.config.js",
33 | "test:native": "JEST_ENV=rn jest --config=jest.rn.config.js",
34 | "build": "rimraf dist react-native && rollup -c",
35 | "start": "rollup -c -w",
36 | "types": "yarn types:web && yarn types:native",
37 | "types:web": "dts-bundle-generator -o ./dist/index.d.ts ./src/web/index.ts --external-imports pusher-js",
38 | "types:native": "dts-bundle-generator -o ./react-native/index.d.ts ./src/native/index.ts --external-imports=pusher-js",
39 | "docs": "typedoc --options ./typedoc.js ./src && netlify deploy --prod",
40 | "release": "yarn test && yarn build && yarn types && yarn publish"
41 | },
42 | "dependencies": {
43 | "dequal": "^2.0.1",
44 | "invariant": "^2.2.4",
45 | "pusher-js": "^7.3.0"
46 | },
47 | "peerDependencies": {
48 | "react": ">=16.9.0"
49 | },
50 | "devDependencies": {
51 | "@babel/core": "^7.8.6",
52 | "@babel/plugin-proposal-class-properties": "^7.10.1",
53 | "@babel/plugin-transform-flow-strip-types": "^7.10.1",
54 | "@babel/plugin-transform-object-assign": "^7.10.3",
55 | "@babel/preset-env": "^7.8.6",
56 | "@babel/preset-react": "^7.0.0",
57 | "@babel/runtime": "^7.3.1",
58 | "@react-native-community/netinfo": "^5.9.3",
59 | "@testing-library/react": "^10.4.8",
60 | "@testing-library/react-hooks": "^3.4.1",
61 | "@testing-library/react-native": "^7.0.2",
62 | "@types/invariant": "^2.2.30",
63 | "@types/jest": "^26.0.10",
64 | "@types/react": "^16.7.22",
65 | "@wessberg/rollup-plugin-ts": "^1.3.2",
66 | "babel-jest": "^26.3.0",
67 | "cross-env": "^7.0.2",
68 | "dts-bundle-generator": "^5.3.0",
69 | "gh-pages": "^3.1.0",
70 | "jest": "^26.4.0",
71 | "jest-fetch-mock": "^3.0.3",
72 | "pusher-js-mock": "mayteio/pusher-js-mock#feature/presence-channels-release",
73 | "react": "^16.9.0",
74 | "react-dom": "^16.9.0",
75 | "react-native": "^0.63.2",
76 | "react-native-typescript-transformer": "^1.2.13",
77 | "react-test-renderer": "^16.9.0",
78 | "rimraf": "^3.0.2",
79 | "rollup": "^2.26.3",
80 | "rollup-plugin-babel": "^4.3.3",
81 | "rollup-plugin-commonjs": "^10.0.2",
82 | "rollup-plugin-dts": "^1.1.6",
83 | "rollup-plugin-node-resolve": "^5.2.0",
84 | "rollup-plugin-peer-deps-external": "^2.2.0",
85 | "rollup-plugin-typescript2": "^0.27.2",
86 | "rollup-plugin-url": "^3.0.1",
87 | "ts-jest": "^26.2.0",
88 | "typedoc": "^0.18.0",
89 | "typescript": "^3.8.3"
90 | }
91 | }
92 |
--------------------------------------------------------------------------------
/rn-cli.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | getTransformModulePath() {
3 | return require.resolve("react-native-typescript-transformer");
4 | },
5 | getSourceExts() {
6 | return ["ts", "tsx"];
7 | },
8 | };
9 |
--------------------------------------------------------------------------------
/rollup.config.js:
--------------------------------------------------------------------------------
1 | import typescript from "rollup-plugin-typescript2";
2 | import commonjs from "rollup-plugin-commonjs";
3 | import external from "rollup-plugin-peer-deps-external";
4 | import resolve from "rollup-plugin-node-resolve";
5 | import url from "rollup-plugin-url";
6 | import babel from "rollup-plugin-babel";
7 | import ts from "@wessberg/rollup-plugin-ts";
8 |
9 | import pkg from "./package.json";
10 |
11 | const plugins = [
12 | external(),
13 | url({ exclude: ["**/*.svg"] }),
14 | resolve(),
15 | ts(),
16 | // typescript({
17 | // rollupCommonJSResolveHack: true,
18 | // clean: true,
19 | // exclude: ["./src/__tests__/*"],
20 | // }),
21 | // babel({
22 | // extensions: [".tsx"],
23 | // exclude: ["node_modules/**", "./src/__tests__"],
24 | // presets: ["@babel/env", "@babel/preset-react"],
25 | // }),
26 | commonjs(),
27 | ];
28 |
29 | export default [
30 | {
31 | input: "src/web/index.ts",
32 | external: ["pusher-js"],
33 | plugins,
34 | output: [
35 | {
36 | file: pkg.main,
37 | format: "cjs",
38 | exports: "named",
39 | sourcemap: true,
40 | },
41 | {
42 | file: pkg.module,
43 | format: "es",
44 | exports: "named",
45 | sourcemap: true,
46 | },
47 | {
48 | // build into our example app for testing with a real client
49 | file: "examples/web/src/use-pusher/index.js",
50 | format: "es",
51 | exports: "named",
52 | sourcemap: true,
53 | },
54 | ],
55 | },
56 | {
57 | input: "src/native/index.ts",
58 | external: ["pusher-js", "react-native"],
59 | plugins,
60 | output: [
61 | {
62 | // allows users to import from @harelpls/use-pusher/react-native
63 | file: "react-native/index.js",
64 | format: "cjs",
65 | exports: "named",
66 | sourcemap: true,
67 | },
68 | {
69 | file: "examples/native-use-pusher-example/use-pusher/native/index.js",
70 | format: "cjs",
71 | exports: "named",
72 | sourcemap: true,
73 | },
74 | ],
75 | },
76 | ];
77 |
--------------------------------------------------------------------------------
/setupTests.js:
--------------------------------------------------------------------------------
1 | global.fetch = require("jest-fetch-mock");
2 |
--------------------------------------------------------------------------------
/setupTests.rn.js:
--------------------------------------------------------------------------------
1 | import mockRNCNetInfo from "@react-native-community/netinfo/jest/netinfo-mock.js";
2 |
3 | jest.mock("@react-native-community/netinfo", () => mockRNCNetInfo);
4 |
--------------------------------------------------------------------------------
/src/__tests__/PusherProvider.test.tsx:
--------------------------------------------------------------------------------
1 | // import { PusherContextValues } from "../types";
2 | import React from "react";
3 |
4 | const Pusher = require(process.env.JEST_ENV === "rn"
5 | ? "pusher-js/react-native"
6 | : "pusher-js");
7 |
8 | const { PusherProvider } = require(process.env.JEST_ENV === "rn"
9 | ? "../native/PusherProvider"
10 | : "../web/PusherProvider");
11 |
12 | const { render } = require(process.env.JEST_ENV === "rn"
13 | ? "@testing-library/react-native"
14 | : "@testing-library/react");
15 |
16 | jest.mock(
17 | process.env.JEST_ENV === "rn" ? "pusher-js/react-native" : "pusher-js",
18 | () => jest.fn()
19 | );
20 |
21 | describe(" ", () => {
22 | beforeEach(() => {
23 | jest.resetAllMocks();
24 | });
25 |
26 | test("should throw warnings when key or cluster isn't present", () => {
27 | jest.spyOn(console, "error");
28 | const { rerender } = render(
29 |
30 | );
31 | expect(console.error).toHaveBeenCalledTimes(1);
32 | rerender( );
33 | expect(console.error).toHaveBeenCalledTimes(2);
34 | });
35 |
36 | test("should create no client if defer is passed, value is passed, or config hasn't changed", () => {
37 | const { rerender } = render(
38 |
39 | );
40 | expect(Pusher.prototype.constructor).toHaveBeenCalledTimes(0);
41 | rerender(
42 |
47 | );
48 | expect(Pusher.prototype.constructor).toHaveBeenCalledTimes(0);
49 | rerender(
50 |
55 | );
56 | rerender(
57 |
62 | );
63 | expect(Pusher.prototype.constructor).toHaveBeenCalledTimes(1);
64 | });
65 |
66 | // test("should create a new pusher client and pass that to context, along with the triggerEndpoint", () => {
67 | // jest.spyOn(console, "log");
68 | // render(
69 | //
70 | // <__PusherContext.Consumer>
71 | // {(value: any) => {
72 | // return ;
73 | // }}
74 | //
75 | //
76 | // );
77 | // expect(console.log).toHaveBeenCalledWith({
78 | // client: {},
79 | // triggerEndpoint: "endpoint",
80 | // });
81 | // });
82 | });
83 |
84 | // const Logger: React.FC<{ value: PusherContextValues }> = ({ value }) => {
85 | // console.log(value);
86 | // return null;
87 | // };
88 |
--------------------------------------------------------------------------------
/src/__tests__/useChannel.tsx:
--------------------------------------------------------------------------------
1 | import { PusherChannelMock, PusherMock } from "pusher-js-mock";
2 | import React from "react";
3 | import { renderHook } from "@testing-library/react-hooks";
4 | import { renderHookWithProvider } from "../testUtils";
5 | import { useChannel } from "../core/useChannel";
6 | import { __PusherContext } from "../core/PusherProvider";
7 | import { ChannelsProvider } from "../web";
8 |
9 | describe("useChannel()", () => {
10 | test("should return undefined when channelName is falsy", () => {
11 | const wrapper: React.FC = ({ children }) => (
12 | <__PusherContext.Provider value={{ client: {} as any }}>
13 | {children}
14 |
15 | );
16 | const { result } = renderHook(() => useChannel(""), {
17 | wrapper,
18 | });
19 |
20 | expect(result.current).toBeUndefined();
21 | });
22 |
23 | test("should return undefined if no pusher client present", () => {
24 | const wrapper: React.FC = ({ children }) => (
25 | <__PusherContext.Provider value={{ client: undefined }}>
26 | {children}
27 |
28 | );
29 | const { result } = renderHook(() => useChannel("public-channel"), {
30 | wrapper,
31 | });
32 |
33 | expect(result.current).toBeUndefined();
34 | });
35 |
36 | test("should return instance of channel", async () => {
37 | const { result } = await renderHookWithProvider(() =>
38 | useChannel("public-channel")
39 | );
40 | expect(result.current).toBeInstanceOf(PusherChannelMock);
41 | });
42 |
43 | test("should unsubscribe on unmount", async () => {
44 | const client = new PusherMock("key");
45 | client.unsubscribe = jest.fn();
46 | const wrapper: React.FC = ({ children, ...props }) => (
47 | <__PusherContext.Provider value={{ client: client as any }} {...props}>
48 | {children}
49 |
50 | );
51 | const { unmount } = renderHook(() => useChannel("public-channel"), {
52 | wrapper,
53 | });
54 | unmount();
55 |
56 | expect(client.unsubscribe).toHaveBeenCalled();
57 | });
58 | });
59 |
--------------------------------------------------------------------------------
/src/__tests__/useClientTrigger.tsx:
--------------------------------------------------------------------------------
1 | import { Channel } from "pusher-js";
2 | import { PusherPresenceChannelMock } from "pusher-js-mock";
3 | import { renderHook } from "@testing-library/react-hooks";
4 | import { useClientTrigger } from "../core/useClientTrigger";
5 |
6 | describe("useClientTrigger()", () => {
7 | test("should trigger client events on the channel", async () => {
8 | const listener = jest.fn();
9 | const channel = new PusherPresenceChannelMock();
10 | channel.bind("event", listener);
11 | const { result } = renderHook(() =>
12 | useClientTrigger((channel as unknown) as Channel)
13 | );
14 |
15 | result.current("event", {});
16 | expect(listener).toHaveBeenCalledWith({});
17 | });
18 | });
19 |
--------------------------------------------------------------------------------
/src/__tests__/useEvent.tsx:
--------------------------------------------------------------------------------
1 | import { Channel, PresenceChannel } from "pusher-js";
2 | import { PusherChannelMock, PusherPresenceChannelMock } from "pusher-js-mock";
3 | import { renderHook } from "@testing-library/react-hooks";
4 | import { useEvent } from "../core/useEvent";
5 |
6 | describe("useEvent()", () => {
7 | test("should bind to events when the hook is called", () => {
8 | const listener = jest.fn();
9 | const channel = new PusherChannelMock();
10 | const { unmount } = renderHook(() =>
11 | useEvent((channel as unknown) as Channel, "event", listener)
12 | );
13 | channel.emit("event", {});
14 | expect(listener).toHaveBeenCalledWith({});
15 |
16 | // test unbinding
17 | unmount();
18 | channel.emit("event", {});
19 | expect(listener).toHaveBeenCalledTimes(1);
20 | });
21 |
22 | test("should not bind when there is no channel", () => {
23 | const listener = jest.fn();
24 | const channel = new PusherChannelMock();
25 | renderHook(() => useEvent(undefined, "event", listener));
26 | channel.emit("event", {});
27 | expect(listener).not.toHaveBeenCalled();
28 | });
29 |
30 | /** pusher-js-mock needs to be updated to test this */
31 | test.skip("should accept metadata from presence channels", () => {
32 | const listener = jest.fn();
33 | const channel = new PusherPresenceChannelMock();
34 | renderHook(() =>
35 | useEvent(
36 | (channel as unknown) as PresenceChannel,
37 | "presence-event",
38 | listener
39 | )
40 | );
41 |
42 | // @ts-ignore
43 | channel.emit("presence-event", {}, { user_id: "my-id" });
44 | });
45 | });
46 |
--------------------------------------------------------------------------------
/src/__tests__/usePresenceChannel.tsx:
--------------------------------------------------------------------------------
1 | import {
2 | actAndFlushPromises,
3 | makeAuthPusherConfig,
4 | renderHookWithProvider,
5 | } from "../testUtils";
6 |
7 | import { PusherMock } from "pusher-js-mock";
8 | import { act } from "@testing-library/react-hooks";
9 | import {
10 | usePresenceChannel,
11 | SET_STATE,
12 | presenceChannelReducer,
13 | ADD_MEMBER,
14 | REMOVE_MEMBER,
15 | } from "../core/usePresenceChannel";
16 | import { __PusherContext } from "../core/PusherProvider";
17 |
18 | describe("presenceChannelReducer", () => {
19 | /** Default state */
20 | const defaultState = {
21 | members: {},
22 | count: 0,
23 | me: undefined,
24 | myID: undefined,
25 | };
26 |
27 | test(SET_STATE, () => {
28 | const state = presenceChannelReducer(defaultState, {
29 | type: SET_STATE,
30 | payload: { count: 1 },
31 | });
32 | expect(state.count).toBe(1);
33 | });
34 |
35 | test(ADD_MEMBER, () => {
36 | const state = presenceChannelReducer(defaultState, {
37 | type: ADD_MEMBER,
38 | payload: { id: "their-id", info: {} },
39 | });
40 | expect(state.members).toEqual({ "their-id": {} });
41 | expect(state.count).toBe(1);
42 | });
43 |
44 | test(REMOVE_MEMBER, () => {
45 | const state = presenceChannelReducer(
46 | { ...defaultState, members: { "their-id": {} }, count: 1 },
47 | { type: REMOVE_MEMBER, payload: { id: "their-id" } }
48 | );
49 | expect(state.members).toEqual({});
50 | expect(state.count).toBe(0);
51 | });
52 | });
53 |
54 | describe("usePresenceChannel()", () => {
55 | test('should throw an error if channelName doesn\'t have "presence-" in it', async () => {
56 | const { result } = await renderHookWithProvider(
57 | () => usePresenceChannel("public-channel"),
58 | makeAuthPusherConfig()
59 | );
60 | expect(result.error.message).toBe(
61 | "Presence channels should use prefix 'presence-' in their name. Use the useChannel hook instead."
62 | );
63 | });
64 |
65 | test("should bind to pusher events and unbind on mount", async () => {
66 | const { result, unmount } = await renderHookWithProvider(
67 | () => usePresenceChannel("presence-channel"),
68 | makeAuthPusherConfig()
69 | );
70 |
71 | const channel = result.current.channel;
72 | expect(channel).toBeDefined();
73 | channel &&
74 | expect(channel.callbacks["pusher:subscription_succeeded"]).toHaveLength(
75 | 1
76 | );
77 | channel && expect(channel.callbacks["pusher:member_added"]).toHaveLength(1);
78 | channel &&
79 | expect(channel.callbacks["pusher:member_removed"]).toHaveLength(1);
80 |
81 | unmount();
82 | channel &&
83 | expect(channel.callbacks["pusher:subscription_succeeded"]).toHaveLength(
84 | 0
85 | );
86 | channel && expect(channel.callbacks["pusher:member_added"]).toHaveLength(0);
87 | channel &&
88 | expect(channel.callbacks["pusher:member_removed"]).toHaveLength(0);
89 | });
90 |
91 | test("should return new member list when members are added and remove them when they unsubscribe", async () => {
92 | const { result } = await renderHookWithProvider(
93 | () => usePresenceChannel("presence-channel"),
94 | makeAuthPusherConfig()
95 | );
96 |
97 | expect(result.current.members).toEqual({ "my-id": {} });
98 | expect(result.current.myID).toEqual("my-id");
99 | expect(result.current.me).toEqual({ id: "my-id", info: {} });
100 | expect(result.current.count).toBe(1);
101 |
102 | let otherClient: PusherMock;
103 | await act(async () => {
104 | otherClient = new PusherMock("key", makeAuthPusherConfig("your-id"));
105 | otherClient.subscribe("presence-channel");
106 | await actAndFlushPromises();
107 | });
108 |
109 | expect(result.current.members).toEqual({ "my-id": {}, "your-id": {} });
110 | expect(result.current.count).toBe(2);
111 |
112 | await act(async () => {
113 | otherClient.unsubscribe("presence-channel");
114 | });
115 | expect(result.current.members).toEqual({ "my-id": {} });
116 | expect(result.current.count).toBe(1);
117 | });
118 | });
119 |
--------------------------------------------------------------------------------
/src/__tests__/usePusher.test.tsx:
--------------------------------------------------------------------------------
1 | import { renderHook } from "@testing-library/react-hooks";
2 | import Pusher from "pusher-js";
3 | import React from "react";
4 |
5 | import { __PusherContext } from "../core/PusherProvider";
6 | import { NOT_IN_CONTEXT_WARNING, usePusher } from "../core/usePusher";
7 |
8 | describe("usePusher()", () => {
9 | test("should warn when outside provider", () => {
10 | jest.spyOn(console, "warn");
11 | renderHook(() => usePusher());
12 | expect(console.warn).toHaveBeenCalledWith(NOT_IN_CONTEXT_WARNING);
13 | });
14 |
15 | test("should return context values of PusherProvider", () => {
16 | const client = {} as Pusher;
17 | const wrapper: React.FC = ({ children }) => (
18 | <__PusherContext.Provider value={{ client }}>
19 | {children}
20 |
21 | );
22 | const { result } = renderHook(() => usePusher(), { wrapper });
23 | expect(result.current.client).toBe(client);
24 | });
25 | });
26 |
--------------------------------------------------------------------------------
/src/__tests__/useTrigger.tsx:
--------------------------------------------------------------------------------
1 | import "jest-fetch-mock";
2 | import React from "react";
3 | import Pusher from "pusher-js";
4 | import { PusherMock } from "pusher-js-mock";
5 | import { renderHook } from "@testing-library/react-hooks";
6 | import { __PusherContext } from "../core/PusherProvider";
7 | import { NO_AUTH_HEADERS_WARNING, useTrigger } from "../core/useTrigger";
8 |
9 | describe("useTrigger()", () => {
10 | beforeEach(() => {
11 | // @ts-ignore
12 | fetch.resetMocks();
13 | });
14 | test("should trigger a fetch event on use and warn about no headers", async () => {
15 | jest.spyOn(console, "warn");
16 | const wrapper: React.FC = ({ children }) => (
17 | <__PusherContext.Provider
18 | value={{
19 | client: (new PusherMock("key") as unknown) as Pusher,
20 | triggerEndpoint: "http://example.com",
21 | }}
22 | >
23 | {children}
24 |
25 | );
26 |
27 | const { result } = await renderHook(() => useTrigger("presence-channel"), {
28 | wrapper,
29 | });
30 |
31 | result.current("event", {});
32 | // @ts-ignore
33 | expect(fetch.mock.calls.length).toBe(1);
34 | expect(console.warn).toHaveBeenCalledWith(NO_AUTH_HEADERS_WARNING);
35 | });
36 | test("should trigger a fetch event on use and warn", async () => {
37 | jest.spyOn(console, "warn");
38 | const wrapper: React.FC = ({ children }) => (
39 | <__PusherContext.Provider
40 | value={{
41 | client: (new PusherMock("key", {
42 | auth: {
43 | headers: {
44 | Authorization: "Bearer token",
45 | },
46 | },
47 | }) as unknown) as Pusher,
48 | triggerEndpoint: "http://example.com",
49 | }}
50 | >
51 | {children}
52 |
53 | );
54 |
55 | const { result } = await renderHook(() => useTrigger("public-channel"), {
56 | wrapper,
57 | });
58 |
59 | result.current("event", {});
60 | // @ts-ignore
61 | expect(fetch.mock.calls[0]).toEqual([
62 | "http://example.com",
63 | {
64 | method: "POST",
65 | body: JSON.stringify({
66 | channelName: "public-channel",
67 | eventName: "event",
68 | data: {},
69 | }),
70 | headers: {
71 | Authorization: "Bearer token",
72 | },
73 | },
74 | ]);
75 | });
76 | });
77 |
--------------------------------------------------------------------------------
/src/core/ChannelsProvider.tsx:
--------------------------------------------------------------------------------
1 | import { Channel, PresenceChannel } from "pusher-js";
2 | import React, { useCallback, useRef } from "react";
3 | import { ChannelsContextValues } from "./types";
4 |
5 | import { usePusher } from "./usePusher";
6 |
7 | // context setup
8 | const ChannelsContext = React.createContext({});
9 | export const __ChannelsContext = ChannelsContext;
10 |
11 | type AcceptedChannels = Channel | PresenceChannel;
12 | type ConnectedChannels = {
13 | [channelName: string]: AcceptedChannels[];
14 | };
15 |
16 | /**
17 | * Provider that creates your channels instances and provides it to child hooks throughout your app.
18 | */
19 |
20 | export const ChannelsProvider: React.FC<{ children: React.ReactNode }> = ({
21 | children,
22 | }) => {
23 | const { client } = usePusher();
24 | const connectedChannels = useRef({});
25 |
26 | const subscribe = useCallback(
27 | (channelName: string) => {
28 | /** Return early if there's no client */
29 | if (!client || !channelName) return;
30 |
31 | /** Subscribe to channel and set it in state */
32 | const pusherChannel = client.subscribe(channelName);
33 | connectedChannels.current[channelName] = [
34 | ...(connectedChannels.current[channelName] || []),
35 | pusherChannel,
36 | ];
37 | return pusherChannel as T;
38 | },
39 | [client, connectedChannels]
40 | );
41 |
42 | const unsubscribe = useCallback(
43 | (channelName: string) => {
44 | /** Return early if there's no props */
45 | if (
46 | !client ||
47 | !channelName ||
48 | !(channelName in connectedChannels.current)
49 | )
50 | return;
51 | /** If just one connection, unsubscribe totally*/
52 | if (connectedChannels.current[channelName].length === 1) {
53 | client.unsubscribe(channelName);
54 | delete connectedChannels.current[channelName];
55 | } else {
56 | connectedChannels.current[channelName].pop();
57 | }
58 | },
59 | [connectedChannels, client]
60 | );
61 |
62 | const getChannel = useCallback(
63 | (channelName: string) => {
64 | /** Return early if there's no client */
65 | if (
66 | !client ||
67 | !channelName ||
68 | !(channelName in connectedChannels.current)
69 | )
70 | return;
71 | /** Return channel */
72 | return connectedChannels.current[channelName][0] as T;
73 | },
74 | [connectedChannels, client]
75 | );
76 |
77 | return (
78 |
85 | {children}
86 |
87 | );
88 | };
89 |
--------------------------------------------------------------------------------
/src/core/PusherProvider.tsx:
--------------------------------------------------------------------------------
1 | import { Options } from "pusher-js";
2 | import React, { useEffect, useMemo, useRef, useState } from "react";
3 | import { dequal } from "dequal";
4 | import { PusherContextValues, PusherProviderProps } from "./types";
5 | import { ChannelsProvider } from "./ChannelsProvider";
6 |
7 | // context setup
8 | const PusherContext = React.createContext({});
9 | export const __PusherContext = PusherContext;
10 |
11 | /**
12 | * Provider that creates your pusher instance and provides it to child hooks throughout your app.
13 | * Note, you can pass in value={{}} as a prop if you'd like to override the pusher client passed.
14 | * This is handy when simulating pusher locally, or for testing.
15 | * @param props Config for Pusher client
16 | */
17 |
18 | export const CorePusherProvider: React.FC = ({
19 | clientKey,
20 | cluster,
21 | triggerEndpoint,
22 | defer = false,
23 | children,
24 | _PusherRuntime,
25 | ...props
26 | }) => {
27 | // errors when required props are not passed.
28 | useEffect(() => {
29 | if (!clientKey) console.error("A client key is required for pusher");
30 | if (!cluster) console.error("A cluster is required for pusher");
31 | }, [clientKey, cluster]);
32 |
33 | const config: Options = useMemo(
34 | () => ({ cluster, ...props }),
35 | [cluster, props]
36 | );
37 |
38 | // track config for comparison
39 | const previousConfig = useRef(props);
40 | useEffect(() => {
41 | previousConfig.current = props;
42 | });
43 | const [client, setClient] = useState();
44 |
45 | useEffect(() => {
46 | // Skip creation of client if deferring, a value prop is passed, or config props are the same.
47 | if (
48 | !_PusherRuntime ||
49 | defer ||
50 | !clientKey ||
51 | props.value ||
52 | (dequal(previousConfig.current, props) && client !== undefined)
53 | ) {
54 | return;
55 | }
56 |
57 | setClient(new _PusherRuntime(clientKey, config));
58 | }, [client, clientKey, props, defer, _PusherRuntime, config]);
59 |
60 | return (
61 |
68 | {children}
69 |
70 | );
71 | };
72 |
--------------------------------------------------------------------------------
/src/core/types.d.ts:
--------------------------------------------------------------------------------
1 | import {
2 | Channel,
3 | default as Pusher,
4 | Options,
5 | PresenceChannel,
6 | } from "pusher-js";
7 | import * as React from "react";
8 | import "jest-fetch-mock";
9 |
10 | export interface PusherContextValues {
11 | // client?: React.MutableRefObject;
12 | client?: Pusher;
13 | triggerEndpoint?: string;
14 | }
15 |
16 | export interface ChannelsContextValues {
17 | subscribe?: (
18 | channelName: string
19 | ) => T | undefined;
20 | unsubscribe?: (
21 | channelName: string
22 | ) => void;
23 | getChannel?: (
24 | channelName: string
25 | ) => T | undefined;
26 | }
27 |
28 | export interface PusherProviderProps extends Options {
29 | _PusherRuntime?: typeof Pusher;
30 | children: React.ReactNode;
31 | clientKey: string | undefined;
32 | cluster:
33 | | "mt1"
34 | | "us2"
35 | | "us3"
36 | | "eu"
37 | | "ap1"
38 | | "ap2"
39 | | "ap3"
40 | | "ap4"
41 | | string
42 | | undefined;
43 | triggerEndpoint?: string;
44 | defer?: boolean;
45 | // for testing purposes
46 | value?: PusherContextValues;
47 | }
48 |
--------------------------------------------------------------------------------
/src/core/useChannel.ts:
--------------------------------------------------------------------------------
1 | import { Channel, PresenceChannel } from "pusher-js";
2 | import { useEffect, useState } from "react";
3 | import { useChannels } from "./useChannels";
4 |
5 | /**
6 | * Subscribe to a channel
7 | *
8 | * @param channelName The name of the channel you want to subscribe to.
9 | * @typeparam Type of channel you're subscribing to. Can be one of `Channel` or `PresenceChannel` from `pusher-js`.
10 | * @returns Instance of the channel you just subscribed to.
11 | *
12 | * @example
13 | * ```javascript
14 | * const channel = useChannel("my-channel")
15 | * channel.bind('some-event', () => {})
16 | * ```
17 | */
18 |
19 | export function useChannel(
20 | channelName: string | undefined
21 | ) {
22 | const [channel, setChannel] = useState();
23 | const { subscribe, unsubscribe } = useChannels();
24 |
25 | useEffect(() => {
26 | if (!channelName || !subscribe || !unsubscribe) return;
27 |
28 | const _channel = subscribe(channelName);
29 | setChannel(_channel);
30 | return () => unsubscribe(channelName);
31 | }, [channelName, subscribe, unsubscribe]);
32 |
33 | /** Return the channel for use. */
34 | return channel;
35 | }
36 |
--------------------------------------------------------------------------------
/src/core/useChannels.tsx:
--------------------------------------------------------------------------------
1 | import { useContext, useEffect } from "react";
2 | import { __ChannelsContext } from "./ChannelsProvider";
3 | import { ChannelsContextValues } from "./types";
4 |
5 | /**
6 | * Provides access to the channels global provider.
7 | */
8 |
9 | export function useChannels() {
10 | const context = useContext(__ChannelsContext);
11 | useEffect(() => {
12 | if (!context || !Object.keys(context).length)
13 | console.warn(NOT_IN_CONTEXT_WARNING);
14 | }, [context]);
15 | return context;
16 | }
17 |
18 | const NOT_IN_CONTEXT_WARNING =
19 | "No Channels context. Did you forget to wrap your app in a ?";
20 |
--------------------------------------------------------------------------------
/src/core/useClientTrigger.ts:
--------------------------------------------------------------------------------
1 | import { Channel, PresenceChannel } from "pusher-js";
2 |
3 | import invariant from "invariant";
4 | import { useCallback } from "react";
5 |
6 | /**
7 | *
8 | * @param channel the channel you'd like to trigger clientEvents on. Get this from [[useChannel]] or [[usePresenceChannel]].
9 | * @typeparam TData shape of the data you're sending with the event.
10 | * @returns A memoized trigger function that will perform client events on the channel.
11 | * @example
12 | * ```javascript
13 | * const channel = useChannel('my-channel');
14 | * const trigger = useClientTrigger(channel)
15 | *
16 | * const handleClick = () => trigger('some-client-event', {});
17 | * ```
18 | */
19 | export function useClientTrigger(
20 | channel: Channel | PresenceChannel | undefined
21 | ) {
22 | channel &&
23 | invariant(
24 | channel.name.match(/(private-|presence-)/gi),
25 | "Channel provided to useClientTrigger wasn't private or presence channel. Client events only work on these types of channels."
26 | );
27 |
28 | // memoize trigger so it's not being created every render
29 | const trigger = useCallback(
30 | (eventName: string, data: TData) => {
31 | invariant(eventName, "Must pass event name to trigger a client event.");
32 | channel && channel.trigger(eventName, data);
33 | },
34 | [channel]
35 | );
36 |
37 | return trigger;
38 | }
39 |
--------------------------------------------------------------------------------
/src/core/useEvent.ts:
--------------------------------------------------------------------------------
1 | import { Channel, PresenceChannel } from "pusher-js";
2 |
3 | import invariant from "invariant";
4 | import { useEffect } from "react";
5 |
6 | /**
7 | * Subscribes to a channel event and registers a callback.
8 | * @param channel Pusher channel to bind to
9 | * @param eventName Name of event to bind to
10 | * @param callback Callback to call on a new event
11 | */
12 | export function useEvent(
13 | channel: Channel | PresenceChannel | undefined,
14 | eventName: string,
15 | callback: (data?: D, metadata?: { user_id: string }) => void
16 | ) {
17 | // error when required arguments aren't passed.
18 | invariant(eventName, "Must supply eventName and callback to onEvent");
19 | invariant(callback, "Must supply callback to onEvent");
20 |
21 | // bind and unbind events whenever the channel, eventName or callback changes.
22 | useEffect(() => {
23 | if (channel === undefined) {
24 | return;
25 | } else channel.bind(eventName, callback);
26 | return () => {
27 | channel.unbind(eventName, callback);
28 | };
29 | }, [channel, eventName, callback]);
30 | }
31 |
--------------------------------------------------------------------------------
/src/core/usePresenceChannel.ts:
--------------------------------------------------------------------------------
1 | import { Members, PresenceChannel } from "pusher-js";
2 | import { useEffect, useReducer } from "react";
3 |
4 | import invariant from "invariant";
5 | import { useChannel } from "./useChannel";
6 |
7 | /**
8 | * Subscribe to presence channel events and get members back
9 | *
10 | * @param channelName name of presence the channel. Should have `presence-` suffix.
11 | * @returns Object with `channel`, `members` and `myID` properties.
12 | *
13 | * @example
14 | * ```javascript
15 | * const { channel, members, myID } = usePresenceChannel("presence-my-channel");
16 | * ```
17 | */
18 |
19 | /** Internal state */
20 | type PresenceChannelState = {
21 | members: Record;
22 | me: Record | undefined;
23 | myID: string | undefined;
24 | count: number;
25 | };
26 |
27 | type MemberAction = { id: string; info?: Record };
28 |
29 | type ReducerAction = {
30 | type: typeof SET_STATE | typeof ADD_MEMBER | typeof REMOVE_MEMBER;
31 | payload: Partial | MemberAction;
32 | };
33 |
34 | /** Hook return value */
35 | interface usePresenceChannelValue extends Partial {
36 | channel?: PresenceChannel;
37 | }
38 |
39 | /** Presence channel reducer to keep track of state */
40 | export const SET_STATE = "set-state";
41 | export const ADD_MEMBER = "add-member";
42 | export const REMOVE_MEMBER = "remove-member";
43 | export const presenceChannelReducer = (
44 | state: PresenceChannelState,
45 | { type, payload }: ReducerAction
46 | ) => {
47 | switch (type) {
48 | /** Generic setState */
49 | case SET_STATE:
50 | return { ...state, ...payload };
51 |
52 | /** Member added */
53 | case ADD_MEMBER:
54 | const { id: addedMemberId, info } = payload as MemberAction;
55 | return {
56 | ...state,
57 | count: state.count + 1,
58 | members: {
59 | ...state.members,
60 | [addedMemberId]: info,
61 | },
62 | };
63 |
64 | /** Member removed */
65 | case REMOVE_MEMBER:
66 | const { id: removedMemberId } = payload as MemberAction;
67 | const members = { ...state.members };
68 | delete members[removedMemberId];
69 | return {
70 | ...state,
71 | count: state.count - 1,
72 | members: {
73 | ...members,
74 | },
75 | };
76 | }
77 | };
78 |
79 | export function usePresenceChannel(
80 | channelName: string | undefined
81 | ): usePresenceChannelValue {
82 | // errors for missing arguments
83 | if (channelName) {
84 | invariant(
85 | channelName.includes("presence-"),
86 | "Presence channels should use prefix 'presence-' in their name. Use the useChannel hook instead."
87 | );
88 | }
89 |
90 | /** Store internal channel state */
91 | const [state, dispatch] = useReducer(presenceChannelReducer, {
92 | members: {},
93 | me: undefined,
94 | myID: undefined,
95 | count: 0,
96 | });
97 |
98 | // bind and unbind member events events on our channel
99 | const channel = useChannel(channelName);
100 | useEffect(() => {
101 | if (channel) {
102 | // Get membership info on successful subscription
103 | const handleSubscriptionSuccess = (members: Members) => {
104 | dispatch({
105 | type: SET_STATE,
106 | payload: {
107 | members: members.members,
108 | myID: members.myID,
109 | me: members.me,
110 | count: Object.keys(members.members).length,
111 | },
112 | });
113 | };
114 |
115 | // Add member to the members object
116 | const handleAdd = (member: any) => {
117 | dispatch({
118 | type: ADD_MEMBER,
119 | payload: member,
120 | });
121 | };
122 |
123 | // Remove member from the members object
124 | const handleRemove = (member: any) => {
125 | dispatch({
126 | type: REMOVE_MEMBER,
127 | payload: member,
128 | });
129 | };
130 |
131 | // bind to all member addition/removal events
132 | channel.bind("pusher:subscription_succeeded", handleSubscriptionSuccess);
133 | channel.bind("pusher:member_added", handleAdd);
134 | channel.bind("pusher:member_removed", handleRemove);
135 |
136 | // cleanup
137 | return () => {
138 | channel.unbind(
139 | "pusher:subscription_succeeded",
140 | handleSubscriptionSuccess
141 | );
142 | channel.unbind("pusher:member_added", handleAdd);
143 | channel.unbind("pusher:member_removed", handleRemove);
144 | };
145 | }
146 |
147 | // to make typescript happy.
148 | return () => {};
149 | }, [channel]);
150 |
151 | return {
152 | channel,
153 | ...state,
154 | };
155 | }
156 |
--------------------------------------------------------------------------------
/src/core/usePusher.ts:
--------------------------------------------------------------------------------
1 | import { useContext, useEffect } from "react";
2 |
3 | import { PusherContextValues } from "./types";
4 | import { __PusherContext } from "./PusherProvider";
5 |
6 | /**
7 | * Provides access to the pusher client instance.
8 | *
9 | * @returns a `MutableRefObject`. The instance is held by a `useRef()` hook.
10 | * @example
11 | * ```javascript
12 | * const { client } = usePusher();
13 | * client.current.subscribe('my-channel');
14 | * ```
15 | */
16 | export function usePusher() {
17 | const context = useContext(__PusherContext);
18 | useEffect(() => {
19 | if (!Object.keys(context).length) console.warn(NOT_IN_CONTEXT_WARNING);
20 | }, [context]);
21 | return context;
22 | }
23 |
24 | export const NOT_IN_CONTEXT_WARNING =
25 | "No Pusher context. Did you forget to wrap your app in a ?";
26 |
--------------------------------------------------------------------------------
/src/core/useTrigger.ts:
--------------------------------------------------------------------------------
1 | import invariant from "invariant";
2 | import { useCallback } from "react";
3 | import { useChannel } from "./useChannel";
4 | import { usePusher } from "./usePusher";
5 |
6 | /**
7 | * Hook to provide a trigger function that calls the server defined in `PusherProviderProps.triggerEndpoint` using `fetch`.
8 | * Any `auth?.headers` in the config object will be passed with the `fetch` call.
9 | *
10 | * @param channelName name of channel to call trigger on
11 | * @typeparam TData shape of the data you're sending with the event
12 | *
13 | * @example
14 | * ```typescript
15 | * const trigger = useTrigger<{message: string}>('my-channel');
16 | * trigger('my-event', {message: 'hello'});
17 | * ```
18 | */
19 | export function useTrigger(channelName: string) {
20 | const { client, triggerEndpoint } = usePusher();
21 |
22 | // you can't use this if you haven't supplied a triggerEndpoint.
23 | invariant(
24 | triggerEndpoint,
25 | "No trigger endpoint specified to . Cannot trigger an event."
26 | );
27 |
28 | // subscribe to the channel we'll be triggering to.
29 | useChannel(channelName);
30 |
31 | // memoized trigger function to return
32 | const trigger = useCallback(
33 | (eventName: string, data?: TData) => {
34 | const fetchOptions: RequestInit = {
35 | method: "POST",
36 | body: JSON.stringify({ channelName, eventName, data }),
37 | };
38 |
39 | // @ts-expect-error deprecated since 7.1.0, but still supported for backwards compatibility
40 | // now it should use channelAuthorization instead
41 | if (client && client.config?.auth) {
42 | // @ts-expect-error deprecated
43 | fetchOptions.headers = client.config.auth.headers;
44 | } else {
45 | console.warn(NO_AUTH_HEADERS_WARNING);
46 | }
47 |
48 | return fetch(triggerEndpoint, fetchOptions);
49 | },
50 | [client, triggerEndpoint, channelName]
51 | );
52 |
53 | return trigger;
54 | }
55 |
56 | export const NO_AUTH_HEADERS_WARNING =
57 | "No auth parameters supplied to . Your events will be unauthenticated.";
58 |
--------------------------------------------------------------------------------
/src/native/PusherProvider.tsx:
--------------------------------------------------------------------------------
1 | import React from "react";
2 | import { default as PusherReactNative } from "pusher-js/react-native";
3 | import { CorePusherProvider } from "../core/PusherProvider";
4 | import { PusherProviderProps } from "../core/types";
5 |
6 | /** Wrapper around the core PusherProvider that passes in the Pusher react-native lib */
7 | export const PusherProvider: React.FC = (props) => (
8 |
9 | );
10 |
--------------------------------------------------------------------------------
/src/native/index.ts:
--------------------------------------------------------------------------------
1 | // hooks for prod
2 | export * from "../core/usePusher";
3 | export * from "../core/useChannel";
4 | export * from "../core/usePresenceChannel";
5 | export * from "../core/useEvent";
6 | export * from "../core/useClientTrigger";
7 | export * from "../core/useTrigger";
8 | export * from "../core/useChannels";
9 | export * from "../core/ChannelsProvider";
10 | export * from "./PusherProvider";
11 | export { __PusherContext } from "../core/PusherProvider";
12 |
--------------------------------------------------------------------------------
/src/react-app-env.d.ts:
--------------------------------------------------------------------------------
1 | ///
2 |
--------------------------------------------------------------------------------
/src/setupTests.js:
--------------------------------------------------------------------------------
1 | global.fetch = require("jest-fetch-mock");
2 |
--------------------------------------------------------------------------------
/src/testUtils.tsx:
--------------------------------------------------------------------------------
1 | import { renderHook, act } from "@testing-library/react-hooks";
2 | import React from "react";
3 |
4 | import Pusher from "pusher-js";
5 | import { PusherMock } from "pusher-js-mock";
6 | import { __PusherContext } from "./core/PusherProvider";
7 | import { ChannelsProvider } from "./core/ChannelsProvider";
8 |
9 | /**
10 | * Flushes async promises in mocks
11 | */
12 | export const actAndFlushPromises = async () =>
13 | await act(async () => await new Promise(setImmediate));
14 |
15 | /**
16 | * Does a bit of setup for us so we don't have to repeat ourselves
17 | * @param hook the hook you want to render, i.e. () => useHook()
18 | * @param clientConfig the client config passed to PusherMock
19 | */
20 | export async function renderHookWithProvider(
21 | hook: () => T,
22 | clientConfig: Record = {}
23 | ) {
24 | const client = new PusherMock("key", clientConfig) as unknown;
25 | const wrapper: React.FC = ({ children, ...props }) => (
26 | <__PusherContext.Provider value={{ client: client as Pusher }} {...props}>
27 | {children}
28 |
29 | );
30 | const result = renderHook(hook, { wrapper });
31 | await actAndFlushPromises();
32 | return result;
33 | }
34 |
35 | /**
36 | * Generates basic Pusher config with authorizer
37 | * @param id the id for the client
38 | * @param info the info object for the client
39 | */
40 | export const makeAuthPusherConfig = (id: string = "my-id", info: any = {}) => ({
41 | authorizer: () => ({
42 | authorize: (
43 | socketId: string,
44 | callback: (errored: boolean, info: any) => void
45 | ) => callback(socketId === "errored", { id, info }),
46 | }),
47 | });
48 |
--------------------------------------------------------------------------------
/src/web/PusherProvider.tsx:
--------------------------------------------------------------------------------
1 | import React from "react";
2 | import { default as Pusher } from "pusher-js";
3 | import { CorePusherProvider } from "../core/PusherProvider";
4 | import { PusherProviderProps } from "../core/types";
5 |
6 | /** Wrapper around the core PusherProvider that passes in the Pusher lib */
7 | export const PusherProvider: React.FC = (props) => (
8 |
9 | );
10 |
--------------------------------------------------------------------------------
/src/web/index.ts:
--------------------------------------------------------------------------------
1 | // hooks for prod
2 | export * from "../core/usePusher";
3 | export * from "../core/useChannel";
4 | export * from "../core/usePresenceChannel";
5 | export * from "../core/useEvent";
6 | export * from "../core/useClientTrigger";
7 | export * from "../core/useChannels";
8 | export * from "../core/useTrigger";
9 | export * from "../core/ChannelsProvider";
10 | export * from "./PusherProvider";
11 | export { __PusherContext } from "../core/PusherProvider";
12 |
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "outDir": "build",
4 | "module": "esnext",
5 | "target": "es5",
6 | "lib": ["es6", "dom", "es2016", "es2017"],
7 | "sourceMap": true,
8 | "allowJs": false,
9 | "jsx": "react",
10 | "moduleResolution": "node",
11 | "forceConsistentCasingInFileNames": true,
12 | "noImplicitReturns": true,
13 | "noImplicitThis": true,
14 | "noImplicitAny": true,
15 | "strictNullChecks": true,
16 | "suppressImplicitAnyIndexErrors": true,
17 | "noUnusedLocals": true,
18 | "noUnusedParameters": true,
19 | "skipLibCheck": true,
20 | "esModuleInterop": true,
21 | "allowSyntheticDefaultImports": true,
22 | "strict": true,
23 | "resolveJsonModule": true,
24 | "isolatedModules": true,
25 | "declaration": false,
26 | "noEmit": true
27 | },
28 | "include": ["src/core/*.*", "src/web/*/*", "node_modules/jest-fetch-mock"],
29 | "exclude": [
30 | "/node_modules",
31 | "/build",
32 | "/dist",
33 | "/react-native",
34 | "/examples",
35 | "rollup.config.js",
36 | "src/__tests__/*"
37 | ]
38 | }
39 |
--------------------------------------------------------------------------------
/tsconfig.rn.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "outDir": "build",
4 | "module": "esnext",
5 | "target": "es5",
6 | "lib": ["es6", "dom", "es2016", "es2017"],
7 | "sourceMap": true,
8 | "allowJs": false,
9 | "jsx": "react",
10 | "moduleResolution": "node",
11 | "forceConsistentCasingInFileNames": true,
12 | "noImplicitReturns": true,
13 | "noImplicitThis": true,
14 | "noImplicitAny": true,
15 | "strictNullChecks": true,
16 | "suppressImplicitAnyIndexErrors": true,
17 | "noUnusedLocals": true,
18 | "noUnusedParameters": true,
19 | "skipLibCheck": true,
20 | "esModuleInterop": true,
21 | "allowSyntheticDefaultImports": true,
22 | "strict": true,
23 | "resolveJsonModule": true,
24 | "isolatedModules": true,
25 | "declaration": false,
26 | "noEmit": true
27 | },
28 | "include": ["src/core/*.*", "src/native/*/*", "node_modules/jest-fetch-mock"],
29 | "exclude": [
30 | "/node_modules",
31 | "/build",
32 | "/dist",
33 | "/react-native",
34 | "/examples",
35 | "rollup.config.js",
36 | "src/__tests__/*"
37 | ]
38 | }
39 |
--------------------------------------------------------------------------------
/tsconfig.test.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "./tsconfig.json",
3 | "compilerOptions": {
4 | "module": "commonjs"
5 | }
6 | }
--------------------------------------------------------------------------------
/typedoc.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | out: './docs',
3 | exclude: ['**/__tests__/*', '*/**/index.ts', '*/**/helpers.ts'],
4 | };
5 |
--------------------------------------------------------------------------------
Hook return value
76 |