Bläddra i källkod

【新增】添加 PWA 支持并配置相关文件

- 新增 `manifest.json` 和 `browserconfig.xml` 以支持应用安装
- 在 `index.html` 中添加 PWA 相关的 meta 标签和图标链接
- 注册 Service Worker 并实现缓存策略
- 添加应用安装提示 UI 及交互逻辑
- 实现通过 URL 参数启动应用功能(番茄钟、休息、统计)
- 新增 `sw.js` 文件用于处理缓存和后台同步等 PWA 功能
PJ568 1 år sedan
förälder
incheckning
9bba9bcce3
4 ändrade filer med 436 tillägg och 2 borttagningar
  1. 11 0
      browserconfig.xml
  2. 226 2
      index.html
  3. 91 0
      manifest.json
  4. 108 0
      sw.js

+ 11 - 0
browserconfig.xml

@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="utf-8"?>
+<browserconfig>
+  <msapplication>
+    <tile>
+      <square70x70logo src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 70 70'%3E%3Crect width='70' height='70' fill='%234caf50'/%3E%3Ctext x='35' y='45' font-size='35' text-anchor='middle' fill='white'%3E🍅%3C/text%3E%3C/svg%3E"/>
+      <square150x150logo src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 150 150'%3E%3Crect width='150' height='150' fill='%234caf50'/%3E%3Ctext x='75' y='100' font-size='75' text-anchor='middle' fill='white'%3E🍅%3C/text%3E%3C/svg%3E"/>
+      <square310x310logo src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 310 310'%3E%3Crect width='310' height='310' fill='%234caf50' rx='24'/%3E%3Ctext x='155' y='205' font-size='155' text-anchor='middle' fill='white'%3E🍅%3C/text%3E%3C/svg%3E"/>
+      <TileColor>#4caf50</TileColor>
+    </tile>
+  </msapplication>
+</browserconfig>

+ 226 - 2
index.html

@@ -5,11 +5,28 @@
     <meta name="viewport" content="width=device-width, initial-scale=1.0" />
     <meta name="description" content="🎓🍅♨️ - 高效记录进度的番茄钟" />
     <meta name="keywords" content="进度跟踪,效率工具,时间管理" />
+
+    <!-- PWA 相关元标签 -->
+    <meta name="theme-color" content="#4caf50" />
+    <meta name="apple-mobile-web-app-capable" content="yes" />
+    <meta name="apple-mobile-web-app-status-bar-style" content="default" />
+    <meta name="apple-mobile-web-app-title" content="番茄钟" />
+    <meta name="application-name" content="番茄钟" />
+    <meta name="msapplication-TileColor" content="#4caf50" />
+    <meta name="msapplication-config" content="browserconfig.xml" />
+
+    <!-- PWA Manifest 和图标 -->
+    <link rel="manifest" href="manifest.json" />
     <link
       rel="icon"
       type="image/svg+xml"
-      href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'%3E%3Ctext y='.9em' font-size='90'%3E⌚%3C/text%3E%3C/svg%3E"
+      href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'%3E%3Crect width='100' height='100' fill='%234caf50'/%3E%3Ctext x='50' y='65' font-size='50' text-anchor='middle' fill='white'%3E🍅%3C/text%3E%3C/svg%3E"
+    />
+    <link
+      rel="apple-touch-icon"
+      href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 180 180'%3E%3Crect width='180' height='180' fill='%234caf50' rx='24'/%3E%3Ctext x='90' y='110' font-size='90' text-anchor='middle' fill='white'%3E🍅%3C/text%3E%3C/svg%3E"
     />
+
     <title>🎓🍅♨️</title>
     <style>
       /* CSS 变量定义 - 浅色主题 */
@@ -361,7 +378,7 @@
             <button class="btn cancel-btn" style="display: none">❎</button>
           </div>
           <!-- <div class="controls"> -->
-            <!-- TODO: 实现“📄(导出数据文件)、⚙️(应用数据文件)和 🏠([源码](https://github.com/PJ-568/time-of-studying))”数据管理按钮和相关功能 -->
+          <!-- TODO: 实现“📄(导出数据文件)、⚙️(应用数据文件)和 🏠([源码](https://github.com/PJ-568/time-of-studying))”数据管理按钮和相关功能 -->
           <!-- </div> -->
         </div>
 
@@ -936,6 +953,213 @@
       const idleElement = document.querySelector(".idle");
       const idleTimer = new IdleTimer(idleElement);
 
+      // PWA 相关功能
+      // 注册 Service Worker
+      if ("serviceWorker" in navigator) {
+        window.addEventListener("load", () => {
+          navigator.serviceWorker
+            .register("./sw.js")
+            .then((registration) => {
+              console.log("Service Worker 注册成功:", registration.scope);
+
+              // 检查是否有更新
+              registration.addEventListener("updatefound", () => {
+                const newWorker = registration.installing;
+                newWorker.addEventListener("statechange", () => {
+                  if (
+                    newWorker.state === "installed" &&
+                    navigator.serviceWorker.controller
+                  ) {
+                    // 有新版本可用
+                    console.log("发现新版本的应用");
+                    // 这里可以添加更新提示
+                  }
+                });
+              });
+            })
+            .catch((error) => {
+              console.error("Service Worker 注册失败:", error);
+            });
+        });
+      }
+
+      // PWA 安装提示 - 使用图标而非文字
+      let deferredPrompt;
+      const installPromptElement = document.createElement("div");
+      installPromptElement.id = "install-prompt";
+      installPromptElement.style.cssText = `
+        position: fixed;
+        bottom: 20px;
+        left: 50%;
+        transform: translateX(-50%);
+        background-color: var(--bg-secondary);
+        color: var(--text-primary);
+        padding: 16px;
+        border-radius: 8px;
+        box-shadow: 0 4px 12px var(--shadow-primary);
+        display: none;
+        align-items: center;
+        gap: 16px;
+        z-index: 1000;
+        animation: slideUp 0.3s ease-out;
+      `;
+
+      // 使用图标表示安装应用
+      const installIcon = document.createElement("span");
+      installIcon.textContent = "📱";
+      installIcon.style.cssText = "font-size: 24px;";
+      installPromptElement.appendChild(installIcon);
+
+      const installButton = document.createElement("button");
+      installButton.textContent = "⬇️";
+      installButton.className = "btn install-btn";
+      installButton.title = "安装应用";
+      installButton.style.cssText = `
+        background-color: var(--text-secondary);
+        color: white;
+        border: none;
+        padding: 8px 16px;
+        border-radius: 50%;
+        cursor: pointer;
+        font-size: 20px;
+        width: 44px;
+        height: 44px;
+        display: flex;
+        align-items: center;
+        justify-content: center;
+      `;
+      installPromptElement.appendChild(installButton);
+
+      const dismissButton = document.createElement("button");
+      dismissButton.textContent = "❌";
+      dismissButton.className = "btn dismiss-btn";
+      dismissButton.title = "忽略";
+      dismissButton.style.cssText = `
+        background: none;
+        border: none;
+        font-size: 18px;
+        cursor: pointer;
+        padding: 4px;
+        color: var(--text-primary);
+      `;
+      installPromptElement.appendChild(dismissButton);
+
+      // 添加动画样式
+      const style = document.createElement("style");
+      style.textContent = `
+        @keyframes slideUp {
+          from { transform: translateX(-50%) translateY(100px); opacity: 0; }
+          to { transform: translateX(-50%) translateY(0); opacity: 1; }
+        }
+        
+        @keyframes slideDown {
+          from { transform: translateX(-50%) translateY(0); opacity: 1; }
+          to { transform: translateX(-50%) translateY(100px); opacity: 0; }
+        }
+        
+        .install-prompt-dismiss {
+          animation: slideDown 0.3s ease-out forwards;
+        }
+      `;
+      document.head.appendChild(style);
+
+      document.body.appendChild(installPromptElement);
+
+      // 监听安装提示事件
+      window.addEventListener("beforeinstallprompt", (e) => {
+        // 阻止默认的安装提示
+        e.preventDefault();
+        // 存储事件以便后续使用
+        deferredPrompt = e;
+
+        // 检查用户是否已经安装了应用
+        if (!localStorage.getItem("pwa-install-dismissed")) {
+          // 显示安装提示
+          installPromptElement.style.display = "flex";
+        }
+      });
+
+      // 安装按钮点击事件
+      installButton.addEventListener("click", async () => {
+        if (deferredPrompt) {
+          // 显示安装提示
+          deferredPrompt.prompt();
+          // 等待用户响应
+          const { outcome } = await deferredPrompt.userChoice;
+          console.log(`用户${outcome === "accepted" ? "接受" : "拒绝"}了安装`);
+          // 重置 deferredPrompt
+          deferredPrompt = null;
+
+          // 隐藏安装提示
+          hideInstallPrompt();
+        }
+      });
+
+      // 忽略按钮点击事件
+      dismissButton.addEventListener("click", () => {
+        hideInstallPrompt();
+        // 记录用户已经忽略过安装提示
+        localStorage.setItem("pwa-install-dismissed", "true");
+      });
+
+      // 隐藏安装提示的函数
+      function hideInstallPrompt() {
+        installPromptElement.classList.add("install-prompt-dismiss");
+        setTimeout(() => {
+          installPromptElement.style.display = "none";
+          installPromptElement.classList.remove("install-prompt-dismiss");
+        }, 300);
+      }
+
+      // 检查应用是否已经安装
+      window.addEventListener("appinstalled", () => {
+        console.log("应用已成功安装");
+        hideInstallPrompt();
+        localStorage.setItem("pwa-installed", "true");
+      });
+
+      // 处理应用启动时的 URL 参数
+      function handleAppAction() {
+        const urlParams = new URLSearchParams(window.location.search);
+        const action = urlParams.get("action");
+
+        if (action === "pomodoro") {
+          // 自动开始番茄钟
+          setTimeout(() => {
+            if (!pomodoroTimer.isRunning) {
+              pomodoroTimer.start();
+            }
+          }, 1000);
+        } else if (action === "idle") {
+          // 自动开始空闲钟
+          setTimeout(() => {
+            if (!idleTimer.isRunning) {
+              idleTimer.start();
+            }
+          }, 1000);
+        } else if (action === "stats") {
+          // 高亮显示学习时长区域
+          const studyTimeElement = document.querySelector(".study-time");
+          studyTimeElement.style.animation = "pulse 2s ease-in-out 3";
+
+          const pulseStyle = document.createElement("style");
+          pulseStyle.textContent = `
+            @keyframes pulse {
+              0%, 100% { transform: scale(1); }
+              50% { transform: scale(1.05); }
+            }
+          `;
+          document.head.appendChild(pulseStyle);
+
+          setTimeout(() => {
+            studyTimeElement.style.animation = "";
+          }, 6000);
+        }
+      }
+
+      // 处理应用启动
+      handleAppAction();
+
       // 请求通知权限
       if ("Notification" in window && Notification.permission === "default") {
         Notification.requestPermission();

+ 91 - 0
manifest.json

@@ -0,0 +1,91 @@
+{
+  "name": "🎓🍅♨️",
+  "short_name": "🍅",
+  "description": "🎓🍅♨️ - 高效记录进度的番茄钟应用",
+  "start_url": "/",
+  "display": "standalone",
+  "background_color": "#f5f5f5",
+  "theme_color": "#4caf50",
+  "orientation": "any",
+  "scope": "/",
+  "lang": "zh-Hans-CN",
+  "dir": "ltr",
+  "categories": ["productivity", "education", "utilities"],
+  "icons": [
+    {
+      "src": "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'%3E%3Crect width='100' height='100' fill='%234caf50'/%3E%3Ctext x='50' y='65' font-size='50' text-anchor='middle' fill='white'%3E🍅%3C/text%3E%3C/svg%3E",
+      "sizes": "any",
+      "type": "image/svg+xml",
+      "purpose": "any maskable"
+    },
+    {
+      "src": "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 192 192'%3E%3Crect width='192' height='192' fill='%234caf50' rx='24'/%3E%3Ctext x='96' y='120' font-size='96' text-anchor='middle' fill='white'%3E🍅%3C/text%3E%3C/svg%3E",
+      "sizes": "192x192",
+      "type": "image/svg+xml",
+      "purpose": "any"
+    },
+    {
+      "src": "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 512 512'%3E%3Crect width='512' height='512' fill='%234caf50' rx='64'/%3E%3Ctext x='256' y='320' font-size='256' text-anchor='middle' fill='white'%3E🍅%3C/text%3E%3C/svg%3E",
+      "sizes": "512x512",
+      "type": "image/svg+xml",
+      "purpose": "any"
+    }
+  ],
+  "shortcuts": [
+    {
+      "name": "开始番茄钟",
+      "short_name": "番茄钟",
+      "description": "快速开始 25 分钟番茄钟计时",
+      "url": "/?action=pomodoro",
+      "icons": [
+        {
+          "src": "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'%3E%3Crect width='100' height='100' fill='%23ff5722' rx='16'/%3E%3Ctext x='50' y='65' font-size='50' text-anchor='middle' fill='white'%3E🍅%3C/text%3E%3C/svg%3E",
+          "sizes": "96x96"
+        }
+      ]
+    },
+    {
+      "name": "开始休息",
+      "short_name": "休息",
+      "description": "快速开始 5 分钟休息计时",
+      "url": "/?action=idle",
+      "icons": [
+        {
+          "src": "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'%3E%3Crect width='100' height='100' fill='%232196f3' rx='16'/%3E%3Ctext x='50' y='65' font-size='50' text-anchor='middle' fill='white'%3E♨️%3C/text%3E%3C/svg%3E",
+          "sizes": "96x96"
+        }
+      ]
+    },
+    {
+      "name": "查看学习统计",
+      "short_name": "统计",
+      "description": "查看总学习时长",
+      "url": "/?action=stats",
+      "icons": [
+        {
+          "src": "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'%3E%3Crect width='100' height='100' fill='%234caf50' rx='16'/%3E%3Ctext x='50' y='65' font-size='50' text-anchor='middle' fill='white'%3E🎓%3C/text%3E%3C/svg%3E",
+          "sizes": "96x96"
+        }
+      ]
+    }
+  ],
+  "screenshots": [
+    {
+      "src": "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 360 640'%3E%3Crect width='360' height='640' fill='%23f5f5f5'/%3E%3Ctext x='180' y='320' font-size='24' text-anchor='middle' fill='%23333'%3E番茄钟应用截图%3C/text%3E%3C/svg%3E",
+      "sizes": "360x640",
+      "type": "image/svg+xml",
+      "form_factor": "narrow"
+    },
+    {
+      "src": "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 1280 720'%3E%3Crect width='1280' height='720' fill='%23f5f5f5'/%3E%3Ctext x='640' y='360' font-size='48' text-anchor='middle' fill='%23333'%3E番茄钟应用桌面视图%3C/text%3E%3C/svg%3E",
+      "sizes": "1280x720",
+      "type": "image/svg+xml",
+      "form_factor": "wide"
+    }
+  ],
+  "related_applications": [],
+  "prefer_related_applications": false,
+  "edge_side_panel": {
+    "preferred_width": 400
+  }
+}

+ 108 - 0
sw.js

@@ -0,0 +1,108 @@
+// Service Worker for 番茄钟应用 PWA 支持
+
+const CACHE_NAME = "time-of-studying-v1";
+const STATIC_CACHE_URLS = [
+  "/",
+  "/index.html",
+  // 添加应用可能需要的其他静态资源
+  "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'%3E%3Ctext y='.9em' font-size='90'%3E⌚%3C/text%3E%3C/svg%3E",
+  "data:audio/wav;base64,UklGRnoGAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQoGAACBhYqFbF1fdJivrJBhNjVgodDbq2EcBj+a2/LDciUFLIHO8tiJNwgZaLvt559NEAxQp+PwtmMcBjiR1/LMeSwFJHfH8N2QQAoUXrTp66hVFApGn+DyvmwhBSuBzvLZiTYIG2m98OScTgwOUarm7blmFgU7k9n1unEiBC13yO/eizEIHWq+8+OWT",
+];
+
+// 安装事件 - 缓存静态资源
+self.addEventListener("install", (event) => {
+  console.log("Service Worker 安装中...");
+  event.waitUntil(
+    caches
+      .open(CACHE_NAME)
+      .then((cache) => {
+        console.log("缓存静态资源");
+        return cache.addAll(STATIC_CACHE_URLS);
+      })
+      .then(() => {
+        console.log("静态资源缓存完成");
+        return self.skipWaiting();
+      })
+  );
+});
+
+// 激活事件 - 清理旧缓存
+self.addEventListener("activate", (event) => {
+  console.log("Service Worker 激活中...");
+  event.waitUntil(
+    caches
+      .keys()
+      .then((cacheNames) => {
+        return Promise.all(
+          cacheNames.map((cacheName) => {
+            if (cacheName !== CACHE_NAME) {
+              console.log("删除旧缓存:", cacheName);
+              return caches.delete(cacheName);
+            }
+          })
+        );
+      })
+      .then(() => {
+        console.log("Service Worker 激活完成");
+        return self.clients.claim();
+      })
+  );
+});
+
+// 网络请求拦截 - 缓存优先策略
+self.addEventListener("fetch", (event) => {
+  // 只处理同源请求
+  if (event.request.url.startsWith(self.location.origin)) {
+    event.respondWith(
+      caches
+        .match(event.request)
+        .then((response) => {
+          // 如果在缓存中找到,则返回缓存版本
+          if (response) {
+            return response;
+          }
+
+          // 否则,从网络获取资源
+          return fetch(event.request).then((response) => {
+            // 检查是否是有效响应
+            if (
+              !response ||
+              response.status !== 200 ||
+              response.type !== "basic"
+            ) {
+              return response;
+            }
+
+            // 克隆响应,因为响应流只能被使用一次
+            const responseToCache = response.clone();
+
+            // 将新资源添加到缓存
+            caches.open(CACHE_NAME).then((cache) => {
+              cache.put(event.request, responseToCache);
+            });
+
+            return response;
+          });
+        })
+        .catch(() => {
+          // 网络请求失败,尝试返回缓存的主页
+          if (event.request.destination === "document") {
+            return caches.match("/index.html");
+          }
+        })
+    );
+  }
+});
+
+// 后台同步 - 用于在恢复网络连接时同步数据
+self.addEventListener("sync", (event) => {
+  if (event.tag === "background-sync") {
+    console.log("执行后台同步");
+    event.waitUntil(doBackgroundSync());
+  }
+});
+
+function doBackgroundSync() {
+  // 这里可以添加数据同步逻辑
+  return Promise.resolve();
+}