### Start Metro Server for Example App Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/CONTRIBUTING.md Starts the Metro bundler to serve the example application. This is necessary for running the example app on a device or simulator. ```sh yarn example start ``` -------------------------------- ### Usage Instructions - Getting Started Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/_autodocs/GENERATION_SUMMARY.txt Provides the recommended starting points for users to navigate the documentation. ```markdown START HERE: 1. Open README.md for overview 2. Jump to INDEX.md for complete function catalog 3. Navigate to specific function pages as needed ``` -------------------------------- ### Complete Video Trimming (New Architecture) Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/README.md This example shows a full implementation for video selection and trimming using the New Architecture. It includes setting up event listeners for trimming completion and errors, and opening the video editor with custom options. Ensure you have the necessary imports and setup for the New Architecture. ```javascript import React, { useEffect, useRef } from 'react'; import { TouchableOpacity, Text, View } from 'react-native'; import { showEditor, isValidFile, type Spec } from 'react-native-video-trim'; import { launchImageLibrary } from 'react-native-image-picker'; export default function VideoTrimmer() { const listeners = useRef({}); useEffect(() => { // Set up event listeners listeners.current.onFinishTrimming = (NativeVideoTrim as Spec) .onFinishTrimming(({ outputPath, startTime, endTime, duration }) => { console.log('Trimming completed:', { outputPath, startTime, endTime, duration }); }); listeners.current.onError = (NativeVideoTrim as Spec) .onError(({ message, errorCode }) => { console.error('Trimming error:', message, errorCode); }); return () => { // Cleanup listeners Object.values(listeners.current).forEach(listener => listener?.remove() ); }; }, []); const selectAndTrimVideo = async () => { const result = await launchImageLibrary({ mediaType: 'video', quality: 1, }); if (result.assets?.[0]?.uri) { const videoUri = result.assets[0].uri; // Validate file first const isValid = await isValidFile(videoUri); if (!isValid) { console.log('Invalid video file'); return; } // Open editor showEditor(videoUri, { maxDuration: 60000, // 1 minute max saveToPhoto: true, // Save to gallery openShareSheetOnFinish: true, headerText: "Trim Video", trimmerColor: "#007AFF", }); } }; return ( Select & Trim Video ); } ``` -------------------------------- ### Run Example App on Android Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/AGENTS.md Builds and runs the example app on an Android device or emulator. This command assumes you have Android development environment set up. ```bash yarn example android ``` -------------------------------- ### Run Example App on iOS Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/CONTRIBUTING.md Builds and runs the example application on an connected iOS simulator or device. ```sh yarn example ios ``` -------------------------------- ### Run Example App on Android Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/CONTRIBUTING.md Builds and runs the example application on an connected Android device or emulator. ```sh yarn example android ``` -------------------------------- ### Test Example App with New Architecture on Android Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/AGENTS.md Runs the example app on Android with the New Architecture enabled. Set the ORG_GRADLE_PROJECT_newArchEnabled environment variable to true. ```bash ORG_GRADLE_PROJECT_newArchEnabled=true yarn example android ``` -------------------------------- ### Example App Structure Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/AGENTS.md Demonstrates the directory structure for the example application, including separate entry points for testing the New Architecture event listeners and the Old Architecture using NativeEventEmitter. ```typescript example/src/App.tsx example/src/App.OldArch.tsx ``` -------------------------------- ### Test Example App with Old Architecture on Android Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/AGENTS.md Runs the example app on Android with the New Architecture disabled. Set the ORG_GRADLE_PROJECT_newArchEnabled environment variable to false. ```bash ORG_GRADLE_PROJECT_newArchEnabled=false yarn example android ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/CONTRIBUTING.md Run this command in the root directory to install all project dependencies using Yarn workspaces. ```sh yarn ``` -------------------------------- ### Complete Example with File Picker Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/README.md Shows a complete example of picking a video using react-native-image-picker and then opening the video editor. This integrates file selection with video trimming. ```javascript import { showEditor } from 'react-native-video-trim'; import { launchImageLibrary } from 'react-native-image-picker'; const trimVideo = () => { // Pick a video launchImageLibrary({ mediaType: 'video' }, (response) => { if (response.assets && response.assets[0]) { const videoUri = response.assets[0].uri; // Open editor showEditor(videoUri, { maxDuration: 60, // 60 seconds max saveToPhoto: true, }); } }); }; ``` -------------------------------- ### Install CocoaPods Dependencies Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/example/README.md Before running the iOS app, install the necessary CocoaPods dependencies. This is a one-time setup or required after updating native dependencies. ```sh bundle install bundle exec pod install ``` -------------------------------- ### iOS Setup for React Native CLI Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/README.md Run pod-install for iOS setup when using React Native CLI. Ensure NSPhotoLibraryUsageDescription is added to Info.plist for saving to Photos. ```bash npx pod-install ios ``` -------------------------------- ### Install iOS Dependencies with CocoaPods Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/_autodocs/architecture.md Run this command in the ios directory to install native dependencies for iOS using CocoaPods. ```bash cd ios && pod install ``` -------------------------------- ### showEditor API Example Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/README.md Illustrates how to use the showEditor function with specific video path and configuration options. This is useful for programmatic control over the editor's initial state. ```javascript showEditor('/path/to/video.mp4', { maxDuration: 30, saveToPhoto: true, }); ``` -------------------------------- ### Complete Configuration Example Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/_autodocs/configuration.md This snippet shows how to configure all available options for the video editor, including basic settings, appearance, time format, behavior, audio, save/share options, dialogs, and text. ```typescript import { showEditor } from 'react-native-video-trim'; showEditor('/path/to/video.mp4', { // Basic settings type: 'video', outputExt: 'mp4', maxDuration: 60000, // 60 seconds minDuration: 3000, // 3 seconds // Appearance theme: 'light', headerText: 'Edit Video', headerTextSize: 18, headerTextColor: '#333333', trimmerColor: '#007AFF', handleIconColor: '#FFFFFF', // Time format durationFormat: 'mm:ss.SS', // Behavior autoplay: true, enablePreciseTrimming: false, enableEditTools: true, enableHapticFeedback: true, // Audio & Speed removeAudio: false, speed: 1.0, // Save & Share saveToPhoto: true, openShareSheetOnFinish: true, removeAfterSavedToPhoto: false, // Dialogs enableCancelDialog: true, cancelDialogTitle: 'Cancel?', cancelDialogMessage: 'Discard changes?', enableSaveDialog: true, saveDialogTitle: 'Save Video?', // Text cancelButtonText: 'Back', saveButtonText: 'Save', trimmingText: 'Processing...'}); ``` -------------------------------- ### Install Dependencies with Yarn Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/AGENTS.md Installs project dependencies using Yarn 4 with the node-modules linker. Ensure you have Yarn 4 installed. ```bash yarn ``` -------------------------------- ### Install react-native-video-trim with npm or yarn Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/README.md Use npm or yarn to add the react-native-video-trim package to your project. ```bash npm install react-native-video-trim # or yarn add react-native-video-trim ``` -------------------------------- ### Example: Convert Video to GIF Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/README.md Demonstrates how to use the `toGif` function to convert a video file to a GIF with specified parameters. Ensure the video file path is correct. ```javascript import { toGif } from 'react-native-video-trim'; const { outputPath } = await toGif('/path/to/video.mp4', { startTime: 2000, endTime: 7000, fps: 15, width: 320, }); ``` -------------------------------- ### Start Metro Bundler Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/example/README.md Run this command to start the Metro JavaScript bundler, which is essential for the React Native development workflow. It supports both npm and Yarn package managers. ```sh # Using npm npm start # OR using Yarn yarn start ``` -------------------------------- ### Example: Merge Video Clips Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/README.md Shows how to use the `merge` function to combine multiple video clips into one. The function returns the output path and the total duration of the merged video. ```javascript import { merge } from 'react-native-video-trim'; const { outputPath, duration } = await merge([ '/path/to/clip1.mp4', '/path/to/clip2.mp4', '/path/to/clip3.mp4', ]); ``` -------------------------------- ### Usage Instructions - Finding Information Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/_autodocs/GENERATION_SUMMARY.txt Guides users on how to locate specific information within the documentation based on their needs. ```markdown FINDING INFORMATION: • By function name → INDEX.md function list • By task/goal → INDEX.md Common Patterns section • By concept → INDEX.md Reference Documents • By error code → errors-and-best-practices.md ``` -------------------------------- ### Video Trimming (Old Architecture) Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/README.md This example demonstrates how to set up event listeners for video trimming using the Old Architecture. It utilizes `NativeEventEmitter` to listen for 'VideoTrim' events, handling 'onFinishTrimming' and 'onError' cases. Ensure the NativeModules and NativeEventEmitter are correctly configured for your project. ```javascript import React, { useEffect } from 'react'; import { NativeEventEmitter, NativeModules } from 'react-native'; import { showEditor } from 'react-native-video-trim'; export default function VideoTrimmer() { useEffect(() => { const eventEmitter = new NativeEventEmitter(NativeModules.VideoTrim); const subscription = eventEmitter.addListener('VideoTrim', (event) => { switch (event.name) { case 'onFinishTrimming': console.log('Video trimmed:', event.outputPath); break; case 'onError': console.error('Trimming failed:', event.message); break; // Handle other events... } }); return () => subscription.remove(); }, []); // Rest of implementation... } ``` -------------------------------- ### Expo Setup for React Native Video Trim Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/README.md Run npx expo prebuild for Expo projects. Note that Expo Go may not work due to native dependencies; use development builds or expo run. ```bash npx expo prebuild ``` -------------------------------- ### Default Options Example Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/_autodocs/architecture.md Demonstrates how default options are merged with user-specified options using the spread operator for type safety and consistency. ```typescript // User only specifies what they want to change trim(url, { endTime: 60000 }) // createTrimOptions merges with all defaults // Result: { startTime: 0, endTime: 60000, type: 'video', outputExt: 'mp4', ...all base defaults } ``` -------------------------------- ### Configure iOS for HTTPS FFmpeg Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/README.md Set `FFMPEGKIT_PACKAGE=https` and `FFMPEG_KIT_PACKAGE_VERSION=6.0` before running `pod install` to enable trimming of remote HTTPS files. ```bash FFMPEGKIT_PACKAGE=https FFMPEG_KIT_PACKAGE_VERSION=6.0 pod install ``` -------------------------------- ### API Reference Overview Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/_autodocs/GENERATION_SUMMARY.txt This section provides an overview of the API reference documentation, guiding users on how to find information about specific functions, types, and configurations. ```APIDOC ## API Reference This documentation provides a detailed reference for the react-native-video-trim library. ### Getting Started 1. **Overview**: Start with `README.md` for a general understanding. 2. **Function Catalog**: Use `INDEX.md` for a complete list of all functions. 3. **Specific Functions**: Navigate to individual pages like `showEditor.md`, `trim.md`, `compress.md`, `extractAudio.md`, `getFrameAt.md`, `merge.md`, and `toGif.md` for detailed API information. ### Finding Information - **By Function Name**: Refer to the function list in `INDEX.md`. - **By Task/Goal**: Consult the 'Common Patterns' section in `INDEX.md`. - **By Concept**: Use the 'Reference Documents' section in `INDEX.md`. - **By Error Code**: See `errors-and-best-practices.md`. ### Reference Usage - **API Details**: Individual function pages (e.g., `showEditor.md`, `trim.md`). - **Type Definitions**: `types.md`. - **Configuration**: `configuration.md`. - **Events**: `events.md`. - **Architecture**: `architecture.md`. - **Patterns**: `errors-and-best-practices.md`. ### Scope Limitations This documentation focuses exclusively on the JavaScript API reference. Native implementation details (Objective-C, Swift, Kotlin), FFmpeg internals, build procedures, installation, tutorials, project history, and marketing content are intentionally excluded. Native code is outside the scope of the JavaScript API, and installation is covered in the project's main README. ``` -------------------------------- ### Configure Header and Trimmer Colors Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/_autodocs/configuration.md This example demonstrates how to set header text, trimmer, and handle icon colors using CSS color string formats. These options accept named colors, hex, RGB, and RGBA strings. ```typescript showEditor('/video.mp4', { headerTextColor: '#333333', // Hex trimmerColor: 'rgba(255, 200, 0, 1)', // RGBA handleIconColor: 'white', // Named }); ``` -------------------------------- ### Key Features Documented Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/_autodocs/GENERATION_SUMMARY.txt Lists the core features covered in the documentation, emphasizing comprehensive API details and practical examples. ```markdown ✓ All function signatures with full type annotations ✓ Parameter tables with name, type, required flag, default, description ✓ Return type documentation ✓ Error codes and conditions ✓ 3-5 realistic code examples per function ✓ Complete TypeScript interface definitions (30+ types) ✓ Configuration option reference (60+ options) ✓ Event emitter system with all event types ✓ Platform-specific notes (iOS, Android, permissions) ✓ Performance optimization patterns ✓ Error handling best practices ✓ Anti-patterns and what to avoid ✓ Cross-references and navigation links ✓ Architecture overview and design patterns ``` -------------------------------- ### TrimOptions Interface Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/_autodocs/types.md Defines configuration for headless video trimming operations. Specify the start and end times in milliseconds for the desired segment. ```typescript interface TrimOptions extends BaseOptions { startTime: number; endTime: number; } ``` -------------------------------- ### Set Appropriate Duration Limits Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/_autodocs/errors-and-best-practices.md Configure `minDuration` and `maxDuration` in `showEditor` to guide users in creating clips within acceptable length constraints. This prevents excessively short or long videos. ```typescript // Prevent users from creating extremely long or short clips showEditor(videoPath, { minDuration: 1000, // At least 1 second maxDuration: 300000, // At most 5 minutes }); ``` -------------------------------- ### Comprehensive Event Listener Setup Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/_autodocs/events.md This snippet shows how to set up listeners for all major events emitted by the react-native-video-trim editor, including lifecycle, loading, trimming, and error events. Ensure you have the necessary helper functions (showProgressIndicator, hideProgressIndicator, handleTrimResult, showErrorAlert, updateProgressBar) defined elsewhere in your component. ```typescript import { useEffect } from 'react'; import { NativeEventEmitter } from 'react-native'; import { showEditor } from 'react-native-video-trim'; import VideoTrim from 'react-native-video-trim'; export function VideoEditorScreen() { useEffect(() => { const eventEmitter = new NativeEventEmitter(VideoTrim); // Editor lifecycle const showSub = eventEmitter.addListener('onShow', () => { console.log('Editor opened'); }); const hideSub = eventEmitter.addListener('onHide', () => { console.log('Editor closed'); }); const cancelSub = eventEmitter.addListener('onCancel', () => { console.log('User cancelled'); }); // Loading const loadSub = eventEmitter.addListener('onLoad', (data) => { console.log(`Media loaded: ${data.duration}ms`); }); // Trimming const startSub = eventEmitter.addListener('onStartTrimming', () => { console.log('Trim started'); showProgressIndicator(); }); const finishSub = eventEmitter.addListener('onFinishTrimming', (result) => { console.log(`Trim completed: ${result.outputPath}`); hideProgressIndicator(); handleTrimResult(result); }); const cancelTrimmingSub = eventEmitter.addListener('onCancelTrimming', () => { console.log('Trim cancelled'); hideProgressIndicator(); }); // Error handling const errorSub = eventEmitter.addListener('onError', (error) => { console.error(`Error: ${error.message} (code: ${error.errorCode})`); showErrorAlert(error.message); }); // Statistics (optional, for progress bar) const statsSub = eventEmitter.addListener('onStatistics', (stats) => { const progress = (stats.time / estimatedDuration) * 100; updateProgressBar(progress); }); return () => { showSub.remove(); hideSub.remove(); cancelSub.remove(); loadSub.remove(); startSub.remove(); finishSub.remove(); cancelTrimmingSub.remove(); errorSub.remove(); statsSub.remove(); }; }, []); return ( // Your component JSX ); } ``` -------------------------------- ### Build and Run iOS App Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/example/README.md Use this command to build and run your React Native application on an iOS simulator or device. Ensure CocoaPods dependencies are installed first. Supports both npm and Yarn. ```sh # Using npm npm run ios # OR using Yarn yarn ios ``` -------------------------------- ### Initialize Video Editor with Configuration Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/_autodocs/configuration.md Import and call showEditor with the video path and a configuration object to customize the editor. All configuration options are optional and have sensible defaults. ```typescript import { showEditor } from 'react-native-video-trim'; showEditor('/path/to/video.mp4', { // Your configuration options here }); ``` -------------------------------- ### Basic Video Editor Usage Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/README.md Demonstrates the basic usage of the showEditor function to open the video editor. This is the simplest way to integrate video trimming. ```javascript import { showEditor } from 'react-native-video-trim'; // 1. Basic usage - open video editor showEditor(videoUrl); ``` ```javascript // 2. With duration limit showEditor(videoUrl, { maxDuration: 20, }); ``` ```javascript // 3. With save options showEditor(videoUrl, { maxDuration: 30, saveToPhoto: true, openShareSheetOnFinish: true, }); ``` -------------------------------- ### Documentation Quality Metrics Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/_autodocs/GENERATION_SUMMARY.txt Presents metrics for documentation completeness, code example quality, organization, and technical accuracy. ```markdown Completeness: • 100% of exported functions documented • 100% of type definitions included • 100% of configuration options covered • 10+ event types documented Code Examples: • ~50 production-ready code snippets • Error handling examples • Platform-specific patterns • Performance optimization examples Organization: • 16 logical documents • Master index with function catalog • Self-contained pages with cross-references • Clear navigation structure Technical Accuracy: • All signatures verified against source code • Type definitions from NativeVideoTrim.ts • Default values from factory functions • Platform support from package.json ``` -------------------------------- ### showEditor() Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/README.md Opens the video trimmer interface for user interaction. It can be used with basic parameters or with a configuration object to customize duration limits and save options. ```APIDOC ## showEditor() ### Description Opens the video trimmer interface. ### Method Signature ```typescript showEditor(videoPath: string, config?: EditorConfig): void ``` ### Parameters - `videoPath` (string): Path to video file (local or remote HTTPS URL) - `config` (EditorConfig, optional): Configuration options. ### Example ```javascript import { showEditor } from 'react-native-video-trim'; // Basic usage showEditor('/path/to/video.mp4'); // With duration limit showEditor('/path/to/video.mp4', { maxDuration: 20, }); // With save options showEditor('/path/to/video.mp4', { maxDuration: 30, saveToPhoto: true, openShareSheetOnFinish: true, }); ``` ``` -------------------------------- ### showEditor() Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/_autodocs/showEditor.md Opens an interactive video or audio editor UI for trimming, with optional transforms (flip, rotate, crop) and advanced features (mute, speed adjustment). ```APIDOC ## showEditor() ### Description Opens an interactive video or audio editor UI for trimming, with optional transforms (flip, rotate, crop) and advanced features (mute, speed adjustment). ### Signature ```typescript function showEditor( filePath: string, config?: Partial> & { headerTextColor?: string; trimmerColor?: string; handleIconColor?: string; waveformColor?: string; waveformBackgroundColor?: string; } ): void ``` ### Parameters #### Path Parameters - **filePath** (string) - Required - Absolute path to local video/audio file or HTTPS remote URL. Must be non-empty. - **config** (Partial) - Optional - Configuration object. Color values are passed as CSS color strings (e.g., `"#ff0000"`, `"white"`) and automatically converted to native platform colors via `processColor()`. ### Color Parameter Handling The `config` object accepts color parameters as CSS color strings, which are converted internally: - `headerTextColor` — Defaults to `"black"` in light theme, `"white"` in dark theme - `trimmerColor` — Defaults to `"#f1d247"` (gold) - `handleIconColor` — Defaults to `"black"` in light theme, `"white"` in dark theme - `waveformColor` — Defaults to `"white"` - `waveformBackgroundColor` — Defaults to `"#3478F6"` (blue) ### Returns `void` — No return value. Editor opens asynchronously. Use event listeners (see [Events](#events)) to respond to user actions. ``` -------------------------------- ### Import Primary Export Functions Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/_autodocs/api-overview.md Import all available functions from the main entry point of the react-native-video-trim library. Ensure you have the library installed. ```typescript import { showEditor, trim, getFrameAt, extractAudio, compress, toGif, merge, saveToPhoto, saveToDocuments, share, isValidFile, listFiles, cleanFiles, deleteFile, closeEditor, } from 'react-native-video-trim'; ``` -------------------------------- ### GifOptions Interface Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/_autodocs/types.md Specifies the parameters for converting a video segment into a GIF. Configure start and end times, frame rate, and width. ```typescript interface GifOptions { startTime: number; endTime: number; fps: number; width: number; } ``` -------------------------------- ### Show Basic Video Editor Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/_autodocs/showEditor.md Use this to open the default video editor. Ensure the video file path is correct. ```typescript import { showEditor } from 'react-native-video-trim'; // Simple editor with default settings showEditor('/path/to/video.mp4'); ``` -------------------------------- ### Build Library with react-native-builder-bob Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/AGENTS.md Builds the library outputting to the 'lib/' directory. This command is essential for preparing the library for distribution or testing. ```bash yarn prepare ``` -------------------------------- ### GifOptions Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/_autodocs/types.md Options for converting a video segment to GIF. These settings define the start and end times, frame rate, and dimensions of the resulting GIF. ```APIDOC ## GifOptions Options for converting a video segment to GIF. ### Parameters #### Request Body - **startTime** (number) - Optional - Start position in milliseconds. Defaults to `0`. - **endTime** (number) - Optional - End position. `-1` = end of video. Defaults to `-1`. - **fps** (number) - Optional - Frame rate of the GIF. Defaults to `10`. - **width** (number) - Optional - Width in pixels. Height auto-scales. `-1` = original. Defaults to `-1`. ``` -------------------------------- ### Release New Version Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/AGENTS.md Initiates the release process using 'release-it' with conventional changelog generation. This command should be used when preparing to publish a new version of the library. ```bash yarn release ``` -------------------------------- ### Basic Video Trim and Save Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/_autodocs/INDEX.md Trim a video file between specified start and end times and save the result directly to the photo library. ```typescript const result = await trim('/path/to/video.mp4', { startTime: 5000, endTime: 25000, saveToPhoto: true, }); ``` -------------------------------- ### Launch Interactive Video Editor Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/_autodocs/README.md This snippet shows how to launch an interactive editor for video trimming. The 'showEditor' function allows customization of themes and save options. ```typescript import { showEditor } from 'react-native-video-trim'; showEditor('/path/to/video.mp4', { maxDuration: 60000, theme: 'light', saveToPhoto: true, }); ``` -------------------------------- ### Editor UI Visibility Event Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/_autodocs/events.md Emitted when the editor UI becomes visible. Use this to track when the editor opens and start loading overlays. ```typescript EventEmitter ``` -------------------------------- ### Configure Video Editor Options Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/README.md Use this configuration object to customize the video editor's behavior, duration limits, saving options, audio settings, UI elements, and overall functionality. Ensure all options are correctly set before initializing the editor. ```javascript showEditor(videoPath, { // Basic settings maxDuration: 60000, minDuration: 3000, // Save options saveToPhoto: true, openShareSheetOnFinish: true, removeAfterSavedToPhoto: true, // Audio & speed removeAudio: false, speed: 1.0, // UI customization theme: 'light', headerText: "Trim Your Video", cancelButtonText: "Back", saveButtonText: "Done", trimmerColor: "#007AFF", // Behavior autoplay: true, enableCancelTrimming: true, }); ``` -------------------------------- ### Video Compression with Error Handling Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/_autodocs/compress.md Demonstrates how to compress a video with error handling using a try-catch block. It logs the output path on success and any errors encountered during compression. Includes commented-out code for deleting the file after use. ```typescript import { compress, deleteFile } from 'react-native-video-trim'; try { const { outputPath } = await compress('/path/to/video.mp4', { quality: 'medium', }); console.log(`Compressed to: ${outputPath}`); // Check file size // Use the compressed file... // When done, delete: // await deleteFile(outputPath); } catch (error) { console.error('Compression failed:', error.message); } ``` -------------------------------- ### Full Video to GIF Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/_autodocs/toGif.md Convert an entire video file to a GIF using default start and end times. This is useful for creating a GIF from the whole video content. ```typescript import { toGif } from 'react-native-video-trim'; const { outputPath } = await toGif('/path/to/video.mp4', { // startTime defaults to 0 // endTime: -1 means to the end of video fps: 10, width: 480, }); ``` -------------------------------- ### Enable Precise Trimming in Headless Mode Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/README.md Enables frame-accurate video trimming in headless mode. This requires a hardware re-encode and specifies the start and end times for the trim operation. ```javascript const result = await trim(videoUrl, { startTime: 5000, endTime: 15000, enablePreciseTrimming: true, }); ``` -------------------------------- ### Importing Types for Video Trim Operations Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/_autodocs/architecture.md Demonstrates how to import specific types for configuring and handling results of video trimming operations. ```typescript import type { TrimOptions, TrimResult } from 'react-native-video-trim'; ``` -------------------------------- ### showEditor Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/_autodocs/README.md Opens a UI for trimming videos. Supports optional transforms like flip, rotate, crop, mute toggle, and speed adjustment. ```APIDOC ## showEditor ### Description Opens a UI for trimming videos. Supports optional transforms like flip, rotate, crop, mute toggle, and speed adjustment. ### Signature ```typescript showEditor(filePath: string, config?: Partial): void ``` ``` -------------------------------- ### Basic Trim Operation Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/_autodocs/trim.md Use this for a straightforward trim of a video file between specified start and end times. Ensure the input URL is a local path or a valid HTTPS URL. ```typescript import { trim } from 'react-native-video-trim'; const result = await trim('/path/to/video.mp4', { startTime: 5000, // 5 seconds endTime: 25000, // 25 seconds }); console.log(`Trimmed: ${result.outputPath}`); console.log(`Duration: ${result.duration}ms`); ``` -------------------------------- ### Compressing a Video File (Quality Preset) Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/README.md Shows how to compress a video file using a quality preset with the compress function. This is a simple way to reduce file size. ```javascript import { compress } from 'react-native-video-trim'; // Quality preset const { outputPath } = await compress('/path/to/video.mp4', { quality: 'medium', }); ``` -------------------------------- ### Merge Clips with Error Handling Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/_autodocs/merge.md Merge video clips with robust error handling. This example includes a check for an empty clip list and a try-catch block for potential merge failures. ```typescript import { merge, deleteFile } from 'react-native-video-trim'; try { const clips = [ '/cache/clip1.mp4', '/cache/clip2.mp4', ]; if (!clips.length) { throw new Error('No clips to merge'); } const { outputPath, duration } = await merge(clips); console.log(`Successfully merged ${duration}ms`); // Use the output... // When done, delete: // await deleteFile(outputPath); } catch (error) { console.error('Merge failed:', error.message); } ``` -------------------------------- ### API Overview and Structure Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/_autodocs/GENERATION_SUMMARY.txt Provides a high-level view of the module structure and available API documentation files. ```markdown api-overview.md 4.1 KB - Module structure overview architecture.md 9.1 KB - Technical architecture details compress.md 5.4 KB - Compression API reference configuration.md 12 KB - Complete configuration guide errors-and-best-practices.md 15 KB - Error handling and patterns events.md 9.4 KB - Event system reference extractAudio.md 4.2 KB - Audio extraction API file-operations.md 9.0 KB - File management functions getFrameAt.md 4.4 KB - Frame extraction API INDEX.md 12 KB - Master index and navigation merge.md 5.5 KB - Merge operation API README.md 3.5 KB - Documentation README showEditor.md 6.4 KB - Editor UI API reference toGif.md 5.6 KB - GIF conversion API trim.md 4.9 KB - Trim operation API types.md 12 KB - Type definitions reference TOTAL: 152 KB across 16 files ``` -------------------------------- ### Basic GIF Conversion Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/_autodocs/toGif.md Converts a video segment to a GIF with specified start and end times. Ensure the video file path or URL is correct and that the specified time range is valid. ```typescript import { toGif } from 'react-native-video-trim'; const { outputPath } = await toGif('/path/to/video.mp4', { startTime: 0, endTime: 5000, // 5 seconds }); console.log(`GIF created: ${outputPath}`); ``` -------------------------------- ### Compressing a Video File (Custom Settings) Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/README.md Illustrates compressing a video file with custom settings such as width, bitrate, and audio removal using the compress function. This provides fine-grained control over compression. ```javascript // Custom settings const { outputPath } = await compress('/path/to/video.mp4', { width: 720, bitrate: 2_000_000, removeAudio: true, }); ``` -------------------------------- ### Quick Compression with Preset Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/_autodocs/compress.md Compresses a video using a predefined quality preset. Use this for a balanced approach to quality and file size. ```typescript import { compress } from 'react-native-video-trim'; const { outputPath } = await compress('/path/to/video.mp4', { quality: 'medium', // CRF 23, balanced quality/size }); console.log(`Compressed: ${outputPath}`); ``` -------------------------------- ### Safely Trim Video Within Duration Bounds Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/_autodocs/errors-and-best-practices.md This function validates the video file and calculates safe start and end times for trimming, ensuring they are within the video's actual duration and non-negative. ```typescript import { isValidFile } from 'react-native-video-trim'; async function safelyTrimVideo(path: string, maxDuration: number) { const validation = await isValidFile(path); if (!validation.isValid) { throw new Error(`File is not valid: ${validation.fileType}`); } const endTime = Math.min(maxDuration, validation.duration); const startTime = Math.max(0, Math.floor(validation.duration * 0.1)); return await trim(path, { startTime, endTime }); } ``` -------------------------------- ### Use HTTPS URLs for showEditor and Trim Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/_autodocs/errors-and-best-practices.md The `showEditor` and `trim` functions support remote HTTPS URLs for video processing. Ensure your URLs are valid and accessible. ```typescript // ✅ Allowed: HTTPS URLs in showEditor and trim operations showEditor('https://example.com/video.mp4', { maxDuration: 60000 }); const result = await trim('https://example.com/video.mp4', { endTime: 30000, }); ``` -------------------------------- ### Run Tests Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/AGENTS.md Executes the project's test suite. Ensure all tests pass before committing changes. ```bash yarn test ``` -------------------------------- ### Configure Video Editor with Options Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/_autodocs/showEditor.md Customize the video editor's appearance and behavior using a configuration object. This includes setting duration limits, theme, text labels, colors, and operational flags like autoplay and saving to photos. ```typescript import { showEditor } from 'react-native-video-trim'; showEditor('/path/to/video.mp4', { // Duration limits maxDuration: 60000, // 60 seconds minDuration: 3000, // 3 seconds // Theme and UI theme: 'light', headerText: 'Trim Your Video', cancelButtonText: 'Cancel', saveButtonText: 'Done', // Colors headerTextColor: '#333333', trimmerColor: '#007AFF', // Behavior autoplay: true, saveToPhoto: true, openShareSheetOnFinish: true, removeAudio: false, speed: 1.0, }); ``` -------------------------------- ### List Files Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/_autodocs/INDEX.md Retrieves a list of all media files managed by the library. ```typescript listFiles(): Promise ``` -------------------------------- ### listFiles() Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/_autodocs/file-operations.md Lists all output files generated by past operations such as trim, compress, GIF, merge, and frame extraction. ```APIDOC ## listFiles() ### Description Lists all output files generated by past trim, compress, GIF, merge, and frame extraction operations. ### Method ```typescript function listFiles(): Promise ``` ### Return Type A Promise that resolves to an array of absolute file paths (`string[]`). ### Example ```typescript import { listFiles } from 'react-native-video-trim'; const files = await listFiles(); console.log(`Generated ${files.length} files:`); files.forEach(file => console.log(file)); ``` ### Notes - Lists all files in the library's cache and documents directories. - Useful for auditing disk usage or finding orphaned files. - Does not include files deleted via `deleteFile()` or `cleanFiles()`. ``` -------------------------------- ### Choose Appropriate Trimming Mode Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/_autodocs/errors-and-best-practices.md Use fast mode for quick edits or precise mode for frame-accurate results. Precise mode leverages the hardware encoder. ```typescript const result1 = await trim(url, { startTime: 5000, endTime: 25000, // enablePreciseTrimming defaults to false }); ``` ```typescript const result2 = await trim(url, { startTime: 5000, endTime: 25000, enablePreciseTrimming: true, // Use hardware encoder }); ``` -------------------------------- ### Import Types Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/_autodocs/INDEX.md Import necessary types for configuring video editing operations. ```typescript import type { EditorConfig, TrimOptions, TrimResult, CompressOptions, GifOptions, MergeOptions, FrameExtractionOptions, ExtractAudioOptions, FileValidationResult, // ... and all other types } from 'react-native-video-trim'; ``` -------------------------------- ### Apply Light Theme to Editor Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/README.md Set the 'theme' option to 'light' to apply a light theme to the editor UI. ```javascript // Light theme showEditor(videoUrl, { theme: 'light', }); ``` -------------------------------- ### Open Interactive Video Editor Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/_autodocs/README.md Opens a UI for trimming videos with optional transforms, mute toggle, and speed adjustment. Requires a file path as input. ```typescript showEditor(filePath: string, config?: Partial): void ``` -------------------------------- ### share() Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/_autodocs/file-operations.md Opens the system share sheet to share a file with other apps or contacts. ```APIDOC ## share() ### Description Open the system share sheet to share a file with other apps or contacts. ### Method ```typescript function share(filePath: string): Promise ``` ### Parameters #### Path Parameters - **filePath** (string) - Required - Absolute path to file to share. Non-empty string required. ### Return Type A Promise that resolves to `ShareResult`: ```typescript { success: boolean; // Whether the user completed the share action (dismiss without action = false) } ``` ### Throws/Rejects Rejects with an `Error` if: - `filePath` is empty or invalid - File does not exist - Share operation fails (no compatible apps, I/O error) ### Example ```typescript import { share } from 'react-native-video-trim'; try { const { success } = await share('/path/to/output.mp4'); if (success) { console.log('File shared successfully'); } else { console.log('User cancelled share'); } } catch (error) { console.error('Share failed:', error.message); } ``` ### Platform Notes - **iOS:** Uses `UIActivityViewController` with native share options (Messages, Mail, AirDrop, etc.) - **Android:** Uses `ACTION_SEND` intent for app chooser and target app - Requires `androidx.core.content.FileProvider` configuration for Android (see platform setup in README) ``` -------------------------------- ### listFiles Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/_autodocs/INDEX.md Retrieves a list of all managed media files. ```APIDOC ## listFiles ### Description Retrieve a list of all managed media files. ### Method ``` listFiles(): Promise ``` ### Returns - **Promise** - A promise that resolves with an array of file paths. ``` -------------------------------- ### Publish New Versions to npm Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/CONTRIBUTING.md Uses release-it to automate the process of version bumping, tagging, and publishing new releases to npm. ```sh yarn release ``` -------------------------------- ### CompressOptions Interface Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/_autodocs/types.md Defines the configuration for video compression. Use this to specify desired quality, bitrate, dimensions, frame rate, output format, and whether to remove audio. ```typescript interface CompressOptions { quality: string; bitrate: number; width: number; height: number; frameRate: number; outputExt: string; removeAudio: boolean; } ``` -------------------------------- ### Build FFmpeg Command with Encoder Arguments Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/AGENTS.md Builds the full FFmpeg argv by inserting encoder arguments into the command. This pattern is used when integrating new Android APIs that re-encode video. ```kotlin val buildCommand: (List) -> Array = { encoderArgs -> // Build the full FFmpeg argv with `encoderArgs` inserted in place of // the encoder portion (`-c:v h264_mediacodec -b:v ` would have gone). } ``` -------------------------------- ### BaseOptions Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/_autodocs/types.md Base configuration options shared by editor and headless operations. These options control fundamental aspects of the video/audio processing. ```APIDOC ## BaseOptions ### Description Base configuration options shared by editor and headless operations. ### Fields - **saveToPhoto** (boolean) - Optional - Auto-save to device photo library after operation. Defaults to `false`. - **type** (string) - Optional - Media type: `'video'` or `'audio'`. Defaults to `'video'`. - **outputExt** (string) - Optional - Output file extension. Defaults to `'mp4'`. - **removeAfterSavedToPhoto** (boolean) - Optional - Delete local output after photo save succeeds. Defaults to `false`. - **removeAfterFailedToSavePhoto** (boolean) - Optional - Delete local output if photo save fails. Defaults to `false`. - **enablePreciseTrimming** (boolean) - Optional - Force re-encoding for frame-accurate cuts (slower). Defaults to `false`. - **removeAudio** (boolean) - Optional - Strip audio track from output. Defaults to `false`. - **speed** (number) - Optional - Playback speed (0.25–4.0). Forces re-encoding when ≠ 1.0. Defaults to `1.0`. ``` -------------------------------- ### Trim Function with Options Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/_autodocs/architecture.md Wraps the native trim call, applying default options and input validation. Ensure 'VideoTrim' is correctly imported and configured. ```typescript function trim(url: string, options: Partial): Promise { return VideoTrim.trim(url, createTrimOptions(options)); } ``` -------------------------------- ### Customize Dialogs and Theme Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/_autodocs/errors-and-best-practices.md Personalize the user interface by customizing button texts, header information, and confirmation dialogs in `showEditor`. You can also adjust the theme and colors to match your application's design. ```typescript showEditor(videoPath, { // Use your app's terminology cancelButtonText: 'Back', saveButtonText: 'Finish', headerText: 'Edit Your Video', // Custom confirmations cancelDialogTitle: 'Discard Changes?', cancelDialogMessage: 'Are you sure you want to quit without saving?', // Match your app's theme theme: isDarkMode ? 'dark' : 'light', headerTextColor: '#FFFFFF', trimmerColor: '#FF6B6B', }); ``` -------------------------------- ### Usage Instructions - Reference Usage Source: https://github.com/maitrungduc1410/react-native-video-trim/blob/master/_autodocs/GENERATION_SUMMARY.txt Directs users to the relevant documentation pages for specific types of reference information. ```markdown REFERENCE USAGE: • API details → Individual function pages (showEditor.md, trim.md, etc.) • Type definitions → types.md • Configuration → configuration.md • Events → events.md • Architecture → architecture.md • Patterns → errors-and-best-practices.md ```