Skip to content

Commit 932591f

Browse files
authored
feat: initial implementation (#1)
1 parent cdb8659 commit 932591f

26 files changed

+18593
-1
lines changed

.commitlintrc.json

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
{
2+
"extends": [
3+
"@commitlint/config-conventional"
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: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
{
2+
"root": true,
3+
"extends": [
4+
"@moxy/eslint-config/es10",
5+
"@moxy/eslint-config/addons/browser",
6+
"@moxy/eslint-config/addons/node",
7+
"@moxy/eslint-config/addons/react",
8+
"@moxy/eslint-config/addons/babel-parser",
9+
"@moxy/eslint-config/addons/es-modules",
10+
"@moxy/eslint-config/addons/jest"
11+
],
12+
"rules": {
13+
"no-new-func": 0
14+
}
15+
}

.github/workflows/deploy-demo.yml

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
name: Deploy demo
2+
3+
on:
4+
push:
5+
paths:
6+
- demo/**/*
7+
branches:
8+
- master
9+
10+
jobs:
11+
deploy:
12+
runs-on: ubuntu-latest
13+
14+
steps:
15+
- name: Checkout code
16+
uses: actions/checkout@v1
17+
18+
- name: Install & build
19+
run: |
20+
npm ci
21+
npm run build
22+
- name: Install & build demo
23+
run: |
24+
cd demo
25+
npm ci
26+
npm run build
27+
npm run export
28+
- name: Deploy
29+
uses: peaceiris/actions-gh-pages@v2
30+
env:
31+
ACTIONS_DEPLOY_KEY: ${{ secrets.ACTIONS_DEPLOY_KEY }}
32+
PUBLISH_DIR: demo/out
33+
PUBLISH_BRANCH: gh-pages

.github/workflows/node-ci.yml

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
name: Node CI
2+
3+
on:
4+
push:
5+
paths-ignore:
6+
- demo/**/*
7+
pull_request:
8+
paths-ignore:
9+
- demo/**/*
10+
11+
jobs:
12+
13+
check:
14+
runs-on: ubuntu-latest
15+
strategy:
16+
matrix:
17+
node: ['12', '13']
18+
name: "[v${{ matrix.node }}] prepare"
19+
20+
steps:
21+
- name: Checkout code
22+
uses: actions/checkout@v1
23+
24+
- name: Install dependencies
25+
run: |
26+
npm ci
27+
28+
- name: Run lint & tests
29+
env:
30+
CI: 1
31+
run: |
32+
npm run lint
33+
npm t
34+
35+
- name: Submit coverage
36+
uses: codecov/codecov-action@v1
37+
with:
38+
token: ${{ secrets.CODECOV_TOKEN }}

.gitignore

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
node_modules
2+
npm-debug.log*
3+
coverage
4+
lib/
5+
es/
6+
src-tmp/
7+
demo/.next
8+
demo/out

.huskyrc

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
{
2+
"hooks": {
3+
"pre-commit": "lint-staged",
4+
"commit-msg": "commitlint -E HUSKY_GIT_PARAMS"
5+
}
6+
}

.lintstagedrc

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
{
2+
"*.js": "eslint"
3+
}

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) 2020 Made With MOXY Lda <hello@moxy.studio>
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: 188 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,188 @@
1-
# react-app-preloader
1+
# react-wait-for-react
2+
3+
[![NPM version][npm-image]][npm-url] [![Downloads][downloads-image]][npm-url] [![Build Status][build-status-image]][build-status-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/@moxy/react-wait-for-react
6+
[downloads-image]:https://img.shields.io/npm/dm/@moxy/react-wait-for-react.svg
7+
[npm-image]:https://img.shields.io/npm/v/@moxy/react-wait-for-react.svg
8+
[build-status-url]:https://github.com/moxystudio/next-with-moxy/actions
9+
[build-status-image]:https://img.shields.io/github/workflow/status/moxystudio/next-with-moxy/Node%20CI/master
10+
[codecov-url]:https://codecov.io/gh/moxystudio/react-wait-for-react
11+
[codecov-image]:https://img.shields.io/codecov/c/github/moxystudio/react-wait-for-react/master.svg
12+
[david-dm-url]:https://david-dm.org/moxystudio/react-wait-for-react
13+
[david-dm-image]:https://img.shields.io/david/moxystudio/react-wait-for-react.svg
14+
[david-dm-dev-url]:https://david-dm.org/moxystudio/react-wait-for-react?type=dev
15+
[david-dm-dev-image]:https://img.shields.io/david/dev/moxystudio/react-wait-for-react.svg
16+
17+
Easily render a splash screen and loader while your React app is not yet interactive, optionally waiting for a promise as well.
18+
19+
## Installation
20+
21+
```sh
22+
$ npm install @moxy/react-wait-for-react
23+
```
24+
25+
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.
26+
27+
## Motivation
28+
29+
Certain apps or pages have impactful experiences. These experiences can make the total bundle size larger as they pack possibly large dependencies and media assets, such as 3D objects and audio files.
30+
31+
It's then often normal to preload all the required files for an uninterrupted experience. `@moxy/react-wait-for-react` is a library that makes it easy to display a spash screen with a loader before your static or server-side rendered app becomes interactive, and optionally until all the required files are loaded (via a promise). This is made possible by injecting a small inline script as part of the initial server-side rendered HTML or exported HTML.
32+
33+
<img src="https://developers.google.com/web/fundamentals/performance/images/perf-metrics-load-timeline.png" alt="Performance metrics timeline" width="700" />
34+
35+
⚠️ You should still render the app or page contents "below" the splash screen, to keep your website SEO friendly.
36+
37+
## Demo
38+
39+
You may see a simple demo of `react-wait-for-react` in [https://moxystudio.github.io/react-wait-for-react](https://moxystudio.github.io/react-wait-for-react/).
40+
41+
## Usage
42+
43+
Using `<WaitForReact>` to render a progress bar while your page assets are being loaded:
44+
45+
```js
46+
import React, { useMemo, useCallback } from 'react';
47+
import classNames from 'classnames';
48+
import WaitForReact from '@moxy/react-wait-for-react';
49+
import styles from './MyPage.module.css';
50+
51+
const preloadAssets = async () => {
52+
// Preload files, like a mp3, 3d objects, etc..
53+
};
54+
55+
const MyPage = () => {
56+
const promise = useMemo(() => preloadAssets(), []);
57+
const applyProgressBeforeInteractive = `function (elements, progress) {
58+
elements.progressBar.style.transform = 'scaleX(' + progress + ')';
59+
}`;
60+
61+
return (
62+
<main>
63+
<WaitForReact
64+
applyProgressBeforeInteractive={ applyProgressBeforeInteractive }
65+
promise={ promise }>
66+
{ ({ progress }) => (
67+
<div
68+
data-wait-for-react-element="progressBar"
69+
className={ classNames(styles.progressBar, progress > 1 && styles.done) }
70+
style={ { transform: `scaleX(${progress})` } } />
71+
) }
72+
</WaitForReact>
73+
<div>My Awesome Page</div>
74+
</main>
75+
);
76+
};
77+
78+
export default MyPage;
79+
```
80+
81+
## API
82+
83+
This package exports a single component called `<WaitForReact>`, with the following props:
84+
85+
### maxProgressBeforeInteractive
86+
87+
Type: `number`
88+
Default: `0.4`
89+
90+
The maximum value the progress can take before the app becomes interactive. Takes a value between 0 and 1 (exclusive).
91+
92+
### applyProgressBeforeInteractive
93+
94+
Type: `string` (*required*)
95+
96+
A function in it's string form to update elements whenever `progress` changes.
97+
98+
`<WaitForReact>` will call `applyProgressBeforeInteractive` **only** before your app becomes interactive. When your app becomes interactive, React takes over and your `children` render prop will then be called as usual. To make this possible, `applyProgressBeforeInteractive` will be added in an inline script included as part SSR or static export.
99+
100+
⚠️ The reason for this prop to be a string instead of a function has to do with compilation. Because server-side compilation usually differ from client-side compilation, the actual function in it's string form would be different and React would complain with a mismatch warning when rehydrating. Having that said, you should be careful in how you write this function so that it's compatible with all your target environments.
101+
102+
The `applyProgressBeforeInteractive` function signature is `(elements, progress) => {}`, where `elements` are DOM nodes that were tagged with `data-wait-for-react-element` attributes. Here's an example where we tag two different elements:
103+
104+
```js
105+
const applyProgressBeforeInteractive = `function (elements, progress) {
106+
// elements.foo
107+
// elements.bar
108+
};
109+
`
110+
111+
const MyPage = () => (
112+
<WaitForReact
113+
applyProgressBeforeInteractive={ applyProgressBeforeInteractive }
114+
promise={ promise }>
115+
{ ({ progress }) => (
116+
<div className={ classNames(styles.progressBarWrapper, progress > 1 && styles.done) }>
117+
<div
118+
data-wait-for-react-element="foo"
119+
className={ styles.progressBarHorizontal }
120+
style={ { transform: `scaleX(${progress})` } } />
121+
<div
122+
data-wait-for-react-element="bar"
123+
className={ styles.progressBarVertical }
124+
style={ { transform: `scaleY(${progress})` } } />
125+
</div>
126+
) }
127+
</WaitForReact>
128+
);
129+
```
130+
131+
### progressDecay
132+
133+
Type: `string`
134+
Default: `function (time) { return Math.min(0.95, 1 - Math.exp(-1 * time / 4000)); }`
135+
136+
A function in it's string form to calculate the progress value based on the elapsed time. Typically, the algorithm has a decay pattern, where increments are smaller and smaller as time passes by.
137+
138+
`<WaitForReact>` will call `progressDecay` to simulate a "fake progress" until your app becomes interactive. To make this possible, `progressDecay` will be added in an inline script included as part SSR or static export. Similarly, `<WaitForReact>` will call `progressDecay` to simulate a "fake progress" if a standard promise is passed as the `promise` prop.
139+
140+
⚠️ The reason for this prop to be a string instead of a function has to do with compilation. Because server-side compilation usually differ from client-side compilation, the actual function in it's string form would be different and React would complain with a mismatch warning when rehydrating. Having that said, you should be careful in how you write this function so that it's compatible with all your target environments.
141+
142+
The `progressDecay` function signature is `(time) => <progress>`, where `time` is the elapsed time in milliseconds. It must return the `progress` value in the form of a number between 0 and 1 (exclusive).
143+
144+
### progressInterval
145+
146+
Type: `number`
147+
Default: 100
148+
149+
The interval, in ms, to report progress. The value of `progressInterval` will effectively throttle all the internal behavior of `<WaitForReact>`, including the frequency in which the `children` render prop will be called.
150+
151+
ℹ️ If you are using CSS transitions, the transition durations should be slightly smaller than `progressInterval`. This circumvents an issue with several browsers, such as Chrome and Firefox, where updating a CSS property in the middle of a transition will cause the animation to "restart".
152+
153+
### promise
154+
155+
Type: `Promise` or `PProgress `
156+
157+
A promise to wait for, after the app becomes interactive.
158+
159+
When a standard `Promise` is given, `<WaitForReact>` will initiate a "fake progress" until the promise settles. However, you may pass a [`PProgress `](https://github.com/sindresorhus/p-progress). In this case, the progress reported by the promise will be used instead of the "fake progress".
160+
161+
### children
162+
163+
Type: `Function`
164+
165+
A [render prop](https://reactjs.org/docs/render-props.html) function that renders children based on the `progress` or `error` (if any).
166+
167+
The `children` function signature is `({ progress, error }) => <node>`, where `progress` the current progress percentage and `error` is the promise rejection value in case a `promise` was passed and it was rejected.
168+
169+
ℹ️ The `progress` value is guaranteed to always between 0 and 0.95.
170+
171+
### onDone
172+
173+
Type: `Function`
174+
175+
A function called when the waiting process is done, that is, when your app becomes interactive or when the promise settles, if one was passed.
176+
177+
The `onDone` function signature is `(err) => {}`, where `error` is the error of the rejected promise, if any.
178+
179+
## Tests
180+
181+
```sh
182+
$ npm test
183+
$ npm test -- --watch # during development
184+
```
185+
186+
## License
187+
188+
Released under the [MIT License](https://www.opensource.org/licenses/mit-license.php).

babel.config.js

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
module.exports = (api) => {
2+
api.cache(true);
3+
4+
return {
5+
ignore: process.env.NODE_ENV === 'test' ? [] : ['**/*.test.js', '**/__snapshots__'],
6+
overrides: [
7+
{
8+
exclude: '**/inline-script.raw.js',
9+
presets: [
10+
['@moxy/babel-preset/lib', { react: true }],
11+
],
12+
plugins: [
13+
['babel-plugin-inline-import', { extensions: ['.raw.js', '.raw'] }],
14+
],
15+
},
16+
{
17+
test: '**/inline-script.raw.js',
18+
presets: [
19+
['@moxy/babel-preset/end-project', {
20+
targets: {
21+
browsers: ['IE 11'],
22+
},
23+
}],
24+
],
25+
},
26+
],
27+
};
28+
};

demo/README.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
# Demo
2+
3+
This project uses [Next.js](https://nextjs.org/)
4+
5+
Be sure to run npm run build inside the root project directory and npm i inside the demo directory each time you make a change to the library.

demo/next.config.js

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
module.exports = {
2+
exportPathMap() {
3+
return {
4+
'/': { page: '/' },
5+
};
6+
},
7+
assetPrefix: process.env.GITHUB_ACTIONS ? '/react-wait-for-react/' : '',
8+
webpack: (config) => {
9+
config.resolve.symlinks = false;
10+
11+
return config;
12+
},
13+
};

0 commit comments

Comments
 (0)