Options
All
  • Public
  • Public/Protected
  • All
Menu

Module @react-md/utils

Index

Namespaces

Enumerations

Interfaces

Type aliases

Variables

Functions

Type aliases

ActiveDescendantId: string
BlueBit: number
ClassNameCloneableChild<T>: ReactElement<T & { className?: string }>

A simple type that can be used for different components that clone a className into a child component.

Type parameters

  • T = {}

ContrastRatioCompliance: "large" | "normal" | "AAA"

The type of contrast ratio compliance to confirm to. The ratios in order are:

  • 3:1 for large text (18pt normal or 14pt bold)
  • 4.5:1 for normal text
  • 7:1 for Level AAA requirements.
see

https://www.w3.org/TR/WCAG20/#visual-audio-contrast

see

https://www.w3.org/TR/WCAG20/#larger-scaledef

DelegatedEventTarget: Window | Document | HTMLElement
DropzoneHanders<E>: DropzoneHandlers<E>
remarks

@since 2.9.0

deprecated

@since 5.1.3 Use DropzoneHandlers instead.

Type parameters

  • E: HTMLElement

DropzoneHandlers<E>: Pick<HTMLAttributes<E>, "onDragEnter" | "onDragOver" | "onDrop" | "onDragLeave">
remarks

@since 5.1.3

Type parameters

  • E: HTMLElement

DropzoneHookReturnValue<E>: [boolean, DropzoneHandlers<E>]
remarks

@since 2.9.0

Type parameters

  • E: HTMLElement

ElementFocusType: "tab" | "programmatic"

An element can be tab focused if it is:

  • an anchor or area with an href
  • a non-disabled input element that is not type="hidden"
  • a non-disabled button, textarea, or select element
  • an element with a tabIndex >= 0

An element can be noted as "programmatically focusable only" has the above rules, but the tabIndex will be set to -1.

remarks

@since 2.8.0

EnsuredRefs<E>: readonly [MutableRefObject<E | null>, RefCallback<E | null>]
remarks

@since 2.3.0

Type parameters

  • E: HTMLElement

FindMatchIndex: typeof findMatchIndex
Focus: "first" | "last" | string
FocusFallback: string | HTMLElement | (() => HTMLElement | null) | null | undefined

This can either be a query selector string, a specific HTMLElement, or a function that finds a specific HTMLElement to focus.

FocusType: "increment" | "decrement" | "first" | "last"

The type of focus that should be triggered from a keypress.

GetItemValue<T>: (item: T, valueKey: string) => string

Type parameters

  • T = unknown

Type declaration

    • (item: T, valueKey: string): string
    • A function that will get a string value from each item. The default implementation will:

      • return a number as a string
      • return a string as itself
      • return the result of item() if it is a function (this will also be used if the valueKey on an object is a function).
      • return item[valueKey] if it's an object (this uses typeof item === "object")
      • return the empty string for all other data types

      Parameters

      • item: T
      • valueKey: string

      Returns string

GreenBit: number
HexString: string
HorizontalPosition: "left" | "right" | "center" | "inner-left" | "inner-right"

Left:

  • the container left is in-line with the right of the element

Right:

  • the container right is in-line with the left of the element

Center:

  • the container's horizontal center point will be aligned with the element's horizontal center point

Inner Left:

  • the container's left is in-line with the left of the element

Inner Right:

  • the container's right is in-line with the right of the element
ItemRef<E>: MutableRefObject<E | null>

A mutable ref object that must be applied to each DOM node within the "focusable"/"searchable" list of elements so that custom focus behavior can be triggered.

Type parameters

  • E: HTMLElement

    the element type of each item within the focusable list.

ItemRefList<E>: readonly ItemRef<E>[]

Type parameters

  • E: HTMLElement = HTMLElement

KeyboardFocusElementLookup: NonNullRef<KeyboardFocusElementData[]>

This is a ref containing all the KeyboardFocusElementData that are being watched by the KeyboardMovementProvider. This is generally used to focus specific elements by index, attempt to find an element by search text, or any additional custom focus behavior.

remarks

@since 5.0.0

internal
KeyboardFocusHandler<E>: (arg: KeyboardFocusArg<E>) => void

Type parameters

  • E: HTMLElement

Type declaration

KeyboardMovementConfig: Required<KeyboardMovementConfiguration>

The defined KeyboardMovementConfiguration that should be used for custom keyboard focus behavior.

remarks

@since 5.0.0

KeyboardMovementProviders<CE, IE>: [ItemRefList<IE>, MovementHandler<CE>]

Returns an ordered list with two items:

  • itemRefs
  • onKeyDown event handler

Type parameters

  • CE: HTMLElement

    The HTMLElement type of the container element that handles the custom keyboard movement.

  • IE: HTMLElement

    The HTMLElement type of each item within the container element that can be focusable.

LabelRequiredForA11y<Props>: RequireAtLeastOne<Props, keyof LabelA11y>

A small accessibility helper to ensure that either aria-label or aria-labelledby have been provided to a component.

Type parameters

Maybe<T, NotFound>: T | NotFound

Type parameters

  • T

  • NotFound = null

MovementHandler<E>: React.KeyboardEventHandler<E>

Type parameters

  • E: HTMLElement

OnOutsideClick<E>: (element: E | null, target: HTMLElement | null, contains: Contains) => void

Type parameters

  • E: HTMLElement

Type declaration

    • (element: E | null, target: HTMLElement | null, contains: Contains): void
    • The on outside click handler that can be used to check for additional logic before triggering some action. This will be provided:

      • the current element or null
      • the current click target or null
      • a nice "safe" contains function that handles nulls

      Parameters

      • element: E | null
      • target: HTMLElement | null
      • contains: Contains

      Returns void

OnResizeObserverChange<E>: (resizeData: ResizeObserverElementData<E>) => void

Type parameters

  • E: HTMLElement = HTMLElement

Type declaration

PositionWidth: "auto" | "equal" | "min"

An optional configuration for calculating and setting the width of the element relative to the width of the container. When this value is set to "auto" (default), the width will be based on content width but still ensuring it can fit within the viewport. Setting this to "equal" will just apply the container's width to the fixed element. Finally, setting this to "min" will set the container's width as the minWidth for the fixed element so that it is at least the same width as the container.

If this is set to "equal" or "min" and the horizontal anchor is not set to "center", an error will be thrown.

defaultvalue

"auto"

PropsWithRef<P, E>: P & { ref?: Ref<E> }

A helper type that allows an optional ref to also be applied with a props object even though a ref isn't a real prop.

Type parameters

  • P: {}

  • E: HTMLElement

QuerySize: number | string
remarks

@since 2.7.0

RadioItem: string | RadioItemValueObject

The radio item value can be a simple string or an object containing a value attribute.

remarks

@since 2.7.0

RadioWidgetAttributes: Omit<HTMLAttributes<HTMLSpanElement>, "id" | "aria-checked" | "onChange" | "tabIndex">

Since the RadioWidget modifies the props a bit for the radio widget, these are the HTMLAttributes for the RadioWidget that can be overwritten.

remarks

@since 2.7.0

RedBit: number
RenderGridListChildren: (size: GridListSize) => ReactNode

Type declaration

    • The children render function that will be provided the current grid list size object and should return renderable elements.

      Note: The first time this is called, the columns and cellWidth will be the defaultSize. Once the GridList has been fully mounted in the DOM, it will begin the sizing calculations and update with the "real" values. This doesn't cause any problems if you are only rendering client side, but it might mess up server-side rendering, so it is recommended to update the defaultSize when server-side rendering if this can be "known" service-side in your app.

      Parameters

      Returns ReactNode

RequireAtLeastOne<T, Keys>: Pick<T, Exclude<keyof T, Keys>> & { [ K in Keys]-?: Required<Pick<T, K>> & Partial<Pick<T, Exclude<Keys, K>>> }[Keys]

This type allows you to require at least one of the provided keys. This is super helpful for things like aria-label or aria-labelledby when it's required for a11y.

see

https://stackoverflow.com/questions/40510611/typescript-interface-require-one-of-two-properties-to-exist/49725198#49725198

Type parameters

  • T

  • Keys: keyof T = keyof T

ResizeListenerProps: Omit<ResizeListenerOptions, "enabled">
ScrollListenerProps: Omit<ScrollListenerHookOptions, "enabled">
SearchChangeEvent<D, E>: (data: SearchData<D, E>) => void

Type parameters

  • D = unknown

  • E: HTMLElement = HTMLElement

Type declaration

SimplePosition: "above" | "below" | "left" | "right"

A "simple" version of all the positioning options. These are generally used across all of react-md as it'll use the "center" version of the opposite type when creating a fixed position.

ThrottleableFunction: (...args: any[]) => any

Type declaration

    • (...args: any[]): any
    • This is really the type definition for the Parameters type provided by TS, but created a type alias to help with documentation.

      Parameters

      • Rest ...args: any[]

      Returns any

ThrottledFunction<F>: (...args: Parameters<F>) => ReturnType<F>

Type parameters

Type declaration

    • (...args: Parameters<F>): ReturnType<F>
    • A strongly typed throttled version of a throttleable function.

      Parameters

      • Rest ...args: Parameters<F>

      Returns ReturnType<F>

UseGridListReturnValue<E>: readonly [ProvidedGridListProps<E>, GridListSize]

Type parameters

  • E: HTMLElement

UserInteractionMode: "keyboard" | "mouse" | "touch"

This is the current mode for how your user is interacting with your app. This will be used to determine which type of state styles should be applied at the time of interacting with an element on your page.

VerticalPosition: "above" | "below" | "center" | "top" | "bottom"

Above:

  • the container top is in-line with the bottom of the element.

Below:

  • the container bottom is in-line with the top of the element

Center:

  • the container center is in-line with the top of the element

Top:

  • the container top is in-line with the top of the element

Bottom:

  • the container bottom is in-line with the bottom of the element
WritingDirection: "ltr" | "rtl"

Note: unlike the dir DOM attribute, the "auto" value is not supported

remarks

@since 2.3.0

Variables

AAA_CONTRAST_RATIO: 7 = 7

The AAA contrast ratio for passing WGAC 2.0 color contrast ratios.

ABOVE_CENTER_ANCHOR: PositionAnchor = ...
ABOVE_INNER_LEFT_ANCHOR: PositionAnchor = ...
ABOVE_INNER_RIGHT_ANCHOR: PositionAnchor = ...
ABOVE_LEFT_ANCHOR: PositionAnchor = ...
ABOVE_RIGHT_ANCHOR: PositionAnchor = ...
ActiveDescendantContextProvider: Provider<ActiveDescendantContext>
AppSizeContext: Context<AppSize & { __initialized: boolean }> = ...
internal
BELOW_CENTER_ANCHOR: PositionAnchor = ...
BELOW_INNER_LEFT_ANCHOR: PositionAnchor = ...
BELOW_INNER_RIGHT_ANCHOR: PositionAnchor = ...
BELOW_LEFT_ANCHOR: PositionAnchor = ...
BELOW_RIGHT_ANCHOR: PositionAnchor = ...
BOTTOM_CENTER_ANCHOR: PositionAnchor = ...
BOTTOM_INNER_LEFT_ANCHOR: PositionAnchor = ...
BOTTOM_INNER_RIGHT_ANCHOR: PositionAnchor = ...
BOTTOM_LEFT_ANCHOR: PositionAnchor = ...
BOTTOM_RIGHT_ANCHOR: PositionAnchor = ...
CELL_MARGIN_VAR: "--rmd-cell-margin" = "--rmd-cell-margin"

This is the css variable that is used store the current margin of each cell.

CELL_SIZE_VAR: "--rmd-cell-size" = "--rmd-cell-size"

This is the css variable that is used store the current size of each cell.

CENTER_CENTER_ANCHOR: PositionAnchor = ...
CENTER_INNER_LEFT_ANCHOR: PositionAnchor = ...
CENTER_INNER_RIGHT_ANCHOR: PositionAnchor = ...
CENTER_LEFT_ANCHOR: PositionAnchor = ...
CENTER_RIGHT_ANCHOR: PositionAnchor = ...
DATA_RMD_NOSCROLL: "data-rmd-noscroll" = "data-rmd-noscroll"

This is used with the useScrollLock effect to determine if the styles were applied by scroll locking or not in the cleanup stage.

DEFAULT_APP_SIZE: AppSize = ...
DEFAULT_DESKTOP_LARGE_MIN_WIDTH: QuerySize = ...
DEFAULT_DESKTOP_MIN_WIDTH: QuerySize = ...
DEFAULT_GRID_LIST_MAX_CELL_SIZE: 150 = 150
remarks

@since 2.3.0

DEFAULT_GRID_LIST_PADDING: 16 = 16
remarks

@since 2.3.0

DEFAULT_HOVER_MODE_DEACTIVATION_TIME: 1000 = 1000

The amount of time the user must no longer hover any element attached to the HoverModeProvider to disable the hover mode.

remarks

@since 2.8.0

DEFAULT_HOVER_MODE_EXIT_TIME: 300 = 300

The amount of time the user must not hover any element attached to the same instance of the useHoverMode hook when the using the sticky mode.

remarks

@since 5.0.0 This was named the DEFAULT_HOVER_MODE_STICKY_EXIT_TIME before.

DEFAULT_HOVER_MODE_VISIBLE_IN_TIME: 1000 = 1000

The amount of time a user must hover an element before the temporary element becomes visible.

remarks

@since 2.8.0

DEFAULT_IGNORE_WHITESPACE: false = false
DEFAULT_KEYBOARD_MOVEMENT: Readonly<KeyboardMovementConfig> = ...

Most custom keyboard functionality use these keys.

remarks

@since 5.0.0

internal
DEFAULT_LTR_KEYBOARD_MOVEMENT: Readonly<KeyboardMovementConfig> = ...
remarks

@since 5.1.2

internal
DEFAULT_PHONE_MAX_WIDTH: QuerySize = ...
DEFAULT_RTL_KEYBOARD_MOVEMENT: Readonly<KeyboardMovementConfig> = ...
remarks

@since 5.1.2

internal
DEFAULT_SEARCH_OPTIONS: Required<SearchOptions> = ...
DEFAULT_SEARCH_RESET_TIME: 500 = 500
DEFAULT_TABLET_MAX_WIDTH: QuerySize = ...
DEFAULT_TABLET_MIN_WIDTH: QuerySize = ...
DEFAULT_TRIM: true = true
DEFAULT_VALUE_KEY: "value" = "value"
FOCUSABLE_ELEMENTS: string[] = ...
FocusContainer: ForwardRefExoticComponent<FocusContainerProps & RefAttributes<HTMLDivElement>> = ...

The FocusContainer is a wrapper for a few of the accessibility hooks to maintain focus within an element.

GRID_COLUMNS_VAR: "--rmd-grid-cols" = "--rmd-grid-cols"

This CSS Variable allows you to override the number of columns that should be displayed in the grid. This is automatically updated with media queries with the default grid implementation, but is used here to add additional inline-style overrides.

internal
GRID_GUTTER_VAR: "--rmd-grid-gutter" = "--rmd-grid-gutter"

This CSS Variable allows you to override the gutter (grid-gap) between each cell in the grid.

internal
Grid: ForwardRefExoticComponent<GridProps & RefAttributes<HTMLDivElement>> = ...

The grid component is generally used for a base layout in your app to provide nice padding and spacing between each item.

Note: This component relies on the AppSizeListener as a parent component to work and will throw an error if it does not exist as a parent.

GridCell: ForwardRefExoticComponent<GridCellProps & RefAttributes<HTMLDivElement>> = ...
GridList: ForwardRefExoticComponent<GridListProps & RefAttributes<HTMLDivElement>> = ...

The GridList component is a different way to render a list of data where the number of columns is dynamic and based on the max-width for each cell. Instead of setting a percentage width to each cell based on the number of columns, this will dynamically add columns to fill up the remaining space and have each cell grow up to a set max-width. A really good use-case for this is displaying a list of images or thumbnails and allowing the user to see a full screen preview once selected/clicked.

GridListCell: ForwardRefExoticComponent<GridListCellProps & RefAttributes<HTMLDivElement>> = ...
GridListSizeProvider: Provider<GridListSize>
HoverModeContextProvider: Provider<HoverModeContext>
KeyboardMovementContextProvider: Provider<KeyboardFocusContext>
LARGE_TEXT_CONTRAST_RATIO: 3 = 3

The contrast ratio that can be used for large text where large text is considered 18pt or 14pt bold.

NORMAL_TEXT_CONTRAST_RATIO: 4.5 = 4.5

The contrast ratio that can be used for normal text.

PROGRAMATICALLY_FOCUSABLE: string = ...

A query selector to find elements that are programmatically focusable.

Example:

const focusableElements = document.querySelectorAll(PROGRAMATICALLY_FOCUSABLE);
// do something with elements
RadioGroup: ForwardRefExoticComponent<(Pick<BaseRadioGroupProps, "className" | "children" | "id" | "defaultChecked" | "defaultValue" | "suppressContentEditableWarning" | "suppressHydrationWarning" | "accessKey" | "contentEditable" | "contextMenu" | "dir" | "draggable" | "hidden" | "lang" | "placeholder" | "slot" | "spellCheck" | "style" | "tabIndex" | "title" | "translate" | "radioGroup" | "role" | "about" | "datatype" | "inlist" | "prefix" | "property" | "resource" | "typeof" | "vocab" | "autoCapitalize" | "autoCorrect" | "autoSave" | "color" | "itemProp" | "itemScope" | "itemType" | "itemID" | "itemRef" | "results" | "security" | "unselectable" | "inputMode" | "is" | "aria-activedescendant" | "aria-atomic" | "aria-autocomplete" | "aria-busy" | "aria-checked" | "aria-colcount" | "aria-colindex" | "aria-colspan" | "aria-controls" | "aria-current" | "aria-describedby" | "aria-details" | "aria-disabled" | "aria-dropeffect" | "aria-errormessage" | "aria-expanded" | "aria-flowto" | "aria-grabbed" | "aria-haspopup" | "aria-hidden" | "aria-invalid" | "aria-keyshortcuts" | "aria-level" | "aria-live" | "aria-modal" | "aria-multiline" | "aria-multiselectable" | "aria-orientation" | "aria-owns" | "aria-placeholder" | "aria-posinset" | "aria-pressed" | "aria-readonly" | "aria-relevant" | "aria-required" | "aria-roledescription" | "aria-rowcount" | "aria-rowindex" | "aria-rowspan" | "aria-selected" | "aria-setsize" | "aria-sort" | "aria-valuemax" | "aria-valuemin" | "aria-valuenow" | "aria-valuetext" | "dangerouslySetInnerHTML" | "onCopy" | "onCopyCapture" | "onCut" | "onCutCapture" | "onPaste" | "onPasteCapture" | "onCompositionEnd" | "onCompositionEndCapture" | "onCompositionStart" | "onCompositionStartCapture" | "onCompositionUpdate" | "onCompositionUpdateCapture" | "onFocus" | "onFocusCapture" | "onBlur" | "onBlurCapture" | "onChange" | "onChangeCapture" | "onBeforeInput" | "onBeforeInputCapture" | "onInput" | "onInputCapture" | "onReset" | "onResetCapture" | "onSubmit" | "onSubmitCapture" | "onInvalid" | "onInvalidCapture" | "onLoad" | "onLoadCapture" | "onError" | "onErrorCapture" | "onKeyDown" | "onKeyDownCapture" | "onKeyPress" | "onKeyPressCapture" | "onKeyUp" | "onKeyUpCapture" | "onAbort" | "onAbortCapture" | "onCanPlay" | "onCanPlayCapture" | "onCanPlayThrough" | "onCanPlayThroughCapture" | "onDurationChange" | "onDurationChangeCapture" | "onEmptied" | "onEmptiedCapture" | "onEncrypted" | "onEncryptedCapture" | "onEnded" | "onEndedCapture" | "onLoadedData" | "onLoadedDataCapture" | "onLoadedMetadata" | "onLoadedMetadataCapture" | "onLoadStart" | "onLoadStartCapture" | "onPause" | "onPauseCapture" | "onPlay" | "onPlayCapture" | "onPlaying" | "onPlayingCapture" | "onProgress" | "onProgressCapture" | "onRateChange" | "onRateChangeCapture" | "onSeeked" | "onSeekedCapture" | "onSeeking" | "onSeekingCapture" | "onStalled" | "onStalledCapture" | "onSuspend" | "onSuspendCapture" | "onTimeUpdate" | "onTimeUpdateCapture" | "onVolumeChange" | "onVolumeChangeCapture" | "onWaiting" | "onWaitingCapture" | "onAuxClick" | "onAuxClickCapture" | "onClick" | "onClickCapture" | "onContextMenu" | "onContextMenuCapture" | "onDoubleClick" | "onDoubleClickCapture" | "onDrag" | "onDragCapture" | "onDragEnd" | "onDragEndCapture" | "onDragEnter" | "onDragEnterCapture" | "onDragExit" | "onDragExitCapture" | "onDragLeave" | "onDragLeaveCapture" | "onDragOver" | "onDragOverCapture" | "onDragStart" | "onDragStartCapture" | "onDrop" | "onDropCapture" | "onMouseDown" | "onMouseDownCapture" | "onMouseEnter" | "onMouseLeave" | "onMouseMove" | "onMouseMoveCapture" | "onMouseOut" | "onMouseOutCapture" | "onMouseOver" | "onMouseOverCapture" | "onMouseUp" | "onMouseUpCapture" | "onSelect" | "onSelectCapture" | "onTouchCancel" | "onTouchCancelCapture" | "onTouchEnd" | "onTouchEndCapture" | "onTouchMove" | "onTouchMoveCapture" | "onTouchStart" | "onTouchStartCapture" | "onPointerDown" | "onPointerDownCapture" | "onPointerMove" | "onPointerMoveCapture" | "onPointerUp" | "onPointerUpCapture" | "onPointerCancel" | "onPointerCancelCapture" | "onPointerEnter" | "onPointerEnterCapture" | "onPointerLeave" | "onPointerLeaveCapture" | "onPointerOver" | "onPointerOverCapture" | "onPointerOut" | "onPointerOutCapture" | "onGotPointerCapture" | "onGotPointerCaptureCapture" | "onLostPointerCapture" | "onLostPointerCaptureCapture" | "onScroll" | "onScrollCapture" | "onWheel" | "onWheelCapture" | "onAnimationStart" | "onAnimationStartCapture" | "onAnimationEnd" | "onAnimationEndCapture" | "onAnimationIteration" | "onAnimationIterationCapture" | "onTransitionEnd" | "onTransitionEndCapture" | "value" | "items" | "getRadioStyle" | "getRadioClassName"> & Required<Pick<BaseRadioGroupProps, "aria-label">> & Partial<Pick<BaseRadioGroupProps, "aria-labelledby">> & RefAttributes<HTMLSpanElement>) & (Pick<BaseRadioGroupProps, "className" | "children" | "id" | "defaultChecked" | "defaultValue" | "suppressContentEditableWarning" | "suppressHydrationWarning" | "accessKey" | "contentEditable" | "contextMenu" | "dir" | "draggable" | "hidden" | "lang" | "placeholder" | "slot" | "spellCheck" | "style" | "tabIndex" | "title" | "translate" | "radioGroup" | "role" | "about" | "datatype" | "inlist" | "prefix" | "property" | "resource" | "typeof" | "vocab" | "autoCapitalize" | "autoCorrect" | "autoSave" | "color" | "itemProp" | "itemScope" | "itemType" | "itemID" | "itemRef" | "results" | "security" | "unselectable" | "inputMode" | "is" | "aria-activedescendant" | "aria-atomic" | "aria-autocomplete" | "aria-busy" | "aria-checked" | "aria-colcount" | "aria-colindex" | "aria-colspan" | "aria-controls" | "aria-current" | "aria-describedby" | "aria-details" | "aria-disabled" | "aria-dropeffect" | "aria-errormessage" | "aria-expanded" | "aria-flowto" | "aria-grabbed" | "aria-haspopup" | "aria-hidden" | "aria-invalid" | "aria-keyshortcuts" | "aria-level" | "aria-live" | "aria-modal" | "aria-multiline" | "aria-multiselectable" | "aria-orientation" | "aria-owns" | "aria-placeholder" | "aria-posinset" | "aria-pressed" | "aria-readonly" | "aria-relevant" | "aria-required" | "aria-roledescription" | "aria-rowcount" | "aria-rowindex" | "aria-rowspan" | "aria-selected" | "aria-setsize" | "aria-sort" | "aria-valuemax" | "aria-valuemin" | "aria-valuenow" | "aria-valuetext" | "dangerouslySetInnerHTML" | "onCopy" | "onCopyCapture" | "onCut" | "onCutCapture" | "onPaste" | "onPasteCapture" | "onCompositionEnd" | "onCompositionEndCapture" | "onCompositionStart" | "onCompositionStartCapture" | "onCompositionUpdate" | "onCompositionUpdateCapture" | "onFocus" | "onFocusCapture" | "onBlur" | "onBlurCapture" | "onChange" | "onChangeCapture" | "onBeforeInput" | "onBeforeInputCapture" | "onInput" | "onInputCapture" | "onReset" | "onResetCapture" | "onSubmit" | "onSubmitCapture" | "onInvalid" | "onInvalidCapture" | "onLoad" | "onLoadCapture" | "onError" | "onErrorCapture" | "onKeyDown" | "onKeyDownCapture" | "onKeyPress" | "onKeyPressCapture" | "onKeyUp" | "onKeyUpCapture" | "onAbort" | "onAbortCapture" | "onCanPlay" | "onCanPlayCapture" | "onCanPlayThrough" | "onCanPlayThroughCapture" | "onDurationChange" | "onDurationChangeCapture" | "onEmptied" | "onEmptiedCapture" | "onEncrypted" | "onEncryptedCapture" | "onEnded" | "onEndedCapture" | "onLoadedData" | "onLoadedDataCapture" | "onLoadedMetadata" | "onLoadedMetadataCapture" | "onLoadStart" | "onLoadStartCapture" | "onPause" | "onPauseCapture" | "onPlay" | "onPlayCapture" | "onPlaying" | "onPlayingCapture" | "onProgress" | "onProgressCapture" | "onRateChange" | "onRateChangeCapture" | "onSeeked" | "onSeekedCapture" | "onSeeking" | "onSeekingCapture" | "onStalled" | "onStalledCapture" | "onSuspend" | "onSuspendCapture" | "onTimeUpdate" | "onTimeUpdateCapture" | "onVolumeChange" | "onVolumeChangeCapture" | "onWaiting" | "onWaitingCapture" | "onAuxClick" | "onAuxClickCapture" | "onClick" | "onClickCapture" | "onContextMenu" | "onContextMenuCapture" | "onDoubleClick" | "onDoubleClickCapture" | "onDrag" | "onDragCapture" | "onDragEnd" | "onDragEndCapture" | "onDragEnter" | "onDragEnterCapture" | "onDragExit" | "onDragExitCapture" | "onDragLeave" | "onDragLeaveCapture" | "onDragOver" | "onDragOverCapture" | "onDragStart" | "onDragStartCapture" | "onDrop" | "onDropCapture" | "onMouseDown" | "onMouseDownCapture" | "onMouseEnter" | "onMouseLeave" | "onMouseMove" | "onMouseMoveCapture" | "onMouseOut" | "onMouseOutCapture" | "onMouseOver" | "onMouseOverCapture" | "onMouseUp" | "onMouseUpCapture" | "onSelect" | "onSelectCapture" | "onTouchCancel" | "onTouchCancelCapture" | "onTouchEnd" | "onTouchEndCapture" | "onTouchMove" | "onTouchMoveCapture" | "onTouchStart" | "onTouchStartCapture" | "onPointerDown" | "onPointerDownCapture" | "onPointerMove" | "onPointerMoveCapture" | "onPointerUp" | "onPointerUpCapture" | "onPointerCancel" | "onPointerCancelCapture" | "onPointerEnter" | "onPointerEnterCapture" | "onPointerLeave" | "onPointerLeaveCapture" | "onPointerOver" | "onPointerOverCapture" | "onPointerOut" | "onPointerOutCapture" | "onGotPointerCapture" | "onGotPointerCaptureCapture" | "onLostPointerCapture" | "onLostPointerCaptureCapture" | "onScroll" | "onScrollCapture" | "onWheel" | "onWheelCapture" | "onAnimationStart" | "onAnimationStartCapture" | "onAnimationEnd" | "onAnimationEndCapture" | "onAnimationIteration" | "onAnimationIterationCapture" | "onTransitionEnd" | "onTransitionEndCapture" | "value" | "items" | "getRadioStyle" | "getRadioClassName"> & Required<Pick<BaseRadioGroupProps, "aria-labelledby">> & Partial<Pick<BaseRadioGroupProps, "aria-label">> & RefAttributes<HTMLSpanElement>)> = ...

The RadioGroup is a low-level component that does not provide any styles and instead only provides the accessibility required for a role="radiogroup" and rendering each role="radio" item.

remarks

@since 2.7.0

RadioWidget: ForwardRefExoticComponent<RadioWidgetProps & RefAttributes<HTMLSpanElement>> = ...

This component offers no styles and probably shouldn't be used externally since it is just rendered by the RadioGroup component.

remarks

@since 2.7.0

TAB_FOCUSABLE: string = ...

A query selector to find elements that are focusable only with tab and shift+tab.

Example:

const focusableElements = document.querySelectorAll(TAB_FOCUSABLE);
// do something with elements
TOP_CENTER_ANCHOR: PositionAnchor = ...
TOP_INNER_LEFT_ANCHOR: PositionAnchor = ...
TOP_INNER_RIGHT_ANCHOR: PositionAnchor = ...
TOP_LEFT_ANCHOR: PositionAnchor = ...
TOP_RIGHT_ANCHOR: PositionAnchor = ...

Functions

  • This component should be used with the KeyboardMovementProvider component to implement custom keyboard focusable behavior using aria-activedescendant.

    example

    Base Example

    function Descendant({ id, children, ...props }: HTMLAttributes<HTMLDivElement>): ReactElement {
    const { ref, active } = useActiveDescendant({ id });
    return (
    <div
    {...props}
    id={id}
    ref={ref}
    role="option"
    tabIndex={-1}
    className={active ? "active" : undefined}
    >
    {children}
    </div>
    );
    }

    function CustomFocus(): ReactElement {
    const { providerProps, focusIndex, ...containerProps } =
    useActiveDescendantFocus()

    return (
    <ActiveDescendantMovementProvider>
    <div
    {...containerProps}
    id="some-unique-id"
    role="listbox"
    tabIndex={0}
    >
    <Descendant id="some-descendant-id">
    Some Option
    </Descendant>
    </div>
    </ActiveDescendantMovementProvider>
    );
    }

    function Example() {
    return (
    <KeyboardMovementProvider loopable searchable>
    <CustomFocus />
    </KeyboardMovementProvider>
    );
    }
    see

    https://www.w3.org/TR/wai-aria-practices/#kbd_focus_activedescendant

    internal
    remarks

    @since 5.0.0

    Parameters

    Returns ReactElement

  • DEFAULT_GET_ITEM_VALUE(item: unknown, valueKey?: string): string
  • Dir(__namedParameters: DirProps): ReactElement
  • The Dir component is used to handle the current writing direction within your app as well as conditionally updating the writing direction for small sections in your app. When this component is used for the first time near the root of your React component tree, the current direction will be applied to the root <html> element. Otherwise the current dir will be cloned into the child element so it can be passed as a prop.

    // html element will be updated to have `dir="ltr"`
    ReactDOM.render(<Dir><App /></Dir>, root)
    // html element will be updated to have `dir="rtl"` while the `<span>` will
    // now be `<span dir="ltr">`
    ReactDOM.render(
    <Dir defaultDir="rtl">
    <Some>
    <Other>
    <Components>
    <Dir defaultDir="ltr">
    <span>Content</span>
    </Dir>
    </Components>
    </Other>
    </Some>
    </Dir>,
    root
    );

    Note: Since the dir is cloned into the child element, you need to make sure that the child is either a DOM element or the dir prop is passed from your custom component.

    remarks

    @since 2.3.0

    Parameters

    Returns ReactElement

  • This component should normally be mounted near the root of your app to enable hover mode for child components. However, it can also be used at other levels if hover mode functionality should not carry over between two different parts of the screen.

    example

    Separating Hover Mode

    export default function Example(): ReactElement {
    return (
    <>
    <HoverModeProvider>
    <HeaderActions />
    </HoverModeProvider>
    <HoverModeProvider>
    <MainContent />
    </HoverModeProvider>
    </>
    );
    }
    remarks

    @since 2.8.0

    Parameters

    Returns ReactElement

  • example

    Main Usage

    function Example() {
    return (
    <KeyboardMovementProvider>
    <CustomKeyboardFocusWidget />
    </KeyboardMovementProvider>
    );
    }

    function CustomKeyboardFocusWidget() {
    const { focusIndex: _focusIndex, ...eventHandlers } = useKeyboardFocus();
    return (
    <div {...eventHandlers}>
    <FocusableChild />
    <FocusableChild />
    <FocusableChild />
    <FocusableChild />
    </div>
    );
    }

    function FocusableChild() {
    const refCallback = useKeyboardFocusableElement()

    return <div role="menuitem" tabIndex={-1} ref={refCallback}>Content</div>;
    }
    remarks

    @since 5.0.0

    Parameters

    Returns ReactElement

  • A simple component that will render the children only when the app is considered in mobile mode via the AppSizeContext. A mobile view will be true for both phones and tablets.

    Parameters

    Returns ReactElement | null

  • This is a simple component that will attach a throttled resize event listener when mounted, and detach when it unmounts.

    This component only works for entire app resize events. If you are looking for specific element resize events, check out the ResizeObserver component instead.

    Parameters

    Returns null

  • This component is used to determine how the user is current interacting with your app as well as modifying the document.body's className with the current mode. This is what allows the rmd-utils-phone-only, rmd-utils-keyboard-only, and rmd-utils-mouse-only mixins to work.

    remarks

    @since 2.6.0 Renamed from InteractionModeListener

    throws

    When this component has been mounted multiple times in your app.

    Parameters

    Returns ReactElement

  • applyRef<E>(instance: null | E, ref?: Ref<E>): void
  • A small utility function that allows me to apply a passed in ref along with my own custom ref logic.

    Type parameters

    • E

    Parameters

    • instance: null | E

      The DOM Node instance

    • Optional ref: Ref<E>

      The prop ref

    Returns void

  • bem(base: string): BEMResult
  • caseInsensitiveFilter<T>(query: string, searchable: readonly T[], options?: CaseInsensitiveOptions<T>): readonly T[]
  • Filters a list by ensuring that all items contain the query string in order anywhere in it's own value.

    Type parameters

    • T = unknown

    Parameters

    • query: string

      The current query string

    • searchable: readonly T[]

      The list of searchable items that should be filtered

    • options: CaseInsensitiveOptions<T> = {}

      All the search options to use

    Returns readonly T[]

    A filtered list of all the searchable items based on the query string.

  • containsElement(container: CheckableThing, child: CheckableThing): boolean
  • Checks if a container element contains another element as a child while allowing for nulls or a MutableRefObject of HTMLElement or null. Mostly just a convenience function that should be used internally.

    internal

    Parameters

    • container: CheckableThing

      The element to use as a container element. This can be an HTMLElement, null, or a MutableRefObject of HTMLElement or null.

    • child: CheckableThing

      The element that might be a child of the container element. This can be an HTMLElement, null, or a MutableRefObject of HTMLElement or null.

    Returns boolean

    True if the container contains the child element and both the container and child are valid HTMLElements (not null).

  • defaults<O, R>(optional: O, required: R): O & R
  • This is normally used for reusable shareable configs that have multiple shared options with default values that should be used. This basically works just like defaultProps in react.

    internal

    Type parameters

    • O: {}

    • R: {}

    Parameters

    • optional: O

      The original object that has the optional/omitted values

    • required: R

      The required default values that should be used to fill the optional object with

    Returns O & R

    a new object with both the values of the optional and required objects but use the optional values if they were defined.

  • Creates a delegated event listener using custom events. Most of this code comes from the MDN about resize listeners.

    This will return an object for adding or removing event handlers for the provided eventType since only one base throttled event listener will be created. Each callback that is added will be called with the event each time the event is triggered. This does mean that you will manually need to remove your callback like normal or else it can be called when no longer in use. This also means that it doesn't "hurt" to call this function without immediately calling the add function since the event won't start until there is at least 1 callback.

    see

    https://developer.mozilla.org/en-US/docs/Web/Events/resize#Examples

    Parameters

    • eventType: string

      One of the event types that should be used to create a delegated event for. This should be things like resize, click, scroll, etc.

    • eventTarget: DelegatedEventTarget = window

      The target that should have the delegated event handler attached to. This is normally the window, but can be any element as needed.

    • throttle: boolean = ...

      Boolean if the event should be throttled or not. Normally only event types like resize or scroll should be throttled for performance boosts, but anything can be.

    • Optional options: boolean | AddEventListenerOptions

    Returns DelegatedEventHandler

    The delegated event handler that allows you to add or remove EventListeners to that event.

  • disableScrollLock(element: HTMLElement): void
  • Attempts to disable the scroll locking behavior for an element. If the element does not have data-rmd-noscroll, it will not be modified. This is really just a safety catch to ensure that pre-existing styles aren't removed on accident.

    If the data-rmd-noscroll attribute exists, overflow style and the data-rmd-noscroll attribute will be removed.

    internal
    remarks

    @since 5.0.0 Renamed from disable to disableScrollLock.

    Parameters

    • element: HTMLElement

      Either the <body> tag or an element within the page to disable scroll locking for.

    Returns void

  • enableScrollLock(element: HTMLElement): void
  • This will enable scroll locking for the provided element. Scroll locking works by fixing the element within the page and hiding overflow for that element.

    internal
    remarks

    @since 5.0.0 Renamed from enable to enableScrollLock.

    Parameters

    • element: HTMLElement

      Either the <body> tag or an element within the page to disable scroll for.

    Returns void

  • extractTextContent(stringOrElement: string | HTMLElement, fontIconQuerySelector?: string): string
  • The default function used to extract the text from nodes. This will just return the textContent by default unless the node has a react-md FontIcon as a child. If there is a FontIcon child, the node will be cloned without the FontIcon to return the textContent instead. This is because the FontIcon's text content would also be returned from the node's text content.

    Parameters

    • stringOrElement: string | HTMLElement

      Either a string or an element element to convert

    • fontIconQuerySelector: string = ".rmd-icon--font"

      A string to use for finding font icons in the HTML Element. When this is set to the empty string, the element will not be checked for font icons which might be a slight performance boost if you are guaranteed to not use font icons

    Returns string

  • findIgnoreCase<T>(query: string, searchable: readonly T[], options?: SearchOptions<T>): T | null
  • This is a simple array.find implementation that will work for any searchable item type and return the first item that starts with the current query string ignoring case.

    Type parameters

    • T = unknown

    Parameters

    • query: string

      The current query string to use to match with

    • searchable: readonly T[]

      The list of searchable items

    • options: SearchOptions<T> = {}

      The additional search options available.

    Returns T | null

    the found item in the searchable list or null

  • findMatchInRange(value: string, values: readonly string[], startIndex: number, endIndex: number): number
  • Attempts to find the first match index for a list of values that starts with the provided query string and is within the start and end indexes. If no matches are found, -1 will be returned instead.

    Since this is normally coming from a keydown event, the query must be a string of all capital letters to work as each value will be converted to uppercase before checking.

    internal

    Parameters

    • value: string

      The current query string to find within the values

    • values: readonly string[]

      The list of values to search within

    • startIndex: number

      The start index for the search

    • endIndex: number

      The end index for the search

    Returns number

  • findMatchIndex(value: string, values: readonly string[], startIndex: number, isSelfMatchable?: boolean): number
  • A function that is used to find the next match index within a list of values by comparing the start values ignoring case.

    If a match can not be found from the search string, -1 will be returned. The search value is self-matchable by default, but it can be omitted by disabling the isSelfMatchable argument. This will make a self-match return -1.

    internal

    Parameters

    • value: string

      The current search value

    • values: readonly string[]

      A list of values to search within

    • startIndex: number

      The index within the values list to start the search from

    • isSelfMatchable: boolean = true

      Boolean if the current index can be included in the search

    Returns number

  • findSizingContainer(el: null | HTMLElement): HTMLElement | null
  • Attempts to find a sizing container based on the provided HTMLElement. By default, the sizing element will just be the provided element unless:

    • the item has a known role within react-md that can target known classes
    • the item has a data-sizing-selector attribute that is a valid query selector for the nested item.

    NOTE: The data-sizing-selector will be run from the current element instead of the document.

    throws

    This error will be thrown if using the data-query-selector and the query selector does not return an element on the page.

    Parameters

    • el: null | HTMLElement

      The element to find a sizing container for.

    Returns HTMLElement | null

    the sizing container relative to the provided element, or null if none could be found.

  • focusElementWithin(container: HTMLElement | Document, focus: string, programmatic?: boolean, preventScroll?: boolean, elements?: readonly HTMLElement[]): void
  • A function that is used to focus an element within the provided node. This can either focus the first, last, or a querySelector found element.

    remarks

    @since 2.8.0 Supports focusing the container element if it is focusable

    Parameters

    • container: HTMLElement | Document

      Either an HTMLElement or the document to focus an element within.

    • focus: string

      Either the "first" or "last" string to focus the first or last focusable element within the container or a query selector string to find a focusable element within the container.

    • programmatic: boolean = false

      Boolean if programmatically focusable elements should be included as well.

    • preventScroll: boolean = false

      Boolean if the focus event should not scroll the element into view. This should normally remain false, but can be useful if the element gets focused while offscreen during a transition.

    • Optional elements: readonly HTMLElement[]

      Optional child elements to search

    Returns void

  • fuzzyFilter<T>(query: string, searchable: readonly T[], options?: SearchOptions<T>): readonly T[]
  • Filters a list by using a fuzzy search "algorithm" (huge double quotes on algorithm). The fuzzy search will just ensure that all the letters in the query string appear in-order for all the remaining items. However, the letters do not need to be consecutive.

    Type parameters

    • T = unknown

    Parameters

    • query: string

      The current query string

    • searchable: readonly T[]

      The list of searchable items that should be filtered

    • options: SearchOptions<T> = {}

      All the search options to use

    Returns readonly T[]

    A filtered list of all the searchable items based on the query string.

  • getContrastRatio(background: string, foreground: string): number
  • getElement<E>(element: null | E | MutableRefObject<null | E>): E | null
  • Gets the HTMLElement or null from a provided RefObject or HTMLElement/null

    internal

    Type parameters

    • E: HTMLElement

    Parameters

    • element: null | E | MutableRefObject<null | E>

    Returns E | null

  • getElementRect(element: HTMLElement, coords?: Coords): DOMRect
  • This util is used to get the "true" element.getBoundingClientRect() that ensures that transitions using transforms don't mess up the sizing so that position calculations are easier to do.

    internal

    Parameters

    • element: HTMLElement

      The element to get a rect for.

    • coords: Coords = {}

      An optional object of coordinates to apply to the positioning styles. This should be used when the coords might resize the element since it needs to try to fit within the viewport.

    Returns DOMRect

    either a DOMRect for the element

  • One of the most complicated functions in this project that will attempt to position an element relative to another container element while still being visible within the viewport. Below is the logical flow for attempting to fix the element to the container:

    No Container: If there is no container element, return the provided x and y positions and no styles since there's nothing we can use to calculate the position.

    No Element: If the container was provided but the element to position does not exist, return an style object containing the left and top values for the container and apply as many of the positioning options as possible so that the styles are "as close as possible" before the fixed element is added to the DOM. This will also return the provided x and y positions since nothing could be swapped around yet.

    Container and Element: If both the container and fixed element were provided, apply all the positioning options to the left and top values of the container based on the sizes of both elements.

    Now that the left and top values were applied, check to see if the element is fully visible within the viewport with the provided positioning options. If it is fully visible, do nothing else. If it isn't... follow the next flow:

    First, check the horizontal sizes and make sure that the element is still within the viewport with the provided view width margin. If it isn't, first try to swap only to a right style instead of left to see if that fixes it, otherwise keep both the left and right styles.

    Parameters

    Returns FixedPosition

  • getFocusableElements(container: HTMLElement | Document, programatic?: boolean): readonly HTMLElement[]
  • A simple util that will find all the tab focusable elements within a container element. The container should normally be a specific HTMLElement, but it can also be the entire document if you want to find all focusable elements within your page.

    Parameters

    • container: HTMLElement | Document

      The container element/document to find focusable elements within.

    • programatic: boolean = false

      Boolean if programatically focusable elements should be included instead of only tab focusable.

    Returns readonly HTMLElement[]

    A list of HTMLElements that are focusable within the container.

  • getFuzzyRegExp(query: string): RegExp
  • Creates an "amazing" regular expression that matches the letters in order and escapes any letters that could be part of a regex. This should normally be used in fuzzy filters or determining fuzzy matches.

    Parameters

    • query: string

      The query string to convert into a "fuzzy" regular expression

    Returns RegExp

    The "fuzzy" regular expression that can be used to determine matches.

  • getItemId(id: string, i: number): string
  • An extremely simple function that is used to generate an id for an item within a list of other items. This is generally used with list of items that should have custom focus with the aria-activedescendant flow instead of native focus.

    Parameters

    • id: string

      The base id for the container element of all the items.

    • i: number

      The index of the item within the list. This number will be incremented by 1 as an id to start from 1 instead of 0.

    Returns string

  • getItemValue(item: unknown, valueKey?: string): string
  • The default implementation of the getItemValue search option that will attempt to "stringify" any unknown item as a string.

    internal

    Parameters

    • item: unknown

      The current item to transform

    • valueKey: string = "value"

      The key to use that should hold the value if the item is an object

    Returns string

    the item as a string

  • getOrientationType(): OrientationType
  • Gets the current percentage based on the min, max, and current value.

    internal
    remarks

    @since 4.0.1 uses an object for options instead of multiple arguments.

    Parameters

    Returns number

    the percentage that the value is between the min and max values.

  • getSearchString(value: string, lowercase?: boolean, trim?: boolean, ignoreWhitespace?: boolean): string
  • This is a small util that is used to transform a search string with common patterns.

    internal

    Parameters

    • value: string

      The string to transform

    • lowercase: boolean = false

      Boolean if the value should be lowercased for case-insensitive searches

    • trim: boolean = false

      Boolean if the leading and trailing whitespace should be trimmed

    • ignoreWhitespace: boolean = false

      Boolean if all whitespace should be ignored. This will take precedence over the trim parameter if set to true.

    Returns string

    The transformed search string

  • getViewportSize(direction: "height" | "width"): number
  • This is a simple wrapper to get the view width or view height.

    Parameters

    • direction: "height" | "width"

      Either the "height" or "width" string to get that dimension

    Returns number

    the view width or view height.

  • isContrastCompliant(background: string, foreground: string, compliance?: number | ContrastRatioCompliance): boolean
  • Checks if there is an acceptable contrast ratio between the background and foreground colors based on the provided compliance level.

    Parameters

    • background: string

      The background color to check against

    • foreground: string

      The foreground color to check against

    • compliance: number | ContrastRatioCompliance = "normal"

      The compliance level to use or a custom number as a ratio.

    Returns boolean

    true if there is enough contrast between the foreground and background colors for the provided compliance level.

  • isFocusable(element: HTMLElement | Window | Document, type?: ElementFocusType): element is HTMLElement
  • A small util that is used to increment or decrement a number until it reaches the max value or -1. When that happens, it will loop around to 0 or the max value respectively. This does not work for different increment numbers or any values below 0 for now.

    internal
    remarks

    @since 2.7.0 The min option was added and the arguments changed to an object

    Parameters

    Returns number

  • nearest(value: number, min: number, max: number, steps: number, range?: number): number
  • Rounds a number to the nearest step within a min/max range.

    see

    https://stackoverflow.com/a/13635455

    remarks

    @since 2.5.0 - Added the range param

    Parameters

    • value: number

      The value to round to the nearest step

    • min: number

      The min value allowed

    • max: number

      The max value allowed

    • steps: number

      The number of steps in the min/max range

    • range: number = ...

      The range allowed for the value that defaults to max - min

    Returns number

    the value rounded to the nearest step in the min/max range

  • omit<T, K>(object: T, omitKeys: readonly (string | K)[]): Omit<T, K>
  • Create a new object that does not contain the provided keys.

    example

    Simple Examples

    const object = {
    a: "",
    b: 3,
    c: false,
    4: null,
    } as const;

    expect(omit(object, ["a"])).toEqual({
    b: 3,
    c: false,
    4: null,
    });
    expect(omit(object, ["a", "c", "d"])).toEqual({ b: 3 });
    internal

    Type parameters

    • T: object

    • K: string | number | symbol

    Parameters

    • object: T

      The object to remove keys from

    • omitKeys: readonly (string | K)[]

      The keys to remove.

    Returns Omit<T, K>

    a new object without the specified keys

  • scrollIntoView(container: null | HTMLElement, element: null | HTMLElement): void
  • Attempts to scroll an element into view within another container element if needed. If either the container or element are null, nothing will happen.

    Parameters

    • container: null | HTMLElement

      The container element that should be scrolled if the child element is not within view.

    • element: null | HTMLElement

      The element that should be visible within the container element's scroll area.

    Returns void

  • Creates a throttled version of a function so that it'll be called with trailing and leading calls. Since I always get this confused with debounce, here's a quick summary of the differences:

    • debounce will wait to call the function until it hasn't been called again for the wait duration without trailing or leading calls. If it has the trailing and leading calls, I can't figure out how it's different than throttle.
    • throttle will be called each time it is available to be called.

    So debounce is great for things like auto-save features if you want to save whenever the user stops typing for a few seconds while throttle is good for things like sending an API request when the user is typing so that it isn't sent every keystroke, but every few letters. You could also do debounce here, but it'll feel more "responsive" to the user when throttled.

    Type parameters

    Parameters

    • fn: F

      The function that should be throttled

    • wait: number

      The number of milliseconds to wait before calling the function again

    Returns ThrottledFunction<F>

    a throttled version of the function that'll return the last computed value if it was called again during the "wait" period.

  • toWidthPart(v: undefined | QuerySize, prefix: "max" | "min"): string
  • tryToSubmitRelatedForm(event: KeyboardSubmitEventPartial): boolean
  • The default behavior when pressing the "Enter" key on a form control (input, textarea, select) is to submit the form that the form control is in. This util will try to polyfill this behavior for custom widgets that use are using a role to act as a form control.

    The way this works is:

    • Check if the event.key is the "Enter" key. Do nothing if it is not.
    • Call event.preventDefault() and event.stopPropagation() to prevent other unwanted keyboard behavior
    • Check the event target to see if it is contained in a <form>
    • Try to find a submit button and click it by:
      • First check with form.querySelector('[type="submit"]')
      • Fallback to document.querySelector('[type="submit"][form="{{FORM_ID}}"]')
        • submit buttons can be placed outside of the form and link it back using the form attribute pointing to the id of the form

    The reason the submit button has to be found and clicked is because calling form.submit() won't actually fire any attached form.onsubmit event handlers. If you click the submit button though, the form.onsubmit handlers will be called correctly.

    remarks

    @since 2.7.0

    Parameters

    • event: KeyboardSubmitEventPartial

      The keyboard event that should attempt to submit the form when the enter key is pressed.

    Returns boolean

    true if the event.key was the "Enter" key so that other keydown logic can be ignored.

  • A simple util to convert a unit that is using px, em, or rem to a number so that calculations can be made on that unit.

    Parameters

    Returns number

    the unit as a number

  • This hook allows for custom keyboard "focus" movement using the aria-activedescendant movement pattern. This is generally used when the DOM focus shouldn't actually change from the container element (like listboxes) but you still need to indicate that another element is "focused" due to a key press.

    To use this hook, you'll want to update the container element of all the items to have an aria-activedescendant={activeId} attribute and onKeyDown={onKeyDown} that are provided by this hook. The aria-activedescendant will help screen readers known what element is "focused" since the container element should never really lose focus during these keyboard movement events. Finally, you'll want to update each item have an id that is the result of getItem(baseId, index) so that it matches the aria-activedescendant value and then apply ref={itemRefs[i]}. Unfortunately, this means that all the child items must either be an HTMLElement or the ref is forwarded down to the HTMLElement.

    The itemRefs must be applied so that a new "focused" item can be scrolled into view as needed.

    Type parameters

    • D = unknown

      The type of each data item within the items list.

    • CE: HTMLElement = HTMLElement

      The HTMLElement type of the container element that handles the custom keyboard movement.

    • IE: HTMLElement = HTMLElement

      The HTMLElement type of each item within the container element that can be focusable.

    Parameters

    • __namedParameters: ActiveDescendantOptions<D, CE, IE>

    Returns ActiveDescendantMovementProviders<CE, IE>

  • This hook is used to determine the current application size based on the provided query sizes. When you want to render your app server side, you will need to provide a custom defaultSize that implements your logic to determine the type of device requesting a page. Once the app has been rendered in the DOM, this hook will attach event listeners to automatically update the app size when the page is resized.

    internal

    Parameters

    Returns AppSize

  • useCloseOnEscape<E>(onRequestClose: () => void, disabled: boolean, onKeyDown?: KeyboardEventHandler<E>): KeyboardEventHandler<E> | undefined
  • This will conditionally close the dialog when the escape key is pressed.

    Type parameters

    • E: HTMLElement

    Parameters

    • onRequestClose: () => void

      The function to call to close the dialog.

        • (): void
        • Returns void

    • disabled: boolean

      Boolean if the escape key functionality should be disabled

    • Optional onKeyDown: KeyboardEventHandler<E>

      An optional keydown event handler to also call.

    Returns KeyboardEventHandler<E> | undefined

    A keydown event handler

  • Triggers a callback function when another element in the page is clicked that is outside of the provided element. This is generally used for closing temporary elements when something else within the page has been clicked.

    The callback will be provided the current element as well as the click target if additional logic should be applied before closing.

    Type parameters

    • E: HTMLElement

      The type of element

    Parameters

    Returns void

  • This hook can be used to implement simple drag-and-drop behavior for file uploads or special styles while dragging an element over a part of a page.

    example

    Simple File

    const style: CSSProperties = {
    border: '1px solid blue',
    };

    function Example(): ReactElement {
    const { onDrop } = useFileUpload()
    const [isOver, handlers] = useDropzone({
    onDrop: (event) => {
    // normally use the `onDrop` behavior from `useFileUpload` to upload
    // files:
    // onDrop(event);
    }
    });

    return (
    <div {...handlers} style={isOver ? style : {}}>
    Drag and drop some files!
    {isOver && <UploadSVGIcon />}
    </div>
    );
    }
    see

    useFileUpload for a more complex example

    remarks

    @since 2.9.0

    Type parameters

    • E: HTMLElement

    Parameters

    Returns DropzoneHookReturnValue<E>

  • useEnsuredRef<E>(propRef?: Ref<null | E>): EnsuredRefs<E>
  • This is mostly an internal hook that allows for an optional ref (normally from props or hook options) to be merged with a hook's required ref. This will return a MutableRefObject used for DOM manipulation in a custom hook followed by a ref callback function that should be passed to the DOM node that will ensure that both the optional propRef and hook ref are updated.

    remarks

    @since 2.3.0

    Type parameters

    • E: HTMLElement

    Parameters

    • Optional propRef: Ref<null | E>

    Returns EnsuredRefs<E>

  • This hook allows for custom keyboard focus movement using DOM focus behavior by actually focusing each DOM node.

    To use this hook, you'll want to update the container element of all the items to have a correct role applied as well as the onKeyDown event handler provided by this hook. Then, you'll want to applied a ref={itemRefs[i]} for each item within the items list so that the DOM nodes can be focused as needed. Unfortunately, this means that all the child items must either be an HTMLElement or the ref is forwarded down to the HTMLElement.

    Type parameters

    • D = unknown

      The type of each data item within the items list.

    • CE: HTMLElement = HTMLElement

      The HTMLElement type of the container element that handles the custom keyboard movement.

    • IE: HTMLElement = HTMLElement

      The HTMLElement type of each item within the container element that can be focusable.

    Parameters

    • __namedParameters: KeyboardFocusOptions<D, CE, IE>

    Returns KeyboardMovementProviders<CE, IE>

  • useFocusOnMount(refOrInstance: RefOrInstance, defaultFocus: string, preventScroll?: boolean, programmatic?: boolean, disabled?: boolean): void
  • This hook is used to focus an element once a component has mounted. To help with keyboard click events, it will actually wait for an animation frame before attempting to focus as an enter key might click both elements at the same time.

    This hook will first focus the HTMLElement (if it is focusable) and then focus an element based on the defaultFocus prop.

    Parameters

    • refOrInstance: RefOrInstance

      This is either a ref object containing the element to focus or the element itself.

    • defaultFocus: string

      The element to focus within the containing element once it has been mounted. This can either be "first" or "last" to focus the first or last focusable elements or a query selector string to find an element to focus.

    • preventScroll: boolean = false

      Boolean if the focus events should try to prevent the default scroll-into-view behavior. This is generally recommended to be kept as false, but can be useful to enable if the component mounts offscreen during a transition.

    • programmatic: boolean = false

      Boolean if programmatically focusable elements should be included instead of only tab focusable.

    • disabled: boolean = false

      Boolean if the focus behavior should be disabled.

    Returns void

  • The useGridList hook allows you to get all the grid and sizing functionality of the GridList component without needing to wrap your children in a <div> element.

    Example:

    const [gridListProps] = useGridList({
    cellMargin: 16,
    maxCellSize: 300,
    containerPadding: 4,
    });

    return <div {...gridListProps}>{children}</div>;

    Note: You must manually provide the gridSize to the GridListSizeProvider component that was added in 2.3.0 if you want to use the useGridSize hook.

    Example:

    const [gridListProps, gridSize] = useGridList()

    return (
    <GridListSizeProvider value={gridSize}>
    <MyComponent {...gridListProps} />
    </GridListSizeProvider>
    );
    remarks

    @since 2.3.0

    Type parameters

    • E: HTMLElement

    Parameters

    Returns UseGridListReturnValue<E>

  • This hook is used to add the hover mode functionality to any component.

    example

    Displaying a Color Preview when hovering a Hex Code

    import type { ReactElement } from "react";
    import { CSSTransition } from "@react-md/transition";
    import { useHoverMode } from "@react-md/utils";

    interface Props {
    value: string;
    }

    export default function Color({ value }: Props): ReactElement {
    const { visible, onMouseEnter, onMouseLeave } =
    useHoverMode({ exitVisibilityDelay: 0 });

    return (
    <>
    <span
    onMouseEnter={onMouseEnter}
    onMouseLeave={onMouseLeave}
    style={{
    // pretend styles
    }}
    >
    {value}
    </span>
    <CSSTransition
    transitionIn={visible}
    classNames="opacity-change"
    timeout={150}
    temporary
    >
    <span
    style={{
    backgroundColor: value,
    // other styles
    }}
    />
    </CSSTransition>
    </>
    );
    }
    example

    Sticky Usage with a Fixed Dialog

    const {
    stuck,
    active,
    visible,
    setVisible,
    handlers,
    hoverHandlers,
    } = useHoverMode();
    const buttonRef = useRef<HTMLButtonElement>(null);

    return (
    <>
    <Button {...handlers} ref={buttonRef}>
    Click Me
    </Button>
    <FixedDialog
    {...hoverHandlers}
    aria-labelledby="dialog-title-id"
    id="dialog-id"
    visible={visible}
    onRequestClose={() => setVisible(false)}
    fixedTo={buttonRef}
    anchor={BELOW_CENTER_ANCHOR}
    options={{ preventOverlap: true }}
    // this allows the close on outside click"" behavior" to work
    overlay={!stuck && active ? false : undefined}
    disableScrollLock={active}
    >
    <YourDialogContent />
    </FixedDialog>
    </>
    );
    remarks

    @since 2.8.0

    remarks

    @since 5.0.0 This hook no longer returns handlers or stickyHandlers and does not hide when an element on the page is clicked.

    Parameters

    Returns HoverModeHookReturnValue

    either the {@link HoverModeReturnValue} or {@link HoverModeReturnValue}

  • useInterval(callback: (stop: () => void) => void, delay: number, defaultRunning?: boolean): ReturnValue
  • Simple hook to use an interval with auto setup and teardown. The provided functions will be guaranteed to not change and are memoized.

    Parameters

    • callback: (stop: () => void) => void

      The callback function to call

        • (stop: () => void): void
        • Parameters

          • stop: () => void
              • (): void
              • Returns void

          Returns void

    • delay: number

      The time in milliseconds the timer should delay between executions of the callback function

    • defaultRunning: boolean = false

      Boolean if the interval should be started immediately

    Returns ReturnValue

    a list containing a boolean if the interval is running, function to start the interval, and a function to stop the interval.

  • useIsomorphicLayoutEffect(effect: EffectCallback, deps?: DependencyList): void
  • useKeyboardFocusableElement<E>(ref?: Ref<E>): RefCallback<E>
  • This is a low-level hook for providing custom keyboard movement based on key configurations. This normally shouldn't really be used externally since you'll most likely want to use the "presets" of useFocusMovement and useActiveDescendantMovement that implement the main movement types already for you.

    The way this works is that it will general a list of mutable item refs that should be applied to each DOM node for the corresponding item within the items list. This list will change and regenerate itself each time the items array changes so it'll always be in-sync with the DOM nodes. This means that if you have some items that should not be rendered, they should not be included within the items list. The main reason these item refs are required is so that the aria-activedescendant movement can scroll the new "focused" element into view if needed while the "true" focus movement can trigger a ref.current.focus() on the new item as needed.

    Finally, this will create a keydown event handler that will merge in the optionally provided onKeyDown prop and check if the pressed key should trigger a custom keyboard movement event. If it does, an onChange event will be fired with the matching data and allows for custom movement with target.focus() or updating the aria-activedescendant attribute as needed.

    Type parameters

    • D = unknown

      The type of each data item within the items list.

    • CE: HTMLElement = HTMLElement

      The HTMLElement type of the container element that handles the custom keyboard movement.

    • IE: HTMLElement = HTMLElement

      The HTMLElement type of each item within the container element that can be focusable.

    Parameters

    Returns KeyboardMovementProviders<CE, IE>

  • useMediaQuery(query: string, defaultValue?: boolean, disabled?: boolean, checkImmediately?: boolean): boolean
  • A helper hook that is used to create a memoized media query tester for window.matchMedia.

    Note: This is a client side only hook as it requires the window to attach a resize event listener to.

    Parameters

    • query: string

      The media query to use

    • Optional defaultValue: boolean

      The default value for if this media query matches. When this is undefined, it will default to false unless the window is defined and the checkImmediately param was not set to false. Otherwise, it will check the media query matches on mount and use that value.

    • disabled: boolean = false

      Boolean if the media query checking should be disabled.

    • checkImmediately: boolean = ...

      Boolean if the media query should be checked immediately on mount. When omitted, it will default to checking when the window is defined.

    Returns boolean

    true if the media query is a match.

  • useOnUnmount(callback: () => void): void
  • A simple hook that only triggers the callback when a component is unmounted. This will make sure that the callback function does not have a stale closure by the time the component unmounts as well.

    example

    Simple Example

    useOnUnmount(() => {
    console.log('Component is unmounted.');
    });

    const [data, setData] = useState(initialData);
    useOnUnmount(() => {
    API.saveCurrentData(data);
    });

    // update data
    remarks

    @since 2.7.1

    Parameters

    • callback: () => void

      the function to call when the component unmounts.

        • (): void
        • Returns void

    Returns void

  • useOrientation(defaultValue?: OrientationType): OrientationType
  • This media query is used to determine the current orientation of the app based on the window.screen.orientation.type. This will always be "landscape-primary" server side unless a default value is provided.

    Parameters

    • Optional defaultValue: OrientationType

      an optional default value to use. When this is omitted, it will default to "landscape-primary" unless the window is defined. If the window is defined, it will immediately check the orientation type on mount.

    Returns OrientationType

    the orientation type value.

  • usePreviousFocus(disabled: boolean, fallback?: FocusFallback, previousElement?: null | HTMLElement): void
  • This hook is used to focus the previous element when a component unmounts. The default behavior is to store the current activeElement within the document when the component mounts and then try to focus it again when the component unmounts. You can also provide your own HTMLElement to focus when unmounting.

    During the unmount phase, it will wait for an animation frame before checking if the fallback element still exists within the page. If it doesn't, it will use the fallback query/element/function to attempt to find another element to focus. If the element exists within the page, it will then finally be focused.

    The animation frame is unfortunately required for keyboard users as pressing enter key will click the previous element immediately on focus as well.

    Parameters

    • disabled: boolean

      Boolean if the focus behavior should be disabled.

    • fallback: FocusFallback = undefined

      The fallback query, element, or function to use if the previous element no longer exists in the DOM.

    • previousElement: null | HTMLElement = null

      An optional previous element to focus. If this is omitted, the document.activeElement will be used instead.

    Returns void

  • useRefCache<T>(cacheable: T): { current: T }
  • This hook allows you to provide anything that should be "cached" and puts it into a ref that'll be updated each render. This is pretty overkill for most places, but it's really nice when you want to create event handlers that shouldn't update if the developer used arrow functions to define callbacks. (A great example is for ref callbacks that shouldn't be triggered each render. But that might just be a programming error instead).

    Type parameters

    • T

    Parameters

    • cacheable: T

      The cacheable thing that gets updated after each render.

    Returns { current: T }

    a mutable ref object containing the current cache.

    • Readonly current: T
  • This is a simple hook that will attach a throttled resize event listener when mounted, and detach when it unmounts.

    This hook only works for entire app resize events. If you are looking for specific element resize events, check out the ResizeObserver component or useResizeObserver hook instead.

    Parameters

    Returns void

  • The new resize observer API that returns a refHandler to attach to a DOM node instead of using the weird target API.

    remarks

    @since 2.3.0

    Type parameters

    • E: HTMLElement

    Parameters

    • onResize: OnResizeObserverChange<E>

      The resize handler to call when the element has changed height or width. If you notice performance issues or other oddities, it is recommended to wrap this function in useCallback.

    • options: UseResizeObserverOptions<E> = {}

      Any additional options to use for the resize observer.

    Returns EnsuredRefs<E>

  • useScrollLock(enabled: boolean, selectorOrElement?: null | string | HTMLElement | (() => HTMLElement)): void
  • A hook that is used to dynamically add scroll locking to an element. By default, this will use the main <body> tag for scroll locking, but a query selector string or an HTML element can also be used instead.

    Parameters

    • enabled: boolean

      Boolean if the scroll locking behavior should be enabled

    • Optional selectorOrElement: null | string | HTMLElement | (() => HTMLElement)

      Either a query selector string, HTMLElement, or a function that returns an HTMLElement to apply scroll locking to.

    Returns void

  • useTempValue<T>(defaultValue: T, resetTime?: number): ReturnValue<T>
  • Creates a temporary value that gets reset every xms back to the provided default value. This is useful when doing keyboard searching or other interactions.

    NOTE: This does not force a re-render when the value changes and instead uses a ref value instead.

    Type parameters

    • T

      the type for the value

    Parameters

    • defaultValue: T

      The default value to use. Each time the reset timeout is triggered, this value will be set again.

    • resetTime: number = 500

      The amount of time before the value is reset back to the default value

    Returns ReturnValue<T>

  • useTimeout(cb: () => void, delay: number, defaultStarted?: boolean | (() => boolean)): ReturnValue
  • Simple hook to use an timeout with auto setup and teardown. The provided functions will be guaranteed to not change and are memoized.

    Parameters

    • cb: () => void

      The callback function to call

        • (): void
        • Returns void

    • delay: number

      The time in milliseconds the timer should delay between executions of the callback function

    • defaultStarted: boolean | (() => boolean) = false

      Boolean if the timeout should be started immediately.

    Returns ReturnValue

    a list containing a function to start the timeout, a function to stop the timeout, and a function to restart the timeout.

  • useToggle(defaultToggled: boolean | (() => boolean)): ReturnValue
  • This hooks provides an easy way to toggle a boolean flag for React components. The main use case for this will be toggling the visibility of something. All the provided actions are guaranteed to never change.

    Parameters

    • defaultToggled: boolean | (() => boolean)

      Boolean if the visibility should be enabled first render.

    Returns ReturnValue

    an array containing the toggled state, an enable function, a disable function, a toggle function, and then a manual set toggle function.

  • useWidthMediaQuery(__namedParameters: (WidthMediaQuery & { min: QuerySize }) & (WidthMediaQuery & { max: QuerySize }) & (WidthMediaQuery & { max: QuerySize; min: QuerySize })): boolean
  • withinRange(value: number, min: undefined | number, max: undefined | number): number
  • A simple util that will ensure that a number is within the optional min and max values.

    remarks

    @since 2.5.0

    Parameters

    • value: number

      The number to ensure that is within the range

    • min: undefined | number

      The optional min value

    • max: undefined | number

      The optional max value

    Returns number

    the updated value

Generated using TypeDoc