breakfast 0.0.4 → 0.0.5

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
  SHA1:
3
- metadata.gz: 81dc47bb8e920de4a76c9f9786c27bd477f276c5
4
- data.tar.gz: fb19acceae3867db1b3646a4414e941733f1aefc
3
+ metadata.gz: 85745d03b1181faa797c521daf152ac125061542
4
+ data.tar.gz: f2366625165c66c770a05928eca64dc86cb24e0e
5
5
  SHA512:
6
- metadata.gz: 673231b3a2dea8137c755fe7c735c7d4e2a8b360b8ac5dbab7a50a5e788f83f96d7bf922465e90d15232f04fe0ed399d497a2707b38804d152c6d10c999570ae
7
- data.tar.gz: 98a0f9223a3c68e60dc73a30a727cb06e4f6d59422c71bf1d62ce9c3e1ada5c53b55c375b967be326c624a2d4c6f47cff9f11f5b9ad4c6e525a80843aec19312
6
+ metadata.gz: 45c9038b1d2a10e4e956ff3a38341ac5d19a0ad4829e998920055544cc8b6730935dc8ff9da9e967ff6ea432af6da831a0eadf7e219f12d89fa0dce56d7052ed
7
+ data.tar.gz: 394312cf9ca5d820042c411b8adc868bc9a02235b4903f7c4ac774c2fbb45396dae74fcf6d1a4f48b4025ba24f6d8eb3e6df89ed9da26c1b8c14a8aff4365dbe
data/.gitignore CHANGED
@@ -9,3 +9,4 @@
9
9
  /tmp/
10
10
  node_package/node_modules/*
11
11
  node_package/lib/*
12
+ npm-debug.log
@@ -22,7 +22,7 @@ Gem::Specification.new do |spec|
22
22
  spec.add_development_dependency "bundler", "~> 1.12"
23
23
  spec.add_development_dependency "rake", "~> 10.0"
24
24
  spec.add_development_dependency "rspec", "~> 3.0"
25
- spec.add_dependency "rails", "5.0.0.rc2"
25
+ spec.add_dependency "rails", "~> 5.0"
26
26
  spec.add_dependency "actioncable"
27
27
  spec.add_dependency "listen"
28
28
  end
@@ -7,26 +7,28 @@ module BrunchRails
7
7
 
8
8
  config.before_configuration do |app|
9
9
  config.breakfast.live_reload = true
10
+ config.breakfast.html_reload_strategy = :turbolinks
11
+ config.breakfast.js_reload_strategy = :page
12
+ config.breakfast.css_reload_strategy = :hot
10
13
 
11
- config.breakfast.output_folders = [Rails.root.join("public")]
14
+ config.breakfast.asset_output_folders = [Rails.root.join("public")]
12
15
  config.breakfast.view_folders = [Rails.root.join("app", "views")]
13
-
14
- config.breakfast.websocket_hostname = "localhost"
15
- config.breakfast.websocket_port = 3000
16
16
  config.breakfast.environments = %w(development)
17
17
  end
18
18
 
19
19
  initializer "breakfast.setup_view_helpers" do |app|
20
- ActiveSupport.on_load(:action_view) do
21
- include ::Breakfast::ViewHelper
20
+ if config.breakfast.environments.include?(Rails.env)
21
+ ActiveSupport.on_load(:action_view) do
22
+ include ::Breakfast::ViewHelper
23
+ end
22
24
  end
23
25
  end
24
26
 
25
27
  config.after_initialize do |app|
26
- if Rails.env.development? && defined?(Rails::Server)
28
+ if config.breakfast.environments.include?(Rails.env) && defined?(Rails::Server)
27
29
  Process.spawn("brunch watch")
28
30
 
29
- listen_to_paths = Array.wrap(config.breakfast.output_folders) +
31
+ listen_to_paths = Array.wrap(config.breakfast.asset_output_folders) +
30
32
  Array.wrap(config.breakfast.view_folders)
31
33
 
32
34
  listener = ::Listen.to(*listen_to_paths) do |modified, added, removed|
@@ -35,8 +37,7 @@ module BrunchRails
35
37
 
36
38
  extensions.each do |extension|
37
39
  if files.any? { |file| file.match(/\.#{extension}/) }
38
- ActionCable.server.broadcast "breakfast_live_reload",
39
- { extension: extension }
40
+ ActionCable.server.broadcast "breakfast_live_reload", { extension: extension }
40
41
  end
41
42
  end
42
43
  end
@@ -1,3 +1,3 @@
1
1
  module Breakfast
2
- VERSION = "0.0.4"
2
+ VERSION = "0.0.5"
3
3
  end
@@ -6,7 +6,15 @@ module Breakfast
6
6
  <<-SCRIPT.html_safe
7
7
  window.Breakfast = window.Breakfast || {};
8
8
  window.Breakfast.liveReload = #{Rails.configuration.breakfast.live_reload};
9
- require("breakfast-rails").init();
9
+ require("breakfast-rails").init({
10
+ host: "#{request.host}",
11
+ port: #{request.port},
12
+ reloadStrategies: {
13
+ js: "#{Rails.configuration.breakfast.js_reload_strategy}",
14
+ css: "#{Rails.configuration.breakfast.css_reload_strategy}",
15
+ html: "#{Rails.configuration.breakfast.html_reload_strategy}"
16
+ }
17
+ });
10
18
  SCRIPT
11
19
  end
12
20
  end
@@ -1,3 +1,6 @@
1
+ const Turbolinks = require("turbolinks")
2
+ Turbolinks.start()
3
+
1
4
  const App = {
2
5
  }
3
6
 
@@ -1,14 +1,17 @@
1
1
  {
2
2
  "repository": {},
3
3
  "dependencies": {
4
+ "breakfast-rails": "0.0.5",
5
+ "actioncable": "^5.0.0",
6
+ "turbolinks": "^5.0.0"
7
+ },
8
+ "devDependencies": {
4
9
  "babel-brunch": "~6.0.0",
5
- "breakfast-rails": "0.0.1",
6
10
  "brunch": "~2.1.3",
7
11
  "clean-css-brunch": "~1.8.0",
8
12
  "css-brunch": "~1.7.0",
9
13
  "javascript-brunch": "~1.8.0",
10
14
  "sass-brunch": "~2.6.3",
11
15
  "uglify-js-brunch": "~1.7.0"
12
- },
13
- "devDependencies": {}
16
+ }
14
17
  }
@@ -1,18 +1,23 @@
1
1
  {
2
2
  "name": "breakfast-rails",
3
- "version": "0.0.4",
3
+ "version": "0.0.5",
4
4
  "description": "Assets for the Breakfast Gem",
5
- "main": "src/breakfast-rails.js",
5
+ "main": "./lib/breakfast-rails.js",
6
6
  "scripts": {
7
7
  "test": "echo \"Error: no test specified\" && exit 1",
8
- "compile": "babel --presets es2015 -d lib/ src/",
9
- "prepublish": "npm run compile"
8
+ "prepublish": "node_modules/babel-cli/bin/babel.js src --out-dir lib"
10
9
  },
11
10
  "author": "Patrick Koperwas",
12
11
  "license": "MIT",
13
- "dependencies": {},
12
+ "dependencies": {
13
+ "actioncable": "^5.0.0"
14
+ },
14
15
  "devDependencies": {
15
16
  "babel-cli": "^6.10.1",
17
+ "babel-core": "^6.10.4",
16
18
  "babel-preset-es2015": "^6.9.0"
19
+ },
20
+ "babel": {
21
+ "presets": ["es2015"]
17
22
  }
18
23
  }
@@ -1,11 +1,10 @@
1
- let LiveReloader = require("./live-reload")
1
+ let LiveReloader = require("./live-reload");
2
2
 
3
3
  let BreakfastRails = {
4
- init() {
4
+ init(options = {}) {
5
5
  let liveReloader = new LiveReloader
6
- liveReloader.init()
6
+ liveReloader.init(options)
7
7
  }
8
8
  }
9
9
 
10
- // The plugin has to be the module’s default export
11
10
  module.exports = BreakfastRails;
@@ -1,4 +1,4 @@
1
- const ActionCable = require('./action-cable');
1
+ const ActionCable = require('actioncable');
2
2
 
3
3
  class LiveReloader {
4
4
  buildFreshUrl(url) {
@@ -8,29 +8,63 @@ class LiveReloader {
8
8
  return(`${url}${(url.indexOf('?') >= 0 ? '&' : '?')}version=${date}`);
9
9
  }
10
10
 
11
- cssReload() {
12
- var reloadableLinkElements = window.top.document.querySelectorAll(
13
- 'link[rel=stylesheet]:not([data-no-reload]):not([data-pending-removal])'
14
- );
11
+ cssReload(strategy) {
12
+ switch(strategy) {
13
+ case "hot":
14
+ let reloadableLinkElements = window.top.document.querySelectorAll(
15
+ 'link[rel=stylesheet]:not([data-no-reload]):not([data-pending-removal])'
16
+ );
15
17
 
16
- [].slice
17
- .call(reloadableLinkElements)
18
- .filter(link => link.href)
19
- .forEach(link => link.href = this.buildFreshUrl(link.href))
18
+ [].slice
19
+ .call(reloadableLinkElements)
20
+ .filter(link => link.href)
21
+ .forEach(link => link.href = this.buildFreshUrl(link.href))
20
22
 
21
- // Repaint
22
- setTimeout(function(){ document.body.offsetHeight; }, 25);
23
+ // Repaint
24
+ setTimeout(() => { document.body.offsetHeight; }, 25);
25
+ break;
26
+ case "page":
27
+ window.top.location.reload();
28
+ break;
29
+ case "off":
30
+ break;
31
+ }
32
+ }
33
+
34
+ jsReload(strategy) {
35
+ switch(strategy) {
36
+ case "page":
37
+ window.top.location.reload();
38
+ break;
39
+ case "off":
40
+ break;
41
+ }
23
42
  }
24
43
 
25
- pageReload() {
26
- window.top.location.reload();
44
+ htmlReload(strategy) {
45
+ switch(strategy) {
46
+ case "turbolinks":
47
+ let location = window.top.location
48
+
49
+ if(typeof Turbolinks != 'undefined') {
50
+ Turbolinks.visit(location)
51
+ } else {
52
+ location.reload();
53
+ }
54
+ break;
55
+ case "page":
56
+ window.top.location.reload();
57
+ break;
58
+ case "off":
59
+ break;
60
+ }
27
61
  }
28
62
 
29
- init(host = "localhost", port = 3000) {
63
+ init(options = {}) {
30
64
  const reloaders = {
31
- js: this.pageReload.bind(this),
65
+ js: this.jsReload.bind(this),
32
66
  css: this.cssReload.bind(this),
33
- html: this.pageReload.bind(this)
67
+ html: this.htmlReload.bind(this)
34
68
  }
35
69
 
36
70
  document.addEventListener('DOMContentLoaded', () => {
@@ -39,11 +73,11 @@ class LiveReloader {
39
73
  if(Breakfast.liveReload) {
40
74
  let reloadChannel = 'Breakfast::LiveReloadChannel'
41
75
 
42
- Breakfast.cable = ActionCable.createConsumer(`ws://${host}:${port}/cable`);
76
+ Breakfast.cable = ActionCable.createConsumer(`ws://${options.host}:${options.port}/cable`);
43
77
  Breakfast.channel = Breakfast.cable.subscriptions.create(reloadChannel, {
44
78
  received: (data) => {
45
- let reloader = reloaders[data.extension]
46
- reloader();
79
+ let reloader = reloaders[data.extension];
80
+ reloader(options.reloadStrategies[data.extension]);
47
81
  }
48
82
  })
49
83
  }
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: breakfast
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.0.4
4
+ version: 0.0.5
5
5
  platform: ruby
6
6
  authors:
7
7
  - Patrick Koperwas
8
8
  autorequire:
9
9
  bindir: exe
10
10
  cert_chain: []
11
- date: 2016-07-12 00:00:00.000000000 Z
11
+ date: 2016-07-19 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: bundler
@@ -56,16 +56,16 @@ dependencies:
56
56
  name: rails
57
57
  requirement: !ruby/object:Gem::Requirement
58
58
  requirements:
59
- - - '='
59
+ - - "~>"
60
60
  - !ruby/object:Gem::Version
61
- version: 5.0.0.rc2
61
+ version: '5.0'
62
62
  type: :runtime
63
63
  prerelease: false
64
64
  version_requirements: !ruby/object:Gem::Requirement
65
65
  requirements:
66
- - - '='
66
+ - - "~>"
67
67
  - !ruby/object:Gem::Version
68
- version: 5.0.0.rc2
68
+ version: '5.0'
69
69
  - !ruby/object:Gem::Dependency
70
70
  name: actioncable
71
71
  requirement: !ruby/object:Gem::Requirement
@@ -123,7 +123,6 @@ files:
123
123
  - lib/generators/breakfast/templates/package.json
124
124
  - node_package/.npmignore
125
125
  - node_package/package.json
126
- - node_package/src/action-cable.js
127
126
  - node_package/src/breakfast-rails.js
128
127
  - node_package/src/live-reload.js
129
128
  homepage: https://github.com/devlocker/breakfast
@@ -1,572 +0,0 @@
1
- // Copied from Rails source. Rails RC1.
2
- var ActionCable = {
3
- INTERNAL: {
4
- "message_types": {
5
- "welcome": "welcome",
6
- "ping": "ping",
7
- "confirmation": "confirm_subscription",
8
- "rejection": "reject_subscription"
9
- },
10
- "default_mount_path": "/cable",
11
- "protocols": ["actioncable-v1-json", "actioncable-unsupported"]
12
- },
13
- WebSocket: window.WebSocket,
14
- logger: window.console,
15
- createConsumer: function(url) {
16
- var ref;
17
- if (url == null) {
18
- url = (ref = this.getConfig("url")) != null ? ref : this.INTERNAL.default_mount_path;
19
- }
20
- return new ActionCable.Consumer(this.createWebSocketURL(url));
21
- },
22
- getConfig: function(name) {
23
- var element;
24
- element = document.head.querySelector("meta[name='action-cable-" + name + "']");
25
- return element != null ? element.getAttribute("content") : void 0;
26
- },
27
- createWebSocketURL: function(url) {
28
- var a;
29
- if (url && !/^wss?:/i.test(url)) {
30
- a = document.createElement("a");
31
- a.href = url;
32
- a.href = a.href;
33
- a.protocol = a.protocol.replace("http", "ws");
34
- return a.href;
35
- } else {
36
- return url;
37
- }
38
- },
39
- startDebugging: function() {
40
- return this.debugging = true;
41
- },
42
- stopDebugging: function() {
43
- return this.debugging = null;
44
- },
45
- log: function() {
46
- var messages, ref;
47
- messages = 1 <= arguments.length ? slice.call(arguments, 0) : [];
48
- if (this.debugging) {
49
- messages.push(Date.now());
50
- return (ref = this.logger).log.apply(ref, ["[ActionCable]"].concat(slice.call(messages)));
51
- }
52
- }
53
- };
54
-
55
- var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
56
-
57
- ActionCable.ConnectionMonitor = (function() {
58
- var clamp, now, secondsSince;
59
-
60
- ConnectionMonitor.pollInterval = {
61
- min: 3,
62
- max: 30
63
- };
64
-
65
- ConnectionMonitor.staleThreshold = 6;
66
-
67
- function ConnectionMonitor(connection) {
68
- this.connection = connection;
69
- this.visibilityDidChange = bind(this.visibilityDidChange, this);
70
- this.reconnectAttempts = 0;
71
- }
72
-
73
- ConnectionMonitor.prototype.start = function() {
74
- if (!this.isRunning()) {
75
- this.startedAt = now();
76
- delete this.stoppedAt;
77
- this.startPolling();
78
- document.addEventListener("visibilitychange", this.visibilityDidChange);
79
- return ActionCable.log("ConnectionMonitor started. pollInterval = " + (this.getPollInterval()) + " ms");
80
- }
81
- };
82
-
83
- ConnectionMonitor.prototype.stop = function() {
84
- if (this.isRunning()) {
85
- this.stoppedAt = now();
86
- this.stopPolling();
87
- document.removeEventListener("visibilitychange", this.visibilityDidChange);
88
- return ActionCable.log("ConnectionMonitor stopped");
89
- }
90
- };
91
-
92
- ConnectionMonitor.prototype.isRunning = function() {
93
- return (this.startedAt != null) && (this.stoppedAt == null);
94
- };
95
-
96
- ConnectionMonitor.prototype.recordPing = function() {
97
- return this.pingedAt = now();
98
- };
99
-
100
- ConnectionMonitor.prototype.recordConnect = function() {
101
- this.reconnectAttempts = 0;
102
- this.recordPing();
103
- delete this.disconnectedAt;
104
- return ActionCable.log("ConnectionMonitor recorded connect");
105
- };
106
-
107
- ConnectionMonitor.prototype.recordDisconnect = function() {
108
- this.disconnectedAt = now();
109
- return ActionCable.log("ConnectionMonitor recorded disconnect");
110
- };
111
-
112
- ConnectionMonitor.prototype.startPolling = function() {
113
- this.stopPolling();
114
- return this.poll();
115
- };
116
-
117
- ConnectionMonitor.prototype.stopPolling = function() {
118
- return clearTimeout(this.pollTimeout);
119
- };
120
-
121
- ConnectionMonitor.prototype.poll = function() {
122
- return this.pollTimeout = setTimeout((function(_this) {
123
- return function() {
124
- _this.reconnectIfStale();
125
- return _this.poll();
126
- };
127
- })(this), this.getPollInterval());
128
- };
129
-
130
- ConnectionMonitor.prototype.getPollInterval = function() {
131
- var interval, max, min, ref;
132
- ref = this.constructor.pollInterval, min = ref.min, max = ref.max;
133
- interval = 5 * Math.log(this.reconnectAttempts + 1);
134
- return Math.round(clamp(interval, min, max) * 1000);
135
- };
136
-
137
- ConnectionMonitor.prototype.reconnectIfStale = function() {
138
- if (this.connectionIsStale()) {
139
- ActionCable.log("ConnectionMonitor detected stale connection. reconnectAttempts = " + this.reconnectAttempts + ", pollInterval = " + (this.getPollInterval()) + " ms, time disconnected = " + (secondsSince(this.disconnectedAt)) + " s, stale threshold = " + this.constructor.staleThreshold + " s");
140
- this.reconnectAttempts++;
141
- if (this.disconnectedRecently()) {
142
- return ActionCable.log("ConnectionMonitor skipping reopening recent disconnect");
143
- } else {
144
- ActionCable.log("ConnectionMonitor reopening");
145
- return this.connection.reopen();
146
- }
147
- }
148
- };
149
-
150
- ConnectionMonitor.prototype.connectionIsStale = function() {
151
- var ref;
152
- return secondsSince((ref = this.pingedAt) != null ? ref : this.startedAt) > this.constructor.staleThreshold;
153
- };
154
-
155
- ConnectionMonitor.prototype.disconnectedRecently = function() {
156
- return this.disconnectedAt && secondsSince(this.disconnectedAt) < this.constructor.staleThreshold;
157
- };
158
-
159
- ConnectionMonitor.prototype.visibilityDidChange = function() {
160
- if (document.visibilityState === "visible") {
161
- return setTimeout((function(_this) {
162
- return function() {
163
- if (_this.connectionIsStale() || !_this.connection.isOpen()) {
164
- ActionCable.log("ConnectionMonitor reopening stale connection on visibilitychange. visbilityState = " + document.visibilityState);
165
- return _this.connection.reopen();
166
- }
167
- };
168
- })(this), 200);
169
- }
170
- };
171
-
172
- now = function() {
173
- return new Date().getTime();
174
- };
175
-
176
- secondsSince = function(time) {
177
- return (now() - time) / 1000;
178
- };
179
-
180
- clamp = function(number, min, max) {
181
- return Math.max(min, Math.min(max, number));
182
- };
183
-
184
- return ConnectionMonitor;
185
-
186
- })();
187
-
188
- var i, message_types, protocols, ref, supportedProtocols, unsupportedProtocol,
189
- slice = [].slice,
190
- bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
191
- indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };
192
-
193
- ref = ActionCable.INTERNAL, message_types = ref.message_types, protocols = ref.protocols;
194
-
195
- supportedProtocols = 2 <= protocols.length ? slice.call(protocols, 0, i = protocols.length - 1) : (i = 0, []), unsupportedProtocol = protocols[i++];
196
-
197
- ActionCable.Connection = (function() {
198
- Connection.reopenDelay = 500;
199
-
200
- function Connection(consumer) {
201
- this.consumer = consumer;
202
- this.open = bind(this.open, this);
203
- this.subscriptions = this.consumer.subscriptions;
204
- this.monitor = new ActionCable.ConnectionMonitor(this);
205
- this.disconnected = true;
206
- }
207
-
208
- Connection.prototype.send = function(data) {
209
- if (this.isOpen()) {
210
- this.webSocket.send(JSON.stringify(data));
211
- return true;
212
- } else {
213
- return false;
214
- }
215
- };
216
-
217
- Connection.prototype.open = function() {
218
- if (this.isActive()) {
219
- ActionCable.log("Attempted to open WebSocket, but existing socket is " + (this.getState()));
220
- throw new Error("Existing connection must be closed before opening");
221
- } else {
222
- ActionCable.log("Opening WebSocket, current state is " + (this.getState()) + ", subprotocols: " + protocols);
223
- if (this.webSocket != null) {
224
- this.uninstallEventHandlers();
225
- }
226
- this.webSocket = new ActionCable.WebSocket(this.consumer.url, protocols);
227
- this.installEventHandlers();
228
- this.monitor.start();
229
- return true;
230
- }
231
- };
232
-
233
- Connection.prototype.close = function(arg) {
234
- var allowReconnect, ref1;
235
- allowReconnect = (arg != null ? arg : {
236
- allowReconnect: true
237
- }).allowReconnect;
238
- if (!allowReconnect) {
239
- this.monitor.stop();
240
- }
241
- if (this.isActive()) {
242
- return (ref1 = this.webSocket) != null ? ref1.close() : void 0;
243
- }
244
- };
245
-
246
- Connection.prototype.reopen = function() {
247
- var error, error1;
248
- ActionCable.log("Reopening WebSocket, current state is " + (this.getState()));
249
- if (this.isActive()) {
250
- try {
251
- return this.close();
252
- } catch (error1) {
253
- error = error1;
254
- return ActionCable.log("Failed to reopen WebSocket", error);
255
- } finally {
256
- ActionCable.log("Reopening WebSocket in " + this.constructor.reopenDelay + "ms");
257
- setTimeout(this.open, this.constructor.reopenDelay);
258
- }
259
- } else {
260
- return this.open();
261
- }
262
- };
263
-
264
- Connection.prototype.getProtocol = function() {
265
- var ref1;
266
- return (ref1 = this.webSocket) != null ? ref1.protocol : void 0;
267
- };
268
-
269
- Connection.prototype.isOpen = function() {
270
- return this.isState("open");
271
- };
272
-
273
- Connection.prototype.isActive = function() {
274
- return this.isState("open", "connecting");
275
- };
276
-
277
- Connection.prototype.isProtocolSupported = function() {
278
- var ref1;
279
- return ref1 = this.getProtocol(), indexOf.call(supportedProtocols, ref1) >= 0;
280
- };
281
-
282
- Connection.prototype.isState = function() {
283
- var ref1, states;
284
- states = 1 <= arguments.length ? slice.call(arguments, 0) : [];
285
- return ref1 = this.getState(), indexOf.call(states, ref1) >= 0;
286
- };
287
-
288
- Connection.prototype.getState = function() {
289
- var ref1, state, value;
290
- for (state in WebSocket) {
291
- value = WebSocket[state];
292
- if (value === ((ref1 = this.webSocket) != null ? ref1.readyState : void 0)) {
293
- return state.toLowerCase();
294
- }
295
- }
296
- return null;
297
- };
298
-
299
- Connection.prototype.installEventHandlers = function() {
300
- var eventName, handler;
301
- for (eventName in this.events) {
302
- handler = this.events[eventName].bind(this);
303
- this.webSocket["on" + eventName] = handler;
304
- }
305
- };
306
-
307
- Connection.prototype.uninstallEventHandlers = function() {
308
- var eventName;
309
- for (eventName in this.events) {
310
- this.webSocket["on" + eventName] = function() {};
311
- }
312
- };
313
-
314
- Connection.prototype.events = {
315
- message: function(event) {
316
- var identifier, message, ref1, type;
317
- if (!this.isProtocolSupported()) {
318
- return;
319
- }
320
- ref1 = JSON.parse(event.data), identifier = ref1.identifier, message = ref1.message, type = ref1.type;
321
- switch (type) {
322
- case message_types.welcome:
323
- this.monitor.recordConnect();
324
- return this.subscriptions.reload();
325
- case message_types.ping:
326
- return this.monitor.recordPing();
327
- case message_types.confirmation:
328
- return this.subscriptions.notify(identifier, "connected");
329
- case message_types.rejection:
330
- return this.subscriptions.reject(identifier);
331
- default:
332
- return this.subscriptions.notify(identifier, "received", message);
333
- }
334
- },
335
- open: function() {
336
- ActionCable.log("WebSocket onopen event, using '" + (this.getProtocol()) + "' subprotocol");
337
- this.disconnected = false;
338
- if (!this.isProtocolSupported()) {
339
- ActionCable.log("Protocol is unsupported. Stopping monitor and disconnecting.");
340
- return this.close({
341
- allowReconnect: false
342
- });
343
- }
344
- },
345
- close: function(event) {
346
- ActionCable.log("WebSocket onclose event");
347
- if (this.disconnected) {
348
- return;
349
- }
350
- this.disconnected = true;
351
- this.monitor.recordDisconnect();
352
- return this.subscriptions.notifyAll("disconnected", {
353
- willAttemptReconnect: this.monitor.isRunning()
354
- });
355
- },
356
- error: function() {
357
- return ActionCable.log("WebSocket onerror event");
358
- }
359
- };
360
-
361
- return Connection;
362
-
363
- })();
364
-
365
- var slice = [].slice;
366
-
367
- ActionCable.Subscriptions = (function() {
368
- function Subscriptions(consumer) {
369
- this.consumer = consumer;
370
- this.subscriptions = [];
371
- }
372
-
373
- Subscriptions.prototype.create = function(channelName, mixin) {
374
- var channel, params, subscription;
375
- channel = channelName;
376
- params = typeof channel === "object" ? channel : {
377
- channel: channel
378
- };
379
- subscription = new ActionCable.Subscription(this.consumer, params, mixin);
380
- return this.add(subscription);
381
- };
382
-
383
- Subscriptions.prototype.add = function(subscription) {
384
- this.subscriptions.push(subscription);
385
- this.consumer.ensureActiveConnection();
386
- this.notify(subscription, "initialized");
387
- this.sendCommand(subscription, "subscribe");
388
- return subscription;
389
- };
390
-
391
- Subscriptions.prototype.remove = function(subscription) {
392
- this.forget(subscription);
393
- if (!this.findAll(subscription.identifier).length) {
394
- this.sendCommand(subscription, "unsubscribe");
395
- }
396
- return subscription;
397
- };
398
-
399
- Subscriptions.prototype.reject = function(identifier) {
400
- var i, len, ref, results, subscription;
401
- ref = this.findAll(identifier);
402
- results = [];
403
- for (i = 0, len = ref.length; i < len; i++) {
404
- subscription = ref[i];
405
- this.forget(subscription);
406
- this.notify(subscription, "rejected");
407
- results.push(subscription);
408
- }
409
- return results;
410
- };
411
-
412
- Subscriptions.prototype.forget = function(subscription) {
413
- var s;
414
- this.subscriptions = (function() {
415
- var i, len, ref, results;
416
- ref = this.subscriptions;
417
- results = [];
418
- for (i = 0, len = ref.length; i < len; i++) {
419
- s = ref[i];
420
- if (s !== subscription) {
421
- results.push(s);
422
- }
423
- }
424
- return results;
425
- }).call(this);
426
- return subscription;
427
- };
428
-
429
- Subscriptions.prototype.findAll = function(identifier) {
430
- var i, len, ref, results, s;
431
- ref = this.subscriptions;
432
- results = [];
433
- for (i = 0, len = ref.length; i < len; i++) {
434
- s = ref[i];
435
- if (s.identifier === identifier) {
436
- results.push(s);
437
- }
438
- }
439
- return results;
440
- };
441
-
442
- Subscriptions.prototype.reload = function() {
443
- var i, len, ref, results, subscription;
444
- ref = this.subscriptions;
445
- results = [];
446
- for (i = 0, len = ref.length; i < len; i++) {
447
- subscription = ref[i];
448
- results.push(this.sendCommand(subscription, "subscribe"));
449
- }
450
- return results;
451
- };
452
-
453
- Subscriptions.prototype.notifyAll = function() {
454
- var args, callbackName, i, len, ref, results, subscription;
455
- callbackName = arguments[0], args = 2 <= arguments.length ? slice.call(arguments, 1) : [];
456
- ref = this.subscriptions;
457
- results = [];
458
- for (i = 0, len = ref.length; i < len; i++) {
459
- subscription = ref[i];
460
- results.push(this.notify.apply(this, [subscription, callbackName].concat(slice.call(args))));
461
- }
462
- return results;
463
- };
464
-
465
- Subscriptions.prototype.notify = function() {
466
- var args, callbackName, i, len, results, subscription, subscriptions;
467
- subscription = arguments[0], callbackName = arguments[1], args = 3 <= arguments.length ? slice.call(arguments, 2) : [];
468
- if (typeof subscription === "string") {
469
- subscriptions = this.findAll(subscription);
470
- } else {
471
- subscriptions = [subscription];
472
- }
473
- results = [];
474
- for (i = 0, len = subscriptions.length; i < len; i++) {
475
- subscription = subscriptions[i];
476
- results.push(typeof subscription[callbackName] === "function" ? subscription[callbackName].apply(subscription, args) : void 0);
477
- }
478
- return results;
479
- };
480
-
481
- Subscriptions.prototype.sendCommand = function(subscription, command) {
482
- var identifier;
483
- identifier = subscription.identifier;
484
- return this.consumer.send({
485
- command: command,
486
- identifier: identifier
487
- });
488
- };
489
-
490
- return Subscriptions;
491
-
492
- })();
493
-
494
- ActionCable.Subscription = (function() {
495
- var extend;
496
-
497
- function Subscription(consumer, params, mixin) {
498
- this.consumer = consumer;
499
- if (params == null) {
500
- params = {};
501
- }
502
- this.identifier = JSON.stringify(params);
503
- extend(this, mixin);
504
- }
505
-
506
- Subscription.prototype.perform = function(action, data) {
507
- if (data == null) {
508
- data = {};
509
- }
510
- data.action = action;
511
- return this.send(data);
512
- };
513
-
514
- Subscription.prototype.send = function(data) {
515
- return this.consumer.send({
516
- command: "message",
517
- identifier: this.identifier,
518
- data: JSON.stringify(data)
519
- });
520
- };
521
-
522
- Subscription.prototype.unsubscribe = function() {
523
- return this.consumer.subscriptions.remove(this);
524
- };
525
-
526
- extend = function(object, properties) {
527
- var key, value;
528
- if (properties != null) {
529
- for (key in properties) {
530
- value = properties[key];
531
- object[key] = value;
532
- }
533
- }
534
- return object;
535
- };
536
-
537
- return Subscription;
538
-
539
- })();
540
-
541
- ActionCable.Consumer = (function() {
542
- function Consumer(url) {
543
- this.url = url;
544
- this.subscriptions = new ActionCable.Subscriptions(this);
545
- this.connection = new ActionCable.Connection(this);
546
- }
547
-
548
- Consumer.prototype.send = function(data) {
549
- return this.connection.send(data);
550
- };
551
-
552
- Consumer.prototype.connect = function() {
553
- return this.connection.open();
554
- };
555
-
556
- Consumer.prototype.disconnect = function() {
557
- return this.connection.close({
558
- allowReconnect: false
559
- });
560
- };
561
-
562
- Consumer.prototype.ensureActiveConnection = function() {
563
- if (!this.connection.isActive()) {
564
- return this.connection.open();
565
- }
566
- };
567
-
568
- return Consumer;
569
-
570
- })();
571
-
572
- module.exports = ActionCable