Skip to content
KnockDevelopers
Chat

Build your own chat UI

Draw the Knock chat with your own UI (headless). The rules your UI must follow, Continue on Telegram or Slack, the client's types, and complete examples in TypeScript and React.

Chat with a Developer

With headless, Knock draws nothing. Your page gets the conversation as a client, and your UI draws it. Knock downloads only the conversation: no React, no styles and no fonts.

To see one working, open the playground and pick Your own UI, Eagle or Ask bar. The Ask bar is a prompt bar at the foot of the page: it calls knock.chat.open() when it expands into the chat and knock.chat.close() when it collapses, so replies that come while it is collapsed count in unread.

The rules

Follow all of them. A UI that skips rule 3 shows an empty chat to a new visitor.

  1. Set headless in init({ chat }), once, at app start. It must be set before the chat loads. Set after Knock's own UI has loaded, it only prints a warning, and Knock's UI stays.
  2. Keep the client. Knock calls your function once, when the chat has loaded, after your Knock tag is ready. Until then you have no client: show your launcher, or nothing.
  3. Call knock.chat.open() when your UI shows the chat, and knock.chat.close() when it hides it.
    • open() starts the conversation. On first use it identifies the visitor, connects, and brings the greeting. It also sets unread to 0.
    • Calling open() again while the chat is open is safe.
    • While your UI is hidden, new replies from the agent or a rep count in unread.
    • A UI that is always on screen calls open() once, when it mounts.
  4. Draw from getState(), and draw again in subscribe(). getState() returns the same object until something changes, so you can compare with ===. In React, use it with useSyncExternalStore.
  5. Send with send(text). It returns false and sends nothing when the text is blank, longer than 4,000 characters, or status is 'unavailable'. Keep the visitor's text when it returns false.
  6. Show the starters. Starters are suggested first messages that you set yourself: starters in init({ chat }), up to 4. Knock does not send any. While state.starters is not empty, show each one as a button. A click sends it: send(starter). The list is empty after the visitor's first message.
  7. Draw each part by its type, and skip a type you do not know. Later versions can add types.
  8. Never insert text as raw HTML. Text from the agent and from reps is Markdown: render it with a Markdown library and sanitize the result. Text from the visitor is plain text.
  9. Call resolveAction(id) inside the visitor's click. An action can open a booking page or an app, and the browser blocks a page that opens outside a click. Call it directly in the click handler, with no await before it, and never from an effect. The client opens the tab before its own first await. id is the id of an action, the actionId of a continueOn option, or continuedOn.actionId.
  10. Group messages by author. Consecutive messages from the same person belong together: compare author with ===. A long reply can arrive as more than one message.
  11. Offer the apps in continueOn. Draw a button for each option whose channel you know (telegram or slack), and skip any other. Pass its actionId to resolveAction() as it is. Allow one tap at a time: disable the buttons until the Promise settles. The client does not stop a second tap, and each tap gets a new link and opens a tab. Draw no app buttons once continuedOn is set: draw the app it continued on, as the way back to it. See Continue on Telegram or Slack.

What to draw

From the stateWhat it meansWhat to draw
status: 'connecting'The visitor's history is loadingA loader
status: 'reconnecting'The live connection dropped. Messages still go and comeA quiet note, or nothing
status: 'unavailable'The chat is off, or blocked on this siteA short message. Hide the message box
status: 'ready'Everything elseThe conversation
typing not nullThe agent or a rep is typing"typing.name is typing"
unread above 0Replies that arrived while your UI was hiddenA badge on your launcher
message.status: 'sending'Knock does not have the visitor's message yetThe message, dimmed
message.status: 'failed'Knock gave up on the visitor's messageA Retry button: retry(message.id)
message.editedA rep edited the message"edited"
author.kind'visitor', 'agent' or 'rep'The visitor's messages on one side, the rest on the other
author.name, author.imageUrlThe agent's or the rep's name and picture. null for the visitorA name and an avatar
continueOn not emptyThe apps the visitor can continue the chat on, in Knock's orderA button per app that you know
continuedOn not nullThe visitor arrived on that app. The chat goes on in both places"Continued on Telegram" as the way back to the app, and no app buttons
Part typeIts fieldsWhat to draw
'text'textMarkdown for the agent and reps, plain text for the visitor
'image'url (http or https), altAn image
'actions'actions: each has id, label, primary and kindA button per action. Style primary ones as the main button. kind is 'book-a-meeting' today: draw a kind you do not know as a plain button
'joined'None"author.name joined": a rep joined the conversation here

Continue on Telegram or Slack

Knock can let the visitor continue the chat on Telegram, or on Slack in a workspace Knock runs. The visitor goes on there as the same contact, and gets a short recap of the website chat. Knock decides which apps to offer: see Before you start. With your own UI, you draw the apps.

From the stateWhat it meansWhat to draw
continueOnThe apps the visitor can continue on, in Knock's order: Telegram, then Slack. Each option has a channel and an actionIdA button per option whose channel you know. A tap calls resolveAction(option.actionId)
continuedOnnull until the visitor arrives on an app. Then the app's channel, and at, when they arrived, in ms since the epoch. channel and at never change after that"Continued on Telegram". No app buttons
continuedOn.actionIdThe way back to the app when it needs Knock's sign-in: 'continue:slack' on Slack. null on Telegram, whose url needs no sign-in. Also null on Slack 30 days after the visitor continuedWhen it is set, a button. Its tap calls resolveAction(continuedOn.actionId), as a tap on an app does
continuedOn.urlA link that opens the app. It holds no sign-in code. For Telegram, it opens your bot. For Slack, it opens the visitor's channel in a browser that is signed in to Slack, and another browser gets the sign-in page of Knock's Slack workspace. url can be null at first, mostly on Slack, and get a link in a later stateWhen actionId is null, a link that opens in a new tab. When url is also null, show the name only. Draw it from the current state each time

resolveAction() returns a Promise of what happened, a KnockChatActionResult:

ResultWhat happenedWhat to draw
openedThe app's page opened in a new tabNothing more. continuedOn follows when the visitor arrives on the app. After a tap before the visitor's first message, it never comes: that tap opened the app's plain link
blockedThe browser opened no tab. In an in-app browser, this is always the resultA "Tap to open Telegram" button that calls open() in a later click. Remove it at expiresAt, in ms: at most 15 minutes after the tap, and null means no end. After that, open() does nothing. In an in-app browser, open() can open the app's page in place of yours
failed with not-offeredKnock no longer offers the app. It left continueOn"Telegram isn't available right now."
failed with continuedThe chat already continued on that app. On the way back, Slack's 30 days endedNothing: the state follows. On the way back, continuedOn.actionId is null then, so draw the link
failed with rate-limited, session-ended or networkToo many taps (rate-limited). The visitor's session ended, and the error event fires (session-ended). Knock did not answer, or not within 20 seconds (network)"Couldn't open Telegram. Try again."
  • Read a reason that you do not know as network.
  • The state has no field for "Waiting for you on Telegram", which Knock's UI shows between the tap and continuedOn. To show it, keep the wait yourself. Start it at opened when the visitor has sent a message, or in the click that calls a blocked result's open() when its expiresAt is not null. Before the visitor's first message, the tap opened the plain link, so there is nothing to wait for. Show the wait until continuedOn is set, or for 15 minutes after the tap. To keep the wait across a page reload, store the tap time. The examples below leave the wait out.
  • A booking action resolves only with opened or failed.
  • The way back on Slack (continuedOn.actionId) signs the visitor back in to their channel in the Slack workspace Knock runs. It works in any browser that has the chat. Each tap gets a new link that works once, for 15 minutes, and its results are those of a tap on an app. It does not send a recap again.
  • Knock does not sign the browser in when the visitor's Slack account also has conversations with another company. The tap still opens Slack, and the visitor may need to sign in there.
  • Once the chat continued, the visitor's messages on the app and the replies there arrive in messages, like any other message. Nothing marks the app they came from.
  • A message that the visitor sends from your UI stays on the website. It does not go to the app. A rep's reply from your team's Slack card goes to both places.
  • The recap never arrives in messages. Knock sends it to the visitor on the app only.
  • Knock still writes the tab that a tap opens ("Opening Telegram…"), also under your UI. strings and locale set its words, and the language Knock gets with each tap: see Change the words and the language of "Continue on".
  • The examples below draw the apps. To try them, see Build it in test mode.

Open the chat from your page

  • Your own launcher: show your panel, then call knock.chat.open().
  • A first message: knock.chat.open({ send: 'I want a demo' }) sends it for the visitor, once per conversation.
  • Another magic link: knock.chat.open({ magicLinkId: 'ANOTHER_LINK_ID' }) moves the chat to that link. Each link has its own conversation.
  • A page element: an element with data-knock-chat calls open() when the visitor clicks it. Add data-knock-send to send a first message. Use a plain <button> or <a href>: the chat leaves a click alone when your code or your router calls preventDefault().
  • Show your panel whenever the chat opens: when something other than your launcher calls open() (a data-knock-chat element, or knock.chat.open() elsewhere in your code), listen for it and show your panel: knock.on('chat:open', showPanel) and knock.on('chat:close', hidePanel). Each fires once per change.

Headless ignores the options that only change Knock's UI: skin, launcher, screens, container, setSkin(), resetSkin(), and open({ message, screen }). Each one prints a console warning. strings and locale still apply: they set the words of the tab that a tap on an app opens, and the language Knock gets with each tap.

The client's types

These types ship in @knock-ai/sdk. The types of Continue on Telegram or Slack (continueOn, continuedOn, KnockChatContinueOption, KnockChatContinuedOn and KnockChatActionResult) need 0.1.5 or later: in 0.1.4, resolveAction() returns void. Import them with import type { ... } from '@knock-ai/sdk'.

The headless client
interface KnockChatClient {
  /** The conversation now. The same object until something in it changes. */
  getState(): KnockChatConversation;
  /** Calls `listener` once after each change. Returns a function that stops it. */
  subscribe(listener: () => void): () => void;
  /** Sends a visitor message. False when blank, over 4,000 characters, or 'unavailable'. */
  send(text: string): boolean;
  /** Sends a 'failed' visitor message again. */
  retry(messageId: string): void;
  /** Runs an action of an 'actions' part, the actionId of a continueOn option, or continuedOn.actionId. Call it inside the visitor's click. */
  resolveAction(actionId: string): Promise<KnockChatActionResult>;
}

interface KnockChatConversation {
  status: 'ready' | 'connecting' | 'reconnecting' | 'unavailable';
  messages: readonly KnockChatMessage[];
  /** Who is typing: the agent or a rep. */
  typing: KnockChatPerson | null;
  /** Suggested first messages. Empty after the visitor's first message. */
  starters: readonly string[];
  /** Replies from the agent or a rep that arrived while your UI was hidden. */
  unread: number;
  /** The apps the visitor can continue on, in Knock's order. Empty when there are none. */
  continueOn: readonly KnockChatContinueOption[];
  /** The app the chat continued on, once the visitor arrived there. The chat goes on here too. */
  continuedOn: KnockChatContinuedOn | null;
}

interface KnockChatContinueOption {
  /** 'telegram' or 'slack' today. Skip any other. */
  channel: string;
  /** Pass it to resolveAction() as it is. */
  actionId: string;
}

interface KnockChatContinuedOn {
  channel: string;
  /** When the visitor arrived on the app, in ms since the epoch. */
  at: number;
  /** Opens the app. It holds no sign-in code. null when there is no link to give. */
  url: string | null;
  /** The way back when it needs Knock's sign-in (Slack): pass it to resolveAction() inside the click. null: open url. */
  actionId: string | null;
}

/** What resolveAction() did. */
type KnockChatActionResult =
  | { status: 'opened' }
  /** The browser opened no tab. Call open() in a later click, until expiresAt (ms; null: no end). */
  | { status: 'blocked'; open(): void; expiresAt: number | null }
  /** Nothing opened. Read a reason you do not know as 'network'. */
  | { status: 'failed'; reason: 'not-offered' | 'continued' | 'rate-limited' | 'session-ended' | 'network' };

interface KnockChatMessage {
  /** Stable. A visitor message keeps its id from 'sending' to 'sent'. */
  id: string;
  /** Within one state the same person is the same object: group with ===. */
  author: KnockChatPerson;
  /** Sent at, in ms since the epoch. */
  at: number;
  parts: readonly KnockChatPart[];
  /** Visitor messages: 'sending', then 'sent' or 'failed'. Every other message: 'sent'. */
  status: 'sending' | 'sent' | 'failed';
  /** A rep edited it. */
  edited: boolean;
}

type KnockChatPart =
  | { type: 'text'; text: string }
  | { type: 'image'; url: string; alt: string }
  | { type: 'actions'; actions: readonly KnockChatAction[] }
  | { type: 'joined' };

interface KnockChatAction {
  id: string;
  label: string;
  primary: boolean;
  /** 'book-a-meeting' today. */
  kind: string;
}

interface KnockChatPerson {
  kind: 'visitor' | 'agent' | 'rep';
  /** null for the visitor. */
  name: string | null;
  imageUrl: string | null;
}

Example: TypeScript, no framework

This page has a launcher button, a panel, a message list, the apps to continue on and a form. The form stays in the page: the code only redraws the list and the buttons, so the input keeps its focus and its text.

index.html
<button id="chat-launcher">Chat <span id="chat-unread" hidden></span></button>
<section id="chat-panel" hidden>
  <header>
    <span id="chat-continued" hidden></span>
    <button id="chat-close">Close</button>
  </header>
  <p id="chat-status" hidden></p>
  <ol id="chat-log"></ol>
  <div id="chat-starters"></div>
  <div id="chat-apps"></div>
  <p id="chat-note" role="status"></p>
  <p id="chat-typing" hidden></p>
  <form id="chat-form">
    <input id="chat-input" autocomplete="off" placeholder="Write a message" />
    <button type="submit">Send</button>
  </form>
</section>
chat.ts
import { knock } from '@knock-ai/sdk';
import type { KnockChatClient, KnockChatContinueOption, KnockChatConversation, KnockChatPart } from '@knock-ai/sdk';

const $ = <T extends HTMLElement>(id: string) => document.getElementById(id) as T;
const panel = $('chat-panel');
const log = $<HTMLOListElement>('chat-log');
const form = $<HTMLFormElement>('chat-form');
const input = $<HTMLInputElement>('chat-input');
let chat: KnockChatClient | null = null;

// Continue on: the apps this UI knows, and the state of a tap.
const APPS: Record<string, string> = { telegram: 'Telegram', slack: 'Slack' };
let tapping = false;
let tapToOpen: { name: string; open(): void } | null = null;
let tapToOpenTimer: ReturnType<typeof setTimeout> | undefined;
let note = '';

knock.init({
  tagId: 'YOUR_TAG_ID',
  chat: {
    magicLinkId: 'YOUR_MAGIC_LINK_ID',
    starters: ['What does Knock do?', 'Can I see a demo?'],
    headless(client) {
      chat = client;
      client.subscribe(() => render(client.getState()));
      render(client.getState());
    },
  },
});

function redraw(): void {
  if (chat) render(chat.getState());
}

// Rule 3: tell Knock when your UI shows and hides the chat.
$('chat-launcher').addEventListener('click', () => {
  panel.hidden = false;
  knock.chat.open();
  input.focus();
});
$('chat-close').addEventListener('click', () => {
  panel.hidden = true;
  knock.chat.close();
});

form.addEventListener('submit', (event) => {
  event.preventDefault();
  if (chat?.send(input.value)) input.value = ''; // keep the text when send() returns false
});

function render(state: KnockChatConversation): void {
  const unread = $('chat-unread');
  unread.hidden = state.unread === 0;
  unread.textContent = String(state.unread);

  const status = $('chat-status');
  status.hidden = state.status === 'ready';
  status.textContent =
    state.status === 'connecting' ? 'Loading…' : state.status === 'reconnecting' ? 'Reconnecting…' : 'Chat is not available.';
  form.hidden = state.status === 'unavailable';

  log.replaceChildren();
  let lastAuthor: unknown = null;
  for (const message of state.messages) {
    const item = document.createElement('li');
    item.className = `from-${message.author.kind}`;
    if (message.author !== lastAuthor && message.author.name) {
      item.append(Object.assign(document.createElement('strong'), { textContent: message.author.name }));
    }
    lastAuthor = message.author;
    for (const part of message.parts) {
      const node = drawPart(part, message.author.name);
      if (node) item.append(node);
    }
    if (message.edited) item.append(' (edited)');
    if (message.status === 'sending') item.style.opacity = '0.6';
    if (message.status === 'failed') {
      const retry = Object.assign(document.createElement('button'), { textContent: 'Retry' });
      retry.onclick = () => chat?.retry(message.id);
      item.append(retry);
    }
    log.append(item);
  }

  const starters = $('chat-starters');
  starters.replaceChildren(
    ...state.starters.map((starter) => {
      const button = Object.assign(document.createElement('button'), { textContent: starter });
      button.onclick = () => chat?.send(starter);
      return button;
    }),
  );

  drawApps(state);

  const typing = $('chat-typing');
  typing.hidden = !state.typing;
  typing.textContent = state.typing ? `${state.typing.name ?? 'Someone'} is typing…` : '';
}

// Rule 11: the apps of continueOn, until the chat continued on one. Then the way back to that app.
function drawApps(state: KnockChatConversation): void {
  const apps = $('chat-apps');
  apps.replaceChildren();
  $('chat-note').textContent = note;

  const continued = $('chat-continued');
  const done = state.continuedOn;
  continued.hidden = !done;
  continued.replaceChildren();
  if (done) {
    const name = APPS[done.channel] ?? done.channel;
    const label = `Continued on ${name}`;
    const { actionId, url } = done;
    if (actionId) {
      // Slack: Knock signs the visitor back in. A tap works as a tap on an app.
      const back = Object.assign(document.createElement('button'), { textContent: label, disabled: tapping });
      back.onclick = () => tapApp({ channel: done.channel, actionId }, name);
      continued.append(back);
    } else {
      // Telegram: the url opens your bot. It holds no sign-in code. When it is null, show the name only.
      const link = url && Object.assign(document.createElement('a'), { href: url, target: '_blank', rel: 'noopener', textContent: label });
      continued.append(link || label);
    }
  } else {
    for (const option of state.continueOn) {
      const name = APPS[option.channel];
      if (!name) continue; // an app this UI does not know
      const button = Object.assign(document.createElement('button'), { textContent: name, disabled: tapping });
      button.onclick = () => tapApp(option, name);
      apps.append(button);
    }
  }
  if (tapToOpen) {
    const { name, open } = tapToOpen;
    const button = Object.assign(document.createElement('button'), { textContent: `Tap to open ${name}` });
    button.onclick = () => {
      open(); // inside this click
      tapToOpen = null;
      redraw();
    };
    apps.append(button);
  }
}

function tapApp(option: KnockChatContinueOption, name: string): void {
  if (!chat || tapping) return; // one tap at a time: each tap gets a new link and opens a tab
  const result = chat.resolveAction(option.actionId); // rule 9: in the click, with no await before it
  tapping = true;
  tapToOpen = null;
  clearTimeout(tapToOpenTimer);
  note = '';
  redraw();
  void result.then((outcome) => {
    tapping = false;
    if (outcome.status === 'blocked') {
      tapToOpen = { name, open: outcome.open };
      // "Tap to open" goes at expiresAt. null: no end.
      const until = outcome.expiresAt;
      if (until !== null) tapToOpenTimer = setTimeout(() => { tapToOpen = null; redraw(); }, until - Date.now());
    }
    if (outcome.status === 'failed' && outcome.reason !== 'continued') {
      note = outcome.reason === 'not-offered' ? `${name} isn't available right now.` : `Couldn't open ${name}. Try again.`;
    }
    redraw(); // 'opened': continuedOn follows when the visitor arrives on the app
  });
}

function drawPart(part: KnockChatPart, authorName: string | null): Node | null {
  switch (part.type) {
    case 'text':
      // Plain text is always safe. For Markdown, see "Markdown" below.
      return Object.assign(document.createElement('p'), { textContent: part.text });
    case 'image':
      return Object.assign(document.createElement('img'), { src: part.url, alt: part.alt });
    case 'actions': {
      const row = document.createElement('div');
      for (const action of part.actions) {
        const button = Object.assign(document.createElement('button'), { textContent: action.label });
        if (action.primary) button.className = 'primary';
        button.onclick = () => void chat?.resolveAction(action.id); // rule 9: inside the click
        row.append(button);
      }
      return row;
    }
    case 'joined':
      return Object.assign(document.createElement('em'), { textContent: `${authorName ?? 'A rep'} joined` });
    default:
      return null; // rule 7: skip a type you do not know
  }
}

Example: React

Call init() once at app start, in a client module. A small store hands the client to your components.

knock-chat.ts
'use client';
import { useSyncExternalStore } from 'react';
import { knock } from '@knock-ai/sdk';
import type { KnockChatClient, KnockChatConversation } from '@knock-ai/sdk';

let client: KnockChatClient | null = null;
const listeners = new Set<() => void>();
const notify = () => listeners.forEach((listener) => listener());

knock.init({
  tagId: 'YOUR_TAG_ID',
  chat: {
    magicLinkId: 'YOUR_MAGIC_LINK_ID',
    starters: ['What does Knock do?', 'Can I see a demo?'],
    headless(chat) {
      client = chat;
      chat.subscribe(notify);
      notify();
    },
  },
});

function subscribe(listener: () => void) {
  listeners.add(listener);
  return () => {
    listeners.delete(listener);
  };
}

/** The conversation, or null until the chat has loaded. */
export function useKnockChat(): { chat: KnockChatClient | null; state: KnockChatConversation | null } {
  const state = useSyncExternalStore(subscribe, () => client?.getState() ?? null, () => null);
  return { chat: client, state };
}
ChatPanel.tsx
'use client';
import { useEffect, useRef, useState } from 'react';
import { knock } from '@knock-ai/sdk';
import { useKnockChat } from './knock-chat';
import type { KnockChatClient, KnockChatContinuedOn, KnockChatContinueOption, KnockChatConversation } from '@knock-ai/sdk';

const APPS: Record<string, string> = { telegram: 'Telegram', slack: 'Slack' };

/** Render it only while the panel is on screen: it opens the chat when it mounts and closes it when it unmounts. */
export function ChatPanel() {
  const { chat, state } = useKnockChat();
  const [text, setText] = useState('');

  useEffect(() => {
    knock.chat.open(); // rule 3
    return () => knock.chat.close();
  }, []);

  if (!chat || !state) return <p>Loading…</p>;
  if (state.status === 'unavailable') return <p>Chat is not available.</p>;

  return (
    <section>
      <ContinueOn chat={chat} state={state} />
      {state.status !== 'ready' && <p>{state.status === 'connecting' ? 'Loading…' : 'Reconnecting…'}</p>}
      <ol>
        {state.messages.map((message, i) => (
          <li key={message.id} className={`from-${message.author.kind}`} style={{ opacity: message.status === 'sending' ? 0.6 : 1 }}>
            {message.author.name && message.author !== state.messages[i - 1]?.author && <strong>{message.author.name}</strong>}
            {message.parts.map((part, j) => {
              switch (part.type) {
                case 'text':
                  return <p key={j}>{part.text}</p>;
                case 'image':
                  return <img key={j} src={part.url} alt={part.alt} />;
                case 'actions':
                  return (
                    <div key={j}>
                      {part.actions.map((action) => (
                        <button key={action.id} className={action.primary ? 'primary' : undefined} onClick={() => void chat.resolveAction(action.id)}>
                          {action.label}
                        </button>
                      ))}
                    </div>
                  );
                case 'joined':
                  return <em key={j}>{message.author.name ?? 'A rep'} joined</em>;
                default:
                  return null;
              }
            })}
            {message.edited && <small> (edited)</small>}
            {message.status === 'failed' && <button onClick={() => chat.retry(message.id)}>Retry</button>}
          </li>
        ))}
      </ol>
      {state.starters.map((starter) => (
        <button key={starter} onClick={() => chat.send(starter)}>
          {starter}
        </button>
      ))}
      {state.typing && <p>{state.typing.name ?? 'Someone'} is typing…</p>}
      <form
        onSubmit={(event) => {
          event.preventDefault();
          if (chat.send(text)) setText('');
        }}
      >
        <input value={text} onChange={(event) => setText(event.target.value)} placeholder="Write a message" />
        <button type="submit">Send</button>
      </form>
    </section>
  );
}

/** Rule 11: a button per app this UI knows, one tap at a time. Once the chat continued, the way back to that app. */
function ContinueOn({ chat, state }: { chat: KnockChatClient; state: KnockChatConversation }) {
  const busy = useRef(false);
  const [tapping, setTapping] = useState(false);
  const [note, setNote] = useState<string | null>(null);
  const [tapToOpen, setTapToOpen] = useState<{ name: string; open(): void; expiresAt: number | null } | null>(null);

  // "Tap to open" goes at expiresAt. null: no end.
  useEffect(() => {
    const until = tapToOpen?.expiresAt;
    if (until == null) return;
    const timer = setTimeout(() => setTapToOpen(null), until - Date.now());
    return () => clearTimeout(timer);
  }, [tapToOpen]);

  function tap(option: KnockChatContinueOption, name: string) {
    if (busy.current) return; // each tap gets a new link and opens a tab
    busy.current = true;
    const result = chat.resolveAction(option.actionId); // rule 9: in the click, with no await before it
    setTapping(true);
    setNote(null);
    setTapToOpen(null);
    void result.then((outcome) => {
      busy.current = false;
      setTapping(false);
      if (outcome.status === 'blocked') setTapToOpen({ name, open: outcome.open, expiresAt: outcome.expiresAt });
      if (outcome.status === 'failed' && outcome.reason !== 'continued') {
        setNote(outcome.reason === 'not-offered' ? `${name} isn't available right now.` : `Couldn't open ${name}. Try again.`);
      }
    });
  }

  const continued = state.continuedOn;
  return (
    <div>
      {continued ? (
        <ContinuedOn continued={continued} tapping={tapping} tap={tap} />
      ) : (
        state.continueOn.map((option) => {
          const name = APPS[option.channel];
          if (!name) return null; // an app this UI does not know
          return (
            <button key={option.actionId} disabled={tapping} onClick={() => tap(option, name)}>
              {name}
            </button>
          );
        })
      )}
      {tapToOpen && (
        <button
          onClick={() => {
            tapToOpen.open(); // inside this click
            setTapToOpen(null);
          }}
        >
          Tap to open {tapToOpen.name}
        </button>
      )}
      {note && <p role="status">{note}</p>}
    </div>
  );
}

/** "Continued on Slack": on Slack a tap signs the visitor back in, on Telegram the url opens your bot. */
function ContinuedOn({ continued, tapping, tap }: {
  continued: KnockChatContinuedOn;
  tapping: boolean;
  tap(option: KnockChatContinueOption, name: string): void;
}) {
  const name = APPS[continued.channel] ?? continued.channel;
  const label = `Continued on ${name}`;
  const { actionId, url } = continued;
  if (actionId) {
    return (
      <button disabled={tapping} onClick={() => tap({ channel: continued.channel, actionId }, name)}>
        {label}
      </button>
    );
  }
  // The url holds no sign-in code. When it is null, show the name only.
  return url ? (
    <a href={url} target="_blank" rel="noopener">
      {label}
    </a>
  ) : (
    <span>{label}</span>
  );
}

Markdown

Text from the agent and from reps is Markdown: lists, links and bold text, for example. Render it with a Markdown library, then sanitize the HTML before you insert it. For example, with marked and DOMPurify:

Markdown, sanitized
import { marked } from 'marked';
import DOMPurify from 'dompurify';

const html = DOMPurify.sanitize(marked.parse(part.text, { async: false }));

Do this only for author.kind 'agent' or 'rep'. Draw the visitor's own text as plain text.

Build it in test mode

In test mode the chat plays a scripted conversation, and nothing goes to Knock. It needs no magic link and no allowed origin.

Test mode
knock.init({ tagId: 'YOUR_TAG_ID', chat: { test: true, starters: ['What does Knock do?'], headless(chat) { /* as above */ } } });

test: true runs the 'default' scenario. test also takes a scenario name, to try one situation: 'default', 'returning', 'rep', 'booking', 'media', 'edited', 'send-fails', 'rate-limited', 'session-expired', 'offline', 'no-stream', 'disabled', 'origin-blocked' and 'captcha'. Check your UI with 'rep' (a rep joins), 'booking' (an action), 'media' (an image), 'send-fails' (Retry) and 'disabled' (unavailable).

Every scenario offers Telegram and Slack in continueOn, except those where the chat cannot load: offline, disabled, origin-blocked and captcha. In the others:

  • A tap resolves with opened, and opens nothing.
  • Before the visitor's first message, continuedOn never comes, as in your live chat.
  • After it, continuedOn is set 2 seconds after the tap, and continueOn is empty. Its url leads nowhere.
  • Continued on Slack, continuedOn.actionId is 'continue:slack'. A tap on it resolves with opened, and opens nothing.
  • Continued on Telegram, continuedOn.actionId is null. resolveAction('continue:telegram') then resolves with failed and continued.
  • Test mode cannot give blocked: a tap there always resolves with opened. To see blocked, use your live chat on a magic link that offers an app, in a browser with pop-ups blocked for your site or in an in-app browser.

Before you ship

  • headless is set in init(), and your function keeps the client.
  • Your UI calls knock.chat.open() when it shows the chat and knock.chat.close() when it hides it.
  • Agent and rep text goes through Markdown and a sanitizer. Visitor text is plain text.
  • Unknown part types are skipped, and unknown action kinds are plain buttons.
  • resolveAction() runs inside the click, with no await before it.
  • The app buttons come from continueOn, skip a channel you do not know, and hide once continuedOn is set.
  • Once continuedOn is set, its way back calls resolveAction(continuedOn.actionId) inside the click. When actionId is null, it opens url.
  • The app buttons are disabled while a tap waits for its result.
  • blocked shows a "Tap to open" button that calls open(), until expiresAt.
  • Every failed reason is handled, and a reason you do not know reads as network.
  • Optional: on a Knock tag before 0.10.3, the state has no continueOn or continuedOn, and resolveAction() returns nothing. To be safe there, read state.continueOn ?? [].
  • The scenarios above all look right in test mode.
  • In production, your magic link is set and your site's origin is allowed (see Before you start).
Chat with a Developer

On this page