Skip to content

Commit

Permalink
Add PWA support & new icon
Browse files Browse the repository at this point in the history
  • Loading branch information
Super12138 committed Aug 29, 2024
1 parent 2c99421 commit 39b357e
Show file tree
Hide file tree
Showing 8 changed files with 174 additions and 3 deletions.
15 changes: 13 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,24 @@
"devDependencies": {
"@mdui/icons": "^1.0.2",
"@types/node": "^22.4.1",
"@vite-pwa/assets-generator": "^0.2.4",
"typedoc": "^0.26.6",
"typedoc-plugin-markdown": "^4.2.5",
"typescript": "^5.5.4",
"vite": "^5.4.2",
"vite-plugin-html": "^3.2.2"
"vite-plugin-html": "^3.2.2",
"vite-plugin-pwa": "^0.20.1",
"workbox-core": "^7.1.0",
"workbox-precaching": "^7.1.0",
"workbox-routing": "^7.1.0",
"workbox-strategies": "^7.1.0",
"workbox-window": "^7.1.0"
},
"dependencies": {
"mdui": "^2.1.2"
},
"overrides": {
"sharp": "0.32.6",
"sharp-ico": "0.1.5"
}
}
}
Binary file added public/icon-512.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
12 changes: 12 additions & 0 deletions pwa-assets.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import {
defineConfig,
minimal2023Preset as preset,
} from '@vite-pwa/assets-generator/config'

export default defineConfig({
headLinkOptions: {
preset: '2023',
},
preset,
images: ['public/icon-512.png'],
})
7 changes: 6 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import '@mdui/icons/brush--outlined.js';
import '@mdui/icons/list--outlined.js';
import '@mdui/icons/settings--outlined.js';
import { PageItem } from './interfaces';
import { initPWA } from './pwa/pwa';
import { hide, show } from './utils/element';
import { getFile } from './utils/network';
import { showDisclaimerDialog } from './utils/notices';
Expand Down Expand Up @@ -126,10 +127,14 @@ window.addEventListener('DOMContentLoaded', async () => {
// 启动观察
observer.observe(container, { childList: true, subtree: true });

// 将不同页面的内容上屏
container.innerHTML = pageData;
// 展示使用提示对话框
showDisclaimerDialog();

// 显示页面内容
document.body.classList.add('ready');
// 初始化 PWA
initPWA();
});

/**
Expand Down
73 changes: 73 additions & 0 deletions src/pwa/pwa.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import { snackbar } from "mdui/functions/snackbar.js";
import { registerSW } from 'virtual:pwa-register';

export function initPWA() {
let refreshSW: (reloadPage?: boolean) => Promise<void> | undefined

let swActivated = false
// 每小时检查一次更新
const period = 60 * 60 * 1000

window.addEventListener('load', () => {
refreshSW = registerSW({
immediate: true,
onOfflineReady() {
snackbar({
message: "问心(不包含试题部分)已准备好在离线环境下运行"
})
},
onNeedRefresh() {
snackbar({
message: "问心有新版本",
action: "立即更新",
onActionClick: () => {
refreshSW?.(true)
true
}
});
},
onRegisteredSW(swUrl, r) {
if (period <= 0) return
if (r?.active?.state === 'activated') {
swActivated = true
registerPeriodicSync(period, swUrl, r)
}
else if (r?.installing) {
r.installing.addEventListener('statechange', (e) => {
const sw = e.target as ServiceWorker
swActivated = sw.state === 'activated'
if (swActivated)
registerPeriodicSync(period, swUrl, r)
})
}
},
})
})
}

/**
* 定时进行同步检查,可根据需要修改时间间隔
* @param period 检查时间间隔
* @param swUrl Service Worker URL
* @param r ServiceWorkerRegistration
* @returns
*/
function registerPeriodicSync(period: number, swUrl: string, r: ServiceWorkerRegistration) {
if (period <= 0) return

setInterval(async () => {
if ('onLine' in navigator && !navigator.onLine)
return

const resp = await fetch(swUrl, {
cache: 'no-store',
headers: {
'cache': 'no-store',
'cache-control': 'no-cache',
},
})

if (resp?.status === 200)
await r.update()
}, period)
}
27 changes: 27 additions & 0 deletions src/pwa/sw.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
/// <reference lib="webworker" />
import { cleanupOutdatedCaches, createHandlerBoundToURL, precacheAndRoute } from 'workbox-precaching'
import { NavigationRoute, registerRoute } from 'workbox-routing'

declare let self: ServiceWorkerGlobalScope

self.addEventListener('message', (event) => {
if (event.data && event.data.type === 'SKIP_WAITING')
self.skipWaiting()
})

// self.__WB_MANIFEST is the default injection point
precacheAndRoute(self.__WB_MANIFEST)

// clean old assets
cleanupOutdatedCaches()

let allowlist: RegExp[] | undefined
// in dev mode, we disable precaching to avoid caching issues
if (import.meta.env.DEV)
allowlist = [/^\/$/]

// to allow work offline
registerRoute(new NavigationRoute(
createHandlerBoundToURL('index.html'),
{ allowlist },
))
1 change: 1 addition & 0 deletions src/vite-env.d.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
/// <reference types="vite/client" />
/// <reference types="vite-plugin-pwa/vanillajs" />
42 changes: 42 additions & 0 deletions vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import path from 'path';
import { promisify } from 'util';
import { defineConfig } from 'vite';
import { createHtmlPlugin } from 'vite-plugin-html';
import { VitePWA } from 'vite-plugin-pwa';
import packageJson from './package.json';

const execPromise = promisify(exec);
Expand Down Expand Up @@ -38,6 +39,47 @@ export default defineConfig(async ({ command, mode, isSsrBuild, isPreview }) =>
createHtmlPlugin({
minify: true,
}),
VitePWA({
strategies: 'injectManifest',
srcDir: 'src/pwa',
filename: 'sw.ts',
registerType: 'prompt',
injectRegister: false,

pwaAssets: {
disabled: false,
config: true,
},

manifest: {
name: '问心',
short_name: '问心',
start_url: '/Ask-Yourself/',
description: '心理量表集合',
lang: "zh",
theme_color: '#ffffff',
orientation: "any",
dir: "ltr",
shortcuts: [
{
"name": "问心",
"url": "index.html",
"description": "问心"
}
],
},

injectManifest: {
globPatterns: ['**/*.{js,css,html,svg,png,ico}'],
},

devOptions: {
enabled: false,
navigateFallback: 'index.html',
suppressWarnings: true,
type: 'module',
},
})
],
};
if (command === 'serve') {
Expand Down

0 comments on commit 39b357e

Please sign in to comment.