diff --git a/CHANGELOG.md b/CHANGELOG.md index 65d75ca..213701a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,12 @@ 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). +## [Unreleased] - + +### New Functions 🚀 + +- `use_service_worker` + ## [0.7.1] - 2023-10-02 ### New Function 🚀 diff --git a/Cargo.toml b/Cargo.toml index 2747c15..0031e6d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -15,6 +15,7 @@ homepage = "https://leptos-use.rs" [dependencies] leptos = "0.5" wasm-bindgen = "0.2" +wasm-bindgen-futures = "0.4" js-sys = "0.3" default-struct-builder = "0.5" num = { version = "0.4", optional = true } @@ -69,6 +70,10 @@ features = [ "ResizeObserverSize", "ScrollBehavior", "ScrollToOptions", + "ServiceWorker", + "ServiceWorkerContainer", + "ServiceWorkerRegistration", + "ServiceWorkerState", "Storage", "Touch", "TouchEvent", diff --git a/docs/book/src/SUMMARY.md b/docs/book/src/SUMMARY.md index dbb23c8..955db99 100644 --- a/docs/book/src/SUMMARY.md +++ b/docs/book/src/SUMMARY.md @@ -38,6 +38,7 @@ - [use_media_query](browser/use_media_query.md) - [use_preferred_contrast](browser/use_preferred_contrast.md) - [use_preferred_dark](browser/use_preferred_dark.md) +- [use_service_worker](browser/use_service_worker.md) # Sensors diff --git a/docs/book/src/browser/use_service_worker.md b/docs/book/src/browser/use_service_worker.md new file mode 100644 index 0000000..93f8a0a --- /dev/null +++ b/docs/book/src/browser/use_service_worker.md @@ -0,0 +1,3 @@ +# use_service_worker + + diff --git a/examples/Cargo.toml b/examples/Cargo.toml index 930d976..6fcf5b6 100644 --- a/examples/Cargo.toml +++ b/examples/Cargo.toml @@ -35,6 +35,7 @@ members = [ "use_resize_observer", "use_round", "use_scroll", + "use_service_worker", "use_sorted", "use_storage", "use_throttle_fn", diff --git a/examples/use_service_worker/Cargo.toml b/examples/use_service_worker/Cargo.toml new file mode 100644 index 0000000..878fa9a --- /dev/null +++ b/examples/use_service_worker/Cargo.toml @@ -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" diff --git a/examples/use_service_worker/README.md b/examples/use_service_worker/README.md new file mode 100644 index 0000000..a4e333d --- /dev/null +++ b/examples/use_service_worker/README.md @@ -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 +``` \ No newline at end of file diff --git a/examples/use_service_worker/Trunk.toml b/examples/use_service_worker/Trunk.toml new file mode 100644 index 0000000..241fda5 --- /dev/null +++ b/examples/use_service_worker/Trunk.toml @@ -0,0 +1,7 @@ +[build] +public_url = "/demo/" + +[[hooks]] +stage = "post_build" +command = "bash" +command_arguments = ["-c", "./post_build.sh"] diff --git a/examples/use_service_worker/index.html b/examples/use_service_worker/index.html new file mode 100644 index 0000000..c3733f9 --- /dev/null +++ b/examples/use_service_worker/index.html @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/examples/use_service_worker/input.css b/examples/use_service_worker/input.css new file mode 100644 index 0000000..bd6213e --- /dev/null +++ b/examples/use_service_worker/input.css @@ -0,0 +1,3 @@ +@tailwind base; +@tailwind components; +@tailwind utilities; \ No newline at end of file diff --git a/examples/use_service_worker/manifest.json b/examples/use_service_worker/manifest.json new file mode 100644 index 0000000..8b720cf --- /dev/null +++ b/examples/use_service_worker/manifest.json @@ -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" +} \ No newline at end of file diff --git a/examples/use_service_worker/post_build.sh b/examples/use_service_worker/post_build.sh new file mode 100755 index 0000000..202a47b --- /dev/null +++ b/examples/use_service_worker/post_build.sh @@ -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}" diff --git a/examples/use_service_worker/res/icon/maskable_icon_x128.png b/examples/use_service_worker/res/icon/maskable_icon_x128.png new file mode 100644 index 0000000..f730574 Binary files /dev/null and b/examples/use_service_worker/res/icon/maskable_icon_x128.png differ diff --git a/examples/use_service_worker/res/icon/maskable_icon_x192.png b/examples/use_service_worker/res/icon/maskable_icon_x192.png new file mode 100644 index 0000000..6e308ac Binary files /dev/null and b/examples/use_service_worker/res/icon/maskable_icon_x192.png differ diff --git a/examples/use_service_worker/res/icon/maskable_icon_x384.png b/examples/use_service_worker/res/icon/maskable_icon_x384.png new file mode 100644 index 0000000..3041f52 Binary files /dev/null and b/examples/use_service_worker/res/icon/maskable_icon_x384.png differ diff --git a/examples/use_service_worker/res/icon/maskable_icon_x48.png b/examples/use_service_worker/res/icon/maskable_icon_x48.png new file mode 100644 index 0000000..50e8754 Binary files /dev/null and b/examples/use_service_worker/res/icon/maskable_icon_x48.png differ diff --git a/examples/use_service_worker/res/icon/maskable_icon_x512.png b/examples/use_service_worker/res/icon/maskable_icon_x512.png new file mode 100644 index 0000000..d1e37b9 Binary files /dev/null and b/examples/use_service_worker/res/icon/maskable_icon_x512.png differ diff --git a/examples/use_service_worker/res/icon/maskable_icon_x72.png b/examples/use_service_worker/res/icon/maskable_icon_x72.png new file mode 100644 index 0000000..4196897 Binary files /dev/null and b/examples/use_service_worker/res/icon/maskable_icon_x72.png differ diff --git a/examples/use_service_worker/res/icon/maskable_icon_x96.png b/examples/use_service_worker/res/icon/maskable_icon_x96.png new file mode 100644 index 0000000..32b9490 Binary files /dev/null and b/examples/use_service_worker/res/icon/maskable_icon_x96.png differ diff --git a/examples/use_service_worker/res/icon/pwa.png b/examples/use_service_worker/res/icon/pwa.png new file mode 100644 index 0000000..b5a31af Binary files /dev/null and b/examples/use_service_worker/res/icon/pwa.png differ diff --git a/examples/use_service_worker/res/icon/pwa.svg b/examples/use_service_worker/res/icon/pwa.svg new file mode 100644 index 0000000..55264a9 --- /dev/null +++ b/examples/use_service_worker/res/icon/pwa.svg @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/examples/use_service_worker/rust-toolchain.toml b/examples/use_service_worker/rust-toolchain.toml new file mode 100644 index 0000000..271800c --- /dev/null +++ b/examples/use_service_worker/rust-toolchain.toml @@ -0,0 +1,2 @@ +[toolchain] +channel = "nightly" \ No newline at end of file diff --git a/examples/use_service_worker/service-worker.js b/examples/use_service_worker/service-worker.js new file mode 100644 index 0000000..511a41b --- /dev/null +++ b/examples/use_service_worker/service-worker.js @@ -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; + }); + } + ) +} diff --git a/examples/use_service_worker/src/main.rs b/examples/use_service_worker/src/main.rs new file mode 100644 index 0000000..2df2dcd --- /dev/null +++ b/examples/use_service_worker/src/main.rs @@ -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! { +

"Current build: "{build}

+ +
+ +

"registration: "{move || format!("{:#?}", sw.registration.get())}

+

"installing: "{move || sw.installing.get()}

+

"waiting: "{move || sw.waiting.get()}

+

"active: "{move || sw.active.get()}

+ +
+ + + } +} + +fn main() { + _ = console_log::init_with_level(log::Level::Debug); + console_error_panic_hook::set_once(); + + mount_to(demo_or_body(), || { + view! { } + }) +} + +fn load_meta_element>(name: S) -> Result { + 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::().map_err(|err| { + format!("Unable to cast element to HtmlMetaElement. Err: '{err:?}'.") + }) + }) +} diff --git a/examples/use_service_worker/style/output.css b/examples/use_service_worker/style/output.css new file mode 100644 index 0000000..1c83da6 --- /dev/null +++ b/examples/use_service_worker/style/output.css @@ -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)); + } +} \ No newline at end of file diff --git a/examples/use_service_worker/tailwind.config.js b/examples/use_service_worker/tailwind.config.js new file mode 100644 index 0000000..bc09f5e --- /dev/null +++ b/examples/use_service_worker/tailwind.config.js @@ -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'), + ], +} \ No newline at end of file diff --git a/src/lib.rs b/src/lib.rs index c3384c8..4d2d979 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -25,6 +25,7 @@ mod is_none; mod is_ok; mod is_some; mod on_click_outside; +mod use_service_worker; mod signal_debounced; mod signal_throttled; mod use_active_element; @@ -74,6 +75,7 @@ pub use is_none::*; pub use is_ok::*; pub use is_some::*; pub use on_click_outside::*; +pub use use_service_worker::*; pub use signal_debounced::*; pub use signal_throttled::*; pub use use_active_element::*; diff --git a/src/use_service_worker.rs b/src/use_service_worker.rs new file mode 100644 index 0000000..17f77c3 --- /dev/null +++ b/src/use_service_worker.rs @@ -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) + .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> = + 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) + .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>, + + /// Whether a SW is currently installing. + pub installing: Signal, + + /// Whether a SW was installed and is now awaiting activation. + pub waiting: Signal, + + /// Whether a SW is active. + pub active: Signal, + + /// 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> { + 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::() + .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> { + 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::() + .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> { + 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::() + .expect("conversion into ServiceWorkerRegistration") + }) + } else { + Err(JsValue::from_str("no navigator")) + } + } + }) +}