diff --git a/CI_README.md b/CI_README.md new file mode 100644 index 0000000..e5f305e --- /dev/null +++ b/CI_README.md @@ -0,0 +1,42 @@ +# Gitea Actions CI/CD (build -> push -> deploy) + +This project includes a Gitea Actions workflow at `.gitea/workflows/deploy.yml` which: + +- Builds a Docker image and tags it `latest` as `${REGISTRY_HOST}/${REGISTRY_NAMESPACE}/${REGISTRY_REPO}:latest`. +- Pushes the image to your container registry (supports `REGISTRY_USERNAME`/`REGISTRY_PASSWORD` if needed). +- SSHes to the deployment server and writes `docker-compose.yml` into `/home/services/myapp`, then runs `docker-compose up -d`. + +Required repository secrets (add in Gitea repo settings -> Secrets): + +- DEPLOY_HOST: IP or hostname of the server +- DEPLOY_USER: SSH user +- DEPLOY_KEY: Private SSH key for DEPLOY_USER (no passphrase or use agent) +- REGISTRY_HOST: Registry host (e.g. docker.io or registry.example.com) +- REGISTRY_NAMESPACE: Namespace/org or username +- REGISTRY_REPO: Image/repo name +- (optional) REGISTRY_USERNAME and REGISTRY_PASSWORD for private registries + +How to trigger: +- The workflow triggers on push to `main` and can be triggered manually via `workflow_dispatch`. + +Manual deploy (example): + +```powershell +# Build and push locally +$env:REGISTRY_HOST='registry.example.com' +$env:REGISTRY_NAMESPACE='myuser' +$env:REGISTRY_REPO='greenhomeui' +docker build -t $env:REGISTRY_HOST/$env:REGISTRY_NAMESPACE/$env:REGISTRY_REPO:latest . +docker push $env:REGISTRY_HOST/$env:REGISTRY_NAMESPACE/$env:REGISTRY_REPO:latest + +# Copy docker-compose and run on server +scp docker-compose.yml user@yourserver:/home/services/myapp/docker-compose.yml +ssh user@yourserver "cd /home/services/myapp; docker pull $env:REGISTRY_HOST/$env:REGISTRY_NAMESPACE/$env:REGISTRY_REPO:latest; docker-compose up -d --remove-orphans" +``` + +Manual server helper: +- `scripts/remote-deploy.sh` can be copied to the server and used to pull+run the image. It respects env vars `REGISTRY_HOST`, `REGISTRY_NAMESPACE`, `REGISTRY_REPO` when present. + +Notes: +- The workflow uses `appleboy/ssh-action` to SSH into the server. That action needs the private key provided in `DEPLOY_KEY`. +- The workflow writes a `docker-compose.yml` based on the repo's compose config and uses the `latest` tag. If you prefer not to overwrite server-side compose files, modify the workflow to only run `docker pull` and `docker-compose up -d`. diff --git a/next.config.ts b/next.config.ts index 921073b..ad9d8c4 100644 --- a/next.config.ts +++ b/next.config.ts @@ -1,7 +1,4 @@ import type { NextConfig } from 'next' -import withPWA from 'next-pwa' - -const isProd = process.env.NODE_ENV === 'production' const nextConfig: NextConfig = { reactStrictMode: true, @@ -9,9 +6,4 @@ const nextConfig: NextConfig = { turbopack: { root: __dirname } } -export default withPWA({ - dest: 'public', - disable: !isProd, - register: true, - skipWaiting: true -})(nextConfig) +export default nextConfig diff --git a/package-lock.json b/package-lock.json index 5cb35cd..2dcbe52 100644 --- a/package-lock.json +++ b/package-lock.json @@ -10,6 +10,7 @@ "dependencies": { "chart.js": "^4.5.0", "jalaali-js": "^1.2.8", + "lucide-react": "^0.553.0", "next": "15.5.4", "next-pwa": "^5.6.0", "react": "19.1.0", @@ -7115,6 +7116,14 @@ "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==", "license": "ISC" }, + "node_modules/lucide-react": { + "version": "0.553.0", + "resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-0.553.0.tgz", + "integrity": "sha512-BRgX5zrWmNy/lkVAe0dXBgd7XQdZ3HTf+Hwe3c9WK6dqgnj9h+hxV+MDncM88xDWlCq27+TKvHGE70ViODNILw==", + "peerDependencies": { + "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0" + } + }, "node_modules/magic-string": { "version": "0.30.19", "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.19.tgz", diff --git a/package.json b/package.json index 6c467a2..8c905a0 100644 --- a/package.json +++ b/package.json @@ -11,6 +11,7 @@ "dependencies": { "chart.js": "^4.5.0", "jalaali-js": "^1.2.8", + "lucide-react": "^0.553.0", "next": "15.5.4", "next-pwa": "^5.6.0", "react": "19.1.0", diff --git a/public/fonts/vazirmatn/Vazirmatn-Black.woff2 b/public/fonts/vazirmatn/Vazirmatn-Black.woff2 new file mode 100644 index 0000000..f08cace Binary files /dev/null and b/public/fonts/vazirmatn/Vazirmatn-Black.woff2 differ diff --git a/public/fonts/vazirmatn/Vazirmatn-Bold.woff2 b/public/fonts/vazirmatn/Vazirmatn-Bold.woff2 new file mode 100644 index 0000000..65b427f Binary files /dev/null and b/public/fonts/vazirmatn/Vazirmatn-Bold.woff2 differ diff --git a/public/fonts/vazirmatn/Vazirmatn-ExtraBold.woff2 b/public/fonts/vazirmatn/Vazirmatn-ExtraBold.woff2 new file mode 100644 index 0000000..c074e70 Binary files /dev/null and b/public/fonts/vazirmatn/Vazirmatn-ExtraBold.woff2 differ diff --git a/public/fonts/vazirmatn/Vazirmatn-ExtraLight.woff2 b/public/fonts/vazirmatn/Vazirmatn-ExtraLight.woff2 new file mode 100644 index 0000000..997dea0 Binary files /dev/null and b/public/fonts/vazirmatn/Vazirmatn-ExtraLight.woff2 differ diff --git a/public/fonts/vazirmatn/Vazirmatn-Light.woff2 b/public/fonts/vazirmatn/Vazirmatn-Light.woff2 new file mode 100644 index 0000000..d154722 Binary files /dev/null and b/public/fonts/vazirmatn/Vazirmatn-Light.woff2 differ diff --git a/public/fonts/vazirmatn/Vazirmatn-Medium.woff2 b/public/fonts/vazirmatn/Vazirmatn-Medium.woff2 new file mode 100644 index 0000000..495af75 Binary files /dev/null and b/public/fonts/vazirmatn/Vazirmatn-Medium.woff2 differ diff --git a/public/fonts/vazirmatn/Vazirmatn-Regular.woff2 b/public/fonts/vazirmatn/Vazirmatn-Regular.woff2 new file mode 100644 index 0000000..c9824c8 Binary files /dev/null and b/public/fonts/vazirmatn/Vazirmatn-Regular.woff2 differ diff --git a/public/fonts/vazirmatn/Vazirmatn-SemiBold.woff2 b/public/fonts/vazirmatn/Vazirmatn-SemiBold.woff2 new file mode 100644 index 0000000..5301641 Binary files /dev/null and b/public/fonts/vazirmatn/Vazirmatn-SemiBold.woff2 differ diff --git a/public/fonts/vazirmatn/Vazirmatn-Thin.woff2 b/public/fonts/vazirmatn/Vazirmatn-Thin.woff2 new file mode 100644 index 0000000..b7df278 Binary files /dev/null and b/public/fonts/vazirmatn/Vazirmatn-Thin.woff2 differ diff --git a/public/fonts/vazirmatn/Vazirmatn[wght].woff2 b/public/fonts/vazirmatn/Vazirmatn[wght].woff2 new file mode 100644 index 0000000..a501289 Binary files /dev/null and b/public/fonts/vazirmatn/Vazirmatn[wght].woff2 differ diff --git a/public/fonts/vazirmatn/style.css b/public/fonts/vazirmatn/style.css new file mode 100644 index 0000000..cd8fc81 --- /dev/null +++ b/public/fonts/vazirmatn/style.css @@ -0,0 +1,72 @@ +/* Generated by script */ +@font-face { + font-family: Vazirmatn; + src: url('Vazirmatn-Thin.woff2') format('woff2'); + font-weight: 100; + font-style: normal; + font-display: swap; +} + +@font-face { + font-family: Vazirmatn; + src: url('Vazirmatn-ExtraLight.woff2') format('woff2'); + font-weight: 200; + font-style: normal; + font-display: swap; +} + +@font-face { + font-family: Vazirmatn; + src: url('Vazirmatn-Light.woff2') format('woff2'); + font-weight: 300; + font-style: normal; + font-display: swap; +} + +@font-face { + font-family: Vazirmatn; + src: url('Vazirmatn-Regular.woff2') format('woff2'); + font-weight: 400; + font-style: normal; + font-display: swap; +} + +@font-face { + font-family: Vazirmatn; + src: url('Vazirmatn-Medium.woff2') format('woff2'); + font-weight: 500; + font-style: normal; + font-display: swap; +} + +@font-face { + font-family: Vazirmatn; + src: url('Vazirmatn-SemiBold.woff2') format('woff2'); + font-weight: 600; + font-style: normal; + font-display: swap; +} + +@font-face { + font-family: Vazirmatn; + src: url('Vazirmatn-Bold.woff2') format('woff2'); + font-weight: 700; + font-style: normal; + font-display: swap; +} + +@font-face { + font-family: Vazirmatn; + src: url('Vazirmatn-ExtraBold.woff2') format('woff2'); + font-weight: 800; + font-style: normal; + font-display: swap; +} + +@font-face { + font-family: Vazirmatn; + src: url('Vazirmatn-Black.woff2') format('woff2'); + font-weight: 900; + font-style: normal; + font-display: swap; +} diff --git a/public/manifest.json b/public/manifest.json index ae79f70..e69de29 100644 --- a/public/manifest.json +++ b/public/manifest.json @@ -1,20 +0,0 @@ -{ - "name": "GreenHome", - "short_name": "GreenHome", - "start_url": "/", - "display": "standalone", - "background_color": "#ffffff", - "theme_color": "#16a34a", - "icons": [ - { - "src": "/icon-192.png", - "sizes": "192x192", - "type": "image/png" - }, - { - "src": "/icon-512.png", - "sizes": "512x512", - "type": "image/png" - } - ] -} \ No newline at end of file diff --git a/public/sw.js b/public/sw.js index c034636..cdbf02a 100644 --- a/public/sw.js +++ b/public/sw.js @@ -1 +1,178 @@ -if(!self.define){let e,s={};const a=(a,n)=>(a=new URL(a+".js",n).href,s[a]||new Promise(s=>{if("document"in self){const e=document.createElement("script");e.src=a,e.onload=s,document.head.appendChild(e)}else e=a,importScripts(a),s()}).then(()=>{let e=s[a];if(!e)throw new Error(`Module ${a} didn’t register its module`);return e}));self.define=(n,t)=>{const i=e||("document"in self?document.currentScript.src:"")||location.href;if(s[i])return;let c={};const r=e=>a(e,i),f={module:{uri:i},exports:c,require:r};s[i]=Promise.all(n.map(e=>f[e]||r(e))).then(e=>(t(...e),c))}}define(["./workbox-4754cb34"],function(e){"use strict";importScripts(),self.skipWaiting(),e.clientsClaim(),e.precacheAndRoute([{url:"/_next/app-build-manifest.json",revision:"a15966a041cf07b186d84e068867b754"},{url:"/_next/static/X6BpqBqKZqclHqSOt2VZ4/_buildManifest.js",revision:"dfa6ee76df81d588cd43a11576b4f2d1"},{url:"/_next/static/X6BpqBqKZqclHqSOt2VZ4/_ssgManifest.js",revision:"b6652df95db52feb4daf4eca35380933"},{url:"/_next/static/chunks/139.7a5a8e93a21948c1.js",revision:"7a5a8e93a21948c1"},{url:"/_next/static/chunks/223-5a7ab5e72b6f383b.js",revision:"5a7ab5e72b6f383b"},{url:"/_next/static/chunks/255-4efeec91c7871d79.js",revision:"4efeec91c7871d79"},{url:"/_next/static/chunks/4bd1b696-c023c6e3521b1417.js",revision:"c023c6e3521b1417"},{url:"/_next/static/chunks/646.f342b7cffc01feb0.js",revision:"f342b7cffc01feb0"},{url:"/_next/static/chunks/app/_not-found/page-5191f0f6258b1ec1.js",revision:"5191f0f6258b1ec1"},{url:"/_next/static/chunks/app/calendar/month/page-0434baa5123a85f1.js",revision:"0434baa5123a85f1"},{url:"/_next/static/chunks/app/calendar/page-99af92619a2ddfec.js",revision:"99af92619a2ddfec"},{url:"/_next/static/chunks/app/day_details/page-5131311f21adb520.js",revision:"5131311f21adb520"},{url:"/_next/static/chunks/app/device_settings/page-6829625d24bec575.js",revision:"6829625d24bec575"},{url:"/_next/static/chunks/app/devices/page-72355d75ab5f2149.js",revision:"72355d75ab5f2149"},{url:"/_next/static/chunks/app/layout-20802b7028a4f9b5.js",revision:"20802b7028a4f9b5"},{url:"/_next/static/chunks/app/month_select/page-8d4c94bee7fd07af.js",revision:"8d4c94bee7fd07af"},{url:"/_next/static/chunks/app/page-f47082ca351a8369.js",revision:"f47082ca351a8369"},{url:"/_next/static/chunks/ca377847-f6e45424dfc78afc.js",revision:"f6e45424dfc78afc"},{url:"/_next/static/chunks/framework-acd67e14855de5a2.js",revision:"acd67e14855de5a2"},{url:"/_next/static/chunks/main-1e4b9f954557e26e.js",revision:"1e4b9f954557e26e"},{url:"/_next/static/chunks/main-app-ccaeafef51f7075b.js",revision:"ccaeafef51f7075b"},{url:"/_next/static/chunks/pages/_app-82835f42865034fa.js",revision:"82835f42865034fa"},{url:"/_next/static/chunks/pages/_error-013f4188946cdd04.js",revision:"013f4188946cdd04"},{url:"/_next/static/chunks/polyfills-42372ed130431b0a.js",revision:"846118c33b2c0e922d7b3a7676f81f6f"},{url:"/_next/static/chunks/webpack-a2a7106df7a920d1.js",revision:"a2a7106df7a920d1"},{url:"/_next/static/css/f20cda96e4316492.css",revision:"f20cda96e4316492"},{url:"/file.svg",revision:"d09f95206c3fa0bb9bd9fefabfd0ea71"},{url:"/globe.svg",revision:"2aaafa6a49b6563925fe440891e32717"},{url:"/icon-192.png",revision:"a8f5fbdcdd5ae60dfbf04c412a29366c"},{url:"/icon-512.png",revision:"386b6a1e6cf3e2e5012c72359a20018b"},{url:"/manifest.json",revision:"bb3b5e9c94d68d189f1ad2f0cf8e4c0e"},{url:"/next.svg",revision:"8e061864f388b47f33a1c3780831193e"},{url:"/vercel.svg",revision:"c0af2f507b369b085b35ef4bbe3bcf1e"},{url:"/window.svg",revision:"a2760511c65806022ad20adf74370ff3"}],{ignoreURLParametersMatching:[]}),e.cleanupOutdatedCaches(),e.registerRoute("/",new e.NetworkFirst({cacheName:"start-url",plugins:[{cacheWillUpdate:async({request:e,response:s,event:a,state:n})=>s&&"opaqueredirect"===s.type?new Response(s.body,{status:200,statusText:"OK",headers:s.headers}):s}]}),"GET"),e.registerRoute(/^https:\/\/fonts\.(?:gstatic)\.com\/.*/i,new e.CacheFirst({cacheName:"google-fonts-webfonts",plugins:[new e.ExpirationPlugin({maxEntries:4,maxAgeSeconds:31536e3})]}),"GET"),e.registerRoute(/^https:\/\/fonts\.(?:googleapis)\.com\/.*/i,new e.StaleWhileRevalidate({cacheName:"google-fonts-stylesheets",plugins:[new e.ExpirationPlugin({maxEntries:4,maxAgeSeconds:604800})]}),"GET"),e.registerRoute(/\.(?:eot|otf|ttc|ttf|woff|woff2|font.css)$/i,new e.StaleWhileRevalidate({cacheName:"static-font-assets",plugins:[new e.ExpirationPlugin({maxEntries:4,maxAgeSeconds:604800})]}),"GET"),e.registerRoute(/\.(?:jpg|jpeg|gif|png|svg|ico|webp)$/i,new e.StaleWhileRevalidate({cacheName:"static-image-assets",plugins:[new e.ExpirationPlugin({maxEntries:64,maxAgeSeconds:86400})]}),"GET"),e.registerRoute(/\/_next\/image\?url=.+$/i,new e.StaleWhileRevalidate({cacheName:"next-image",plugins:[new e.ExpirationPlugin({maxEntries:64,maxAgeSeconds:86400})]}),"GET"),e.registerRoute(/\.(?:mp3|wav|ogg)$/i,new e.CacheFirst({cacheName:"static-audio-assets",plugins:[new e.RangeRequestsPlugin,new e.ExpirationPlugin({maxEntries:32,maxAgeSeconds:86400})]}),"GET"),e.registerRoute(/\.(?:mp4)$/i,new e.CacheFirst({cacheName:"static-video-assets",plugins:[new e.RangeRequestsPlugin,new e.ExpirationPlugin({maxEntries:32,maxAgeSeconds:86400})]}),"GET"),e.registerRoute(/\.(?:js)$/i,new e.StaleWhileRevalidate({cacheName:"static-js-assets",plugins:[new e.ExpirationPlugin({maxEntries:32,maxAgeSeconds:86400})]}),"GET"),e.registerRoute(/\.(?:css|less)$/i,new e.StaleWhileRevalidate({cacheName:"static-style-assets",plugins:[new e.ExpirationPlugin({maxEntries:32,maxAgeSeconds:86400})]}),"GET"),e.registerRoute(/\/_next\/data\/.+\/.+\.json$/i,new e.StaleWhileRevalidate({cacheName:"next-data",plugins:[new e.ExpirationPlugin({maxEntries:32,maxAgeSeconds:86400})]}),"GET"),e.registerRoute(/\.(?:json|xml|csv)$/i,new e.NetworkFirst({cacheName:"static-data-assets",plugins:[new e.ExpirationPlugin({maxEntries:32,maxAgeSeconds:86400})]}),"GET"),e.registerRoute(({url:e})=>{if(!(self.origin===e.origin))return!1;const s=e.pathname;return!s.startsWith("/api/auth/")&&!!s.startsWith("/api/")},new e.NetworkFirst({cacheName:"apis",networkTimeoutSeconds:10,plugins:[new e.ExpirationPlugin({maxEntries:16,maxAgeSeconds:86400})]}),"GET"),e.registerRoute(({url:e})=>{if(!(self.origin===e.origin))return!1;return!e.pathname.startsWith("/api/")},new e.NetworkFirst({cacheName:"others",networkTimeoutSeconds:10,plugins:[new e.ExpirationPlugin({maxEntries:32,maxAgeSeconds:86400})]}),"GET"),e.registerRoute(({url:e})=>!(self.origin===e.origin),new e.NetworkFirst({cacheName:"cross-origin",networkTimeoutSeconds:10,plugins:[new e.ExpirationPlugin({maxEntries:32,maxAgeSeconds:3600})]}),"GET")}); +const CACHE_NAME = 'greenhome-v2'; +const STATIC_CACHE_NAME = 'greenhome-static-v2'; + +// Static assets to cache on install +const STATIC_FILES_TO_CACHE = [ + '/', + '/manifest.json', + '/icon-192.png', + '/icon-512.png', +]; + +// Check if request is for static assets +function isStaticAsset(url) { + return ( + url.includes('/_next/static/') || + url.includes('/_next/image') || + url.match(/\.(js|css|woff|woff2|ttf|eot|svg|png|jpg|jpeg|gif|webp|ico)$/i) + ); +} + +// Check if request is for external API (skip caching) +function isExternalApiRequest(url) { + return url.startsWith('http') && !url.startsWith(self.location.origin); +} + +self.addEventListener('install', (event) => { + event.waitUntil( + (async () => { + const cache = await caches.open(STATIC_CACHE_NAME); + try { + await cache.addAll(STATIC_FILES_TO_CACHE); + } catch (error) { + console.log('Some static files failed to cache:', error); + } + await self.skipWaiting(); + })() + ); +}); + +self.addEventListener('activate', (event) => { + event.waitUntil( + (async () => { + await self.clients.claim(); + + // Remove old caches + const keys = await caches.keys(); + await Promise.all( + keys + .filter((key) => key !== CACHE_NAME && key !== STATIC_CACHE_NAME) + .map((key) => caches.delete(key)) + ); + })() + ); +}); + +self.addEventListener('fetch', (event) => { + const { request } = event; + const url = new URL(request.url); + + // Skip non-GET requests and external API requests + if (request.method !== 'GET' || isExternalApiRequest(url.href)) { + return; + } + + // Handle navigation requests (pages) + if (request.mode === 'navigate') { + event.respondWith( + (async () => { + try { + // Try network first + const preloadResponse = await event.preloadResponse; + if (preloadResponse) { + const cache = await caches.open(CACHE_NAME); + cache.put(request, preloadResponse.clone()); + return preloadResponse; + } + + const networkResponse = await fetch(request); + + // Cache successful responses + if (networkResponse.ok) { + const cache = await caches.open(CACHE_NAME); + cache.put(request, networkResponse.clone()); + } + + return networkResponse; + } catch (error) { + // Network failed, try cache + const cache = await caches.open(CACHE_NAME); + const cachedResponse = await cache.match(request); + + if (cachedResponse) { + return cachedResponse; + } + + // Fallback to home page if available + const homePage = await cache.match('/'); + if (homePage) { + return homePage; + } + + // Last resort: return offline page + return new Response('Offline - No internet connection', { + status: 503, + statusText: 'Service Unavailable', + headers: { 'Content-Type': 'text/html' }, + }); + } + })() + ); + return; + } + + // Handle static assets (Cache First strategy) + if (isStaticAsset(url.href)) { + event.respondWith( + (async () => { + const cache = await caches.open(STATIC_CACHE_NAME); + const cachedResponse = await cache.match(request); + + if (cachedResponse) { + return cachedResponse; + } + + try { + const networkResponse = await fetch(request); + + // Cache successful responses + if (networkResponse.ok) { + cache.put(request, networkResponse.clone()); + } + + return networkResponse; + } catch (error) { + // If network fails and no cache, return error + return new Response('Resource not available offline', { + status: 503, + statusText: 'Service Unavailable', + }); + } + })() + ); + return; + } + + // Handle other requests (Network First strategy) + event.respondWith( + (async () => { + const cache = await caches.open(CACHE_NAME); + + try { + // Try network first + const networkResponse = await fetch(request); + + // Cache successful responses + if (networkResponse.ok) { + cache.put(request, networkResponse.clone()); + } + + return networkResponse; + } catch (error) { + // Network failed, try cache + const cachedResponse = await cache.match(request); + + if (cachedResponse) { + return cachedResponse; + } + + // Return error if no cache available + return new Response('Resource not available offline', { + status: 503, + statusText: 'Service Unavailable', + }); + } + })() + ); +}); + diff --git a/public/workbox-00a24876.js b/public/workbox-00a24876.js new file mode 100644 index 0000000..c2e0217 --- /dev/null +++ b/public/workbox-00a24876.js @@ -0,0 +1 @@ +define(["exports"],function(t){"use strict";try{self["workbox:core:6.5.4"]&&_()}catch(t){}const e=(t,...e)=>{let s=t;return e.length>0&&(s+=` :: ${JSON.stringify(e)}`),s};class s extends Error{constructor(t,s){super(e(t,s)),this.name=t,this.details=s}}try{self["workbox:routing:6.5.4"]&&_()}catch(t){}const n=t=>t&&"object"==typeof t?t:{handle:t};class i{constructor(t,e,s="GET"){this.handler=n(e),this.match=t,this.method=s}setCatchHandler(t){this.catchHandler=n(t)}}class r extends i{constructor(t,e,s){super(({url:e})=>{const s=t.exec(e.href);if(s&&(e.origin===location.origin||0===s.index))return s.slice(1)},e,s)}}class a{constructor(){this.t=new Map,this.i=new Map}get routes(){return this.t}addFetchListener(){self.addEventListener("fetch",t=>{const{request:e}=t,s=this.handleRequest({request:e,event:t});s&&t.respondWith(s)})}addCacheListener(){self.addEventListener("message",t=>{if(t.data&&"CACHE_URLS"===t.data.type){const{payload:e}=t.data,s=Promise.all(e.urlsToCache.map(e=>{"string"==typeof e&&(e=[e]);const s=new Request(...e);return this.handleRequest({request:s,event:t})}));t.waitUntil(s),t.ports&&t.ports[0]&&s.then(()=>t.ports[0].postMessage(!0))}})}handleRequest({request:t,event:e}){const s=new URL(t.url,location.href);if(!s.protocol.startsWith("http"))return;const n=s.origin===location.origin,{params:i,route:r}=this.findMatchingRoute({event:e,request:t,sameOrigin:n,url:s});let a=r&&r.handler;const o=t.method;if(!a&&this.i.has(o)&&(a=this.i.get(o)),!a)return;let c;try{c=a.handle({url:s,request:t,event:e,params:i})}catch(t){c=Promise.reject(t)}const h=r&&r.catchHandler;return c instanceof Promise&&(this.o||h)&&(c=c.catch(async n=>{if(h)try{return await h.handle({url:s,request:t,event:e,params:i})}catch(t){t instanceof Error&&(n=t)}if(this.o)return this.o.handle({url:s,request:t,event:e});throw n})),c}findMatchingRoute({url:t,sameOrigin:e,request:s,event:n}){const i=this.t.get(s.method)||[];for(const r of i){let i;const a=r.match({url:t,sameOrigin:e,request:s,event:n});if(a)return i=a,(Array.isArray(i)&&0===i.length||a.constructor===Object&&0===Object.keys(a).length||"boolean"==typeof a)&&(i=void 0),{route:r,params:i}}return{}}setDefaultHandler(t,e="GET"){this.i.set(e,n(t))}setCatchHandler(t){this.o=n(t)}registerRoute(t){this.t.has(t.method)||this.t.set(t.method,[]),this.t.get(t.method).push(t)}unregisterRoute(t){if(!this.t.has(t.method))throw new s("unregister-route-but-not-found-with-method",{method:t.method});const e=this.t.get(t.method).indexOf(t);if(!(e>-1))throw new s("unregister-route-route-not-registered");this.t.get(t.method).splice(e,1)}}let o;const c=()=>(o||(o=new a,o.addFetchListener(),o.addCacheListener()),o);function h(t,e,n){let a;if("string"==typeof t){const s=new URL(t,location.href);a=new i(({url:t})=>t.href===s.href,e,n)}else if(t instanceof RegExp)a=new r(t,e,n);else if("function"==typeof t)a=new i(t,e,n);else{if(!(t instanceof i))throw new s("unsupported-route-type",{moduleName:"workbox-routing",funcName:"registerRoute",paramName:"capture"});a=t}return c().registerRoute(a),a}try{self["workbox:strategies:6.5.4"]&&_()}catch(t){}const u={cacheWillUpdate:async({response:t})=>200===t.status||0===t.status?t:null},l={googleAnalytics:"googleAnalytics",precache:"precache-v2",prefix:"workbox",runtime:"runtime",suffix:"undefined"!=typeof registration?registration.scope:""},f=t=>[l.prefix,t,l.suffix].filter(t=>t&&t.length>0).join("-"),w=t=>t||f(l.precache),d=t=>t||f(l.runtime);function p(t,e){const s=new URL(t);for(const t of e)s.searchParams.delete(t);return s.href}class y{constructor(){this.promise=new Promise((t,e)=>{this.resolve=t,this.reject=e})}}const m=new Set;function g(t){return"string"==typeof t?new Request(t):t}class R{constructor(t,e){this.h={},Object.assign(this,e),this.event=e.event,this.u=t,this.l=new y,this.p=[],this.m=[...t.plugins],this.R=new Map;for(const t of this.m)this.R.set(t,{});this.event.waitUntil(this.l.promise)}async fetch(t){const{event:e}=this;let n=g(t);if("navigate"===n.mode&&e instanceof FetchEvent&&e.preloadResponse){const t=await e.preloadResponse;if(t)return t}const i=this.hasCallback("fetchDidFail")?n.clone():null;try{for(const t of this.iterateCallbacks("requestWillFetch"))n=await t({request:n.clone(),event:e})}catch(t){if(t instanceof Error)throw new s("plugin-error-request-will-fetch",{thrownErrorMessage:t.message})}const r=n.clone();try{let t;t=await fetch(n,"navigate"===n.mode?void 0:this.u.fetchOptions);for(const s of this.iterateCallbacks("fetchDidSucceed"))t=await s({event:e,request:r,response:t});return t}catch(t){throw i&&await this.runCallbacks("fetchDidFail",{error:t,event:e,originalRequest:i.clone(),request:r.clone()}),t}}async fetchAndCachePut(t){const e=await this.fetch(t),s=e.clone();return this.waitUntil(this.cachePut(t,s)),e}async cacheMatch(t){const e=g(t);let s;const{cacheName:n,matchOptions:i}=this.u,r=await this.getCacheKey(e,"read"),a=Object.assign(Object.assign({},i),{cacheName:n});s=await caches.match(r,a);for(const t of this.iterateCallbacks("cachedResponseWillBeUsed"))s=await t({cacheName:n,matchOptions:i,cachedResponse:s,request:r,event:this.event})||void 0;return s}async cachePut(t,e){const n=g(t);var i;await(i=0,new Promise(t=>setTimeout(t,i)));const r=await this.getCacheKey(n,"write");if(!e)throw new s("cache-put-with-no-response",{url:(a=r.url,new URL(String(a),location.href).href.replace(new RegExp(`^${location.origin}`),""))});var a;const o=await this.v(e);if(!o)return!1;const{cacheName:c,matchOptions:h}=this.u,u=await self.caches.open(c),l=this.hasCallback("cacheDidUpdate"),f=l?await async function(t,e,s,n){const i=p(e.url,s);if(e.url===i)return t.match(e,n);const r=Object.assign(Object.assign({},n),{ignoreSearch:!0}),a=await t.keys(e,r);for(const e of a)if(i===p(e.url,s))return t.match(e,n)}(u,r.clone(),["__WB_REVISION__"],h):null;try{await u.put(r,l?o.clone():o)}catch(t){if(t instanceof Error)throw"QuotaExceededError"===t.name&&await async function(){for(const t of m)await t()}(),t}for(const t of this.iterateCallbacks("cacheDidUpdate"))await t({cacheName:c,oldResponse:f,newResponse:o.clone(),request:r,event:this.event});return!0}async getCacheKey(t,e){const s=`${t.url} | ${e}`;if(!this.h[s]){let n=t;for(const t of this.iterateCallbacks("cacheKeyWillBeUsed"))n=g(await t({mode:e,request:n,event:this.event,params:this.params}));this.h[s]=n}return this.h[s]}hasCallback(t){for(const e of this.u.plugins)if(t in e)return!0;return!1}async runCallbacks(t,e){for(const s of this.iterateCallbacks(t))await s(e)}*iterateCallbacks(t){for(const e of this.u.plugins)if("function"==typeof e[t]){const s=this.R.get(e),n=n=>{const i=Object.assign(Object.assign({},n),{state:s});return e[t](i)};yield n}}waitUntil(t){return this.p.push(t),t}async doneWaiting(){let t;for(;t=this.p.shift();)await t}destroy(){this.l.resolve(null)}async v(t){let e=t,s=!1;for(const t of this.iterateCallbacks("cacheWillUpdate"))if(e=await t({request:this.request,response:e,event:this.event})||void 0,s=!0,!e)break;return s||e&&200!==e.status&&(e=void 0),e}}class v{constructor(t={}){this.cacheName=d(t.cacheName),this.plugins=t.plugins||[],this.fetchOptions=t.fetchOptions,this.matchOptions=t.matchOptions}handle(t){const[e]=this.handleAll(t);return e}handleAll(t){t instanceof FetchEvent&&(t={event:t,request:t.request});const e=t.event,s="string"==typeof t.request?new Request(t.request):t.request,n="params"in t?t.params:void 0,i=new R(this,{event:e,request:s,params:n}),r=this.q(i,s,e);return[r,this.D(r,i,s,e)]}async q(t,e,n){let i;await t.runCallbacks("handlerWillStart",{event:n,request:e});try{if(i=await this.U(e,t),!i||"error"===i.type)throw new s("no-response",{url:e.url})}catch(s){if(s instanceof Error)for(const r of t.iterateCallbacks("handlerDidError"))if(i=await r({error:s,event:n,request:e}),i)break;if(!i)throw s}for(const s of t.iterateCallbacks("handlerWillRespond"))i=await s({event:n,request:e,response:i});return i}async D(t,e,s,n){let i,r;try{i=await t}catch(r){}try{await e.runCallbacks("handlerDidRespond",{event:n,request:s,response:i}),await e.doneWaiting()}catch(t){t instanceof Error&&(r=t)}if(await e.runCallbacks("handlerDidComplete",{event:n,request:s,response:i,error:r}),e.destroy(),r)throw r}}function b(t){t.then(()=>{})}function q(){return q=Object.assign?Object.assign.bind():function(t){for(var e=1;e(t[e]=s,!0),has:(t,e)=>t instanceof IDBTransaction&&("done"===e||"store"===e)||e in t};function O(t){return t!==IDBDatabase.prototype.transaction||"objectStoreNames"in IDBTransaction.prototype?(U||(U=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(t)?function(...e){return t.apply(T(this),e),B(x.get(this))}:function(...e){return B(t.apply(T(this),e))}:function(e,...s){const n=t.call(T(this),e,...s);return L.set(n,e.sort?e.sort():[e]),B(n)}}function k(t){return"function"==typeof t?O(t):(t instanceof IDBTransaction&&function(t){if(I.has(t))return;const e=new Promise((e,s)=>{const n=()=>{t.removeEventListener("complete",i),t.removeEventListener("error",r),t.removeEventListener("abort",r)},i=()=>{e(),n()},r=()=>{s(t.error||new DOMException("AbortError","AbortError")),n()};t.addEventListener("complete",i),t.addEventListener("error",r),t.addEventListener("abort",r)});I.set(t,e)}(t),e=t,(D||(D=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])).some(t=>e instanceof t)?new Proxy(t,N):t);var e}function B(t){if(t instanceof IDBRequest)return function(t){const e=new Promise((e,s)=>{const n=()=>{t.removeEventListener("success",i),t.removeEventListener("error",r)},i=()=>{e(B(t.result)),n()},r=()=>{s(t.error),n()};t.addEventListener("success",i),t.addEventListener("error",r)});return e.then(e=>{e instanceof IDBCursor&&x.set(e,t)}).catch(()=>{}),C.set(e,t),e}(t);if(E.has(t))return E.get(t);const e=k(t);return e!==t&&(E.set(t,e),C.set(e,t)),e}const T=t=>C.get(t);const M=["get","getKey","getAll","getAllKeys","count"],P=["put","add","delete","clear"],W=new Map;function j(t,e){if(!(t instanceof IDBDatabase)||e in t||"string"!=typeof e)return;if(W.get(e))return W.get(e);const s=e.replace(/FromIndex$/,""),n=e!==s,i=P.includes(s);if(!(s in(n?IDBIndex:IDBObjectStore).prototype)||!i&&!M.includes(s))return;const r=async function(t,...e){const r=this.transaction(t,i?"readwrite":"readonly");let a=r.store;return n&&(a=a.index(e.shift())),(await Promise.all([a[s](...e),i&&r.done]))[0]};return W.set(e,r),r}N=(t=>q({},t,{get:(e,s,n)=>j(e,s)||t.get(e,s,n),has:(e,s)=>!!j(e,s)||t.has(e,s)}))(N);try{self["workbox:expiration:6.5.4"]&&_()}catch(t){}const S="cache-entries",K=t=>{const e=new URL(t,location.href);return e.hash="",e.href};class A{constructor(t){this._=null,this.I=t}L(t){const e=t.createObjectStore(S,{keyPath:"id"});e.createIndex("cacheName","cacheName",{unique:!1}),e.createIndex("timestamp","timestamp",{unique:!1})}C(t){this.L(t),this.I&&function(t,{blocked:e}={}){const s=indexedDB.deleteDatabase(t);e&&s.addEventListener("blocked",t=>e(t.oldVersion,t)),B(s).then(()=>{})}(this.I)}async setTimestamp(t,e){const s={url:t=K(t),timestamp:e,cacheName:this.I,id:this.N(t)},n=(await this.getDb()).transaction(S,"readwrite",{durability:"relaxed"});await n.store.put(s),await n.done}async getTimestamp(t){const e=await this.getDb(),s=await e.get(S,this.N(t));return null==s?void 0:s.timestamp}async expireEntries(t,e){const s=await this.getDb();let n=await s.transaction(S).store.index("timestamp").openCursor(null,"prev");const i=[];let r=0;for(;n;){const s=n.value;s.cacheName===this.I&&(t&&s.timestamp=e?i.push(n.value):r++),n=await n.continue()}const a=[];for(const t of i)await s.delete(S,t.id),a.push(t.url);return a}N(t){return this.I+"|"+K(t)}async getDb(){return this._||(this._=await function(t,e,{blocked:s,upgrade:n,blocking:i,terminated:r}={}){const a=indexedDB.open(t,e),o=B(a);return n&&a.addEventListener("upgradeneeded",t=>{n(B(a.result),t.oldVersion,t.newVersion,B(a.transaction),t)}),s&&a.addEventListener("blocked",t=>s(t.oldVersion,t.newVersion,t)),o.then(t=>{r&&t.addEventListener("close",()=>r()),i&&t.addEventListener("versionchange",t=>i(t.oldVersion,t.newVersion,t))}).catch(()=>{}),o}("workbox-expiration",1,{upgrade:this.C.bind(this)})),this._}}class F{constructor(t,e={}){this.O=!1,this.k=!1,this.B=e.maxEntries,this.T=e.maxAgeSeconds,this.M=e.matchOptions,this.I=t,this.P=new A(t)}async expireEntries(){if(this.O)return void(this.k=!0);this.O=!0;const t=this.T?Date.now()-1e3*this.T:0,e=await this.P.expireEntries(t,this.B),s=await self.caches.open(this.I);for(const t of e)await s.delete(t,this.M);this.O=!1,this.k&&(this.k=!1,b(this.expireEntries()))}async updateTimestamp(t){await this.P.setTimestamp(t,Date.now())}async isURLExpired(t){if(this.T){const e=await this.P.getTimestamp(t),s=Date.now()-1e3*this.T;return void 0===e||e{e&&(e.originalRequest=t)},this.cachedResponseWillBeUsed=async({event:t,state:e,cachedResponse:s})=>{if("install"===t.type&&e&&e.originalRequest&&e.originalRequest instanceof Request){const t=e.originalRequest.url;s?this.notUpdatedURLs.push(t):this.updatedURLs.push(t)}return s}}}class V{constructor({precacheController:t}){this.cacheKeyWillBeUsed=async({request:t,params:e})=>{const s=(null==e?void 0:e.cacheKey)||this.W.getCacheKeyForURL(t.url);return s?new Request(s,{headers:t.headers}):t},this.W=t}}let J,Q;async function z(t,e){let n=null;if(t.url){n=new URL(t.url).origin}if(n!==self.location.origin)throw new s("cross-origin-copy-response",{origin:n});const i=t.clone(),r={headers:new Headers(i.headers),status:i.status,statusText:i.statusText},a=e?e(r):r,o=function(){if(void 0===J){const t=new Response("");if("body"in t)try{new Response(t.body),J=!0}catch(t){J=!1}J=!1}return J}()?i.body:await i.blob();return new Response(o,a)}class X extends v{constructor(t={}){t.cacheName=w(t.cacheName),super(t),this.j=!1!==t.fallbackToNetwork,this.plugins.push(X.copyRedirectedCacheableResponsesPlugin)}async U(t,e){const s=await e.cacheMatch(t);return s||(e.event&&"install"===e.event.type?await this.S(t,e):await this.K(t,e))}async K(t,e){let n;const i=e.params||{};if(!this.j)throw new s("missing-precache-entry",{cacheName:this.cacheName,url:t.url});{const s=i.integrity,r=t.integrity,a=!r||r===s;n=await e.fetch(new Request(t,{integrity:"no-cors"!==t.mode?r||s:void 0})),s&&a&&"no-cors"!==t.mode&&(this.A(),await e.cachePut(t,n.clone()))}return n}async S(t,e){this.A();const n=await e.fetch(t);if(!await e.cachePut(t,n.clone()))throw new s("bad-precaching-response",{url:t.url,status:n.status});return n}A(){let t=null,e=0;for(const[s,n]of this.plugins.entries())n!==X.copyRedirectedCacheableResponsesPlugin&&(n===X.defaultPrecacheCacheabilityPlugin&&(t=s),n.cacheWillUpdate&&e++);0===e?this.plugins.push(X.defaultPrecacheCacheabilityPlugin):e>1&&null!==t&&this.plugins.splice(t,1)}}X.defaultPrecacheCacheabilityPlugin={cacheWillUpdate:async({response:t})=>!t||t.status>=400?null:t},X.copyRedirectedCacheableResponsesPlugin={cacheWillUpdate:async({response:t})=>t.redirected?await z(t):t};class Y{constructor({cacheName:t,plugins:e=[],fallbackToNetwork:s=!0}={}){this.F=new Map,this.H=new Map,this.$=new Map,this.u=new X({cacheName:w(t),plugins:[...e,new V({precacheController:this})],fallbackToNetwork:s}),this.install=this.install.bind(this),this.activate=this.activate.bind(this)}get strategy(){return this.u}precache(t){this.addToCacheList(t),this.G||(self.addEventListener("install",this.install),self.addEventListener("activate",this.activate),this.G=!0)}addToCacheList(t){const e=[];for(const n of t){"string"==typeof n?e.push(n):n&&void 0===n.revision&&e.push(n.url);const{cacheKey:t,url:i}=$(n),r="string"!=typeof n&&n.revision?"reload":"default";if(this.F.has(i)&&this.F.get(i)!==t)throw new s("add-to-cache-list-conflicting-entries",{firstEntry:this.F.get(i),secondEntry:t});if("string"!=typeof n&&n.integrity){if(this.$.has(t)&&this.$.get(t)!==n.integrity)throw new s("add-to-cache-list-conflicting-integrities",{url:i});this.$.set(t,n.integrity)}if(this.F.set(i,t),this.H.set(i,r),e.length>0){const t=`Workbox is precaching URLs without revision info: ${e.join(", ")}\nThis is generally NOT safe. Learn more at https://bit.ly/wb-precache`;console.warn(t)}}}install(t){return H(t,async()=>{const e=new G;this.strategy.plugins.push(e);for(const[e,s]of this.F){const n=this.$.get(s),i=this.H.get(e),r=new Request(e,{integrity:n,cache:i,credentials:"same-origin"});await Promise.all(this.strategy.handleAll({params:{cacheKey:s},request:r,event:t}))}const{updatedURLs:s,notUpdatedURLs:n}=e;return{updatedURLs:s,notUpdatedURLs:n}})}activate(t){return H(t,async()=>{const t=await self.caches.open(this.strategy.cacheName),e=await t.keys(),s=new Set(this.F.values()),n=[];for(const i of e)s.has(i.url)||(await t.delete(i),n.push(i.url));return{deletedURLs:n}})}getURLsToCacheKeys(){return this.F}getCachedURLs(){return[...this.F.keys()]}getCacheKeyForURL(t){const e=new URL(t,location.href);return this.F.get(e.href)}getIntegrityForCacheKey(t){return this.$.get(t)}async matchPrecache(t){const e=t instanceof Request?t.url:t,s=this.getCacheKeyForURL(e);if(s){return(await self.caches.open(this.strategy.cacheName)).match(s)}}createHandlerBoundToURL(t){const e=this.getCacheKeyForURL(t);if(!e)throw new s("non-precached-url",{url:t});return s=>(s.request=new Request(t),s.params=Object.assign({cacheKey:e},s.params),this.strategy.handle(s))}}const Z=()=>(Q||(Q=new Y),Q);class tt extends i{constructor(t,e){super(({request:s})=>{const n=t.getURLsToCacheKeys();for(const i of function*(t,{ignoreURLParametersMatching:e=[/^utm_/,/^fbclid$/],directoryIndex:s="index.html",cleanURLs:n=!0,urlManipulation:i}={}){const r=new URL(t,location.href);r.hash="",yield r.href;const a=function(t,e=[]){for(const s of[...t.searchParams.keys()])e.some(t=>t.test(s))&&t.searchParams.delete(s);return t}(r,e);if(yield a.href,s&&a.pathname.endsWith("/")){const t=new URL(a.href);t.pathname+=s,yield t.href}if(n){const t=new URL(a.href);t.pathname+=".html",yield t.href}if(i){const t=i({url:r});for(const e of t)yield e.href}}(s.url,e)){const e=n.get(i);if(e){return{cacheKey:e,integrity:t.getIntegrityForCacheKey(e)}}}},t.strategy)}}t.CacheFirst=class extends v{async U(t,e){let n,i=await e.cacheMatch(t);if(!i)try{i=await e.fetchAndCachePut(t)}catch(t){t instanceof Error&&(n=t)}if(!i)throw new s("no-response",{url:t.url,error:n});return i}},t.ExpirationPlugin=class{constructor(t={}){this.cachedResponseWillBeUsed=async({event:t,request:e,cacheName:s,cachedResponse:n})=>{if(!n)return null;const i=this.V(n),r=this.J(s);b(r.expireEntries());const a=r.updateTimestamp(e.url);if(t)try{t.waitUntil(a)}catch(t){}return i?n:null},this.cacheDidUpdate=async({cacheName:t,request:e})=>{const s=this.J(t);await s.updateTimestamp(e.url),await s.expireEntries()},this.X=t,this.T=t.maxAgeSeconds,this.Y=new Map,t.purgeOnQuotaError&&function(t){m.add(t)}(()=>this.deleteCacheAndMetadata())}J(t){if(t===d())throw new s("expire-custom-caches-only");let e=this.Y.get(t);return e||(e=new F(t,this.X),this.Y.set(t,e)),e}V(t){if(!this.T)return!0;const e=this.Z(t);if(null===e)return!0;return e>=Date.now()-1e3*this.T}Z(t){if(!t.headers.has("date"))return null;const e=t.headers.get("date"),s=new Date(e).getTime();return isNaN(s)?null:s}async deleteCacheAndMetadata(){for(const[t,e]of this.Y)await self.caches.delete(t),await e.delete();this.Y=new Map}},t.NetworkFirst=class extends v{constructor(t={}){super(t),this.plugins.some(t=>"cacheWillUpdate"in t)||this.plugins.unshift(u),this.tt=t.networkTimeoutSeconds||0}async U(t,e){const n=[],i=[];let r;if(this.tt){const{id:s,promise:a}=this.et({request:t,logs:n,handler:e});r=s,i.push(a)}const a=this.st({timeoutId:r,request:t,logs:n,handler:e});i.push(a);const o=await e.waitUntil((async()=>await e.waitUntil(Promise.race(i))||await a)());if(!o)throw new s("no-response",{url:t.url});return o}et({request:t,logs:e,handler:s}){let n;return{promise:new Promise(e=>{n=setTimeout(async()=>{e(await s.cacheMatch(t))},1e3*this.tt)}),id:n}}async st({timeoutId:t,request:e,logs:s,handler:n}){let i,r;try{r=await n.fetchAndCachePut(e)}catch(t){t instanceof Error&&(i=t)}return t&&clearTimeout(t),!i&&r||(r=await n.cacheMatch(e)),r}},t.StaleWhileRevalidate=class extends v{constructor(t={}){super(t),this.plugins.some(t=>"cacheWillUpdate"in t)||this.plugins.unshift(u)}async U(t,e){const n=e.fetchAndCachePut(t).catch(()=>{});e.waitUntil(n);let i,r=await e.cacheMatch(t);if(r);else try{r=await n}catch(t){t instanceof Error&&(i=t)}if(!r)throw new s("no-response",{url:t.url,error:i});return r}},t.cleanupOutdatedCaches=function(){self.addEventListener("activate",t=>{const e=w();t.waitUntil((async(t,e="-precache-")=>{const s=(await self.caches.keys()).filter(s=>s.includes(e)&&s.includes(self.registration.scope)&&s!==t);return await Promise.all(s.map(t=>self.caches.delete(t))),s})(e).then(t=>{}))})},t.clientsClaim=function(){self.addEventListener("activate",()=>self.clients.claim())},t.precacheAndRoute=function(t,e){!function(t){Z().precache(t)}(t),function(t){const e=Z();h(new tt(e,t))}(e)},t.registerRoute=h}); diff --git a/public/workbox-4754cb34.js b/public/workbox-4754cb34.js deleted file mode 100644 index 788fd6c..0000000 --- a/public/workbox-4754cb34.js +++ /dev/null @@ -1 +0,0 @@ -define(["exports"],function(t){"use strict";try{self["workbox:core:6.5.4"]&&_()}catch(t){}const e=(t,...e)=>{let s=t;return e.length>0&&(s+=` :: ${JSON.stringify(e)}`),s};class s extends Error{constructor(t,s){super(e(t,s)),this.name=t,this.details=s}}try{self["workbox:routing:6.5.4"]&&_()}catch(t){}const n=t=>t&&"object"==typeof t?t:{handle:t};class r{constructor(t,e,s="GET"){this.handler=n(e),this.match=t,this.method=s}setCatchHandler(t){this.catchHandler=n(t)}}class i extends r{constructor(t,e,s){super(({url:e})=>{const s=t.exec(e.href);if(s&&(e.origin===location.origin||0===s.index))return s.slice(1)},e,s)}}class a{constructor(){this.t=new Map,this.i=new Map}get routes(){return this.t}addFetchListener(){self.addEventListener("fetch",t=>{const{request:e}=t,s=this.handleRequest({request:e,event:t});s&&t.respondWith(s)})}addCacheListener(){self.addEventListener("message",t=>{if(t.data&&"CACHE_URLS"===t.data.type){const{payload:e}=t.data,s=Promise.all(e.urlsToCache.map(e=>{"string"==typeof e&&(e=[e]);const s=new Request(...e);return this.handleRequest({request:s,event:t})}));t.waitUntil(s),t.ports&&t.ports[0]&&s.then(()=>t.ports[0].postMessage(!0))}})}handleRequest({request:t,event:e}){const s=new URL(t.url,location.href);if(!s.protocol.startsWith("http"))return;const n=s.origin===location.origin,{params:r,route:i}=this.findMatchingRoute({event:e,request:t,sameOrigin:n,url:s});let a=i&&i.handler;const o=t.method;if(!a&&this.i.has(o)&&(a=this.i.get(o)),!a)return;let c;try{c=a.handle({url:s,request:t,event:e,params:r})}catch(t){c=Promise.reject(t)}const h=i&&i.catchHandler;return c instanceof Promise&&(this.o||h)&&(c=c.catch(async n=>{if(h)try{return await h.handle({url:s,request:t,event:e,params:r})}catch(t){t instanceof Error&&(n=t)}if(this.o)return this.o.handle({url:s,request:t,event:e});throw n})),c}findMatchingRoute({url:t,sameOrigin:e,request:s,event:n}){const r=this.t.get(s.method)||[];for(const i of r){let r;const a=i.match({url:t,sameOrigin:e,request:s,event:n});if(a)return r=a,(Array.isArray(r)&&0===r.length||a.constructor===Object&&0===Object.keys(a).length||"boolean"==typeof a)&&(r=void 0),{route:i,params:r}}return{}}setDefaultHandler(t,e="GET"){this.i.set(e,n(t))}setCatchHandler(t){this.o=n(t)}registerRoute(t){this.t.has(t.method)||this.t.set(t.method,[]),this.t.get(t.method).push(t)}unregisterRoute(t){if(!this.t.has(t.method))throw new s("unregister-route-but-not-found-with-method",{method:t.method});const e=this.t.get(t.method).indexOf(t);if(!(e>-1))throw new s("unregister-route-route-not-registered");this.t.get(t.method).splice(e,1)}}let o;const c=()=>(o||(o=new a,o.addFetchListener(),o.addCacheListener()),o);function h(t,e,n){let a;if("string"==typeof t){const s=new URL(t,location.href);a=new r(({url:t})=>t.href===s.href,e,n)}else if(t instanceof RegExp)a=new i(t,e,n);else if("function"==typeof t)a=new r(t,e,n);else{if(!(t instanceof r))throw new s("unsupported-route-type",{moduleName:"workbox-routing",funcName:"registerRoute",paramName:"capture"});a=t}return c().registerRoute(a),a}try{self["workbox:strategies:6.5.4"]&&_()}catch(t){}const u={cacheWillUpdate:async({response:t})=>200===t.status||0===t.status?t:null},l={googleAnalytics:"googleAnalytics",precache:"precache-v2",prefix:"workbox",runtime:"runtime",suffix:"undefined"!=typeof registration?registration.scope:""},f=t=>[l.prefix,t,l.suffix].filter(t=>t&&t.length>0).join("-"),w=t=>t||f(l.precache),d=t=>t||f(l.runtime);function p(t,e){const s=new URL(t);for(const t of e)s.searchParams.delete(t);return s.href}class y{constructor(){this.promise=new Promise((t,e)=>{this.resolve=t,this.reject=e})}}const g=new Set;function m(t){return"string"==typeof t?new Request(t):t}class v{constructor(t,e){this.h={},Object.assign(this,e),this.event=e.event,this.u=t,this.l=new y,this.p=[],this.m=[...t.plugins],this.v=new Map;for(const t of this.m)this.v.set(t,{});this.event.waitUntil(this.l.promise)}async fetch(t){const{event:e}=this;let n=m(t);if("navigate"===n.mode&&e instanceof FetchEvent&&e.preloadResponse){const t=await e.preloadResponse;if(t)return t}const r=this.hasCallback("fetchDidFail")?n.clone():null;try{for(const t of this.iterateCallbacks("requestWillFetch"))n=await t({request:n.clone(),event:e})}catch(t){if(t instanceof Error)throw new s("plugin-error-request-will-fetch",{thrownErrorMessage:t.message})}const i=n.clone();try{let t;t=await fetch(n,"navigate"===n.mode?void 0:this.u.fetchOptions);for(const s of this.iterateCallbacks("fetchDidSucceed"))t=await s({event:e,request:i,response:t});return t}catch(t){throw r&&await this.runCallbacks("fetchDidFail",{error:t,event:e,originalRequest:r.clone(),request:i.clone()}),t}}async fetchAndCachePut(t){const e=await this.fetch(t),s=e.clone();return this.waitUntil(this.cachePut(t,s)),e}async cacheMatch(t){const e=m(t);let s;const{cacheName:n,matchOptions:r}=this.u,i=await this.getCacheKey(e,"read"),a=Object.assign(Object.assign({},r),{cacheName:n});s=await caches.match(i,a);for(const t of this.iterateCallbacks("cachedResponseWillBeUsed"))s=await t({cacheName:n,matchOptions:r,cachedResponse:s,request:i,event:this.event})||void 0;return s}async cachePut(t,e){const n=m(t);var r;await(r=0,new Promise(t=>setTimeout(t,r)));const i=await this.getCacheKey(n,"write");if(!e)throw new s("cache-put-with-no-response",{url:(a=i.url,new URL(String(a),location.href).href.replace(new RegExp(`^${location.origin}`),""))});var a;const o=await this.R(e);if(!o)return!1;const{cacheName:c,matchOptions:h}=this.u,u=await self.caches.open(c),l=this.hasCallback("cacheDidUpdate"),f=l?await async function(t,e,s,n){const r=p(e.url,s);if(e.url===r)return t.match(e,n);const i=Object.assign(Object.assign({},n),{ignoreSearch:!0}),a=await t.keys(e,i);for(const e of a)if(r===p(e.url,s))return t.match(e,n)}(u,i.clone(),["__WB_REVISION__"],h):null;try{await u.put(i,l?o.clone():o)}catch(t){if(t instanceof Error)throw"QuotaExceededError"===t.name&&await async function(){for(const t of g)await t()}(),t}for(const t of this.iterateCallbacks("cacheDidUpdate"))await t({cacheName:c,oldResponse:f,newResponse:o.clone(),request:i,event:this.event});return!0}async getCacheKey(t,e){const s=`${t.url} | ${e}`;if(!this.h[s]){let n=t;for(const t of this.iterateCallbacks("cacheKeyWillBeUsed"))n=m(await t({mode:e,request:n,event:this.event,params:this.params}));this.h[s]=n}return this.h[s]}hasCallback(t){for(const e of this.u.plugins)if(t in e)return!0;return!1}async runCallbacks(t,e){for(const s of this.iterateCallbacks(t))await s(e)}*iterateCallbacks(t){for(const e of this.u.plugins)if("function"==typeof e[t]){const s=this.v.get(e),n=n=>{const r=Object.assign(Object.assign({},n),{state:s});return e[t](r)};yield n}}waitUntil(t){return this.p.push(t),t}async doneWaiting(){let t;for(;t=this.p.shift();)await t}destroy(){this.l.resolve(null)}async R(t){let e=t,s=!1;for(const t of this.iterateCallbacks("cacheWillUpdate"))if(e=await t({request:this.request,response:e,event:this.event})||void 0,s=!0,!e)break;return s||e&&200!==e.status&&(e=void 0),e}}class R{constructor(t={}){this.cacheName=d(t.cacheName),this.plugins=t.plugins||[],this.fetchOptions=t.fetchOptions,this.matchOptions=t.matchOptions}handle(t){const[e]=this.handleAll(t);return e}handleAll(t){t instanceof FetchEvent&&(t={event:t,request:t.request});const e=t.event,s="string"==typeof t.request?new Request(t.request):t.request,n="params"in t?t.params:void 0,r=new v(this,{event:e,request:s,params:n}),i=this.q(r,s,e);return[i,this.D(i,r,s,e)]}async q(t,e,n){let r;await t.runCallbacks("handlerWillStart",{event:n,request:e});try{if(r=await this.U(e,t),!r||"error"===r.type)throw new s("no-response",{url:e.url})}catch(s){if(s instanceof Error)for(const i of t.iterateCallbacks("handlerDidError"))if(r=await i({error:s,event:n,request:e}),r)break;if(!r)throw s}for(const s of t.iterateCallbacks("handlerWillRespond"))r=await s({event:n,request:e,response:r});return r}async D(t,e,s,n){let r,i;try{r=await t}catch(i){}try{await e.runCallbacks("handlerDidRespond",{event:n,request:s,response:r}),await e.doneWaiting()}catch(t){t instanceof Error&&(i=t)}if(await e.runCallbacks("handlerDidComplete",{event:n,request:s,response:r,error:i}),e.destroy(),i)throw i}}function b(t){t.then(()=>{})}function q(){return q=Object.assign?Object.assign.bind():function(t){for(var e=1;e(t[e]=s,!0),has:(t,e)=>t instanceof IDBTransaction&&("done"===e||"store"===e)||e in t};function O(t){return t!==IDBDatabase.prototype.transaction||"objectStoreNames"in IDBTransaction.prototype?(U||(U=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(t)?function(...e){return t.apply(B(this),e),k(x.get(this))}:function(...e){return k(t.apply(B(this),e))}:function(e,...s){const n=t.call(B(this),e,...s);return I.set(n,e.sort?e.sort():[e]),k(n)}}function T(t){return"function"==typeof t?O(t):(t instanceof IDBTransaction&&function(t){if(L.has(t))return;const e=new Promise((e,s)=>{const n=()=>{t.removeEventListener("complete",r),t.removeEventListener("error",i),t.removeEventListener("abort",i)},r=()=>{e(),n()},i=()=>{s(t.error||new DOMException("AbortError","AbortError")),n()};t.addEventListener("complete",r),t.addEventListener("error",i),t.addEventListener("abort",i)});L.set(t,e)}(t),e=t,(D||(D=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])).some(t=>e instanceof t)?new Proxy(t,N):t);var e}function k(t){if(t instanceof IDBRequest)return function(t){const e=new Promise((e,s)=>{const n=()=>{t.removeEventListener("success",r),t.removeEventListener("error",i)},r=()=>{e(k(t.result)),n()},i=()=>{s(t.error),n()};t.addEventListener("success",r),t.addEventListener("error",i)});return e.then(e=>{e instanceof IDBCursor&&x.set(e,t)}).catch(()=>{}),E.set(e,t),e}(t);if(C.has(t))return C.get(t);const e=T(t);return e!==t&&(C.set(t,e),E.set(e,t)),e}const B=t=>E.get(t);const P=["get","getKey","getAll","getAllKeys","count"],M=["put","add","delete","clear"],W=new Map;function j(t,e){if(!(t instanceof IDBDatabase)||e in t||"string"!=typeof e)return;if(W.get(e))return W.get(e);const s=e.replace(/FromIndex$/,""),n=e!==s,r=M.includes(s);if(!(s in(n?IDBIndex:IDBObjectStore).prototype)||!r&&!P.includes(s))return;const i=async function(t,...e){const i=this.transaction(t,r?"readwrite":"readonly");let a=i.store;return n&&(a=a.index(e.shift())),(await Promise.all([a[s](...e),r&&i.done]))[0]};return W.set(e,i),i}N=(t=>q({},t,{get:(e,s,n)=>j(e,s)||t.get(e,s,n),has:(e,s)=>!!j(e,s)||t.has(e,s)}))(N);try{self["workbox:expiration:6.5.4"]&&_()}catch(t){}const S="cache-entries",K=t=>{const e=new URL(t,location.href);return e.hash="",e.href};class A{constructor(t){this._=null,this.L=t}I(t){const e=t.createObjectStore(S,{keyPath:"id"});e.createIndex("cacheName","cacheName",{unique:!1}),e.createIndex("timestamp","timestamp",{unique:!1})}C(t){this.I(t),this.L&&function(t,{blocked:e}={}){const s=indexedDB.deleteDatabase(t);e&&s.addEventListener("blocked",t=>e(t.oldVersion,t)),k(s).then(()=>{})}(this.L)}async setTimestamp(t,e){const s={url:t=K(t),timestamp:e,cacheName:this.L,id:this.N(t)},n=(await this.getDb()).transaction(S,"readwrite",{durability:"relaxed"});await n.store.put(s),await n.done}async getTimestamp(t){const e=await this.getDb(),s=await e.get(S,this.N(t));return null==s?void 0:s.timestamp}async expireEntries(t,e){const s=await this.getDb();let n=await s.transaction(S).store.index("timestamp").openCursor(null,"prev");const r=[];let i=0;for(;n;){const s=n.value;s.cacheName===this.L&&(t&&s.timestamp=e?r.push(n.value):i++),n=await n.continue()}const a=[];for(const t of r)await s.delete(S,t.id),a.push(t.url);return a}N(t){return this.L+"|"+K(t)}async getDb(){return this._||(this._=await function(t,e,{blocked:s,upgrade:n,blocking:r,terminated:i}={}){const a=indexedDB.open(t,e),o=k(a);return n&&a.addEventListener("upgradeneeded",t=>{n(k(a.result),t.oldVersion,t.newVersion,k(a.transaction),t)}),s&&a.addEventListener("blocked",t=>s(t.oldVersion,t.newVersion,t)),o.then(t=>{i&&t.addEventListener("close",()=>i()),r&&t.addEventListener("versionchange",t=>r(t.oldVersion,t.newVersion,t))}).catch(()=>{}),o}("workbox-expiration",1,{upgrade:this.C.bind(this)})),this._}}class F{constructor(t,e={}){this.O=!1,this.T=!1,this.k=e.maxEntries,this.B=e.maxAgeSeconds,this.P=e.matchOptions,this.L=t,this.M=new A(t)}async expireEntries(){if(this.O)return void(this.T=!0);this.O=!0;const t=this.B?Date.now()-1e3*this.B:0,e=await this.M.expireEntries(t,this.k),s=await self.caches.open(this.L);for(const t of e)await s.delete(t,this.P);this.O=!1,this.T&&(this.T=!1,b(this.expireEntries()))}async updateTimestamp(t){await this.M.setTimestamp(t,Date.now())}async isURLExpired(t){if(this.B){const e=await this.M.getTimestamp(t),s=Date.now()-1e3*this.B;return void 0===e||er||e&&e<0)throw new s("range-not-satisfiable",{size:r,end:n,start:e});let i,a;return void 0!==e&&void 0!==n?(i=e,a=n+1):void 0!==e&&void 0===n?(i=e,a=r):void 0!==n&&void 0===e&&(i=r-n,a=r),{start:i,end:a}}(i,r.start,r.end),o=i.slice(a.start,a.end),c=o.size,h=new Response(o,{status:206,statusText:"Partial Content",headers:e.headers});return h.headers.set("Content-Length",String(c)),h.headers.set("Content-Range",`bytes ${a.start}-${a.end-1}/${i.size}`),h}catch(t){return new Response("",{status:416,statusText:"Range Not Satisfiable"})}}function $(t,e){const s=e();return t.waitUntil(s),s}try{self["workbox:precaching:6.5.4"]&&_()}catch(t){}function z(t){if(!t)throw new s("add-to-cache-list-unexpected-type",{entry:t});if("string"==typeof t){const e=new URL(t,location.href);return{cacheKey:e.href,url:e.href}}const{revision:e,url:n}=t;if(!n)throw new s("add-to-cache-list-unexpected-type",{entry:t});if(!e){const t=new URL(n,location.href);return{cacheKey:t.href,url:t.href}}const r=new URL(n,location.href),i=new URL(n,location.href);return r.searchParams.set("__WB_REVISION__",e),{cacheKey:r.href,url:i.href}}class G{constructor(){this.updatedURLs=[],this.notUpdatedURLs=[],this.handlerWillStart=async({request:t,state:e})=>{e&&(e.originalRequest=t)},this.cachedResponseWillBeUsed=async({event:t,state:e,cachedResponse:s})=>{if("install"===t.type&&e&&e.originalRequest&&e.originalRequest instanceof Request){const t=e.originalRequest.url;s?this.notUpdatedURLs.push(t):this.updatedURLs.push(t)}return s}}}class V{constructor({precacheController:t}){this.cacheKeyWillBeUsed=async({request:t,params:e})=>{const s=(null==e?void 0:e.cacheKey)||this.W.getCacheKeyForURL(t.url);return s?new Request(s,{headers:t.headers}):t},this.W=t}}let J,Q;async function X(t,e){let n=null;if(t.url){n=new URL(t.url).origin}if(n!==self.location.origin)throw new s("cross-origin-copy-response",{origin:n});const r=t.clone(),i={headers:new Headers(r.headers),status:r.status,statusText:r.statusText},a=e?e(i):i,o=function(){if(void 0===J){const t=new Response("");if("body"in t)try{new Response(t.body),J=!0}catch(t){J=!1}J=!1}return J}()?r.body:await r.blob();return new Response(o,a)}class Y extends R{constructor(t={}){t.cacheName=w(t.cacheName),super(t),this.j=!1!==t.fallbackToNetwork,this.plugins.push(Y.copyRedirectedCacheableResponsesPlugin)}async U(t,e){const s=await e.cacheMatch(t);return s||(e.event&&"install"===e.event.type?await this.S(t,e):await this.K(t,e))}async K(t,e){let n;const r=e.params||{};if(!this.j)throw new s("missing-precache-entry",{cacheName:this.cacheName,url:t.url});{const s=r.integrity,i=t.integrity,a=!i||i===s;n=await e.fetch(new Request(t,{integrity:"no-cors"!==t.mode?i||s:void 0})),s&&a&&"no-cors"!==t.mode&&(this.A(),await e.cachePut(t,n.clone()))}return n}async S(t,e){this.A();const n=await e.fetch(t);if(!await e.cachePut(t,n.clone()))throw new s("bad-precaching-response",{url:t.url,status:n.status});return n}A(){let t=null,e=0;for(const[s,n]of this.plugins.entries())n!==Y.copyRedirectedCacheableResponsesPlugin&&(n===Y.defaultPrecacheCacheabilityPlugin&&(t=s),n.cacheWillUpdate&&e++);0===e?this.plugins.push(Y.defaultPrecacheCacheabilityPlugin):e>1&&null!==t&&this.plugins.splice(t,1)}}Y.defaultPrecacheCacheabilityPlugin={cacheWillUpdate:async({response:t})=>!t||t.status>=400?null:t},Y.copyRedirectedCacheableResponsesPlugin={cacheWillUpdate:async({response:t})=>t.redirected?await X(t):t};class Z{constructor({cacheName:t,plugins:e=[],fallbackToNetwork:s=!0}={}){this.F=new Map,this.H=new Map,this.$=new Map,this.u=new Y({cacheName:w(t),plugins:[...e,new V({precacheController:this})],fallbackToNetwork:s}),this.install=this.install.bind(this),this.activate=this.activate.bind(this)}get strategy(){return this.u}precache(t){this.addToCacheList(t),this.G||(self.addEventListener("install",this.install),self.addEventListener("activate",this.activate),this.G=!0)}addToCacheList(t){const e=[];for(const n of t){"string"==typeof n?e.push(n):n&&void 0===n.revision&&e.push(n.url);const{cacheKey:t,url:r}=z(n),i="string"!=typeof n&&n.revision?"reload":"default";if(this.F.has(r)&&this.F.get(r)!==t)throw new s("add-to-cache-list-conflicting-entries",{firstEntry:this.F.get(r),secondEntry:t});if("string"!=typeof n&&n.integrity){if(this.$.has(t)&&this.$.get(t)!==n.integrity)throw new s("add-to-cache-list-conflicting-integrities",{url:r});this.$.set(t,n.integrity)}if(this.F.set(r,t),this.H.set(r,i),e.length>0){const t=`Workbox is precaching URLs without revision info: ${e.join(", ")}\nThis is generally NOT safe. Learn more at https://bit.ly/wb-precache`;console.warn(t)}}}install(t){return $(t,async()=>{const e=new G;this.strategy.plugins.push(e);for(const[e,s]of this.F){const n=this.$.get(s),r=this.H.get(e),i=new Request(e,{integrity:n,cache:r,credentials:"same-origin"});await Promise.all(this.strategy.handleAll({params:{cacheKey:s},request:i,event:t}))}const{updatedURLs:s,notUpdatedURLs:n}=e;return{updatedURLs:s,notUpdatedURLs:n}})}activate(t){return $(t,async()=>{const t=await self.caches.open(this.strategy.cacheName),e=await t.keys(),s=new Set(this.F.values()),n=[];for(const r of e)s.has(r.url)||(await t.delete(r),n.push(r.url));return{deletedURLs:n}})}getURLsToCacheKeys(){return this.F}getCachedURLs(){return[...this.F.keys()]}getCacheKeyForURL(t){const e=new URL(t,location.href);return this.F.get(e.href)}getIntegrityForCacheKey(t){return this.$.get(t)}async matchPrecache(t){const e=t instanceof Request?t.url:t,s=this.getCacheKeyForURL(e);if(s){return(await self.caches.open(this.strategy.cacheName)).match(s)}}createHandlerBoundToURL(t){const e=this.getCacheKeyForURL(t);if(!e)throw new s("non-precached-url",{url:t});return s=>(s.request=new Request(t),s.params=Object.assign({cacheKey:e},s.params),this.strategy.handle(s))}}const tt=()=>(Q||(Q=new Z),Q);class et extends r{constructor(t,e){super(({request:s})=>{const n=t.getURLsToCacheKeys();for(const r of function*(t,{ignoreURLParametersMatching:e=[/^utm_/,/^fbclid$/],directoryIndex:s="index.html",cleanURLs:n=!0,urlManipulation:r}={}){const i=new URL(t,location.href);i.hash="",yield i.href;const a=function(t,e=[]){for(const s of[...t.searchParams.keys()])e.some(t=>t.test(s))&&t.searchParams.delete(s);return t}(i,e);if(yield a.href,s&&a.pathname.endsWith("/")){const t=new URL(a.href);t.pathname+=s,yield t.href}if(n){const t=new URL(a.href);t.pathname+=".html",yield t.href}if(r){const t=r({url:i});for(const e of t)yield e.href}}(s.url,e)){const e=n.get(r);if(e){return{cacheKey:e,integrity:t.getIntegrityForCacheKey(e)}}}},t.strategy)}}t.CacheFirst=class extends R{async U(t,e){let n,r=await e.cacheMatch(t);if(!r)try{r=await e.fetchAndCachePut(t)}catch(t){t instanceof Error&&(n=t)}if(!r)throw new s("no-response",{url:t.url,error:n});return r}},t.ExpirationPlugin=class{constructor(t={}){this.cachedResponseWillBeUsed=async({event:t,request:e,cacheName:s,cachedResponse:n})=>{if(!n)return null;const r=this.V(n),i=this.J(s);b(i.expireEntries());const a=i.updateTimestamp(e.url);if(t)try{t.waitUntil(a)}catch(t){}return r?n:null},this.cacheDidUpdate=async({cacheName:t,request:e})=>{const s=this.J(t);await s.updateTimestamp(e.url),await s.expireEntries()},this.X=t,this.B=t.maxAgeSeconds,this.Y=new Map,t.purgeOnQuotaError&&function(t){g.add(t)}(()=>this.deleteCacheAndMetadata())}J(t){if(t===d())throw new s("expire-custom-caches-only");let e=this.Y.get(t);return e||(e=new F(t,this.X),this.Y.set(t,e)),e}V(t){if(!this.B)return!0;const e=this.Z(t);if(null===e)return!0;return e>=Date.now()-1e3*this.B}Z(t){if(!t.headers.has("date"))return null;const e=t.headers.get("date"),s=new Date(e).getTime();return isNaN(s)?null:s}async deleteCacheAndMetadata(){for(const[t,e]of this.Y)await self.caches.delete(t),await e.delete();this.Y=new Map}},t.NetworkFirst=class extends R{constructor(t={}){super(t),this.plugins.some(t=>"cacheWillUpdate"in t)||this.plugins.unshift(u),this.tt=t.networkTimeoutSeconds||0}async U(t,e){const n=[],r=[];let i;if(this.tt){const{id:s,promise:a}=this.et({request:t,logs:n,handler:e});i=s,r.push(a)}const a=this.st({timeoutId:i,request:t,logs:n,handler:e});r.push(a);const o=await e.waitUntil((async()=>await e.waitUntil(Promise.race(r))||await a)());if(!o)throw new s("no-response",{url:t.url});return o}et({request:t,logs:e,handler:s}){let n;return{promise:new Promise(e=>{n=setTimeout(async()=>{e(await s.cacheMatch(t))},1e3*this.tt)}),id:n}}async st({timeoutId:t,request:e,logs:s,handler:n}){let r,i;try{i=await n.fetchAndCachePut(e)}catch(t){t instanceof Error&&(r=t)}return t&&clearTimeout(t),!r&&i||(i=await n.cacheMatch(e)),i}},t.RangeRequestsPlugin=class{constructor(){this.cachedResponseWillBeUsed=async({request:t,cachedResponse:e})=>e&&t.headers.has("range")?await H(t,e):e}},t.StaleWhileRevalidate=class extends R{constructor(t={}){super(t),this.plugins.some(t=>"cacheWillUpdate"in t)||this.plugins.unshift(u)}async U(t,e){const n=e.fetchAndCachePut(t).catch(()=>{});e.waitUntil(n);let r,i=await e.cacheMatch(t);if(i);else try{i=await n}catch(t){t instanceof Error&&(r=t)}if(!i)throw new s("no-response",{url:t.url,error:r});return i}},t.cleanupOutdatedCaches=function(){self.addEventListener("activate",t=>{const e=w();t.waitUntil((async(t,e="-precache-")=>{const s=(await self.caches.keys()).filter(s=>s.includes(e)&&s.includes(self.registration.scope)&&s!==t);return await Promise.all(s.map(t=>self.caches.delete(t))),s})(e).then(t=>{}))})},t.clientsClaim=function(){self.addEventListener("activate",()=>self.clients.claim())},t.precacheAndRoute=function(t,e){!function(t){tt().precache(t)}(t),function(t){const e=tt();h(new et(e,t))}(e)},t.registerRoute=h}); diff --git a/src/app/calendar/month/page.tsx b/src/app/calendar/month/page.tsx index d0ac51e..a807a31 100644 --- a/src/app/calendar/month/page.tsx +++ b/src/app/calendar/month/page.tsx @@ -2,6 +2,7 @@ import { useEffect, useMemo, useState } from 'react' import { api } from '@/lib/api' import { getCurrentPersianYear, getCurrentPersianMonth } from '@/lib/persian-date' +import Loading from '@/components/Loading' function useQueryParam(name: string) { if (typeof window === 'undefined') return null as string | null @@ -14,11 +15,14 @@ export default function MonthPage() { const month = Number(useQueryParam('month') ?? getCurrentPersianMonth().toString()) const [daysWithCounts, setDaysWithCounts] = useState<{ day: number; count: number }[]>([]) + const [loading, setLoading] = useState(true) useEffect(() => { + setLoading(true) api.monthDays(deviceId, year, month) .then(list => setDaysWithCounts(list.map(x => ({ day: Number(x.persianDate.split('/')[2]), count: x.count })))) .catch(console.error) + .finally(() => setLoading(false)) }, [deviceId, year, month]) const maxDay = useMemo(() => { @@ -32,6 +36,10 @@ export default function MonthPage() { const days = useMemo(() => Array.from({ length: maxDay }, (_, i) => i + 1), [maxDay]) const countByDay = useMemo(() => new Map(daysWithCounts.map(d => [d.day, d.count])), [daysWithCounts]) + if (loading) { + return + } + return (
@@ -51,7 +59,7 @@ export default function MonthPage() { const c = countByDay.get(d) ?? 0 const hasData = c > 0 return ( - +
{d}
{hasData && ( {c} diff --git a/src/app/calendar/page.tsx b/src/app/calendar/page.tsx index 419a400..304b86c 100644 --- a/src/app/calendar/page.tsx +++ b/src/app/calendar/page.tsx @@ -2,6 +2,9 @@ import { useEffect, useMemo, useState } from 'react' import { api } from '@/lib/api' import { getCurrentPersianYear } from '@/lib/persian-date' +import { Calendar as CalendarIcon, ChevronRight, Database, TrendingUp } from 'lucide-react' +import Link from 'next/link' +import Loading from '@/components/Loading' const monthNames = ['فروردین', 'اردیبهشت', 'خرداد', 'تیر', 'مرداد', 'شهریور', 'مهر', 'آبان', 'آذر', 'دی', 'بهمن', 'اسفند'] @@ -24,6 +27,7 @@ export default function CalendarPage() { const [year, setYear] = useState(getCurrentPersianYear()) const [activeMonths, setActiveMonths] = useState([]) const [monthDays, setMonthDays] = useState>({}) + const [loading, setLoading] = useState(true) const years = useMemo(() => Array.from({ length: 10 }, (_, i) => getCurrentPersianYear() - 2 + i), []) // وقتی deviceIdParam تغییر کرد، deviceId را به روز کن @@ -37,6 +41,7 @@ export default function CalendarPage() { let mounted = true setMonthDays({}) setActiveMonths([]) + setLoading(true) api.activeMonths(deviceId, year) .then(async (months) => { @@ -51,44 +56,113 @@ export default function CalendarPage() { setMonthDays(Object.fromEntries(entries)) }) .catch(console.error) + .finally(() => { + if (mounted) setLoading(false) + }) return () => { mounted = false } }, [deviceId, year]) const totalDays = useMemo(() => Object.values(monthDays).reduce((s, v) => s + (v?.days ?? 0), 0), [monthDays]) const totalRecords = useMemo(() => Object.values(monthDays).reduce((s, v) => s + (v?.records ?? 0), 0), [monthDays]) + if (loading) { + return + } + return ( -
-
-
انتخاب سال و ماه 📅
- -
- - +
+
+ {/* Header */} +
+ + + بازگشت به صفحه اصلی + +
+
+ +
+

انتخاب سال و ماه

+
-
- خلاصه {year}: {totalDays} روز دارای دیتا · {totalRecords} رکورد -
+ {/* Main Card */} +
+ {/* Year Selector */} +
+ + +
-
diff --git a/src/app/day-details/page.tsx b/src/app/day-details/page.tsx new file mode 100644 index 0000000..c7cd9c3 --- /dev/null +++ b/src/app/day-details/page.tsx @@ -0,0 +1,164 @@ +"use client" +import { useEffect, useState, useMemo } from 'react' +import { api } from '@/lib/api' +import { getCurrentPersianYear, getCurrentPersianMonth, getPersianMonthStartWeekday, getPersianMonthDays } from '@/lib/persian-date' +import { Calendar as CalendarIcon, ChevronRight, Database } from 'lucide-react' +import Link from 'next/link' +import Loading from '@/components/Loading' + +function useQueryParam(name: string) { + if (typeof window === 'undefined') return null as string | null + return new URLSearchParams(window.location.search).get(name) +} + +const monthNames = ['فروردین', 'اردیبهشت', 'خرداد', 'تیر', 'مرداد', 'شهریور', 'مهر', 'آبان', 'آذر', 'دی', 'بهمن', 'اسفند'] + +export default function DayDetailsPage() { + const [items, setItems] = useState<{ persianDate: string; count: number }[]>([]) + const [loading, setLoading] = useState(true) + const deviceId = Number(useQueryParam('deviceId') ?? '1') + const year = Number(useQueryParam('year') ?? getCurrentPersianYear()) + const month = Number(useQueryParam('month') ?? getCurrentPersianMonth()) + + useEffect(() => { + setLoading(true) + api.monthDays(deviceId, year, month) + .then(setItems) + .catch(console.error) + .finally(() => setLoading(false)) + }, [deviceId, year, month]) + + // Create a map of day -> count for quick lookup + const dataByDay = useMemo(() => { + const map = new Map() + items.forEach(item => { + const day = parseInt(item.persianDate.split('/')[2]) + map.set(day, item.count) + }) + return map + }, [items]) + + // Calculate total days in the month + const totalDays = useMemo(() => { + return getPersianMonthDays(year, month) + }, [year, month]) + + // Get the starting weekday of the month (0 = Saturday) + const startWeekday = useMemo(() => { + const sw = getPersianMonthStartWeekday(year, month) + return sw; + }, [year, month]) + + // Generate calendar grid with proper spacing + const calendarGrid = useMemo(() => { + const grid = [] + + // Add empty cells for days before the month starts + for (let i = 0; i < startWeekday; i++) { + grid.push({ type: 'empty', day: null }) + } + + // Add all days of the month + for (let day = 1; day <= totalDays; day++) { + grid.push({ type: 'day', day }) + } + + return grid + }, [startWeekday, totalDays]) + + if (loading) { + return + } + + return ( +
+
+ {/* Header */} +
+ + + بازگشت به تقویم + +
+
+ +
+

+ {monthNames[month - 1]} {year} +

+
+
+ + {/* Calendar Grid */} +
+ {/* Weekday Headers */} +
+ {['شنبه', 'یکشنبه', 'دوشنبه', 'سه‌شنبه', 'چهارشنبه', 'پنجشنبه', 'جمعه'].map(day => ( +
+ {day} +
+ ))} +
+ + {/* Days Grid */} +
+ {calendarGrid.map((cell, index) => { + if (cell.type === 'empty') { + return ( +
+ ) + } + + const day = cell.day! + const hasData = dataByDay.has(day) + const recordCount = dataByDay.get(day) || 0 + + if (hasData) { + return ( + +
{day}
+
+ + {recordCount} +
+ + ) + } else { + return ( +
+
{day}
+
+ ) + } + })} +
+
+ + {/* Summary */} +
+
+ + + {items.length} روز دارای داده از{' '} + {totalDays} روز ماه + +
+
+
+
+ ) +} + diff --git a/src/app/day_details/page.tsx b/src/app/day_details/page.tsx deleted file mode 100644 index 876aa28..0000000 --- a/src/app/day_details/page.tsx +++ /dev/null @@ -1,141 +0,0 @@ -"use client" -import { useEffect, useState, useMemo } from 'react' -import { api } from '@/lib/api' -import { getCurrentPersianYear, getCurrentPersianMonth, getPersianMonthStartWeekday, getPersianMonthDays } from '@/lib/persian-date' - -function useQueryParam(name: string) { - if (typeof window === 'undefined') return null as string | null - return new URLSearchParams(window.location.search).get(name) -} - -const monthNames = ['فروردین', 'اردیبهشت', 'خرداد', 'تیر', 'مرداد', 'شهریور', 'مهر', 'آبان', 'آذر', 'دی', 'بهمن', 'اسفند'] - -export default function DayDetailsPage() { - const [items, setItems] = useState<{ persianDate: string; count: number }[]>([]) - const deviceId = Number(useQueryParam('deviceId') ?? '1') - const year = Number(useQueryParam('year') ?? getCurrentPersianYear()) - const month = Number(useQueryParam('month') ?? getCurrentPersianMonth()) - - useEffect(() => { - api.monthDays(deviceId, year, month).then(setItems).catch(console.error) - }, [deviceId, year, month]) - - // Create a map of day -> count for quick lookup - const dataByDay = useMemo(() => { - const map = new Map() - items.forEach(item => { - const day = parseInt(item.persianDate.split('/')[2]) - map.set(day, item.count) - }) - return map - }, [items]) - - // Calculate total days in the month - const totalDays = useMemo(() => { - return getPersianMonthDays(year, month) - }, [year, month]) - - // Get the starting weekday of the month (0 = Saturday) - const startWeekday = useMemo(() => { - const sw = getPersianMonthStartWeekday(year, month)//- 1; - //if (sw < 0) sw += 7; - return sw; - }, [year, month]) - - // Generate calendar grid with proper spacing - const calendarGrid = useMemo(() => { - const grid = [] - - // Add empty cells for days before the month starts - for (let i = 0; i < startWeekday; i++) { - grid.push({ type: 'empty', day: null }) - } - - // Add all days of the month - for (let day = 1; day <= totalDays; day++) { - grid.push({ type: 'day', day }) - } - - return grid - }, [startWeekday, totalDays]) - - return ( -
- {/* Header */} -
- - ← بازگشت به تقویم - -

- {monthNames[month - 1]} {year} -

-
{/* Spacer for centering */} -
- - {/* Calendar Grid */} -
- {/* Weekday Headers */} -
- {['شنبه', 'یکشنبه', 'دوشنبه', 'سه‌شنبه', 'چهارشنبه', 'پنجشنبه', 'جمعه'].map(day => ( -
- {day} -
- ))} -
- - {/* Days Grid */} -
- {calendarGrid.map((cell, index) => { - if (cell.type === 'empty') { - return ( -
-
- ) - } - - const day = cell.day! - const hasData = dataByDay.has(day) - const recordCount = dataByDay.get(day) || 0 - - if (hasData) { - return ( - -
{day}
-
- {recordCount} رکورد -
-
- - - ) - } else { - return ( -
-
{day}
-
- ) - } - })} -
-
- - {/* Summary */} -
- {items.length} روز دارای داده از {totalDays} روز ماه -
-
- ) -} diff --git a/src/app/device-settings/page.tsx b/src/app/device-settings/page.tsx new file mode 100644 index 0000000..d6f481f --- /dev/null +++ b/src/app/device-settings/page.tsx @@ -0,0 +1,345 @@ +"use client" +import { useEffect, useState, useCallback } from 'react' +import { api, DeviceSettingsDto } from '@/lib/api' +import { Settings, ChevronRight, Thermometer, Wind, Sun, Droplets, Save, Loader2, AlertCircle, CheckCircle2 } from 'lucide-react' +import Link from 'next/link' +import Loading from '@/components/Loading' + +function useQueryParam(name: string) { + if (typeof window === 'undefined') return null as string | null + return new URLSearchParams(window.location.search).get(name) +} + +export default function DeviceSettingsPage() { + const [settings, setSettings] = useState(null) + const [loading, setLoading] = useState(true) + const [saving, setSaving] = useState(false) + const [error, setError] = useState(null) + const [success, setSuccess] = useState(null) + + const deviceId = Number(useQueryParam('deviceId') ?? '1') + const deviceName = useQueryParam('deviceName') ?? 'دستگاه' + + const loadSettings = useCallback(async () => { + try { + setLoading(true) + setError(null) + const data = await api.getDeviceSettings(deviceId) + setSettings(data) + } catch (err) { + console.error('Error loading settings:', err) + setError('خطا در بارگذاری تنظیمات') + } finally { + setLoading(false) + } + }, [deviceId]) + + useEffect(() => { + loadSettings() + }, [loadSettings]) + + const handleSave = async () => { + if (!settings) return + + try { + setSaving(true) + setError(null) + setSuccess(null) + + if (settings.id === 0) { + await api.createDeviceSettings(settings) + setSuccess('تنظیمات با موفقیت ایجاد شد') + } else { + await api.updateDeviceSettings(settings) + setSuccess('تنظیمات با موفقیت به‌روزرسانی شد') + } + } catch (err) { + console.error('Error saving settings:', err) + setError('خطا در ذخیره تنظیمات') + } finally { + setSaving(false) + } + } + + const handleInputChange = (field: keyof DeviceSettingsDto, value: number) => { + if (!settings) return + setSettings({ ...settings, [field]: value }) + } + + const initializeDefaultSettings = () => { + const defaultSettings: DeviceSettingsDto = { + id: 0, + deviceId: deviceId, + deviceName: deviceName, + dangerMaxTemperature: 40, + dangerMinTemperature: 5, + maxTemperature: 35, + minTemperature: 10, + maxGasPPM: 1000, + minGasPPM: 0, + maxLux: 100000, + minLux: 0, + maxHumidityPercent: 80, + minHumidityPercent: 20, + createdAt: new Date().toISOString(), + updatedAt: new Date().toISOString() + } + setSettings(defaultSettings) + } + + if (loading) { + return + } + + if (!deviceId) { + return ( +
+
+ +
شناسه دستگاه مشخص نشده است
+ + + بازگشت به انتخاب دستگاه + +
+
+ ) + } + + return ( +
+
+ {/* Header */} +
+ + + بازگشت به انتخاب دستگاه + +
+
+ +
+

+ تنظیمات {deviceName} +

+
+
+ + {/* Messages */} + {error && ( +
+ + {error} +
+ )} + {success && ( +
+ + {success} +
+ )} + + {!settings ? ( +
+ +
+ تنظیمات برای این دستگاه وجود ندارد +
+ +
+ ) : ( +
+
+ {/* Temperature Settings */} +
+
+
+ +
+

+ تنظیمات دما +

+
+ +
+ + handleInputChange('maxTemperature', parseFloat(e.target.value) || 0)} + className="w-full px-4 py-3 border-2 border-gray-200 rounded-xl focus:border-red-500 focus:outline-none focus:ring-2 focus:ring-red-500/20 transition-all bg-gray-50 focus:bg-white" + /> +
+ +
+ + handleInputChange('minTemperature', parseFloat(e.target.value) || 0)} + className="w-full px-4 py-3 border-2 border-gray-200 rounded-xl focus:border-red-500 focus:outline-none focus:ring-2 focus:ring-red-500/20 transition-all bg-gray-50 focus:bg-white" + /> +
+
+ + {/* Gas Settings */} +
+
+
+ +
+

+ تنظیمات گاز +

+
+ +
+ + handleInputChange('maxGasPPM', parseInt(e.target.value) || 0)} + className="w-full px-4 py-3 border-2 border-gray-200 rounded-xl focus:border-gray-600 focus:outline-none focus:ring-2 focus:ring-gray-600/20 transition-all bg-gray-50 focus:bg-white" + /> +
+ +
+ + handleInputChange('minGasPPM', parseInt(e.target.value) || 0)} + className="w-full px-4 py-3 border-2 border-gray-200 rounded-xl focus:border-gray-600 focus:outline-none focus:ring-2 focus:ring-gray-600/20 transition-all bg-gray-50 focus:bg-white" + /> +
+
+ + {/* Light Settings */} +
+
+
+ +
+

+ تنظیمات نور +

+
+ +
+ + handleInputChange('maxLux', parseFloat(e.target.value) || 0)} + className="w-full px-4 py-3 border-2 border-gray-200 rounded-xl focus:border-yellow-500 focus:outline-none focus:ring-2 focus:ring-yellow-500/20 transition-all bg-gray-50 focus:bg-white" + /> +
+ +
+ + handleInputChange('minLux', parseFloat(e.target.value) || 0)} + className="w-full px-4 py-3 border-2 border-gray-200 rounded-xl focus:border-yellow-500 focus:outline-none focus:ring-2 focus:ring-yellow-500/20 transition-all bg-gray-50 focus:bg-white" + /> +
+
+ + {/* Humidity Settings */} +
+
+
+ +
+

+ تنظیمات رطوبت هوا +

+
+ +
+ + handleInputChange('maxHumidityPercent', parseFloat(e.target.value) || 0)} + className="w-full px-4 py-3 border-2 border-gray-200 rounded-xl focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-500/20 transition-all bg-gray-50 focus:bg-white" + /> +
+ +
+ + handleInputChange('minHumidityPercent', parseFloat(e.target.value) || 0)} + className="w-full px-4 py-3 border-2 border-gray-200 rounded-xl focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-500/20 transition-all bg-gray-50 focus:bg-white" + /> +
+
+
+ + {/* Save Button */} +
+ +
+
+ )} +
+
+ ) +} + diff --git a/src/app/device_settings/page.tsx b/src/app/device_settings/page.tsx deleted file mode 100644 index e86872f..0000000 --- a/src/app/device_settings/page.tsx +++ /dev/null @@ -1,330 +0,0 @@ -"use client" -import { useEffect, useState, useCallback } from 'react' -import { api, DeviceSettingsDto } from '@/lib/api' - -function useQueryParam(name: string) { - if (typeof window === 'undefined') return null as string | null - return new URLSearchParams(window.location.search).get(name) -} - -export default function DeviceSettingsPage() { - const [settings, setSettings] = useState(null) - const [loading, setLoading] = useState(true) - const [saving, setSaving] = useState(false) - const [error, setError] = useState(null) - const [success, setSuccess] = useState(null) - - const deviceId = Number(useQueryParam('deviceId') ?? '1') - const deviceName = useQueryParam('deviceName') ?? 'دستگاه' - - const loadSettings = useCallback(async () => { - try { - setLoading(true) - setError(null) - const data = await api.getDeviceSettings(deviceId) - setSettings(data) - } catch (err) { - console.error('Error loading settings:', err) - setError('خطا در بارگذاری تنظیمات') - } finally { - setLoading(false) - } - }, [deviceId]) - - useEffect(() => { - loadSettings() - }, [loadSettings]) - - const handleSave = async () => { - if (!settings) return - - try { - setSaving(true) - setError(null) - setSuccess(null) - - if (settings.id === 0) { - // Create new settings - await api.createDeviceSettings(settings) - setSuccess('تنظیمات با موفقیت ایجاد شد') - } else { - // Update existing settings - await api.updateDeviceSettings(settings) - setSuccess('تنظیمات با موفقیت به‌روزرسانی شد') - } - } catch (err) { - console.error('Error saving settings:', err) - setError('خطا در ذخیره تنظیمات') - } finally { - setSaving(false) - } - } - - const handleInputChange = (field: keyof DeviceSettingsDto, value: number) => { - if (!settings) return - setSettings({ ...settings, [field]: value }) - } - - const initializeDefaultSettings = () => { - const defaultSettings: DeviceSettingsDto = { - id: 0, - deviceId: deviceId, - deviceName: deviceName, - dangerMaxTemperature: 40, - dangerMinTemperature: 5, - maxTemperature: 35, - minTemperature: 10, - maxGasPPM: 1000, - minGasPPM: 0, - maxLux: 100000, - minLux: 0, - maxHumidityPercent: 80, - minHumidityPercent: 20, - createdAt: new Date().toISOString(), - updatedAt: new Date().toISOString() - } - setSettings(defaultSettings) - } - - if (loading) { - return ( -
-
در حال بارگذاری...
-
- ) - } - - if (!deviceId) { - return ( -
-
شناسه دستگاه مشخص نشده است
- - ← بازگشت به انتخاب دستگاه - -
- ) - } - - return ( -
- {/* Header */} -
- - ← بازگشت به انتخاب دستگاه - -

- ⚙️ تنظیمات {deviceName} -

-
{/* Spacer for centering */} -
- - {/* Messages */} - {error && ( -
- {error} -
- )} - {success && ( -
- {success} -
- )} - - {!settings ? ( -
-
- تنظیمات برای این دستگاه وجود ندارد -
- -
- ) : ( -
-
-
- {/* Temperature Settings */} -
-

- 🌡️ تنظیمات دما -

- - {/*
- - handleInputChange('dangerMaxTemperature', parseFloat(e.target.value) || 0)} - className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500" - /> -
- -
- - handleInputChange('dangerMinTemperature', parseFloat(e.target.value) || 0)} - className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500" - /> -
*/} - -
- - handleInputChange('maxTemperature', parseFloat(e.target.value) || 0)} - className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500" - /> -
- -
- - handleInputChange('minTemperature', parseFloat(e.target.value) || 0)} - className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500" - /> -
-
- - {/* Gas Settings */} -
-

- 🫁 تنظیمات گاز -

- -
- - handleInputChange('maxGasPPM', parseInt(e.target.value) || 0)} - className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500" - /> -
- -
- - handleInputChange('minGasPPM', parseInt(e.target.value) || 0)} - className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500" - /> -
-
- - {/* Light Settings */} -
-

- 💡 تنظیمات نور -

- -
- - handleInputChange('maxLux', parseFloat(e.target.value) || 0)} - className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500" - /> -
- -
- - handleInputChange('minLux', parseFloat(e.target.value) || 0)} - className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500" - /> -
-
- - {/* Humidity Settings */} -
-

- 💧 تنظیمات رطوبت هوا -

- -
- - handleInputChange('maxHumidityPercent', parseFloat(e.target.value) || 0)} - className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500" - /> -
- -
- - handleInputChange('minHumidityPercent', parseFloat(e.target.value) || 0)} - className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500" - /> -
-
-
- - {/* Save Button */} -
- -
-
-
- )} -
- ) -} diff --git a/src/app/devices/page.tsx b/src/app/devices/page.tsx index 50e1fc4..a607bb9 100644 --- a/src/app/devices/page.tsx +++ b/src/app/devices/page.tsx @@ -1,6 +1,9 @@ "use client" import { useMemo, useState, useRef, useEffect } from 'react' import { api, DeviceDto } from '@/lib/api' +import { Settings, CheckCircle2, ArrowRight, Calendar, BarChart3, Activity, RotateCcw } from 'lucide-react' +import Link from 'next/link' +import Loading from '@/components/Loading' export default function DevicesPage() { const [loading, setLoading] = useState(false) @@ -94,140 +97,173 @@ export default function DevicesPage() { if (passwordRef.current) passwordRef.current.value = '' } - if (loading) return
در حال بررسی دستگاه...
+ if (loading) { + return + } return ( -
+
{/* Main Card */} -
+
{/* Title Section */} -
-
- 🚀 -

- {selected ? 'دستگاه فعال' : 'انتخاب دستگاه'} -

+
+
+ {selected ? ( + + ) : ( + + )}
-

+

+ {selected ? 'دستگاه فعال' : 'انتخاب دستگاه'} +

+

{selected ? `دستگاه "${selected.deviceName}" با موفقیت تأیید شد` - : 'نام دستگاه و رمز عبور را وارد کنید تا عملیات فعال شود.' + : 'نام دستگاه و رمز عبور را وارد کنید' }

{/* نمایش فرم فقط وقتی دستگاه انتخاب نشده */} {!selected ? ( -
+ {/* Input Fields */} -
- - +
+
+ + +
+
+ + +
{/* Error Message */} {error && ( -
{error}
+
+ {error} +
)} - {/* Confirm Button - همیشه فعال */} -
- -
+ {/* Confirm Button */} + ) : ( /* نمایش دکمه‌های عملیات وقتی دستگاه انتخاب شده */ -
+
{/* اطلاعات دستگاه فعال */} -
-

{selected.deviceName}

-

دستگاه فعال

+
+
+ +

{selected.deviceName}

+
+

دستگاه فعال و آماده استفاده

{/* Main Action Button */} - + + + داده‌های امروز + {/* Secondary Action Buttons */} -
- + - ⚙️ - تنظیمات - - - تقویم ماه جاری - - - انتخاب سال و ماه - + + تنظیمات دستگاه + +
+ + + تقویم ماه + + + + انتخاب ماه + +
{/* دکمه تغییر دستگاه */} -
+
)}
+ + {/* Back to Home */} +
+ + + بازگشت به صفحه اصلی + +
) diff --git a/src/app/globals.css b/src/app/globals.css index 1011a4b..a72a6d1 100644 --- a/src/app/globals.css +++ b/src/app/globals.css @@ -8,8 +8,8 @@ @theme inline { /* --color-background: var(--background); */ --color-foreground: var(--foreground); - --font-sans: var(--font-geist-sans); - --font-mono: var(--font-geist-mono); + --font-sans: 'Vazirmatn', -apple-system, BlinkMacSystemFont, 'Segoe UI', Arial, sans-serif; + --font-mono: 'Vazirmatn', monospace; } @media (prefers-color-scheme: dark) { @@ -19,9 +19,20 @@ } } +* { + font-family: 'Vazirmatn', -apple-system, BlinkMacSystemFont, 'Segoe UI', Arial, sans-serif; +} + body { /* background: var(--background); */ background: linear-gradient(180deg, #eef7ff, #f6fbff); color: var(--foreground); - font-family: vazir,Arial, Helvetica, sans-serif; + font-family: 'Vazirmatn', -apple-system, BlinkMacSystemFont, 'Segoe UI', Arial, sans-serif; + font-weight: 400; } + +.persian-number { + font-feature-settings: 'ss01'; + font-variant-numeric: persian; + font-family: 'Vazirmatn', -apple-system, BlinkMacSystemFont, 'Segoe UI', Arial, sans-serif; +} \ No newline at end of file diff --git a/src/app/layout.tsx b/src/app/layout.tsx index cf2998e..bd27a8d 100644 --- a/src/app/layout.tsx +++ b/src/app/layout.tsx @@ -1,21 +1,41 @@ import type { Metadata } from 'next' import './globals.css' +import ServiceWorkerRegistration from '@/components/ServiceWorkerRegistration' export const metadata: Metadata = { title: 'GreenHome', - description: 'GreenHome PWA', - manifest: 'manifest.json', - + description: 'مدیریت هوشمند گلخانه', + appleWebApp: { + capable: true, + statusBarStyle: 'default', + title: 'GreenHome' + } +} + +export const viewport = { + width: 'device-width', + initialScale: 1, + maximumScale: 1, + userScalable: false } export default function RootLayout({ children }: Readonly<{ children: React.ReactNode }>) { return ( - + + + + + + + - {children} + + + {children} + ) } diff --git a/src/app/manifest.ts b/src/app/manifest.ts new file mode 100644 index 0000000..55a03a3 --- /dev/null +++ b/src/app/manifest.ts @@ -0,0 +1,27 @@ +import { MetadataRoute } from 'next' + +export default function manifest(): MetadataRoute.Manifest { + return { + name: 'GreenHome', + short_name: 'GreenHome', + description: 'مدیریت هوشمند گلخانه', + start_url: '/', + display: 'standalone', + background_color: '#ffffff', + theme_color: '#16a34a', + icons: [ + { + src: '/icon-192.png', + sizes: '192x192', + type: 'image/png', + purpose: 'maskable' + }, + { + src: '/icon-512.png', + sizes: '512x512', + type: 'image/png', + purpose: 'maskable' + } + ] + } +} diff --git a/src/app/month_select/page.tsx b/src/app/month_select/page.tsx deleted file mode 100644 index 2465aaf..0000000 --- a/src/app/month_select/page.tsx +++ /dev/null @@ -1,144 +0,0 @@ -"use client" -import { useEffect, useMemo, useState } from 'react' -import { api, TelemetryDto } from '@/lib/api' -import { Card, DashboardGrid } from '@/components/DashboardCards' -import { LineChart, Panel } from '@/components/Charts' -import { persianToGregorian, getCurrentPersianDay, getCurrentPersianYear, getCurrentPersianMonth } from '@/lib/persian-date' - -function useQueryParam(name: string) { - if (typeof window === 'undefined') return null as string | null - return new URLSearchParams(window.location.search).get(name) -} - -export default function MonthSelectPage() { - const [telemetry, setTelemetry] = useState([]) - const [total, setTotal] = useState(0) - const [loading, setLoading] = useState(true) - const deviceId = Number(useQueryParam('deviceId') ?? '1') - const dateParam = useQueryParam('date') ?? `${getCurrentPersianYear()}/${getCurrentPersianMonth()}/${getCurrentPersianDay()}` // e.g., "1404/7/14" or "1404%2F7%2F14" - - // Decode the date parameter - const selectedDate = useMemo(() => { - if (!dateParam) return null - try { - // Decode URL-encoded date (e.g., "1404%2F7%2F14" -> "1404/7/14") - const decodedDate = decodeURIComponent(dateParam) - return decodedDate - } catch (error) { - console.error('Error decoding date parameter:', error) - return null - } - }, [dateParam]) - - useEffect(() => { - if (!selectedDate) { - setLoading(false) - return - } - - setLoading(true) - - try { - // Parse the Persian date (e.g., "1404/7/14") - const [year, month, day] = selectedDate.split('/').map(Number) - - // Convert to Gregorian date for start of day - const startDate = persianToGregorian(year, month, day) - startDate.setHours(0, 0, 0, 0) - - // End of day - const endDate = new Date(startDate) - endDate.setHours(23, 59, 59, 999) - - // Convert to UTC strings - const startUtc = startDate.toISOString() - const endUtc = endDate.toISOString() - - // Load telemetry data for the specific date range - api.listTelemetry({ deviceId, startUtc, endUtc }).then(r => { - setTelemetry(r.items) - setTotal(r.totalCount) - }).catch(console.error).finally(() => setLoading(false)) - } catch (error) { - console.error('Error parsing date:', error) - setLoading(false) - } - }, [deviceId, selectedDate]) - - // Sort telemetry data by timestamp to ensure proper chronological order - const sortedTelemetry = useMemo(() => { - return [...telemetry].sort((a, b) => new Date(a.timestampUtc).getTime() - new Date(b.timestampUtc).getTime()) - }, [telemetry]) - - const labels = useMemo(() => sortedTelemetry.map(t => t.persianDate), [sortedTelemetry]) - const soil = useMemo(() => sortedTelemetry.map(t => Number(t.soilPercent ?? 0)), [sortedTelemetry]) - const temp = useMemo(() => sortedTelemetry.map(t => Number(t.temperatureC ?? 0)), [sortedTelemetry]) - const hum = useMemo(() => sortedTelemetry.map(t => Number(t.humidityPercent ?? 0)), [sortedTelemetry]) - const gas = useMemo(() => sortedTelemetry.map(t => Number(t.gasPPM ?? 0)), [sortedTelemetry]) - const lux = useMemo(() => sortedTelemetry.map(t => Number(t.lux ?? 0)), [sortedTelemetry]) - - if (loading) { - return ( -
-
در حال بارگذاری...
-
- ) - } - - if (!selectedDate) { - return ( -
-
تاریخ انتخاب نشده است
- - ← بازگشت به تقویم - -
- ) - } - - return ( -
- {/* Header with navigation */} -
-
- - ← بازگشت به تقویم - -

- 📊 جزئیات داده‌های {selectedDate} -

-
{/* Spacer for centering */} -
-
- - - - - - - - - -
- - - - - - - - - - - - -
-
- ) -} diff --git a/src/app/page.tsx b/src/app/page.tsx index cd7cebf..f306332 100644 --- a/src/app/page.tsx +++ b/src/app/page.tsx @@ -1,13 +1,90 @@ +import { Home as HomeIcon, Settings, Calendar, BarChart3, Leaf } from 'lucide-react' +import Link from 'next/link' + export default function Home() { + const menuItems = [ + { + title: 'انتخاب دستگاه', + description: 'اتصال به دستگاه گلخانه', + href: '/devices', + icon: Settings, + color: 'from-blue-500 to-blue-600', + iconColor: 'text-blue-500' + }, + { + title: 'تقویم', + description: 'مشاهده داده‌های ماهانه', + href: '/calendar?deviceId=1', + icon: Calendar, + color: 'from-green-500 to-green-600', + iconColor: 'text-green-500' + }, + { + title: 'جزئیات روز', + description: 'داده‌های روزانه', + href: '/day-details?deviceId=1&year=1403&month=1', + icon: BarChart3, + color: 'from-purple-500 to-purple-600', + iconColor: 'text-purple-500' + }, + { + title: 'داده‌های تله‌متری', + description: 'مشاهده داده‌های لحظه‌ای', + href: '/telemetry?deviceId=1', + icon: Leaf, + color: 'from-orange-500 to-orange-600', + iconColor: 'text-orange-500' + } + ] + return ( -
-

GreenHome

- +
+
+ {/* Header */} +
+
+ +
+

GreenHome

+

مدیریت هوشمند گلخانه

+
+ + {/* Menu Grid */} +
+ {menuItems.map((item) => { + const Icon = item.icon + return ( + +
+
+
+ +
+
+

+ {item.title} +

+

{item.description}

+
+
+
+
+ + ) + })} +
+ + {/* Footer Info */} +
+

+ سیستم مدیریت و مانیتورینگ گلخانه هوشمند +

+
+
) } diff --git a/src/app/service-worker.ts b/src/app/service-worker.ts new file mode 100644 index 0000000..d6021cd --- /dev/null +++ b/src/app/service-worker.ts @@ -0,0 +1,95 @@ +/// + +export type {}; +declare let self: ServiceWorkerGlobalScope; + +const CACHE_NAME = 'greenhome-v1'; + +// Add list of files to cache here. +const FILES_TO_CACHE = [ + '/', + '/manifest.json', + '/icon-192.png', + '/icon-512.png', +]; + +self.addEventListener('install', (event: ExtendableEvent) => { + event.waitUntil( + (async () => { + const cache = await caches.open(CACHE_NAME); + await cache.addAll(FILES_TO_CACHE); + await self.skipWaiting(); + })() + ); +}); + +self.addEventListener('activate', (event: ExtendableEvent) => { + event.waitUntil( + (async () => { + await self.clients.claim(); + + // Remove old caches + const keys = await caches.keys(); + await Promise.all( + keys + .filter((key) => key !== CACHE_NAME) + .map((key) => caches.delete(key)) + ); + })() + ); +}); + +self.addEventListener('fetch', (event: FetchEvent) => { + if (event.request.mode === 'navigate') { + event.respondWith( + (async () => { + try { + const preloadResponse = await event.preloadResponse; + if (preloadResponse) { + return preloadResponse; + } + + return await fetch(event.request); + } catch (e) { + const cache = await caches.open(CACHE_NAME); + return await cache.match('/') || new Response('', { + status: 404, + statusText: 'Not Found', + }); + } + })() + ); + return; + } + + event.respondWith( + (async () => { + const cache = await caches.open(CACHE_NAME); + const cachedResponse = await cache.match(event.request); + + if (cachedResponse) { + return cachedResponse; + } + + try { + const response = await fetch(event.request); + + if (!response || response.status !== 200 || response.type !== 'basic') { + return response; + } + + if (event.request.url.startsWith('http')) { + const responseToCache = response.clone(); + await cache.put(event.request, responseToCache); + } + + return response; + } catch (e) { + return new Response('', { + status: 404, + statusText: 'Not Found', + }); + } + })() + ); +}); diff --git a/src/app/telemetry/page.tsx b/src/app/telemetry/page.tsx new file mode 100644 index 0000000..a6deaa3 --- /dev/null +++ b/src/app/telemetry/page.tsx @@ -0,0 +1,207 @@ +"use client" +import { useEffect, useMemo, useState, useCallback, useRef } from 'react' +import { api, TelemetryDto } from '@/lib/api' +import { Card, DashboardGrid } from '@/components/DashboardCards' +import { LineChart, Panel } from '@/components/Charts' +import { persianToGregorian, getCurrentPersianDay, getCurrentPersianYear, getCurrentPersianMonth } from '@/lib/persian-date' +import { BarChart3, ChevronRight, Calendar as CalendarIcon, RefreshCw } from 'lucide-react' +import Link from 'next/link' +import Loading from '@/components/Loading' + +// زمان به‌روزرسانی خودکار (به میلی‌ثانیه) - می‌توانید این مقدار را تغییر دهید +const AUTO_REFRESH_INTERVAL = 10 * 1000 // 10 ثانیه + +function useQueryParam(name: string) { + if (typeof window === 'undefined') return null as string | null + return new URLSearchParams(window.location.search).get(name) +} + +export default function TelemetryPage() { + const [telemetry, setTelemetry] = useState([]) + const [total, setTotal] = useState(0) + const [loading, setLoading] = useState(true) + const [lastUpdate, setLastUpdate] = useState(null) + const deviceId = Number(useQueryParam('deviceId') ?? '1') + const dateParam = useQueryParam('date') ?? `${getCurrentPersianYear()}/${getCurrentPersianMonth()}/${getCurrentPersianDay()}` + const intervalRef = useRef(null) + + const selectedDate = useMemo(() => { + if (!dateParam) return null + try { + const decodedDate = decodeURIComponent(dateParam) + return decodedDate + } catch (error) { + console.error('Error decoding date parameter:', error) + return null + } + }, [dateParam]) + + // تابع بارگذاری داده‌ها + const loadData = useCallback(async (showLoading = true) => { + if (!selectedDate) { + setLoading(false) + return + } + + if (showLoading) { + setLoading(true) + } + + try { + const [year, month, day] = selectedDate.split('/').map(Number) + const startDate = persianToGregorian(year, month, day) + startDate.setHours(0, 0, 0, 0) + const endDate = new Date(startDate) + endDate.setHours(23, 59, 59, 999) + const startUtc = startDate.toISOString() + const endUtc = endDate.toISOString() + + const result = await api.listTelemetry({ deviceId, startUtc, endUtc }) + setTelemetry(result.items) + setTotal(result.totalCount) + setLastUpdate(new Date()) + } catch (error) { + console.error('Error loading telemetry:', error) + } finally { + if (showLoading) { + setLoading(false) + } + } + }, [deviceId, selectedDate]) + + // بارگذاری اولیه + useEffect(() => { + loadData(true) + }, [loadData]) + + // تنظیم به‌روزرسانی خودکار + useEffect(() => { + if (!selectedDate) return + + // پاک کردن interval قبلی + if (intervalRef.current) { + clearInterval(intervalRef.current) + } + + // تنظیم interval جدید + intervalRef.current = setInterval(() => { + loadData(false) // بدون نمایش loading + }, AUTO_REFRESH_INTERVAL) + + // Cleanup + return () => { + if (intervalRef.current) { + clearInterval(intervalRef.current) + } + } + }, [selectedDate, loadData]) + + const sortedTelemetry = useMemo(() => { + return [...telemetry].sort((a, b) => new Date(a.timestampUtc).getTime() - new Date(b.timestampUtc).getTime()) + }, [telemetry]) + + // تبدیل timestamp به ساعت (HH:MM:SS) + const labels = useMemo(() => { + return sortedTelemetry.map(t => { + const date = new Date(t.timestampUtc) + const hours = date.getHours().toString().padStart(2, '0') + const minutes = date.getMinutes().toString().padStart(2, '0') + const seconds = date.getSeconds().toString().padStart(2, '0') + return `${hours}:${minutes}:${seconds}` + }) + }, [sortedTelemetry]) + const soil = useMemo(() => sortedTelemetry.map(t => Number(t.soilPercent ?? 0)), [sortedTelemetry]) + const temp = useMemo(() => sortedTelemetry.map(t => Number(t.temperatureC ?? 0)), [sortedTelemetry]) + const hum = useMemo(() => sortedTelemetry.map(t => Number(t.humidityPercent ?? 0)), [sortedTelemetry]) + const gas = useMemo(() => sortedTelemetry.map(t => Number(t.gasPPM ?? 0)), [sortedTelemetry]) + const lux = useMemo(() => sortedTelemetry.map(t => Number(t.lux ?? 0)), [sortedTelemetry]) + + if (loading) { + return + } + + if (!selectedDate) { + return ( +
+
+ +
تاریخ انتخاب نشده است
+ + + بازگشت به تقویم + +
+
+ ) + } + + return ( +
+
+ {/* Header */} +
+ + + بازگشت به تقویم + +
+
+
+ +
+
+

+ جزئیات داده‌های {selectedDate} +

+ {lastUpdate && ( +

+ آخرین به‌روزرسانی: {lastUpdate.toLocaleTimeString('fa-IR')} +

+ )} +
+
+ +
+
+ + + + + + + + + +
+ + + + + + + + + + + + +
+
+
+ ) +} + diff --git a/src/components/Charts.tsx b/src/components/Charts.tsx index af0383e..a7135fd 100644 --- a/src/components/Charts.tsx +++ b/src/components/Charts.tsx @@ -13,6 +13,12 @@ import { Chart.register(LineElement, CategoryScale, LinearScale, PointElement, Legend, Tooltip, Filler) +// تابع تبدیل ارقام انگلیسی به فارسی +function toPersianDigits(str: string | number): string { + const persianDigits = ['۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹'] + return str.toString().replace(/\d/g, (digit) => persianDigits[parseInt(digit)]) +} + type Series = { label: string; data: number[]; borderColor: string; backgroundColor?: string; fill?: boolean } type Props = { @@ -23,34 +29,106 @@ type Props = { export function Panel({ title, children }: { title: string; children: React.ReactNode }) { return ( -
-
{title}
- {children} +
+
+

{title}

+
+
+ {children} +
) } export function LineChart({ labels, series }: Props) { return ( - ({ - label: s.label, - data: s.data, - borderColor: s.borderColor, - backgroundColor: s.backgroundColor ?? s.borderColor, - fill: s.fill ?? false, - tension: 0.3, - pointRadius: 2 - })) - }} - options={{ - responsive: true, - plugins: { legend: { display: true, position: 'bottom' } }, - scales: { x: { display: true }, y: { display: true } } - }} - /> +
+ ({ + label: s.label, + data: s.data, + borderColor: s.borderColor, + backgroundColor: s.backgroundColor ?? s.borderColor, + fill: s.fill ?? false, + tension: 0.3, + pointRadius: 2 + })) + }} + options={{ + responsive: true, + maintainAspectRatio: true, + font: { + family: "'Vazirmatn', -apple-system, BlinkMacSystemFont, 'Segoe UI', Arial, sans-serif" + }, + plugins: { + legend: { + display: true, + position: 'bottom', + labels: { + font: { + family: "'Vazirmatn', -apple-system, BlinkMacSystemFont, 'Segoe UI', Arial, sans-serif", + size: 12 + }, + padding: 15 + } + }, + tooltip: { + titleFont: { + family: "'Vazirmatn', -apple-system, BlinkMacSystemFont, 'Segoe UI', Arial, sans-serif" + }, + bodyFont: { + family: "'Vazirmatn', -apple-system, BlinkMacSystemFont, 'Segoe UI', Arial, sans-serif" + }, + callbacks: { + label: function(context) { + return `${context.dataset.label}: ${toPersianDigits(context.parsed.y.toFixed(2))}` + }, + title: function(context) { + return `ساعت: ${context[0].label}` + } + } + } + }, + scales: { + x: { + display: true, + ticks: { + font: { + family: "'Vazirmatn', -apple-system, BlinkMacSystemFont, 'Segoe UI', Arial, sans-serif", + size: 11 + }, + callback: function(value, index) { + const label = labels[index] + return label ? toPersianDigits(label) : '' + } + }, + grid: { + display: true, + color: 'rgba(0, 0, 0, 0.05)' + } + }, + y: { + display: true, + ticks: { + font: { + family: "'Vazirmatn', -apple-system, BlinkMacSystemFont, 'Segoe UI', Arial, sans-serif", + size: 11 + }, + callback: function(value) { + return toPersianDigits(value.toString()) + } + }, + grid: { + display: true, + color: 'rgba(0, 0, 0, 0.05)' + } + } + } + }} + /> +
) } diff --git a/src/components/DashboardCards.tsx b/src/components/DashboardCards.tsx index 46c0d27..df7ac5b 100644 --- a/src/components/DashboardCards.tsx +++ b/src/components/DashboardCards.tsx @@ -1,23 +1,115 @@ "use client" import React from 'react' +import { Sun, Wind, Droplets, Thermometer, Database, TrendingUp, TrendingDown } from 'lucide-react' type CardProps = { title: string value: string | number - subtitle?: string, - icon?:string + subtitle?: string + icon?: string + color?: 'light' | 'gas' | 'soil' | 'humidity' | 'temperature' | 'data' +} + +const iconMap: Record> = { + '💡': Sun, + '🫁': Wind, + '🌱': Droplets, + '💧': Droplets, + '🌡️': Thermometer, + '📊': Database, +} + +const colorConfig: Record = { + light: { + gradient: 'from-yellow-500 to-orange-500', + border: 'border-yellow-200', + iconBg: 'from-yellow-500 to-orange-500' + }, + gas: { + gradient: 'from-gray-600 to-gray-700', + border: 'border-gray-300', + iconBg: 'from-gray-600 to-gray-700' + }, + soil: { + gradient: 'from-green-500 to-emerald-600', + border: 'border-green-200', + iconBg: 'from-green-500 to-emerald-600' + }, + humidity: { + gradient: 'from-blue-500 to-cyan-500', + border: 'border-blue-200', + iconBg: 'from-blue-500 to-cyan-500' + }, + temperature: { + gradient: 'from-red-500 to-orange-500', + border: 'border-red-200', + iconBg: 'from-red-500 to-orange-500' + }, + data: { + gradient: 'from-purple-500 to-indigo-600', + border: 'border-purple-200', + iconBg: 'from-purple-500 to-indigo-600' + } +} + +// Auto-detect color based on title +function detectColor(title: string, icon?: string): 'light' | 'gas' | 'soil' | 'humidity' | 'temperature' | 'data' { + const lowerTitle = title.toLowerCase() + if (lowerTitle.includes('نور') || icon === '💡') return 'light' + if (lowerTitle.includes('گاز') || icon === '🫁') return 'gas' + if (lowerTitle.includes('خاک') || icon === '🌱') return 'soil' + if (lowerTitle.includes('رطوبت') || icon === '💧') return 'humidity' + if (lowerTitle.includes('دما') || icon === '🌡️') return 'temperature' + if (lowerTitle.includes('داده') || icon === '📊') return 'data' + return 'data' // default } export function DashboardGrid({ children }: { children: React.ReactNode }) { - return
{children}
+ return
{children}
} -export function Card({ title, value, subtitle,icon }: CardProps) { +export function Card({ title, value, subtitle, icon, color }: CardProps) { + const IconComponent = icon && iconMap[icon] ? iconMap[icon] : null + const cardColor = color || detectColor(title, icon) + const colors = colorConfig[cardColor] + + // Extract max and min from subtitle if available + const hasStats = subtitle?.includes('حداکثر') && subtitle?.includes('حداقل') + return ( -
-
{icon} {title}
-
{value}
- {subtitle &&
{subtitle}
} +
+
+
+
+ {title.replace(/[💡🫁🌱💧🌡️📊]/g, '').trim()} +
+ {IconComponent && ( +
+ +
+ )} +
+
{value}
+ {subtitle && ( +
+ {hasStats ? ( + <> + + + {subtitle.match(/حداکثر:\s*([0-9.]+)/)?.[1]} + + + + {subtitle.match(/حداقل:\s*([0-9.]+)/)?.[1]} + + + ) : ( + subtitle + )} +
+ )} +
+
) } diff --git a/src/components/Loading.tsx b/src/components/Loading.tsx new file mode 100644 index 0000000..3e038d3 --- /dev/null +++ b/src/components/Loading.tsx @@ -0,0 +1,27 @@ +'use client' + +import { Loader2 } from 'lucide-react' + +type LoadingProps = { + message?: string + fullScreen?: boolean +} + +export default function Loading({ message = 'در حال بارگذاری...', fullScreen = true }: LoadingProps) { + const containerClass = fullScreen + ? 'min-h-screen flex items-center justify-center p-4' + : 'flex items-center justify-center p-8' + + return ( +
+
+
+ +
+
+

{message}

+
+
+ ) +} + diff --git a/src/components/ServiceWorkerRegistration.tsx b/src/components/ServiceWorkerRegistration.tsx new file mode 100644 index 0000000..4591c6b --- /dev/null +++ b/src/components/ServiceWorkerRegistration.tsx @@ -0,0 +1,47 @@ +'use client'; + +import { useEffect } from 'react'; + +export default function ServiceWorkerRegistration() { + useEffect(() => { + if ( + typeof window !== 'undefined' && + 'serviceWorker' in navigator + ) { + const registerServiceWorker = async () => { + try { + const registration = await navigator.serviceWorker.register('/sw.js', { + scope: '/', + }); + + console.log('Service Worker registered successfully:', registration.scope); + + // Handle updates + registration.addEventListener('updatefound', () => { + const newWorker = registration.installing; + if (newWorker) { + newWorker.addEventListener('statechange', () => { + if (newWorker.state === 'installed' && navigator.serviceWorker.controller) { + // New service worker available + console.log('New service worker available'); + } + }); + } + }); + } catch (error) { + console.error('Service Worker registration failed:', error); + } + }; + + // Register immediately if page is already loaded + if (document.readyState === 'complete') { + registerServiceWorker(); + } else { + window.addEventListener('load', registerServiceWorker); + } + } + }, []); + + return null; +} +