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

react-conversation

v1.2.1

Published

Hooks to help you build conversations between your app and the user.

Downloads

3

Readme

react-conversation

NPM

This package only includes react hooks that you can use in your own components. There are no UI components in here. Check out the example app for some 'inspiration' 😁


Installation

npm install react-conversation

Usage

Setup

Add the ConversationProvider:

ReactDOM.render(
  <ConversationProvider>
    <MyApp />
  </ConversationProvider>,
  document.getElementById('root'),
)

General message structure

// a message looks like this
const message = {
  type: 'bot', // or 'user'
  text: 'Hello world!',
  meta: {
    /* optional */
    someKey: 'some value',
  },
}

Message timestamps

The timestamps of the messages are unique and also serve as their identifier. If you send multiple messages at the same time, the timestamp of subsequent messages will be increased by one millisecond.

Example

If three messages get sent at 1595441078505 their timestamps will be the following:

| Message No. | Timestamp | | :---------: | ----------------: | | 1 | 1595441078505 | | 2 | 1595441078506 | | 3 | 1595441078507 |


Metadata

The messages can carry any form of metadata. In the examples MessageMetadata will be used as a placeholder.


Get a collection of all the messages

The messages are sorted by their respective timestamps.

const messages = useMessages<MessageMetadata>()

// the returned message collection is defined as follows
const messages = {
  // timestamp
  1595110300625: {
    /* message */
  },
  // timestamp
  1595110400845: {
    /* message */
  },
}
Only get bot messages
const botMessages = useBotMessages<MessageMetadata>()
Only get user messages
const userMessages = useUserMessages<MessageMetadata>()

Send a message

const sendMessage = useSendMessage<MessageMetadata>()

// send a bot message
sendMessage({
  type: 'bot',
  text: 'Hello human!',
  meta: {
    /* optional */
  },
})

// send a user message
sendMessage({
  type: 'user',
  text: 'Hello bot!',
  meta: {
    /* optional */
  },
})

Listen for messages

// listen for bot messages
useOnBotMessage(
  (message: MessageBot<MessageMetadata>, botState: ConversationBotState) => {
    // do something with the message
  },
)

// listen for user messages
useOnUserMessage(
  (message: MessageUser<MessageMetadata>, botState: ConversationBotState) => {
    // do something with the message
  },
)

Edit a message

It is possible to update the text or the metadata of a message (or both at the same time). You need to provide the timestamp of the message you want to edit.

const editMessage = useEditMessage<MessageMetadata>()

// update a message
editMessage(
  /* timestamp of the message you want to edit */
  1337,
  /* Partial message data */
  {
    text: 'Hello world!' /* optional */,
    meta: {
      /* optional */
    },
  },
)

React to user messages

The bot will only trigger one reaction at once.

The following is an example for a message reaction:

interface FieldMetaData {
  name: string
}

const reactToZipCode = async ({ text, meta }: Message<FieldMetaData>) => {
  const cityName = await fetchCity(text)

  if (!cityName) {
    return undefined
  }

  return {
    text: `Do you live in ${cityName}?`,
    meta: {
      suggestedCity: cityName,
    },
  }
}

const messageReactions: MessageReactionCollection<FieldMetaData> = {
  // observe the property `meta.name`
  'meta.name': {
    // react when the value of that property is zipCode
    zipCode: reactToZipCode,
  },
  // You can also observe the message text directly
  text: {
    'hello bot': () => {
      return {
        text: 'hello human',
      }
    },
  },
}

ReactDOM.render(
  <ConversationProvider>
    <MessageReactionProvider reactions={messageReactions}>
      <MyApp />
    </MessageReactionProvider>
  </ConversationProvider>,
  document.getElementById('root'),
)
Add reactions programatically
const addReaction = useAddMessageReaction()

addReaction('meta.name', 'zipCode', reactToZipCode)
Remove reactions programatically
const removeReaction = useRemoveMessageReaction()

removeReaction('meta.name', 'zipCode')

Handle bot states

At the moment it is possible for the bot to be in one of two states: idle or reacting.

| State | Description | | :--------: | -------------------------------------------------------------------------------------------------------------------------------------------------: | | idle | This is the default state of the bot. Nothing is being done in the background | | reacting | This state gets triggered as soon as the bot is reacting to a user message. The bot will return to the idle state when the reaction is finished. |

In general you should never send other bot messages when the bot is in any other state than idle. Otherwise, the order of the bot messages might be confusing.

Get the current state
const botState = useBotState()
React to state changes
useOnBotStateChange((state: ConversationBotState) => {
  // Do something when the state changed..
})

Delete messages

Delete a single message
const deleteMessage = useDeleteMessage()

// delete the message with the timestamp '1337'
deleteMessage(1337)
Delete a range of messages
const clearMessages = useClearMessages()

// delete messages starting at the timestamp '10' and ending with timestamp '50' (inclusively)
clearMessages(10, 50)

// delete messages starting at the timestamp '100' and ending with the latest message (inclusively)
clearMessages(100)

Example app

There is a small example app where you can see the hooks in action. Feel free to check out the source code to see how it works.

  1. Execute npm run build in the root directory
  2. cd example
  3. Execute npm run start
  4. Open localhost:3000 in any browser

Try to send a user message with an angry tone ;)