npm package: @formio/offline-plugin
Description: A formio.js plugin that provides an offline mode for a single project. Offline requests will automatically kick in when a request fails due to a network error and serve data cached offline, if available. You may also create/edit/delete submissions while o
Latest version: 5.3.2

# @formio/offline-plugin

A formio.js plugin that provides an offline mode for a single project. Offline requests will automatically kick in when a request fails due to a network error and serve data cached offline, if available. You may also create/edit/delete submissions while offline, and the requests will be queued to be sent when the app goes back online.

## Browser support

The offline plugin uses IndexedDB to store records so the browser must support it to be able to use offline mode. In addition, files are stored as Blobs in IndexedDB but will fall back to Base64 storage if not supported.

### Browser Minimums:

Offline mode is using features supported in the following browsers and later:

	- Chrome v38
	- Safari 7.1
	- IE 11
	- Firefox 13

## Installing the plugin

This module is now distributed via NPM and will require a premium license for use in runtime applications and can now be imported using the standard and common NPM methods:

`npm install @formio/offline-plugin`

`yarn add @formio/offline-plugin`

For more details please see our [help docs](https://help.form.io/deployments/maintenance-and-migration/premium-libraries). 


## Using the offline mode module in your project
To use this module, you will use the same process described @ https://help.form.io/developers/modules#using-a-module but for this module. This will
look like the following in your application.

```javascript
import { Formio } from '@formio/js';
import { OfflinePlugin } from '@formio/offline-plugin';

// You need to have a valid Library License key to use this package.
// If you don't have one yet, please contact sales@form.io.
Formio.license = 'yourLibraryLicenseKey';
Formio.use(OfflinePlugin(
  'myproject-offline', // The name of this offline instance.
  'https://myproject.form.io', // Your project URL
  'path/to/project.json' // OPTIONAL: the exported project.json file.
));
```

The arguments that you provide to the ```OfflinePlugin``` method are found below in the SDK section.

If you are using any of the Angular or React, wrappers, you may need to import the ```Formio``` instance from those modules instead as follows.

```javascript
import { Formio } from '@formio/angular';
```

## Accessing the module
Once the module has been intialized, you can access the instance of this plugin anywhere in your application using the ```getPlugin``` API as follows.

```javascript
const OfflinePlugin = Formio.getPlugin('myproject-offline');
```

If you want to use a <script> tag directly in your HTML file instead*:

```html
<script src="node_modules/@formio/offline-plugin/offline.full.min.js"></script>
```

*Once you do this, the offline module will introduce a new global called ```FormioOfflinePlugin```, which you can now use to register the OfflinePlugin as you did above using the following script.

```html
<script type="application/javascript">
  Formio.use(FormioOfflinePlugin.OfflinePlugin('myproject-offline', 'https://myproject.form.io', 'path/to/project.json'));
</script>
```

You can now embed your form as you normally would and it will use the offline mode system.

#### Deployed Servers
Deployed installations may also need to provide baseUrl and projectUrl. These tell the renderer the Base URL as well as the project URL being used when embedding the offline script.

```html
<script type="application/javascript">
  Formio.setBaseUrl('https://forms.yourdomain.com');
  Formio.setProjectUrl('https://forms.yourdomain.com/yourproject');
  Formio.use(FormioOfflinePlugin.OfflinePlugin('myproject-offline', 'https://forms.yourdomain.com/yourproject', 'path/to/project.json'));
</script>
```

## SDK

### OfflinePlugin(name, projectUrl, [projectJsonPath], [options])
Factory method that returns a Form.io Module which contains a new instance of the FormioOfflinePlugin class, which controls the offline mode for this project.

 - **name**: This is a name you come up with to contexualize your offline mode for this project.
 - **projectUrl**: This is the URL of the project this offline mode plugin is attached to.
 - **projectJson** (optional): Providing this will provide the default project.json of your project. You can get this by exporting your project. If you do not provide this, then your application will need to request the Form online before it will cache that form to be used offline. By providing the url to this file, the offline mode will use the offline form by default and not have to send a request to the api.
 - **options** (optional): Optional configurations to control how the offline module plugin behaves. The following options are allowed.
   - **dequeueOnReconnect** - Set to true if you wish for the plugin to automatically dequeue the saved offline submissions as soon as an internet connection has been made.
   - **queryFiltersTypes** - Default query arguments to add to the search queries for the submission index for caching purposes.
   - **notToShowDeletedOfflineSubmissions** - Set to true if you do not wish to show deleted offline submissions in the submission index.
   - **deleteErrorSubmissions** - Set to true if you wish to automatically delete submission errors.

### new FormioOfflinePlugin(projectUrl, [projectJsonPath])
Creates a new offline module instance for a project.

 - **projectUrl**: This is the URL of the project this offline mode plugin is attached to.
 - **projectJson** (optional): Providing this will provide the default project.json of your project. You can get this by exporting your project. If you do not provide this, then your application will need to request the Form online before it will cache that form to be used offline. By providing the url to this file, the offline mode will use the offline form by default and not have to send a request to the api.

## Saving forms and submissions offline
Once you register a plugin for a particular project, all load requests for forms and submissions in that project will automatically save and update in an offline browser data store.

For example, you can have all submissions for a form available offline if you call `formio.loadSubmissions()` at some point in your app while online.

## Loading forms and submissions offline
When your app goes offline, requests to load a form or submission will automatically return the data cached offline, if available.

## Submitting forms offline
Form submissions work a little bit differently when this plugin is registered. All form submissions, submission edits, and submission deletions are added to a queue. If the app is online, the queue will be emptied immediately and behave like normal. But when the app is offline, the submissions stay in the queue until the app goes back online. Until then, Formio.js will behave as if the submission was successful.

The queue will automatically start to empty when a submission is successfully made online, or you may [manually start](#plugindequeuesubmissions) it.

## Deleting submissions offline
When you delete a submission offline, this won't be deleted from the local DB, it will be just marked as '_deleted'. The submission will be deleted from the local DB only in online, when the 'DELETE' request is sent. You can prevent showing deleted submissions in offline by setting the 'notToShowDeletedOfflineSubmissions' flag in the plugin's config to 'true'.

## Handling submission queue errors
Some queued submissions may fail when they are sent online (ex: unique validation fails on the server). In the event a queued submission fails, the queue is stopped and events are triggered to allow your app to resolve the bad submission before continuing. It's up to your app to decide how to handle these errors. Your app may decide to prompt the user to [fix the form submission](#pluginsetnextqueuedsubmissionrequest) or simply [ignore the submission](#pluginskipnextqueuedsubmission), and [restart the queue](#plugindequeuesubmissions).

## Plugin methods

### plugin.forceOffline(offline)

Forces all requests for this plugin's project into offline mode, even when a connection is available.

### plugin.isForcedOffline()

Returns true if this plugin is currently forced offline.

### plugin.clearOfflineData()

Clears all offline data. This includes offline cached forms and submissions, as well as submissions waiting in the offline queue.

### plugin.dequeueSubmissions()

Starts to process the submission queue. All requests in the offline submission queue will be sent in the order they were made. Successful requests will either resolve their original promise or trigger the [`offline.formSubmission`](#offlineformsubmission) event from `Formio.events`. A failed request will stop processing the queue and trigger the [`offline.formError`](#offlineformerror) event. The app must handle this event to resolve the failing requests and restart the queue.

### plugin.submissionQueueLength()

Returns the number of submission requests currently in the offline queue.

### plugin.getNextQueuedSubmission()

Returns the next request in the submission queue.

### plugin.setNextQueuedSubmission(request)

Sets the next request in the submission queue to `request`.

You can use this to fix a failed submission and then call [`dequeueSubmissions()`](#plugindequeuesubmissions) to resubmit and continue the queue.

### plugin.skipNextQueuedSubmission()

Discards the next request in the submission queue.

You can use this to ignore a failed submission and then call [`dequeueSubmissions()`](#plugindequeuesubmissions) to continue to the next queued request.


## Events

You can listen for these events by adding listeners to the `Formio.events` EventEmitter.

NOTE: if you are using the Angular ngFormio library, you can listen for these events in the Angular scope by adding `formio.` before each event name.

### offline.queue

Triggered when a submission is added to the submission queue.

### offline.dequeue

Triggered when the submission queue starts to process a submission.

### offline.requeue

Triggered when a submission fails and is added back to the front of the submission queue.

### offline.formSubmission

Triggered when a queued submission is successfully submitted. This is not called if the original promise of the request can be resolved (in which case it behaves like a normal online submission).

### offline.formError

Triggered when a queued submission returns an error. This means the app needs to either fix the submission or skip it, and restart the queue.

### offline.queueEmpty

Triggered when the queue becomes empty after dequeuing.

## Request Options

### skipQueue

You may set `skipQueue` to save a submission immediately, skipping the queue. This will disable offline queuing for that submission. For example:

```javascript
formio.saveSubmission(submission, {skipQueue: true});
```

If you are using the Angular ngFormio library, you can set the skipQueue option with formio-options:

```html
<formio src="userLoginForm" formio-options="{skipQueue: true}"></formio>
```

## Build Commands

* `npm run build` - build for production
* `npm run watch` - automatically recompile during development

## FAQs

### Where is the form/submission data stored offline?

This plugin uses IndexedDB to store data.

### How can I tell if my requests were loaded from the offline cache?

Requests that return data stored offline will have the `offline` property set to true.

### Can I login while offline?

Unfortunately, authentication will not work in offline mode. It is highly recommended to use the [skipQueue](#skipqueue) option when submitting authentication forms.