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

@b2chatorg/chat-center-widget-sdk

v2.0.0

Published

This is small lib that allows interoperabilty with [B2Chat Console](https://app.b2chat.io/agent/chat])

Downloads

110

Readme

@b2chatorg/chat-center-widget-sdk

This is small lib that allows interoperabilty with B2Chat Console

Getting start

Core

B2ChatStore

Installation

We recommend to use this React template to bootstrap a widget

But if you prefer use a different UI lib than React as Svelte or Vue, only need to install this package:

npm install @b2chatorg/chat-center-widget-sdk

and start the development server at 3010 port.

Usage

You can subscribe to properties.

import { getB2ChatStore } from "@b2chatorg/chat-center-widget-sdk";

/// get b2chat store instance
const store = getB2ChatStore();

// subscribe to new changes
const unsub = store.state.activeChat.subscribe((chat) => {
  console.log(chat);
});

// stop receive changes
unsub();

You can do the same with React.

import { useEffect, useState } from "react";
import { useB2ChatStore } from "@b2chatorg/chat-center-widget-sdk/dist/react";

const App = () => {
  const { state } = useB2ChatStore();

  useEffect(() => { // subscribe to new changes
    console.log(state.activeChat);
  }, [state.activeChat]);

  return (
    <div>{state.activeChat.chatId}<div>
  );
};

Core

These are utils that are available for public usage and are the core of this SDK.

EventEmitter ➡️

import { eventEmitter } from "@b2chatorg/chat-center-widget-sdk/dist/utils/eventEmitter";

const eventEmitter: <T>(start?: StartStopNotifier<T>) => EventEmitter<T>;

A function that create a minimal EventEmitter to dispatch a single event type. It is an object with dispatch and subscribe methods.

subscribe, dispatch Methods

// start: StartStopNotifier
const emitter = eventEmitter<string>();

const unsubscribe = emitter.subscribe((event) => console.log(event));

emitter.dispatch("hello"); // logs 'hello'

unsubscribe(); // unsubscribe

emitter.dispatch("world"); // does nothing

start/stop Lifecycle

start is executed just before the first subscription, it could returns a stop callback that will be executed by the emitter after the last unsubscription.

// `start` callback
const emitter = eventEmitter<string>((dispatch) => {
  console.log("first subscriber");

  // `stop` callback
  return () => console.log("no subscribers");
});

emitter.dispatch("hello"); // does nothing

const unsub = emitter.subscribe((event) => {
  console.log(event);
}); // logs `first subscriber`;

emitter.dispatch("hello"); // logs 'hello'

unsub(); // will exec `stop` callback and logs 'no subscribers'

Writable

export const writable = <T>(
  initialValue: T,
  start?: StartStopNotifier<T>,
  equalFn: EqualFn<T> = strictEquals
) => Writable<T>;

It creates a mutable value observable

Usage

subscribe, get, set and update

import { writable } from "@b2chatorg/chat-center-widget-sdk/dist/utils/store";

const count = writable<number>(0);

const unsub = count.subscribe((value) => console.log(value));

count.set(2); // logs '1'
console.log(count.get()); // logs '1'

count.update((current) => current + 1); // increments count and logs '2'

unsub(); // unobserve count

when(predicate)

It waits for condition to be fulfill

const counter = writable(0, (set, update) => {
  const interval = setInterval(() => {
    update(val => val + 1)
  }, 1000)

  return () => clearInterval(interval)
});

async waitUntil10() {
  await counter.when(val => val === 10)
  console.log('10 reached!')
}

waitUntil10()

Readable

export const readable = <T>(
  initialValue: T,
  start?: StartStopNotifier<T>,
  equalFn: EqualFn<T> = strictEquals
): Readable<T> => writable(initialValue, start, equalFn);

Similar to a Writable but it is a non-mutable observable

Example:

import { readable } from "@b2chatorg/chat-center-widget-sdk/dist/utils/store";

const ticktock = readable("tick", (set, update) => {
  const interval = setInterval(() => {
    update((sound) => (sound == "tick" ? "tock" : "tick"));
  }, 1000);

  return () => clearInterval(interval);
});

const unsub = ticktock.subscribe((value) => console.log(value)); // logs 'tick' or 'tock' each seg

unsub(); // unobserve tictock and stop ticktock

React Hook UseAsyncFunction

const useAsyncFunction = <
  Fn extends (...args: any[]) => Promise<any>,
  E = Error
>(
  fn: Fn,
  initialResult?: Awaited<ReturnType<Fn>>
) => UseAsyncFunctionInstance<Fn, E>;

type UseAsyncFunctionInstance<
  Fn extends (...args: any[]) => Promise<any>,
  E = unknown
> = {
  args: Parameters<Fn> | [];
  result: Awaited<ReturnType<Fn>>;
  error: E;
  isPending: boolean;
  isSuccess: true;
  isError: false;
};

This is a React hook to manage async calls, it takes a async fn and optionally an initialResult to use as initial value for result prop

Usage

import useAsyncFunction from "@b2chatorg/chat-center-widget-sdk/dist/react/useAsyncFunction";

const doLogin = async (user: string) => {
  await new Promise(r => setTimeout(r, 2000)); // wait 2 seg

  if (user === "david") return { user };

  throw new Error("Unknown user");
};

const App = () => {
  const login = useAsyncFunction(doLogin);

  useEffect(() => {
    login('david')
  }, [])

  return (
    <div>
      {login.isPending & "loading..."}
      {login.isSuccess && (<div>Login success: {login.result.user}<div>)}
      {login.isError && (<div>Login failed: {login.error.message}<div>)}
    </div>
  );
};

B2ChatStore

B2ChatStore is simply a set of properties, events and methods that allow subscribe, listen or take actions inside the B2Chat console. It is agnostic to any UI library but there are some pretty easy utils to work with React.

JS vanilla

import { getB2ChatStore } from "@b2chatorg/chat-center-widget-sdk";

/// get b2chat store instance
const store = getB2ChatStore();

// subscribe to new changes
const unsub = store.state.activeChat.subscribe((chat) => {
  console.log(chat);
});

// stop receive changes
unsub();

const result = await store.methods.findChat({ contactName: "foo" }); // find a chat in the current tray

With React library

import { useEffect, useState } from "react";
import { useB2ChatStore } from "@b2chatorg/chat-center-widget-sdk/dist/react";

const App = () => {
  const { state } = useB2ChatStore();

  useEffect(() => { // subscribe to new changes
    console.log(state.activeChat);
  }, [state.activeChat]);

  return (
    <div>{state.activeChat.chatId}<div>
  );
};

Properties

activeChat: Readable<Chat>

It contains the Chat actually selected by the agent.

Example

const { state } = getB2ChatStore();
state.activeChat.subscribe((activeChat) => {
  console.log(activeChat.chatId);
});

// or with React
const App = () => {
  const { state } = useB2ChatStore();
  return <div>{state.activeChat.chatId}</div>;
};

agentInfo: Readable<AgentInfo>

It has the basic information about the agent and the departments which it belongs. If you want to search for an specific chat use : findChat

Example

const { state } = getB2ChatStore();
state.agentInfo.subscribe((agentInfo) => {
  console.log(agentInfo.username);
});

// or with React
const App = () => {
  const { state } = useB2ChatStore();
  return <div>{state.agentInfo.username}</div>;
};

departments: Readable<Department[]>

It has the list the all posible departments for this merchant

Example

const { state } = getB2ChatStore();
state.departments.subscribe((departments) => {
  departments.forEach((item) => console.log(item.tagName));
});

// or with React
const App = () => {
  const { state } = useB2ChatStore();
  return (
    <>
      {state.departments.map((item) => (
        <div>{item.tagName}</div>
      ))}
    </>
  );
};

inputMessageContent: InputMessageContent

It has the console input message. See setInputMessageContent to modify its value

Example

const { state } = getB2ChatStore();
state.inputMessageContent.subscribe((content) => {
  console.log(content.chatId, content.text);
});

// or with React
const App = () => {
  const { state } = useB2ChatStore();
  return <div>{state.inputMessageContent.text}</div>;
};

Events

onChatClosed: Emitter

event emitted when a chat is closed wether by agent or contact

Methods

findChat: (query: FindChatQuery) => Promise<FindChatResponse>

Find a chat by name, chatId or tags.

The query can be omitted to traverse through all chats

const { methods } = getB2ChatStore();
const response = await findChat({ contactName: "jean", limit: 10 });
console.log(response.data);

Types

All types related to B2Chat are available at:

import {...} from "@b2chatorg/chat-center-widget-sdk/dist/types";

Please take a look to all types.