CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-react-native-windows

React Native for Windows framework that enables cross-platform mobile and desktop app development with JavaScript and TypeScript

Pending
Overview
Eval results
Files

events.mddocs/

Event Handling System

Comprehensive event handling system with Windows-specific enhancements including keyboard navigation, mouse interactions, focus management, and native event integration.

Capabilities

Keyboard Events

Enhanced Keyboard Support

Windows-specific keyboard event handling with support for modifier keys, key combinations, and navigation patterns.

/**
 * Event phase enumeration for keyboard and mouse events
 */
namespace EventPhase {
  export const None = 0;
  export const Capturing = 1;
  export const AtTarget = 2;
  export const Bubbling = 3;
}

/**
 * React Native synthetic event wrapper
 */
interface NativeSyntheticEvent<T> {
  nativeEvent: T;
  currentTarget: EventTarget;
  target: EventTarget;
  bubbles: boolean;
  cancelable: boolean;
  defaultPrevented: boolean;
  eventPhase: number;
  isTrusted: boolean;
  preventDefault(): void;
  stopPropagation(): void;
  timeStamp: number;
  type: string;
}

/**
 * Windows keyboard event interface with comprehensive key information
 * Supports modifier keys, key codes, and event phases
 */
interface INativeKeyboardEvent {
  /** Alt key pressed state */
  altKey: boolean;
  /** Ctrl key pressed state */
  ctrlKey: boolean;
  /** Meta key (Windows key) pressed state */
  metaKey: boolean;
  /** Shift key pressed state */
  shiftKey: boolean;
  /** Key identifier string */
  key: string;
  /** Physical key code */
  code: string;
  /** Event phase (capturing, at target, bubbling) */
  eventPhase: EventPhase.None | EventPhase.Capturing | EventPhase.AtTarget | EventPhase.Bubbling;
}

type IKeyboardEvent = NativeSyntheticEvent<INativeKeyboardEvent>;

/**
 * Handled keyboard event configuration interface
 */
interface IHandledKeyboardEvent {
  /** Alt key requirement */
  altKey?: boolean;
  /** Ctrl key requirement */
  ctrlKey?: boolean;
  /** Meta key requirement */
  metaKey?: boolean;
  /** Shift key requirement */
  shiftKey?: boolean;
  /** Physical key code to handle */
  code: string;
  /** Event phase to handle */
  handledEventPhase?: EventPhase.Capturing | EventPhase.Bubbling;
}

/**
 * Keyboard event handlers for Windows components
 */
interface KeyboardEventHandlers {
  /** Key down event handler */
  onKeyDown?: (args: IKeyboardEvent) => void;
  /** Key up event handler */
  onKeyUp?: (args: IKeyboardEvent) => void;
  /** Capture phase key down handler */
  onKeyDownCapture?: (args: IKeyboardEvent) => void;
  /** Capture phase key up handler */
  onKeyUpCapture?: (args: IKeyboardEvent) => void;
  /** Array of handled keyboard events for onKeyDown */
  keyDownEvents?: IHandledKeyboardEvent[];
  /** Array of handled keyboard events for onKeyUp */
  keyUpEvents?: IHandledKeyboardEvent[];
}

Usage Examples:

import React from 'react';
import { View, Text } from 'react-native-windows';

const KeyboardExample: React.FC = () => {
  const handleKeyDown = (event: IKeyboardEvent) => {
    const { key, ctrlKey, shiftKey, altKey } = event.nativeEvent;

    // Handle specific key combinations
    if (ctrlKey && key === 's') {
      console.log('Save shortcut pressed');
      event.preventDefault();
    } else if (key === 'Enter') {
      console.log('Enter key pressed');
    } else if (key === 'Escape') {
      console.log('Escape key pressed');
    }

    // Handle modifier combinations
    if (ctrlKey && shiftKey && key === 'p') {
      console.log('Command palette shortcut');
    }
  };

  return (
    <View
      tabIndex={0}
      onKeyDown={handleKeyDown}
      keyDownEvents={[
        { code: 'Enter' },
        { code: 'Escape' },
        { code: 'Space' },
        { code: 'ArrowUp' },
        { code: 'ArrowDown' }
      ]}
      style={{ padding: 16, backgroundColor: '#f0f0f0' }}
    >
      <Text>Press keys to interact</Text>
    </View>
  );
};

Mouse Events

Mouse Interaction Support

Comprehensive mouse event handling with button states, coordinates, and modifier key support.

/**
 * Windows mouse event interface with detailed interaction information
 * Provides button states, coordinates, and modifier keys
 */
type INativeMouseEvent = {
  /** Target element reference */
  target: number;
  /** Mouse event identifier */
  identifier: number;
  /** X coordinate relative to page */
  pageX: number;
  /** Y coordinate relative to page */
  pageY: number;
  /** X coordinate relative to the element */
  locationX: number;
  /** Y coordinate relative to the element */
  locationY: number;
  /** Event timestamp */
  timestamp: number;
  /** Pointer type (mouse, pen, touch) */
  pointerType: string;
  /** Pressure force applied */
  force: number;
  /** Left mouse button pressed state */
  isLeftButton: boolean;
  /** Right mouse button pressed state */
  isRightButton: boolean;
  /** Middle mouse button pressed state */
  isMiddleButton: boolean;
  /** Barrel button pressed state (pen) */
  isBarrelButtonPressed: boolean;
  /** Horizontal scroll wheel active */
  isHorizontalScrollWheel: boolean;
  /** Eraser mode active (pen) */
  isEraser: boolean;
  /** Shift key pressed state */
  shiftKey: boolean;
  /** Ctrl key pressed state */
  ctrlKey: boolean;
  /** Alt key pressed state */
  altKey: boolean;
};

type IMouseEvent = NativeSyntheticEvent<INativeMouseEvent>;

/**
 * Mouse event handlers for Windows components
 */
interface MouseEventHandlers {
  /** Mouse enter event handler */
  onMouseEnter?: (args: IMouseEvent) => void;
  /** Mouse leave event handler */
  onMouseLeave?: (args: IMouseEvent) => void;
}

Usage Examples:

import React, { useState } from 'react';
import { View, Text } from 'react-native-windows';

const MouseExample: React.FC = () => {
  const [mouseInfo, setMouseInfo] = useState('');
  const [isHovered, setIsHovered] = useState(false);

  const handleMouseEnter = (event: IMouseEvent) => {
    setIsHovered(true);
    setMouseInfo(`Mouse entered at (${event.nativeEvent.pageX}, ${event.nativeEvent.pageY})`);
  };

  const handleMouseLeave = () => {
    setIsHovered(false);
    setMouseInfo('Mouse left');
  };


  return (
    <View
      onMouseEnter={handleMouseEnter}
      onMouseLeave={handleMouseLeave}
      style={{
        padding: 20,
        backgroundColor: isHovered ? '#e3f2fd' : '#f5f5f5',
        borderRadius: 8,
        margin: 16,
      }}
    >
      <Text>Mouse interaction area</Text>
      <Text style={{ fontSize: 12, color: '#666', marginTop: 8 }}>
        {mouseInfo || 'Move mouse over this area'}
      </Text>
    </View>
  );
};

Focus Events

Focus Management System

Windows focus management with accessibility support and keyboard navigation.

/**
 * Focus event interface for accessibility and navigation
 */
interface IFocusEvent {
  /** Target element that received/lost focus */
  target: any;
  /** Related target (element losing/gaining focus) */
  relatedTarget?: any;
  /** Event timestamp */
  timeStamp: number;
}

/**
 * Focus event handlers
 */
interface FocusEventHandlers {
  /** Focus gained handler */
  onFocus?: (event: { nativeEvent: IFocusEvent }) => void;
  /** Focus lost handler */
  onBlur?: (event: { nativeEvent: IFocusEvent }) => void;
  /** Focus gained (capture phase) */
  onFocusCapture?: (event: { nativeEvent: IFocusEvent }) => void;
  /** Focus lost (capture phase) */
  onBlurCapture?: (event: { nativeEvent: IFocusEvent }) => void;
}

/**
 * Focus management properties
 */
interface FocusProps {
  /** Tab navigation index */
  tabIndex?: number;
  /** Enable focus ring visibility */
  enableFocusRing?: boolean;
  /** Auto focus on mount */
  autoFocus?: boolean;
  /** Focus on click/press */
  focusable?: boolean;
}

Usage Examples:

import React, { useState, useRef } from 'react';
import { View, Text, Pressable } from 'react-native-windows';

const FocusExample: React.FC = () => {
  const [focusedElement, setFocusedElement] = useState<string>('');
  const buttonRefs = useRef<Array<React.RefObject<any>>>([]);

  const handleFocus = (elementName: string) => (event: { nativeEvent: IFocusEvent }) => {
    setFocusedElement(elementName);
    console.log(`${elementName} gained focus`);
  };

  const handleBlur = (elementName: string) => () => {
    console.log(`${elementName} lost focus`);
  };

  const handleKeyDown = (event: { nativeEvent: IKeyboardEvent }) => {
    const { key } = event.nativeEvent;

    // Arrow key navigation
    if (key === 'ArrowDown' || key === 'ArrowRight') {
      // Move to next focusable element
      const currentIndex = focusedElement ? parseInt(focusedElement.split(' ')[1]) - 1 : -1;
      const nextIndex = Math.min(currentIndex + 1, buttonRefs.current.length - 1);
      buttonRefs.current[nextIndex]?.current?.focus();
    } else if (key === 'ArrowUp' || key === 'ArrowLeft') {
      // Move to previous focusable element
      const currentIndex = focusedElement ? parseInt(focusedElement.split(' ')[1]) - 1 : buttonRefs.current.length;
      const prevIndex = Math.max(currentIndex - 1, 0);
      buttonRefs.current[prevIndex]?.current?.focus();
    }
  };

  return (
    <View onKeyDown={handleKeyDown} style={{ padding: 16 }}>
      <Text style={{ marginBottom: 16 }}>
        Currently focused: {focusedElement || 'None'}
      </Text>

      {[1, 2, 3].map((num) => {
        const ref = React.createRef();
        buttonRefs.current[num - 1] = ref;

        return (
          <Pressable
            key={num}
            ref={ref}
            tabIndex={num}
            enableFocusRing={true}
            onFocus={handleFocus(`Button ${num}`)}
            onBlur={handleBlur(`Button ${num}`)}
            style={{
              padding: 12,
              backgroundColor: focusedElement === `Button ${num}` ? '#0078d4' : '#f0f0f0',
              marginBottom: 8,
              borderRadius: 4,
            }}
          >
            <Text style={{
              color: focusedElement === `Button ${num}` ? 'white' : 'black'
            }}>
              Button {num} (Tab Index: {num})
            </Text>
          </Pressable>
        );
      })}
    </View>
  );
};

Touch and Gesture Events

Touch Event System

Enhanced touch event handling with Windows-specific touch and pen support.

/**
 * Touch event interface with multi-touch support
 */
interface ITouchEvent {
  /** Array of changed touch points */
  changedTouches: Touch[];
  /** Touch identifier */
  identifier: number;
  /** X coordinate relative to component */
  locationX: number;
  /** Y coordinate relative to component */
  locationY: number;
  /** X coordinate relative to page */
  pageX: number;
  /** Y coordinate relative to page */
  pageY: number;
  /** Target element */
  target: number;
  /** Event timestamp */
  timestamp: number;
  /** All active touch points */
  touches: Touch[];
}

interface Touch {
  /** Unique touch identifier */
  identifier: number;
  /** X coordinate relative to component */
  locationX: number;
  /** Y coordinate relative to component */
  locationY: number;
  /** X coordinate relative to page */
  pageX: number;
  /** Y coordinate relative to page */
  pageY: number;
  /** Target element */
  target: number;
  /** Touch timestamp */
  timestamp: number;
  /** Touch force (pressure) */
  force?: number;
  /** Touch radius */
  majorRadius?: number;
  /** Touch radius */
  minorRadius?: number;
}

/**
 * Touch event handlers
 */
interface TouchEventHandlers {
  /** Touch start handler */
  onTouchStart?: (event: { nativeEvent: ITouchEvent }) => void;
  /** Touch move handler */
  onTouchMove?: (event: { nativeEvent: ITouchEvent }) => void;
  /** Touch end handler */
  onTouchEnd?: (event: { nativeEvent: ITouchEvent }) => void;
  /** Touch cancel handler */
  onTouchCancel?: (event: { nativeEvent: ITouchEvent }) => void;
}

Event Phase Management

Event Phase Control

Windows-specific event phase management for capture and bubble phases.

/**
 * Event phase enumeration for Windows event handling
 */
enum EventPhase {
  /** No event phase */
  None = 0,
  /** Capture phase (top-down) */
  Capturing = 1,
  /** At target element */
  AtTarget = 2,
  /** Bubble phase (bottom-up) */
  Bubbling = 3,
}

/**
 * Handled event phase enumeration
 */
enum HandledEventPhase {
  /** No handling */
  None = 0,
  /** Handle in capture phase */
  Capturing = 1,
  /** Handle at target */
  AtTarget = 2,
  /** Handle in bubble phase */
  Bubbling = 3,
}

/**
 * Event handler configuration with phase control
 */
interface EventHandlerConfig {
  /** Event phase to handle */
  handledEventPhase?: HandledEventPhase;
  /** Stop event propagation */
  stopPropagation?: boolean;
  /** Prevent default behavior */
  preventDefault?: boolean;
}

Usage Examples:

import React from 'react';
import { View, Text } from 'react-native-windows';

const EventPhaseExample: React.FC = () => {
  const handleParentKeyDown = (event: { nativeEvent: IKeyboardEvent }) => {
    console.log('Parent received key event in:',
      event.nativeEvent.eventPhase === EventPhase.Capturing ? 'Capture' : 'Bubble');
  };

  const handleChildKeyDown = (event: { nativeEvent: IKeyboardEvent }) => {
    console.log('Child handling key event:', event.nativeEvent.key);

    // Stop propagation to parent
    if (event.nativeEvent.key === 'Escape') {
      event.stopPropagation();
    }
  };

  return (
    <View
      tabIndex={0}
      onKeyDown={handleParentKeyDown}
      onKeyDownCapture={handleParentKeyDown} // Capture phase
      style={{ padding: 20, backgroundColor: '#f0f0f0' }}
    >
      <Text>Parent Container (receives events in capture and bubble)</Text>

      <View
        tabIndex={0}
        onKeyDown={handleChildKeyDown}
        style={{
          padding: 16,
          marginTop: 16,
          backgroundColor: '#e3f2fd',
          borderRadius: 4
        }}
      >
        <Text>Child Element (press Escape to stop propagation)</Text>
      </View>
    </View>
  );
};

Custom Event Handling

Advanced Event Patterns

Complex event handling patterns for Windows applications.

/**
 * Custom event handler utilities
 */
interface EventUtils {
  /** Throttle event handler */
  throttle<T extends (...args: any[]) => any>(
    func: T,
    delay: number
  ): T;

  /** Debounce event handler */
  debounce<T extends (...args: any[]) => any>(
    func: T,
    delay: number
  ): T;

  /** Combine multiple event handlers */
  combine<T>(...handlers: Array<(event: T) => void>): (event: T) => void;
}

Usage Examples:

import React, { useCallback, useMemo } from 'react';
import { View, Text } from 'react-native-windows';

const CustomEventExample: React.FC = () => {
  // Debounced search handler
  const debouncedSearch = useCallback(
    debounce((query: string) => {
      console.log('Searching for:', query);
    }, 300),
    []
  );

  // Throttled scroll handler
  const throttledScroll = useCallback(
    throttle((event: any) => {
      console.log('Scroll position:', event.nativeEvent.contentOffset);
    }, 100),
    []
  );

  // Combined key handler
  const combinedKeyHandler = useMemo(
    () => combine(
      (event: { nativeEvent: IKeyboardEvent }) => {
        // Log all keys
        console.log('Key pressed:', event.nativeEvent.key);
      },
      (event: { nativeEvent: IKeyboardEvent }) => {
        // Handle shortcuts
        if (event.nativeEvent.ctrlKey && event.nativeEvent.key === 'f') {
          console.log('Find shortcut');
        }
      }
    ),
    []
  );

  return (
    <View
      tabIndex={0}
      onKeyDown={combinedKeyHandler}
      style={{ padding: 16 }}
    >
      <Text>Advanced event handling example</Text>
    </View>
  );
};

// Utility implementations
function debounce<T extends (...args: any[]) => any>(func: T, delay: number): T {
  let timeoutId: NodeJS.Timeout;
  return ((...args: any[]) => {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => func.apply(this, args), delay);
  }) as T;
}

function throttle<T extends (...args: any[]) => any>(func: T, delay: number): T {
  let inThrottle: boolean;
  return ((...args: any[]) => {
    if (!inThrottle) {
      func.apply(this, args);
      inThrottle = true;
      setTimeout(() => inThrottle = false, delay);
    }
  }) as T;
}

function combine<T>(...handlers: Array<(event: T) => void>): (event: T) => void {
  return (event: T) => {
    handlers.forEach(handler => handler(event));
  };
}

Windows Event Patterns

Keyboard Navigation

// Standard Windows keyboard navigation
const keyboardNavigation = {
  // Tab navigation
  'Tab': () => focusNext(),
  'Shift+Tab': () => focusPrevious(),

  // Arrow navigation
  'ArrowDown': () => moveDown(),
  'ArrowUp': () => moveUp(),
  'ArrowLeft': () => moveLeft(),
  'ArrowRight': () => moveRight(),

  // Action keys
  'Enter': () => activate(),
  'Space': () => activate(),
  'Escape': () => cancel(),

  // Windows shortcuts
  'Ctrl+a': () => selectAll(),
  'Ctrl+c': () => copy(),
  'Ctrl+v': () => paste(),
  'Ctrl+z': () => undo(),
  'F1': () => showHelp(),
  'Alt+F4': () => closeWindow(),
};

Accessibility Events

// Accessibility-focused event handling
const accessibilityEvents = {
  onFocus: (event) => {
    // Announce focus change to screen readers
    announceForAccessibility(`Focused on ${getAccessibilityLabel(event.target)}`);
  },

  onKeyDown: (event) => {
    // Handle accessibility shortcuts
    if (event.nativeEvent.key === 'F6') {
      // Move between major UI sections
      moveToNextSection();
    }
  },

  onMouseEnter: (event) => {
    // Provide hover feedback for screen readers
    if (isScreenReaderActive()) {
      announceHoverContent(event.target);
    }
  },
};

High Performance Events

// Optimized event handling for performance
const highPerformanceEvents = {
  // Use native driver for animations
  onScroll: Animated.event(
    [{ nativeEvent: { contentOffset: { y: scrollY } } }],
    { useNativeDriver: true }
  ),

  // Minimize re-renders with useCallback
  onPress: useCallback((event) => {
    handlePress(event);
  }, [dependencies]),

  // Batch state updates
  onMultipleEvents: (events) => {
    unstable_batchedUpdates(() => {
      events.forEach(handleEvent);
    });
  },
};

Install with Tessl CLI

npx tessl i tessl/npm-react-native-windows

docs

apis.md

components.md

events.md

index.md

styling.md

windows-apis.md

windows-components.md

tile.json