m1m02530125 commited on
Commit
404ee14
·
1 Parent(s): 9865854

PWAをiOS/Android向けに完全対応(Service Worker全体スコープ化、スプラッシュ画面、インストール導線)

Browse files

- Service Workerを/sw.jsとしてルートスコープで配信し、オフライン時はキャッシュ
またはオフラインページにフォールバックするよう強化
- manifest.jsonにid/scope/lang/shortcuts/maskableアイコンを追加
- iOS向けスプラッシュスクリーン(apple-touch-startup-image)と
mobile-web-app-capableメタタグを追加
- ホーム画面追加を案内するインストールバナーを追加
(Android: beforeinstallprompt, iOS: 共有メニュー案内)
- アイコン/スプラッシュ生成スクリプト(scripts/generate_pwa_assets.py)を追加

routes/pwa_routes.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Blueprint, render_template, make_response
2
+
3
+ bp = Blueprint("pwa", __name__)
4
+
5
+
6
+ @bp.get("/sw.js")
7
+ def service_worker():
8
+ """Service Workerをルートパスで配信し、scopeをアプリ全体(/)にする"""
9
+ resp = make_response(render_template("pwa/sw.js"))
10
+ resp.headers["Content-Type"] = "application/javascript; charset=utf-8"
11
+ resp.headers["Cache-Control"] = "no-cache"
12
+ resp.headers["Service-Worker-Allowed"] = "/"
13
+ return resp
14
+
15
+
16
+ @bp.get("/offline")
17
+ def offline():
18
+ """オフライン時にService Workerが表示するフォールバックページ"""
19
+ return render_template("pwa/offline.html")
scripts/generate_pwa_assets.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """PWA用アセット生成スクリプト(一回限りの実行用)。
2
+
3
+ static/icons/icon-512.png(SKY DINING UOMANロゴ)を元に、
4
+ - Android用maskableアイコン(セーフゾーン80%でパディング)
5
+ - iOS用スプラッシュスクリーン(apple-touch-startup-image)
6
+ - スプラッシュスクリーンの<link>タグを含むテンプレート
7
+
8
+ を生成する。ロゴ画像を変更した場合に再実行する。
9
+
10
+ 実行方法:
11
+ python scripts/seed_test_data.py のように、リポジトリルートから:
12
+ python scripts/generate_pwa_assets.py
13
+ """
14
+ from __future__ import annotations
15
+
16
+ from pathlib import Path
17
+ from PIL import Image
18
+
19
+ ROOT = Path(__file__).resolve().parent.parent
20
+ ICONS_DIR = ROOT / "static" / "icons"
21
+ SPLASH_DIR = ICONS_DIR / "splash"
22
+ TEMPLATE_OUT = ROOT / "templates" / "pwa" / "_splash_links.html"
23
+
24
+ BG_COLOR = (255, 255, 255, 255) # manifest.json の background_color と一致
25
+
26
+ # iOSスプラッシュスクリーン対象デバイス
27
+ # (出力ファイル幅, 出力ファイル高さ, device-width, device-height, dpr, orientation)
28
+ SPLASH_DEVICES = [
29
+ (750, 1334, 375, 667, 2, "portrait", "iPhone SE/7/8"),
30
+ (1125, 2436, 375, 812, 3, "portrait", "iPhone X/11 Pro/12-13 mini"),
31
+ (1170, 2532, 390, 844, 3, "portrait", "iPhone 12/13/14"),
32
+ (1179, 2556, 393, 852, 3, "portrait", "iPhone 14 Pro/15/16"),
33
+ (1290, 2796, 430, 932, 3, "portrait", "iPhone 14-16 Plus/Pro Max"),
34
+ (1668, 2388, 834, 1194, 2, "portrait", "iPad Air/Pro 11インチ(縦)"),
35
+ (2388, 1668, 834, 1194, 2, "landscape", "iPad Air/Pro 11インチ(横)"),
36
+ ]
37
+
38
+
39
+ def make_maskable(src: Image.Image, size: int, out: Path) -> None:
40
+ """セーフゾーン80%でロゴを中央配置したmaskableアイコンを生成"""
41
+ canvas = Image.new("RGBA", (size, size), BG_COLOR)
42
+ inner = round(size * 0.8)
43
+ logo = src.resize((inner, inner), Image.LANCZOS)
44
+ offset = (size - inner) // 2
45
+ canvas.paste(logo, (offset, offset), logo)
46
+ canvas.save(out)
47
+ print(f"generated {out.relative_to(ROOT)}")
48
+
49
+
50
+ def make_splash(src: Image.Image, width: int, height: int, out: Path) -> None:
51
+ """背景色のキャンバス中央にロゴを配置したスプラッシュ画像を生成"""
52
+ canvas = Image.new("RGBA", (width, height), BG_COLOR)
53
+ logo_size = round(min(width, height) * 0.35)
54
+ logo = src.resize((logo_size, logo_size), Image.LANCZOS)
55
+ pos = ((width - logo_size) // 2, (height - logo_size) // 2)
56
+ canvas.paste(logo, pos, logo)
57
+ canvas.convert("RGB").save(out)
58
+ print(f"generated {out.relative_to(ROOT)}")
59
+
60
+
61
+ def main() -> None:
62
+ src = Image.open(ICONS_DIR / "icon-512.png").convert("RGBA")
63
+
64
+ make_maskable(src, 512, ICONS_DIR / "icon-512-maskable.png")
65
+ make_maskable(src, 192, ICONS_DIR / "icon-192-maskable.png")
66
+
67
+ SPLASH_DIR.mkdir(parents=True, exist_ok=True)
68
+ links = []
69
+ for width, height, dw, dh, dpr, orientation, label in SPLASH_DEVICES:
70
+ filename = f"apple-splash-{width}-{height}.png"
71
+ make_splash(src, width, height, SPLASH_DIR / filename)
72
+ media = (
73
+ f"(device-width: {dw}px) and (device-height: {dh}px) "
74
+ f"and (-webkit-device-pixel-ratio: {dpr}) and (orientation: {orientation})"
75
+ )
76
+ links.append(
77
+ f' <!-- {label} -->\n'
78
+ f' <link rel="apple-touch-startup-image" media="{media}" '
79
+ f'href="/static/icons/splash/{filename}">'
80
+ )
81
+
82
+ TEMPLATE_OUT.parent.mkdir(parents=True, exist_ok=True)
83
+ TEMPLATE_OUT.write_text(
84
+ "<!-- iOSスプラッシュスクリーン(scripts/generate_pwa_assets.py で自動生成) -->\n"
85
+ + "\n".join(links) + "\n"
86
+ )
87
+ print(f"generated {TEMPLATE_OUT.relative_to(ROOT)}")
88
+
89
+
90
+ if __name__ == "__main__":
91
+ main()
static/icons/icon-192-maskable.png ADDED
static/icons/icon-512-maskable.png ADDED
static/icons/splash/apple-splash-1125-2436.png ADDED
static/icons/splash/apple-splash-1170-2532.png ADDED
static/icons/splash/apple-splash-1179-2556.png ADDED
static/icons/splash/apple-splash-1290-2796.png ADDED
static/icons/splash/apple-splash-1668-2388.png ADDED
static/icons/splash/apple-splash-2388-1668.png ADDED
static/icons/splash/apple-splash-750-1334.png ADDED
static/manifest.json CHANGED
@@ -1,14 +1,38 @@
1
  {
 
2
  "name": "SDU-Shift",
3
  "short_name": "SDU-Shift",
4
  "description": "スタッフシフト管理",
5
  "start_url": "/",
 
6
  "display": "standalone",
7
  "background_color": "#ffffff",
8
  "theme_color": "#1e293b",
9
  "orientation": "portrait",
 
 
 
10
  "icons": [
11
- { "src": "/static/icons/icon-192.png", "sizes": "192x192", "type": "image/png" },
12
- { "src": "/static/icons/icon-512.png", "sizes": "512x512", "type": "image/png", "purpose": "any maskable" }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
  ]
14
  }
 
1
  {
2
+ "id": "/",
3
  "name": "SDU-Shift",
4
  "short_name": "SDU-Shift",
5
  "description": "スタッフシフト管理",
6
  "start_url": "/",
7
+ "scope": "/",
8
  "display": "standalone",
9
  "background_color": "#ffffff",
10
  "theme_color": "#1e293b",
11
  "orientation": "portrait",
12
+ "lang": "ja",
13
+ "dir": "ltr",
14
+ "categories": ["business", "productivity"],
15
  "icons": [
16
+ { "src": "/static/icons/icon-192.png", "sizes": "192x192", "type": "image/png", "purpose": "any" },
17
+ { "src": "/static/icons/icon-512.png", "sizes": "512x512", "type": "image/png", "purpose": "any" },
18
+ { "src": "/static/icons/icon-192-maskable.png", "sizes": "192x192", "type": "image/png", "purpose": "maskable" },
19
+ { "src": "/static/icons/icon-512-maskable.png", "sizes": "512x512", "type": "image/png", "purpose": "maskable" }
20
+ ],
21
+ "shortcuts": [
22
+ {
23
+ "name": "希望シフト",
24
+ "url": "/shifts",
25
+ "icons": [{ "src": "/static/icons/icon-192.png", "sizes": "192x192", "type": "image/png" }]
26
+ },
27
+ {
28
+ "name": "シフト表",
29
+ "url": "/schedule",
30
+ "icons": [{ "src": "/static/icons/icon-192.png", "sizes": "192x192", "type": "image/png" }]
31
+ },
32
+ {
33
+ "name": "自動生成",
34
+ "url": "/generate",
35
+ "icons": [{ "src": "/static/icons/icon-192.png", "sizes": "192x192", "type": "image/png" }]
36
+ }
37
  ]
38
  }
static/sw.js DELETED
@@ -1,25 +0,0 @@
1
- // Service Worker: オフラインキャッシュ(シェル)
2
- const CACHE = "sdu-shift-v1";
3
- const SHELL = ["/", "/static/manifest.json"];
4
-
5
- self.addEventListener("install", e => {
6
- e.waitUntil(caches.open(CACHE).then(c => c.addAll(SHELL)));
7
- self.skipWaiting();
8
- });
9
-
10
- self.addEventListener("activate", e => {
11
- e.waitUntil(
12
- caches.keys().then(keys =>
13
- Promise.all(keys.filter(k => k !== CACHE).map(k => caches.delete(k)))
14
- )
15
- );
16
- self.clients.claim();
17
- });
18
-
19
- self.addEventListener("fetch", e => {
20
- // ネットワーク優先、失敗時にキャッシュ
21
- if (e.request.method !== "GET") return;
22
- e.respondWith(
23
- fetch(e.request).catch(() => caches.match(e.request))
24
- );
25
- });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
templates/base.html CHANGED
@@ -5,6 +5,7 @@
5
  <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
6
  <meta name="theme-color" content="#0f172a">
7
  <meta name="apple-mobile-web-app-capable" content="yes">
 
8
  <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
9
  <meta name="apple-mobile-web-app-title" content="SDU-Shift">
10
  <meta name="csrf-token" content="{{ csrf_token() }}">
@@ -13,6 +14,7 @@
13
  <link rel="icon" type="image/png" sizes="32x32" href="/static/icons/favicon-32.png">
14
  <link rel="icon" type="image/png" sizes="16x16" href="/static/icons/favicon-16.png">
15
  <link rel="apple-touch-icon" href="/static/icons/apple-touch-icon.png">
 
16
  <!-- Noto Sans JP (ノンブロッキング読み込み) -->
17
  <link rel="preconnect" href="https://fonts.googleapis.com">
18
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
@@ -263,6 +265,40 @@
263
  background: var(--accent);
264
  }
265
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
266
  /* ── ハンバーガードロワー ─────────────────────────── */
267
  .drawer-backdrop {
268
  display: none; position: fixed; inset: 0;
@@ -397,6 +433,19 @@
397
  {% endif %}
398
  </nav>
399
 
 
 
 
 
 
 
 
 
 
 
 
 
 
400
  <!-- Mobile Bottom Nav -->
401
  {% set _in_drawer = request.endpoint and (
402
  request.endpoint.startswith('customers') or
@@ -635,8 +684,64 @@
635
  })();
636
 
637
  if ('serviceWorker' in navigator) {
638
- navigator.serviceWorker.register('/static/sw.js').catch(() => {});
639
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
640
  </script>
641
  {% block scripts %}{% endblock %}
642
  </body>
 
5
  <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
6
  <meta name="theme-color" content="#0f172a">
7
  <meta name="apple-mobile-web-app-capable" content="yes">
8
+ <meta name="mobile-web-app-capable" content="yes">
9
  <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
10
  <meta name="apple-mobile-web-app-title" content="SDU-Shift">
11
  <meta name="csrf-token" content="{{ csrf_token() }}">
 
14
  <link rel="icon" type="image/png" sizes="32x32" href="/static/icons/favicon-32.png">
15
  <link rel="icon" type="image/png" sizes="16x16" href="/static/icons/favicon-16.png">
16
  <link rel="apple-touch-icon" href="/static/icons/apple-touch-icon.png">
17
+ {% include "pwa/_splash_links.html" %}
18
  <!-- Noto Sans JP (ノンブロッキング読み込み) -->
19
  <link rel="preconnect" href="https://fonts.googleapis.com">
20
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
 
265
  background: var(--accent);
266
  }
267
 
268
+ /* ── ホーム画面に追加バナー ───────────────────────── */
269
+ .pwa-install-banner {
270
+ display: none;
271
+ position: fixed; left: .75rem; right: .75rem;
272
+ bottom: calc(var(--nav-h) + var(--safe-bottom) + .75rem);
273
+ z-index: 1000;
274
+ align-items: center; gap: .75rem;
275
+ background: var(--bg-card);
276
+ backdrop-filter: blur(20px);
277
+ -webkit-backdrop-filter: blur(20px);
278
+ border: 1.5px solid var(--border);
279
+ border-radius: var(--radius-lg);
280
+ box-shadow: var(--shadow-lg);
281
+ padding: .75rem;
282
+ color: var(--text);
283
+ }
284
+ .pwa-install-banner.show { display: flex; }
285
+ .pwa-install-banner img { width: 40px; height: 40px; border-radius: 10px; flex-shrink: 0; }
286
+ .pwa-install-text { flex: 1; min-width: 0; display: flex; flex-direction: column; }
287
+ .pwa-install-text strong { font-size: .85rem; }
288
+ .pwa-install-text span { font-size: .75rem; color: var(--text-muted); }
289
+ .pwa-install-action {
290
+ background: var(--primary); color: #fff; border: none; border-radius: var(--radius-md);
291
+ padding: .4rem .9rem; font-size: .8rem; font-weight: 600; white-space: nowrap;
292
+ font-family: inherit;
293
+ }
294
+ .pwa-install-close {
295
+ background: none; border: none; color: var(--text-muted); font-size: 1.1rem;
296
+ padding: .25rem; line-height: 1; flex-shrink: 0; cursor: pointer;
297
+ }
298
+ @media (min-width: 768px) {
299
+ .pwa-install-banner { left: auto; right: 1.5rem; bottom: 1.5rem; max-width: 360px; }
300
+ }
301
+
302
  /* ── ハンバーガードロワー ─────────────────────────── */
303
  .drawer-backdrop {
304
  display: none; position: fixed; inset: 0;
 
433
  {% endif %}
434
  </nav>
435
 
436
+ <!-- ホーム画面に追加バナー -->
437
+ <div class="pwa-install-banner" id="pwa-install-banner">
438
+ <img src="/static/icons/icon-192.png" alt="">
439
+ <div class="pwa-install-text">
440
+ <strong>ホーム画面に追加</strong>
441
+ <span id="pwa-install-desc">アプリのように使えます</span>
442
+ </div>
443
+ <button type="button" class="pwa-install-action d-none" id="pwa-install-action">追加</button>
444
+ <button type="button" class="pwa-install-close" id="pwa-install-close" aria-label="閉じる">
445
+ <i class="bi bi-x-lg"></i>
446
+ </button>
447
+ </div>
448
+
449
  <!-- Mobile Bottom Nav -->
450
  {% set _in_drawer = request.endpoint and (
451
  request.endpoint.startswith('customers') or
 
684
  })();
685
 
686
  if ('serviceWorker' in navigator) {
687
+ navigator.serviceWorker.register('/sw.js').catch(() => {});
688
  }
689
+
690
+ // ── ホーム画面に追加バナー ──────────────────────────
691
+ (() => {
692
+ const KEY = 'pwaInstallDismissedUntil';
693
+ const banner = document.getElementById('pwa-install-banner');
694
+ const desc = document.getElementById('pwa-install-desc');
695
+ const actionBtn = document.getElementById('pwa-install-action');
696
+ const closeBtn = document.getElementById('pwa-install-close');
697
+ if (!banner) return;
698
+
699
+ // 既にホーム画面から起動している場合は表示しない
700
+ const isStandalone = window.matchMedia('(display-mode: standalone)').matches
701
+ || window.navigator.standalone === true;
702
+ if (isStandalone) return;
703
+
704
+ // 閉じてから14日以内は再表示しない
705
+ const dismissedUntil = Number(localStorage.getItem(KEY) || 0);
706
+ if (Date.now() < dismissedUntil) return;
707
+
708
+ const DISMISS_MS = 14 * 24 * 60 * 60 * 1000;
709
+ const show = () => banner.classList.add('show');
710
+ const hide = () => banner.classList.remove('show');
711
+
712
+ const isIOS = /iphone|ipad|ipod/i.test(navigator.userAgent);
713
+ let deferredPrompt = null;
714
+
715
+ if (isIOS) {
716
+ // iOS Safariはbeforeinstallpromptに対応していないため案内文のみ表示
717
+ desc.textContent = '共有ボタン →「ホーム画面に��加」';
718
+ show();
719
+ } else {
720
+ window.addEventListener('beforeinstallprompt', e => {
721
+ e.preventDefault();
722
+ deferredPrompt = e;
723
+ actionBtn.classList.remove('d-none');
724
+ show();
725
+ });
726
+ }
727
+
728
+ actionBtn.addEventListener('click', async () => {
729
+ if (!deferredPrompt) return;
730
+ hide();
731
+ await deferredPrompt.prompt();
732
+ deferredPrompt = null;
733
+ });
734
+
735
+ closeBtn.addEventListener('click', () => {
736
+ hide();
737
+ localStorage.setItem(KEY, String(Date.now() + DISMISS_MS));
738
+ });
739
+
740
+ window.addEventListener('appinstalled', () => {
741
+ hide();
742
+ localStorage.setItem(KEY, String(Date.now() + DISMISS_MS));
743
+ });
744
+ })();
745
  </script>
746
  {% block scripts %}{% endblock %}
747
  </body>
templates/pwa/_splash_links.html ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!-- iOSスプラッシュスクリーン(scripts/generate_pwa_assets.py で自動生成) -->
2
+ <!-- iPhone SE/7/8 -->
3
+ <link rel="apple-touch-startup-image" media="(device-width: 375px) and (device-height: 667px) and (-webkit-device-pixel-ratio: 2) and (orientation: portrait)" href="/static/icons/splash/apple-splash-750-1334.png">
4
+ <!-- iPhone X/11 Pro/12-13 mini -->
5
+ <link rel="apple-touch-startup-image" media="(device-width: 375px) and (device-height: 812px) and (-webkit-device-pixel-ratio: 3) and (orientation: portrait)" href="/static/icons/splash/apple-splash-1125-2436.png">
6
+ <!-- iPhone 12/13/14 -->
7
+ <link rel="apple-touch-startup-image" media="(device-width: 390px) and (device-height: 844px) and (-webkit-device-pixel-ratio: 3) and (orientation: portrait)" href="/static/icons/splash/apple-splash-1170-2532.png">
8
+ <!-- iPhone 14 Pro/15/16 -->
9
+ <link rel="apple-touch-startup-image" media="(device-width: 393px) and (device-height: 852px) and (-webkit-device-pixel-ratio: 3) and (orientation: portrait)" href="/static/icons/splash/apple-splash-1179-2556.png">
10
+ <!-- iPhone 14-16 Plus/Pro Max -->
11
+ <link rel="apple-touch-startup-image" media="(device-width: 430px) and (device-height: 932px) and (-webkit-device-pixel-ratio: 3) and (orientation: portrait)" href="/static/icons/splash/apple-splash-1290-2796.png">
12
+ <!-- iPad Air/Pro 11インチ(縦) -->
13
+ <link rel="apple-touch-startup-image" media="(device-width: 834px) and (device-height: 1194px) and (-webkit-device-pixel-ratio: 2) and (orientation: portrait)" href="/static/icons/splash/apple-splash-1668-2388.png">
14
+ <!-- iPad Air/Pro 11インチ(横) -->
15
+ <link rel="apple-touch-startup-image" media="(device-width: 834px) and (device-height: 1194px) and (-webkit-device-pixel-ratio: 2) and (orientation: landscape)" href="/static/icons/splash/apple-splash-2388-1668.png">
templates/pwa/offline.html ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <html lang="ja">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
6
+ <meta name="theme-color" content="#0f172a">
7
+ <title>オフライン - SDU-Shift</title>
8
+ <style>
9
+ html, body {
10
+ margin: 0; height: 100%;
11
+ background: linear-gradient(165deg, #020617 0%, #0f172a 45%, #1e293b 100%);
12
+ color: #f8fafc;
13
+ font-family: system-ui, -apple-system, "Noto Sans JP", sans-serif;
14
+ }
15
+ .wrap {
16
+ min-height: 100%;
17
+ display: flex; flex-direction: column; align-items: center; justify-content: center;
18
+ text-align: center; padding: 2rem;
19
+ padding-top: calc(2rem + env(safe-area-inset-top, 0px));
20
+ padding-bottom: calc(2rem + env(safe-area-inset-bottom, 0px));
21
+ }
22
+ img { width: 96px; height: 96px; border-radius: 20px; margin-bottom: 1.5rem; }
23
+ h1 { font-size: 1.25rem; margin: 0 0 .5rem; }
24
+ p { color: #94a3b8; margin: 0 0 1.5rem; line-height: 1.6; }
25
+ button {
26
+ background: #0ea5e9; color: #fff; border: none; border-radius: 10px;
27
+ padding: .7rem 1.5rem; font-size: 1rem; cursor: pointer;
28
+ }
29
+ button:active { background: #0284c7; }
30
+ </style>
31
+ </head>
32
+ <body>
33
+ <div class="wrap">
34
+ <img src="/static/icons/icon-192.png" alt="SDU-Shift">
35
+ <h1>オフラインです</h1>
36
+ <p>インターネット接続を確認してから<br>再度お試しください。</p>
37
+ <button onclick="location.reload()">再読み込み</button>
38
+ </div>
39
+ </body>
40
+ </html>
templates/pwa/sw.js ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Service Worker: アプリシェルのオフラインキャッシュ
2
+ // キャッシュ名にgitコミットハッシュ(app_version)を含めることで、
3
+ // デプロイごとに古いキャッシュが自動的に破棄される
4
+ const CACHE = "sdu-shift-{{ app_version }}";
5
+ const SHELL = [
6
+ "/",
7
+ "/offline",
8
+ "/static/manifest.json",
9
+ "/static/icons/icon-192.png",
10
+ "/static/icons/icon-512.png",
11
+ "/static/icons/apple-touch-icon.png",
12
+ ];
13
+
14
+ self.addEventListener("install", e => {
15
+ e.waitUntil(
16
+ caches.open(CACHE).then(cache =>
17
+ Promise.all(SHELL.map(url => cache.add(url).catch(() => {})))
18
+ )
19
+ );
20
+ self.skipWaiting();
21
+ });
22
+
23
+ self.addEventListener("activate", e => {
24
+ e.waitUntil(
25
+ caches.keys().then(keys =>
26
+ Promise.all(keys.filter(k => k !== CACHE).map(k => caches.delete(k)))
27
+ )
28
+ );
29
+ self.clients.claim();
30
+ });
31
+
32
+ // ページ遷移: ネットワーク優先、失敗時はキャッシュ→オフラインページ
33
+ async function handleNavigate(request) {
34
+ try {
35
+ const res = await fetch(request);
36
+ const cache = await caches.open(CACHE);
37
+ cache.put(request, res.clone());
38
+ return res;
39
+ } catch {
40
+ return (await caches.match(request)) || (await caches.match("/offline"));
41
+ }
42
+ }
43
+
44
+ // 静的ファイル: キャッシュ優先、無ければネットワークから取得してキャッシュに保存
45
+ async function handleStatic(request) {
46
+ const cached = await caches.match(request);
47
+ if (cached) return cached;
48
+ try {
49
+ const res = await fetch(request);
50
+ const cache = await caches.open(CACHE);
51
+ cache.put(request, res.clone());
52
+ return res;
53
+ } catch {
54
+ return cached;
55
+ }
56
+ }
57
+
58
+ // その他のGET: ネットワーク優先、失敗時はキャッシュ
59
+ async function handleOther(request) {
60
+ try {
61
+ return await fetch(request);
62
+ } catch {
63
+ return caches.match(request);
64
+ }
65
+ }
66
+
67
+ self.addEventListener("fetch", e => {
68
+ if (e.request.method !== "GET") return;
69
+ const url = new URL(e.request.url);
70
+ if (e.request.mode === "navigate") {
71
+ e.respondWith(handleNavigate(e.request));
72
+ } else if (url.pathname.startsWith("/static/")) {
73
+ e.respondWith(handleStatic(e.request));
74
+ } else {
75
+ e.respondWith(handleOther(e.request));
76
+ }
77
+ });
web_app.py CHANGED
@@ -94,7 +94,7 @@ def create_app():
94
  def require_login():
95
  if not APP_PASSWORD:
96
  return # パスワード未設定なら全開放
97
- exempt = {"auth.login", "auth.login_post", "static"}
98
  if request.endpoint in exempt:
99
  return
100
  if not session.get("authenticated") or session.get("sv") != SESSION_VERSION:
@@ -123,6 +123,7 @@ def create_app():
123
  from routes.settings_routes import bp as settings_bp
124
  from routes.export_routes import bp as export_bp
125
  from routes.help_routes import bp as help_bp
 
126
 
127
  app.register_blueprint(emp_bp)
128
  app.register_blueprint(shifts_bp)
@@ -132,6 +133,7 @@ def create_app():
132
  app.register_blueprint(settings_bp)
133
  app.register_blueprint(export_bp)
134
  app.register_blueprint(help_bp)
 
135
 
136
  @app.teardown_appcontext
137
  def close_db(error):
 
94
  def require_login():
95
  if not APP_PASSWORD:
96
  return # パスワード未設定なら全開放
97
+ exempt = {"auth.login", "auth.login_post", "static", "pwa.service_worker", "pwa.offline"}
98
  if request.endpoint in exempt:
99
  return
100
  if not session.get("authenticated") or session.get("sv") != SESSION_VERSION:
 
123
  from routes.settings_routes import bp as settings_bp
124
  from routes.export_routes import bp as export_bp
125
  from routes.help_routes import bp as help_bp
126
+ from routes.pwa_routes import bp as pwa_bp
127
 
128
  app.register_blueprint(emp_bp)
129
  app.register_blueprint(shifts_bp)
 
133
  app.register_blueprint(settings_bp)
134
  app.register_blueprint(export_bp)
135
  app.register_blueprint(help_bp)
136
+ app.register_blueprint(pwa_bp)
137
 
138
  @app.teardown_appcontext
139
  def close_db(error):