CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-ionic--react

React specific wrapper for @ionic/core providing React components and hooks for building cross-platform mobile applications

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

platform-utilities.mddocs/

Platform Utilities

Utilities for platform detection, configuration management, and platform-specific adaptations that enable responsive behavior across iOS, Android, and web platforms.

Capabilities

Platform Detection

Functions for detecting the current platform and adapting application behavior accordingly.

/**
 * Check if the current platform matches the specified platform type.
 * Useful for conditional rendering and platform-specific behavior.
 * @param platform - Platform type to check against
 * @returns true if the current platform matches the specified platform
 */
function isPlatform(platform: Platforms): boolean;

/**
 * Get all currently active platforms as an array of strings.
 * A device can match multiple platforms (e.g., ['mobile', 'ios', 'pwa']).
 * @returns Array of currently active platform names
 */
function getPlatforms(): string[];

/**
 * Platform types that can be detected by isPlatform.
 */
type Platforms = 
  /** iOS platform (iPhone, iPad) */
  | 'ios'
  /** Android platform */
  | 'android'
  /** Progressive Web App */
  | 'pwa'
  /** Any mobile platform (iOS or Android) */
  | 'mobile'
  /** Mobile web browser */
  | 'mobileweb'
  /** Desktop/laptop computer */
  | 'desktop'
  /** Hybrid app (Capacitor/Cordova) */
  | 'hybrid'
  /** Tablet device */
  | 'tablet'
  /** Phone device */
  | 'phone'
  /** Electron app */
  | 'electron';

Animation Utilities

Utilities for creating custom animations and integrating with Ionic's animation system.

/**
 * Creates a new animation with Web Animations API integration
 * @returns Animation instance for chaining
 */
function createAnimation(animationId?: string): Animation;

/**
 * Animation builder function type for custom transitions
 */
type AnimationBuilder = (
  baseEl: any,
  opts?: any
) => Animation;

/**
 * iOS-style transition animation
 */
function iosTransitionAnimation(
  navEl: HTMLElement,
  opts: TransitionOptions
): Animation;

/**
 * Material Design transition animation  
 */
function mdTransitionAnimation(
  navEl: HTMLElement,
  opts: TransitionOptions
): Animation;

/**
 * Utility for animation timing calculations
 */
function getTimeGivenProgression(
  p0: number,
  p1: number,
  p2: number,
  p3: number,
  progression: number
): number;

interface Animation {
  /** Add one or more elements to the animation */
  addElement(el: Element | Element[] | Node | Node[]): Animation;
  /** Add CSS class to animation elements */
  addClassNames(classNames: string[]): Animation;
  /** Remove CSS class from animation elements */
  removeClassNames(classNames: string[]): Animation;
  /** Set animation properties */
  duration(milliseconds: number): Animation;
  easing(name: string): Animation;
  from(property: string, value: any): Animation;
  to(property: string, value: any): Animation;
  /** Set keyframes for the animation */
  keyframes(keyframes: any[]): Animation;
  /** Control animation playback */
  play(): Promise<void>;
  pause(): Animation;
  stop(): Animation;
  destroy(): Animation;
  /** Animation callbacks */
  onFinish(callback: (didComplete: boolean, animation: Animation) => void): Animation;
  beforeStyles(styles: { [property: string]: any }): Animation;
  afterStyles(styles: { [property: string]: any }): Animation;
}

interface TransitionOptions {
  mode?: string;
  animated?: boolean;
  direction?: 'forward' | 'back';
  duration?: number;
  easing?: string;
  progressAnimation?: boolean;
}

Gesture Utilities

Utilities for creating custom gestures and handling touch interactions.

/**
 * Creates a custom gesture with touch/mouse event handling
 * @param options - Gesture configuration options
 * @returns Gesture instance
 */
function createGesture(options: GestureConfig): Gesture;

interface GestureConfig {
  /** Element to attach gesture to */
  el: HTMLElement;
  /** Gesture name/identifier */
  gestureName: string;
  /** Threshold before gesture starts */
  threshold?: number;
  /** Gesture priority */
  gesturePriority?: number;
  /** Whether gesture can start */
  canStart?: (detail: GestureDetail) => boolean;
  /** Gesture start callback */
  onStart?: (detail: GestureDetail) => void;
  /** Gesture move callback */
  onMove?: (detail: GestureDetail) => void;
  /** Gesture end callback */
  onEnd?: (detail: GestureDetail) => void;
  /** Whether to capture events */
  capture?: boolean;
  /** Passive event listeners */
  passive?: boolean;
}

interface Gesture {
  /** Enable the gesture */
  enable(enable?: boolean): void;
  /** Destroy the gesture */
  destroy(): void;
}

interface GestureDetail {
  /** Gesture type */
  type: string;
  /** Starting X coordinate */
  startX: number;
  /** Starting Y coordinate */
  startY: number;
  /** Current X coordinate */
  currentX: number;
  /** Current Y coordinate */
  currentY: number;
  /** Change in X from start */
  deltaX: number;
  /** Change in Y from start */
  deltaY: number;
  /** Time elapsed since start */
  timeStamp: number;
  /** Original event */
  event: any;
  /** Additional data */
  data?: any;
}

Swiper Integration

Integration with Swiper.js for advanced slider functionality.

/**
 * IonicSlides - Swiper integration for Ionic
 * Configuration object for Swiper with Ionic-specific defaults
 */
const IonicSlides: {
  /** Enable touch gestures */
  touch?: boolean;
  /** Enable keyboard navigation */
  keyboard?: boolean;
  /** Enable mouse wheel control */
  mousewheel?: boolean;
  /** Autoplay configuration */
  autoplay?: boolean | object;
  /** Loop slides */
  loop?: boolean;
  /** Number of slides per view */
  slidesPerView?: number | 'auto';
  /** Space between slides */
  spaceBetween?: number;
  /** Pagination configuration */
  pagination?: boolean | object;
  /** Navigation arrows */
  navigation?: boolean | object;
  /** Scrollbar */
  scrollbar?: boolean | object;
  /** Free mode */
  freeMode?: boolean;
  /** Effect transition */
  effect?: 'slide' | 'fade' | 'cube' | 'coverflow' | 'flip';
};

Utility Functions

Additional platform and navigation utilities.

/**
 * Get the IonPage element for the current view
 */
function getIonPageElement(element: HTMLElement): HTMLElement | null;

/**
 * Open URL with appropriate handler for the platform
 */
function openURL(
  url: string, 
  target?: string, 
  features?: string
): Promise<void>;

Configuration Management

Functions for managing global Ionic configuration and retrieving current settings.

/**
 * Get the current Ionic configuration object.
 * Returns the configuration set by setupIonicReact or platform defaults.
 * @returns Current Ionic configuration or null if not initialized
 */
function getConfig(): IonicConfig | null;

/**
 * Global configuration interface for Ionic React.
 * These settings affect the behavior and appearance of all Ionic components.
 */
interface IonicConfig {
  /** Enable/disable ripple effect on interactive elements globally */
  rippleEffect?: boolean;
  /** Global mode setting for all components */
  mode?: 'ios' | 'android' | 'md';
  /** Enable/disable swipe-to-go-back gesture */
  swipeBackEnabled?: boolean;
  /** Enable/disable animations globally */
  animated?: boolean;
  /** Animation duration in milliseconds */
  animationDuration?: number;
  /** Default spinner type for loading components */
  spinner?: SpinnerTypes;
  /** Platform-specific configuration overrides */
  platforms?: {
    [platform: string]: Partial<IonicConfig>;
  };
  /** Menu settings */
  menuIcon?: string;
  menuType?: 'overlay' | 'reveal' | 'push';
  /** Back button settings */
  backButtonIcon?: string;
  backButtonText?: string;
  /** Tab bar settings */
  tabButtonLayout?: 'icon-top' | 'icon-start' | 'icon-end' | 'icon-bottom' | 'icon-hide' | 'label-hide';
  /** Global color scheme */
  darkMode?: boolean;
}

/**
 * Available spinner types for loading indicators.
 */
type SpinnerTypes = 
  | 'bubbles' 
  | 'circles' 
  | 'circular' 
  | 'crescent' 
  | 'dots' 
  | 'lines' 
  | 'lines-small';

Animation Utilities

Utilities for creating and managing animations with platform-specific behavior.

/**
 * Declarative animation component for creating complex animations.
 * Provides a React wrapper around Ionic's createAnimation API.
 */
const CreateAnimation: React.FC<{
  /** Animation delay in milliseconds */
  delay?: number;
  /** Animation direction */
  direction?: 'normal' | 'reverse' | 'alternate' | 'alternate-reverse';
  /** Animation duration in milliseconds */
  duration?: number;
  /** Animation easing function */
  easing?: string;
  /** End delay in milliseconds */
  endDelay?: number;
  /** Animation fill mode */
  fill?: 'none' | 'forwards' | 'backwards' | 'both';
  /** Number of iterations */
  iterations?: number;
  /** Animation keyframes */
  keyframes?: any[];
  /** Play state */
  play?: boolean;
  /** Animation builder function */
  children?: (animation: Animation) => React.ReactNode;
  /** Callback when animation starts */
  onAnimationStart?: (animation: Animation) => void;
  /** Callback when animation ends */
  onAnimationEnd?: (animation: Animation) => void;
}>;

/**
 * Animation instance interface for controlling animations.
 */
interface Animation {
  /** Add CSS class to animated elements */
  addElement(element: HTMLElement | HTMLElement[]): Animation;
  /** Remove CSS class from animated elements */
  removeElement(element: HTMLElement | HTMLElement[]): Animation;
  /** Add CSS class during animation */
  addClasses(classes: string[]): Animation;
  /** Remove CSS class during animation */
  removeClasses(classes: string[]): Animation;
  /** Set CSS properties for animation */
  css(property: string, value: string): Animation;
  /** Set transform properties */
  transform(transform: string): Animation;
  /** Play the animation */
  play(): Promise<void>;
  /** Pause the animation */
  pause(): Animation;
  /** Stop the animation */
  stop(): Animation;
  /** Destroy the animation */
  destroy(): Animation;
}

Usage Examples:

import React from 'react';
import { 
  isPlatform, 
  getPlatforms, 
  getConfig, 
  CreateAnimation,
  IonButton,
  IonContent,
  IonPage
} from '@ionic/react';

// Platform-specific rendering
const PlatformSpecificComponent: React.FC = () => {
  const isIOS = isPlatform('ios');
  const isAndroid = isPlatform('android');
  const isMobile = isPlatform('mobile');
  const platforms = getPlatforms();

  return (
    <IonContent>
      <div>
        <p>Current platforms: {platforms.join(', ')}</p>
        
        {isIOS && (
          <p>Welcome iOS user! Enjoy the native iOS experience.</p>
        )}
        
        {isAndroid && (
          <p>Welcome Android user! Material Design at its finest.</p>
        )}
        
        {!isMobile && (
          <p>You're using a desktop browser. Consider our mobile app!</p>
        )}
        
        <IonButton 
          fill={isIOS ? 'outline' : 'solid'}
          color={isAndroid ? 'primary' : 'secondary'}
        >
          Platform-styled Button
        </IonButton>
      </div>
    </IonContent>
  );
};

// Configuration-based behavior
const ConfigAwareComponent: React.FC = () => {
  const config = getConfig();
  const isAnimated = config?.animated !== false;
  const rippleEffect = config?.rippleEffect !== false;

  return (
    <IonButton 
      className={!rippleEffect ? 'no-ripple' : ''}
      style={{
        transition: isAnimated ? 'all 0.3s ease' : 'none'
      }}
    >
      {isAnimated ? 'Animated Button' : 'Static Button'}
    </IonButton>
  );
};

// Animation example
const AnimatedComponent: React.FC = () => {
  return (
    <CreateAnimation
      duration={1000}
      iterations={1}
      direction="normal"
      fill="forwards"
      keyframes={[
        { offset: 0, transform: 'scale(1) rotate(0deg)', opacity: '1' },
        { offset: 0.5, transform: 'scale(1.2) rotate(180deg)', opacity: '0.8' },
        { offset: 1, transform: 'scale(1) rotate(360deg)', opacity: '1' }
      ]}
      onAnimationEnd={(animation) => console.log('Animation completed')}
    >
      {(animation) => (
        <div 
          ref={(el) => el && animation.addElement(el)}
          style={{ 
            width: '100px', 
            height: '100px', 
            backgroundColor: 'var(--ion-color-primary)' 
          }}
        >
          Animated Element
        </div>
      )}
    </CreateAnimation>
  );
};

// Responsive design with platform detection
const ResponsiveLayout: React.FC = () => {
  const isTablet = isPlatform('tablet');
  const isDesktop = isPlatform('desktop');
  const isMobile = isPlatform('mobile');

  const getColumnSize = () => {
    if (isDesktop) return '4';
    if (isTablet) return '6';
    return '12';
  };

  return (
    <IonGrid>
      <IonRow>
        <IonCol size={getColumnSize()}>
          <IonCard>
            <IonCardContent>
              Content optimized for {
                isDesktop ? 'desktop' : 
                isTablet ? 'tablet' : 
                'mobile'
              }
            </IonCardContent>
          </IonCard>
        </IonCol>
      </IonRow>
    </IonGrid>
  );
};

// Custom hook for platform-specific logic
const usePlatformSpecificBehavior = () => {
  const isIOS = isPlatform('ios');
  const isAndroid = isPlatform('android');
  const config = getConfig();

  const getButtonStyle = () => ({
    borderRadius: isIOS ? '8px' : '4px',
    padding: isIOS ? '12px 24px' : '10px 20px',
    fontWeight: isIOS ? '600' : '500'
  });

  const getTransitionDuration = () => {
    if (config?.animated === false) return '0ms';
    return isIOS ? '300ms' : '250ms';
  };

  return {
    isIOS,
    isAndroid,
    getButtonStyle,
    getTransitionDuration,
    hapticFeedbackEnabled: isIOS || (isAndroid && isPlatform('hybrid'))
  };
};

// Usage of custom hook
const PlatformAwareButton: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const { getButtonStyle, getTransitionDuration, hapticFeedbackEnabled } = usePlatformSpecificBehavior();

  const handleClick = () => {
    if (hapticFeedbackEnabled) {
      // Trigger haptic feedback on supported platforms
      // This would require Capacitor Haptics plugin
    }
    console.log('Button clicked');
  };

  return (
    <IonButton 
      style={{
        ...getButtonStyle(),
        transition: `all ${getTransitionDuration()} ease`
      }}
      onClick={handleClick}
    >
      {children}
    </IonButton>
  );
};

Platform Detection Reference

PlatformDescriptionWhen it matches
iosiOS devicesiPhone, iPad running iOS
androidAndroid devicesDevices running Android OS
mobileMobile devicesAny mobile device (iOS or Android)
tabletTablet devicesiPad or Android tablets
phonePhone devicesiPhone or Android phones
desktopDesktop browsersDesktop/laptop browsers
pwaProgressive Web AppApp installed as PWA
hybridHybrid appCapacitor or Cordova app
electronElectron appApp running in Electron
mobilewebMobile webMobile browser (not hybrid)

Best Practices

  1. Responsive Design: Use platform detection for responsive layouts and component behavior
  2. Performance: Check platform capabilities to enable/disable features appropriately
  3. User Experience: Adapt animations and transitions to platform conventions
  4. Testing: Test platform-specific code paths across different devices and browsers
  5. Progressive Enhancement: Use platform detection to enhance experiences rather than restrict them

docs

core-setup.md

index.md

lifecycle-management.md

navigation-routing.md

overlay-management.md

platform-utilities.md

ui-components.md

tile.json