Skip to content

Expand documentation with examples and best practices #149

@RAprogramm

Description

@RAprogramm

Problem

The SDK provides comprehensive Telegram WebApp API coverage but documentation and examples focus primarily on basic initialization and framework integration. Advanced features lack usage demonstrations, making it difficult for developers to:

  1. Understand best practices for complex features
  2. Test their implementations effectively
  3. Handle edge cases properly
  4. Optimize WASM performance

Missing Documentation

Undocumented Features

The following APIs are implemented but lack examples:

  1. Cloud Storage - No examples for secure storage or standard storage
  2. Biometric Authentication - Missing usage patterns for biometric manager
  3. Device Sensors - No accelerometer or gyroscope examples
  4. Location Services - Location manager usage not demonstrated
  5. Haptic Feedback - No haptic API examples
  6. Settings Button - Mentioned but not documented
  7. Home Screen Shortcuts - Referenced but no implementation guide
  8. Background Events - No examples for background/foreground lifecycle

Incomplete Guides

  1. Error Handling - Limited guidance on recovery strategies
  2. Testing Patterns - Mock environment exists but testing workflows not documented
  3. Performance - No optimization guidance for WASM bundles
  4. Migration - No upgrade guides between versions
  5. Security - Best practices for initData handling missing

Framework Integration Gaps

While Yew and Leptos have basic examples, advanced patterns are absent:

  1. State Management - Integrating with yewdux/leptos_reactive
  2. Routing - Deep linking and navigation patterns
  3. Component Composition - Building complex UIs with SDK hooks
  4. Error Boundaries - Handling SDK failures gracefully

Proposed Solutions

1. Comprehensive Example Applications

Create full-featured example apps demonstrating:

examples/
├── basic/                    # Minimal setup
├── payments/                 # Invoice handling
├── storage/                  # Cloud storage patterns
├── biometric-auth/           # Biometric authentication
├── sensors/                  # Device sensor integration
├── location/                 # Location services
├── haptics/                  # Haptic feedback
└── full-featured-yew/        # Complete Yew app
    └── full-featured-leptos/ # Complete Leptos app

2. API Documentation Enhancements

Add to each major API module:

/// # Cloud Storage
///
/// Provides persistent key-value storage in Telegram cloud.
///
/// ## Examples
///
/// ### Basic Usage
/// ```rust
/// use telegram_webapp_sdk::TelegramWebApp;
///
/// let app = TelegramWebApp::instance()?;
/// let storage = app.cloud_storage()?;
///
/// // Store data
/// storage.set_item("user_pref", "dark_mode").await?;
///
/// // Retrieve data
/// let pref = storage.get_item("user_pref").await?;
/// ```
///
/// ### Error Handling
/// ```rust
/// match storage.set_item("key", "value").await {
///     Ok(_) => println!("Saved successfully"),
///     Err(e) => eprintln!("Storage error: {:?}", e),
/// }
/// ```
///
/// ### Common Patterns
/// ```rust
/// // Batch operations
/// let items = vec![("k1", "v1"), ("k2", "v2")];
/// for (key, val) in items {
///     storage.set_item(key, val).await?;
/// }
///
/// // Clear all data
/// storage.clear().await?;
/// ```
///
/// ## Errors
///
/// Returns `Err` when:
/// - Storage quota exceeded
/// - Network unavailable
/// - Invalid key format
/// - Permission denied
///
/// ## Platform Notes
///
/// Cloud storage may not be available in all Telegram clients.
/// Use `try_cloud_storage()` to handle unsupported environments.

3. Testing Guide

Document testing strategies:

## Testing Your Telegram Mini App

### Unit Testing with Mocks

Configure mock environment in `telegram-webapp.toml`:

\`\`\`toml
[mock]
user_id = 12345
first_name = "Test User"
platform = "ios"
\`\`\`

### Integration Testing

\`\`\`rust
#[cfg(test)]
mod tests {
    use telegram_webapp_sdk::mock::MockTelegramWebApp;
    
    #[test]
    fn test_user_flow() {
        let mock = MockTelegramWebApp::new();
        mock.set_user_id(12345);
        // Test your logic
    }
}
\`\`\`

### E2E Testing

Use Telegram Bot API test environment...

4. Migration Guides

For each major version:

## Migrating from 0.2.x to 0.3.x

### Breaking Changes

1. `init_sdk()` now returns typed errors:
   \`\`\`diff
   - pub fn init_sdk() -> Result<(), JsValue>
   + pub fn init_sdk() -> Result<(), InitError>
   \`\`\`

2. Event handlers now return cleanup handles:
   \`\`\`diff
   - app.on_theme_changed(callback)?;
   + let handle = app.on_theme_changed(callback)?;
   + // Remember to drop handle on unmount
   \`\`\`

### Deprecated APIs

- `TelegramWebApp::old_method` → Use `new_method` instead

5. Best Practices Guide

## Best Practices

### Performance

1. Lazy-load SDK features:
   \`\`\`rust
   let storage = app.cloud_storage().ok();
   if let Some(s) = storage {
       // Use storage
   }
   \`\`\`

2. Minimize WASM bundle size with selective features:
   \`\`\`toml
   [dependencies.telegram-webapp-sdk]
   default-features = false
   features = ["yew", "storage"]
   \`\`\`

### Security

1. Never validate initData on client
2. Always send raw initData to backend
3. Use HTTPS for all API calls

### Error Handling

1. Gracefully degrade when features unavailable
2. Provide user feedback on errors
3. Log failures for debugging

Benefits

  1. Faster Onboarding - Developers find answers quickly
  2. Fewer Support Issues - Self-service documentation
  3. Better Quality - Following best practices from start
  4. Increased Adoption - Lower barrier to entry
  5. Community Contributions - Clear examples enable contributions

Priority

Medium-High - Good documentation significantly impacts developer experience and adoption.

Implementation Plan

  1. Start with most-used features (storage, payments)
  2. Add examples incrementally
  3. Gather feedback from early adopters
  4. Iterate based on common questions

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions