update.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536
  1. const byId = id => document.getElementById(id)
  2. let closed = false
  3. let localError = '', previousPhase = ''
  4. const sizeLabel = value => value < 1048576 ? `${(value / 1024).toFixed(1)} KB` : `${(value / 1048576).toFixed(1)} MB`
  5. function render(state) {
  6. const busy = ['checking', 'downloading', 'verifying'].includes(state.phase)
  7. const ready = state.phase === 'ready'
  8. byId('current').textContent = `${state.currentVersion} · ${state.arch}`
  9. byId('latest').textContent = state.latestVersion || (state.phase === 'failed' ? '检查失败' : '待检查')
  10. byId('status').textContent = state.message
  11. byId('error').hidden = !(state.error || localError); byId('error').textContent = state.error || localError
  12. byId('check').disabled = busy
  13. byId('download').disabled = busy || !state.available; byId('download').hidden = ready
  14. byId('download').textContent = state.phase === 'failed' || state.phase === 'cancelled' ? '重试下载' : '下载 DMG'
  15. byId('cancel').hidden = !busy
  16. byId('open').hidden = !ready; byId('folder').hidden = !ready
  17. byId('progress').hidden = !['downloading', 'verifying'].includes(state.phase)
  18. byId('progress').max = state.total || 1; byId('progress').value = state.received || 0
  19. byId('bytes').textContent = state.received ? `${sizeLabel(state.received)} / ${sizeLabel(state.total)}` : ''
  20. byId('notes-section').hidden = !state.notes; byId('notes').textContent = state.notes || ''
  21. if (state.phase !== previousPhase && ['download', 'cancel'].includes(document.activeElement?.id)) {
  22. if (ready) byId('open').focus()
  23. else if (!busy) byId(state.available ? 'download' : 'check').focus()
  24. }
  25. previousPhase = state.phase
  26. }
  27. async function action(name) {
  28. if (name !== 'state') localError = ''
  29. try { const state = await window.yaoyaoUpdate[name](); if (state && !closed) render(state) }
  30. catch (error) { if (!closed) { localError = error.message; byId('error').hidden = false; byId('error').textContent = localError } }
  31. }
  32. for (const name of ['check', 'download', 'cancel', 'open', 'folder', 'release']) byId(name).addEventListener('click', () => void action(name))
  33. const timer = setInterval(() => void action('state'), 500)
  34. window.addEventListener('unload', () => { closed = true; clearInterval(timer) })
  35. document.addEventListener('keydown', event => { if (event.key === 'Escape') window.close() })
  36. void action('check')