CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-rc-util

Common utility functions and components specifically designed for React development.

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

development-styling.mddocs/

Development & Styling

Development tools and styling utilities including deprecation warnings, attribute filtering, layout effect management, and data manipulation helpers.

Capabilities

Attribute Management

pickAttrs

Extracts valid HTML attributes and events from props object, useful for passing through valid DOM props while filtering out component-specific props.

/**
 * Pick valid HTML attributes and events from props
 * @param {object} props - Props object to filter
 * @param {boolean} [ariaOnly=false] - If true, only pick aria-* attributes
 * @returns {object} Filtered props containing only valid HTML attributes
 */
function pickAttrs(props: object, ariaOnly?: boolean): object;

Usage Example:

import pickAttrs from 'rc-util/lib/pickAttrs';

function Button({ 
  children, 
  type = 'button', 
  customProp, 
  onClick, 
  className,
  'aria-label': ariaLabel,
  'data-testid': testId,
  ...restProps 
}) {
  // Get only valid HTML attributes
  const htmlProps = pickAttrs(restProps);
  
  return (
    <button 
      type={type}
      onClick={onClick}
      className={className}
      aria-label={ariaLabel}
      data-testid={testId}
      {...htmlProps}
    >
      {children}
    </button>
  );
}

// Only aria attributes
const ariaProps = pickAttrs(props, true);

Styling Utilities

setStyle

Sets element styles and returns previous styles for restoration, with IE browser compatibility.

/**
 * Set element styles and return previous styles
 * @param {React.CSSProperties} style - Styles to apply
 * @param {SetStyleOptions} [options] - Configuration options
 * @returns {React.CSSProperties} Previous styles for restoration
 */
function setStyle(
  style: React.CSSProperties,
  options?: SetStyleOptions
): React.CSSProperties;

interface SetStyleOptions {
  /** Target element (defaults to document.body) */
  element?: HTMLElement;
}

Usage Example:

import setStyle from 'rc-util/lib/setStyle';

// Apply modal styles
const previousStyles = setStyle({
  overflow: 'hidden',
  paddingRight: '17px'
});

// Later restore original styles
setStyle(previousStyles);

// Apply to specific element
const elementStyles = setStyle(
  { position: 'fixed', top: '0' },
  { element: document.getElementById('header') }
);

Data Utilities

get

Safe property access using path array, useful for accessing nested object properties without throwing errors.

/**
 * Safe property access using path array
 * @param {any} entity - Object to access properties from
 * @param {(string | number)[]} path - Property path as array
 * @returns {T | undefined} Property value or undefined if not found
 */
function get<T = any>(entity: any, path: (string | number)[]): T | undefined;

Usage Example:

import get from 'rc-util/lib/utils/get';

const user = {
  profile: {
    address: {
      city: 'New York'
    }
  }
};

// Safe nested access
const city = get(user, ['profile', 'address', 'city']); // 'New York'
const missing = get(user, ['profile', 'phone', 'number']); // undefined

// Array access
const items = [{ name: 'first' }, { name: 'second' }];
const firstName = get(items, [0, 'name']); // 'first'

set

Immutable property setting using path array, returns new object with updated property.

/**
 * Immutable property setting using path array
 * @param {Entity} entity - Source object/array
 * @param {(string | number)[]} paths - Property path as array
 * @param {Value} value - Value to set
 * @returns {Output} New object/array with updated property
 */
function set<Entity = any, Output = Entity, Value = any>(
  entity: Entity,
  paths: (string | number)[],
  value: Value
): Output;

Usage Example:

import set from 'rc-util/lib/utils/set';

const original = {
  user: {
    profile: {
      name: 'John'
    }
  }
};

// Immutable update
const updated = set(original, ['user', 'profile', 'name'], 'Jane');
// Original object is unchanged, new object returned

// Array updates
const items = [{ id: 1, name: 'Item 1' }];
const updatedItems = set(items, [0, 'name'], 'Updated Item');

KeyCode Utilities

KeyCode

Comprehensive keyboard key code definitions and utilities for keyboard event handling.

/**
 * Key code constants and utilities
 */
const KeyCode: {
  // Key code constants
  MAC_ENTER: 3;
  BACKSPACE: 8;
  TAB: 9;
  ENTER: 13;
  SHIFT: 16;
  CTRL: 17;
  ALT: 18;
  ESC: 27;
  SPACE: 32;
  LEFT: 37;
  UP: 38;
  RIGHT: 39;
  DOWN: 40;
  DELETE: 46;
  // ... many more key codes
  
  /**
   * Check if key event is a text-modifying key
   * @param {Event} e - Keyboard event
   * @returns {boolean} True if key modifies text
   */
  isTextModifyingKeyEvent(e: Event): boolean;
  
  /**
   * Check if key code represents a character key
   * @param {number} keyCode - Key code to check
   * @returns {boolean} True if key produces character input
   */
  isCharacterKey(keyCode: number): boolean;
};

Usage Example:

import KeyCode from 'rc-util/lib/KeyCode';

function handleKeyDown(e) {
  switch (e.keyCode) {
    case KeyCode.ENTER:
      handleSubmit();
      break;
    case KeyCode.ESC:
      handleCancel();
      break;
    case KeyCode.TAB:
      // Handle tab navigation
      break;
  }
  
  // Check if text is being modified
  if (KeyCode.isTextModifyingKeyEvent(e)) {
    setHasChanges(true);
  }
  
  // Check if character was entered
  if (KeyCode.isCharacterKey(e.keyCode)) {
    updateCharacterCount();
  }
}

Children Utilities

mapSelf

Returns a shallow copy of React children, useful for React element manipulation.

/**
 * Return a shallow copy of React children
 * @param {ReactNode} children - React children to copy
 * @returns {ReactNode[]} Shallow copy of children
 */
function mapSelf(children: ReactNode): ReactNode[];

toArray

Converts React children to a flat array, handling fragments and nested arrays.

/**
 * Convert React children to flat array
 * @param {React.ReactNode} children - React children to convert
 * @returns {React.ReactElement[]} Flat array of React elements
 */
function toArray(children: React.ReactNode): React.ReactElement[];

Usage Examples:

import mapSelf from 'rc-util/lib/Children/mapSelf';
import toArray from 'rc-util/lib/Children/toArray';

// Shallow copy children
function ParentComponent({ children }) {
  const childrenCopy = mapSelf(children);
  return <div>{childrenCopy}</div>;
}

// Convert to flat array
function ListComponent({ children }) {
  const childArray = toArray(children);
  
  return (
    <ul>
      {childArray.map((child, index) => (
        <li key={index}>{child}</li>
      ))}
    </ul>
  );
}

// Handles fragments automatically
<ListComponent>
  <span>Item 1</span>
  <>
    <span>Item 2</span>
    <span>Item 3</span>
  </>
  {[<span key="4">Item 4</span>, <span key="5">Item 5</span>]}
</ListComponent>

Legacy Utilities

PureRenderMixin

Legacy pure render mixin for class components (use React.memo for functional components).

/**
 * Legacy mixin for pure rendering in class components
 */
const PureRenderMixin: {
  shouldComponentUpdate(nextProps: object, nextState: object): boolean;
};

unsafeLifecyclesPolyfill

Polyfill for unsafe React lifecycle methods.

/**
 * Polyfill for unsafe React lifecycle methods
 * @param {React.ComponentType} Component - Component to polyfill
 */
function unsafeLifecyclesPolyfill(Component: React.ComponentType): void;

Debug Utilities

diff

Development debugging utility for deep object comparison and difference detection.

/**
 * Deep diff two objects and return difference list
 * @param {any} obj1 - First object to compare
 * @param {any} obj2 - Second object to compare
 * @param {number} [depth=10] - Maximum comparison depth
 * @param {string[]} [path=[]] - Current path being compared
 * @param {Array} [diffList] - Accumulator for differences
 * @returns {Array} List of differences with paths and values
 */
function diff(
  obj1: any, 
  obj2: any, 
  depth?: number, 
  path?: string[], 
  diffList?: Array
): Array;

Test Utilities

Testing utilities for DOM element spying and mocking in test environments.

spyElementPrototypes

Spy on multiple element prototype properties for testing.

/**
 * Spy on multiple element prototype properties
 * @param {ElementClass} elementClass - Element class to spy on
 * @param {Record<string, Property>} properties - Properties to spy
 * @returns {{ mockRestore(): void }} Object with restore method
 */
function spyElementPrototypes<T extends ElementClass>(
  elementClass: T,
  properties: Record<string, Property>
): { mockRestore(): void };

type ElementClass = Function;
type Property = PropertyDescriptor | Function;

spyElementPrototype

Spy on a single element prototype property for testing.

/**
 * Spy on single element prototype property
 * @param {ElementClass} Element - Element class to spy on
 * @param {string} propName - Property name to spy
 * @param {Property} property - Property descriptor or function
 * @returns {{ mockRestore(): void }} Object with restore method
 */
function spyElementPrototype(
  Element: ElementClass, 
  propName: string, 
  property: Property
): { mockRestore(): void };

Install with Tessl CLI

npx tessl i tessl/npm-rc-util

docs

core-utilities.md

development-styling.md

dom-utilities.md

index.md

react-components.md

react-hooks.md

tile.json