react-native-leader-line
Version:
React Native port of leader-line library for drawing arrow lines and connectors
485 lines (387 loc) ⢠15.8 kB
Markdown
# React Native Leader Line
[](https://badge.fury.io/js/react-native-leader-line)
[](http://www.typescriptlang.org/)
[](https://reactnative.dev/)
[](https://github.com/puppetmaster886/react-native-leader-line)
[](https://snack.expo.dev)
[](https://snack.expo.dev)
[](https://github.com/puppetmaster886/react-native-leader-line)
[](https://opensource.org/licenses/MIT)
A React Native port of the popular [leader-line](https://github.com/anseki/leader-line) library for drawing arrow lines and connectors between UI components. This library brings the powerful line-drawing capabilities of leader-line to React Native applications, with additional fixes and enhancements from community forks.
## š¤ LLM-Optimized Library
This library is specifically optimized for **Large Language Model (LLM) consumption** with:
- š **Comprehensive JSDoc** - Every interface, type, and function is extensively documented
- š **JSON Schemas** - Structured validation schemas for all component props
- š” **Embedded Examples** - Complete working examples in documentation
- šÆ **Pattern Library** - Pre-defined patterns for common use cases
- š”ļø **Type Safety** - Strict TypeScript types with detailed descriptions
- š¤ **AI-Friendly** - Designed to be easily understood and used by AI coding assistants
### For AI Tools & LLMs
```javascript
// The library includes specialized files for LLM consumption:
// - docs/llm-guide.js - Comprehensive examples and patterns
// - .llmconfig.js - Configuration and metadata for AI tools
// - Extensive JSDoc with @example tags throughout
// - JSON Schema validation for all props
```
## ⨠Features
- šÆ **Multiple API Styles**: Functional components, Hook-based API, Imperative API (leader-line compatible)
- š **Dynamic Updates**: Change line properties in real-time
- šØ **Rich Styling**: Colors, gradients, outlines, shadows, dash patterns
- š **Path Types**: Straight lines, arcs, and custom curvature
- š **Socket System**: Flexible connection points with gravity
- š·ļø **Multiple Labels**: Start, middle, end, caption, and path labels
- ā” **Animations**: Show/hide effects with smooth transitions
- šŖ **Plug Types**: Arrows, discs, squares, and custom markers
- š± **Mobile Optimized**: Performance tuned for React Native with React.memo
- š§ **TypeScript**: Full type safety and IntelliSense support
- š **Migration Ready**: Backward compatible with original leader-line API
- ā” **Performance**: Optimized components with memoization and smart re-rendering
## š¦ Installation
```bash
npm install react-native-leader-line react-native-svg
# or
yarn add react-native-leader-line react-native-svg
```
### iOS Setup
```bash
cd ios && pod install
```
## š Quick Start
### Functional Component API (Recommended)
```tsx
import React, { useRef } from 'react';
import { View } from 'react-native';
import { LeaderLine } from 'react-native-leader-line';
const MyComponent = () => {
const startRef = useRef(null);
const endRef = useRef(null);
return (
<View>
<View ref={startRef} style={{...}} />
<View ref={endRef} style={{...}} />
<LeaderLine
start={{ element: startRef }}
end={{ element: endRef }}
color="#3498db"
strokeWidth={3}
endPlug="arrow1"
startLabel="Start"
endLabel="End"
/>
</View>
);
};
```
### Imperative API (leader-line compatibility)
```tsx
import { useLeaderLineCompatibility } from 'react-native-leader-line';
const MyComponent = () => {
const { LeaderLine, LeaderLineContainer } = useLeaderLineCompatibility();
const startRef = useRef(null);
const endRef = useRef(null);
const createLine = () => {
// Same API as original leader-line!
const line = new LeaderLine(startRef, endRef, {
color: 'coral',
size: 4, // legacy property supported
endPlug: 'arrow1'
});
// Imperative methods work the same
line.setOptions({ color: 'blue' });
line.hide();
setTimeout(() => line.show(), 1000);
};
return (
<View>
<View ref={startRef} style={{...}} />
<View ref={endRef} style={{...}} />
<LeaderLineContainer />
<Button onPress={createLine} title="Create Line" />
</View>
);
};
```
## šØ Advanced Styling
```tsx
<LeaderLine
start={{ element: startRef }}
end={{ element: endRef }}
color="#e74c3c"
strokeWidth={4}
path="arc"
curvature={0.3}
endPlug="arrow2"
outline={{
enabled: true,
color: "white",
size: 2,
}}
dropShadow={{
dx: 2,
dy: 2,
blur: 4,
color: "rgba(0,0,0,0.3)",
}}
dash={{
pattern: "8,4",
animation: true,
}}
startLabel="Begin"
middleLabel={{
text: "Processing",
backgroundColor: "#f39c12",
color: "white",
borderRadius: 8,
padding: 6,
}}
endLabel="Complete"
/>
```
## š Examples & Live Demos
### š® Interactive Expo Snacks
Try react-native-leader-line directly in your browser with these interactive examples:
| Demo | Description | Features |
|------|-------------|----------|
| [šÆ **Basic Demo**](https://snack.expo.dev/@your-username/react-native-leader-line-basic-demo) | Simple usage and core functionality | Basic connections, colors, socket positioning |
| [š **Advanced Features**](https://snack.expo.dev/@your-username/react-native-leader-line-advanced-demo) | Complex styling and effects | Path types, outlines, shadows, labels |
| [ā” **Imperative API**](https://snack.expo.dev/@your-username/react-native-leader-line-imperative-demo) | Programmatic control | Dynamic creation, batch operations |
| [š® **Interactive Playground**](https://snack.expo.dev/@your-username/react-native-leader-line-playground) | Real-time property editor | Live adjustments, code generation |
| [š **Real-world Examples**](https://snack.expo.dev/@your-username/react-native-leader-line-real-world) | Production use cases | Workflows, networks, dashboards |
### š± Local Examples
For complete integration examples, check out the [`examples/`](./examples) directory:
#### Basic Example
Simple usage demonstrating core functionality:
```bash
cd examples/basic && npm install && npm run android
```
#### Advanced Example
Comprehensive demos with all features:
```bash
cd examples/advanced && npm install && npm run android
```
Both examples use the published npm package, showing exactly how to integrate the library in your projects.
## š¤ AI Assistant Integration
This library is designed to work seamlessly with AI coding assistants. The comprehensive documentation and type definitions enable AI tools to:
- Generate accurate code examples
- Suggest proper prop combinations
- Validate configurations automatically
- Provide context-aware completions
### For ChatGPT, Copilot, and other AI tools:
```tsx
// The library provides extensive type information and examples
// that AI tools can understand and use effectively
import {
LeaderLineProps,
SocketPosition,
PathType,
} from "react-native-leader-line";
// All types are thoroughly documented with JSDoc
const props: LeaderLineProps = {
start: { element: startRef },
end: { element: endRef },
// AI tools will suggest valid values with descriptions
endPlug: "arrow1", // Standard arrow (recommended)
path: "arc", // Simple curved arc
color: "#3498db", // Line color (CSS color string)
};
```
## š§ API Reference
### LeaderLine Props
| Prop | Type | Default | Description |
| ------------- | ---------------- | ------------ | ----------------------------------------------------------------- |
| `start` | `Attachment` | **required** | Starting attachment point |
| `end` | `Attachment` | **required** | Ending attachment point |
| `color` | `string` | `"#ff6b6b"` | Line color (CSS color string) |
| `strokeWidth` | `number` | `2` | Line thickness in pixels |
| `path` | `PathType` | `"straight"` | Line path type: `"straight"`, `"arc"`, `"fluid"`. See `PathType`. |
| `endPlug` | `PlugType` | `"arrow1"` | End marker style. See `PlugType` definition. |
| `startSocket` | `SocketPosition` | `"center"` | Connection point on start element |
| `endSocket` | `SocketPosition` | `"center"` | Connection point on end element |
### Socket Positions
```tsx
type SocketPosition =
| "auto" // Auto-detect best connection point
| "center" // Center of element
| "top" // Top center
| "right" // Right center
| "bottom" // Bottom center
| "left" // Left center
| "top_left" // Top-left corner
| "top_right" // Top-right corner
| "bottom_left" // Bottom-left corner
| "bottom_right"; // Bottom-right corner
```
### Plug Types
```typescript
type PlugType =
| "none"
| "arrow1"
| "arrow2"
| "arrow3"
| "disc"
| "square"
| "behind";
```
### Path Types
```typescript
type PathType = "straight" | "arc" | "fluid";
```
## š Migrating from leader-line
Coming from the original [leader-line](https://github.com/anseki/leader-line) library? We've got you covered!
### Quick Migration
**Before (leader-line):**
```javascript
const line = new LeaderLine(
document.getElementById('start'),
document.getElementById('end'),
{ color: 'coral', size: 4 }
);
```
**After (react-native-leader-line):**
```tsx
// Option 1: Declarative (Recommended)
<LeaderLine
start={{ element: startRef }}
end={{ element: endRef }}
color="coral"
strokeWidth={4}
/>
// Option 2: Imperative (Same API!)
const { LeaderLine } = useLeaderLineCompatibility();
const line = new LeaderLine(startRef, endRef, {
color: 'coral',
size: 4 // legacy property still works!
});
```
### Compatibility Features
- ā
**Same API**: `new LeaderLine(start, end, options)`
- ā
**Same methods**: `show()`, `hide()`, `setOptions()`, `remove()`
- ā
**Same properties**: `color`, `size`, `path`, `endPlug`, etc.
- ā
**Legacy support**: `size` property works alongside `strokeWidth`
š **[Full Migration Guide](./MIGRATION_GUIDE.md)** - Complete step-by-step migration instructions
## šÆ Common Patterns
### Basic Arrow
```tsx
<LeaderLine
start={{ element: startRef }}
end={{ element: endRef }}
color="#3498db"
strokeWidth={2}
endPlug="arrow1"
/>
```
### Styled Connection
```tsx
<LeaderLine
start={{ element: startRef }}
end={{ element: endRef }}
color="#e74c3c"
strokeWidth={4}
path="arc"
curvature={0.3}
endPlug="arrow2"
outline={{ enabled: true, color: "white", size: 2 }}
/>
```
### Animated Flow
```tsx
<LeaderLine
start={{ element: startRef }}
end={{ element: endRef }}
color="#2ecc71"
strokeWidth={3}
dash={{ pattern: "8,4", animation: true }}
endPlug="arrow1"
/>
```
## š§ For LLM Development
If you're an AI or working with LLMs to generate code using this library, check out:
- [`docs/llm-guide.js`](./docs/llm-guide.js) - Comprehensive examples and patterns
- [`.llmconfig.js`](./.llmconfig.js) - Library metadata and configuration
- Type definitions in [`src/types/index.ts`](./src/types/index.ts) - Complete TypeScript interfaces
## š Hook-based API (Manager Pattern)
For users who need to manage multiple lines programmatically:
```tsx
import React, { useEffect, useRef } from 'react';
import { View } from 'react-native';
import { useLeaderLineManager, LeaderLine } from "react-native-leader-line";
const MyComponent = () => {
const manager = useLeaderLineManager();
const startRef = useRef(null);
const endRef = useRef(null);
useEffect(() => {
// Create lines using the manager
const lineId = manager.createLine('my-line', {
start: { element: startRef },
end: { element: endRef },
color: "red",
strokeWidth: 3,
endPlug: "arrow2",
});
// Dynamic updates
setTimeout(() => {
manager.updateLine(lineId, { color: "blue", strokeWidth: 5 });
}, 1000);
// Show/hide with opacity changes
setTimeout(() => {
manager.hideLine(lineId); // Sets opacity to 0
setTimeout(() => manager.showLine(lineId), 500); // Sets opacity to 1
}, 2000);
return () => manager.removeLine(lineId);
}, []);
return (
<View>
<View ref={startRef} style={{...}} />
<View ref={endRef} style={{...}} />
{/* Render managed lines using functional components */}
{manager.lines.map((lineData) => (
<LeaderLine
key={lineData.id}
{...lineData.props}
/>
))}
</View>
);
};
```
### useLeaderLineManager API
The hook returns an object with the following methods and properties:
#### Methods
| Method | Parameters | Description |
| ------------ | ------------------------------------------------ | ------------------------------- |
| `createLine` | `(id: string, props?: Partial<LeaderLineProps>)` | Create a new line with given ID |
| `addLine` | `(id: string, props?: Partial<LeaderLineProps>)` | Alias for `createLine` |
| `updateLine` | `(id: string, props: Partial<LeaderLineProps>)` | Update line properties |
| `removeLine` | `(id: string)` | Remove a line by ID |
| `showLine` | `(id: string)` | Show a line (sets opacity to 1) |
| `hideLine` | `(id: string)` | Hide a line (sets opacity to 0) |
| `refreshAll` | `()` | Force refresh all lines |
| `clear` | `()` | Remove all lines |
| `clearAll` | `()` | Alias for `clear` |
| `getLine` | `(id: string)` | Get line data by ID |
| `hasLine` | `(id: string)` | Check if line exists |
#### Properties
| Property | Type | Description |
| --------------- | ----------------- | ---------------------------- |
| `lines` | `Array<LineData>` | Array of all managed lines |
| `isInitialized` | `boolean` | Whether the manager is ready |
#### LineData Structure
```tsx
interface LineData {
id: string;
props: Partial<LeaderLineProps>;
isVisible: boolean;
lastUpdate: number;
}
```
## š¤ Contributing
Contributions are welcome! Please read our contributing guidelines and ensure your code follows the TypeScript and documentation standards.
## š License
MIT License - see [LICENSE](LICENSE) file for details.
## š Acknowledgments
- Original [leader-line](https://github.com/anseki/leader-line) library by anseki
- React Native SVG team for the excellent SVG support
- Community contributors and feedback
---
**Made with ā¤ļø for the React Native community and optimized for AI development tools**