# Resync React Native

A powerful React Native library for optimising campaign conversions and dynamic content management. Resync allows you to create campaigns with dynamic content blocks in your React Native applications. Supports forms, lists, sections, and interactive elements.

## Features

- 🎨 **Mobile App Campaigns** - Create and Manage Campaigns in your mobile app.
- 🎨 **Event tracking** - Track any events in your mobile app.
- 🎨 **User Segmentation** - Manage Audiences, Run Campaigns with fine grain user targeting.
- 🎨 **Statistical Significance** - Optimize campaigns with statistical confidence.
- 🎨 **Dynamic Content Rendering** - Render content blocks defined in your Resync dashboard
- 📱 **React Native Components** - Native components for text, buttons, images, inputs, and more
- **Icon** - Render Icons with React Native SVG and Lucide.
- 📋 **Form Support** - Complete form rendering with validation and submission handling
- 📊 **List Components** - Dynamic lists with static data, API integration, or database sources
- 🎯 **Interactive Elements** - Click actions, navigation, and custom function handling
- 🔧 **Customizable Styling** - Full control over component appearance and layout
- 📈 **Analytics Integration** - Built-in event tracking and analytics support
- 🚀 **TypeScript Support** - Full TypeScript definitions for better development experience

## Installation

```sh
npm install resync-react-native
# or
yarn add resync-react-native
```

### Peer Dependencies

This library requires React Native SVG and Lucide as peer dependencies for Icons:

```sh
npm react-native-svg, lucide-react-native
```

For storage, you can use React Native Async Storage

## Quick Start

### 1. Initialize Resync

```tsx
import Resync from 'resync-react-native';

// Initialize Resync with your API credentials as early as possible
Resync.init({
  key: 'your-api-key',
  appId: 7,
  callback: async (data) => {
    console.log('Resync initialized');
  },
  storage: AsyncStorage, // or storage library with similar api
  environment: 'sandbox'
});

// Cache TTL is set automatically:
// - Development: 0ms (no caching, always fresh)
// - Production: 6 hours (21600000ms)
```

### 2. Render Campaign

```tsx
import { ResyncCampaignView } from 'resync-react-native';

export default function App() {
  return (
    <ResyncCampaignView
      name="Holiday Sales"
    />
  );
}
```

### 3. Render Content

```tsx
import { ResyncContentBlock } from 'resync-react-native';

export default function App() {
  return (
    <ResyncContentBlock
      name="HomeWelcomeCard"
    />
  );
}
```

### 4. Remote Config
#### For dynamic content & configuration

```tsx
import { ResyncContentBlock } from 'resync-react-native';

export default function App() {
  const [contentName, setContentName] = useState('');

  // In this way, you can dynamically render different views on the fly, without ever coming back to manually update the view
  useEffect(() => {
    const viewConfig = Resync.getConfig('HOME_VIEW');
    setname(viewConfig);
  }, [])

  return (
    <ResyncContentBlock
      name={contentName}
    />
  );
}
```


### 5. Login User

```tsx
import { ResyncContentBlock, useResync } from 'resync-react-native';

export default function App() {
  const { logInUser } = useResync();
  
  useEffect(() => {
    logInUser('user-38mikey', {
      email: 'mik123@test.com',
      name: 'Mike 123',
      phone: '1234567890',
      language: 'en',
    })
  }, [])

  return (
    <ResyncContentBlock
      name="HomeWelcomeCard"
    />
  );
}
```

### 6. Event Logging
#### You can log custom events in any part of your application

```tsx
import { View, Text } from 'react-native';
import Resync from 'resync-react-native';

export default function App() {

// log custom event you created on the dashboard
useEffect(() => {
    Resync.logEvent({
      eventId: 'evt_app_loaded'
    });
  }, [])

  return (
    <View>
      <Text>Hello World</Text>
    </View>
  );
}
```

## API Reference

### ResyncContentBlock

The main component for rendering dynamic content blocks.

#### Props

| Prop | Type | Required | Description |
|------|------|----------|-------------|
| `name` | `string` | ✅ | Name of the content view to render |
| `loadingComponent` | `React.ReactNode` | ❌ | Custom loading component |
| `errorComponent` | `React.ReactNode` | ❌ | Custom error component |
| `emptyComponent` | `React.ReactNode` | ❌ | Custom empty state component |
| `functionRegistry` | `FunctionRegistry` | ❌ | Custom functions for element interactions |
| `navigationRegistry` | `NavigationRegistry` | ❌ | Navigation functions for click actions |
| `logAnalytics` | `LogAnalytics` | ❌ | Analytics logging function |

### Advanced Usage

#### Custom Function Registry

```tsx
const functionRegistry = {
  // names of functions passed to a specifc content item in visual editor
  handleButtonClick: (data) => {
    console.log('Button clicked with data:', data);
  },
  handleFormSubmit: (formData) => {
    console.log('Form submitted:', formData);
  },
};

<ResyncContentBlock
  name="MyContentView"
  functionRegistry={functionRegistry}
/>
```

#### Navigation Integration
##### You can use any navigation library, so long as they provide the following methods: navigate, push and goBack.

```tsx
// with React Navigation
import { useNavigation } from '@react-navigation/native';

const navigation = useNavigation();

const navigationRegistry = {
  navigate: (routeName, params) => navigation.navigate(routeName, params),
  push: (routeName, params) => navigation.push(routeName, params),
  goBack: () => navigation.goBack(),
};

<ResyncContentBlock
  name="MyContentView"
  navigationRegistry={navigationRegistry}
/>
```

#### Analytics Integration
##### For custom analytics like Firebase, Adjust etc

```tsx
const logAnalytics = (logId, event) => {
  // Send to your analytics service
  analytics.track(event.type, {
    logId,
    ...event,
  });
};

<ResyncContentBlock
  name="MyContentView"
  logAnalytics={logAnalytics}
/>
```

## Content Types

### Sections
Container components that can hold other elements with flexible layouts.

### Lists
Dynamic lists that can display data from:
- Static data arrays
- API endpoints

### Forms
Complete form rendering with:
- Input validation
- Custom styling
- Submission handling
- Success/error actions

### Elements
Individual UI components:
- Text
- Buttons
- Images
- Icons
- Divider
- Inputs (text, email, numeric, etc.)
- Select dropdowns
- Checkboxes
- Radio buttons
- Textareas

## Styling

All components support extensive styling options through the Resync dashboard or programmatically:

```tsx
// Example of styled content
const customStyle = {
  container: {
    backgroundColor: '#f5f5f5',
    padding: 16,
    borderRadius: 8,
  },
  text: {
    fontSize: 18,
    fontWeight: 'bold',
    color: '#333',
  },
};
```

## TypeScript Support

The library includes comprehensive TypeScript definitions:

```tsx
import type {
  ContentView,
  ContentItem,
  FunctionRegistry,
  NavigationRegistry,
  LogAnalytics,
} from 'resync-react-native';
```

## Examples

Check out the [example app](./example) for complete usage examples.

## Contributing

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

## License

MIT

---

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