open-index/open-npm huggingface dataset:
npm package: @onaio/cbv
Description: Class Based Views powered by React & Redux
Author: Ona Engineering
Latest version: 0.0.1

# Redux Class Based Views

This package came out of the [ideas expressed here](https://github.com/onaio/js-tools/issues/126).

The objective is to make the process of connecting React components to the Redux store more DRY, and with less boilerplate.

Currently, this package implements the following class based views:

## ObjectList

`ObjectList` is a class based view that works with components that expect to receive an array of objects from the Redux store.

### How does it work?

ObjectList is a generic class that is instantiated with two parameters:

1. The component that you want to connect to the redux store
2. The ObjectList options

### Sample usage

```tsx
import reducer, {
  Message,
  selectAllMessages,
  sendMessage,
  SendMessageAction
} from 'some reducer module';

// this is the component that wants to be connected to the Redux store
const SomeComponent = (props: Props) => {
  const { messages } = props;
  const listItems = messages ? messages.map((e, index) => <li key={index}>{e.message}</li>) : null;
  return listItems ? <ul>{listItems}</ul> : <span>error</span>;
};

// these are options that ObjectList uses
const objectListOptions = {
  actionCreator: sendMessage,
  dispatchPropName: 'actionCreator',
  returnPropName: 'messages',
  selector: selectAllMessages
};

// this is how you implement ObjectList
const ClassBasedView = new ObjectList<Message, SendMessageAction, typeof selectAllMessages, Props>(
  SomeComponent,
  objectListOptions
);

// Voila!  This is a fully redux-connected version of SomeComponent
const ConnectedSomeComponent = ClassBasedView.render();
```

## SingleObject

`SingleObject` is a class based view that works with components that expect to receive a single of objects from the Redux store.

### How does it work?

SingleObject is a generic class that is instantiated with two parameters:

1. The component that you want to connect to the redux store
2. The SingleObject options

### Sample usage

```tsx
import reducer, {
  Message,
  selectAllMessages,
  sendMessage,
  SendMessageAction
} from 'some reducer module';

const TheComponent = (props: Props) => {
  const { message } = props;
  return message ? <div>{message.message}</div> : <div>error</div>;
};

/** SingleObject options */
const singleObjectOptions = {
  actionCreator: sendMessage,
  dispatchPropName: 'actionCreator',
  returnPropName: 'message',
  selector: selectOneMessage
};

// this is how you instantiate SingleObject
const ClassBasedView = new SingleObject<
  Message,
  SendMessageAction,
  typeof selectOneMessage,
  TestProps
>(TheComponent, singleObjectOptions);

// Voila!  This is a fully redux-connected version of SomeComponent
const ConnectedSomeComponent = ClassBasedView.render();
```
npm package: @onaio/connected-private-route
Description: Declarative private routing for React and Redux
Author: Ona Engineering
Latest version: 0.1.0

# connected-private-route

This is a wrapper around the [`Route` component from react-router](https://reacttraining.com/react-router/web/api/Route).

Basically what it does is that it checks if the current user is logged in and if so allows them to access the route/page, otherwise it sends them to the defined redirect page(usually the login page).

The component will append the path the user was trying to access onto the redirect path as query string with key `next` should authentication fail.

For instance. Say the user types in some url in the browser e.g `example.com/dashboard`.

If the path `/dashboard` routes to this component like so:

```typescript
        <Router>
          <div className={'main-container'}>
            <Switch>
              <Route path="/login" component={Login} />
              <ConnectedPrivateRoute
                exact
                path="/dashboard"
                component={Dashboard}
                redirectPath="/login"
                disableLoginProtection=false
                routerEnabled=true
                routerDisabledRedirectPath='/'
              />
              <Route component={NotFound} />
            </Switch>
          </div>
        </Router>
```

then if the user is authenticated he will be redirected to `example.com/login?next=%2Fdashboard`
`

## Sample usage

```ts
import ConnectedPrivateRoute from '@onaio/connected-private-route'
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'

class App extends Component {
  render() {
    return (
     ...
        <Router>
          <div className={'main-container'}>
            <Switch>
              <Route path="/login" component={Login} />
              <ConnectedPrivateRoute
                exact
                path="/"
                component={Home}
                redirectPath="/login"
                routerEnabled=true
                routerDisabledRedirectPath='/'
                disableLoginProtection=false
              />
              <Route component={NotFound} />
            </Switch>
          </div>
        </Router>
     ...
    )
  }
}

export default App
```

## How it works

Behind the scenes, it works with the [session reducer](https://github.com/onaio/js-tools/tree/master/packages/session-reducer) to check if the user is logged in.

## The props

- **disableLoginProtection**: if this is true, we don't check if the user is authenticated. Useful for turning off login protection without doing much else. Default value is false.
- **redirectPath**: the path that the user will be redirected to if they are not logged in. Default is "/login".
- **routerEnabled**: check if user is allowed to navigate to this route. Is a protection against navigation to disabled routes. Default is true.
- **routerDisabledRedirectPath**: redirect path if the router is disabled. Default is "/".
npm package: @onaio/connected-reducer-registry
Description: Connected Reducer Registry
Author: Ona Engineering
Latest version: 0.0.3

# Connected Reducer Registry

This package primarily provides a "connected reducer registry".

But what does this even mean? To explain that, let us talk about the two things that this package provides:

## 1. Connected redux store

```ts
import store from '@onaio/connected-reducer-registry';
```

This is a redux store that:

- works with the Reducer Registry i.e. any reducers added to the Reducer registry will be added to the Redux store dynamically
- is integrated with [connected-react-router](https://github.com/supasate/connected-react-router)
- is integrated with [redux thunk](https://github.com/reduxjs/redux-thunk)
- includes redux dev tools for easy debugging

By default, the store that is provided includes only a router reducer.

## 2. A way to created a connected redux store

```ts
import { combine } from '@onaio/redux-reducer-registry';
import { connectReducer, getConnectedStore } from '@onaio/connected-reducer-registry';
import someReducer from 'somewhere'; // obviously change this!

/** create default reducers */
const defaultReducers = {
  router: connectReducer as any,
  anotherReducer: someReducer
};

/** Create the store */
const store = getConnectedStore(defaultReducers);

/** Set listener to add reducers to store when registered */
reducerRegistry.setChangeListener(reducers => {
  store.replaceReducer(combine(reducers));
});
```

## Redux modules

We highly recommend and encourage that you use [redux modules](https://github.com/erikras/ducks-modular-redux).
npm package: @onaio/element-map
Description: Simple component takes a list of elements and returns them wrapped in the provided HTML tag
Author: Ona Engineering
Latest version: 0.0.5

# ElementMap

A simple `React` component that takes a list of elements and a HTML tag and outputs the same list of elements wrapped in the same HTML tag provided.

## Why is this useful?

`ElementMap` helps to keep code DRY - use it every time that have a list of things that you want to render wrapped inside a HTML tag, which happens a lot of times in any medium/large codebase.

Therefore this (or variations of it):

```js
const items = ['a', 'b', 'c'];
const wrappedItems = items.map(el => <li>el</li>);
return <ol>{wrappedItems}</ol>;
```

Becomes:

```js
import ElementMap from '@onaio/element-map';

const things = ['a', 'b', 'c'];
return (
  <ol>
    <ElementMap items={things} HTMLTag="li" />
  </ol>
);
```

## Examples

```js
import ElementMap from '@onaio/element-map';

const headerItems = ['Name', 'Age'];
let output = <ElementMap items={headerItems} HTMLTag="th" />;
// output should now look like:
// [<th>Name</th>, <th>Age</th>]
```

```js
import ElementMap from '@onaio/element-map';

const headerItems = ['Fruit', 'Price'];
let output = <ElementMap items={headerItems} HTMLTag="th" className="css-class" />;
// output should now look like:
// [<th className="css-class">Fruit</th>, <th className="css-class">Price</th>]
```
npm package: @onaio/formik-effect
Description: Declarative Formik component for side-effects.
Author: Ona Engineering
Latest version: 0.0.1

# Formik Effect

Declarative Formik component for side-effects. Use with caution. Please. I. beg. you.

```sh
yarn add @onaio/formik-effect --save
```

Note: this has peer dependencies of react, and formik.

## The Problem

Formik is an uncontrolled component. However, there are times when you want to trigger a side effect based on a state change. By design, Formik does not expose a prop for you to do this because I'm terrified as to how it would be abused--it encourages people to attempt to "sync" Formik's state in elsewhere (cough like in a Redux store cough cough). Anyways, please don't do that. You never ever ever ever want to store the same state in 2 places in a React application because it is almost impossible to keep them in sync unless you are a goddamn jedi. You may think it's working, and high five a teammate, but you are a just a lifecycle method away from lots and lots of pain and I can guarantee you are not considering all the edge cases. Sooooo....

**SAY IT WITH ME**:

**"I WILL NOT USE THIS TO STORE FORMIK STATE ELSEWHERE IN MY APP."**

**"I WILL NOT USE THIS TO STORE FORMIK STATE ELSEWHERE IN MY APP."**

**"I WILL NOT USE THIS TO STORE FORMIK STATE ELSEWHERE IN MY APP."**

## Basic Usage

Import the <FormikEffect> component and put it inside any Formik form. It renders null! Pass it an onChange() function and it will be called whenever your Formik form's state updates.

```tsx
import React from 'react';
import { Formik, Field, Form } from 'formik';
import { FormikEffect } from '@onaio/formik-effect';

export const SignupForm = () => (
  <div>
    <h1>My Cool Form with a SideEffect</h1>
    {/* tslint:disable jsx-no-lambda */}
    {/* tslint:disable no-console */}
    <Formik
      onSubmit={values => console.log(values)}
      initialValues={{ firstName: '', lastName: '', email: '' }}
    >
      {() => (
        <Form translate="yes">
          <FormikEffect onChange={(currentFormikState, nextFormikState) => {
               // do whatevs
               // FYI if you alter state it will cause another render
            }};
          <Field id="firstName" name="firstName" placeholder="First Name" />
          <Field id="lastName" name="lastName" placeholder="Last Name" />
          <Field name="email" type="email" placeholder="Email Address" />
          <button type="submit">Submit</button>
        </Form>
      )}
    </Formik>
    {/* tslint:enable jsx-no-lambda */}
    {/* tslint:enable no-console */}
  </div>
```

## API

Only one!

> **onChange: (currentState: FormikState<Values>, nextState: FormikState<Values>) => void**

Put your side effect here.

FormikState includes:

- values
- errors
- touched
- isSubmitting

## Inspiration

This package was inspired by, and builds heavily on, the [original formik-effect package](https://github.com/jaredpalmer/formik-effect) written by Jared Palmer.
npm package: @onaio/gisida-lite
Description: Mininimal map wrapper for MAPBOX GL JS
Author: Ona Engineering
Latest version: 0.0.2

# GisidaLite

A simple `React` component that takes react-mapbox-gl configurations and outputs a map based on configurations provided.

## Why is this useful?

`GisidaLite` helps to keep code DRY - use it every time you want to render maps on a react app. The package aims to avoid duplication of efforts whilst saving time when building maps on the web.

A basic understanding of [react-mapbox-gl](https://github.com/alex3165/react-mapbox-gl) terminologies is needed to use this library:

Package Configurations:
To get your map up and running. The following configurations are needed.

```js
interface GisidaLiteProps {
  reactMapboxGlMapFactoryUtilConfigs: FactoryParameters;
  mapConfigs: Props & Events;
  mapComponents: JSX.Element[];
  layers: JSX.Element[];
}
```

1. _reactMapboxGlMapFactoryUtilConfigs_ - [FactoryParameters](reactMapboxGlMapFactoryUtilConfigs) - Factory parameters for ReactMapboxGl method that returns a map component.
2. _mapConfigs_ - Component properties. The component takes map settings and event handlers as listed [here](https://github.com/alex3165/react-mapbox-gl/blob/master/docs/API.md#component-properties)
3. _mapComponents_ - Custom Map components. Should be passed to the component as a list. More info on this can be found [here](https://github.com/alex3165/react-mapbox-gl/blob/master/docs/API.md#zoomcontrol)
4. _layers_ - layers prop holds layers and associated sources. The prop expects a list. More info on Layers can be found on the links below
   - [sources](https://github.com/alex3165/react-mapbox-gl/blob/master/docs/API.md#source)
   - [layer](https://github.com/alex3165/react-mapbox-gl/blob/master/docs/API.md#layer)
   - [GeoJSONLayer](https://github.com/alex3165/react-mapbox-gl/blob/master/docs/API.md#geojsonlayer)
npm package: @onaio/head-bread-crumb
Description: Configurable Breadcrumbs Component that renders breadcrumb items with urls as links or without urls as text nodes
Author: Ona Engineering
Latest version: 0.0.2

# HeaderBreadcrumb

HeaderBreadcrumb component is a configurable BreadCrumbs component that renders breadcrumb items with urls as links or without urls as text nodes

## Installation

```sh
yarn add @onaio/head-bread-crumb
```

### The props

The props passed to HeaderBreadcrumb looks like this:

```ts
/** interface for breadcrumb items */
export interface BreadCrumbProps {
  currentPage: Page;
  pages: Page[];
}

/** interface describing page object for use in breadcrumbs */
interface Page {
  url?: string;
  label: string;
}
```

Each page requires a label parameter that is displayed on the HeadBreadcrumb and pages with urls are turned into links and displayed in blue.

### Code example

```ts
import HeaderBreadCrumb from '@onaio/head-bread-crumb';
import { Router } from 'react-router';
import { createBrowserHistory } from 'history';

const history = createBrowserHistory();

const props = {
  currentPage: {
    label: 'IRS',
    url: '/irs'
  },
  pages: [
    {
      label: 'Home',
      url: '/'
    },
    {
      label: 'Programs',
      url: '/programs'
    },
    {
      label: 'Provinces',
      url: ''
    },
    {
      label: 'Disctricts'
    }
  ]
};
<Router history={history}>
  <HeaderBreadcrumb {...props} />
</Router>;
```

note that the HeaderBreadcrumb component must be used within a Router component because it has Link component ancestors
npm package: @onaio/loaders
Description: Loading components for your everyday use
Author: Ona Engineering
Latest version: 0.0.3

# Loaders

This package provides a number of React loading elements that you can use to show
that something on your page is... loading.

## Installation

```node
yarn add @onaio/loaders
```

## Ripple Loader

The Ripple Loader displays a nice ripple effect via pure CSS.

### Usage

```javascript
import Ripple from '@onaio/loaders';

<Ripple />;
```

### Customization

The Ripple loader takes a number of props that can be used to customize it:

- **borderColor**: the border color
- **borderStyle**: the border style
- **borderWidth**: the border width
- **height**: the height
- **minHeight**: the minimum height
- **width**: the width

#### Code example

```javascript
import Ripple from '@onaio/loaders'

const props = {
  borderColor: '#FF22EF',
  borderStyle: 'dotted',
  borderWidth: '4px',
}

<Ripple {...props} />
```

### Facebook, Grid, DualRing, Ring, Ellipsis, CircleRotate

Attribution: [Loading.io](loading.io)

These Loaders display a nice loading effects via pure CSS. using [styled-components](https://styled-components.com)

### Customization

These loader can be parametrized by animation speed, size and color through the below props:

- **color**: color of component
- **scaleSizeBy**: a number to scale the size relative to the default
- **scaleSpeedBy**: a number to scale the speed relative to the default

#### Code example

```typescript
import { CircleRotate } from '@onaio/loaders';

<CircleRotate {...props} />;
```
npm package: @onaio/pagination
Description: Bootstrap powered pagination component
Author: Ona Engineering
Latest version: 0.0.4

# Pagination

This package provides a number of Pagination components that you can use to split huge data sets into smaller data chunks

## usePagination Hook

this hook provides the essential logic needed in managing the state of any pagination use-case.

### Installation

```node
yarn add @onaio/pagination
```

#### Options

`UsePagination` makes use of the following props

- **totalRecords:**(number)
  - **required**
  - the total numnber of records to be paginated
- **pageSize:**(number)
  - **required**
  - the number of records in a single page
- **reducer:**(redux-styled reducer function)
  - optional
  - uses the [state reducer pattern](https://kentcdodds.com/blog/the-state-reducer-pattern-with-react-hooks) allowing you take control of state updates logic
- **initialState:**(< generic >)
  - optional
  - any object passed as an initial state is spread over the default initial state before doing anything else.

#### Paginator Code example

Here is a [code sandbox](https://codesandbox.io/s/bootstrap-pagination-component-jxtbt) showing how this hook could be used to create a bootstrap-powered pagination component

#### Exposed API

1. paginationState: the pagination state:

- currentPage
- pageSize
- pagesToBeDisplayed
- totalPages
- totalRecords

**PS**: One can override the above exposed variables via the initial state or using their own custom reducer. due to this dynamic nature the pagination state is not guaranteed to always be as shown above.

2. nextPage: increments the currentPage counter by one
3. firstPage: goes to the first page
4. lastPage: goes to the last page
5. goToPage: takes to arbitrary page
6. previousPage: decrements the currentPage counter by one
7. dispatch: The base dispatch method, the above helper functions are wrapper functions around this, use this to dispatch custom actions if any
8. canNextPage: can i go to the nextPage?, is there a nextPage?
9. canPreviousPage: can i go to the previousPage?, is there a previousPage?
npm package: @onaio/progress-indicators
Description: linear progress indicator
Author: Ona Engineering
Latest version: 0.0.5

# ProgressBar

Graphical control element to visualize progress

## Installation

```sh
yarn add @onaio/progress-indicators
```

## Configuration

configuration is done via props; properties currently supported include:

```typescript
/**
 *  {boolean} anime - apply animation over stripped gradient
 *  {boolean} showLabel - add label to the progressBar
 *  {boolean} stripped - apply stripped gradient on the progressBar
 *  {number} decimalPoints - Rounds off the value to this number of decimalPoints;
 *  {string} height - height of the bar;
 *  {number} min:  - the lower bound for the range of the progressBar
 *  {number} max: - the upper bound for the range of the progressBar
 *  {number} value - number that represents the progress; should be in range[min, max)
 *  {string} lineColor:  - A color to use for the line; defaults to blue
 *  { [key: string]: number } | undefined} [lineColorThresholds] - an optional object
 *               that represents the thresholds at which the line should change colors
 *       lineColorThresholds: {
 *                [GREEN]: 70,
 *                [RED]: 0,
 *                [YELLOW]: 30
 *            }
 * {string} cssClass - apply either stripped or animated css gradient on progressBar
 */
```

A sample of the full list of props:

```typescript
const props = {
  anime: true,
  cssClass: 'progress-bar-striped progress-bar-animated',
  decimalPoints: 0,
  height: '10px',
  lineColor: '#5269EB',
  lineColorThresholds: {
    [GREEN]: 70,
    [RED]: 0,
    [YELLOW]: 30
  },
  max: 100,
  min: 0,
  value: 70,
  showLabel: false,
  stripped: false
};
```

### Code Example

```typescript
import ProgressBar from '@onaio/progress-indicators';

// props defined above

<ProgressBar {...props} />;
```
npm package: @onaio/redux-reducer-registry
Description: Redux registry tool for dynamically loading reducers
Author: Ona Engineering
Latest version: 0.0.9

# Redux Reducer Registry

The reducer registry enables Redux reducers to be added to the store’s reducer after the store has been created. This allows Redux modules to be loaded on-demand, without requiring all Redux modules to be bundled in the main chunk for the store to correctly initialize.

This package was inspired by this blog post: [Redux modules and code splitting](http://nicolasgallagher.com/redux-modules-and-code-splitting/).

## Installation

```sh
yarn add @onaio/redux-reducer-registry
```

## How it works

By maintaining a registry of reducers, we are able to load any reducer dynamically as and when we need it.

### The Store

A sample registry-aware redux store with no initial state is included in this package.

```ts
import store from '@onaio/redux-reducer-registry';
```

Alternatively, you can create your own store by doing something like:

```ts
import { getStore, combine } from '@onaio/redux-reducer-registry';
import reducerRegistry from '@onaio/redux-reducer-registry';

const initialState = {
  things: ['users', 'messages'],
  x: 1
};
const newStore = getStore(reducerRegistry.getReducers(), initialState);

// don't forget to do this so that you add a reducer to store when it is registered
reducerRegistry.setChangeListener(reducers => {
  newStore.replaceReducer(combine(reducers));
});
```

### Registering Reducers

This is simply:

```ts
import reducerRegistry from 'redux-reducer-registry';
import reducer from 'some-module/reducers/users';

reducerRegistry.register('users', reducer);
```

After this the `users` reducer should now be fully loaded and ready to go.

### Redux modules

We highly recommend and encourage that you use [redux modules](https://github.com/erikras/ducks-modular-redux).
npm package: @onaio/superset-reducer
Description: This is a reducer module that helps handle superset information in the redux store.
Author: Ona Engineering
Latest version: 0.0.1

# superset reducer

This is a [reducer module](https://github.com/erikras/ducks-modular-redux) that helps handle superset information in the redux store

## The store

the store, currently, looks like this

```typescript
/** interface for Superset state */
interface SupersetState {
  authorized: boolean | null;
}
```

## Action creators

The following action creators are provided:

- `authorizeSuperset`: set authorized property of state object to a boolean value(true or false)
- `resetSuperset`: reset the authorized property of the state object to null

### Sample code to use these selectors

```
import { authorizeSuperset, resetSuperset } from '@onaio/superset-reducer';

/**  authorizeSuperset action creator expects the following argument
 * @param {boolean} authorizedOrNot - whether the superset is authorized or not
 */
authorizeSuperset(authorizedOrNot);//example usage

/** resetSuperset takes no params */
resetSuperset()//example usage
```

## Selectors

The following selector is provided:

- `isAuthorized`: check if superset is authorized

### Sample code to use selectors

```
import { isAuthorized } from '@onaio/superset-reducer';

// we assume you have a state object defined somewhere
let state;

const authorized = isAuthorized(state);
```

## Usage

Using this reducer is quite simple and can be done in one of two ways:

1. Use [combineReducers](https://redux.js.org/api/combinereducers) to ensure that the superset reducer is loaded into your Redux store

OR

1. Register the superset reducer so that it is added to your Redux store dynamically. You would do this in the case that you are using the [Reducer Registry](https://github.com/onaio/js-tools/tree/master/packages/reducer-registry).

### sample code to register the reducer

```typescript
import supersetReducer, { reducerName as supersetReducerName } from '@onaio/superset-reducer';
import reducerRegistry from '@onaio/redux-reducer-registry';

// /** register the superset reducer */
reducerRegistry.register(supersetReducerName, supersetReducer);
```
npm package: @onaio/utils
Description: Useful utilities from Ona
Author: Ona Engineering
Latest version: 0.0.1

# Ona Utils

This package is a collection of useful utilities.

## What is included

### Utility Type Definitions

- Dictionary: an interface that can describe any object
- UpdateType: a generic type used to merge one object interface with another
- Result: a generic type that is meant to describe the result of any function, with in-built error handling.

### Utility Functions

- percentage: a small little function that converts a decimal into a percentage e.g. 0.18 into 18%