@ludiks/react
Version:
Complete React library for Ludiks gamification platform - includes SDK and ready-to-use components
405 lines (321 loc) โข 9.05 kB
Markdown
# @ludiks/react
Complete React library for Ludiks gamification platform. Includes both the SDK and ready-to-use React components. Integrate gamification features into your application with just a few lines of code.
## Installation
```bash
npm install @ludiks/react
# or
yarn add @ludiks/react
# or
pnpm add @ludiks/react
```
## Quick Start
1. Configure your Ludiks API key:
```tsx
import { setLudiksConfig } from '@ludiks/react';
// Production: use your real API key
setLudiksConfig('your-ludiks-api-key');
// Development/Demo: use mock data
setLudiksConfig('mock'); // or 'demo' or any key starting with 'mock-'
```
2. Use the components:
```tsx
import { UserProfile, StreakCounter, Leaderboard, GamificationToaster } from '@ludiks/react';
function App() {
return (
<div>
<UserProfile userId="user123" />
<StreakCounter userId="user123" />
<Leaderboard />
<GamificationToaster
notification={{
type: 'step-completed',
title: 'Step Completed!',
description: 'Great job completing this step',
points: 50
}}
animations={true}
/>
</div>
);
}
```
## Mock Mode for Development & Documentation
Perfect for testing, demos, documentation, and development without real API calls:
```tsx
import { setLudiksConfig, enableMockMode, mockUserProfile } from '@ludiks/react';
// Method 1: Auto-detection (recommended)
setLudiksConfig('mock'); // Automatically enables mock mode
// Method 2: Manual control
setLudiksConfig('your-api-key');
enableMockMode(); // Force enable mock mode
// Method 3: Check if in mock mode
import { isMock } from '@ludiks/react';
if (isMock()) {
console.log('Using mock data');
}
```
**Perfect for:**
- ๐จ **Documentation sites** - Show components with realistic data
- ๐งช **Testing environments** - No API dependencies
- ๐ **Development** - Instant feedback without API setup
- ๐ **Demos** - Consistent sample data for presentations
- ๐ง **Prototyping** - Quick iteration without backend
**Mock data includes:**
- Realistic user profiles with circuits and rewards
- Leaderboard with 5 sample users
- Streak data with history
- Simulated API delays for realistic feel
## Components
### UserProfile
Display comprehensive user gamification profile with circuits progress, rewards, and statistics.
```tsx
<UserProfile
userId="user123"
showCircuits={true}
showRewards={true}
showStreak={true}
variant="card" // card | detailed | minimal | dashboard
colors={{
primary: "#8b5cf6",
secondary: "#06d6a0"
}}
/>
```
**Props:**
- `userId` (string): User identifier
- `showCircuits` (boolean): Show user's circuit progress
- `showRewards` (boolean): Display earned rewards
- `showMetadata` (boolean): Show user metadata
- `showStreak` (boolean): Display streak information
- `circuitLimit` (number): Max circuits to display
- `variant` (string): Display style
- `orientation` (string): Layout orientation
- `colors` (object): Custom color scheme
### StreakCounter
Show user's current streak with optional record display.
```tsx
<StreakCounter
userId="user123"
showRecord={true}
variant="flame" // minimal | detailed | flame | calendar
animate={true}
size="md" // sm | md | lg
/>
```
**Props:**
- `userId` (string): User identifier
- `showRecord` (boolean): Display longest streak
- `variant` (string): Display style
- `animate` (boolean): Enable animations
- `size` (string): Component size
- `colors` (object): Custom color scheme
### Leaderboard
Display project leaderboard with rankings and user stats.
```tsx
<Leaderboard
period="week" // day | week | month | all
limit={10}
variant="table" // table | podium | minimal
showUserDetails={true}
autoRefresh={false}
/>
```
**Props:**
- `period` (string): Time period for rankings
- `limit` (number): Number of users to display
- `showUserDetails` (boolean): Show additional user info
- `variant` (string): Display style
- `autoRefresh` (boolean): Auto-refresh data
- `refreshInterval` (number): Refresh interval in ms
- `colors` (object): Custom color scheme
### GamificationToaster
Display notifications for completed steps, circuits, and earned rewards.
```tsx
<GamificationToaster
notification={{
type: 'step-completed',
title: 'Congratulations!',
description: 'You completed this step',
points: 100,
rewards: [{ name: 'First Step Badge' }]
}}
position="top-right"
duration={4000}
showRewards={true}
showPoints={true}
animations={true}
/>
```
**Props:**
- `notification` (object): Notification data
- `position` (string): Toast position
- `duration` (number): Auto-close duration
- `showRewards` (boolean): Display rewards
- `showPoints` (boolean): Show earned points
- `animations` (boolean): Enable animations
- `onClose` (function): Close callback
## Hooks
### useUserProfile
```tsx
import { useUserProfile } from '@ludiks/react';
const { profile, loading, error, refetch } = useUserProfile({
userId: 'user123',
autoRefresh: false,
refreshInterval: 30000
});
```
### useLeaderboard
```tsx
import { useLeaderboard } from '@ludiks/react';
const { data, loading, error, refetch } = useLeaderboard({
period: 'week',
limit: 10,
autoRefresh: false,
refreshInterval: 30000
});
```
## Styling
All components support custom styling through:
1. **CSS classes**: Use the `className` prop
2. **Custom colors**: Pass a `colors` object
3. **CSS variables**: Override default values
```css
/* Custom styling example */
.my-leaderboard {
border-radius: 12px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
```
## Examples
### Complete Integration
```tsx
import React, { useState } from 'react';
import {
UserProfile,
StreakCounter,
Leaderboard,
GamificationToaster,
setLudiksConfig
} from '@ludiks/react';
// Initialize configuration
setLudiksConfig('your-api-key');
function GamificationDashboard({ userId }) {
const [notification, setNotification] = useState(null);
const handleTrackEvent = async (eventName) => {
// Track event using @ludiks/sdk
const response = await trackEvent({ userId, eventName });
// Show notification if step/circuit completed
if (response.stepCompleted || response.circuitCompleted) {
setNotification({
type: response.circuitCompleted ? 'circuit-completed' : 'step-completed',
title: response.circuitCompleted ? 'Circuit Complete!' : 'Step Complete!',
points: response.points,
rewards: response.rewards
});
}
};
return (
<div className="space-y-6">
<div className="grid md:grid-cols-3 gap-6">
<UserProfile userId={userId} variant="card" />
<StreakCounter userId={userId} variant="flame" />
<Leaderboard period="week" limit={5} variant="minimal" />
</div>
{notification && (
<GamificationToaster
notification={notification}
onClose={() => setNotification(null)}
showRewards={true}
showPoints={true}
animations={true}
/>
)}
</div>
);
}
```
### Documentation Site Example
```tsx
import React from 'react';
import {
UserProfile,
StreakCounter,
Leaderboard,
setLudiksConfig
} from '@ludiks/react';
// Enable mock mode for documentation
setLudiksConfig('mock');
function DocumentationPage() {
return (
<div className="max-w-6xl mx-auto p-8">
<h1>Ludiks Components Documentation</h1>
<section className="mb-12">
<h2>User Profile Component</h2>
<UserProfile
userId="demo-user"
variant="card"
showCircuits={true}
showRewards={true}
/>
</section>
<section className="mb-12">
<h2>Streak Counter Component</h2>
<StreakCounter
userId="demo-user"
variant="flame"
showRecord={true}
/>
</section>
<section className="mb-12">
<h2>Leaderboard Component</h2>
<Leaderboard
period="all"
limit={5}
variant="table"
/>
</section>
</div>
);
}
```
## Development
### Local Development
```bash
# Install dependencies
npm install
# Start development server
npm run dev
# Build library
npm run build
# Run tests
npm test
```
### Demo Environment
```bash
# Start demo server
npm run dev:demo
# Build demo
npm run build:demo
# Preview demo
npm run preview:demo
```
## TypeScript Support
Full TypeScript support with comprehensive type definitions:
```tsx
import type {
LudiksTheme,
NotificationData,
LeaderboardEntry
} from '@ludiks/react';
```
## What's Included
This library includes:
- **Full Ludiks SDK**: All SDK methods and utilities
- **React Components**: Ready-to-use UI components
- **TypeScript Support**: Complete type definitions
- **Mock Mode**: Perfect for development and testing
No need to install `@ludiks/sdk` separately - it's included!
## Requirements
- React >= 16.8.0
## License
MIT