Essential utilities for data manipulation, string processing, array operations, and basic DOM functionality used throughout Facebook's JavaScript ecosystem.
Detects the execution environment and available features.
const ExecutionEnvironment = require('fbjs/lib/ExecutionEnvironment');
// Environment detection object
interface ExecutionEnvironmentType {
canUseDOM: boolean; // Whether DOM is available
canUseWorkers: boolean; // Whether Web Workers are supported
canUseEventListeners: boolean; // Whether event listeners are supported
canUseViewport: boolean; // Whether viewport/screen is available
isInWorker: boolean; // Whether code is running in a worker
}Usage Examples:
const ExecutionEnvironment = require('fbjs/lib/ExecutionEnvironment');
if (ExecutionEnvironment.canUseDOM) {
// Safe to use document, window, etc.
const element = document.getElementById('myElement');
}
if (ExecutionEnvironment.canUseEventListeners) {
// Safe to use addEventListener
element.addEventListener('click', handler);
}Empty function utilities and function creation helpers.
const emptyFunction = require('fbjs/lib/emptyFunction');
/**
* Empty function that does nothing
* @returns void
*/
function emptyFunction(): void;
// Static methods on emptyFunction
emptyFunction.thatReturns = function(returnValue: any): () => any;
emptyFunction.thatReturnsFalse = function(): () => false;
emptyFunction.thatReturnsTrue = function(): () => true;
emptyFunction.thatReturnsNull = function(): () => null;
emptyFunction.thatReturnsThis = function(): () => any;
emptyFunction.thatReturnsArgument = function(): (arg: any) => any;Usage Examples:
const emptyFunction = require('fbjs/lib/emptyFunction');
// Use as placeholder callback
const callback = emptyFunction;
// Create functions that return specific values
const alwaysTrue = emptyFunction.thatReturnsTrue();
const alwaysFalse = emptyFunction.thatReturnsFalse();
const identity = emptyFunction.thatReturnsArgument();Object creation and comparison utilities.
const emptyObject = require('fbjs/lib/emptyObject');
const shallowEqual = require('fbjs/lib/shallowEqual');
const areEqual = require('fbjs/lib/areEqual');
// Empty frozen object constant
const emptyObject: {};
/**
* Performs shallow equality comparison of two objects
* Uses inlined Object.is polyfill for SameValue algorithm (handles NaN and +0/-0 correctly)
* Compares object keys and values using strict equality with special NaN/zero handling
* @param objA - First value to compare (any type)
* @param objB - Second value to compare (any type)
* @returns True if objects are shallowly equal using SameValue comparison
*/
function shallowEqual(objA: mixed, objB: mixed): boolean;
/**
* Performs deep equality comparison
* @param a - First value to compare
* @param b - Second value to compare
* @returns True if values are deeply equal
*/
function areEqual(a: any, b: any): boolean;Usage Examples:
const shallowEqual = require('fbjs/lib/shallowEqual');
const areEqual = require('fbjs/lib/areEqual');
// Shallow comparison (React-style)
const props1 = { name: 'Alice', age: 25 };
const props2 = { name: 'Alice', age: 25 };
const isSame = shallowEqual(props1, props2); // true
// Special SameValue algorithm cases - handles NaN and +0/-0 correctly
const nanComparison = shallowEqual({ value: NaN }, { value: NaN }); // true
const zeroComparison = shallowEqual({ value: +0 }, { value: -0 }); // false (unlike ===)
const nullComparison = shallowEqual(null, null); // true
const primitiveComparison = shallowEqual(42, 42); // true
// Type checking - non-objects return false unless same primitive
const mixedTypes = shallowEqual({ a: 1 }, 'not an object'); // false
const nullVsObject = shallowEqual(null, { a: 1 }); // false
// Safe shallow comparison wrapper
function safeShallowEqual(a, b, defaultValue = false) {
try {
return shallowEqual(a, b);
} catch (error) {
console.warn('shallowEqual comparison failed:', error.message);
return defaultValue;
}
}
// Performance consideration - early returns for identical references
const obj = { x: 1, y: 2 };
const sameReference = shallowEqual(obj, obj); // true (fast path)
// Different key counts - efficient early return
const different = shallowEqual({ a: 1, b: 2 }, { a: 1 }); // false (different key count)
// Deep comparison
const deep1 = { user: { name: 'Bob', meta: { active: true } } };
const deep2 = { user: { name: 'Bob', meta: { active: true } } };
const isDeepEqual = areEqual(deep1, deep2); // trueString formatting and transformation utilities.
const sprintf = require('fbjs/lib/sprintf');
const camelize = require('fbjs/lib/camelize');
const camelizeStyleName = require('fbjs/lib/camelizeStyleName');
const hyphenate = require('fbjs/lib/hyphenate');
const hyphenateStyleName = require('fbjs/lib/hyphenateStyleName');
/**
* String formatting utility with %s placeholder support
* @param format - Format string with %s placeholders
* @param args - Values to substitute
* @returns Formatted string
*/
function sprintf(format: string, ...args: Array<any>): string;
/**
* Converts hyphenated string to camelCase
* @param string - Hyphenated string
* @returns CamelCase string
*/
function camelize(string: string): string;
/**
* Converts CSS property names to camelCase
* @param name - CSS property name (e.g., 'background-color')
* @returns CamelCase property name (e.g., 'backgroundColor')
*/
function camelizeStyleName(name: string): string;
/**
* Converts camelCase string to hyphenated
* @param string - CamelCase string
* @returns Hyphenated string
*/
function hyphenate(string: string): string;
/**
* Converts camelCase CSS properties to hyphenated
* @param name - CamelCase CSS property (e.g., 'backgroundColor')
* @returns Hyphenated property (e.g., 'background-color')
*/
function hyphenateStyleName(name: string): string;Usage Examples:
const sprintf = require('fbjs/lib/sprintf');
const camelize = require('fbjs/lib/camelize');
// String formatting
const message = sprintf('User %s has %s points', 'Alice', 100);
// Result: 'User Alice has 100 points'
// Case conversion
const camelCase = camelize('background-color'); // 'backgroundColor'
const hyphenated = hyphenate('backgroundColor'); // 'background-color'Array creation, manipulation, and enumeration utilities.
const createArrayFromMixed = require('fbjs/lib/createArrayFromMixed');
const flattenArray = require('fbjs/lib/flattenArray');
const enumerate = require('fbjs/lib/enumerate');
/**
* Creates array from array-like or iterable object
* @param obj - Array-like or iterable object
* @returns Standard array
*/
function createArrayFromMixed(obj: any): Array<any>;
/**
* Flattens nested arrays into a single array
* @param array - Nested array structure
* @returns Flattened array
*/
function flattenArray(array: Array<any>): Array<any>;
/**
* Enumerates object properties with callback
* @param object - Object to enumerate
* @param callback - Function called for each property
* @param context - Optional context for callback
*/
function enumerate(object: any, callback: (value: any, key: string) => void, context?: any): void;Usage Examples:
const createArrayFromMixed = require('fbjs/lib/createArrayFromMixed');
const flattenArray = require('fbjs/lib/flattenArray');
// Convert NodeList to array
const elements = createArrayFromMixed(document.querySelectorAll('.item'));
// Flatten nested arrays
const nested = [[1, 2], [3, 4], [5]];
const flat = flattenArray(nested); // [1, 2, 3, 4, 5]Mathematical operations and number utilities.
const clamp = require('fbjs/lib/clamp');
/**
* Clamps a number within specified range
* @param value - Number to clamp
* @param min - Minimum value
* @param max - Maximum value
* @returns Clamped number
*/
function clamp(value: number, min: number, max: number): number;Usage Examples:
const clamp = require('fbjs/lib/clamp');
const clamped = clamp(150, 0, 100); // 100
const inRange = clamp(50, 0, 100); // 50
const below = clamp(-10, 0, 100); // 0Data validation and checking utilities.
const isEmail = require('fbjs/lib/isEmail');
const isEmpty = require('fbjs/lib/isEmpty');
/**
* Validates email address format
* @param value - String to validate as email
* @returns True if valid email format
*/
function isEmail(value: string): boolean;
/**
* Checks if value is empty (null, undefined, empty string, etc.)
* @param value - Value to check
* @returns True if value is considered empty
*/
function isEmpty(value: any): boolean;Function optimization and memoization utilities.
const memoizeStringOnly = require('fbjs/lib/memoizeStringOnly');
const debounceCore = require('fbjs/lib/debounceCore');
/**
* Memoizes function that takes only string arguments
* @param fn - Function to memoize (must accept only string args)
* @returns Memoized version of function
*/
function memoizeStringOnly<T>(fn: (arg: string) => T): (arg: string) => T;
/**
* Debounces function calls
* @param func - Function to debounce
* @param wait - Delay in milliseconds
* @param immediate - Whether to trigger on leading edge
* @returns Debounced function
*/
function debounceCore(func: Function, wait: number, immediate?: boolean): Function;CSS property manipulation and vendor prefixing utilities.
const getVendorPrefixedName = require('fbjs/lib/getVendorPrefixedName');
const joinClasses = require('fbjs/lib/joinClasses');
/**
* Gets vendor-prefixed CSS property name
* @param property - CSS property name
* @param style - Style object to test against
* @returns Vendor-prefixed property name or original
*/
function getVendorPrefixedName(property: string, style?: any): string;
/**
* Joins CSS class names, filtering out falsy values
* @param classes - Class names to join
* @returns Space-separated class string
*/
function joinClasses(...classes: Array<string>): string;Keyboard key codes and other constants.
const Keys = require('fbjs/lib/Keys');
// Keyboard key code constants
interface KeysType {
BACKSPACE: 8;
TAB: 9;
NUM_CENTER: 12;
ENTER: 13;
SHIFT: 16;
CTRL: 17;
ALT: 18;
PAUSE: 19;
CAPS_LOCK: 20;
ESC: 27;
SPACE: 32;
PAGE_UP: 33;
PAGE_DOWN: 34;
END: 35;
HOME: 36;
LEFT: 37;
UP: 38;
RIGHT: 39;
DOWN: 40;
PRINT_SCREEN: 44;
INSERT: 45;
DELETE: 46;
ZERO: 48;
ONE: 49;
TWO: 50;
THREE: 51;
FOUR: 52;
FIVE: 53;
SIX: 54;
SEVEN: 55;
EIGHT: 56;
NINE: 57;
QUESTION_MARK: 63;
A: 65;
B: 66;
C: 67;
D: 68;
E: 69;
F: 70;
G: 71;
H: 72;
I: 73;
J: 74;
K: 75;
L: 76;
M: 77;
N: 78;
O: 79;
P: 80;
Q: 81;
R: 82;
S: 83;
T: 84;
U: 85;
V: 86;
W: 87;
X: 88;
Y: 89;
Z: 90;
META: 91;
NUM_ZERO: 96;
NUM_ONE: 97;
NUM_TWO: 98;
NUM_THREE: 99;
NUM_FOUR: 100;
NUM_FIVE: 101;
NUM_SIX: 102;
NUM_SEVEN: 103;
NUM_EIGHT: 104;
NUM_NINE: 105;
NUM_MULTIPLY: 106;
NUM_PLUS: 107;
NUM_MINUS: 109;
NUM_PERIOD: 110;
NUM_DIVISION: 111;
F1: 112;
F2: 113;
F3: 114;
F4: 115;
F5: 116;
F6: 117;
F7: 118;
F8: 119;
F9: 120;
F10: 121;
F11: 122;
F12: 123;
NUMLOCK: 144;
SEMICOLON: 186;
DASH: 189;
EQUALS: 187;
COMMA: 188;
PERIOD: 190;
SLASH: 191;
APOSTROPHE: 192;
SINGLE_QUOTE: 222;
}Utilities for handling file transfers and clipboard data operations.
const DataTransfer = require('fbjs/lib/DataTransfer');
const PhotosMimeType = require('fbjs/lib/PhotosMimeType');
/**
* Data transfer utility class for file handling
* Provides methods for file transfer and clipboard data operations
*/
class DataTransfer {
/**
* Handles file transfer operations
* @param files - FileList or array of File objects
* @returns Processed file data
*/
static processFiles(files: FileList | File[]): any;
/**
* Manages clipboard data operations
* @param clipboardData - Clipboard data object
* @returns Processed clipboard content
*/
static processClipboard(clipboardData: any): any;
}
/**
* Photo and image MIME type utilities
* Validates and processes image MIME types
*/
const PhotosMimeType: {
/**
* Checks if MIME type is a supported image format
* @param mimeType - MIME type string to check
* @returns True if MIME type represents an image
*/
isImage(mimeType: string): boolean;
/**
* Gets file extension for image MIME type
* @param mimeType - Image MIME type
* @returns File extension or null if not supported
*/
getExtension(mimeType: string): ?string;
/**
* Lists all supported image MIME types
* @returns Array of supported MIME type strings
*/
getSupportedTypes(): Array<string>;
};Usage Examples:
const DataTransfer = require('fbjs/lib/DataTransfer');
const PhotosMimeType = require('fbjs/lib/PhotosMimeType');
// File upload handling
function handleFileUpload(event) {
const files = event.target.files;
const processedFiles = DataTransfer.processFiles(files);
Array.from(files).forEach(file => {
if (PhotosMimeType.isImage(file.type)) {
console.log(`Processing image: ${file.name}`);
console.log(`Extension: ${PhotosMimeType.getExtension(file.type)}`);
} else {
console.log(`Unsupported file type: ${file.type}`);
}
});
}
// Drag and drop handling
function handleDrop(event) {
event.preventDefault();
const clipboardData = event.dataTransfer;
const processedData = DataTransfer.processClipboard(clipboardData);
const files = Array.from(clipboardData.files);
const imageFiles = files.filter(file => PhotosMimeType.isImage(file.type));
console.log(`Dropped ${imageFiles.length} image files`);
}
// Supported image types
const supportedTypes = PhotosMimeType.getSupportedTypes();
console.log('Supported image formats:', supportedTypes);
// Example output: ['image/jpeg', 'image/png', 'image/gif', 'image/webp']Utility for removing elements from arrays (windowless environment compatible).
const removeFromArray = require('fbjs/lib/removeFromArray');
/**
* Removes element from array in-place
* @param array - Array to modify
* @param element - Element to remove
*/
function removeFromArray<T>(array: Array<T>, element: T): void;Usage Examples:
const removeFromArray = require('fbjs/lib/removeFromArray');
const items = ['a', 'b', 'c', 'b'];
removeFromArray(items, 'b'); // items is now ['a', 'c', 'b'] (removes first occurrence)