You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
* feat: track dhis2 connection status with hook
* feat(offline): ping server for status periodically
* fix: use better endpoint
* chore: add a comment
* fix: file extension
* test(offline): add custom data provider to tests
* fix: fix tests
* chore: satisfy types
* feat: useProgressiveInterval hook
* feat: use smart intervals in connection status (wip)
* fix: pinging, back-off, pausing, fn references
* fix: pausing correctly
* fix: don't start pinging if window isn't focused
* chore: remove unused eslint ignore
* feat: add 'invokeCallbackImmediately' fn
* feat: ping on network status changes
* fix: enter standby when network changes while blurred
* chore: format
* fix: only ping when going offline to save resources
* fix: don't increment delay on immediate cb unless regular timer has elapsed
* refactor: smart interval as class
* fix: use data engine for pings to avoid rerenders; handle fetch errors
* refactor: make class properties private again
* feat: handle sw-free conditions; simplify logic
* chore: remove interval hook
* fix: don't check auth
* refactor: use shorter isConnected name
* feat: add lastConnected value
* fix: await callbacks to reset correct intervals
* chore: cleanup
* fix: update subscription callback name
* refactor: rename to NetworkStatus
* refactor: rename type to match NetworkStatus
* chore: fix import
* chore: other renaming clean-up
* chore: bump cli-style version
* refactor: rename method for clarity
* chore: clarify logs
* fix: bump cli-app-scripts version for jest v27
* refactor: use ping query for easier testing
* ci: use node 14
* fix: accept header on ping requests
* fix: check for err.type instead of err.message
* chore: add comment to remove clg
* test: fix tests for RestAPILink
* chore: prep for tests
* test: initial test commit (dirty wip)
* refactor: use a `start` method on SmartInterval
* fix(smart-interval): delay reset after 'partial standby'
* refactor: use a function for smartInterval instead of class
* chore: remove comment
* test: some more testing attempts (dirty)
* refactor: don't await callback
* test(dhis2-connection-status): tweak test for smart interval
* test: delays in ping interval
* refactor: only create smartInterval once
* test: resetting ping interval
* test: standby behavior
* test: offline & refocusing behavior
* fix: maintain lastConnected when disconnected during startup
* test: lastConnected handling
* fix: initialize to correct status based on offline interface
* chore: comment updates
* fix: set lastConnected if not set yet and starting while offline
* test: initialization conditions
* chore: remove console log
* chore: reorganize tests
* test: refactor to generalize to any default values
* chore: clean up smartInterval tests
* chore: ignore eslint warning
* test: fix test for offlineInterface effects
* test: refactor to improve assertions on `setTimeout` delays
* chore: remove console log
* fix: clear lastConnected when online
* refactor: setting lastConnected on startup
* fix: make lastConnected specific to each app
* docs: reorganize and update docs
* docs: useDhis2ConnectionStatus
* refactor: remove unused function
* chore: explanatory comments
* docs: clarify importance of useDhis2ConnectionStatus
* refactor: only use logs when specified in dev env
* fix: allow logging in production env for netlify previews
* chore: undo changes from old ping endpoint
* fix: migrate to new ping endpoint
* chore: remove unused data service from offline service
* chore: reorganize connection status dir
* fix: don't ping on unsupported server versions
* fix: choose default timer values
---------
Co-authored-by: Hendrik de Graaf <hendrik@dhis2.org>
Copy file name to clipboardExpand all lines: docs/advanced/offline/CacheableSections.md
+10-36Lines changed: 10 additions & 36 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,28 +1,22 @@
1
-
# Offline tools
1
+
# Cacheable sections
2
2
3
-
!> **WARNING** These features are considered **experimental** and are **subject to breaking changes outside of the normal release cycle.**
3
+
> This feature can only be used when PWA is enabled in `d2.config.js`. See the [App Platform docs](https://platform.dhis2.nu/#/pwa/pwa) for more information.
4
4
5
-
The app platform provides some support for PWA features, including a `manifest.json` file for installability and service worker which can provide offline caching. In addition to those features, the app runtime provides support for "cacheable sections", which are sections of an app that can be individually cached on-demand. The [`useCacheableSection`](#usecacheablesection-api)hook and the [`CacheableSection`](#cacheablesection-api)component provide the controls for the section and the wrapper for the section, respectively. The [`useCachedSections`](#usecachedsections-api) hook returns a list of sections that are stored in the cache and a function that can delete them.
5
+
The [`useCacheableSection` hook](#usecacheablesection-api) and the [`CacheableSection` component](#cacheablesection-api) provide the controls for the section and the wrapper for the section, respectively. The [`useCachedSections` hook](#usecachedsections-api) returns a list of sections that are stored in the cache and a function that can delete them.
6
6
7
-
There is also a [`useOnlineStatus`](#online-status) hook which returns the online or offline status of the client.
7
+
These features are supported by an `<OfflineProvider>` component which the app platform provides to the app.
8
8
9
9
To see a good example of these functions' APIs and their usage, see `SectionWrapper.js` in the [PWA example app](https://github.com/dhis2/app-platform/tree/master/examples/pwa-app/src/components/SectionWrapper.js) in the platform repository.
10
10
11
-
## Cacheable sections
12
-
13
-
> This feature can only be used when PWA is enabled in `d2.config.js`. See the [App Platform docs](https://platform.dhis2.nu/#/pwa/pwa) for more information.
14
-
15
-
These features are supported by an `<OfflineProvider>` component which the app platform provides to the app.
16
-
17
-
### How it works
11
+
## How it works
18
12
19
13
Cacheable sections enable sections of an app to be individually cached offline on demand. Using the `CacheableSection` wrapper and the `useCacheableSection` hook, when a user requests a section to be cached for offline use, the section's component tree will rerender, and the app's service worker will listen to all the network traffic for the component to cache it offline. To avoid caching that components' data before a user requests to do so, you can use the [URL filters feature](https://platform.dhis2.nu/#/pwa/pwa?id=opting-in) in `d2.config.js`.
20
14
21
15
Note that, without using these features, an app using offline caching will cache all the data that is requested by user as they use the app without needing to use cacheable sections.
22
16
23
17
Keep an eye out for this feature in use in the Dashboards app coming soon!
24
18
25
-
###Usage
19
+
## Usage
26
20
27
21
Wrap the component to be cached in a `CacheableSection` hook, providing an `id` and `loadingMask` prop. The loading mask should block the screen from interaction, and it will be rendered while the component is in 'recording mode'. Note that the `useCacheableSection` hook _does not need to be used in the same component_ as the `<CacheableSection>`, they just need to use the same `id`. There is an example of this in the file linked below.
28
22
@@ -57,15 +51,15 @@ export function CacheableSectionWrapper({ id }) {
|`children`| Component | Yes | Section that will be cached upon recording |
65
59
|`id`| String | Yes | ID of the section to be cached. Should match the ID used in the `useCacheableSection` hook. |
66
60
|`loadingMask`| Component | Yes | A UI mask that should block the screen from interaction. While the component is rerendering and recording, this mask will be rendered to block user interaction which may interfere with the recorded data. |
|`isCached`| Boolean |`true` if this section is in offline storage; Provided for convenience. |
87
81
|`recordingState`| String | One of `'default'`, `'pending'`, `'recording'`, or `'error'`. Under the hood, the `CacheableSection` component changes how its children are rendered based on the states. They are returned here in case an app wants to change UI or behavior based on the recording state. |
88
82
89
-
####`startRecording` API
83
+
### `startRecording` API
90
84
91
85
The `startRecording` function returned by `useCacheableSection` returns a promise that resolves if 'start recording' signal is sent successfully or rejects if there is an error with the offline interface initiating recording. It accepts an `options` parameter with the following optional properties:
92
86
@@ -123,7 +117,7 @@ function StartRecordingButton({ id }) {
123
117
}
124
118
```
125
119
126
-
####`useCachedSections` API
120
+
### `useCachedSections` API
127
121
128
122
The `useCachedSections` hook returns a list of all the sections that are cached, which can be useful if an app needs to manage that whole list at once. It takes no arguments and it returns an object with the following properties:
129
123
@@ -132,23 +126,3 @@ The `useCachedSections` hook returns a list of all the sections that are cached,
132
126
|`cachedSections`| Object | An object of cached sections' statuses, where the keys are the section IDs and the values are objects with a `lastUpdated` property that holds a `Date` object reflecting the time this section was last updated. |
133
127
|`removeById`| Function | Receives an `id` parameter and attempts to remove the section with that ID from the offline cache. If successful, updates the cached sections list. Returns a promise that resolves to `true` if that section is successfully removed or `false` if a section with that ID was not found. |
134
128
|`syncCachedSections`| Function | Syncs the list of cached sections with the list in IndexedDB. Returns a promise. This is handled by the `removeById` function and is probably not necessary to use in most applications. |
135
-
136
-
## Online status
137
-
138
-
The `useOnlineStatus` returns the client's online or offline status. It debounces the values by default to prevent rapid changes of any UI elements that depend on the online status.
|`debounceDelay`| Number |`1000`| Duration in ms to debounce changing `online` values. Set it to `0` to remove debouncing. |
153
-
154
-
Under the hood, the `online` value is initialized to `navigator.onLine`, then the value changes in response to browser `online` and `offline` events. In the future, the hook may use periodic server pings to detect online status.
!> **WARNING** These features are considered **experimental** and are **subject to breaking changes outside of the normal release cycle.**
4
+
5
+
The app platform provides some support for PWA features, including a `manifest.json` file for installability and service worker which can provide offline caching. In addition to those features, the app runtime provides support for ["cacheable sections"](advanced/offline/CacheableSections), which are sections of an app that can be individually cached on-demand. The [`useCacheableSection` hook](advanced/offline/CacheableSections#usecacheablesection-api) and the [`CacheableSection` component](advanced/offline/CacheableSections#cacheablesection-api) provide the controls for the section and the wrapper for the section, respectively. The [`useCachedSections` hook](advanced/offline/CacheableSections#usecachedsections-api) returns a list of sections that are stored in the cache and a function that can delete them.
6
+
7
+
An important tool for offline-capable apps is the [`useDhis2ConnectionStatus` hook](advanced/offline/useDhis2ConnectionStatus.md), which can be used to determine whether or not the app can connect to the DHIS2 server. There is also a [`useOnlineStatus` hook](advanced/offline/useOnlineStatus.md) which returns whether or not the client is connected to the internet, but `useDhis2ConnectionStatus` is probably the one you want to use. On instances where DHIS2 is deployed locally in an environment without internet, `useOnlineStatus` can cause problems, because it will always return `false` even though the app can communicate with the DHIS2 server and therefore function just fine. `useDhis2ConnectionStatus` was created to address this problem.
8
+
9
+
## Examples
10
+
11
+
To see some examples of the APIs in use, see the [PWA example app](https://github.com/dhis2/app-platform/tree/master/examples/pwa-app/src/components/) in the platform repository.
> This feature can only be used when PWA is enabled in `d2.config.js`. See the [App Platform docs](https://platform.dhis2.nu/#/pwa/pwa) for more information.
4
+
5
+
This hook is used to detect whether or not the app can connect to the DHIS2 server. This can be useful, for example, to make changes in the UI to prevent the user from taking actions that would cause errors while unable to reach the server.
6
+
7
+
It's designed to detect server connection because checking just the internet connection can lead to problems on DHIS2 instances that are implemented offline, where features or actions might be blocked because the device is offline, even though the app can connect to the DHIS2 server just fine. In these cases, what matters is whether or not the app can connect to the DHIS2 server.
|`isConnected`|`boolean`| Represents whether the app can connect to the DHIS2 server |
21
+
|`isDisconnected`|`boolean`| The opposite of `isConnected`. Provided as a convenience value |
22
+
|`lastConnected`|`Date`| The last time the app was able to connect to the server, or `null` when `isConnected` is true. See more [below](#lastconnected-details) about details of this value |
23
+
24
+
### `lastConnected` details
25
+
26
+
The value will be persisted locally so it will be consistent across sessions while disconnected.
27
+
28
+
Since we can’t actually detect the ‘lastConnected’ value between sessions, the `lastConnected` value is set to “now” if the app starts up while disconnected from the server and can’t find an existing value stored from previous sessions.
29
+
30
+
**Tip!** Given the above caveat, this value is most accurately thought of as “Time since starting to work offline”.
31
+
32
+
This value can be specific to each app — make sure the ‘appName’ is set in d2.config.js to enable this. Otherwise it will use a value that’s shared between apps.
33
+
34
+
## Design
35
+
36
+
This hook is a refinement to `useNetworkStatus`, since it will work for implementations where the server is used locally without internet.
37
+
38
+
The `isConnected` value is primarily detected by the service worker, which listens to the incidental network traffic of the app and interprets the value from successes and failures of requests.
39
+
40
+
During periods when there’s no network traffic from the app, “pings” will be used **conservatively** to see if the server is reachable. There are several measures taken to limit the usage of these pings:
41
+
42
+
- While the connection status is stable, the intervals between pings will increase exponentially up to a long interval.
43
+
- Any new network traffic from the app will postpone future pings.
44
+
- If the app is not focused, no pings will be sent.
45
+
46
+
### Supported versions
47
+
48
+
The pings are only sent for server versions that support them, meaning patch versions 2.40.0, 2.39.2, 2.38.3, and 2.37.10. and after. For unsupported versions, the hook will still use the incidental network traffic to determind a connections status value.
!> This hook only detects whether or not you're connected to the internet, which could be problematic for DHIS2 instances that are hosted locally or offline, where what really matters is whether or not you can communicate with the DHIS2 server. The [`useDhis2ConnectionStatus` hook](advanced/offline/useDhis2ConnectionStatus) is usually better for that reason, and is therefore recommended.
4
+
5
+
The `useOnlineStatus` returns whether the client is online or offline. It debounces the returned values by default to prevent rapid changes of any UI elements that depend on the online status.
0 commit comments