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

@sphinx-software/antenna

v1.2.2

Published

The react client for @sphinx-software/station

Downloads

4

Readme

@sphinx-software/antenna

Antenna

The React client for @sphinx-software/station

NPM JavaScript Style Guide

Install

npm install --save @sphinx-software/antenna

Setup

To start using this library, you'll need initialize a firebase application at first.

import React from 'react'
import firebase from 'firebase/app'
import 'firebase/firestore'
import 'firebase/auth'

const firebaseApp = firebase.initializeApp({})

Now, let's create a firestore transport

import { firestore } from '@sphinx-software/antenna'
///

export default firestore({
  firebase: firebaseApp,
  handshake: async () => {
    // Resolve to firebase custom token here.
    // Usually, you'll make an API call.
    return customToken
  },

  authorize: async (channel) => {
    // Request subscription permission to the server
  }
})

Initialize Antenna by AntennaProvider

Wrap your React application by AntennaProvider component

import { AntennaProvider } from '@sphinx-software/antenna'
import transport from './transport'

/// App component

const App = () => {

  return (
    <AntennaProvider
      transport={transport}
      fallback={<div>Signaling ...</div>}
    >
      {/* Your application code  */}
    </AntennaProvider>
  )
}

Now, you are ready to receive the signal 📡

Subscribe to a channel with useAntenna hook

import { useAntenna } from '@sphinx-software/antenna'
import React, { useEffect, useState } from 'react'

export default () => {

  const antenna = useAntenna()
  const [lastMessage, setLastMessage] = useState(null)

  useEffect(() => {
    return antenna.subscribe('channel-name', (message) => setLastMessage(message))
  }, [antenna])

  return (
    <div>
      {JSON.stringify(lastMessage)}
    </div>
  )
}

⚠️ IMPORTANT

Components using the useAntenna hook will be suspended while the antenna is handshaking to the server. Remember to wrap it with Suspense component to prevent errors.

Using the Subscription component

In real world application, you will have to manage rather complex state than the above demo. This is where the Subscription component shining.

Subscription component can automatically subscribe & unsubscribe to a channel - thanks to useEffect hook. Each subscription will have its own state, and can update the state according to the message it received. You have complete control over that state by providing a reducer to it.

Let's define your subscription reducer

// chatReducer.js
export default (state, action) => {
   switch (action.type) {
      // ...
      // When transport receives a message, it will dispatch an action with this format: { type: 'the message type', payload: { ... the message payload }}
      case 'chat.message': {
        return {
          ...state,
          unreads: [...state.unreads, action.payload],
          messages: [...state.messages, action.payload]
        }
      }

      case 'chat.join': {
        return {
          ...state,
          members: [...state.members, action.payload]
        }
      }

      case 'chat.leave': {
        return {
          ...state,
          members: state.members.filter(member => member.id !== action.payload.id)
        }
      }

      // You can certainly define your custom action type
      case 'chat.markAsRead': {
        return {
          ...state,
          unreads: state.unreads.filter(message => message.id !== action.messageId)
        }
      }
      default: return state
   }
}

Then we can provide a subscription to the channel

// Chat.js
import React, { Suspense } from 'react'
import { Subscription } from '@sphinx-software/antenna'
import chatReducer from './chatReducer'

const INITIAL_CHAT_STATE = { unreads: [], members: [], messages: [] }

export default () => {
  return (
    <Suspense fallback='...'>
        <Subscription channel='channel_chat' initialState={INITIAL_CHAT_STATE} reducer={chatReducer}>
          {/*  TODO  */}
        </Subscription>
    </Suspense>
  )
}

⚠️ IMPORTANT

Subscription component will be suspended while the antenna is handshaking to the server. Remember to wrap it with Suspense component to prevent errors.

Interacting with subscription state

You can use the useSubscription hook to interact with the subscription state

import React from 'react'
import { useSubscription } from '@sphinx-software/antenna'

const Messages = () => {
  const [ state, dispatch ] = useSubscription()
  return (
    <ul>
      {
        state.messages.map(message => {
          return (
            <li
              onClick={() => dispatch({ type: 'chat.markAsRead', messageId: message.id})}
              key={message.id}>{message.content}
            </li>
          )
        })
      }
    </ul>
  )
}

Then place your Messages component into the Subscription context:

// Chat.js
import React, { Suspense } from 'react' 
import { Subscription } from '@sphinx-software/antenna'
import chatReducer from './chatReducer'
import Messages from './Messages'

const INITIAL_CHAT_STATE = { unreads: [], members: [], messages: [] }

export default () => {
  return (
    <Suspense fallback='...'>
        <Subscription channel='channel_chat' initialState={INITIAL_CHAT_STATE} reducer={chatReducer}>
          {/*  Place your Messages component here  */}
          <Messages/>
        </Subscription>
    </Suspense>
  )
}

You also can use the Subscriber HoC to archive the same functionality

const Messages = ({ state, dispatch }) => {
  return (
    <ul>
      {
        state.messages.map(message => {
          return (
            <li
              onClick={() => dispatch({ type: 'chat.markAsRead', messageId: message.id})}
              key={message.id}>{message.content}
            </li>
          )
        })
      }
    </ul>
  )
}
// Chat.js
import React, { Suspense } from 'react' 
import { Subscription, Subscriber } from '@sphinx-software/antenna'
import chatReducer from './chatReducer'
import Messages from './Messages'

const INITIAL_CHAT_STATE = { unreads: [], members: [], messages: [] }

export default () => {
  return (
    <Suspense fallback='...'>
        <Subscription channel='channel_chat' initialState={INITIAL_CHAT_STATE} reducer={chatReducer}>
          {/*  Place your Messages component here  */}
          <Subscriber component={Messages} />
        </Subscription>
    </Suspense>
    
  )
}

Subscribe to private channel

To subscribe to a private channel, you can pass the isPrivate channel prop to the Subscription component.

// ....
<Subscription isPrivate channel='channel_chat' initialState={INITIAL_CHAT_STATE} reducer={chatReducer}>
  {/* ... */}
</Subscription>

Under the hood, if the subscription is subscribing to the private channel, antenna will trigger the authorize() callback that you have passed from the config.

While authorization process is running, the Subscription component will be suspended.

💡

Since Subscription has its state, you can consider it as a boundary of the channel data (the Subscription state). Its child component can and should be well aware about such data.

You can add as many Subscriber as you want inside a Subscription.

You can have multiple Subscription components sharing the same channel. All of them will receive messages from the channel. This approach is very useful when you want to have various ways of presenting the channel data.

That's all! Happy signaling ❤️

License

MIT © monkey-programmer