Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: sw 提示更新 #42

Merged
merged 3 commits into from
Aug 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions languages/en.yml
Original file line number Diff line number Diff line change
Expand Up @@ -47,3 +47,9 @@ busuanzi:
uv: Number of visitors

sticky: Sticky

service_worker:
title: New version found
content: The website seems to have new content, do you want to update?
confirm: Update
cancel: Cancel
6 changes: 6 additions & 0 deletions languages/ja.yml
Original file line number Diff line number Diff line change
Expand Up @@ -47,3 +47,9 @@ busuanzi:
uv: 総閲覧者数

sticky: 固定

service_worker:
title: 新しいバージョンが見つかりました
content: ウェブサイトに新しいコンテンツがあるようです。更新しますか?
confirm: 更新
cancel: キャンセル
6 changes: 6 additions & 0 deletions languages/zh-CN.yml
Original file line number Diff line number Diff line change
Expand Up @@ -47,3 +47,9 @@ busuanzi:
uv: 总访客量

sticky: 置顶

service_worker:
title: 发现新版本
content: 网站好像有新内容,是否更新(゚⊿゚)ツ?
confirm: 更新
cancel: 取消
6 changes: 6 additions & 0 deletions languages/zh-TW.yml
Original file line number Diff line number Diff line change
Expand Up @@ -47,3 +47,9 @@ busuanzi:
uv: 縂訪客量

sticky: 置頂

service_worker:
title: 發現新版本
content: 網站好像有新內容,是否更新?
confirm: 更新
cancel: 取消
4 changes: 4 additions & 0 deletions layout/_partial/after-footer.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -337,4 +337,8 @@

<% if (theme.footer.busuanzi) { %>
<%- js({src: vendorCdn(theme.vendor.js.busuanzi)[0], async: true}) %>
<% } %>

<% if (theme.service_worker.enable) { %>
<%- js('js/service_worker.js') %>
<% } %>
3 changes: 0 additions & 3 deletions layout/_partial/head.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,4 @@
}).init();
</script>
<% } %>
<% if (theme.service_worker.enable) { %>
<script src="<%- url_for('/sw.js', {relative: false}) %>"></script>
<% } %>
</head>
11 changes: 11 additions & 0 deletions layout/_partial/loader.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,14 @@
<% } %>
<div id="copy-tooltip" style="pointer-events: none; opacity: 0; transition: all 0.2s ease; position: fixed;top: 50%;left: 50%;z-index: 999;transform: translate(-50%, -50%);color: white;background: rgba(0, 0, 0, 0.5);padding: 10px 15px;border-radius: 10px;">
</div>

<% if (theme.service_worker.enable) { %>
<div class="notification-wrapper">
<h1><%= __("service_worker.title") %></h1>
<p><%= __("service_worker.content") %></p>
<div class="notification-btn">
<button id="notification-update-btn"><%= __("service_worker.confirm") %></button>
<button id="notification-close-btn"><%= __("service_worker.cancel") %></button>
</div>
</div>
<% } %>
1 change: 0 additions & 1 deletion scripts/generator/servicework.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ hexo.extend.generator.register("ServiceWorker", (locals) => {
"${url_for.call(hexo, "/css/style.css")}",
"${url_for.call(hexo, "/js/script.js")}",
];\n` + content;
content = `const swPath = "${url_for.call(hexo, "/sw.js")}";\n` + content;
return {
path: "sw.js",
data: content,
Expand Down
5 changes: 5 additions & 0 deletions scripts/helper/config.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
const { url_for } = require("hexo-util");

hexo.extend.helper.register("themeConfig", () => {
const { config } = hexo.theme;
const icon_font = config.icon_font;
Expand All @@ -9,6 +11,9 @@ hexo.extend.helper.register("themeConfig", () => {
if (clipboard_tips) {
_global.push(`window.clipboard_tips = ${JSON.stringify(clipboard_tips)};`);
}
if (config.service_worker.enable) {
_global.push(`window.swPath = '${url_for.call(hexo, "/sw.js")}';`);
}
return `
<script>${_global.join("")}</script>
`;
Expand Down
45 changes: 45 additions & 0 deletions source/css/_partial/notification.styl
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
.notification-wrapper
position: fixed
z-index: 1000
top: 20px
right: 20px
background: var(--color-header-background)
box-shadow: 0 0 10px var(--color-hover-shadow)
border-radius: 5px
padding: 10px 20px
margin-left: 20px
opacity: 0
visibility: hidden
transition: .5s
color: var(--grey-7)

&.show
opacity: 1
visibility: visible

h1
padding: 10px 0

p
padding: 10px 0

.notification-btn
display: flex
justify-content: flex-end
gap: 15px
padding: 10px 0

button
background: #ff7777
border-radius: 5px
color: #fff
padding: 5px 10px
font-family: 'Noto Serif SC', 'Noto Serif JP', -apple-system, 'PingFang SC', 'Microsoft YaHei', sans-serif
border: none
transition: .2s

&:hover
background: rgb(255, 77, 77)

&:active
background: #ff2e2e
3 changes: 3 additions & 0 deletions source/css/style.styl
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,9 @@ if sidebar
@import "_partial/search.styl"
@import "_partial/card.styl"

if hexo-config("service_worker.enable")
@import "_partial/notification.styl"

if sidebar
@import "_partial/sidebar"

Expand Down
8 changes: 6 additions & 2 deletions source/js/script.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,11 @@
});
// Simple Selector
window._$ = (selector) => {
if (selector.startsWith("#") && !selector.includes(' ') && !selector.includes('.')) {
if (
selector.startsWith("#") &&
!selector.includes(" ") &&
!selector.includes(".")
) {
return document.getElementById(selector.slice(1));
}
return document.querySelector(selector);
Expand Down Expand Up @@ -115,7 +119,7 @@
.getElementById("header-nav")
.classList.remove("header-nav-hidden");
} else {
document.getElementById("header-nav").classList.add("header-nav-hidden");
_$("#header-nav").classList.add("header-nav-hidden");
}
});
})();
53 changes: 53 additions & 0 deletions source/js/service_worker.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
// service worker
if ("serviceWorker" in navigator && window.swPath) {
_$("#notification-update-btn").onclick = () => {
try {
navigator.serviceWorker.getRegistration().then((reg) => {
reg.waiting.postMessage("skipWaiting");
});
} catch (e) {
window.location.reload();
}
};

_$("#notification-close-btn").onclick = () => {
_$(".notification-wrapper").classList.remove("show");
}

function emitUpdate() {
_$(".notification-wrapper").classList.add("show");
}

navigator.serviceWorker
.register(swPath)
.then((registration) => {
console.log("Service Worker 注册成功: ", registration);
if (registration.waiting) {
emitUpdate();
return;
}
registration.onupdatefound = () => {
console.log("Service Worker 更新中...");
const installingWorker = registration.installing;
installingWorker.onstatechange = () => {
if (installingWorker.state === "installed") {
if (navigator.serviceWorker.controller) {
emitUpdate();
}
}
};
};
})
.catch((error) => {
console.log("Service Worker 注册失败: ", error);
});

let refreshing = false;
navigator.serviceWorker.addEventListener("controllerchange", () => {
if (refreshing) {
return;
}
refreshing = true;
window.location.reload();
});
}
20 changes: 10 additions & 10 deletions source/js/sw.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,15 @@ async function cacheRequest(request, options) {
try {
const responseToCache = await fetch(request);
const cache = await caches.open(VERSION);
if (!/^https?:$/i.test(new URL(request.url).protocol))
return responseToCache;
cache.put(request, responseToCache.clone());
return responseToCache;
} catch (e) {
const responseToCache = await fetch(request, options);
const cache = await caches.open(VERSION);
if (!/^https?:$/i.test(new URL(request.url).protocol))
return responseToCache;
cache.put(request, responseToCache.clone());
return responseToCache;
}
Expand Down Expand Up @@ -72,13 +76,9 @@ self.addEventListener("activate", (event) => {
console.log(`Service Worker ${VERSION} activated.`);
});

if ("serviceWorker" in navigator) {
navigator.serviceWorker
.register(swPath)
.then((registration) => {
console.log("Service Worker 注册成功: ", registration);
})
.catch((error) => {
console.log("Service Worker 注册失败: ", error);
});
}
self.addEventListener("message", (event) => {
console.log("Service Worker: message received");
if (event.data === "skipWaiting") {
self.skipWaiting();
}
});
Loading