npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@anycable/turbo-stream

v0.7.0

Published

AnyCable Client plugin to support Turbo Streams

Downloads

10,424

Readme

npm version

AnyCable Turbo Streams

This package provides AnyCable client integration for Turbo Streams.

The default @hotwired/turbo-rails package doesn't allow you to replace the default Action Cable client with a custom consumer implementation.

🎥 You can learn more about the motivation behind the custom Turbo Streams integration from the AnyCasts episode "Using anycable-client to auto-refresh tokens"

NOTE: Make sure you're not importing @hotwired/turbo-rails or use a custom tag name: Hotwire's package registers the custom element implicitly and it's not possible to override it.

Usage

Assuming that you have a cable instance defined somewhere, to activate Turbo Streams elements you need to add the following code:

import { start } from "@anycable/turbo-stream"
// This is your cable instance
import cable from "cable"
// Explicitly activate stream source elements
start(cable)

This approach let you control when (and how) to start streaming from the <turbo-cable-stream-source> HTML elements.

No server-side changes required. We support all standard functionality: passing a custom channel class and subscription params.

Compatibility with @hotwired/turbo-rails

Our integration aims to be API compatible with the official packages, which means, HTML elements and their attributes are recognized and interpreted the same way as with @hotwired/turbo-rails.

One subtle but important difference is that @anycable/turbo-stream does not activate stream elements added to temporary Turbo cache pages. This way we avoid unnecessary subscriptions/unsubscriptions and potential race conditions.

Advanced configuration

Delayed unsubscribe

When using Turbo Drive for navigation, it's common to have a stream source element attached to the same stream to appear in both old and new HTML. In order to avoid re-subscription to the underlying stream, we can keep the subscription during navigation by postponing the unsubscribe call (or more precisely, channel.disconnect()). Thus, we can avoid unnecessary Action Cable commands and avoid losing messages arrived in-between resubscription. You must opt-in to use this features:

import { start } from "@anycable/turbo-stream"
import cable from "cable"

start(cable, { delayedUnsubscribe: true }) // default is 300ms

start(cable, { delayedUnsubscribe: 1000 }) // Custom number of milliseconds

Attaching X-Socket-ID header to Turbo requests

You can automatically add a header to all Turbo requests with the current socket session ID. This can be used to perform broadcasts to others (see Rails integration docs):

import { start } from "@anycable/turbo-stream"
import cable from "cable"

start(cable, { requestSocketIDHeader: true })

// You can also specify a custom header name
// start(cable, { requestSocketIDHeader: 'X-My-Socket-ID' })

Custom channel classes

You define a custom JS channel class for Turbo Streams subscriptions:

import { TurboChannel } from "@anycable/turbo-stream"

class CustomTurboChannel extends TurboChannel {
  // Constructor receives the current HTML element (turbo-cable-stream-source),
  // a channel name (Turbo::StreamsChannel) by default and subscription params
  constructor(element, channelName, params) {
    // You can override the server-side channel name
    super(element, 'MyTurboChannel', params)
    // Additional state configuration goes here
    this.totalActions = 0
  }

  // You can override receive function to intercept actions
  receive(message) {
    this.totalActions++

    // Ignore every second message
    if (this.totalActions % 2 === 0) return

    // Fallback to the default behaviour,
    // which sends the action to Turbo
    super.receive(message)
  }
}

Another example is a channel which logs all the actions before executing them:

class LogChannel extends TurboChannel {
  receive(message) {
    console.log("TURBO ACTION", message)
    super.receive(message)
  }
}

start(cable, {channelClass: LogChannel})

Custom tags

You can use a custom tag name for Turbo Streams source elements. One use case is to use different JS channels for different tags:

// Assuming you have some special channel class
import { TurboPresenceChannel } from './channel.js'
import { start } from "@anycable/turbo-stream"

import cable from "cable"

// Default behaviour
start(cable)

// Custom behaviour
start(cable, { tagName: 'turbo-presence-source', channelClass: TurboPresenceChannel })

NOTE: You need to create a custom Rails helper to render custom elements. For example:

def turbo_presence_stream_from(*streamables, **attributes)
  attributes[:channel] = attributes[:channel]&.to_s || "Turbo::StreamsChannel"
  attributes[:"signed-stream-name"] = Turbo::StreamsChannel.signed_stream_name(streamables)

  tag.turbo_presence_source(**attributes)
end