/** * พารามิเตอร์เปิด PDF ในตัวดูของเบราว์เซอร์ (`#view=FitH&toolbar=0`) — Chrome/Edge รองรับ, Firefox บางส่วน, Safari ไม่สนใจ * ค่าเริ่มต้นพอดีความกว้างหน้า (ยกจาก supplychain `withPdfViewParams`) · URL ที่มี `#` อยู่แล้วต่อด้วย `&` */ export function withPdfViewParams( url: string, { view = "FitH", toolbar = true }: { view?: "Fit" | "FitH" | "FitV"; toolbar?: boolean } = {}, ): string { const params = [`view=${view}`, toolbar ? null : "toolbar=0"].filter(Boolean).join("&"); return url.includes("#") ? `${url}&${params}` : `${url}#${params}`; } const RESERVED_NAME = /^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\.|$)/i; /** * ชื่อไฟล์ที่บันทึกได้ทุกระบบ: แทนอักขระต้องห้าม (`\ / : * ? " < > |`) ด้วย `-`, ตัดอักขระควบคุม, ยุบช่องว่าง, * ตัดที่ 120 ตัว (นับตาม code point ไม่ตัด emoji ครึ่งตัว), ตัดจุด/ช่องว่างท้าย, ชื่ออุปกรณ์ของ Windows (`CON` …) เติม `_` หน้า, * เติมนามสกุลถ้ายังไม่มี * * safeFileName("ใบสั่งซื้อ PO/001", ".pdf") → "ใบสั่งซื้อ PO-001.pdf" */ export function safeFileName(name: string, extension?: string): string { const collapsed = name // biome-ignore lint/suspicious/noControlCharactersInRegex: ตัดอักขระควบคุมออกโดยตั้งใจ .replace(/[\u0000-\u001f\u007f]/g, "") .replace(/[\\/:*?"<>|]/g, "-") .replace(/\s+/g, " ") .trim(); // ครึ่งตัวของอักขระคู่ (emoji) ทำให้ encodeURIComponent ของ Content-Disposition throw const cleaned = Array.from(collapsed) .slice(0, 120) .join("") .replace(/[. ]+$/, ""); const base = !cleaned ? "download" : RESERVED_NAME.test(cleaned) ? `_${cleaned}` : cleaned; if (!extension) return base; const ext = extension.startsWith(".") ? extension : `.${extension}`; return base.toLowerCase().endsWith(ext.toLowerCase()) ? base : `${base}${ext}`; } /** เบราว์เซอร์แสดง PDF ใน iframe ได้แค่ไหน: `full` ปกติ, `first-page` เห็นแค่หน้าแรก (iOS/iPadOS), `none` ไม่แสดง (Android Chrome ฯลฯ) */ export type PdfInlineSupport = "full" | "first-page" | "none"; /** * ตรวจจาก `navigator` — เรียกฝั่ง client เท่านั้น (server ได้ `full`) * iPadOS รายงานตัวเป็น Mac จึงดู `maxTouchPoints` ด้วย · `pdfViewerEnabled === false` = ไม่มีตัวดู PDF ในตัว */ export function detectPdfInlineSupport( nav: Pick & { pdfViewerEnabled?: boolean; platform?: string; } = typeof navigator === "undefined" ? { userAgent: "", maxTouchPoints: 0 } : navigator, ): PdfInlineSupport { const ua = nav.userAgent ?? ""; const ios = /iP(hone|od|ad)/.test(ua) || (/Macintosh/.test(ua) && (nav.maxTouchPoints ?? 0) > 1); if (ios) return "first-page"; if (nav.pdfViewerEnabled === false) return "none"; return "full"; }