UNPKG

nablitalks-frontend-sdk

Version:

Frontend SDK for Nablitalks chat support

214 lines (158 loc) 10.2 kB
# Nablitalks Frontend SDK The **Nablitalks Frontend SDK** makes it simple to integrate chat experiences into your React apps — from full-page chat UIs to floating launcher buttons — and provides client APIs for session and message handling. Visit [https://nablitalks.online](https://nablitalks.online) for more information. --- ## 📦 Installation ```bash npm install nablitalks-frontend-sdk ``` or ```bash yarn add nablitalks-frontend-sdk ``` You must also import the bundled CSS once in your app: ```ts import "nablitalks-frontend-sdk/dist/index.css"; ``` --- ## ⚙️ Configuration (SDKConfig) All components and clients require a `config` object of type `SDKConfig`: ```ts import type { SDKConfig } from "nablitalks-frontend-sdk"; // Call your backend here to obtain these. const exampleConfig: SDKConfig = { getNewCustomerId: async (): Promise<string> => { const res = await fetch("/create-customer", { method: "POST", headers: { "Content-Type": "application/json" }, }); const data = await res.json(); return data.customerId || data.id; }, getNewToken: async (customerId: string): Promise<string> => { const res = await fetch(`/get-token/${customerId}`); const data = await res.json(); return data.token; }, }; ``` | Key | Type | Description | | ------------------ | ----------------------------------------- | --------------------------------------------------------------------------- | | `getNewCustomerId` | `() => Promise<string>` | Async function that returns a unique customer ID from your backend. | | `getNewToken` | `(customerId: string) => Promise<string>` | Async function that returns an authentication token for the given customer. | For the backend APIs, see the [NabliTalks Backend SDK](https://www.npmjs.com/package/nablitalks-backend-sdk). For more info, visit [https://nablitalks.online](https://nablitalks.online). --- ## 💬 Using `ChatInterface` `ChatInterface` is a **full chat UI** that can either take over the full page or fit into a container. Make sure to pass the height value. ```tsx import { ChatInterface } from "nablitalks-frontend-sdk"; import "nablitalks-frontend-sdk/dist/index.css"; export default function FullPageChat() { return ( <div style={{ width: "100%", height: "100vh" }}> <ChatInterfaceInternal config={exampleConfig} style={{height: "100%"}} /> </div> ); } ``` **Props:** | Prop | Type | Required | Description | | ----------- | --------------------- | -------- | ----------------------------------------------------------------- | | `config` | `SDKConfig` | ✅ | The configuration object for authentication and session creation. | | `className` | `string` | ❌ | Optional custom class for outer container. | | `style` | `React.CSSProperties` | ❌ | Inline styles to override layout (e.g., set width/height). | --- ## 🟡 Using `FloatingChatLauncher` The **FloatingChatLauncher** creates a floating action button that opens a chat drawer. Great for embedding in existing pages without taking up space. ```tsx import { FloatingChatLauncher } from "nablitalks-frontend-sdk"; import 'nablitalks-frontend-sdk/dist/index.css'; export default function App() { return ( <> <h1>Welcome to My Site</h1> <FloatingChatLauncher config={exampleConfig} position="right" buttonLabel="💬" /> </> ); } ``` **Props:** | Prop | Type | Default | Description | | ------------- | ------------------------ | ------------ | ------------------------------------------------------------------ | | `config` | `SDKConfig` | **Required** | Chat configuration object. | | `position` | `"left"` \| `"right"` | `"right"` | Which corner the button appears in. | | `buttonLabel` | `string \| ReactNode` | `"💬"` | Button content (emoji, icon, or text). | --- ## Example: Mixed Usage ```tsx function MyApp() { return ( <div style={{ height: "100vh" }}> {/* Option 1: Full chat interface */} {/* <ChatInterface config={exampleConfig} /> */} {/* Option 2: Floating chat button */} <FloatingChatLauncher config={exampleConfig} position="left" buttonLabel={<span>Chat 💬</span>} /> </div> ); } ``` --- ## 🔑 Using `NablitalksClient` You can use the `NablitalksClient` directly in any JS/TS file to manage sessions, send messages, or integrate with a custom UI. The client automatically initializes by fetching and storing a customer ID (using `config.getNewCustomerId`) and a short-lived chat token (using `config.getNewToken`) during instantiation. Tokens are automatically refreshed via `SDKConfig` when they expire (e.g., on 401/403 errors). The SDK also provides utility functions to manage local storage for customer IDs, session IDs, and tokens. ### Available Methods | Method | Arguments | Returns | Description | | ----------------- | ----------------------- | ------------------------ | ---------------------------------------------------------------- | | `createSession` | `(sessionId?: string)` | `Promise<Session>` | Creates a new session with an optional `sessionId`. If not provided, a unique ID is generated and stored using `setSessionId`. | | `getSessions` | `()` | `Promise<Session[]>` | Fetches all sessions for the current customer. Ensures a session exists if none are present. | | `deleteSession` | `(sessionId: string)` | `Promise<void>` | Deletes a session by its ID. | | `getChatHistory` | `(sessionId: string)` | `Promise<ChatHistory>` | Retrieves the chat history for a specific session. | | `sendQuery` | `(query: string, sessionId?: string)` | `Promise<QueryResponse>` | Sends a query to the backend and returns the response. Uses stored session ID if none provided. | | `getToken` | `()` | `string \| null` | Returns the cached authentication token. | ### Storage Utility Functions The SDK provides the following utility functions to manage local storage, which are used internally by the client but can also be accessed directly: | Function | Arguments | Returns | Description | | ----------------- | ----------------- | ------------------ | ------------------------------------------------------------ | | `getCustomerId` | `()` | `string \| null` | Retrieves the customer ID from local storage. | | `setCustomerId` | `(id: string)` | `void` | Stores the customer ID in local storage. | | `getSessionId` | `()` | `string \| null` | Retrieves the session ID from local storage. | | `setSessionId` | `(id: string)` | `void` | Stores the session ID in local storage. | | `getToken` | `()` | `string \| null` | Retrieves the authentication token from local storage. | | `clearToken` | `()` | `void` | Removes the authentication token from local storage. | ### Building a Custom Chat Interface To create a custom chat interface using `NablitalksClient`, follow these steps: 1. **Initialize the Client**: Create an instance of `NablitalksClient` with your `SDKConfig`. The client automatically fetches and stores a customer ID using `setCustomerId` and a short-lived token using `setToken`. 2. **Create a Session**: Call `createSession()` to generate a new session ID, which is automatically stored using `setSessionId`. 3. **Send Queries**: Use `sendQuery(query, sessionId)` to send messages and receive responses. If no `sessionId` is provided, the client uses the stored session ID from `getSessionId`. 4. **Manage Sessions and History**: Use `getSessions()` to list all sessions and `getChatHistory(sessionId)` to retrieve message history for a session. 5. **Access Stored Data**: Use `getCustomerId`, `getSessionId`, or `getToken` to access cached values if needed for your UI logic. 6. **Display Branding (Legal Requirement)**: If using the free plan, you **must** display "Powered by NabliTalks" with a link to [https://nablitalks.online](https://nablitalks.online) in your chat interface. #### Minimal Example ```ts import NablitalksClient, { getCustomerId, getSessionId } from "nablitalks-frontend-sdk/client"; const client = new NablitalksClient(exampleConfig); // Initialize and send a message async function startChat() { const customerId = getCustomerId(); // Access stored customer ID const session = await client.createSession(); // Creates and stores session ID const response = await client.sendQuery("Hello!", getSessionId()); // Send query console.log(response); // Fetch history const history = await client.getChatHistory(getSessionId()!); console.log(history.messages); // Render "Powered by NabliTalks" in your UI // Example: <a href="https://nablitalks.online">Powered by NabliTalks</a> } ``` --- ## 🛠️ Notes & Best Practices * This SDK uses **peerDependencies** for `react` and `react-dom`, so it works with React 18+ including React 19. * Make sure to import the `dist/chat.css` file once globally. * The chat interface is responsive — in small containers or mobile views, the sidebar auto-collapses and shows a drawer behavior. * **Legal Requirement**: If using the free plan, you **must** display "Powered by NabliTalks" with a link to [https://nablitalks.online](https://nablitalks.online) in your chat interface.