Files
Bkk1234 fcdab3ac80 pwa: automatic update UX - no more hard refresh
- ui/version.json: server-side version marker, polled by pwa.js (load, 5 min,
  tab focus, network online); mismatch -> toast + auto reload once per version
- pwa.js: silent reload when tab hidden, guarded reload (sessionStorage) so a
  partial deploy cannot loop, ATUpdate.check() exposed for testing
- _shared.css: .mu-update-toast pill (bottom center, reduced-motion aware)
- shell js/css get ?v=<version> automatically (bump-version.py) so HTTP cache
  cannot serve stale files before the service worker takes control
- sw: cache fallback now ignores query string (precache still matches ?v= URLs)
- bump-version.py: writes version.json + verifies it in --check
- VERSION 2026.09.27.108
2026-11-03 00:32:41 +07:00

141 lines
6.8 KiB
Python

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""bump-version.py — เพิ่มเวอร์ชันแอป (cache busting) ให้ตรงกันทุกที่ในคำสั่งเดียว
ทำอะไร:
1) ui/sw.js const VERSION = "..." ← ตัวจริง (cache-first ใช้ค่านี้)
2) ui/index.html <meta name="app-version" ...> ← ให้ ImgURL.of() ใช้
3) ui/index.html โลโก้/ไอคอน ?v=... (static) ← รูปที่ฝังใน HTML
วิธีใช้:
python resource/tools/bump-version.py # +1 รอบ (เช่น 2026.09.27.23 → .24)
python resource/tools/bump-version.py 2026.10.01 # ตั้งค่าเอง (จะได้ 2026.10.01.1)
python resource/tools/bump-version.py --show # แค่แสดงเวอร์ชันปัจจุบัน (ไม่เขียน)
python resource/tools/bump-version.py --sync # ไม่เพิ่มเลข แค่ทำให้ทุกที่ตรงกับ sw.js
หลังอัปรูป: รันคำสั่งนี้ แล้วให้ผู้ใช้กด Ctrl+Shift+R ครั้งเดียว = เห็นรูปใหม่ทั้งหมด
"""
import argparse
import json
import re
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
UI = ROOT / "ui"
SW = UI / "sw.js"
INDEX = UI / "index.html"
VERSION_JSON = UI / "version.json"
VER_RE = re.compile(r'const VERSION = "([^"]+)";')
# src="./x.js" | href="./x.css" (ไม่แตะ URL ภายนอก/ไฟล์อื่น)
SHELL_ASSET_RE = re.compile(r'((?:src|href)=")(\./[^"?]+\.(?:js|css))(?:\?v=[^"]*)?(")')
def read_version():
m = VER_RE.search(SW.read_text(encoding="utf-8"))
if not m:
sys.exit("ไม่พบ const VERSION ใน ui/sw.js")
return m.group(1)
def next_version(cur, base=None):
"""cur = '2026.09.27.23' → '2026.09.27.24' · base='2026.10.01' → '2026.10.01.1'"""
if base:
m = re.match(r"^(\d{4}\.\d{2}\.\d{2})(?:\.(\d+))?$", base.strip())
if not m:
sys.exit(f"รูปแบบวันที่ไม่ถูกต้อง: {base} (ต้องเป็น YYYY.MM.DD)")
n = int(m.group(2) or 0) + 1
return f"{m.group(1)}.{n}"
parts = cur.split(".")
if len(parts) < 4 or not parts[-1].isdigit():
return cur + ".1"
return ".".join(parts[:-1] + [str(int(parts[-1]) + 1)])
def apply(ver, dry=False):
changed = []
# 1) sw.js
sw = SW.read_text(encoding="utf-8")
sw2 = VER_RE.sub(f'const VERSION = "{ver}";', sw, count=1)
if sw2 != sw:
if not dry:
SW.write_text(sw2, encoding="utf-8")
changed.append("ui/sw.js")
# 2) index.html — meta + โลโก้ static (?v=) + shell asset (?v=)
idx = INDEX.read_text(encoding="utf-8")
idx2 = re.sub(r'(<meta name="app-version" content=")[^"]*(">)', rf"\g<1>{ver}\g<2>", idx)
idx2 = re.sub(r'(\.image/icons/[^"?]+\.(?:png|jpg|jpeg|webp|svg))\?v=[^"&]*', rf"\g<1>?v={ver}", idx2)
# JS/CSS ของ shell (./xxx.js, ./xxx.css) → ?v= กัน HTTP cache คืนของเก่าก่อน SW ทำงาน
idx2 = SHELL_ASSET_RE.sub(rf"\g<1>\g<2>?v={ver}\g<3>", idx2)
if idx2 != idx:
if not dry:
INDEX.write_text(idx2, encoding="utf-8")
changed.append("ui/index.html")
# 3) version.json — ให้ pwa.js ตรวจเวอร์ชันใหม่ได้เอง (ทุกเครื่อง)
want = '{"version": "%s"}\n' % ver
old = VERSION_JSON.read_text(encoding="utf-8") if VERSION_JSON.exists() else ""
if old != want:
if not dry:
VERSION_JSON.write_text(want, encoding="utf-8")
changed.append("ui/version.json")
return changed
def report(ver, changed, dry=False):
n_img = len(re.findall(r"\.image/[^\"]+\?v=", INDEX.read_text(encoding="utf-8")))
print(f"เวอร์ชัน: {ver}" + (" [dry-run]" if dry else ""))
print(f" แก้ไฟล์: {', '.join(changed) if changed else 'ไม่มี (ตรงกันอยู่แล้ว)'}")
print(f" รูป static ที่เติม ?v= ใน index.html: {n_img} จุด")
print(f" รูป dynamic (routes/qrcode/stations/stops): เติมอัตโนมัติผ่าน ImgURL.of()")
def main():
ap = argparse.ArgumentParser()
ap.add_argument("base", nargs="?", help="วันที่ฐาน YYYY.MM.DD (ไม่ใส่ = เพิ่มเลขรอบเดิม)")
ap.add_argument("--show", action="store_true", help="แสดงเวอร์ชันปัจจุบัน")
ap.add_argument("--sync", action="store_true", help="ทำให้ทุกที่ตรงกับ sw.js (ไม่เพิ่มเลข)")
ap.add_argument("--check", action="store_true", help="ตรวจว่าทุกที่ตรงกันไหม (exit 1 ถ้าไม่ตรง)")
args = ap.parse_args()
cur = read_version()
if args.show:
print(f"เวอร์ชันปัจจุบัน: {cur}")
return 0
if args.check:
idx = INDEX.read_text(encoding="utf-8")
m = re.search(r'<meta name="app-version" content="([^"]*)"', idx)
meta = m.group(1) if m else None
logos = set(re.findall(r"\.image/icons/[^\"]+?\?v=([^\"&]+)", idx))
shell = set(re.findall(r'"\./[^"?]+\.(?:js|css)\?v=([^"]*)"', idx))
vjson = None
if VERSION_JSON.exists():
try:
vjson = json.loads(VERSION_JSON.read_text(encoding="utf-8")).get("version")
except Exception:
vjson = "parse-error"
ok = (meta == cur) and (logos == {cur} or not logos) and (shell == {cur} or not shell) and vjson == cur
print(f"sw.js VERSION = {cur}")
print(f"meta app-version= {meta} {'✓' if meta == cur else '✗ ไม่ตรง'}")
print(f"โลโก้ ?v= = {sorted(logos) or '-'} {'✓' if (logos == {cur} or not logos) else '✗ ไม่ตรง'}")
print(f"shell js/css ?v== {sorted(shell) or '-'} {'✓' if (shell == {cur} or not shell) else '✗ ไม่ตรง'}")
print(f"version.json = {vjson} {'✓' if vjson == cur else '✗ ไม่ตรง'}")
return 0 if ok else 1
ver = cur if args.sync else next_version(cur, args.base)
changed = apply(ver, dry=False)
report(ver, changed)
print("\nผู้ใช้ไม่ต้องกด Ctrl+Shift+R — pwa.js ตรวจ version.json เองแล้วอัปเดตให้")
return 0
if __name__ == "__main__":
sys.exit(main())