Skip to content

Commit ab5a696

Browse files
authored
feat: initial implementation (#1)
1 parent 6e8a893 commit ab5a696

25 files changed

+11685
-1
lines changed

.babelrc

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
{
2+
"presets": [
3+
["babel-preset-moxy/lib", { "react": true }]
4+
]
5+
}

.editorconfig

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
# editorconfig.org
2+
root = true
3+
4+
[*]
5+
indent_style = space
6+
indent_size = 4
7+
end_of_line = lf
8+
charset = utf-8
9+
trim_trailing_whitespace = true
10+
insert_final_newline = true
11+
12+
[package.json]
13+
indent_size = 2
14+
15+
[{*.md,*.snap}]
16+
trim_trailing_whitespace = false

.eslintrc.json

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
{
2+
"root": true,
3+
"extends": [
4+
"eslint-config-moxy/es9",
5+
"eslint-config-moxy/addons/react",
6+
"eslint-config-moxy/addons/jest",
7+
"eslint-config-moxy/addons/babel-parser",
8+
"eslint-config-moxy/addons/es-modules",
9+
"eslint-config-moxy/addons/browser",
10+
"eslint-config-moxy/addons/node"
11+
]
12+
}

.gitignore

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
node_modules
2+
npm-debug.log*
3+
coverage
4+
lib/
5+
es/

.travis.yml

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
language: node_js
2+
node_js:
3+
- "node"
4+
- "lts/*"
5+
# Report coverage
6+
after_success:
7+
- "npm i codecov"
8+
- "node_modules/.bin/codecov"

LICENSE

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
The MIT License (MIT)
2+
3+
Copyright (c) 2019 Protocol Labs Inc.
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy
6+
of this software and associated documentation files (the "Software"), to deal
7+
in the Software without restriction, including without limitation the rights
8+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
copies of the Software, and to permit persons to whom the Software is
10+
furnished to do so, subject to the following conditions:
11+
12+
The above copyright notice and this permission notice shall be included in
13+
all copies or substantial portions of the Software.
14+
15+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21+
THE SOFTWARE.

README.md

Lines changed: 285 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,286 @@
11
# react-idm-wallet
2-
React bindings for the reference implementation of the IDM Wallet in JavaScript
2+
3+
[![NPM version][npm-image]][npm-url] [![Downloads][downloads-image]][npm-url] [![Build Status][travis-image]][travis-url] [![Coverage Status][codecov-image]][codecov-url] [![Dependency status][david-dm-image]][david-dm-url] [![Dev Dependency status][david-dm-dev-image]][david-dm-dev-url]
4+
5+
[npm-url]:https://npmjs.org/package/react-idm-wallet
6+
[downloads-image]:http://img.shields.io/npm/dm/react-idm-wallet.svg
7+
[npm-image]:http://img.shields.io/npm/v/react-idm-wallet.svg
8+
[travis-url]:https://travis-ci.org/ipfs-shipyard/react-idm-wallet
9+
[travis-image]:http://img.shields.io/travis/ipfs-shipyard/react-idm-wallet/master.svg
10+
[codecov-url]:https://codecov.io/gh/ipfs-shipyard/react-idm-wallet
11+
[codecov-image]:https://img.shields.io/codecov/c/github/ipfs-shipyard/react-idm-wallet/master.svg
12+
[david-dm-url]:https://david-dm.org/ipfs-shipyard/react-idm-wallet
13+
[david-dm-image]:https://img.shields.io/david/ipfs-shipyard/react-idm-wallet.svg
14+
[david-dm-dev-url]:https://david-dm.org/ipfs-shipyard/react-idm-wallet?type=dev
15+
[david-dm-dev-image]:https://img.shields.io/david/dev/ipfs-shipyard/react-idm-wallet.svg
16+
17+
React bindings for the [reference implementation](https://npmjs.org/package/idm-wallet) of the IDM Wallet in JavaScript.
18+
19+
20+
## Installation
21+
22+
```sh
23+
$ npm install react-idm-wallet idm-wallet
24+
```
25+
26+
You must also install `idm-wallet` as this module has a peer-depedency on it.
27+
28+
This library is written in modern JavaScript and is published in both CommonJS and ES module transpiled variants. If you target older browsers please make sure to transpile accordingly.
29+
30+
31+
## Usage
32+
33+
First, wrap your application in `<IdmWalletProvider>`:
34+
35+
```js
36+
import React, { Fragment } from 'react';
37+
import ReactDOM from 'react-dom';
38+
import createIdmWallet from 'idm-wallet';
39+
import { IdmWalletProvider } from 'react-idm-wallet';
40+
import App from './App';
41+
42+
// We are using async mode in this example, read more below
43+
ReactDOM.render(
44+
<IdmWalletProvider createIdmWallet={ createIdmWallet }>
45+
{ (status, error) => (
46+
<Fragment>
47+
{ status === 'loading' && <div>Creating wallet...</div> }
48+
{ status === 'error' && <div>Oops, unable to create wallet: { error.message }</div> }
49+
{ status === 'ok' && <App /> }
50+
</Fragment>
51+
) }
52+
</IdmWalletProvider>,,
53+
document.getElementById('root')
54+
);
55+
```
56+
57+
Then, you may use `connectIdmWallet` to connect a component to a IDM Wallet:
58+
59+
```js
60+
// App.js
61+
import React from 'react';
62+
import { connectIdmWallet } from 'react-idm-wallet';
63+
64+
const App = ({ locked, onLock }) => (
65+
<div>
66+
<p>Locked: { locked }</p>
67+
<button onClick={ onLock }>Lock wallet</button>
68+
</div>
69+
);
70+
71+
const createMapWalletToProps = (idmWallet) => {
72+
const onLocked = () => idmWallet.locker.lock();
73+
74+
return () => {
75+
locked: idmWallet.locker.isLocked(),
76+
onLock,
77+
});
78+
};
79+
80+
export connectIdmWallet(createMapWalletToProps)(App);
81+
```
82+
83+
84+
## API
85+
86+
- [`<IdmWalletProvider>`](#idmwalletprovider)
87+
- [`connectIdmWallet(createMapWalletToProps, [options])`](#connectidmwalletcreatemapwallettoprops-options)
88+
- [`createIdmWalletObservable(idmWallet)`](#createidmwalletobservableidmwallet)
89+
90+
### IdmWalletProvider
91+
92+
The `<IdmWalletProvider>` makes a IDM Wallet available to any nested components that have been wrapped in the `connectIdmWallet()` function.
93+
94+
Since any React component in an app can be connected, most applications will render a `<IdmWalletProvider>` at the top level, with the entire app's component tree inside of it. You can't use a connected component unless it is nested inside of a `<IdmWalletProvider>`.
95+
96+
#### Modes
97+
98+
There are two modes of operation: **sync** and **async**. The sync mode assumes that you take care of creating the IDM Wallet instance, which is an asynchronous operation, while the async mode does that for you and makes it part of the rendering.
99+
100+
**Sync mode:**
101+
102+
```js
103+
import React from 'react';
104+
import ReactDOM from 'react-dom';
105+
import createIdmWallet from 'idm-wallet';
106+
import { IdmWalletProvider } from 'react-idm-wallet';
107+
import App from './App';
108+
109+
const renderApp = (idmWallet) => {
110+
ReactDOM.render(
111+
<IdmWalletProvider idmWallet={ idmWallet }>
112+
<App />
113+
</IdmWalletProvider>,
114+
document.getElementById('root')
115+
);
116+
};
117+
118+
createIdmWallet()
119+
.then(renderApp)
120+
.catch((err) => console.error(err));
121+
```
122+
123+
**Async mode:**
124+
125+
```js
126+
import React, { Fragment } from 'react';
127+
import ReactDOM from 'react-dom';
128+
import createIdmWallet from 'idm-wallet';
129+
import { IdmWalletProvider } from 'react-idm-wallet';
130+
import App from './App';
131+
132+
ReactDOM.render(
133+
<IdmWalletProvider createIdmWallet={ createIdmWallet }>
134+
{ (status, error) => (
135+
<Fragment>
136+
{ status === 'loading' && <div>Creating wallet...</div> }
137+
{ status === 'error' && <div>Oops, unable to create wallet: { error.message }</div> }
138+
{ status === 'ok' && <App /> }
139+
</Fragment>
140+
) }
141+
</IdmWalletProvider>,
142+
document.getElementById('root')
143+
);
144+
```
145+
146+
The async mode leverages the [render props](https://reactjs.org/docs/render-props.html) technique to know what to render. The children render prop is invoked with the following signature:
147+
148+
```js
149+
const render = (status, error) => ();
150+
```
151+
152+
The `status` may be either `loading`, `error` or `ok`. When status is set to error, the `error` argument will contain the error object that was caught.
153+
154+
#### Props
155+
156+
##### idmWallet
157+
158+
ℹ️ Using this property will make the provider operate in sync mode.
159+
160+
Type: `object`
161+
162+
The [idmWallet](https://npmjs.org/package/idm-wallet) instance to use in your app.
163+
Internally, [`createIdmWalletObservable()`](#createidmwalletobservableidmwallet) will be used to observe changes to IDM Wallet's data or state.
164+
165+
##### createIdmWallet
166+
167+
Type: `function`
168+
169+
ℹ️ Using this property will make the provider operate in async mode.
170+
171+
A function that returns a promise for the IDM Wallet to use in your app.
172+
Internally, [`createIdmWalletObservable()`](#createidmwalletobservableidmwallet) will be used to observe changes to IDM Wallet's data or state.
173+
174+
If you want to pass options when creating the IDM wallet, you may create a custom factory and use it as the `createIdmWallet` prop:
175+
176+
```js
177+
const createIdmWalletWithOptions = () => createIdmWallet({ /* Your options */ });
178+
179+
// ...
180+
<IdmWalletProvider createIdmWallet={ createIdmWalletWithOptions }>
181+
```
182+
183+
##### children
184+
185+
Type: `Node` (any React's node), `Function`
186+
187+
What to render as the children. A React node is expected in sync mode while a function is expected in async mode.
188+
189+
### connectIdmWallet(createMapWalletToProps, [options])
190+
191+
The `connectIdmWallet()` function connects a React component to a IDM Wallet instance, by providing the connected component with the pieces of the data or state and functions it needs from the IDM Wallet.
192+
193+
It does not modify the component class passed to it; instead, it returns a new, connected component that wraps the component you passed in. Moreover, any ref will be automatically forwarded to the component you passed in.
194+
195+
#### createMapWalletToProps
196+
197+
Type: `function`
198+
199+
A factory that creates a function that maps any data, state or mutators from a IDM Wallet to props that will be passed to the wrapped component. **From now on**, we will call the factory and the returned function **`createMapWalletToProps`** and **`mapWalletToProps`** respectively.
200+
201+
```js
202+
const createMapWalletToProps = (idmWallet) => (ownProps) => ({});
203+
```
204+
205+
Your `createMapWalletToProps` will be called once per `idmWallet` instance, which usually does not change.
206+
207+
If your `mapWalletToProps` function is declared with `ownProps`, it will be called whenever any data or state on the IDM Wallet changes or when the wrapper component receives new props (based on shallow equality comparisons). On the other hand, if the function is declared without any parameter, it will be called only whenever any data or state on the IDM Wallet changes.
208+
209+
All calls to mutators of the `idmWallet` must be bound, so that the correct `this` is used. This means that you will often wrap mutators in functions to keep them bounded. For that reason, it's **important to declare them in the factory** to avoid creating new functions everytime `mapWalletToProps` runs, thus avoiding unwanted re-renders:
210+
211+
```js
212+
// ❌ Incorrect: `onLock` prop will be new everytime
213+
const createMapWalletToProps = (idmWallet) => (ownProps) => ({
214+
locked: idmWallet.locker.isLocked(),
215+
onLock: () => idmWallet.locker.lock(),
216+
});
217+
218+
// ✅ Correct: `onLock` prop will have the same reference everytime
219+
const createMapWalletToProps = (idmWallet) => {
220+
onLock = () => idmWallet.locker.lock();
221+
222+
return (ownProps) => {
223+
locked: idmWallet.locker.isLocked(),
224+
onLock,
225+
};
226+
});
227+
```
228+
229+
#### options
230+
231+
##### options.pure
232+
233+
Type: `boolean`
234+
Default: `true`
235+
236+
Assumes that the wrapped component is a "pure" component and does not rely on any input or state other than its props and the mapped props from the IDM Wallet. Several equality checks are performed to avoid unnecessary calls to `mapWalletToProps` as well as to bail out on unnecessary renders.
237+
238+
### createIdmWalletObservable(idmWallet)
239+
240+
Creates an observer with the ability to watch changes of `idmWallet`. Those changes are captured by adding listeners to the `idmWallet`, such as `idmWallet.locker.onLockedChange(listener)`, and by wrapping functions that mutate underlying data or state, such as `idmWallet.locker.lock()`.
241+
242+
Note that the same observer will be returned for the same `idmWallet`.
243+
244+
### idmWallet
245+
246+
Type: `object`
247+
248+
The [idmWallet](https://npmjs.org/package/idm-wallet) instance to observe.
249+
250+
### Returned observer
251+
252+
The observer returned by `createIdmWalletObservable()` is an object with the following methods:
253+
254+
#### subscribe(fn)
255+
256+
Subscribes to changes to the IDM Wallet, returning a function that unsubscribes when called.
257+
258+
```js
259+
const observable = createIdmWalletObservable(idmWallet);
260+
261+
const unsubscribe = observable.subscribe(() => {
262+
console.log('changed!');
263+
});
264+
```
265+
266+
#### unsubscribe(fn)
267+
268+
Unsubscribes a previously added subscriber.
269+
270+
#### cleanup()
271+
272+
Resets the IDM Wallet to its original state if there are no subscribers left, removing the previously added listeners and wrappers from the `idmWallet`.
273+
The next call to `subscribe()` will add the listeners and wrappers to the `idmWallet` again.
274+
275+
276+
## Tests
277+
278+
```sh
279+
$ npm test
280+
$ npm test -- --watch # during development
281+
```
282+
283+
284+
## License
285+
286+
Released under the [MIT License](http://www.opensource.org/licenses/mit-license.php).

0 commit comments

Comments
 (0)