import { onBeforeUnmount, ref } from 'vue' import { versionDownloadPath, wordOpenUrl, type VersionFormat } from '../utils/versionDownload' /** Shared by history and generate success. Links stay available even if the focus heuristic fires. */ export function useVersionOpen() { const { apiJson } = useApi() const openingVersionId = ref(null) const downloadError = ref(null) const fallbackUrl = ref(null) const openNotice = ref(null) let cleanup = () => {} let generation = 0 let pendingTab: Window | null = null function resetOpen() { generation++ pendingTab?.close() pendingTab = null cleanup() openingVersionId.value = null downloadError.value = null fallbackUrl.value = null openNotice.value = null } async function openVersion(documentId: string, versionId: string, format: VersionFormat = 'docx') { if (openingVersionId.value) return resetOpen() const current = generation openingVersionId.value = versionId // Reserve a tab during the user gesture, before the authenticated request loses activation. let tab: Window | null = null try { tab = format === 'pdf' ? window.open('about:blank', '_blank') : null if (tab) tab.opener = null pendingTab = tab const link = await apiJson<{ url: string; expiresAt: string }>(versionDownloadPath(documentId, versionId, format)) if (current !== generation) { tab?.close(); return } if (!link) throw new Error('ขอลิงก์เปิดไฟล์ไม่สำเร็จ') fallbackUrl.value = link.url if (format === 'pdf') { if (tab && !tab.closed) { tab.location.replace(link.url) pendingTab = null } else openNotice.value = 'เบราว์เซอร์บล็อกแท็บใหม่ กรุณากดลิงก์เปิดไฟล์ด้านล่าง' } else { let switched = false const onBlur = () => { switched = true } const onVisibility = () => { if (document.hidden) switched = true } window.addEventListener('blur', onBlur) document.addEventListener('visibilitychange', onVisibility) const timer = window.setTimeout(() => { if (!switched) openNotice.value = 'หาก Word ไม่เปิด กรุณาดาวน์โหลดไฟล์แล้วเปิดใน Word' cleanup() }, 1500) cleanup = () => { window.clearTimeout(timer) window.removeEventListener('blur', onBlur) document.removeEventListener('visibilitychange', onVisibility) } window.location.assign(wordOpenUrl(link.url)) } } catch (err) { tab?.close() if (pendingTab === tab) pendingTab = null if (current === generation) downloadError.value = err instanceof Error ? err.message : 'เปิดไฟล์ไม่สำเร็จ' } finally { if (current === generation) openingVersionId.value = null } } onBeforeUnmount(resetOpen) return { openingVersionId, downloadError, fallbackUrl, openNotice, openVersion, resetOpen } }