Skip to content

Instantly share code, notes, and snippets.

@bensheldon
Last active September 12, 2025 00:34
Show Gist options
  • Save bensheldon/32554d59c3ddf9a13d18c9413bed1b80 to your computer and use it in GitHub Desktop.
Save bensheldon/32554d59c3ddf9a13d18c9413bed1b80 to your computer and use it in GitHub Desktop.
# frozen_string_literal: true
module TurboPermanentCableHelper
def turbo_permanent_stream_from(*streamables, **attributes)
raise ArgumentError, "streamables can't be blank" unless streamables.any?(&:present?)
raise ArgumentError, "an id is required" if attributes[:id].blank?
attributes[:channel] = attributes[:channel]&.to_s || "Turbo::StreamsChannel"
attributes[:'signed-stream-name'] = Turbo::StreamsChannel.signed_stream_name(streamables)
attributes[:data] ||= {}
attributes[:data][:turbo_permanent] = true
tag.turbo_permanent_cable_stream_source(**attributes)
end
end
await customElements.whenDefined("turbo-cable-stream-source");
// https://github.com/hotwired/turbo-rails/blob/30cd8fcc6f82c1ad4edd1ed6069ba878f21f02b3/app/javascript/turbo/cable_stream_source_element.js
const TurboCableStreamSourceElement = customElements.get("turbo-cable-stream-source");
class TurboPermanentCableStreamSourceElement extends TurboCableStreamSourceElement {
static get observedAttributes() { return TurboCableStreamSourceElement.observedAttributes || []; }
async connectedCallback() {
if (this.disconnecting) {
this.disconnecting = false;
return;
}
return super.connectedCallback();
}
async disconnectedCallback() {
// delay the disconnect to allow a potential re-connect to occur
// and avoid performing disconnect+reconnect behavior unnecessarily
this.disconnecting = true;
await new Promise(requestAnimationFrame);
if (!this.disconnecting) return;
return super.disconnectedCallback();
}
}
if (!customElements.get("turbo-permanent-cable-stream-source")) {
customElements.define("turbo-permanent-cable-stream-source", TurboPermanentCableStreamSourceElement);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment