/** * ทะเบียน "หน้านี้มีการแก้ค้าง" ระดับหน้า — UnsavedChangesGuard ลงทะเบียนเมื่อ dirty * ตัวที่จะ reload หน้าเอง (service worker อัปเดต) ถามที่นี่ก่อน ไม่ reload ทับสิ่งที่ผู้ใช้กรอกค้าง * ไม่พึ่ง React/next — ใช้ได้จากทุก entry */ let count = 0; /** ลงทะเบียนว่ามีการแก้ค้าง — คืนฟังก์ชันถอน (เรียกซ้ำได้ ไม่ลบเกิน) */ export function registerUnsavedChanges(): () => void { count += 1; let done = false; return () => { if (done) return; done = true; count = Math.max(0, count - 1); }; } export function hasRegisteredUnsavedChanges(): boolean { return count > 0; } /** ช่องกรอกแบบไม่คุมค่า (form ธรรมดา / server action) ที่ค่าต่างจากค่าเริ่มต้น */ export function hasEditedFields(doc: Document): boolean { for (const el of doc.querySelectorAll( "input, textarea", )) { if (el instanceof HTMLInputElement) { if (el.type === "checkbox" || el.type === "radio") { if (el.checked !== el.defaultChecked) return true; continue; } if (["hidden", "submit", "button", "reset", "file", "image"].includes(el.type)) continue; } if (el.value !== el.defaultValue) return true; } return false; }