starchild-widget
v1.0.3
Published
Starchild Widget
Maintainers
Readme
StarChild Widget
A powerful React Widget SDK integrating AI chat, real-time voice, trading capabilities, search components, and more. Features include theme switching, internationalization, authentication management, and draggable floating components.
✨ Key Features
🤖 AI Chat Capabilities
- Intelligent Conversations: Natural language interaction with AI
- Real-time Voice: Real-time voice input and output (WebSocket streaming)
- Voice Recording: Trigger voice recording via click or keyboard shortcut
- Deep Thinking: Visualize AI thinking process
- Source References: Display data sources for AI responses
- Conversation History: Thread list management with session switching and deletion
- Feedback System: Like/dislike functionality with detailed feedback options
- Smart Recommendations: Intelligent suggestion of related questions
💰 Trading Features
- Order Entry: Support for market orders, limit orders, stop orders, and more
- Take Profit/Stop Loss: Set TP/SL prices
- Trailing Stop: Configurable trailing stop settings
- Order Confirmation: Secondary confirmation before order placement
- Real-time Charts: K-line chart display
- Leverage Selection: Adjustable leverage multiplier
- Position Management: Integrated position information
🔍 Search Functionality
- Global Search: Quick search capability
- Market Search: Token market search
- Quick Actions: Shortcuts to common operations
- Aurora Effects: Stunning visual effects
👤 Agent Management
- My Agent Panel: Agent overview and management
- Agent Cards: Detailed agent information display
- Unread Messages: Unread message count notifications
🎨 Theming & Styling
- Dark/Light Mode: Theme mode switching
- Custom Themes: Fully customizable color schemes
- Mode-specific Configuration: Separate configurations for dark/light modes
- Global CSS: Custom global style injection
- Shadow DOM: Component style isolation to prevent conflicts
- Responsive Design: Adaptive to different screen sizes
🌍 Internationalization
- Multi-language Support: Chinese, English, and more
- Dynamic Switching: Runtime language switching
- Lingui Framework: Modern i18n solution based on Lingui
⚡ User Experience
- Draggable Components: Freely draggable chat button positioning
- Position Memory: Automatic save and restore of component positions
- Keyboard Shortcuts: Customizable voice and chat shortcuts
- Event Callbacks: Rich lifecycle and event hooks
- Container Mode: Support for rendering in specified containers
- Auto/Manual Init: Support for automatic or manual initialization
🔐 Authentication & Security
- Multi-key Authentication: Support for secretKey, orderlyKey, aiChatKey, etc.
- Sub-account Support: Switch between main and sub-accounts
- Environment Configuration: Testnet/Mainnet environment switching
🛠️ Developer Friendly
- TypeScript: Complete type definition support
- React Hooks: Provides
useStarChildWidgetHook - Modular Architecture: Clear component and state management architecture
- State Persistence: Automatic persistence of user settings and positions
- Error Handling: Comprehensive error handling and callback mechanisms
- Development Tools: Rich development and debugging tools
📦 Installation
NPM Installation (Recommended)
This widget supports installation via npm package managers and is designed specifically for React projects:
# Using npm
npm install starchild-widget
# Using yarn
yarn add starchild-widget
# Using pnpm
pnpm add starchild-widgetPeer Dependencies
{
"react": ">=18.0.0",
"react-dom": ">=18.0.0",
"styled-components": ">=6.0.0"
}Note: This widget does not support CDN imports and must be used in React projects.
🚀 Quick Start
React Hook Method (Recommended)
This widget exposes APIs through React Hooks, providing automated lifecycle management and a clean functional interface.
Complete Configuration Example
import { useStarChildWidget, ThemeMode, Locale, ComponentType } from 'starchild-widget'
function MyComponent() {
const {
init,
isInitialized,
setThemeMode,
setLocale,
setChatVisible,
showChat,
getVoiceShortcut,
getChatShortcut,
getUnreadCount,
// ... more methods
} = useStarChildWidget()
React.useEffect(() => {
init({
// Theme configuration
themeMode: ThemeMode.DARK, // ThemeMode.DARK | ThemeMode.LIGHT
customTheme: {
colors: {
dn1: '#00d4ff',
dn2: '#ff6b6b'
}
},
// Language configuration
locale: Locale.ZH_CN, // Locale.EN_US | Locale.ZH_CN
// Environment configuration
environment: 'testnet', // 'testnet' | 'mainnet'
// Authentication configuration (Required)
secretKey: 'your-secret-key',
accountId: 'your-account-id',
account: 'your-account', // Optional
orderlyKey: 'your-orderly-key',
aiChatKey: 'your-ai-chat-key',
userInfoId: 'your-user-info-id',
// Component configuration
components: {
chat: {
type: ComponentType.CHAT,
visible: true,
disabled: false
},
search: {
type: ComponentType.SEARCH,
visible: false,
disabled: false,
value: '',
placeholder: 'Search...'
}
},
// Global styles
zIndex: 9999,
globalCSS: 'your-custom-css',
// Event callbacks
onError: (error) => {
console.error('Widget Error:', error)
},
onPositionChange: (position) => {
console.log('Component position changed:', position)
},
onReady: () => {
console.log('Widget Ready!')
},
onSearchOpen: () => {
console.log('Search opened')
},
onSearchClose: () => {
console.log('Search closed')
},
onChatShow: () => {
console.log('Chat shown')
},
onChatHide: () => {
console.log('Chat hidden')
},
onMarketSwitch: (symbol) => {
console.log('Market switched to:', symbol)
},
onVoiceShortcutChange: (voiceShortcut) => {
console.log('Voice shortcut changed to:', voiceShortcut)
},
onChatShortcutChange: (chatShortcut) => {
console.log('Chat shortcut changed to:', chatShortcut)
},
onUnreadCountChange: (count) => {
console.log('Unread count changed to:', count)
}
})
}, [init])
return (
<div>
{/* Your application content */}
</div>
)
}Configuration Options (WidgetConfig)
| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| themeMode | ThemeMode.LIGHT \| ThemeMode.DARK | No | ThemeMode.DARK | Theme mode (dark/light) |
| customTheme | Partial<Theme> | No | - | Custom theme override with color palette |
| locale | Locale.EN_US \| Locale.ZH_CN | No | Locale.EN_US | Language setting |
| environment | 'testnet' \| 'mainnet' | No | 'testnet' | Blockchain environment configuration |
| secretKey | string | Yes | - | Secret Key for authentication |
| accountId | string | Yes | - | Account ID for authentication |
| account | string | No | - | Account address (optional) |
| orderlyKey | string | Yes | - | Orderly Key for trading authentication |
| aiChatKey | string | Yes | - | AI Chat API Key for chat features |
| userInfoId | string | Yes | - | User Info ID for personalization |
| components | ComponentConfig | No | - | Component-specific configuration |
| components.chat | ChatConfig | No | {type: ComponentType.CHAT, visible: true, disabled: false} | Chat component configuration |
| components.search | SearchConfig | No | {type: ComponentType.SEARCH, visible: false, disabled: false} | Search component configuration |
| zIndex | number | No | 10000 | Base z-index level for widget layers |
| globalCSS | string | No | - | Global CSS styles to inject |
| onError | (error: Error) => void | No | - | Error callback handler |
| onPositionChange | (position: Position) => void | No | - | Position change callback (when dragging) |
| onReady | () => void | No | - | Widget ready callback |
| onSearchOpen | () => void | No | - | Search component open callback |
| onSearchClose | () => void | No | - | Search component close callback |
| onChatShow | () => void | No | - | Chat modal show callback |
| onChatHide | () => void | No | - | Chat modal hide callback |
| onMarketSwitch | (symbol: string) => void | No | - | Market/token switch callback |
| onVoiceShortcutChange | (voiceShortcut: string) => void | No | - | Voice shortcut key change callback |
| onChatShortcutChange | (chatShortcut: string) => void | No | - | Chat shortcut key change callback |
| onUnreadCountChange | (count: number) => void | No | - | Unread message count change callback |
🎯 API Methods
The useStarChildWidget Hook provides the following methods:
Initialization & Lifecycle
init(config: WidgetConfig)- Initialize the widgetinit({ secretKey: 'your-secret-key', accountId: 'your-account-id', orderlyKey: 'your-orderly-key', aiChatKey: 'your-ai-chat-key', userInfoId: 'your-user-info-id', })destroy()- Destroy the widget instancedestroy()isInitialized- Check if the widget is initialized (boolean property)if (isInitialized) { // Widget is ready }updateConfig(config: Partial<WidgetConfig>)- Update widget configurationupdateConfig({ themeMode: ThemeMode.LIGHT })getConfig()- Get current widget configurationconst config = getConfig()
General Configuration Methods
setThemeMode(mode: ThemeMode)- Set theme modesetThemeMode(ThemeMode.LIGHT)setLocale(locale: Locale)- Set languagesetLocale(Locale.ZH_CN)setEnvironment(environment: 'testnet' | 'mainnet')- Set environmentsetEnvironment('mainnet')
Chat Component Control
showChat(containerId?: string)- Show the chat modal directly// Show chat modal in default position showChat() // Show chat modal in a specific container showChat('my-container-id')setChatVisible(visible: boolean)- Show/hide chat componentsetChatVisible(true)getChatVisible()- Get chat component visibility stateconst isVisible = getChatVisible()setChatDisabled(disabled: boolean)- Enable/disable chat componentsetChatDisabled(false)setChatPosition(position: Position)- Set chat component positionsetChatPosition({ x: 100, y: 100 })resetChatPosition()- Reset chat component position to defaultresetChatPosition()triggerVoiceRecording()- Trigger voice recordingtriggerVoiceRecording()showMyAgent()- Show the My Agent panel in the chat modal// Opens chat modal and displays My Agent panel showMyAgent()
Account Management
setIsSubAccount(isSubAccount: boolean)- Set whether the account is a sub-account// Switch to sub-account mode setIsSubAccount(true) // Switch to main account mode setIsSubAccount(false)getIsSubAccount()- Get current account type statusconst isSubAccount = getIsSubAccount() console.log('Is sub-account:', isSubAccount)
Search Component Control
setSearchVisible(visible: boolean)- Show/hide search inputsetSearchVisible(true)setSearchDisabled(disabled: boolean)- Enable/disable search inputsetSearchDisabled(false)setSearchValue(value: string)- Set search input valuesetSearchValue('BTC')setSearchPlaceholder(placeholder: string)- Set search input placeholdersetSearchPlaceholder('Search tokens...')
Shortcut & State Getters
getVoiceShortcut()- Get the current voice shortcut valueconst voiceShortcut = getVoiceShortcut() console.log('Current voice shortcut:', voiceShortcut) // e.g., "L"getChatShortcut()- Get the current chat shortcut valueconst chatShortcut = getChatShortcut() console.log('Current chat shortcut:', chatShortcut) // e.g., "K"getUnreadCount()- Get the current unread count valueconst unreadCount = getUnreadCount() console.log('Unread count:', unreadCount)
Note: To listen for shortcut and unread count changes, use the corresponding callback functions (
onVoiceShortcutChange,onChatShortcutChange,onUnreadCountChange) in the widget configuration
Other Exported Items
While using the Hook is recommended, the following items can also be imported from the package:
import {
StarChildWidget, // Widget class (not recommended for direct use)
init, // Init function (not recommended for direct use)
getInstance, // Get instance function (not recommended for direct use)
destroy, // Destroy function (not recommended for direct use)
ThemeMode, // Theme mode enum
Locale, // Locale enum
ComponentType, // Component type enum
} from 'starchild-widget'
// Note: Direct class methods are mainly for internal implementation
// Always use useStarChildWidget Hook for better React integrationRecommendation: Always use the
useStarChildWidgetHook, which provides better React integration and automatic lifecycle management.
📋 Complete Hook API Reference
The useStarChildWidget hook returns an object with the following properties and methods:
interface UseStarChildWidgetReturn {
// Instance & State
widget: StarChildWidget | null
isInitialized: boolean
// Lifecycle
init: (config: WidgetConfig) => void
destroy: () => void
updateConfig: (config: Partial<WidgetConfig>) => void
getConfig: () => WidgetConfig | null
// General Configuration
setThemeMode: (themeMode: ThemeMode) => void
setLocale: (locale: Locale) => void
setEnvironment: (environment: 'testnet' | 'mainnet') => void
// Chat Component Control
setChatVisible: (visible: boolean) => void
getChatVisible: () => boolean
setChatDisabled: (disabled: boolean) => void
setChatPosition: (position: Position) => void
showChat: (containerId?: string) => void
resetChatPosition: () => void
triggerVoiceRecording: () => void
showMyAgent: () => void
// Account Management
setIsSubAccount: (isSubAccount: boolean) => void
getIsSubAccount: () => boolean
// Search Component Control
setSearchVisible: (visible: boolean) => void
setSearchDisabled: (disabled: boolean) => void
setSearchValue: (value: string) => void
setSearchPlaceholder: (placeholder: string) => void
// Getters
getVoiceShortcut: () => string
getChatShortcut: () => string
getUnreadCount: () => number
}