WIP: Add use_service_worker
|
@ -3,6 +3,12 @@
|
||||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
||||||
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||||
|
|
||||||
|
## [Unreleased] -
|
||||||
|
|
||||||
|
### New Functions 🚀
|
||||||
|
|
||||||
|
- `use_service_worker`
|
||||||
|
|
||||||
## [0.7.1] - 2023-10-02
|
## [0.7.1] - 2023-10-02
|
||||||
|
|
||||||
### New Function 🚀
|
### New Function 🚀
|
||||||
|
|
|
@ -15,6 +15,7 @@ homepage = "https://leptos-use.rs"
|
||||||
[dependencies]
|
[dependencies]
|
||||||
leptos = "0.5"
|
leptos = "0.5"
|
||||||
wasm-bindgen = "0.2"
|
wasm-bindgen = "0.2"
|
||||||
|
wasm-bindgen-futures = "0.4"
|
||||||
js-sys = "0.3"
|
js-sys = "0.3"
|
||||||
default-struct-builder = "0.5"
|
default-struct-builder = "0.5"
|
||||||
num = { version = "0.4", optional = true }
|
num = { version = "0.4", optional = true }
|
||||||
|
@ -69,6 +70,10 @@ features = [
|
||||||
"ResizeObserverSize",
|
"ResizeObserverSize",
|
||||||
"ScrollBehavior",
|
"ScrollBehavior",
|
||||||
"ScrollToOptions",
|
"ScrollToOptions",
|
||||||
|
"ServiceWorker",
|
||||||
|
"ServiceWorkerContainer",
|
||||||
|
"ServiceWorkerRegistration",
|
||||||
|
"ServiceWorkerState",
|
||||||
"Storage",
|
"Storage",
|
||||||
"Touch",
|
"Touch",
|
||||||
"TouchEvent",
|
"TouchEvent",
|
||||||
|
|
|
@ -38,6 +38,7 @@
|
||||||
- [use_media_query](browser/use_media_query.md)
|
- [use_media_query](browser/use_media_query.md)
|
||||||
- [use_preferred_contrast](browser/use_preferred_contrast.md)
|
- [use_preferred_contrast](browser/use_preferred_contrast.md)
|
||||||
- [use_preferred_dark](browser/use_preferred_dark.md)
|
- [use_preferred_dark](browser/use_preferred_dark.md)
|
||||||
|
- [use_service_worker](browser/use_service_worker.md)
|
||||||
|
|
||||||
# Sensors
|
# Sensors
|
||||||
|
|
||||||
|
|
3
docs/book/src/browser/use_service_worker.md
Normal file
|
@ -0,0 +1,3 @@
|
||||||
|
# use_service_worker
|
||||||
|
|
||||||
|
<!-- cmdrun python3 ../extract_doc_comment.py use_service_worker -->
|
|
@ -35,6 +35,7 @@ members = [
|
||||||
"use_resize_observer",
|
"use_resize_observer",
|
||||||
"use_round",
|
"use_round",
|
||||||
"use_scroll",
|
"use_scroll",
|
||||||
|
"use_service_worker",
|
||||||
"use_sorted",
|
"use_sorted",
|
||||||
"use_storage",
|
"use_storage",
|
||||||
"use_throttle_fn",
|
"use_throttle_fn",
|
||||||
|
|
16
examples/use_service_worker/Cargo.toml
Normal file
|
@ -0,0 +1,16 @@
|
||||||
|
[package]
|
||||||
|
name = "use_service_worker"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2021"
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
leptos = { version = "0.5", features = ["nightly", "csr"] }
|
||||||
|
console_error_panic_hook = "0.1"
|
||||||
|
console_log = "1"
|
||||||
|
log = "0.4"
|
||||||
|
leptos-use = { path = "../..", features = ["docs"] }
|
||||||
|
web-sys = "0.3"
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
wasm-bindgen = "0.2"
|
||||||
|
wasm-bindgen-test = "0.3.0"
|
23
examples/use_service_worker/README.md
Normal file
|
@ -0,0 +1,23 @@
|
||||||
|
A simple example for `use_service_worker`.
|
||||||
|
|
||||||
|
If you don't have it installed already, install [Trunk](https://trunkrs.dev/) and [Tailwind](https://tailwindcss.com/docs/installation)
|
||||||
|
as well as the nightly toolchain for Rust and the wasm32-unknown-unknown target:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cargo install trunk
|
||||||
|
npm install -D tailwindcss @tailwindcss/forms
|
||||||
|
rustup toolchain install nightly
|
||||||
|
rustup target add wasm32-unknown-unknown
|
||||||
|
```
|
||||||
|
|
||||||
|
Then, open two terminals. In the first one, run:
|
||||||
|
|
||||||
|
```
|
||||||
|
npx tailwindcss -i ./input.css -o ./style/output.css --watch
|
||||||
|
```
|
||||||
|
|
||||||
|
In the second one, run:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
trunk serve --open
|
||||||
|
```
|
7
examples/use_service_worker/Trunk.toml
Normal file
|
@ -0,0 +1,7 @@
|
||||||
|
[build]
|
||||||
|
public_url = "/demo/"
|
||||||
|
|
||||||
|
[[hooks]]
|
||||||
|
stage = "post_build"
|
||||||
|
command = "bash"
|
||||||
|
command_arguments = ["-c", "./post_build.sh"]
|
10
examples/use_service_worker/index.html
Normal file
|
@ -0,0 +1,10 @@
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<meta name="version" content="{{buildVersion}}">
|
||||||
|
<link data-trunk rel="css" href="style/output.css">
|
||||||
|
<link data-trunk rel="copy-file" href="manifest.json" />
|
||||||
|
<link data-trunk rel="copy-file" href="service-worker.js" />
|
||||||
|
</head>
|
||||||
|
<body></body>
|
||||||
|
</html>
|
3
examples/use_service_worker/input.css
Normal file
|
@ -0,0 +1,3 @@
|
||||||
|
@tailwind base;
|
||||||
|
@tailwind components;
|
||||||
|
@tailwind utilities;
|
54
examples/use_service_worker/manifest.json
Normal file
|
@ -0,0 +1,54 @@
|
||||||
|
{
|
||||||
|
"name": "Demo",
|
||||||
|
"short_name": "Demo",
|
||||||
|
"icons": [
|
||||||
|
{
|
||||||
|
"src": "./res/icon/maskable_icon_x48.png",
|
||||||
|
"sizes": "48x48",
|
||||||
|
"type": "image/png",
|
||||||
|
"purpose": "maskable"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"src": "./res/icon/maskable_icon_x72.png",
|
||||||
|
"sizes": "72x72",
|
||||||
|
"type": "image/png",
|
||||||
|
"purpose": "maskable"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"src": "./res/icon/maskable_icon_x96.png",
|
||||||
|
"sizes": "96x96",
|
||||||
|
"type": "image/png",
|
||||||
|
"purpose": "maskable"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"src": "./res/icon/maskable_icon_x128.png",
|
||||||
|
"sizes": "128x128",
|
||||||
|
"type": "image/png",
|
||||||
|
"purpose": "maskable"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"src": "./res/icon/maskable_icon_x192.png",
|
||||||
|
"sizes": "192x192",
|
||||||
|
"type": "image/png",
|
||||||
|
"purpose": "maskable"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"src": "./res/icon/maskable_icon_x384.png",
|
||||||
|
"sizes": "384x384",
|
||||||
|
"type": "image/png",
|
||||||
|
"purpose": "maskable"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"src": "./res/icon/maskable_icon_x512.png",
|
||||||
|
"sizes": "512x512",
|
||||||
|
"type": "image/png",
|
||||||
|
"purpose": "maskable"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"lang": "en-US",
|
||||||
|
"id": "/demo/",
|
||||||
|
"start_url": "/demo/",
|
||||||
|
"display": "standalone",
|
||||||
|
"background_color": "#e52320",
|
||||||
|
"theme_color": "#e52320"
|
||||||
|
}
|
56
examples/use_service_worker/post_build.sh
Executable file
|
@ -0,0 +1,56 @@
|
||||||
|
#!/bin/bash
|
||||||
|
set -e
|
||||||
|
|
||||||
|
appName="use_service_worker"
|
||||||
|
stylePrefix="output"
|
||||||
|
styleFormat="css"
|
||||||
|
|
||||||
|
# Extract build version
|
||||||
|
indexJsFile=$(find ./dist/.stage -iname "${appName}-*.js")
|
||||||
|
echo "Extracting build version from file: ${indexJsFile}"
|
||||||
|
regex="(.*)${appName}-(.*).js"
|
||||||
|
_src="${indexJsFile}"
|
||||||
|
while [[ "${_src}" =~ ${regex} ]]; do
|
||||||
|
buildVersion="${BASH_REMATCH[2]}"
|
||||||
|
_i=${#BASH_REMATCH}
|
||||||
|
_src=${_src:_i}
|
||||||
|
done
|
||||||
|
if [ -z "${buildVersion}" ]; then
|
||||||
|
echo "Could not determine build version!"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
echo "Build-Version is: ${buildVersion}"
|
||||||
|
|
||||||
|
# Replace placeholder in service-worker.js
|
||||||
|
serviceWorkerJsFile=$(find ./dist/.stage -iname "service-worker.js")
|
||||||
|
echo "Replacing {{buildVersion}} placeholder in: ${serviceWorkerJsFile}"
|
||||||
|
sed "s/{{buildVersion}}/${buildVersion}/g" "${serviceWorkerJsFile}" > "${serviceWorkerJsFile}.modified"
|
||||||
|
mv -f "${serviceWorkerJsFile}.modified" "${serviceWorkerJsFile}"
|
||||||
|
|
||||||
|
# Replace placeholder in index.html
|
||||||
|
indexHtmlFile=$(find ./dist/.stage -iname "index.html")
|
||||||
|
echo "Replacing {{buildVersion}} placeholder in: ${indexHtmlFile}"
|
||||||
|
sed "s/{{buildVersion}}/${buildVersion}/g" "${indexHtmlFile}" > "${indexHtmlFile}.modified"
|
||||||
|
mv -f "${indexHtmlFile}.modified" "${indexHtmlFile}"
|
||||||
|
|
||||||
|
# Extract CSS build version
|
||||||
|
indexJsFile=$(find ./dist/.stage -iname "${stylePrefix}-*.${styleFormat}")
|
||||||
|
echo "Extracting style build version from file: ${indexJsFile}"
|
||||||
|
regex="(.*)${stylePrefix}-(.*).${styleFormat}"
|
||||||
|
_src="${indexJsFile}"
|
||||||
|
while [[ "${_src}" =~ ${regex} ]]; do
|
||||||
|
cssBuildVersion="${BASH_REMATCH[2]}"
|
||||||
|
_i=${#BASH_REMATCH}
|
||||||
|
_src=${_src:_i}
|
||||||
|
done
|
||||||
|
if [ -z "${cssBuildVersion}" ]; then
|
||||||
|
echo "Could not determine style build version!"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
echo "CSS Build-Version is: ${cssBuildVersion}"
|
||||||
|
|
||||||
|
# Replace placeholder in service-worker.js
|
||||||
|
serviceWorkerJsFile=$(find ./dist/.stage -iname "service-worker.js")
|
||||||
|
echo "Replacing {{cssBuildVersion}} placeholder in: ${serviceWorkerJsFile}"
|
||||||
|
sed "s/{{cssBuildVersion}}/${cssBuildVersion}/g" "${serviceWorkerJsFile}" > "${serviceWorkerJsFile}.modified"
|
||||||
|
mv -f "${serviceWorkerJsFile}.modified" "${serviceWorkerJsFile}"
|
BIN
examples/use_service_worker/res/icon/maskable_icon_x128.png
Normal file
After Width: | Height: | Size: 4.2 KiB |
BIN
examples/use_service_worker/res/icon/maskable_icon_x192.png
Normal file
After Width: | Height: | Size: 6 KiB |
BIN
examples/use_service_worker/res/icon/maskable_icon_x384.png
Normal file
After Width: | Height: | Size: 14 KiB |
BIN
examples/use_service_worker/res/icon/maskable_icon_x48.png
Normal file
After Width: | Height: | Size: 1.3 KiB |
BIN
examples/use_service_worker/res/icon/maskable_icon_x512.png
Normal file
After Width: | Height: | Size: 22 KiB |
BIN
examples/use_service_worker/res/icon/maskable_icon_x72.png
Normal file
After Width: | Height: | Size: 2.4 KiB |
BIN
examples/use_service_worker/res/icon/maskable_icon_x96.png
Normal file
After Width: | Height: | Size: 2.8 KiB |
BIN
examples/use_service_worker/res/icon/pwa.png
Normal file
After Width: | Height: | Size: 49 KiB |
9
examples/use_service_worker/res/icon/pwa.svg
Normal file
|
@ -0,0 +1,9 @@
|
||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" baseProfile="full" width="1952" height="734.935" viewBox="0 0 1952.00 734.93" enable-background="new 0 0 1952.00 734.93" xml:space="preserve">
|
||||||
|
<g>
|
||||||
|
<path fill="#3D3D3D" fill-opacity="1" stroke-width="0.2" stroke-linejoin="round" d="M 1436.62,603.304L 1493.01,460.705L 1655.83,460.705L 1578.56,244.39L 1675.2,0.000528336L 1952,734.933L 1747.87,734.933L 1700.57,603.304L 1436.62,603.304 Z "/>
|
||||||
|
<path fill="#5A0FC8" fill-opacity="1" stroke-width="0.2" stroke-linejoin="round" d="M 1262.47,734.935L 1558.79,0.00156593L 1362.34,0.0025425L 1159.64,474.933L 1015.5,0.00351906L 864.499,0.00351906L 709.731,474.933L 600.585,258.517L 501.812,562.819L 602.096,734.935L 795.427,734.935L 935.284,309.025L 1068.63,734.935L 1262.47,734.935 Z "/>
|
||||||
|
<path fill="#3D3D3D" fill-opacity="1" stroke-width="0.2" stroke-linejoin="round" d="M 186.476,482.643L 307.479,482.643C 344.133,482.643 376.772,478.552 405.396,470.37L 436.689,373.962L 524.148,104.516C 517.484,93.9535 509.876,83.9667 501.324,74.5569C 456.419,24.852 390.719,0.000406265 304.222,0.000406265L -3.8147e-006,0.000406265L -3.8147e-006,734.933L 186.476,734.933L 186.476,482.643 Z M 346.642,169.079C 364.182,186.732 372.951,210.355 372.951,239.95C 372.951,269.772 365.238,293.424 349.813,310.906C 332.903,330.331 301.766,340.043 256.404,340.043L 186.476,340.043L 186.476,142.598L 256.918,142.598C 299.195,142.598 329.103,151.425 346.642,169.079 Z "/>
|
||||||
|
</g>
|
||||||
|
</svg>
|
2
examples/use_service_worker/rust-toolchain.toml
Normal file
|
@ -0,0 +1,2 @@
|
||||||
|
[toolchain]
|
||||||
|
channel = "nightly"
|
82
examples/use_service_worker/service-worker.js
Normal file
|
@ -0,0 +1,82 @@
|
||||||
|
var buildVersion = "{{buildVersion}}"
|
||||||
|
var cssBuildVersion = "{{cssBuildVersion}}"
|
||||||
|
var cacheName = "demo";
|
||||||
|
var filesToCache = [
|
||||||
|
'./',
|
||||||
|
'./index.html',
|
||||||
|
'./manifest.json',
|
||||||
|
'./use_service_worker-' + buildVersion + '_bg.wasm',
|
||||||
|
'./use_service_worker-' + buildVersion + '.js',
|
||||||
|
'./output-' + cssBuildVersion + '.css',
|
||||||
|
'./res/icon/maskable_icon_x48.png',
|
||||||
|
'./res/icon/maskable_icon_x72.png',
|
||||||
|
'./res/icon/maskable_icon_x96.png',
|
||||||
|
'./res/icon/maskable_icon_x128.png',
|
||||||
|
'./res/icon/maskable_icon_x192.png',
|
||||||
|
'./res/icon/maskable_icon_x384.png',
|
||||||
|
'./res/icon/maskable_icon_x512.png',
|
||||||
|
|
||||||
|
// TODO: Add files you want the SW to cache. Rename entries to match your build output!
|
||||||
|
];
|
||||||
|
|
||||||
|
/* Start the service worker and cache all of the app's content */
|
||||||
|
self.addEventListener('install', function (event) {
|
||||||
|
console.log("Installing service-worker for build", buildVersion);
|
||||||
|
const preCache = async () => {
|
||||||
|
get_cache().then(function (cache) {
|
||||||
|
// We clear the whole cache, as we do not know which resources were updated!
|
||||||
|
cache.keys().then(function (requests) {
|
||||||
|
for (let request of requests) {
|
||||||
|
cache.delete(request);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
cache.addAll(filesToCache.map(url => new Request(url, { credentials: 'same-origin' })));
|
||||||
|
})
|
||||||
|
};
|
||||||
|
event.waitUntil(preCache);
|
||||||
|
});
|
||||||
|
|
||||||
|
self.addEventListener('message', function (messageEvent) {
|
||||||
|
if (messageEvent.data === "skipWaiting") {
|
||||||
|
console.log("Service-worker received skipWaiting event", buildVersion);
|
||||||
|
self.skipWaiting();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
self.addEventListener('fetch', function (e) {
|
||||||
|
e.respondWith(cache_then_network(e.request));
|
||||||
|
});
|
||||||
|
|
||||||
|
async function get_cache() {
|
||||||
|
return caches.open(cacheName);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function cache_then_network(request) {
|
||||||
|
const cache = await get_cache();
|
||||||
|
return cache.match(request).then(
|
||||||
|
(cache_response) => {
|
||||||
|
if (!cache_response) {
|
||||||
|
return fetch_from_network(request, cache);
|
||||||
|
} else {
|
||||||
|
return cache_response;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
(reason) => {
|
||||||
|
return fetch_from_network(request, cache);
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function fetch_from_network(request, cache) {
|
||||||
|
return fetch(request).then(
|
||||||
|
(net_response) => {
|
||||||
|
return net_response;
|
||||||
|
},
|
||||||
|
(reason) => {
|
||||||
|
console.error("Network fetch rejected. Falling back to ./index.html. Reason: ", reason);
|
||||||
|
return cache.match("./index.html").then(function (cache_root_response) {
|
||||||
|
return cache_root_response;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
61
examples/use_service_worker/src/main.rs
Normal file
|
@ -0,0 +1,61 @@
|
||||||
|
use leptos::*;
|
||||||
|
use leptos_use::docs::demo_or_body;
|
||||||
|
use leptos_use::{use_service_worker, use_window};
|
||||||
|
use web_sys::HtmlMetaElement;
|
||||||
|
|
||||||
|
#[component]
|
||||||
|
fn Demo() -> impl IntoView {
|
||||||
|
let build = load_meta_element("version")
|
||||||
|
.map(|meta| meta.content())
|
||||||
|
.expect("'version' meta element");
|
||||||
|
|
||||||
|
let sw = use_service_worker();
|
||||||
|
|
||||||
|
view! {
|
||||||
|
<p>"Current build: "{build}</p>
|
||||||
|
|
||||||
|
<br/>
|
||||||
|
|
||||||
|
<p>"registration: "{move || format!("{:#?}", sw.registration.get())}</p>
|
||||||
|
<p>"installing: "{move || sw.installing.get()}</p>
|
||||||
|
<p>"waiting: "{move || sw.waiting.get()}</p>
|
||||||
|
<p>"active: "{move || sw.active.get()}</p>
|
||||||
|
|
||||||
|
<br/>
|
||||||
|
|
||||||
|
<button on:click=move |_| {sw.skip_waiting.call(())}>"Send skipWaiting event"</button>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
_ = console_log::init_with_level(log::Level::Debug);
|
||||||
|
console_error_panic_hook::set_once();
|
||||||
|
|
||||||
|
mount_to(demo_or_body(), || {
|
||||||
|
view! { <Demo/> }
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn load_meta_element<S: AsRef<str>>(name: S) -> Result<web_sys::HtmlMetaElement, String> {
|
||||||
|
use wasm_bindgen::JsCast;
|
||||||
|
use_window()
|
||||||
|
.as_ref()
|
||||||
|
.ok_or_else(|| "No window instance!".to_owned())
|
||||||
|
.and_then(|window| {
|
||||||
|
window
|
||||||
|
.document()
|
||||||
|
.ok_or_else(|| "No document instance!".to_owned())
|
||||||
|
})
|
||||||
|
.and_then(|document| {
|
||||||
|
document
|
||||||
|
.query_selector(format!("meta[name=\"{}\"]", name.as_ref()).as_str())
|
||||||
|
.ok()
|
||||||
|
.flatten()
|
||||||
|
.ok_or_else(|| format!("Unable to find meta element with name 'version'."))
|
||||||
|
})
|
||||||
|
.and_then(|element| {
|
||||||
|
element.dyn_into::<HtmlMetaElement>().map_err(|err| {
|
||||||
|
format!("Unable to cast element to HtmlMetaElement. Err: '{err:?}'.")
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
294
examples/use_service_worker/style/output.css
Normal file
|
@ -0,0 +1,294 @@
|
||||||
|
[type='text'],input:where(:not([type])),[type='email'],[type='url'],[type='password'],[type='number'],[type='date'],[type='datetime-local'],[type='month'],[type='search'],[type='tel'],[type='time'],[type='week'],[multiple],textarea,select {
|
||||||
|
-webkit-appearance: none;
|
||||||
|
-moz-appearance: none;
|
||||||
|
appearance: none;
|
||||||
|
background-color: #fff;
|
||||||
|
border-color: #6b7280;
|
||||||
|
border-width: 1px;
|
||||||
|
border-radius: 0px;
|
||||||
|
padding-top: 0.5rem;
|
||||||
|
padding-right: 0.75rem;
|
||||||
|
padding-bottom: 0.5rem;
|
||||||
|
padding-left: 0.75rem;
|
||||||
|
font-size: 1rem;
|
||||||
|
line-height: 1.5rem;
|
||||||
|
--tw-shadow: 0 0 #0000;
|
||||||
|
}
|
||||||
|
|
||||||
|
[type='text']:focus, input:where(:not([type])):focus, [type='email']:focus, [type='url']:focus, [type='password']:focus, [type='number']:focus, [type='date']:focus, [type='datetime-local']:focus, [type='month']:focus, [type='search']:focus, [type='tel']:focus, [type='time']:focus, [type='week']:focus, [multiple]:focus, textarea:focus, select:focus {
|
||||||
|
outline: 2px solid transparent;
|
||||||
|
outline-offset: 2px;
|
||||||
|
--tw-ring-inset: var(--tw-empty,/*!*/ /*!*/);
|
||||||
|
--tw-ring-offset-width: 0px;
|
||||||
|
--tw-ring-offset-color: #fff;
|
||||||
|
--tw-ring-color: #2563eb;
|
||||||
|
--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);
|
||||||
|
--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);
|
||||||
|
box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);
|
||||||
|
border-color: #2563eb;
|
||||||
|
}
|
||||||
|
|
||||||
|
input::-moz-placeholder, textarea::-moz-placeholder {
|
||||||
|
color: #6b7280;
|
||||||
|
opacity: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
input::placeholder,textarea::placeholder {
|
||||||
|
color: #6b7280;
|
||||||
|
opacity: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
::-webkit-datetime-edit-fields-wrapper {
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
::-webkit-date-and-time-value {
|
||||||
|
min-height: 1.5em;
|
||||||
|
text-align: inherit;
|
||||||
|
}
|
||||||
|
|
||||||
|
::-webkit-datetime-edit {
|
||||||
|
display: inline-flex;
|
||||||
|
}
|
||||||
|
|
||||||
|
::-webkit-datetime-edit,::-webkit-datetime-edit-year-field,::-webkit-datetime-edit-month-field,::-webkit-datetime-edit-day-field,::-webkit-datetime-edit-hour-field,::-webkit-datetime-edit-minute-field,::-webkit-datetime-edit-second-field,::-webkit-datetime-edit-millisecond-field,::-webkit-datetime-edit-meridiem-field {
|
||||||
|
padding-top: 0;
|
||||||
|
padding-bottom: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
select {
|
||||||
|
background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 20 20'%3e%3cpath stroke='%236b7280' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='M6 8l4 4 4-4'/%3e%3c/svg%3e");
|
||||||
|
background-position: right 0.5rem center;
|
||||||
|
background-repeat: no-repeat;
|
||||||
|
background-size: 1.5em 1.5em;
|
||||||
|
padding-right: 2.5rem;
|
||||||
|
-webkit-print-color-adjust: exact;
|
||||||
|
print-color-adjust: exact;
|
||||||
|
}
|
||||||
|
|
||||||
|
[multiple],[size]:where(select:not([size="1"])) {
|
||||||
|
background-image: initial;
|
||||||
|
background-position: initial;
|
||||||
|
background-repeat: unset;
|
||||||
|
background-size: initial;
|
||||||
|
padding-right: 0.75rem;
|
||||||
|
-webkit-print-color-adjust: unset;
|
||||||
|
print-color-adjust: unset;
|
||||||
|
}
|
||||||
|
|
||||||
|
[type='checkbox'],[type='radio'] {
|
||||||
|
-webkit-appearance: none;
|
||||||
|
-moz-appearance: none;
|
||||||
|
appearance: none;
|
||||||
|
padding: 0;
|
||||||
|
-webkit-print-color-adjust: exact;
|
||||||
|
print-color-adjust: exact;
|
||||||
|
display: inline-block;
|
||||||
|
vertical-align: middle;
|
||||||
|
background-origin: border-box;
|
||||||
|
-webkit-user-select: none;
|
||||||
|
-moz-user-select: none;
|
||||||
|
user-select: none;
|
||||||
|
flex-shrink: 0;
|
||||||
|
height: 1rem;
|
||||||
|
width: 1rem;
|
||||||
|
color: #2563eb;
|
||||||
|
background-color: #fff;
|
||||||
|
border-color: #6b7280;
|
||||||
|
border-width: 1px;
|
||||||
|
--tw-shadow: 0 0 #0000;
|
||||||
|
}
|
||||||
|
|
||||||
|
[type='checkbox'] {
|
||||||
|
border-radius: 0px;
|
||||||
|
}
|
||||||
|
|
||||||
|
[type='radio'] {
|
||||||
|
border-radius: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
[type='checkbox']:focus,[type='radio']:focus {
|
||||||
|
outline: 2px solid transparent;
|
||||||
|
outline-offset: 2px;
|
||||||
|
--tw-ring-inset: var(--tw-empty,/*!*/ /*!*/);
|
||||||
|
--tw-ring-offset-width: 2px;
|
||||||
|
--tw-ring-offset-color: #fff;
|
||||||
|
--tw-ring-color: #2563eb;
|
||||||
|
--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);
|
||||||
|
--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);
|
||||||
|
box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);
|
||||||
|
}
|
||||||
|
|
||||||
|
[type='checkbox']:checked,[type='radio']:checked {
|
||||||
|
border-color: transparent;
|
||||||
|
background-color: currentColor;
|
||||||
|
background-size: 100% 100%;
|
||||||
|
background-position: center;
|
||||||
|
background-repeat: no-repeat;
|
||||||
|
}
|
||||||
|
|
||||||
|
[type='checkbox']:checked {
|
||||||
|
background-image: url("data:image/svg+xml,%3csvg viewBox='0 0 16 16' fill='white' xmlns='http://www.w3.org/2000/svg'%3e%3cpath d='M12.207 4.793a1 1 0 010 1.414l-5 5a1 1 0 01-1.414 0l-2-2a1 1 0 011.414-1.414L6.5 9.086l4.293-4.293a1 1 0 011.414 0z'/%3e%3c/svg%3e");
|
||||||
|
}
|
||||||
|
|
||||||
|
[type='radio']:checked {
|
||||||
|
background-image: url("data:image/svg+xml,%3csvg viewBox='0 0 16 16' fill='white' xmlns='http://www.w3.org/2000/svg'%3e%3ccircle cx='8' cy='8' r='3'/%3e%3c/svg%3e");
|
||||||
|
}
|
||||||
|
|
||||||
|
[type='checkbox']:checked:hover,[type='checkbox']:checked:focus,[type='radio']:checked:hover,[type='radio']:checked:focus {
|
||||||
|
border-color: transparent;
|
||||||
|
background-color: currentColor;
|
||||||
|
}
|
||||||
|
|
||||||
|
[type='checkbox']:indeterminate {
|
||||||
|
background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 16 16'%3e%3cpath stroke='white' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M4 8h8'/%3e%3c/svg%3e");
|
||||||
|
border-color: transparent;
|
||||||
|
background-color: currentColor;
|
||||||
|
background-size: 100% 100%;
|
||||||
|
background-position: center;
|
||||||
|
background-repeat: no-repeat;
|
||||||
|
}
|
||||||
|
|
||||||
|
[type='checkbox']:indeterminate:hover,[type='checkbox']:indeterminate:focus {
|
||||||
|
border-color: transparent;
|
||||||
|
background-color: currentColor;
|
||||||
|
}
|
||||||
|
|
||||||
|
[type='file'] {
|
||||||
|
background: unset;
|
||||||
|
border-color: inherit;
|
||||||
|
border-width: 0;
|
||||||
|
border-radius: 0;
|
||||||
|
padding: 0;
|
||||||
|
font-size: unset;
|
||||||
|
line-height: inherit;
|
||||||
|
}
|
||||||
|
|
||||||
|
[type='file']:focus {
|
||||||
|
outline: 1px solid ButtonText;
|
||||||
|
outline: 1px auto -webkit-focus-ring-color;
|
||||||
|
}
|
||||||
|
|
||||||
|
*, ::before, ::after {
|
||||||
|
--tw-border-spacing-x: 0;
|
||||||
|
--tw-border-spacing-y: 0;
|
||||||
|
--tw-translate-x: 0;
|
||||||
|
--tw-translate-y: 0;
|
||||||
|
--tw-rotate: 0;
|
||||||
|
--tw-skew-x: 0;
|
||||||
|
--tw-skew-y: 0;
|
||||||
|
--tw-scale-x: 1;
|
||||||
|
--tw-scale-y: 1;
|
||||||
|
--tw-pan-x: ;
|
||||||
|
--tw-pan-y: ;
|
||||||
|
--tw-pinch-zoom: ;
|
||||||
|
--tw-scroll-snap-strictness: proximity;
|
||||||
|
--tw-gradient-from-position: ;
|
||||||
|
--tw-gradient-via-position: ;
|
||||||
|
--tw-gradient-to-position: ;
|
||||||
|
--tw-ordinal: ;
|
||||||
|
--tw-slashed-zero: ;
|
||||||
|
--tw-numeric-figure: ;
|
||||||
|
--tw-numeric-spacing: ;
|
||||||
|
--tw-numeric-fraction: ;
|
||||||
|
--tw-ring-inset: ;
|
||||||
|
--tw-ring-offset-width: 0px;
|
||||||
|
--tw-ring-offset-color: #fff;
|
||||||
|
--tw-ring-color: rgb(59 130 246 / 0.5);
|
||||||
|
--tw-ring-offset-shadow: 0 0 #0000;
|
||||||
|
--tw-ring-shadow: 0 0 #0000;
|
||||||
|
--tw-shadow: 0 0 #0000;
|
||||||
|
--tw-shadow-colored: 0 0 #0000;
|
||||||
|
--tw-blur: ;
|
||||||
|
--tw-brightness: ;
|
||||||
|
--tw-contrast: ;
|
||||||
|
--tw-grayscale: ;
|
||||||
|
--tw-hue-rotate: ;
|
||||||
|
--tw-invert: ;
|
||||||
|
--tw-saturate: ;
|
||||||
|
--tw-sepia: ;
|
||||||
|
--tw-drop-shadow: ;
|
||||||
|
--tw-backdrop-blur: ;
|
||||||
|
--tw-backdrop-brightness: ;
|
||||||
|
--tw-backdrop-contrast: ;
|
||||||
|
--tw-backdrop-grayscale: ;
|
||||||
|
--tw-backdrop-hue-rotate: ;
|
||||||
|
--tw-backdrop-invert: ;
|
||||||
|
--tw-backdrop-opacity: ;
|
||||||
|
--tw-backdrop-saturate: ;
|
||||||
|
--tw-backdrop-sepia: ;
|
||||||
|
}
|
||||||
|
|
||||||
|
::backdrop {
|
||||||
|
--tw-border-spacing-x: 0;
|
||||||
|
--tw-border-spacing-y: 0;
|
||||||
|
--tw-translate-x: 0;
|
||||||
|
--tw-translate-y: 0;
|
||||||
|
--tw-rotate: 0;
|
||||||
|
--tw-skew-x: 0;
|
||||||
|
--tw-skew-y: 0;
|
||||||
|
--tw-scale-x: 1;
|
||||||
|
--tw-scale-y: 1;
|
||||||
|
--tw-pan-x: ;
|
||||||
|
--tw-pan-y: ;
|
||||||
|
--tw-pinch-zoom: ;
|
||||||
|
--tw-scroll-snap-strictness: proximity;
|
||||||
|
--tw-gradient-from-position: ;
|
||||||
|
--tw-gradient-via-position: ;
|
||||||
|
--tw-gradient-to-position: ;
|
||||||
|
--tw-ordinal: ;
|
||||||
|
--tw-slashed-zero: ;
|
||||||
|
--tw-numeric-figure: ;
|
||||||
|
--tw-numeric-spacing: ;
|
||||||
|
--tw-numeric-fraction: ;
|
||||||
|
--tw-ring-inset: ;
|
||||||
|
--tw-ring-offset-width: 0px;
|
||||||
|
--tw-ring-offset-color: #fff;
|
||||||
|
--tw-ring-color: rgb(59 130 246 / 0.5);
|
||||||
|
--tw-ring-offset-shadow: 0 0 #0000;
|
||||||
|
--tw-ring-shadow: 0 0 #0000;
|
||||||
|
--tw-shadow: 0 0 #0000;
|
||||||
|
--tw-shadow-colored: 0 0 #0000;
|
||||||
|
--tw-blur: ;
|
||||||
|
--tw-brightness: ;
|
||||||
|
--tw-contrast: ;
|
||||||
|
--tw-grayscale: ;
|
||||||
|
--tw-hue-rotate: ;
|
||||||
|
--tw-invert: ;
|
||||||
|
--tw-saturate: ;
|
||||||
|
--tw-sepia: ;
|
||||||
|
--tw-drop-shadow: ;
|
||||||
|
--tw-backdrop-blur: ;
|
||||||
|
--tw-backdrop-brightness: ;
|
||||||
|
--tw-backdrop-contrast: ;
|
||||||
|
--tw-backdrop-grayscale: ;
|
||||||
|
--tw-backdrop-hue-rotate: ;
|
||||||
|
--tw-backdrop-invert: ;
|
||||||
|
--tw-backdrop-opacity: ;
|
||||||
|
--tw-backdrop-saturate: ;
|
||||||
|
--tw-backdrop-sepia: ;
|
||||||
|
}
|
||||||
|
|
||||||
|
.static {
|
||||||
|
position: static;
|
||||||
|
}
|
||||||
|
|
||||||
|
.text-\[--brand-color\] {
|
||||||
|
color: var(--brand-color);
|
||||||
|
}
|
||||||
|
|
||||||
|
.text-green-600 {
|
||||||
|
--tw-text-opacity: 1;
|
||||||
|
color: rgb(22 163 74 / var(--tw-text-opacity));
|
||||||
|
}
|
||||||
|
|
||||||
|
.opacity-75 {
|
||||||
|
opacity: 0.75;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.dark\:text-green-500 {
|
||||||
|
--tw-text-opacity: 1;
|
||||||
|
color: rgb(34 197 94 / var(--tw-text-opacity));
|
||||||
|
}
|
||||||
|
}
|
15
examples/use_service_worker/tailwind.config.js
Normal file
|
@ -0,0 +1,15 @@
|
||||||
|
/** @type {import('tailwindcss').Config} */
|
||||||
|
module.exports = {
|
||||||
|
content: {
|
||||||
|
files: ["*.html", "./src/**/*.rs", "../../src/docs/**/*.rs"],
|
||||||
|
},
|
||||||
|
theme: {
|
||||||
|
extend: {},
|
||||||
|
},
|
||||||
|
corePlugins: {
|
||||||
|
preflight: false,
|
||||||
|
},
|
||||||
|
plugins: [
|
||||||
|
require('@tailwindcss/forms'),
|
||||||
|
],
|
||||||
|
}
|
|
@ -25,6 +25,7 @@ mod is_none;
|
||||||
mod is_ok;
|
mod is_ok;
|
||||||
mod is_some;
|
mod is_some;
|
||||||
mod on_click_outside;
|
mod on_click_outside;
|
||||||
|
mod use_service_worker;
|
||||||
mod signal_debounced;
|
mod signal_debounced;
|
||||||
mod signal_throttled;
|
mod signal_throttled;
|
||||||
mod use_active_element;
|
mod use_active_element;
|
||||||
|
@ -74,6 +75,7 @@ pub use is_none::*;
|
||||||
pub use is_ok::*;
|
pub use is_ok::*;
|
||||||
pub use is_some::*;
|
pub use is_some::*;
|
||||||
pub use on_click_outside::*;
|
pub use on_click_outside::*;
|
||||||
|
pub use use_service_worker::*;
|
||||||
pub use signal_debounced::*;
|
pub use signal_debounced::*;
|
||||||
pub use signal_throttled::*;
|
pub use signal_throttled::*;
|
||||||
pub use use_active_element::*;
|
pub use use_active_element::*;
|
||||||
|
|
269
src/use_service_worker.rs
Normal file
|
@ -0,0 +1,269 @@
|
||||||
|
use default_struct_builder::DefaultBuilder;
|
||||||
|
use leptos::*;
|
||||||
|
use std::borrow::Cow;
|
||||||
|
use wasm_bindgen::{prelude::Closure, JsCast, JsValue};
|
||||||
|
use web_sys::ServiceWorkerRegistration;
|
||||||
|
|
||||||
|
use crate::use_window;
|
||||||
|
|
||||||
|
///
|
||||||
|
///
|
||||||
|
/// ## Demo
|
||||||
|
///
|
||||||
|
/// [Link to Demo](https://github.com/Synphonyte/leptos-use/tree/main/examples/use_service_worker)
|
||||||
|
///
|
||||||
|
/// ## Usage
|
||||||
|
///
|
||||||
|
/// ```
|
||||||
|
/// # use leptos::*;
|
||||||
|
/// # use leptos_use::use_service_worker;
|
||||||
|
/// #
|
||||||
|
/// # #[component]
|
||||||
|
/// # fn Demo() -> impl IntoView {
|
||||||
|
/// # let sw = use_service_worker_with_options(UseServiceWorkerOptions {
|
||||||
|
/// # script_url: "service-worker.js".into(),
|
||||||
|
/// # skip_waiting_message: "skipWaiting".into(),
|
||||||
|
/// # ..UseServiceWorkerOptions::default()
|
||||||
|
/// # });
|
||||||
|
/// #
|
||||||
|
/// # view! { }
|
||||||
|
/// # }
|
||||||
|
/// ```
|
||||||
|
pub fn use_service_worker() -> UseServiceWorkerReturn {
|
||||||
|
use_service_worker_with_options(UseServiceWorkerOptions::default())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Version of [`use_service_worker`] that takes a `UseServiceWorkerOptions`. See [`use_service_worker`] for how to use.
|
||||||
|
pub fn use_service_worker_with_options(options: UseServiceWorkerOptions) -> UseServiceWorkerReturn {
|
||||||
|
// Reload the page whenever a new ServiceWorker is installed.
|
||||||
|
if let Some(navigator) = use_window().navigator() {
|
||||||
|
let on_controller_change = options.on_controller_change.clone();
|
||||||
|
let reload = Closure::wrap(Box::new(move |_event: JsValue| {
|
||||||
|
on_controller_change.call(());
|
||||||
|
}) as Box<dyn FnMut(JsValue)>)
|
||||||
|
.into_js_value();
|
||||||
|
navigator
|
||||||
|
.service_worker()
|
||||||
|
.set_oncontrollerchange(Some(reload.as_ref().unchecked_ref()));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create async actions.
|
||||||
|
let create_or_update_registration = create_action_create_or_update_sw_registration();
|
||||||
|
let get_registration = create_action_get_sw_registration();
|
||||||
|
let update_action = create_action_update_sw();
|
||||||
|
|
||||||
|
// Immediately create or update the SW registration.
|
||||||
|
create_or_update_registration.dispatch(ServiceWorkerScriptUrl(options.script_url.to_string()));
|
||||||
|
|
||||||
|
// And parse the result into individual signals.
|
||||||
|
let registration: Signal<Result<ServiceWorkerRegistration, ServiceWorkerRegistrationError>> =
|
||||||
|
Signal::derive(move || {
|
||||||
|
let a = get_registration.value().get();
|
||||||
|
let b = create_or_update_registration.value().get();
|
||||||
|
// We only dispatch create_or_update_registration once. Whenever we manually re-fetched the registration, the result of that has precedence!
|
||||||
|
match a {
|
||||||
|
Some(res) => res.map_err(ServiceWorkerRegistrationError::Js),
|
||||||
|
None => match b {
|
||||||
|
Some(res) => res.map_err(ServiceWorkerRegistrationError::Js),
|
||||||
|
None => Err(ServiceWorkerRegistrationError::NeverQueried),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
let fetch_registration = Closure::wrap(Box::new(move |_event: JsValue| {
|
||||||
|
get_registration.dispatch(());
|
||||||
|
}) as Box<dyn FnMut(JsValue)>)
|
||||||
|
.into_js_value();
|
||||||
|
|
||||||
|
// Handle a changing registration state.
|
||||||
|
// Notify to developer if SW registration or retrieval fails.
|
||||||
|
create_effect(move |_| {
|
||||||
|
registration.with(|reg| match reg {
|
||||||
|
Ok(registration) => {
|
||||||
|
// We must be informed when an updated SW is available.
|
||||||
|
registration.set_onupdatefound(Some(fetch_registration.as_ref().unchecked_ref()));
|
||||||
|
|
||||||
|
// Trigger a check to see IF an updated SW is available.
|
||||||
|
update_action.dispatch(registration.clone());
|
||||||
|
|
||||||
|
// If a SW is installing, we must be notified if its state changes!
|
||||||
|
if let Some(sw) = registration.installing() {
|
||||||
|
sw.set_onstatechange(Some(fetch_registration.as_ref().unchecked_ref()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(err) => match err {
|
||||||
|
ServiceWorkerRegistrationError::Js(err) => {
|
||||||
|
tracing::warn!("ServiceWorker registration failed: {err:?}")
|
||||||
|
}
|
||||||
|
ServiceWorkerRegistrationError::NeverQueried => {}
|
||||||
|
},
|
||||||
|
})
|
||||||
|
});
|
||||||
|
|
||||||
|
UseServiceWorkerReturn {
|
||||||
|
registration,
|
||||||
|
installing: Signal::derive(move || {
|
||||||
|
registration.with(|reg| {
|
||||||
|
reg.as_ref()
|
||||||
|
.map(|reg| reg.installing().is_some())
|
||||||
|
.unwrap_or_default()
|
||||||
|
})
|
||||||
|
}),
|
||||||
|
waiting: Signal::derive(move || {
|
||||||
|
registration.with(|reg| {
|
||||||
|
reg.as_ref()
|
||||||
|
.map(|reg| reg.waiting().is_some())
|
||||||
|
.unwrap_or_default()
|
||||||
|
})
|
||||||
|
}),
|
||||||
|
active: Signal::derive(move || {
|
||||||
|
registration.with(|reg| {
|
||||||
|
reg.as_ref()
|
||||||
|
.map(|reg| reg.active().is_some())
|
||||||
|
.unwrap_or_default()
|
||||||
|
})
|
||||||
|
}),
|
||||||
|
check_for_update: Callback::new(move |()| {
|
||||||
|
registration.with(|reg| {
|
||||||
|
if let Ok(reg) = reg {
|
||||||
|
update_action.dispatch(reg.clone())
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}),
|
||||||
|
skip_waiting: Callback::new(move |()| {
|
||||||
|
registration.with_untracked(|reg| if let Ok(reg) = reg {
|
||||||
|
match reg.waiting() {
|
||||||
|
Some(sw) => {
|
||||||
|
tracing::info!("Updating to newly installed SW...");
|
||||||
|
sw.post_message(&JsValue::from_str(&options.skip_waiting_message)).expect("post message");
|
||||||
|
},
|
||||||
|
None => {
|
||||||
|
tracing::warn!("You tried to update the SW while no new SW was waiting. This is probably a bug.");
|
||||||
|
},
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Options for [`use_service_worker_with_options`].
|
||||||
|
#[derive(DefaultBuilder)]
|
||||||
|
pub struct UseServiceWorkerOptions {
|
||||||
|
/// The name of your service-worker.
|
||||||
|
/// You will most likely deploy the service-worker JS fiel alongside your app.
|
||||||
|
/// A typical name is 'service-worker.js'.
|
||||||
|
pub script_url: Cow<'static, str>,
|
||||||
|
|
||||||
|
/// The message sent to a waiting ServiceWorker when you call the `skip_waiting` callback.
|
||||||
|
pub skip_waiting_message: Cow<'static, str>,
|
||||||
|
|
||||||
|
/// What should happen when a new service worker was activated?
|
||||||
|
/// The default implementation reloads the current page.
|
||||||
|
pub on_controller_change: Callback<()>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for UseServiceWorkerOptions {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
script_url: "service-worker.js".into(),
|
||||||
|
skip_waiting_message: "skipWaiting".into(),
|
||||||
|
on_controller_change: Callback::new(move |()| {
|
||||||
|
use std::ops::Deref;
|
||||||
|
if let Some(window) = use_window().deref() {
|
||||||
|
match window.location().reload() {
|
||||||
|
Ok(()) => {}
|
||||||
|
Err(err) => tracing::warn!(
|
||||||
|
"Detected a ServiceWorkerController change but the page reload failed! Error: {err:?}"
|
||||||
|
),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Return type of [`use_service_worker`].
|
||||||
|
pub struct UseServiceWorkerReturn {
|
||||||
|
/// The current registration state.
|
||||||
|
pub registration: Signal<Result<ServiceWorkerRegistration, ServiceWorkerRegistrationError>>,
|
||||||
|
|
||||||
|
/// Whether a SW is currently installing.
|
||||||
|
pub installing: Signal<bool>,
|
||||||
|
|
||||||
|
/// Whether a SW was installed and is now awaiting activation.
|
||||||
|
pub waiting: Signal<bool>,
|
||||||
|
|
||||||
|
/// Whether a SW is active.
|
||||||
|
pub active: Signal<bool>,
|
||||||
|
|
||||||
|
/// Check for ServiceWorker update.
|
||||||
|
pub check_for_update: Callback<()>,
|
||||||
|
|
||||||
|
/// Call this to activate a new ("waiting") SW if one is available.
|
||||||
|
pub skip_waiting: Callback<()>,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct ServiceWorkerScriptUrl(pub String);
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub enum ServiceWorkerRegistrationError {
|
||||||
|
Js(JsValue),
|
||||||
|
NeverQueried,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A leptos action which asynchronously checks for ServiceWorker updates, given an existing ServiceWorkerRegistration.
|
||||||
|
fn create_action_update_sw(
|
||||||
|
) -> Action<ServiceWorkerRegistration, Result<ServiceWorkerRegistration, JsValue>> {
|
||||||
|
create_action(move |registration: &ServiceWorkerRegistration| {
|
||||||
|
let registration = registration.clone();
|
||||||
|
async move {
|
||||||
|
let update_promise = registration.update().expect("update to not fail");
|
||||||
|
wasm_bindgen_futures::JsFuture::from(update_promise)
|
||||||
|
.await
|
||||||
|
.map(|ok| {
|
||||||
|
ok.dyn_into::<ServiceWorkerRegistration>()
|
||||||
|
.expect("conversion into ServiceWorkerRegistration")
|
||||||
|
})
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A leptos action which asynchronously creates or updates and than retrieves the ServiceWorkerRegistration.
|
||||||
|
fn create_action_create_or_update_sw_registration(
|
||||||
|
) -> Action<ServiceWorkerScriptUrl, Result<ServiceWorkerRegistration, JsValue>> {
|
||||||
|
create_action(move |script_url: &ServiceWorkerScriptUrl| {
|
||||||
|
let script_url = script_url.0.to_owned();
|
||||||
|
async move {
|
||||||
|
if let Some(navigator) = use_window().navigator() {
|
||||||
|
let promise = navigator.service_worker().register(script_url.as_str());
|
||||||
|
wasm_bindgen_futures::JsFuture::from(promise)
|
||||||
|
.await
|
||||||
|
.map(|ok| {
|
||||||
|
ok.dyn_into::<ServiceWorkerRegistration>()
|
||||||
|
.expect("conversion into ServiceWorkerRegistration")
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
Err(JsValue::from_str("no navigator"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A leptos action which asynchronously fetches the current ServiceWorkerRegistration.
|
||||||
|
fn create_action_get_sw_registration() -> Action<(), Result<ServiceWorkerRegistration, JsValue>> {
|
||||||
|
create_action(move |(): &()| {
|
||||||
|
async move {
|
||||||
|
if let Some(navigator) = use_window().navigator() {
|
||||||
|
let promise = navigator.service_worker().get_registration(); // Could take a scope like "/app"...
|
||||||
|
wasm_bindgen_futures::JsFuture::from(promise)
|
||||||
|
.await
|
||||||
|
.map(|ok| {
|
||||||
|
ok.dyn_into::<ServiceWorkerRegistration>()
|
||||||
|
.expect("conversion into ServiceWorkerRegistration")
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
Err(JsValue::from_str("no navigator"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|