### Manual iOS Setup for react-native-text-size-latest using CocoaPods Source: https://github.com/abdulmateentechbits/react-native-text-size-latest/blob/master/_autodocs/integration-guide.md Integrate the library into your iOS project using CocoaPods by adding the specified line to your `Podfile` and then running `pod install`. ```ruby pod 'react-native-text-size-latest', :path => '../node_modules/react-native-text-size-latest' ``` ```bash cd ios && pod install && cd .. ``` -------------------------------- ### Install react-native-text-size-latest using Yarn or npm Source: https://github.com/abdulmateentechbits/react-native-text-size-latest/blob/master/_autodocs/integration-guide.md Choose either Yarn or npm for installing the library. Yarn is recommended for faster and more reliable dependency management. ```bash # Using yarn (recommended) yarn add react-native-text-size-latest ``` ```bash # Using npm npm install react-native-text-size-latest ``` -------------------------------- ### List Available Fonts Example Source: https://github.com/abdulmateentechbits/react-native-text-size-latest/blob/master/_autodocs/api-reference-core.md Demonstrates how to call the `fontFamilyNames` method and log the results. Includes an example of filtering for custom fonts on Android by excluding common system font names. Ensure the library is imported correctly before use. ```javascript import rnTextSize from 'react-native-text-size-latest'; const listAvailableFonts = async () => { try { const families = await rnTextSize.fontFamilyNames(); console.log(`Available fonts: ${families.join(', ')}`); // Filter for custom fonts on Android const customFonts = families.filter(f => !['sans-serif', 'serif', 'monospace'].includes(f) ); console.log('Custom fonts:', customFonts); } catch (error) { console.error('Failed to get font families'); } }; ``` -------------------------------- ### Verify react-native-text-size-latest Installation Source: https://github.com/abdulmateentechbits/react-native-text-size-latest/blob/master/_autodocs/integration-guide.md Test the installation by importing the library and using its `measure` function to get text dimensions. This verifies that the library is correctly linked and functional. ```javascript import rnTextSize from 'react-native-text-size-latest'; rnTextSize.measure({ text: 'Hello World', fontSize: 16, }).then(result => { console.log('Installation successful!', result); }).catch(error => { console.error('Installation failed:', error); }); ``` -------------------------------- ### Manual iOS Setup for react-native-text-size-latest using Xcode Source: https://github.com/abdulmateentechbits/react-native-text-size-latest/blob/master/_autodocs/integration-guide.md Manually add the library to your Xcode project by linking the static library file in the 'Link Binary with Libraries' build phase. ```bash libRNTextSize.a ``` -------------------------------- ### Manual Android Setup for react-native-text-size-latest Source: https://github.com/abdulmateentechbits/react-native-text-size-latest/blob/master/_autodocs/integration-guide.md Follow these steps to manually integrate the library into your Android project if automatic linking fails or is not preferred. Ensure to update your `settings.gradle` and `build.gradle` files accordingly. ```gradle include ':react-native-text-size-latest' project(':react-native-text-size-latest').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-text-size-latest/android') ``` ```gradle dependencies { implementation project(':react-native-text-size-latest') // Change 'compile' to 'implementation' if not already done } ``` ```gradle // Change from: compile 'com.android.support:appcompat-v7:27.1.1' // To: implementation 'com.android.support:appcompat-v7:27.1.1' ``` -------------------------------- ### Install and Link React Native Text Size Source: https://github.com/abdulmateentechbits/react-native-text-size-latest/blob/master/_autodocs/module-architecture.md Use yarn to add the package and then link it to your React Native project. Manual verification of Android and iOS linking is recommended. ```bash yarn add react-native-text-size-latest react-native link react-native-text-size-latest ``` -------------------------------- ### Handle Platform-Specific Configurations Source: https://github.com/abdulmateentechbits/react-native-text-size-latest/blob/master/_autodocs/configuration.md Adapt configuration settings based on the operating system (Android or iOS) to ensure consistent behavior. This example shows how to set default font sizes or include font padding for Android, and handle font variants for iOS. ```javascript import { Platform } from 'react-native'; const getMeasurementConfig = (baseConfig) => { const config = { ...baseConfig }; if (Platform.OS === 'android') { // Android-specific handling if (config.fontSize <= 0) { config.fontSize = 14; } if (!config.includeFontPadding) { config.includeFontPadding = true; } } else { // iOS-specific handling if (config.fontVariant) { config.fontVariant = config.fontVariant; // Already array } } return config; }; ``` -------------------------------- ### Example Usage of flatHeights with React Native Source: https://github.com/abdulmateentechbits/react-native-text-size-latest/blob/master/README.md This example demonstrates how to use the `flatHeights` function within a React component to measure text heights. It fetches dimensions, defines font specifications, and updates the component's state with the calculated heights for rendering. ```jsx //...import React, { useEffect, useState } from 'react'; import { View, Text, Dimensions } from 'react-native'; import rnTextSize, { TSFontSpecs } from 'react-native-text-size-latest'; type Props = { texts: string[] }; const Test: React.FC = ({ texts }) => { const [heights, setHeights] = useState([]); useEffect(() => { const fetchData = async () => { const width = Dimensions.get('window').width * 0.8; const fontSpecs: TSFontSpecs = { fontFamily: undefined, fontSize: 24, fontStyle: 'italic', fontWeight: 'bold', }; const heights = await rnTextSize.flatHeights({ text: texts, width, ...fontSpecs, }); setHeights(heights); }; fetchData(); }, [texts]); return ( {texts.map((text, index) => ( {text} ))} ); }; export default Test; ``` -------------------------------- ### Handle E_UNKNOWN_ERROR During Text Measurement Source: https://github.com/abdulmateentechbits/react-native-text-size-latest/blob/master/_autodocs/errors.md This example demonstrates how to catch and handle unexpected native exceptions during text measurement, flat heights calculation, or font specification. It suggests logging the error message for debugging and potentially implementing retry logic or fallbacks. ```javascript try { const result = await rnTextSize.measure({ text: largeText, fontSize: 16, }); } catch (error) { if (error.code === 'E_UNKNOWN_ERROR') { console.error('Measurement failed, details:', error.message); // Log for debugging reportToErrorTracking(error); // Retry with simpler input or fallback } } ``` -------------------------------- ### Get Font Metrics Source: https://github.com/abdulmateentechbits/react-native-text-size-latest/blob/master/_autodocs/integration-guide.md Retrieve font metrics like line height for a given font specification. Useful for precise text layout calculations. ```javascript const getFontInfo = async () => { try { const info = await rnTextSize.fontFromSpecs({ fontFamily: 'sans-serif', fontSize: 16, fontWeight: 'bold', }); console.log(`Line height: ${info.lineHeight}`); } catch (error) { console.error('Font query failed:', error); } }; ``` -------------------------------- ### Get Dynamic Type Specs (iOS) Source: https://github.com/abdulmateentechbits/react-native-text-size-latest/blob/master/_autodocs/configuration.md Fetch system text styles that respect Dynamic Type settings on iOS. The 'body' style's fontSize property provides the unscaled font size. ```javascript const styles = await rnTextSize.specsForTextStyles(); // iOS styles available: // body, callout, caption1, caption2, footnote, headline // subheadline, largeTitle (iOS 11+), title1, title2, title3 const bodyStyle = styles.body; console.log(bodyStyle.fontSize); // Unscaled font size ``` -------------------------------- ### Validate and Sanitize Custom Inputs Source: https://github.com/abdulmateentechbits/react-native-text-size-latest/blob/master/_autodocs/configuration.md When accepting custom input for text measurement configurations, validate and sanitize the values to prevent errors and ensure they fall within acceptable ranges. This example ensures font size is between 8 and 72, width is non-negative, and text is a string. ```javascript const safelyMeasure = async (text, specs = {}) => { return await rnTextSize.measure({ text: String(text || ''), fontSize: Math.max(8, Math.min(72, specs.fontSize || 14)), fontFamily: specs.fontFamily || undefined, width: specs.width !== undefined ? Math.max(0, specs.width) : undefined, }); }; ``` -------------------------------- ### Examples of Invalid Font Specifications Source: https://github.com/abdulmateentechbits/react-native-text-size-latest/blob/master/_autodocs/errors.md Demonstrates various ways an invalid font specification can trigger the E_INVALID_FONT_SPEC error, including non-existent font families, null specs, and invalid font sizes. ```javascript // Invalid fontFamily await rnTextSize.measure({ text: 'Hello', fontFamily: 'NonExistentFont123', // May fail on iOS }); ``` ```javascript // Null specs await rnTextSize.fontFromSpecs(null); // Error ``` ```javascript // Invalid fontSize (rare) await rnTextSize.measure({ text: 'Hello', fontSize: -10, // Invalid }); ``` -------------------------------- ### Use Default Configuration Source: https://github.com/abdulmateentechbits/react-native-text-size-latest/blob/master/_autodocs/configuration.md Utilize the library's default settings for simplicity and to leverage OS defaults when possible. This is the most straightforward way to perform text measurements. ```javascript // Good: Simple, uses OS defaults const result = await rnTextSize.measure({ text: 'Hello World', width: 200, }); ``` -------------------------------- ### Measure Text Dimensions in React Native Source: https://github.com/abdulmateentechbits/react-native-text-size-latest/blob/master/README.md This example demonstrates how to use the `rnTextSize.measure` function to calculate the dimensions of a given text with specified font properties and a maximum width. It utilizes `useEffect` for fetching data once on component mount and `Dimensions` to get the screen width. ```jsx //...\nimport React, { useEffect, useState } from 'react';\nimport { View, Text, Dimensions } from 'react-native';\nimport rnTextSize, { TSFontSpecs } from 'react-native-text-size-latest';\n\ntype Props = {};\n\nconst Test: React.FC = () => {\n const [dimensions, setDimensions] = useState({ width: 0, height: 0 });\n\n useEffect(() => {\n const fetchData = async () => {\n const width = Dimensions.get('window').width * 0.8;\n const fontSpecs: TSFontSpecs = {\n fontFamily: undefined,\n fontSize: 24,\n fontStyle: 'italic',\n fontWeight: 'bold',\n };\n const text = 'I ❤️ rnTextSize';\n\n const size = await rnTextSize.measure({\n text,\n width,\n ...fontSpecs,\n });\n\n setDimensions({\n width: size.width,\n height: size.height,\n });\n };\n\n fetchData();\n }, []); // Empty dependency array ensures useEffect runs only once, equivalent to componentDidMount\n\n return (\n \n \n I ❤️ rnTextSize\n \n \n );\n};\n\nexport default Test;\n ``` -------------------------------- ### Get Font Characteristics from Specs Source: https://github.com/abdulmateentechbits/react-native-text-size-latest/blob/master/README.md Returns font characteristics based on provided specifications. Use this to get detailed metrics like ascender, descender, and line height for a specific font configuration. ```typescript fontFromSpecs(specs: TSFontSpecs): Promise ``` -------------------------------- ### Get Font Names for a Specific Family Source: https://github.com/abdulmateentechbits/react-native-text-size-latest/blob/master/README.md Wraps UIKit's UIFont.fontNamesForFamilyName to return an array of font names within a given font family. This function is iOS-only; on Android, it resolves to null. Use fontFamilyNames() to get available family names. ```typescript fontNamesForFamilyName(fontFamily: string): Promise ``` -------------------------------- ### Configuration Object Flow Source: https://github.com/abdulmateentechbits/react-native-text-size-latest/blob/master/_autodocs/module-architecture.md Illustrates the path of configuration parameters from a TypeScript interface through JavaScript objects to native data structures for measurement. ```text TSMeasureParams (TS interface) ↓ JavaScript object { text, width, fontSize, ... } ↓ React Native Serialization ↓ ReadableMap (Android) / NSDictionary (iOS) ↓ RNTextSizeConf (Android) parses and validates ↓ Native measurement with extracted config ``` -------------------------------- ### Custom Font Variants (Android) Source: https://github.com/abdulmateentechbits/react-native-text-size-latest/blob/master/_autodocs/module-architecture.md Provides examples of font family variants for fine-grained control over font styles on Android. ```javascript // "sans-serif-light", "sans-serif-medium", "sans-serif-black", etc. ``` -------------------------------- ### flatHeights() Parameters Source: https://github.com/abdulmateentechbits/react-native-text-size-latest/blob/master/_autodocs/configuration.md Configuration options for the `flatHeights()` function. This function measures an array of strings and accepts parameters for width constraints and font scaling. ```APIDOC ## flatHeights() Parameters ### Parameters - **text** (Array) - Required - Array of strings. Null elements return 0. Empty strings return minimal height (14 points/SP). - **width** (number) - Optional, Default: MAX_INT - Maximum width for all strings. Single constraint applies to entire batch. - **allowFontScaling** (boolean) - Optional, Default: true - Respects system font scaling for all measurements. **Note:** `usePreciseWidth` and `lineInfoForLine` are not supported in flatHeights (always ignored). ``` -------------------------------- ### Import Library Source: https://github.com/abdulmateentechbits/react-native-text-size-latest/blob/master/_autodocs/integration-guide.md Import the necessary components and types from the react-native-text-size library. ```typescript import rnTextSize, { TSFontSpecs, TSMeasureResult, TSFontInfo, } from 'react-native-text-size-latest'; ``` -------------------------------- ### Trigger E_MISSING_TEXT Error Source: https://github.com/abdulmateentechbits/react-native-text-size-latest/blob/master/_autodocs/errors.md Provides examples of conditions that trigger the 'E_MISSING_TEXT' error for both `measure` (missing or null text) and `flatHeights` (text not an array) functions. ```javascript // measure await rnTextSize.measure({ fontSize: 16 }); // Error: no text await rnTextSize.measure({ text: null }); // Error: text is null // flatHeights await rnTextSize.flatHeights({ text: null }); // Error await rnTextSize.flatHeights({ text: "string" }); // Error: not an array ``` -------------------------------- ### Get System Font Styles Source: https://github.com/abdulmateentechbits/react-native-text-size-latest/blob/master/README.md Retrieves system font information for the current OS. This is useful for applying system-defined text styles to React Native components. ```typescript specsForTextStyles(): Promise<{ [key: string]: TSFontForStyle }> ``` -------------------------------- ### Graceful Degradation Wrapper for Text Measurement Source: https://github.com/abdulmateentechbits/react-native-text-size-latest/blob/master/_autodocs/integration-guide.md Provides a wrapper for text measurement functions that gracefully degrades by estimating dimensions when errors occur. Includes fallbacks for both `measure` and `flatHeights`. ```javascript const TextSizeWrapper = { async measure(params) { try { return await rnTextSize.measure(params); } catch (error) { // Estimate dimensions as fallback const textLength = params.text?.length || 0; const fontSize = params.fontSize || 14; return { width: textLength * (fontSize * 0.6), height: fontSize * 1.5, lineCount: 1, }; } }, async flatHeights(params) { try { return await rnTextSize.flatHeights(params); } catch (error) { const fontSize = params.fontSize || 14; return params.text.map(t => t ? fontSize * 1.5 : 0 ); } }, }; export { TextSizeWrapper }; ``` -------------------------------- ### Performance Instrumentation with PerformanceMonitor Source: https://github.com/abdulmateentechbits/react-native-text-size-latest/blob/master/_autodocs/best-practices.md Implement a PerformanceMonitor class to track and collect detailed metrics for text measurement operations. This helps in analyzing performance bottlenecks and understanding measurement costs. ```typescript interface PerformanceMetrics { durationMs: number; textLength: number; fontSize: number; success: boolean; cached?: boolean; } class PerformanceMonitor { private metrics: PerformanceMetrics[] = []; async measureWithMetrics( params: TSMeasureParams ): Promise<[TSMeasureResult, PerformanceMetrics]> { const startTime = performance.now(); const textLength = params.text.length; const fontSize = params.fontSize || 14; try { const result = await rnTextSize.measure(params); const durationMs = performance.now() - startTime; const metrics: PerformanceMetrics = { durationMs, textLength, fontSize, success: true, }; this.metrics.push(metrics); return [result, metrics]; } catch (error) { const durationMs = performance.now() - startTime; const metrics: PerformanceMetrics = { durationMs, textLength, fontSize, success: false, }; this.metrics.push(metrics); throw error; } } getAverageTime(): number { if (this.metrics.length === 0) return 0; const total = this.metrics.reduce((sum, m) => sum + m.durationMs, 0); return total / this.metrics.length; } getMetrics(): PerformanceMetrics[] { return [...this.metrics]; } reset(): void { this.metrics = []; } } ``` -------------------------------- ### Mock Implementation for Text Size Testing Source: https://github.com/abdulmateentechbits/react-native-text-size-latest/blob/master/_autodocs/best-practices.md This mock class allows for controlled testing of components that rely on text size measurement. It enables setting predefined results or errors for `measure` and `flatHeights` methods, facilitating isolated unit tests. ```typescript type MockMeasureResult = TSMeasureResult | Error; class MockTextSize { private measureResult: MockMeasureResult = { width: 100, height: 20, lineCount: 1, }; setMeasureResult(result: MockMeasureResult): void { this.measureResult = result; } async measure(params: TSMeasureParams): Promise { if (this.measureResult instanceof Error) { throw this.measureResult; } return this.measureResult; } async flatHeights(params: TSHeightsParams): Promise { if (this.measureResult instanceof Error) { throw this.measureResult; } return params.text.map(() => (this.measureResult as TSMeasureResult).height ); } // Other mocked methods... } // Usage in tests it('handles measurement', async () => { const mock = new MockTextSize(); mock.setMeasureResult({ width: 150, height: 30, lineCount: 2 }); const result = await mock.measure({ text: 'Hello World' }); expect(result.height).toBe(30); }); ``` -------------------------------- ### RNTextSizeConf Factory Method Source: https://github.com/abdulmateentechbits/react-native-text-size-latest/blob/master/_autodocs/module-architecture.md The factory method for creating RNTextSizeConf instances, taking a ReadableMap, a Promise, and a boolean flag. ```java getConf(ReadableMap, Promise, boolean) ``` -------------------------------- ### Get System Font Names (iOS) Source: https://github.com/abdulmateentechbits/react-native-text-size-latest/blob/master/_autodocs/configuration.md Retrieve available system font family names and specific font names within a family on iOS. Use system font names directly in your application. ```javascript // System fonts const families = await rnTextSize.fontFamilyNames(); // Returns: ["Helvetica", "Times New Roman", "Courier", ...] const names = await rnTextSize.fontNamesForFamilyName('Helvetica'); // Returns: ["Helvetica", "Helvetica-Bold", "Helvetica-Oblique", "Helvetica-BoldOblique"] ``` -------------------------------- ### Debug Logging Wrapper for Text Size Measurement Source: https://github.com/abdulmateentechbits/react-native-text-size-latest/blob/master/_autodocs/best-practices.md This wrapper logs detailed information during text measurement operations in development environments. It helps in understanding the input parameters and results of `measure` and `flatHeights` functions. ```typescript class DebugTextSize { private enabled = __DEV__; // Only in development async measure(params: TSMeasureParams): Promise { if (this.enabled) { console.log('[TextSize.measure]', { textLength: params.text.length, fontSize: params.fontSize, width: params.width, }); } const result = await rnTextSize.measure(params); if (this.enabled) { console.log('[TextSize.measure] Result:', { width: result.width, height: result.height, lineCount: result.lineCount, }); } return result; } async flatHeights(params: TSHeightsParams): Promise { if (this.enabled) { console.log('[TextSize.flatHeights]', { itemCount: params.text.length, fontSize: params.fontSize, }); } const result = await rnTextSize.flatHeights(params); if (this.enabled) { console.log('[TextSize.flatHeights] Result:', { itemCount: result.length, avgHeight: result.reduce((a, b) => a + b, 0) / result.length, }); } return result; } } export const debugTextSize = new DebugTextSize(); ``` -------------------------------- ### Get Font Names for a Family (iOS) Source: https://github.com/abdulmateentechbits/react-native-text-size-latest/blob/master/_autodocs/api-reference-core.md Retrieves an array of font names available within a specific font family on iOS. Returns null on Android as the functionality is not implemented. Ensure the fontFamily exists by checking with `fontFamilyNames()` first. ```javascript import rnTextSize from 'react-native-text-size-latest'; import { Platform } from 'react-native'; const getFontsInFamily = async (familyName) => { if (Platform.OS !== 'ios') { console.log('fontNamesForFamilyName is iOS-only'); return; } try { const fontNames = await rnTextSize.fontNamesForFamilyName(familyName); if (fontNames) { console.log(`Fonts in ${familyName}: ${fontNames.join(', ')}`); } } catch (error) { console.error(`Family ${familyName} not found`); } }; ``` -------------------------------- ### measure() Parameters Source: https://github.com/abdulmateentechbits/react-native-text-size-latest/blob/master/_autodocs/configuration.md Configuration options for the `measure()` function. These parameters control how text is measured, including text content, width constraints, font scaling, and precision. ```APIDOC ## measure() Parameters ### Parameters - **text** (string) - Required - The string to measure. Supports emojis. Can be empty "" but NOT null. - **width** (number) - Optional, Default: MAX_INT - Maximum width constraint in DIP (Android) or points (iOS). Triggers automatic line breaking when set. Used for FlatList columns, card widths, etc. - **allowFontScaling** (boolean) - Optional, Default: true - Respects system accessibility font size settings. If false, uses DIP/pixel units regardless of user settings. - **usePreciseWidth** (boolean) - Optional, Default: false - If true, calculates exact lastLineWidth (slower). Set true only when you need precise last-line measurement. - **lineInfoForLine** (number) - Optional - If >= 0, result includes lineInfo for line number (0-based). If greater than lineCount, uses last line. Useful for underline/highlight positioning. ``` -------------------------------- ### specsForTextStyles Source: https://github.com/abdulmateentechbits/react-native-text-size-latest/blob/master/_autodocs/INDEX.md Retrieves system text style specifications. Returns a promise that resolves with an object mapping text style keys to their specifications. ```APIDOC ## specsForTextStyles ### Description Retrieves system text style specifications. ### Method `specsForTextStyles(): Promise<{ [key: string]: TSFontForStyle }> ` ### Returns An object where keys are text style names and values are their corresponding specifications. ``` -------------------------------- ### Get Font Metrics with fontFromSpecs Source: https://github.com/abdulmateentechbits/react-native-text-size-latest/blob/master/_autodocs/api-reference-core.md Use this function to retrieve detailed font metrics for a given font specification. It's useful for precise text layout calculations. Ensure to handle potential errors from invalid font specifications. ```javascript import rnTextSize from 'react-native-text-size-latest'; const getFontMetrics = async () => { try { const fontInfo = await rnTextSize.fontFromSpecs({ fontFamily: 'sans-serif', fontSize: 16, fontWeight: 'bold', }); console.log(`Line Height: ${fontInfo.lineHeight}`); console.log(`Ascender: ${fontInfo.ascender}`); console.log(`Leading: ${fontInfo.leading}`); } catch (error) { console.error('Invalid font specification'); } }; ``` -------------------------------- ### flatHeights() Parameters Interface Source: https://github.com/abdulmateentechbits/react-native-text-size-latest/blob/master/_autodocs/configuration.md Defines the parameters for the `flatHeights()` function, accepting an array of strings and optional width and font scaling. Note that `usePreciseWidth` and `lineInfoForLine` are ignored. ```typescript interface TSHeightsParams extends TSFontSpecs { text: (string | null)[]; // Required width?: number; // Optional, MAX_INT allowFontScaling?: boolean; // Optional, true } ``` -------------------------------- ### Dynamic Height FlatList Source: https://github.com/abdulmateentechbits/react-native-text-size-latest/blob/master/_autodocs/integration-guide.md Implement a FlatList where item heights are dynamically calculated based on text content using `rnTextSize.flatHeights`. Ensures proper rendering for variable text lengths. ```javascript import React, { useEffect, useState } from 'react'; import { View, FlatList, Text, Dimensions } from 'react-native'; import rnTextSize from 'react-native-text-size-latest'; const DynamicHeightFlatList = ({ data }) => { const [itemHeights, setItemHeights] = useState({}); const width = Dimensions.get('window').width - 32; useEffect(() => { const measureItems = async () => { try { const heights = await rnTextSize.flatHeights({ text: data.map(item => item.title), width: width, fontSize: 16, }); // Map heights to item IDs const heightMap = {}; data.forEach((item, index) => { heightMap[item.id] = heights[index]; }); setItemHeights(heightMap); } catch (error) { console.error('Height measurement failed:', error); } }; if (data.length > 0) { measureItems(); } }, [data]); const renderItem = ({ item }) => { const itemHeight = itemHeights[item.id] || 50; return ( {item.title} ); }; return ( item.id} /> ); }; export default DynamicHeightFlatList; ``` -------------------------------- ### Handle E_MISSING_PARAMETERS Error Source: https://github.com/abdulmateentechbits/react-native-text-size-latest/blob/master/_autodocs/errors.md Demonstrates how to catch and handle the 'E_MISSING_PARAMETERS' error, which occurs when required parameters are not provided to functions like `measure`, `flatHeights`, or `fontFromSpecs`. ```javascript try { const result = await rnTextSize.measure({ text: 'Hello', fontSize: 16, }); } catch (error) { if (error.code === 'E_MISSING_PARAMETERS') { console.error('Must provide a params object'); } } ``` -------------------------------- ### Get System Font Specifications for Text Styles Source: https://github.com/abdulmateentechbits/react-native-text-size-latest/blob/master/_autodocs/api-reference-core.md Retrieve system font specifications for predefined text styles. Use this to style Text and TextInput components consistently with system defaults. Note that keys differ between iOS and Android, and font sizes are unscaled. ```typescript specsForTextStyles(): Promise<{ [key: string]: TSFontForStyle }> ``` ```javascript import rnTextSize from 'react-native-text-size-latest'; import { Text, StyleSheet } from 'react-native'; const styles = StyleSheet.create({ h1: { fontSize: 96, fontWeight: 'bold' }, }); const applySystemStyles = async () => { try { const specs = await rnTextSize.specsForTextStyles(); // Android const h1Spec = specs.h1; console.log(`h1 Font Size: ${h1Spec.fontSize}, Family: ${h1Spec.fontFamily}`); // iOS const titleSpec = specs.title1; console.log(`title1 Font Size: ${titleSpec.fontSize}`); } catch (error) { console.error('Failed to get text styles'); } }; ``` -------------------------------- ### Configure Text Break Strategies (Android API 23+) Source: https://github.com/abdulmateentechbits/react-native-text-size-latest/blob/master/_autodocs/configuration.md Control how text is broken into lines using the `textBreakStrategy` option. Available strategies are 'simple' (fastest), 'highQuality' (default, best results), and 'balanced' (middle ground). ```javascript // Simple: Fastest but less optimal await rnTextSize.measure({ text: largeText, width: 300, textBreakStrategy: 'simple', fontSize: 14, }); ``` ```javascript // High Quality: Default, best results await rnTextSize.measure({ text: largeText, width: 300, textBreakStrategy: 'highQuality', fontSize: 14, }); ``` ```javascript // Balanced: Middle ground await rnTextSize.measure({ text: largeText, width: 300, textBreakStrategy: 'balanced', fontSize: 14, }); ``` -------------------------------- ### Get Available Font Family Names Source: https://github.com/abdulmateentechbits/react-native-text-size-latest/blob/master/_autodocs/api-reference-core.md Retrieves an alphabetically sorted array of all available font family names on the device. This includes system fonts and custom fonts if present on Android, and all system font families on iOS. Use this to list all possible font families for user selection or inspection. ```typescript fontFamilyNames(): Promise ``` -------------------------------- ### Enable Logging for Text Measurement Source: https://github.com/abdulmateentechbits/react-native-text-size-latest/blob/master/_autodocs/integration-guide.md Use this function to log all measurement calls made by the library. It logs the parameters, the result, and the duration of each measurement. ```javascript import { LogBox } from 'react-native'; // Log all measurement calls const measureWithLogging = async (params) => { const startTime = Date.now(); console.log('Measuring:', params); try { const result = await rnTextSize.measure(params); const duration = Date.now() - startTime; console.log('Measurement result:', result, `(${duration}ms)`); return result; } catch (error) { const duration = Date.now() - startTime; console.error('Measurement error:', error, `(${duration}ms)`); throw error; } }; ``` -------------------------------- ### Load Custom Fonts (Android) Source: https://github.com/abdulmateentechbits/react-native-text-size-latest/blob/master/_autodocs/configuration.md Place custom font files (.ttf, .otf) in the `android/app/src/main/assets/fonts/` directory. Reference them in your measurements by their filename without the extension. ```javascript await rnTextSize.measure({ text: 'Hello', fontFamily: 'MyCustomFont', // Filename without .ttf fontSize: 14, }); ``` -------------------------------- ### Migrate to react-native-text-size-latest Source: https://github.com/abdulmateentechbits/react-native-text-size-latest/blob/master/_autodocs/integration-guide.md Demonstrates the import change when migrating from the original react-native-text-size package. The API remains identical, requiring no code modifications beyond the import statement. ```javascript // Old import // import RNTextSize from 'react-native-text-size'; // New import import RNTextSize from 'react-native-text-size-latest'; // API is identical, no code changes needed const result = await RNTextSize.measure({ text: 'Hello', fontSize: 16, }); ``` -------------------------------- ### Configure FlatList Item Heights Source: https://github.com/abdulmateentechbits/react-native-text-size-latest/blob/master/_autodocs/configuration.md Use this configuration to measure the heights of items within a FlatList. Ensure to account for screen padding when setting the width. ```javascript const flatListConfig = { width: Dimensions.get('window').width - 32, // Minus padding fontSize: 14, fontFamily: undefined, // System default includeFontPadding: true, allowFontScaling: true, }; const heights = await rnTextSize.flatHeights({ ...flatListConfig, text: items.map(i => i.title), }); ``` -------------------------------- ### Heights Parameters Source: https://github.com/abdulmateentechbits/react-native-text-size-latest/blob/master/_autodocs/types.md Parameters for batch text height measurement via `flatHeights`. This function is optimized for measuring the heights of multiple text strings efficiently. ```APIDOC ## flatHeights ### Description Calculates the heights of an array of text strings in a batch operation. ### Method (Implicitly a function call, not an HTTP method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body ##### Parameters for `flatHeights` function: - **text** (Array) - Required - Array of text strings to measure. Null elements return 0. Empty strings return minimal height. - **width** (number) - Optional - Maximum width constraint for all strings. Defaults to MAX_INT. - **allowFontScaling** (boolean) - Optional - Respects system font scaling. Defaults to true. - **...TSFontSpecs** - Inherits all font specification fields. usePreciseWidth and lineInfoForLine are ignored. ### Request Example ```json { "text": ["First line", "Second line", null, ""], "width": 200, "allowFontScaling": false } ``` ### Response #### Success Response - **Promise** - An array of numbers representing the calculated height for each input string. ``` -------------------------------- ### Optimize with Batch Text Measurements Source: https://github.com/abdulmateentechbits/react-native-text-size-latest/blob/master/_autodocs/integration-guide.md Utilize the `flatHeights` method for batch processing of text measurements to improve performance over sequential `measure` calls. This is recommended when measuring multiple text elements with the same styling and width. ```javascript // Good: Single batch call const heights = await rnTextSize.flatHeights({ text: items.map(i => i.title), width: 300, fontSize: 16, }); // Avoid: Multiple sequential calls // for (const item of items) { // const result = await rnTextSize.measure({ // text: item.title, // width: 300, // fontSize: 16, // }); // } ``` -------------------------------- ### Error Flow Source: https://github.com/abdulmateentechbits/react-native-text-size-latest/blob/master/_autodocs/module-architecture.md Explains how native exceptions or explicit rejections are translated into JavaScript Promise rejections. ```text Android: Native exception or promise.reject(code, message) ↓ Promise rejected with error code string iOS: RCTPromiseRejectBlock(code, message, nil) ↓ Promise rejected with error code string ``` -------------------------------- ### RNTextSizeConf scale Method Source: https://github.com/abdulmateentechbits/react-native-text-size-latest/blob/master/_autodocs/module-architecture.md Applies font scaling, converting between Scaled Pixels (SP) and Density-Independent Pixels (DIP). ```java scale(float) ``` -------------------------------- ### RNTextSizeConf getWidth Method Source: https://github.com/abdulmateentechbits/react-native-text-size-latest/blob/master/_autodocs/module-architecture.md Resolves the width constraint for text measurement. ```java getWidth(float) ``` -------------------------------- ### Optimize Measurements with Batching Source: https://github.com/abdulmateentechbits/react-native-text-size-latest/blob/master/_autodocs/best-practices.md Process multiple text measurements in batches to reduce the overhead of individual calls. This function groups items into batches and uses `rnTextSize.flatHeights` for efficient measurement. Includes error handling for batch failures. ```typescript async function optimizedMeasureBatch( items: Array<{ id: string; text: string }>, batchSize = 50 ): Promise> { const results = new Map(); for (let i = 0; i < items.length; i += batchSize) { const batch = items.slice(i, i + batchSize); try { const heights = await rnTextSize.flatHeights({ text: batch.map(item => item.text), width: 300, fontSize: 14, }); batch.forEach((item, index) => { results.set(item.id, heights[index]); }); } catch (error) { console.error(`Batch ${Math.floor(i / batchSize)} failed:`, error); // Fallback for this batch batch.forEach(item => { results.set(item.id, 20); // Default height }); } } return results; } ``` -------------------------------- ### Font Scaling Behavior Comparison Source: https://github.com/abdulmateentechbits/react-native-text-size-latest/blob/master/_autodocs/platform-differences.md Demonstrates how `allowFontScaling` affects text measurement. With scaling enabled, user font size settings influence the measured height. Without scaling, the size remains fixed. ```javascript const scaled = await rnTextSize.measure({ text: 'Hello', fontSize: 14, allowFontScaling: true, // Default }); const fixed = await rnTextSize.measure({ text: 'Hello', fontSize: 14, allowFontScaling: false, }); // scaled.height might be 1.3x larger if user has large fonts enabled ``` -------------------------------- ### Measure Text Width Differences (Android vs. iOS) Source: https://github.com/abdulmateentechbits/react-native-text-size-latest/blob/master/_autodocs/platform-differences.md Demonstrates how leading whitespace affects text width measurement differently on Android and iOS. Android discards leading whitespace, while iOS includes it. This can lead to significant width discrepancies. Trim user input and account for variance in layouts. ```javascript const result = await rnTextSize.measure({ text: ' Hello ', // Leading spaces width: 300, }); // Android: width excludes leading spaces // iOS: width includes leading spaces // Difference can be ~20-30% for texts with significant leading whitespace ``` -------------------------------- ### Implement Caching for Text Measurements Source: https://github.com/abdulmateentechbits/react-native-text-size-latest/blob/master/_autodocs/integration-guide.md Use this class to cache text measurement results in memory, avoiding redundant calculations for identical parameters. Initialize with a unique cache key if needed. ```javascript import AsyncStorage from '@react-native-async-storage/async-storage'; import rnTextSize from 'react-native-text-size-latest'; class MeasurementCache { constructor(cacheKey = 'text_measurements') { this.cacheKey = cacheKey; this.memoryCache = new Map(); } async measure(params) { const key = JSON.stringify(params); // Check memory cache first if (this.memoryCache.has(key)) { return this.memoryCache.get(key); } // Perform measurement const result = await rnTextSize.measure(params); // Cache in memory this.memoryCache.set(key, result); return result; } async flatHeights(params) { // Similar pattern for batches const key = JSON.stringify(params); if (this.memoryCache.has(key)) { return this.memoryCache.get(key); } const result = await rnTextSize.flatHeights(params); this.memoryCache.set(key, result); return result; } clear() { this.memoryCache.clear(); } } const measurementCache = new MeasurementCache(); export { measurementCache }; ``` -------------------------------- ### Import RNTextSize in TypeScript Source: https://github.com/abdulmateentechbits/react-native-text-size-latest/blob/master/_autodocs/module-architecture.md Demonstrates how to import the RNTextSize module in a TypeScript project. You can use either ES module imports or CommonJS require syntax. ```typescript import rnTextSize from 'react-native-text-size-latest'; // or const rnTextSize = require('react-native-text-size-latest').default; ``` -------------------------------- ### fontFromSpecs() Function Source: https://github.com/abdulmateentechbits/react-native-text-size-latest/blob/master/_autodocs/INDEX.md Creates font styles based on provided specifications. ```APIDOC ## fontFromSpecs() ### Description Creates font styles based on provided `TSFontSpecs`. This function uses only the core font specifications without additional parameters. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **TSFontSpecs** (object) - Required - An object containing font properties like `fontFamily`, `fontSize`, `fontWeight`, `fontStyle`, `fontVariant`, `letterSpacing`, `includeFontPadding`, and `textBreakStrategy`. ``` -------------------------------- ### Return Value Flow Source: https://github.com/abdulmateentechbits/react-native-text-size-latest/blob/master/_autodocs/module-architecture.md Details how measurement results are passed from native code back to JavaScript using Promises. ```text Android: WritableMap/WritableArray ↓ Promise.resolve(result) ↓ JavaScript: TSMeasureResult / number[] iOS: NSDictionary/NSArray ↓ RCTPromiseResolveBlock(result) ↓ JavaScript: TSMeasureResult / number[] ``` -------------------------------- ### Provide Fallbacks for Measurement Errors Source: https://github.com/abdulmateentechbits/react-native-text-size-latest/blob/master/_autodocs/errors.md Implement a try-catch block to handle potential measurement errors. If an error occurs, log the error code and return estimated dimensions as a fallback. ```javascript const measureWithFallback = async (text, specs = {}) => { try { return await rnTextSize.measure({ text: text || 'Fallback Text', fontSize: specs.fontSize || 14, fontFamily: specs.fontFamily || undefined, // OS default ...specs, }); } catch (error) { console.warn('Measurement failed:', error.code); // Return estimated dimensions return { width: (text || '').length * 8, height: 20, lineCount: 1, }; } }; ``` -------------------------------- ### Measure Text Height Differences (Android vs. iOS) Source: https://github.com/abdulmateentechbits/react-native-text-size-latest/blob/master/_autodocs/platform-differences.md Illustrates potential minor differences in text height calculation between Android and iOS. Android's height can be influenced by the 'includeFontPadding' setting, whereas iOS does not have a comparable setting and always includes necessary space. ```javascript const result = await rnTextSize.measure({ text: 'Hello\nWorld', fontSize: 14, }); // Heights should be similar but may differ by 1-2 pixels // Android: influenced by includeFontPadding setting // iOS: no setting available ``` -------------------------------- ### RNTextSize scaledUIFontFromUserSpecs Method Source: https://github.com/abdulmateentechbits/react-native-text-size-latest/blob/master/_autodocs/module-architecture.md Creates a UIFont instance with scaling applied, suitable for iOS text measurement. ```objectivec scaledUIFontFromUserSpecs(_:) ```