# @opero-pro/native-sdk

A lightweight React Native SDK for integrating Opero's AI assistant

## Features

- **React Native Support**: Compatible with React Native 0.72.0+
- **iOS, Android and web**: Cross-platform support with native performance
- **Flexible Triggers**: Use any component as a chat trigger (buttons, search bars, etc.)
- **Provider Pattern**: Clean architecture with React Context for state management
- **Real-time Streaming**: Live streaming of AI responses with typing effect
- **Markdown Support**: Rich text rendering with proper formatting
- **Progress Indicators**: Real-time progress updates during AI processing
- **Sources Display**: Shows document sources with page references (when available)
- **Document Viewer**: Built-in PDF viewer with page navigation and zoom controls
- **Sample Questions**: Suggested questions based on available documents
- **Conversation Management**: Server-side conversation persistence
- **Chat History**: View and continue previous conversations with collapsible history section
- **Error Handling**: Smart error display with persistent vs. temporary messages
- **Connectivity Check**: Optional API health check on initialization
- **Customizable Styling**: Extensive StyleSheet customization options
- **Callback System**: Event-driven architecture for integration
- **TypeScript Support**: Full TypeScript support from day one

## Installation

### Using pnpm (Recommended)

```bash
pnpm add @opero-pro/native-sdk
```

### Using npm

```bash
npm install @opero-pro/native-sdk
```

### Using yarn

```bash
yarn add @opero-pro/native-sdk
```

## Quick Start

### Basic Implementation

```tsx
import React from "react";
import { View, TouchableOpacity, Text } from "react-native";
import { OperoChatProvider, useOperoChatTrigger } from "@opero-pro/native-sdk";

const CustomTrigger = () => {
  const openChat = useOperoChatTrigger();

  return (
    <TouchableOpacity onPress={openChat}>
      <Text>Ask AI Assistant</Text>
    </TouchableOpacity>
  );
};

const App = () => {
  return (
    <OperoChatProvider
      apiKey="your-api-key"
      userEmail="user@example.com"
      userRole="admin"
      onReady={() => console.log("Chat ready!")}
      onError={(error) => console.error("Error:", error)}
    >
      <View>
        <Text>My App Content</Text>
        <CustomTrigger />
      </View>
    </OperoChatProvider>
  );
};
```

### Multiple Triggers

```tsx
import React from "react";
import { View, TouchableOpacity, Text, TextInput } from "react-native";
import { OperoChatProvider, useOperoChatTrigger } from "@opero-pro/native-sdk";

const SearchBar = () => {
  const openChat = useOperoChatTrigger();

  return (
    <TextInput
      placeholder="Search..."
      onFocus={openChat}
      style={{ borderWidth: 1, padding: 10 }}
    />
  );
};

const HelpButton = () => {
  const openChat = useOperoChatTrigger();

  return (
    <TouchableOpacity onPress={openChat}>
      <Text>💬 Get Help</Text>
    </TouchableOpacity>
  );
};

const App = () => {
  return (
    <OperoChatProvider
      apiKey="your-api-key"
      userEmail="user@example.com"
      userRole="user"
      apiEndpoint="https://api.opero.pro/v1"
      customStyles={{
        primaryColor: "#3b82f6",
        fontSize: 16,
        borderRadius: 12,
      }}
      onReady={() => console.log("SDK ready")}
      onError={(error) => console.error("Error:", error)}
      onMessageSent={(message) => console.log("Message sent:", message)}
      onStreamStart={() => console.log("Stream started")}
      onStreamEnd={(fullMessage) => console.log("Stream ended:", fullMessage)}
      onSources={(sources) => console.log("Sources:", sources)}
    >
      <View>
        <SearchBar />
        <HelpButton />
        <Text>Your app content here...</Text>
      </View>
    </OperoChatProvider>
  );
};
```

## Configuration

### OperoChatProvider Props

#### Required Parameters

- `apiKey`: Authentication token for Opero API. Can be obtained from [Dashboard > Settings](https://app.opero.pro/settings).
- `children`: React components that will have access to the chat functionality

#### Optional Parameters

- `userEmail`: User email for access control and traceability
- `userRole`: User role for access control (e.g., "user", "admin", "guest")
- `apiEndpoint`: Full API URL (defaults to `https://api.opero.pro/v1`)
- `customStyles`: Object with styling overrides for the chat interface
- `filters`: Object with document filters (see Filters section)
- `onReady`: Callback when chat is ready
- `onError`: Callback for error handling
- `onMessageSent`: Callback when message is sent
- `onStreamStart`: Callback when streaming starts
- `onStreamEnd`: Callback when streaming ends
- `onSources`: Callback for transforming sources and setting document URLs before display
- `onProgress`: Callback for transforming progress messages before display (e.g., truncating long document lists)
- `showHistory`: Enable/disable conversation history (default: `true`)

### useOperoChatTrigger Hook

The `useOperoChatTrigger` hook provides a function that opens the chat when called. It can be used with any event handler:

```tsx
const openChat = useOperoChatTrigger();

// Use with onPress
<TouchableOpacity onPress={openChat}>

// Use with onFocus
<TextInput onFocus={openChat} />

// Use with onLongPress
<TouchableOpacity onLongPress={openChat} />
```

## Chat History

The SDK includes a conversation history feature that allows users to view and continue previous conversations:

### Features

- **Recent Conversations**: Shows a list of recent conversations with titles and timestamps
- **Collapsible Interface**: History section can be expanded/collapsed to save space
- **Pagination**: Load more conversations with scroll-based pagination
- **Local Caching**: Conversations are cached locally to reduce API calls

### Configuration

```tsx
<OperoChatProvider
  apiKey="your-api-key"
  userEmail="user@example.com"
  showHistory={true} // Enable/disable history (default: true)
>
  <YourAppContent />
</OperoChatProvider>
```

## Filters

The SDK supports filtering conversations by specific documents. Only `document_names` or `documentNames` is accepted as filter keys:

```tsx
// Filter by specific documents
<OperoChatProvider
  apiKey="your-api-key"
  userEmail="user@example.com"
  filters={{
    document_names: ["manual1.pdf", "manual2.pdf"],
    // or
    // documentNames: ["document1.pdf", "document2.pdf"]
  }}
>
  <YourAppContent />
</OperoChatProvider>
```

**Notes**:

1. Only `document_names` or `documentNames` filter keys are supported. Other filter types will be ignored by the API.
2. Please reach out to `support@opero.pro` to discuss adding more filter options.

## Source Transformation and Document Viewer

The SDK allows you to transform document sources before they are displayed and automatically opens documents when users click on page numbers. The document viewer supports PDF files on iOS, Android, and web platforms.

### Setting Document URLs

For the document viewer to work, set or edit the `url` property on sources using the `onSources` callback. This callback is applied to sources in both live conversations and historical conversations, ensuring consistent source transformation:

```tsx
const handleSources = (sources: OperoSource[]): OperoSource[] => {
  return sources.map((source) => {
    // Set document URL
    const baseUrl = "https://example.com/documents/";

    return {
      ...source,
      url: baseUrl + source.title, // or source.document_id, etc.
      // Optionally transform other properties
      title: source.title.replace("uuid", "My Document"),
    };
  });
};

<OperoChatProvider
  apiKey="your-api-key"
  userEmail="user@example.com"
  onSources={handleSources}
>
  <YourAppContent />
</OperoChatProvider>;
```

### Document Viewer Features

- **Platform Support**: Works on iOS, Android, and web
- **Page Navigation**: Automatically navigates to clicked page number
- **Zoom Controls**: Built-in zoom in/out buttons
- **Loading States**: Shows spinner while document loads
- **Error Handling**: Displays error message if document fails to load
- **Mobile Optimized**: Uses WebView on mobile, iframe on web

### How It Works

1. User clicks on a page number pill (e.g., "Page 16")
2. SDK checks if `source.url` is set
3. If URL exists, opens document viewer in full-screen modal
4. Viewer attempts to navigate to the specific page
5. User can zoom, scroll, and close the viewer

**Important Notes**:

1. **URL Required**: The value `source.url` must be set. The `onSources` callback can be used to set or edit `source.url`.
2. **No URL Behavior**: If `url` is not set, click is ignored with console warning
3. **PDF Support**: Currently supports PDF documents only
4. **Transformations**: Applied per-message when sources are received (both live and historical)
5. **Error Handling**: Viewer shows retry button if document fails to load

## Progress Message Transformation

The SDK allows you to transform progress messages before they are displayed. This is useful for truncating long document lists or customizing progress text to be more user-friendly.

```tsx
const handleProgress = (progressMessage: string): string => {
  // Transform progress messages to make them more user-friendly
  if (progressMessage.includes("Searching in:")) {
    // Truncate long document lists
    const documents = progressMessage.replace("Searching in: ", "").split(", ");
    if (documents.length > 2) {
      return `Searching in: ${documents.slice(0, 2).join(", ")}... (${documents.length - 2} more documents)`;
    }
  }

  // Return original message if no transformation needed
  return progressMessage;
};

<OperoChatProvider
  apiKey="your-api-key"
  userEmail="user@example.com"
  onProgress={handleProgress}
>
  <YourAppContent />
</OperoChatProvider>;
```

**Important Notes**:

1. The `onProgress` callback must return a string
2. If the callback throws an error, it will be propagated to the calling code
3. Transformations are applied in real-time as progress updates are received

## Custom Styling

The SDK provides extensive styling customization options:

### Basic Styling

```tsx
const customStyles = {
  // Colors
  primaryColor: "#3b82f6",
  secondaryColor: "#1e40af",
  backgroundColor: "#ffffff",
  textColor: "#1f2937",
  userBubbleColor: "#000000",
  assistantBubbleColor: "#f3f4f6",
  assistantMessageText: "#1f2937",

  // Typography
  fontSize: 14,
  fontWeight: "normal",

  // Layout
  borderRadius: 8,
  maxWidth: 400,
  searchBarHeight: 48,
  chatBubbleRadius: 12,
};
```

### Advanced Styling

```tsx
const customStyles = {
  // Error banner styling
  errorBannerBackgroundColor: "#fef2f2",
  errorBannerBorderColor: "#fecaca",
  errorBannerTextColor: "#dc2626",
  errorBannerDismissBackgroundColor: "#fecaca",
  errorBannerDismissTextColor: "#dc2626",

  // Progress banner styling
  progressBannerBackgroundColor: "#eff6ff",
  progressBannerBorderColor: "#dbeafe",
  progressBannerTextColor: "#1e40af",
  progressIndicatorColor: "#3b82f6",

  // Sources styling
  sourcesHeaderColor: "#374151",
  sourceItemBackgroundColor: "#f9fafb",
  sourceTitleColor: "#1f2937",
  sourceTagColor: "#6b7280",
  sourceTagBackgroundColor: "#e5e7eb",
};
```

### Complete Styling Example

```tsx
<OperoChatProvider
  apiKey="your-api-key"
  userEmail="user@example.com"
  customStyles={{
    // Brand colors
    primaryColor: "#d32f2f",
    secondaryColor: "#b71c1c",

    // Chat appearance
    backgroundColor: "#ffffff",
    textColor: "#1f2937",
    userBubbleColor: "#d32f2f",
    assistantBubbleColor: "#f5f5f5",
    assistantMessageText: "#1f2937",
    chatBubbleRadius: 12,

    // Error handling
    errorBannerBackgroundColor: "#fef2f2",
    errorBannerTextColor: "#dc2626",

    // Progress indicators
    progressBannerBackgroundColor: "#eff6ff",
    progressIndicatorColor: "#3b82f6",
  }}
>
  <YourAppContent />
</OperoChatProvider>
```

## Hook-based Implementation

### Custom Chat Implementation

For advanced users who want full control over the chat UI, you can use the `useOperoChat` hook directly:

```tsx
import React from "react";
import {
  View,
  Modal,
  ScrollView,
  TextInput,
  TouchableOpacity,
  Text,
} from "react-native";
import { useOperoChat } from "@opero-pro/native-sdk";

const CustomChatComponent = () => {
  const {
    messages,
    conversationTitle,
    isVisible,
    isLoading,
    isConnected,
    errorMessage,
    progressMessage,
    openChat,
    closeChat,
    sendMessage,
    retryLastMessage,
    checkConnectivity,
    clearMessages,
    dismissError,
  } = useOperoChat({
    apiKey: "your-api-key",
    userEmail: "user@example.com",
    userRole: "user",
    customStyles: {
      primaryColor: "#3b82f6",
    },
    callbacks: {
      onReady: () => console.log("Chat ready"),
      onError: (error) => console.error("Error:", error),
    },
  });

  return (
    <View>
      {/* Custom trigger */}
      <TouchableOpacity onPress={openChat}>
        <Text>Ask me anything...</Text>
      </TouchableOpacity>

      {/* Custom chat overlay */}
      {isVisible && (
        <Modal visible={isVisible} onRequestClose={closeChat}>
          <View>
            {/* Custom header */}
            <View>
              <Text>{conversationTitle}</Text>
              <TouchableOpacity onPress={closeChat}>
                <Text>✕</Text>
              </TouchableOpacity>
            </View>

            {/* Custom messages */}
            <ScrollView>
              {messages.map((message) => (
                <View key={message.id}>
                  <Text>{message.content}</Text>
                </View>
              ))}
            </ScrollView>

            {/* Custom input */}
            <TextInput
              placeholder="Type your message..."
              onSubmitEditing={(e) => sendMessage(e.nativeEvent.text)}
            />

            {/* Error display */}
            {errorMessage && (
              <View>
                <Text>{errorMessage}</Text>
                <TouchableOpacity onPress={dismissError}>
                  <Text>Dismiss</Text>
                </TouchableOpacity>
              </View>
            )}
          </View>
        </Modal>
      )}
    </View>
  );
};
```

### Using Individual Components

You can also use individual components for maximum customization:

```tsx
import React from "react";
import {
  OperoChatContainer,
  OperoChatHeader,
  OperoChatMessages,
  OperoChatInput,
  OperoErrorBanner,
  useOperoChat,
} from "@opero-pro/native-sdk";

const MyCustomChat = () => {
  const {
    isVisible,
    messages,
    errorMessage,
    openChat,
    closeChat,
    sendMessage,
  } = useOperoChat({
    apiKey: "your-api-key",
    userEmail: "user@example.com",
  });

  return (
    <View>
      <TouchableOpacity onPress={openChat}>
        <Text>Open Chat</Text>
      </TouchableOpacity>

      <OperoChatContainer isVisible={isVisible} onClose={closeChat}>
        <OperoChatHeader title="My Assistant" onClose={closeChat} />
        <OperoChatMessages messages={messages} />
        <OperoChatInput onSend={sendMessage} />
        {errorMessage && <OperoErrorBanner message={errorMessage} />}
      </OperoChatContainer>
    </View>
  );
};
```

## Error Handling

The SDK provides comprehensive error handling with different error types:

```tsx
interface OperoChatError {
  type: "network" | "api" | "auth" | "validation" | "unknown";
  message: string;
  details?: any;
  persistent?: boolean;
}
```

### Error Types

- **Network errors**: Connection issues, timeouts
- **API errors**: Server-side errors with error codes
- **Auth errors**: Invalid API keys or authentication issues
- **Validation errors**: Invalid input parameters
- **Unknown errors**: Unexpected errors

### Error Handling Example

```tsx
<OperoChatProvider
  apiKey="your-api-key"
  userEmail="user@example.com"
  onError={(error) => {
    switch (error.type) {
      case "auth":
        console.error("Authentication failed:", error.message);
        // Handle auth error
        break;
      case "network":
        console.error("Network error:", error.message);
        // Handle network error
        break;
      case "api":
        console.error("API error:", error.message);
        // Handle API error
        break;
      default:
        console.error("Unknown error:", error.message);
    }
  }}
>
  <YourAppContent />
</OperoChatProvider>
```

## Mobile Behavior

### iOS & Android

- Chat opens as a full-screen overlay on both platforms
- Optimized touch interactions for mobile
- Support for both portrait and landscape orientations

### Responsive Design

- Chat overlay uses full screen on mobile
- Optimized for different screen sizes

## Accessibility

The SDK includes built-in accessibility features:

- Screen reader support
- VoiceOver compatibility (iOS)
- TalkBack compatibility (Android)
- Keyboard navigation support
- Proper ARIA labels and roles

## Error Tracking & Performance Monitoring

The SDK includes built-in analytics to help improve the service:

- **Error Tracking**: Automatic error capture with detailed context for faster issue resolution
- **Performance Monitoring**: API response times, streaming performance, and connectivity metrics

### What We Track

#### Performance Metrics

- API call latency and success rates
- Streaming response times
- Connectivity check results
- Error frequency and types

### Privacy & Data

- **Data Security**: All analytics data is encrypted and securely transmitted
- **No Sensitive Content**: Only interaction patterns and performance metrics are collected

### Development Mode

Analytics are disabled in development by default to:

- Reduce noise in analytics data
- Improve development performance
- Focus on production insights

To enable analytics in development:

```tsx
const App = () => (
  <OperoChatProvider
    apiKey="your-api-key"
    userEmail="user@example.com"
    analytics={{ enableInDevelopment: true }}
  >
    <YourAppContent />
  </OperoChatProvider>
);
```

## Performance Optimization

The SDK is optimized for performance:

- **Bundle size**: < 250KB (minified)
- **Tree-shaking**: Unused features are automatically removed
- **Memory management**: Proper cleanup in component unmount
- **Network optimization**: Automatic retry with exponential backoff

## Troubleshooting

### Common Issues

1. **TypeScript errors**: Ensure you have the latest `@types/react`
2. **Build errors**: Check that React Native version is 0.72.0+
3. **API errors**: Verify your API key and endpoint configuration
4. **Styling issues**: Check that custom styles are properly formatted

### Debug Mode

Enable debug logging in development:

```tsx
import { log } from "@opero-pro/native-sdk";

// Debug logging is automatically enabled in development
log("Debug message", "info");
```

## Development

### Prerequisites

- React Native 0.72.0+
- Node.js 18+
- pnpm (recommended) or npm

### Installation

```bash
cd apps/native-sdk
pnpm install
```

### Build Commands

- `pnpm run build` - Build TypeScript to JavaScript
- `pnpm run dev` - Watch mode for development
- `pnpm run test` - Run unit tests
- `pnpm run lint` - Run ESLint
- `pnpm run type-check` - Run TypeScript type checking

### Development Server

```bash
pnpm run dev
```

### Testing

```bash
# Run all tests
pnpm run test

# Run tests with coverage
pnpm run test --coverage

# Run specific test files
pnpm test components/OperoSampleQuestions.test.tsx
```

### Example App

The SDK includes a comprehensive example app:

```bash
# Navigate to example
cd example

# Install dependencies
pnpm install

# Start the app
pnpm start

# Run on specific platforms
pnpm ios
pnpm android
pnpm web
```

### Project Structure

```
src/
├── components/          # React components
├── hooks/              # Custom hooks
├── services/           # API and business logic
├── types/              # TypeScript definitions
├── utils/              # Utility functions
└── __tests__/          # Test files
```

## License

Copyright (c) 2025 Opero Labs ApS.
See LICENSE file for details.

## Support

For support and questions:

- **Email**: support@opero.pro

## Contributing

- [Development workflow](CONTRIBUTING.md#development-workflow)
- [Sending a pull request](CONTRIBUTING.md#sending-a-pull-request)
- [Code of conduct](CODE_OF_CONDUCT.md)

## Changelog

### v0.12.0

- Improve display of relevance score in source documents
- Sort conversation history by last message's timestamp in each conversation. This simplifies follow-up conversations for the user.

### v0.11.0

- Sort, filter, and display citation sources based on relevance

### v0.10.0

- Add thumbs up/down feedback buttons on assistant messages
- Copy to clipboard
- Floating arrow button for quick navigation to the bottom
- Replaced collapsible conversation history with full-screen slide-in drawer

### v0.9.5

- Apply `onSources` callback transformations to historical conversations (in addition to live).

### v0.9.4

- Fix bug preventing loading user conversations if `userEmail` is missing.

### v0.9.3

- Fix bug with loading conversation history and messages.
- Set fixed version for `posthog-react-native` to `4.4.0`.

### v0.9.2

- Update `posthog-react-native` package to version `4.9.1` to resolve potentially missing `error-tracking` package.

### v0.9.0

- Add `Recent Conversations` section to display user's conversation history.

### v0.8.1

- Update `posthog-react-native` package to resolve potentially missing `error-tracking` package.

### v0.8.0

- Add built-in PDF document viewer with platform support (iOS, Android, Web)
- Remove `onSourceClicked` callback in favor of SDK-managed viewer
- Remove "Retry without filters" functionality from filtered chat

### v0.7.1

- Show API errors in banner, such as "Invalid API keys".

### v0.7.0

- Set flexible trigger pattern to open assistant chat from any component. This replaces the built-in search bar pattern.

### v0.6.0

- Add callback `onProgress` for transforming progress messages before display

### v0.5.0

- Add support for client-side edits of source titles and metadata with callback `onSources`
- Add callback `onSourceClicked` for custom source visualization

### v0.4.0

- Switch to SSE (Server-Side Events) for full support of readable streams on mobile platforms

### v0.3.0

- Added comprehensive documentation
- Performance analytics and error tracking

### v0.2.0

- Added `useOperoChat` hook for advanced implementations
- Enhanced styling customization options
- Improved error handling with detailed error types
- Added filters support for document-based conversations
- Enhanced accessibility features
- Performance optimizations and bundle size improvements

### v0.1.0

- Initial release
- React Native 0.72.0+ support
- iOS and Android compatibility
- Real-time streaming support
- Markdown rendering
- Sources display
- Progress indicators
- Error handling
- Connectivity checks
- Custom styling
- TypeScript support

---

Made with [create-react-native-library](https://github.com/callstack/react-native-builder-bob)
