Module: Staticky::Utils

Defined in:
lib/staticky/utils.rb

Class Method Summary collapse

Class Method Details

.live_reload_js(base_path) ⇒ Object

rubocop:disable Metrics/MethodLength



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/staticky/utils.rb', line 7

def live_reload_js(base_path) # rubocop:disable Metrics/MethodLength
  return "" unless Staticky.env.development?

  path = File.join(base_path, "/_staticky/live_reload")

  <<~JAVASCRIPT
    let lastmod = 0
    let reconnectAttempts = 0

    function statickyReload() {
      if (window.Turbo) {
        Turbo.visit(window.location)
      } else {
        location.reload()
      }
    }

    function startLiveReload() {
      const connection = new EventSource("#{path}")

      connection.addEventListener("message", event => {
        reconnectAttempts = 0

        if (event.data == "reloaded!") {
          statickyReload()
        } else {
          const newmod = Number(event.data)

          if (lastmod < newmod) {
            statickyReload()
            lastmod = newmod
          }
        }
      })

      connection.addEventListener("error", () => {
        if (connection.readyState === 2) {
          // reconnect with new object
          connection.close()
          reconnectAttempts++
          if (reconnectAttempts < 25) {
            console.warn("Live reload: attempting to reconnect in 3 seconds...")
            setTimeout(() => startLiveReload(), 3000)
          } else {
            console.error(
              "Too many live reload connections failed. Refresh the page to try again."
            )
          }
        }
      })
    }

    startLiveReload()
  JAVASCRIPT
end