mata 0.10.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: ab070e4aa36426eec7fdc324a6f493665bb6fbda68280cca8d8e98bbbd15df4d
4
- data.tar.gz: 372274d8821279df66b0ddbf8b5c8f59254aa4e61f7f0ed7b343fbbc5891269e
3
+ metadata.gz: c5d3bf8207f3d65c4f2403277f9b902a5a30b51e3812d1ce6aaf34d31fb2ebf9
4
+ data.tar.gz: 1d4372dc97e20d15337535ac33480a605a17ea4feaea420592e59ece6c66beb4
5
5
  SHA512:
6
- metadata.gz: 3343f58cd5a1cc9bef0aaa7fdb8d8eb102839631c1b5ae1cb141b340f387b00e5f44743ea5742d5eac53dfdb26816231d5643a33158a6a465b11fabd154366d1
7
- data.tar.gz: 3dc12dbb74eaac619279b2d92c0721913f71f46a9cb184370861b7945c84610856466d2a14c24c0ee7595046dc603f249b3f96a2d7e43ebf82eaf2308d08b266
6
+ metadata.gz: 90be02b12107f5fbe3a389c103a500a7d9784d94aacb1608a9fd71414e352b928d366023e6ec02e34da7868b52e182430f8c8fc148120ba94761bfe4fa97c60f
7
+ data.tar.gz: 2f8a07fbe3fe915ec889f13a2949cfd0e6e1cd45597c1b2d77407e1e1e1057223b87fb99ae5707f0622a8429665939a10662adadad0ab0779d7db5805476c373
data/README.md CHANGED
@@ -10,6 +10,7 @@ Live Reload with DOM Morphing for Rack applications using Server-Sent Events (SS
10
10
  <picture>
11
11
  <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/Rails-Designer/mata/HEAD/.github/logo-dark.svg">
12
12
  <source media="(prefers-color-scheme: light)" srcset="https://raw.githubusercontent.com/Rails-Designer/mata/HEAD/.github/logo-light.svg">
13
+
13
14
  <img alt="Rails Designer" src="https://raw.githubusercontent.com/Rails-Designer/mata/HEAD/.github/logo-light.svg" width="240" style="max-width: 100%;">
14
15
  </picture>
15
16
  </a>
@@ -36,20 +37,6 @@ config.middleware.insert_before(
36
37
  ```
37
38
 
38
39
 
39
- ### Other rack-based apps
40
- ```ruby
41
- # config.ru
42
- require "mata"
43
-
44
- use Mata, watch: %w[views assets], skip: %w[views/tmp]
45
-
46
- run YourApp
47
- ```
48
-
49
- > [!NOTE]
50
- > Do share your snippets on how to add Mata into your specific Rack-based apps 💙
51
-
52
-
53
40
  ### Hanami
54
41
  ```ruby
55
42
  # config.ru
@@ -87,6 +74,31 @@ route do |r|
87
74
  end
88
75
  ```
89
76
 
77
+ ### Other rack-based apps
78
+ ```ruby
79
+ # config.ru
80
+ require "mata"
81
+
82
+ use Mata, watch: %w[views assets], skip: %w[views/tmp]
83
+
84
+ run YourApp
85
+ ```
86
+
87
+
88
+ ### Options
89
+
90
+ All options are optional.
91
+
92
+ | Option | Default | Type | Description |
93
+ |---|---|---|---|
94
+ | `watch` | `[]` | Array of String | Directories to watch for changes |
95
+ | `skip` | `[]` | Array of String/Regexp | Paths to ignore |
96
+ | `debounce` | `300` | Integer | Debounce interval in milliseconds before broadcasting changes |
97
+ | `retry` | not set | Integer | SSE retry interval in milliseconds (not set = browser default ~3s, maximum clamped at 30s) |
98
+ | `log_level` | `:verbose` | Symbol | `:verbose` shows all console messages; `:silent` suppresses them in the browser console (`[Mata] Connected with DOM morphing`, etc.) |
99
+ | `idiomorph_options` | `nil` | String | A raw JS object literal passed **verbatim** as the `options` argument to [`Idiomorph.morph`](https://github.com/bigskysoftware/idiomorph#options), fully replacing Mata's built-in defaults. Example: `idiomorph_options: '{ morphStyle: "innerHTML" }'` |
100
+
101
+
90
102
  ## Used in
91
103
 
92
104
  This gem powers live reloading in [Perron](https://github.com/rails-designer/perron), a Rails-based static site generator. It can be enabled with `config.live_reload = true` in your Perron initializer.
data/lib/mata/agent.rb CHANGED
@@ -2,16 +2,25 @@
2
2
 
3
3
  class Mata
4
4
  class Agent
5
+ def initialize(options = {})
6
+ @retry = options[:retry]
7
+ @log_level = options[:log_level]
8
+ end
9
+
5
10
  def insert(status, headers, body)
6
11
  return [status, headers, body] unless html_response?(headers)
7
12
 
8
13
  content = extract(body)
9
14
  return [status, headers, [content]] unless content.include?("</head>")
10
15
 
11
- script_tag = '<script src="/__mata/client.js"></script>'
16
+ script_tag = '<script src="/__mata/client.js"'
17
+ script_tag += %( data-mata-retry="#{@retry}") if @retry
18
+ script_tag += %( data-mata-log-level="#{@log_level}") if @log_level
19
+ script_tag += "></script>"
12
20
  modified_content = content.sub("</head>", "#{script_tag}\n</head>")
13
21
 
14
- headers["Content-Length"] = modified_content.bytesize.to_s if headers["Content-Length"]
22
+ length_header = headers.keys.find { it.to_s.casecmp?("content-length") }
23
+ headers[length_header] = modified_content.bytesize.to_s if length_header
15
24
 
16
25
  [status, headers, [modified_content]]
17
26
  end
@@ -24,12 +33,16 @@ class Mata
24
33
  content_type&.include?("text/html")
25
34
  end
26
35
 
36
+ # The original body is replaced, so it's closed here as the Rack spec asks:
37
+ # that releases a file body and runs Rack::BodyProxy callbacks.
27
38
  def extract(body)
28
39
  if body.respond_to?(:each)
29
40
  [].tap { |parts| body.each { |part| parts << part } }.join
30
41
  else
31
42
  body.to_s
32
43
  end
44
+ ensure
45
+ body.close if body.respond_to?(:close)
33
46
  end
34
47
  end
35
48
  end
@@ -2,9 +2,28 @@
2
2
 
3
3
  class Mata
4
4
  class Broadcaster
5
- def initialize
5
+ DEFAULT_IDIOMORPH_OPTIONS = <<~JS
6
+ {
7
+ ignoreActiveValue: true,
8
+ callbacks: {
9
+ beforeNodeMorphed: function(oldNode, _) {
10
+ if (oldNode.tagName && oldNode.tagName.includes("-")) {
11
+ return false;
12
+ }
13
+
14
+ return true;
15
+ }
16
+ }
17
+ }
18
+ JS
19
+
20
+ HEARTBEAT_INTERVAL = 15
21
+
22
+ def initialize(options = {})
6
23
  @clients = []
7
24
  @clients_mutex = Mutex.new
25
+ @retry = options[:retry]
26
+ @idiomorph_options = options[:idiomorph_options]
8
27
  @cleanup_thread = cleanup_periodically
9
28
  end
10
29
 
@@ -26,6 +45,7 @@ class Mata
26
45
  end
27
46
 
28
47
  begin
48
+ stream << "retry: #{@retry}\n\n" if @retry
29
49
  stream << "data: {\"type\":\"connected\"}\n\n"
30
50
  rescue
31
51
  @clients_mutex.synchronize { @clients.delete(stream) }
@@ -34,9 +54,13 @@ class Mata
34
54
  end
35
55
 
36
56
  def deliver_payload
57
+ raise ArgumentError, "idiomorph_options must be a String containing a raw JS object literal" if @idiomorph_options && !@idiomorph_options.is_a?(String)
58
+
37
59
  idiomorph_js = File.read(File.join(__dir__, "idiomorph.min.js"))
38
60
  client_js = File.read(File.join(__dir__, "client.js"))
39
61
 
62
+ client_js = client_js.gsub("__MATA_IDIOMORPH_OPTIONS__", @idiomorph_options || DEFAULT_IDIOMORPH_OPTIONS)
63
+
40
64
  script = "#{idiomorph_js}\n\n#{client_js}"
41
65
 
42
66
  [200, {"content-type" => "application/javascript"}, [script]]
@@ -46,15 +70,15 @@ class Mata
46
70
  clients_copy = @clients_mutex.synchronize { @clients.dup }
47
71
  return if clients_copy.empty?
48
72
 
49
- files.each do |file|
50
- event_data = {type: "reload"}
51
- message = "data: #{event_data.to_json}\n\n"
73
+ event_data = {type: "reload", files: files}
74
+ message = "data: #{event_data.to_json}\n\n"
52
75
 
53
- clients_copy.each do |stream|
54
- stream << message
55
- rescue
56
- @clients_mutex.synchronize { @clients.delete(stream) }
57
- end
76
+ clients_copy.each do |stream|
77
+ stream << message
78
+ rescue
79
+ @clients_mutex.synchronize { @clients.delete(stream) }
80
+
81
+ hang_up(stream)
58
82
  end
59
83
  end
60
84
 
@@ -69,7 +93,7 @@ class Mata
69
93
  def cleanup_periodically
70
94
  Thread.new do
71
95
  loop do
72
- sleep 60
96
+ sleep HEARTBEAT_INTERVAL
73
97
 
74
98
  cleanup_dead_clients
75
99
  end
@@ -80,13 +104,22 @@ class Mata
80
104
  def cleanup_dead_clients
81
105
  @clients_mutex.synchronize do
82
106
  @clients.reject! do |client|
83
- client << ""
107
+ # an SSE comment; writing nothing never notices a closed tab
108
+ client << ":\n\n"
84
109
 
85
110
  false
86
111
  rescue
112
+ hang_up(client)
113
+
87
114
  true
88
115
  end
89
116
  end
90
117
  end
118
+
119
+ def hang_up(stream)
120
+ stream.close
121
+ rescue
122
+ nil
123
+ end
91
124
  end
92
125
  end
data/lib/mata/client.js CHANGED
@@ -2,26 +2,74 @@
2
2
  initMata();
3
3
 
4
4
  function initMata() {
5
- const eventSource = new EventSource("/__mata/events");
5
+ const retryDelayBase = parseInt(document.currentScript.dataset.mataRetry) || 1000;
6
+ const maximumRetryDelay = 30000;
7
+ let retryDelay = retryDelayBase;
6
8
 
7
- eventSource.onmessage = function(event) {
8
- const data = JSON.parse(event.data);
9
+ const silent = (document.currentScript.dataset.mataLogLevel || "verbose").toLowerCase() === "silent";
9
10
 
11
+ function log(...arguments) {
12
+ if (!silent) console.log("[Mata]", ...arguments);
13
+ }
14
+
15
+ function error(...arguments) {
16
+ if (!silent) console.error("[Mata]", ...arguments);
17
+ }
18
+
19
+ const channel = "BroadcastChannel" in window ? new BroadcastChannel("mata") : null;
20
+
21
+ if (channel && navigator.locks) {
22
+ channel.onmessage = (event) => handle(event.data);
23
+
24
+ navigator.locks.request("mata", () => new Promise(() => connect()));
25
+ } else {
26
+ connect();
27
+ }
28
+
29
+ function connect() {
30
+ const eventSource = new EventSource("/__mata/events");
31
+
32
+ eventSource.onmessage = function(event) {
33
+ const data = JSON.parse(event.data);
34
+
35
+ channel?.postMessage(data);
36
+ handle(data);
37
+ };
38
+
39
+ eventSource.onerror = function() {
40
+ eventSource.close();
41
+
42
+ log(`Connection lost, retrying in ${retryDelay}ms…`);
43
+
44
+ setTimeout(connect, retryDelay);
45
+ retryDelay = Math.min(retryDelay * 2, maximumRetryDelay);
46
+ };
47
+ }
48
+
49
+ function handle(data) {
10
50
  switch(data.type) {
11
51
  case "reload":
12
- morphPage();
52
+ if (data.files?.some((file) => file.endsWith(".js"))) {
53
+ log("JS file changed, reloading…");
54
+
55
+ window.location.reload();
56
+ } else {
57
+ morphPage();
58
+ }
13
59
 
14
60
  break;
15
61
  case "connected":
16
- console.log("[Mata] Connected with DOM morphing");
62
+ retryDelay = retryDelayBase;
63
+
64
+ log("Connected with DOM morphing");
17
65
 
18
66
  break;
19
67
  }
20
- };
68
+ }
21
69
 
22
70
  async function morphPage() {
23
71
  try {
24
- console.log("[Mata] Fetching updated page…");
72
+ log("Fetching updated page…");
25
73
  const response = await fetch(window.location.href);
26
74
 
27
75
  if (!response.ok) {
@@ -36,30 +84,15 @@
36
84
  throw new Error("Invalid HTML response");
37
85
  }
38
86
 
39
- Idiomorph.morph(document.documentElement, updatedDocument.documentElement, {
40
- ignoreActiveValue: true,
41
- callbacks: {
42
- beforeNodeMorphed: function(oldNode, _) {
43
- if (oldNode.tagName && oldNode.tagName.includes("-")) { // skip custom elements
44
- return false;
45
- }
87
+ Idiomorph.morph(document.documentElement, updatedDocument.documentElement, __MATA_IDIOMORPH_OPTIONS__);
46
88
 
47
- return true;
48
- }
49
- }
50
- });
51
-
52
- console.log("[Mata] Page morphed successfully");
89
+ log("Page morphed successfully");
53
90
  } catch (error) {
54
- console.error("[Mata] Morph failed:", error.message);
55
- console.log("[Mata] Falling back to full reload");
91
+ error("Morph failed:", error.message);
92
+ log("Falling back to full reload");
56
93
 
57
94
  window.location.reload();
58
95
  }
59
96
  }
60
-
61
- eventSource.onerror = function() {
62
- console.log("[Mata] Connection lost, retrying…");
63
- };
64
97
  }
65
98
  })();
data/lib/mata/version.rb CHANGED
@@ -1,3 +1,3 @@
1
1
  class Mata
2
- VERSION = "0.10.0"
2
+ VERSION = "0.12.0"
3
3
  end
@@ -5,6 +5,7 @@ class Mata
5
5
  def initialize(options)
6
6
  @watch_paths = Array(options[:watch] || [])
7
7
  @skip_paths = skipped_patterns(options[:skip] || options[:ignore] || [])
8
+ @debounce = options[:debounce] || 300
8
9
  @on_change = nil
9
10
  @listener = nil
10
11
 
@@ -42,8 +43,9 @@ class Mata
42
43
  @last_change_time = Time.now
43
44
 
44
45
  Thread.new do
45
- sleep 0.15
46
- if Time.now - @last_change_time >= 0.15
46
+ sleep(@debounce / 1000.0)
47
+
48
+ if Time.now - @last_change_time >= (@debounce / 1000.0)
47
49
  @on_change&.call(modified + added + removed)
48
50
  end
49
51
  end
data/lib/mata.rb CHANGED
@@ -14,8 +14,8 @@ class Mata
14
14
  return if ENV["MATA_DISABLED"] == "true"
15
15
 
16
16
  @watch_tower = WatchTower.new(options)
17
- @broadcaster = Broadcaster.new
18
- @agent = Agent.new
17
+ @broadcaster = Broadcaster.new(options)
18
+ @agent = Agent.new(options)
19
19
 
20
20
  @watch_tower.on_change { |files| @broadcaster.broadcast_to_all(files) }
21
21
 
@@ -23,6 +23,8 @@ class Mata
23
23
  end
24
24
 
25
25
  def call(environment)
26
+ return @app.call(environment) if @agent.nil?
27
+
26
28
  request = Rack::Request.new(environment)
27
29
 
28
30
  case request.path
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: mata
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.10.0
4
+ version: 0.12.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Rails Designer
@@ -72,7 +72,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
72
72
  - !ruby/object:Gem::Version
73
73
  version: '0'
74
74
  requirements: []
75
- rubygems_version: 4.0.14
75
+ rubygems_version: 4.0.24
76
76
  specification_version: 4
77
77
  summary: Hot module reloading for Rack applications
78
78
  test_files: []