Class: Dommy::History

Inherits:
Object
  • Object
show all
Includes:
Bridge::Methods
Defined in:
lib/dommy/history.rb

Overview

‘window.history` polyfill. Stack-based; back/forward move the cursor. pushState appends; replaceState mutates the current entry. Each entry is `{ state:, url: }`. Popstate fires when back / forward triggers a different cursor (not on pushState per spec).

Instance Method Summary collapse

Methods included from Bridge::Methods

included

Constructor Details

#initialize(window, location) ⇒ History

Returns a new instance of History.



9
10
11
12
13
14
15
16
17
18
# File 'lib/dommy/history.rb', line 9

def initialize(window, location)
  @window = window
  @location = location
  # Each entry records the full href it navigated to, so back/forward can
  # restore Location to it (and fire popstate) — a restoration that
  # framework routers like Turbo's depend on to swap the cached snapshot.
  @stack = [{state: nil, url: @location.href}]
  @cursor = 0
  @scroll_restoration = "auto"
end

Instance Method Details

#__js_call__(method, args) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/dommy/history.rb', line 47

def __js_call__(method, args)
  case method
  when "pushState"
    push(args[0], args[2])
  when "replaceState"
    replace(args[0], args[2])
  when "back"
    go(-1)
  when "forward"
    go(1)
  when "go"
    go((args[0] || 0).to_i)
  end
end

#__js_get__(key) ⇒ Object



20
21
22
23
24
25
26
27
28
29
# File 'lib/dommy/history.rb', line 20

def __js_get__(key)
  case key
  when "length"
    @stack.size
  when "state"
    @stack[@cursor][:state]
  when "scrollRestoration"
    @scroll_restoration
  end
end

#__js_set__(key, value) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/dommy/history.rb', line 31

def __js_set__(key, value)
  case key
  when "scrollRestoration"
    # Per spec, only "auto" and "manual" are accepted. Invalid
    # values silently retain the current value.
    v = value.to_s
    @scroll_restoration = v if %w[auto manual].include?(v)
  else
    return Bridge::UNHANDLED
  end

  nil
end