@fluentui/utilities package

Classes

Async

Bugs often appear in async code when stuff gets disposed, but async operations don't get canceled. This Async helper class solves these issues by tying async code to the lifetime of a disposable object.

Usage: Anything class extending from BaseModel can access this helper via this.async. Otherwise create a new instance of the class and remember to call dispose() during your code's dispose handler.

AutoScroll

AutoScroll simply hooks up mouse events given a parent element, and scrolls the container up/down depending on how close the mouse is to the top/bottom of the container.

Once you don't want autoscroll any more, just dispose the helper and it will unhook events.

BaseComponent

BaseComponent class, which provides basic helpers for all components.

Customizations
Customizer

The Customizer component allows for default props to be mixed into components which are decorated with the customizable() decorator, or use the styled HOC. This enables injection scenarios like:

  1. render svg icons instead of the icon font within all buttons 2. inject a custom theme object into a component

Props are provided via the settings prop which should be one of the following: - A json map which contains 1 or more name/value pairs representing injectable props. - A function that receives the current settings and returns the new ones that apply to the scope

DelayedRender

Utility component for delaying the render of a child component after a given delay. This component requires a single child component; don't pass in many components. Wrap multiple components in a DIV if necessary.

EventGroup

An instance of EventGroup allows anything with a handle to it to trigger events on it. If the target is an HTMLElement, the event will be attached to the element and can be triggered as usual (like clicking for onClick). The event can be triggered by calling EventGroup.raise() here. If the target is an HTMLElement, the event gets raised and is handled by the browser. Otherwise, it gets handled here in EventGroup, and the handler is called in the context of the parent (which is passed in in the constructor).

FabricPerformance

Performance helper class for measuring things.

GlobalSettings

Global settings helper, which stores settings in the global (window) namespace. If window is not provided, it will store settings in module scope. Provides a way to observe changes as well when their values change.

Rectangle

Rectangle helper class.

Selection

Interfaces

IAsAsyncOptions
IBaseProps

BaseProps interface.

IChangeDescription

Change description used for change callbacks in GlobalSettings.

IChangeEventCallback

Change event callback.

IClassNamesFunctionOptions
ICustomizableProps
ICustomizations
ICustomizerContext
IDelayedRenderProps

DelayedRender component props.

IDisposable

Disposable interface.

IFitContentToBoundsOptions

Options for fitting content sizes into bounding sizes.

IObjectWithKey
IPoint

Point interface.

IPropsWithStyles
IRectangle

Rectangle interface.

IRenderComponent

An interface representing a component that will not output any DOM, will just render its children and pass through items to modify the children.

IRenderFunction

Render function interface for providing overrideable render callbacks.

ISelection
ISelectionOptions
ISize
IWarnControlledUsageParams
Point

Point interface.

Enums

SelectionDirection
SelectionMode

Functions

addDirectionalKeyCode(which)

Adds a keycode to the list of keys that, when pressed, should cause the focus outlines to be visible. This can be used to add global shortcut keys that directionally move from section to section within an app or between focus trap zones.

addElementAtIndex(array, index, itemToAdd)

Given an array, this function returns a new array where an element has been inserted at the given index.

appendFunction(parent, functions)

Returns a single function which will call each of the given functions in the context of the parent.

arraysEqual(array1, array2)

Returns a boolean indicating if the two given arrays are equal in length and values.

asAsync(options)

Produces a component which internally loads the target component before first mount. The component passes all props through to the loaded component.

This overload accepts a module with a default export for the component.

assertNever(x)

AssertNever is a utility function that can be used for exhaustiveness checks in switch statements.

assign(this, target, args)

Makes a resulting merge of a bunch of objects. Pass in the target object followed by 1 or more objects as arguments and they will be merged sequentially into the target. Note that this will shallow merge; it will not create new cloned values for target members.

calculatePrecision(value)

Calculates a number's precision based on the number of trailing zeros if the number does not have a decimal indicated by a negative precision. Otherwise, it calculates the number of digits after the decimal point indicated by a positive precision.

classNamesFunction(options)

Creates a getClassNames function which calls getStyles given the props, and injects them into mergeStyleSets.

Note that the props you pass in on every render should be in the same order and immutable (numbers, strings, and booleans). This will allow the results to be memoized. Violating these will cause extra recalcs to occur.

composeComponentAs(outer, inner)

Composes two components which conform to the IComponentAs specification; that is, two components which accept a defaultRender prop, which is a 'default' implementation of a component which accepts the same overall props.

composeRenderFunction(outer, inner)

Composes two 'render functions' to produce a final render function that renders the outer function, passing the inner function as 'default render'. The inner function is then passed the original 'default render' prop.

createArray(size, getItem)

Creates an array of a given size and helper method to populate.

createMemoizer(getValue)

Creates a memoizer for a single-value function, backed by a WeakMap. With a WeakMap, the memoized values are only kept as long as the source objects, ensuring that there is no memory leak.

This function assumes that the input values passed to the wrapped function will be function or object types. To memoize functions which accept other inputs, use memoizeFunction, which memoizes against arbitrary inputs using a lookup cache.

css(args)

Concatination helper, which can merge class names together. Skips over falsey values.

customizable(scope, fields, concatStyles)
disableBodyScroll()

Disables the body scrolling.

doesElementContainFocus(element)

Determines if an element, or any of its children, contain focus.

enableBodyScroll()

Enables the body scrolling.

extendComponent(parent, methods)

Extends a component's lifetime methods by appending new functions to the existing lifetime functions.

filteredAssign(isAllowed, target, args)

Makes a resulting merge of a bunch of objects, but allows a filter function to be passed in to filter the resulting merges. This allows for scenarios where you want to merge "everything except that one thing" or "properties that start with data-". Note that this will shallow merge; it will not create new cloned values for target members.

find(array, cb)

Helper to find the first item within an array that satisfies the callback.

findIndex(array, cb, fromIndex)

Helper to find the index of an item within an array, using a callback to determine the match.

findScrollableParent(startingElement)

Traverses up the DOM for the element with the data-is-scrollable=true attribute, or returns document.body.

fitContentToBounds(options)

Produces a proportionally-scaled version of an input content size when fit to a bounding size. Given a contentSize and a boundsSize, this function scales contentSize proportionally using either contain or cover fit behaviors. Use this function to pre-calculate the layout for the CSS object-fit and background-fit behaviors. With contain, the output size must be the largest it can be while completely within the boundsSize. With cover, the output size must be the smallest it can be while completely around the boundsSize. By default, there is a maxScale value of 1, which prevents the contentSize from being scaled larger.

flatten(array)

Given an array where each element is of type T or T[], flatten it into an array of T

focusAsync(element)

Sets focus to an element asynchronously. The focus will be set at the next browser repaint, meaning it won't cause any extra recalculations. If more than one focusAsync is called during one frame, only the latest called focusAsync element will actually be focused

focusFirstChild(rootElement)

Attempts to focus the first focusable element that is a child or child's child of the rootElement.

format(s, values)

String format method, used for scenarios where at runtime you need to evaluate a formatted string given a tokenized string. This usually only is needed in localization scenarios.

getDistanceBetweenPoints(point1, point2)

Determines the distance between two points.

getDocument(rootElement)

Helper to get the document object. Note that in popup window cases, document might be the wrong document, which is why we look at ownerDocument for the truth. Also note that the SSR flag is used to test ssr scenarios even if document is defined (from JSDOM for example.)

getElementIndexPath(fromElement, toElement)

Finds the element index path from a parent element to a child element.

If you had this node structure: "A has children [B, C] and C has child D", the index path from A to D would be [1, 0], or parent.chidren[1].children[0].

getFirstFocusable(rootElement, currentElement, includeElementsInFocusZones)

Gets the first focusable element.

getFirstTabbable(rootElement, currentElement, includeElementsInFocusZones, checkNode)

Gets the first tabbable element. (The difference between focusable and tabbable is that tabbable elements are focusable elements that also have tabIndex != -1.)

getFocusableByIndexPath(parent, path)

Finds the closest focusable element via an index path from a parent. See getElementIndexPath for getting an index path from an element to a child.

getId(prefix)

Generates a unique id in the global scope (this spans across duplicate copies of the same library.)

getInitials(displayName, isRtl, allowPhoneInitials)

Get (up to 2 characters) initials based on display name of the persona.

getLanguage(persistenceType)

Gets the language set for the page.

getLastFocusable(rootElement, currentElement, includeElementsInFocusZones)

Gets the last focusable element.

getLastTabbable(rootElement, currentElement, includeElementsInFocusZones, checkNode)

Gets the last tabbable element. (The difference between focusable and tabbable is that tabbable elements are focusable elements that also have tabIndex != -1.)

getNativeElementProps(tagName, props, excludedPropNames)

Given an element tagname and user props, filters the props to only allowed props for the given element type.

getNativeProps(props, allowedPropNames, excludedPropNames)

Gets native supported props for an html element provided the allowance set. Use one of the property sets defined (divProperties, buttonPropertes, etc) to filter out supported properties from a given props set. Note that all data- and aria- prefixed attributes will be allowed. NOTE: getNativeProps should always be applied first when adding props to a react component. The non-native props should be applied second. This will prevent getNativeProps from overriding your custom props. For example, if props passed to getNativeProps has an onClick function and getNativeProps is added to the component after an onClick function is added, then the getNativeProps onClick will override it.

getNextElement(rootElement, currentElement, checkNode, suppressParentTraversal, suppressChildTraversal, includeElementsInFocusZones, allowFocusRoot, tabbable)

Traverse to find the next focusable element. If tabbable is true, the element must have tabIndex != -1.

getPreviousElement(rootElement, currentElement, checkNode, suppressParentTraversal, traverseChildren, includeElementsInFocusZones, allowFocusRoot, tabbable)

Traverse to find the previous element. If tabbable is true, the element must have tabIndex != -1.

getPropsWithDefaults(defaultProps, propsWithoutDefaults)

Function to apply default values to a component props object. This function is intended for function components, to maintain parity with the defaultProps feature of class components. It accounts for properties that are specified, but undefined.

getRect(element)

Helper to get bounding client rect. Passing in window will get the window size.

getResourceUrl(url)

Sets the current base url used for fetching images.

getRTL(theme)

Gets the rtl state of the page (returns true if in rtl.)

getRTLSafeKeyCode(key, theme)

Returns the given key, but flips right/left arrows if necessary.

getScrollbarWidth()

Calculates the width of a scrollbar for the browser/os.

getWindow(rootElement)

Helper to get the window object. The helper will make sure to use a cached variable of "window", to avoid overhead and memory leaks in IE11. Note that in popup scenarios the window object won't match the "global" window object, and for these scenarios, you should pass in an element hosted within the popup.

hasHorizontalOverflow(element)

Detects whether an element's content has horizontal overflow

hasOverflow(element)

Detects whether an element's content has overflow in any direction

hasVerticalOverflow(element)

Detects whether an element's content has vertical overflow

hoistMethods(destination, source, exclusions)

Allows you to hoist methods, except those in an exclusion set from a source object into a destination object.

hoistStatics(source, dest)

Allows you to hoist static functions in components. Created for the purpose of fixing broken static functions in classes that utilize decorators.

initializeComponentRef(obj)

Helper to manage componentRef resolution. Internally appends logic to lifetime methods to resolve componentRef to the passed in object.

Usage: call initializeComponentRef(this) in the constructor,

initializeFocusRects(window)

Initializes the logic which:

  1. Subscribes keydown and mousedown events. (It will only do it once per window, so it's safe to call this method multiple times.) 2. When the user presses directional keyboard keys, adds the 'ms-Fabric--isFocusVisible' classname to the document body, removes the 'ms-Fabric-isFocusHidden' classname. 3. When the user clicks a mouse button, adds the 'ms-Fabric-isFocusHidden' classname to the document body, removes the 'ms-Fabric--isFocusVisible' classname.

This logic allows components on the page to conditionally render focus treatments based on the existence of global classnames, which simplifies logic overall.

isControlled(props, valueProp)

Determines whether a component is controlled.

isDirectionalKeyCode(which)

Returns true if the keycode is a directional keyboard key.

isElementFocusSubZone(element)

Determines if a given element is a focus sub zone.

isElementFocusZone(element)

Determines if a given element is a focus zone.

isElementTabbable(element, checkTabIndex)

Determines if an element can receive focus programmatically or via a mouse click. If checkTabIndex is true, additionally checks to ensure the element can be focused with the tab key, meaning tabIndex != -1.

isElementVisible(element)

Determines if an element is visible.

isMac(reset)

Returns true if the user is on a Mac. Caches the result value.

mapEnumByName(theEnum, callback)

Takes an enum and iterates over each value of the enum (as a string), running the callback on each, returning a mapped array.

memoize(target, key, descriptor)

Memoize decorator to be used on class methods. WARNING: the this reference will be inaccessible within a memoized method, given that a cached method's this would not be instance-specific.

memoizeFunction(cb, maxCacheSize, ignoreNullOrUndefinedResult)

Memoizes a function; when you pass in the same parameters multiple times, it returns a cached result. Be careful when passing in objects, you need to pass in the same INSTANCE for caching to work. Otherwise it will grow the cache unnecessarily. Also avoid using default values that evaluate functions; passing in undefined for a value and relying on a default function will execute it the first time, but will not re-evaluate subsequent times which may have been unexpected.

By default, the cache will reset after 100 permutations, to avoid abuse cases where the function is unintendedly called with unique objects. Without a reset, the cache could grow infinitely, so we safeguard by resetting. To override this behavior, pass a value of 0 to the maxCacheSize parameter.

merge(target, args)

Simple deep merge function. Takes all arguments and returns a deep copy of the objects merged together in the order provided. If an object creates a circular reference, it will assign the original reference.

mergeAriaAttributeValues(ariaAttributes)

ARIA helper to concatenate attributes, returning undefined if all attributes are undefined. (Empty strings are not a valid ARIA attribute value.)

mergeCustomizations(props, parentContext)

Merge props and customizations giving priority to props over context. NOTE: This function will always perform multiple merge operations. Use with caution.

mergeScopedSettings(oldSettings, newSettings)
mergeSettings(oldSettings, newSettings)

Merge new and old settings, giving priority to new settings. New settings is optional in which case oldSettings is returned as-is.

modalize(target)

Call this on a target element to make it modal to screen readers. Returns a function that undoes the changes it made.

nullRender()

Simple constant function for returning null, used to render empty templates in JSX.

omit(obj, exclusions)

Tiny helper to do the minimal amount of work in duplicating an object but omitting some props. This ends up faster than using object ...rest or reduce to filter.

This behaves very much like filteredAssign, but does not merge many objects together, uses an exclusion object map, and avoids spreads all for optimal performance.

See perf test for background: https://jsperf.com/omit-vs-rest-vs-reduce/1

on(element, eventName, callback, options)
precisionRound(value, precision, base)

Rounds a number to a certain level of precision. Accepts negative precision.

raiseClick(target)

Raises a click event.

removeIndex(array, index)

Given an array, it returns a new array that does not contain the item at the given index.

replaceElement(array, newElement, index)

Given an array, this function returns a new array where the element at a given index has been replaced.

resetControlledWarnings()

Reset controlled usage warnings for testing purposes.

resetIds(counter)

Resets id counter to an (optional) number.

resetMemoizations()

Reset memoizations.

setBaseUrl(baseUrl)

Gets the current base url used for fetching images.

setFocusVisibility(enabled, target)

Sets the visibility of focus styling.

By default, focus styles (the box surrounding a focused Button, for example) only show up when navigational keypresses occur (through Tab, arrows, PgUp/PgDn, Home and End), and are hidden when mouse interactions occur. This API provides an imperative way to turn them on/off.

A use case might be when you have a keypress like ctrl-f6 navigate to a particular region on the page, and want focus to show up.

setLanguage(language, persistenceType)

Sets the language for the page (by adjusting the lang attribute of the html element).

setLanguage(language, avoidPersisting)

Sets the language for the page (by adjusting the lang attribute of the html element).

setRTL(isRTL, persistSetting)

Sets the rtl state of the page (by adjusting the dir attribute of the html element.)

setSSR(isEnabled)

Helper to set ssr mode to simulate no window object returned from getWindow helper.

setWarningCallback(warningCallback)

Configures the warning callback. Passing in undefined will reset it to use the default console.warn function.

shallowCompare(a, b)

Compares a to b and b to a.

shouldWrapFocus(element, noWrapDataAttribute)

Determines if an, or any of its ancestors, sepcificies that it doesn't want focus to wrap

styled(Component, baseStyles, getProps, customizable, pure)

The styled HOC wrapper allows you to create a functional wrapper around a given component which will resolve getStyles functional props, and mix customized props passed in using concatStyleSets.

styled(Component, baseStyles, getProps, customizable, pure)
toMatrix(items, columnCount)

Convert the given array to a matrix with columnCount number of columns.

unhoistMethods(source, methodNames)

Provides a method for convenience to unhoist hoisted methods.

useCustomizationSettings(properties, scopeName)

Hook to get Customizations settings from Customizations singleton or CustomizerContext. It will trigger component state update on settings change observed.

useFocusRects(rootRef)

Initializes the logic which:

  1. Subscribes keydown and mousedown events. (It will only do it once per window, so it's safe to call this method multiple times.) 2. When the user presses directional keyboard keys, adds the 'ms-Fabric--isFocusVisible' classname to the document body, removes the 'ms-Fabric-isFocusHidden' classname. 3. When the user clicks a mouse button, adds the 'ms-Fabric-isFocusHidden' classname to the document body, removes the 'ms-Fabric--isFocusVisible' classname.

This logic allows components on the page to conditionally render focus treatments based on the existence of global classnames, which simplifies logic overall.

values(obj)

Get all values in an object dictionary

warn(message)

Sends a warning to console, if the api is present.

warnConditionallyRequiredProps(componentName, props, requiredProps, conditionalPropName, condition)

Warns when props are required if a condition is met.

warnControlledUsage(params)

Check for and warn on the following error conditions with a form component: - A value prop is provided (indicated it's being used as controlled) without a change handler, and the component is not read-only - Both the value and defaultValue props are provided - The component is attempting to switch between controlled and uncontrolled

The messages mimic the warnings React gives for these error conditions on input elements. The warning will only be displayed once per component ID.

warnDeprecations(componentName, props, deprecationMap)

Warns when a deprecated props are being used.

warnMutuallyExclusive(componentName, props, exclusiveMap)

Warns when two props which are mutually exclusive are both being used.

Function Details

addDirectionalKeyCode(which)

Adds a keycode to the list of keys that, when pressed, should cause the focus outlines to be visible. This can be used to add global shortcut keys that directionally move from section to section within an app or between focus trap zones.

export declare function addDirectionalKeyCode(which: number): void;

Parameters

which

number

Returns

void

addElementAtIndex(array, index, itemToAdd)

Given an array, this function returns a new array where an element has been inserted at the given index.

export declare function addElementAtIndex<T>(array: T[], index: number, itemToAdd: T): T[];

Parameters

array

T[]

The array to operate on

index

number

The index where an element should be inserted

itemToAdd

T

The element to insert

Returns

T[]

appendFunction(parent, functions)

Returns a single function which will call each of the given functions in the context of the parent.

export declare function appendFunction(parent: any, ...functions: any[]): () => void;

Parameters

parent

any

functions

any[]

Returns

() => void

arraysEqual(array1, array2)

Returns a boolean indicating if the two given arrays are equal in length and values.

export declare function arraysEqual<T>(array1: T[], array2: T[]): boolean;

Parameters

array1

T[]

First array to compare

array2

T[]

Second array to compare

Returns

boolean

True if the arrays are the same length and have the same values in the same positions, false otherwise.

asAsync(options)

Produces a component which internally loads the target component before first mount. The component passes all props through to the loaded component.

This overload accepts a module with a default export for the component.

export declare function asAsync<TProps>(options: IAsAsyncOptions<TProps>): React.ForwardRefExoticComponent<React.PropsWithoutRef<TProps & {
    asyncPlaceholder?: "symbol" | "object" | "text" | "table" | "ruby" | "small" | "input" | "progress" | "select" | "a" | "abbr" | "address" | "area" | "article" | "aside" | "audio" | "b" | "base" | "bdi" | "bdo" | "blockquote" | "body" | "br" | "button" | "canvas" | "caption" | "cite" | "code" | "col" | "colgroup" | "data" | "datalist" | "dd" | "del" | "details" | "dfn" | "dialog" | "div" | "dl" | "dt" | "em" | "embed" | "fieldset" | "figcaption" | "figure" | "footer" | "form" | "h1" | "h2" | "h3" | "h4" | "h5" | "h6" | "head" | "header" | "hgroup" | "hr" | "html" | "i" | "iframe" | "img" | "ins" | "kbd" | "label" | "legend" | "li" | "link" | "main" | "map" | "mark" | "menu" | "meta" | "meter" | "nav" | "noscript" | "ol" | "optgroup" | "option" | "output" | "p" | "param" | "picture" | "pre" | "q" | "rp" | "rt" | "s" | "samp" | "script" | "section" | "slot" | "source" | "span" | "strong" | "style" | "sub" | "summary" | "sup" | "tbody" | "td" | "template" | "textarea" | "tfoot" | "th" | "thead" | "time" | "title" | "tr" | "track" | "u" | "ul" | "var" | "video" | "wbr" | "big" | React.ComponentClass<any, any> | React.FunctionComponent<any> | "keygen" | "menuitem" | "noindex" | "webview" | "svg" | "animate" | "animateMotion" | "animateTransform" | "circle" | "clipPath" | "defs" | "desc" | "ellipse" | "feBlend" | "feColorMatrix" | "feComponentTransfer" | "feComposite" | "feConvolveMatrix" | "feDiffuseLighting" | "feDisplacementMap" | "feDistantLight" | "feDropShadow" | "feFlood" | "feFuncA" | "feFuncB" | "feFuncG" | "feFuncR" | "feGaussianBlur" | "feImage" | "feMerge" | "feMergeNode" | "feMorphology" | "feOffset" | "fePointLight" | "feSpecularLighting" | "feSpotLight" | "feTile" | "feTurbulence" | "filter" | "foreignObject" | "g" | "image" | "line" | "linearGradient" | "marker" | "mask" | "metadata" | "mpath" | "path" | "pattern" | "polygon" | "polyline" | "radialGradient" | "rect" | "stop" | "switch" | "textPath" | "tspan" | "use" | "view" | undefined;
}> & React.RefAttributes<React.ElementType<TProps>>>;

Parameters

options

IAsAsyncOptions<TProps>

Returns

React.ForwardRefExoticComponent<React.PropsWithoutRef<TProps & { asyncPlaceholder?: "symbol" | "object" | "text" | "table" | "ruby" | "small" | "input" | "progress" | "select" | "a" | "abbr" | "address" | "area" | "article" | "aside" | "audio" | "b" | "base" | "bdi" | "bdo" | "blockquote" | "body" | "br" | "button" | "canvas" | "caption" | "cite" | "code" | "col" | "colgroup" | "data" | "datalist" | "dd" | "del" | "details" | "dfn" | "dialog" | "div" | "dl" | "dt" | "em" | "embed" | "fieldset" | "figcaption" | "figure" | "footer" | "form" | "h1" | "h2" | "h3" | "h4" | "h5" | "h6" | "head" | "header" | "hgroup" | "hr" | "html" | "i" | "iframe" | "img" | "ins" | "kbd" | "label" | "legend" | "li" | "link" | "main" | "map" | "mark" | "menu" | "meta" | "meter" | "nav" | "noscript" | "ol" | "optgroup" | "option" | "output" | "p" | "param" | "picture" | "pre" | "q" | "rp" | "rt" | "s" | "samp" | "script" | "section" | "slot" | "source" | "span" | "strong" | "style" | "sub" | "summary" | "sup" | "tbody" | "td" | "template" | "textarea" | "tfoot" | "th" | "thead" | "time" | "title" | "tr" | "track" | "u" | "ul" | "var" | "video" | "wbr" | "big" | React.ComponentClass<any, any> | React.FunctionComponent<any> | "keygen" | "menuitem" | "noindex" | "webview" | "svg" | "animate" | "animateMotion" | "animateTransform" | "circle" | "clipPath" | "defs" | "desc" | "ellipse" | "feBlend" | "feColorMatrix" | "feComponentTransfer" | "feComposite" | "feConvolveMatrix" | "feDiffuseLighting" | "feDisplacementMap" | "feDistantLight" | "feDropShadow" | "feFlood" | "feFuncA" | "feFuncB" | "feFuncG" | "feFuncR" | "feGaussianBlur" | "feImage" | "feMerge" | "feMergeNode" | "feMorphology" | "feOffset" | "fePointLight" | "feSpecularLighting" | "feSpotLight" | "feTile" | "feTurbulence" | "filter" | "foreignObject" | "g" | "image" | "line" | "linearGradient" | "marker" | "mask" | "metadata" | "mpath" | "path" | "pattern" | "polygon" | "polyline" | "radialGradient" | "rect" | "stop" | "switch" | "textPath" | "tspan" | "use" | "view" | undefined; }> & React.RefAttributes<React.ElementType<TProps>>>

assertNever(x)

AssertNever is a utility function that can be used for exhaustiveness checks in switch statements.

export declare function assertNever(x: never): never;

Parameters

x

never

Returns

never

assign(this, target, args)

Makes a resulting merge of a bunch of objects. Pass in the target object followed by 1 or more objects as arguments and they will be merged sequentially into the target. Note that this will shallow merge; it will not create new cloned values for target members.

export declare function assign(this: any, target: any, ...args: any[]): any;

Parameters

this

any

target

any

Target object to merge following object arguments into.

args

any[]

One or more objects that will be mixed into the target in the order they are provided.

Returns

any

Resulting merged target.

calculatePrecision(value)

Calculates a number's precision based on the number of trailing zeros if the number does not have a decimal indicated by a negative precision. Otherwise, it calculates the number of digits after the decimal point indicated by a positive precision.

export declare function calculatePrecision(value: number | string): number;

Parameters

value

number | string

the value to determine the precision of

Returns

number

classNamesFunction(options)

Creates a getClassNames function which calls getStyles given the props, and injects them into mergeStyleSets.

Note that the props you pass in on every render should be in the same order and immutable (numbers, strings, and booleans). This will allow the results to be memoized. Violating these will cause extra recalcs to occur.

export declare function classNamesFunction<TStyleProps extends {}, TStyleSet extends IStyleSet<TStyleSet>>(options?: IClassNamesFunctionOptions): (getStyles: IStyleFunctionOrObject<TStyleProps, TStyleSet> | undefined, styleProps?: TStyleProps) => IProcessedStyleSet<TStyleSet>;

Parameters

Returns

(getStyles: IStyleFunctionOrObject<TStyleProps, TStyleSet> | undefined, styleProps?: TStyleProps) => IProcessedStyleSet<TStyleSet>

composeComponentAs(outer, inner)

Composes two components which conform to the IComponentAs specification; that is, two components which accept a defaultRender prop, which is a 'default' implementation of a component which accepts the same overall props.

export declare function composeComponentAs<TProps>(outer: IComponentAs<TProps>, inner: IComponentAs<TProps>): IComponentAs<TProps>;

Parameters

outer

IComponentAs<TProps>

inner

IComponentAs<TProps>

Returns

IComponentAs<TProps>

composeRenderFunction(outer, inner)

Composes two 'render functions' to produce a final render function that renders the outer function, passing the inner function as 'default render'. The inner function is then passed the original 'default render' prop.

export declare function composeRenderFunction<TProps>(outer: IRenderFunction<TProps>, inner: IRenderFunction<TProps>): IRenderFunction<TProps>;

Parameters

outer

IRenderFunction<TProps>

inner

IRenderFunction<TProps>

Returns

IRenderFunction<TProps>

createArray(size, getItem)

Creates an array of a given size and helper method to populate.

export declare function createArray<T>(size: number, getItem: (index: number) => T): T[];

Parameters

size

number

Size of array.

getItem

(index: number) => T

Callback to populate given cell index.

Returns

T[]

createMemoizer(getValue)

Creates a memoizer for a single-value function, backed by a WeakMap. With a WeakMap, the memoized values are only kept as long as the source objects, ensuring that there is no memory leak.

This function assumes that the input values passed to the wrapped function will be function or object types. To memoize functions which accept other inputs, use memoizeFunction, which memoizes against arbitrary inputs using a lookup cache.

export declare function createMemoizer<F extends (input: any) => any>(getValue: F): F;

Parameters

getValue

F

Returns

F

css(args)

Concatination helper, which can merge class names together. Skips over falsey values.

export declare function css(...args: ICssInput[]): string;

Parameters

args

ICssInput[]

Returns

string

customizable(scope, fields, concatStyles)

export declare function customizable(scope: string, fields: string[], concatStyles?: boolean): <P>(ComposedComponent: React.ComponentType<P>) => any;

Parameters

scope

string

fields

string[]

concatStyles

boolean

Returns

<P>(ComposedComponent: React.ComponentType<P>) => any

disableBodyScroll()

Disables the body scrolling.

export declare function disableBodyScroll(): void;

Returns

void

doesElementContainFocus(element)

Determines if an element, or any of its children, contain focus.

export declare function doesElementContainFocus(element: HTMLElement): boolean;

Parameters

element

HTMLElement

Returns

boolean

enableBodyScroll()

Enables the body scrolling.

export declare function enableBodyScroll(): void;

Returns

void

extendComponent(parent, methods)

Extends a component's lifetime methods by appending new functions to the existing lifetime functions.

export declare function extendComponent<T extends React.Component>(parent: T, methods: {
    [key in keyof T]?: T[key];
}): void;

Parameters

parent

T

methods

{ [key in keyof T]?: T[key]; }

Returns

void

filteredAssign(isAllowed, target, args)

Makes a resulting merge of a bunch of objects, but allows a filter function to be passed in to filter the resulting merges. This allows for scenarios where you want to merge "everything except that one thing" or "properties that start with data-". Note that this will shallow merge; it will not create new cloned values for target members.

export declare function filteredAssign(isAllowed: (propName: string) => boolean, target: any, ...args: any[]): any;

Parameters

isAllowed

(propName: string) => boolean

Callback to determine if the given propName is allowed in the result.

target

any

Target object to merge following object arguments into.

args

any[]

One or more objects that will be mixed into the target in the order they are provided.

Returns

any

Resulting merged target.

find(array, cb)

Helper to find the first item within an array that satisfies the callback.

export declare function find<T>(array: T[], cb: (item: T, index: number) => boolean): T | undefined;

Parameters

array

T[]

Array to search

cb

(item: T, index: number) => boolean

Callback which returns true on matches

Returns

T | undefined

findIndex(array, cb, fromIndex)

Helper to find the index of an item within an array, using a callback to determine the match.

export declare function findIndex<T>(array: T[], cb: (item: T, index: number) => boolean, fromIndex?: number): number;

Parameters

array

T[]

Array to search.

cb

(item: T, index: number) => boolean

Callback which returns true on matches.

fromIndex

number

Optional index to start from (defaults to 0)

Returns

number

findScrollableParent(startingElement)

Traverses up the DOM for the element with the data-is-scrollable=true attribute, or returns document.body.

export declare function findScrollableParent(startingElement: HTMLElement | null): HTMLElement | Window | undefined | null;

Parameters

startingElement

HTMLElement | null

Returns

HTMLElement | Window | undefined | null

fitContentToBounds(options)

Produces a proportionally-scaled version of an input content size when fit to a bounding size. Given a contentSize and a boundsSize, this function scales contentSize proportionally using either contain or cover fit behaviors. Use this function to pre-calculate the layout for the CSS object-fit and background-fit behaviors. With contain, the output size must be the largest it can be while completely within the boundsSize. With cover, the output size must be the smallest it can be while completely around the boundsSize. By default, there is a maxScale value of 1, which prevents the contentSize from being scaled larger.

export declare function fitContentToBounds(options: IFitContentToBoundsOptions): ISize;

Parameters

options
IFitContentToBoundsOptions

the options for the bounds fit operation

Returns

flatten(array)

Given an array where each element is of type T or T[], flatten it into an array of T

export declare function flatten<T>(array: (T | T[])[]): T[];

Parameters

array

(T | T[])[]

The array where each element can optionally also be an array

Returns

T[]

focusAsync(element)

Sets focus to an element asynchronously. The focus will be set at the next browser repaint, meaning it won't cause any extra recalculations. If more than one focusAsync is called during one frame, only the latest called focusAsync element will actually be focused

export declare function focusAsync(element: HTMLElement | {
    focus: () => void;
} | undefined | null): void;

Parameters

element

HTMLElement | { focus: () => void; } | undefined | null

The element to focus

Returns

void

focusFirstChild(rootElement)

Attempts to focus the first focusable element that is a child or child's child of the rootElement.

export declare function focusFirstChild(rootElement: HTMLElement): boolean;

Parameters

rootElement

HTMLElement

Element to start the search for a focusable child.

Returns

boolean

True if focus was set, false if it was not.

format(s, values)

String format method, used for scenarios where at runtime you need to evaluate a formatted string given a tokenized string. This usually only is needed in localization scenarios.

export declare function format(s: string, ...values: any[]): string;

Parameters

s

string

values

any[]

Returns

string

getDistanceBetweenPoints(point1, point2)

Determines the distance between two points.

export declare function getDistanceBetweenPoints(point1: Point, point2: Point): number;

Parameters

point1
Point
point2
Point

Returns

number

getDocument(rootElement)

Helper to get the document object. Note that in popup window cases, document might be the wrong document, which is why we look at ownerDocument for the truth. Also note that the SSR flag is used to test ssr scenarios even if document is defined (from JSDOM for example.)

export declare function getDocument(rootElement?: HTMLElement | null): Document | undefined;

Parameters

rootElement

HTMLElement | null

Returns

Document | undefined

getElementIndexPath(fromElement, toElement)

Finds the element index path from a parent element to a child element.

If you had this node structure: "A has children [B, C] and C has child D", the index path from A to D would be [1, 0], or parent.chidren[1].children[0].

export declare function getElementIndexPath(fromElement: HTMLElement, toElement: HTMLElement): number[];

Parameters

fromElement

HTMLElement

toElement

HTMLElement

Returns

number[]

getFirstFocusable(rootElement, currentElement, includeElementsInFocusZones)

Gets the first focusable element.

export declare function getFirstFocusable(rootElement: HTMLElement, currentElement: HTMLElement, includeElementsInFocusZones?: boolean): HTMLElement | null;

Parameters

rootElement

HTMLElement

currentElement

HTMLElement

includeElementsInFocusZones

boolean

Returns

HTMLElement | null

getFirstTabbable(rootElement, currentElement, includeElementsInFocusZones, checkNode)

Gets the first tabbable element. (The difference between focusable and tabbable is that tabbable elements are focusable elements that also have tabIndex != -1.)

export declare function getFirstTabbable(rootElement: HTMLElement, currentElement: HTMLElement, includeElementsInFocusZones?: boolean, checkNode?: boolean): HTMLElement | null;

Parameters

rootElement

HTMLElement

The parent element to search beneath.

currentElement

HTMLElement

The descendant of rootElement to start the search at. This element is the first one checked, and iteration continues forward. Typical use passes rootElement.firstChild.

includeElementsInFocusZones

boolean

true if traversal should go into FocusZone descendants.

checkNode

boolean

Include currentElement in search when true. Defaults to true.

Returns

HTMLElement | null

getFocusableByIndexPath(parent, path)

Finds the closest focusable element via an index path from a parent. See getElementIndexPath for getting an index path from an element to a child.

export declare function getFocusableByIndexPath(parent: HTMLElement, path: number[]): HTMLElement | undefined;

Parameters

parent

HTMLElement

path

number[]

Returns

HTMLElement | undefined

getId(prefix)

Generates a unique id in the global scope (this spans across duplicate copies of the same library.)

export declare function getId(prefix?: string): string;

Parameters

prefix

string

Returns

string

getInitials(displayName, isRtl, allowPhoneInitials)

Get (up to 2 characters) initials based on display name of the persona.

export declare function getInitials(displayName: string | undefined | null, isRtl: boolean, allowPhoneInitials?: boolean): string;

Parameters

displayName

string | undefined | null

isRtl

boolean

allowPhoneInitials

boolean

Returns

string

getLanguage(persistenceType)

Gets the language set for the page.

export declare function getLanguage(persistenceType?: 'localStorage' | 'sessionStorage' | 'none'): string | null;

Parameters

persistenceType

'localStorage' | 'sessionStorage' | 'none'

Where to persist the value. Default is sessionStorage if available.

Returns

string | null

getLastFocusable(rootElement, currentElement, includeElementsInFocusZones)

Gets the last focusable element.

export declare function getLastFocusable(rootElement: HTMLElement, currentElement: HTMLElement, includeElementsInFocusZones?: boolean): HTMLElement | null;

Parameters

rootElement

HTMLElement

currentElement

HTMLElement

includeElementsInFocusZones

boolean

Returns

HTMLElement | null

getLastTabbable(rootElement, currentElement, includeElementsInFocusZones, checkNode)

Gets the last tabbable element. (The difference between focusable and tabbable is that tabbable elements are focusable elements that also have tabIndex != -1.)

export declare function getLastTabbable(rootElement: HTMLElement, currentElement: HTMLElement, includeElementsInFocusZones?: boolean, checkNode?: boolean): HTMLElement | null;

Parameters

rootElement

HTMLElement

The parent element to search beneath.

currentElement

HTMLElement

The descendant of rootElement to start the search at. This element is the first one checked, and iteration continues in reverse. Typical use passes rootElement.lastChild.

includeElementsInFocusZones

boolean

true if traversal should go into FocusZone descendants.

checkNode

boolean

Include currentElement in search when true. Defaults to true.

Returns

HTMLElement | null

getNativeElementProps(tagName, props, excludedPropNames)

Given an element tagname and user props, filters the props to only allowed props for the given element type.

export declare function getNativeElementProps<TAttributes extends React.HTMLAttributes<any>>(tagName: string, props: {}, excludedPropNames?: string[]): TAttributes;

Parameters

tagName

string

Tag name (e.g. "div")

props

{}

Props object

excludedPropNames

string[]

List of props to disallow

Returns

TAttributes

getNativeProps(props, allowedPropNames, excludedPropNames)

Gets native supported props for an html element provided the allowance set. Use one of the property sets defined (divProperties, buttonPropertes, etc) to filter out supported properties from a given props set. Note that all data- and aria- prefixed attributes will be allowed. NOTE: getNativeProps should always be applied first when adding props to a react component. The non-native props should be applied second. This will prevent getNativeProps from overriding your custom props. For example, if props passed to getNativeProps has an onClick function and getNativeProps is added to the component after an onClick function is added, then the getNativeProps onClick will override it.

export declare function getNativeProps<T extends Record<string, any>>(props: Record<string, any>, allowedPropNames: string[] | Record<string, number>, excludedPropNames?: string[]): T;

Parameters

props

Record<string, any>

The unfiltered input props

allowedPropNames

string[] | Record<string, number>

excludedPropNames

string[]

Returns

T

The filtered props

getNextElement(rootElement, currentElement, checkNode, suppressParentTraversal, suppressChildTraversal, includeElementsInFocusZones, allowFocusRoot, tabbable)

Traverse to find the next focusable element. If tabbable is true, the element must have tabIndex != -1.

export declare function getNextElement(rootElement: HTMLElement, currentElement: HTMLElement | null, checkNode?: boolean, suppressParentTraversal?: boolean, suppressChildTraversal?: boolean, includeElementsInFocusZones?: boolean, allowFocusRoot?: boolean, tabbable?: boolean): HTMLElement | null;

Parameters

rootElement

HTMLElement

currentElement

HTMLElement | null

checkNode

boolean

Include currentElement in search when true.

suppressParentTraversal

boolean

suppressChildTraversal

boolean

includeElementsInFocusZones

boolean

allowFocusRoot

boolean

tabbable

boolean

Returns

HTMLElement | null

getPreviousElement(rootElement, currentElement, checkNode, suppressParentTraversal, traverseChildren, includeElementsInFocusZones, allowFocusRoot, tabbable)

Traverse to find the previous element. If tabbable is true, the element must have tabIndex != -1.

export declare function getPreviousElement(rootElement: HTMLElement, currentElement: HTMLElement | null, checkNode?: boolean, suppressParentTraversal?: boolean, traverseChildren?: boolean, includeElementsInFocusZones?: boolean, allowFocusRoot?: boolean, tabbable?: boolean): HTMLElement | null;

Parameters

rootElement

HTMLElement

currentElement

HTMLElement | null

checkNode

boolean

suppressParentTraversal

boolean

traverseChildren

boolean

includeElementsInFocusZones

boolean

allowFocusRoot

boolean

tabbable

boolean

Returns

HTMLElement | null

getPropsWithDefaults(defaultProps, propsWithoutDefaults)

Function to apply default values to a component props object. This function is intended for function components, to maintain parity with the defaultProps feature of class components. It accounts for properties that are specified, but undefined.

export declare function getPropsWithDefaults<TProps extends {}>(defaultProps: Partial<TProps>, propsWithoutDefaults: TProps): TProps;

Parameters

defaultProps

Partial<TProps>

An object with default values for various properties

propsWithoutDefaults

TProps

The props object passed into the component

Returns

TProps

getRect(element)

Helper to get bounding client rect. Passing in window will get the window size.

export declare function getRect(element: HTMLElement | Window | null): IRectangle | undefined;

Parameters

element

HTMLElement | Window | null

Returns

IRectangle | undefined

getResourceUrl(url)

Sets the current base url used for fetching images.

export declare function getResourceUrl(url: string): string;

Parameters

url

string

Returns

string

getRTL(theme)

Gets the rtl state of the page (returns true if in rtl.)

export declare function getRTL(theme?: {
    rtl?: boolean;
}): boolean;

Parameters

theme

{ rtl?: boolean; }

Returns

boolean

getRTLSafeKeyCode(key, theme)

Returns the given key, but flips right/left arrows if necessary.

export declare function getRTLSafeKeyCode(key: number, theme?: {
    rtl?: boolean;
}): number;

Parameters

key

number

theme

{ rtl?: boolean; }

Returns

number

getScrollbarWidth()

Calculates the width of a scrollbar for the browser/os.

export declare function getScrollbarWidth(): number;

Returns

number

getWindow(rootElement)

Helper to get the window object. The helper will make sure to use a cached variable of "window", to avoid overhead and memory leaks in IE11. Note that in popup scenarios the window object won't match the "global" window object, and for these scenarios, you should pass in an element hosted within the popup.

export declare function getWindow(rootElement?: Element | null): Window | undefined;

Parameters

rootElement

Element | null

Returns

Window | undefined

hasHorizontalOverflow(element)

Detects whether an element's content has horizontal overflow

export declare function hasHorizontalOverflow(element: HTMLElement): boolean;

Parameters

element

HTMLElement

Element to check for overflow

Returns

boolean

True if element's content overflows

hasOverflow(element)

Detects whether an element's content has overflow in any direction

export declare function hasOverflow(element: HTMLElement): boolean;

Parameters

element

HTMLElement

Element to check for overflow

Returns

boolean

True if element's content overflows

hasVerticalOverflow(element)

Detects whether an element's content has vertical overflow

export declare function hasVerticalOverflow(element: HTMLElement): boolean;

Parameters

element

HTMLElement

Element to check for overflow

Returns

boolean

True if element's content overflows

hoistMethods(destination, source, exclusions)

Allows you to hoist methods, except those in an exclusion set from a source object into a destination object.

export declare function hoistMethods(destination: any, source: any, exclusions?: string[]): string[];

Parameters

destination

any

The instance of the object to hoist the methods onto.

source

any

The instance of the object where the methods are hoisted from.

exclusions

string[]

(Optional) What methods to exclude from being hoisted.

Returns

string[]

An array of names of methods that were hoisted.

hoistStatics(source, dest)

Allows you to hoist static functions in components. Created for the purpose of fixing broken static functions in classes that utilize decorators.

export declare function hoistStatics<TSource extends Object, TDest>(source: TSource, dest: TDest): TDest;

Parameters

source

TSource

The object where the methods are hoisted from.

dest

TDest

The object to hoist the methods onto.

Returns

TDest

The dest object with methods added

initializeComponentRef(obj)

Helper to manage componentRef resolution. Internally appends logic to lifetime methods to resolve componentRef to the passed in object.

Usage: call initializeComponentRef(this) in the constructor,

export declare function initializeComponentRef<TProps extends IBaseProps, TState>(obj: React.Component<TProps, TState>): void;

Parameters

obj

React.Component<TProps, TState>

Returns

void

initializeFocusRects(window)

Warning

This API is now deprecated.

Use useFocusRects hook or FocusRects component instead.

Initializes the logic which:

  1. Subscribes keydown and mousedown events. (It will only do it once per window, so it's safe to call this method multiple times.) 2. When the user presses directional keyboard keys, adds the 'ms-Fabric--isFocusVisible' classname to the document body, removes the 'ms-Fabric-isFocusHidden' classname. 3. When the user clicks a mouse button, adds the 'ms-Fabric-isFocusHidden' classname to the document body, removes the 'ms-Fabric--isFocusVisible' classname.

This logic allows components on the page to conditionally render focus treatments based on the existence of global classnames, which simplifies logic overall.

export declare function initializeFocusRects(window?: Window): void;

Parameters

window

Window

the window used to add the event listeners

Returns

void

isControlled(props, valueProp)

Determines whether a component is controlled.

export declare function isControlled<P>(props: P, valueProp: keyof P): boolean;

Parameters

props

P

Component props

valueProp

keyof P

Prop containing the controlled value

Returns

boolean

true if controlled, false if uncontrolled

isDirectionalKeyCode(which)

Returns true if the keycode is a directional keyboard key.

export declare function isDirectionalKeyCode(which: number): boolean;

Parameters

which

number

Returns

boolean

isElementFocusSubZone(element)

Determines if a given element is a focus sub zone.

export declare function isElementFocusSubZone(element?: HTMLElement): boolean;

Parameters

element

HTMLElement

Returns

boolean

isElementFocusZone(element)

Determines if a given element is a focus zone.

export declare function isElementFocusZone(element?: HTMLElement): boolean;

Parameters

element

HTMLElement

Returns

boolean

isElementTabbable(element, checkTabIndex)

Determines if an element can receive focus programmatically or via a mouse click. If checkTabIndex is true, additionally checks to ensure the element can be focused with the tab key, meaning tabIndex != -1.

export declare function isElementTabbable(element: HTMLElement, checkTabIndex?: boolean): boolean;

Parameters

element

HTMLElement

checkTabIndex

boolean

Returns

boolean

isElementVisible(element)

Determines if an element is visible.

export declare function isElementVisible(element: HTMLElement | undefined | null): boolean;

Parameters

element

HTMLElement | undefined | null

Returns

boolean

isMac(reset)

Returns true if the user is on a Mac. Caches the result value.

export declare function isMac(reset?: boolean): boolean;

Parameters

reset

boolean

Reset the cached result value (mainly for testing).

Returns

boolean

mapEnumByName(theEnum, callback)

Takes an enum and iterates over each value of the enum (as a string), running the callback on each, returning a mapped array.

export declare function mapEnumByName<T>(theEnum: any, callback: (name?: string, value?: string | number) => T | undefined): (T | undefined)[] | undefined;

Parameters

theEnum

any

Enum to iterate over

callback

(name?: string, value?: string | number) => T | undefined

The first parameter the name of the entry, and the second parameter is the value of that entry, which is the value you'd normally use when using the enum (usually a number).

Returns

(T | undefined)[] | undefined

memoize(target, key, descriptor)

Memoize decorator to be used on class methods. WARNING: the this reference will be inaccessible within a memoized method, given that a cached method's this would not be instance-specific.

export declare function memoize<T extends Function>(target: any, key: string, descriptor: TypedPropertyDescriptor<T>): {
    configurable: boolean;
    get(): T;
};

Parameters

target

any

key

string

descriptor

TypedPropertyDescriptor<T>

Returns

{ configurable: boolean; get(): T; }

memoizeFunction(cb, maxCacheSize, ignoreNullOrUndefinedResult)

Memoizes a function; when you pass in the same parameters multiple times, it returns a cached result. Be careful when passing in objects, you need to pass in the same INSTANCE for caching to work. Otherwise it will grow the cache unnecessarily. Also avoid using default values that evaluate functions; passing in undefined for a value and relying on a default function will execute it the first time, but will not re-evaluate subsequent times which may have been unexpected.

By default, the cache will reset after 100 permutations, to avoid abuse cases where the function is unintendedly called with unique objects. Without a reset, the cache could grow infinitely, so we safeguard by resetting. To override this behavior, pass a value of 0 to the maxCacheSize parameter.

export declare function memoizeFunction<T extends (...args: any[]) => RetType, RetType>(cb: T, maxCacheSize?: number, ignoreNullOrUndefinedResult?: boolean): T;

Parameters

cb

T

The function to memoize.

maxCacheSize

number

Max results to cache. If the cache exceeds this value, it will reset on the next call.

ignoreNullOrUndefinedResult

boolean

Flag to decide whether to cache callback result if it is undefined/null. If the flag is set to true, the callback result is recomputed every time till the callback result is not undefined/null for the first time, and then the non-undefined/null version gets cached.

Returns

T

A memoized version of the function.

merge(target, args)

Simple deep merge function. Takes all arguments and returns a deep copy of the objects merged together in the order provided. If an object creates a circular reference, it will assign the original reference.

export declare function merge<T = {}>(target: Partial<T>, ...args: (Partial<T> | null | undefined | false)[]): T;

Parameters

target

Partial<T>

args

(Partial<T> | null | undefined | false)[]

Returns

T

mergeAriaAttributeValues(ariaAttributes)

ARIA helper to concatenate attributes, returning undefined if all attributes are undefined. (Empty strings are not a valid ARIA attribute value.)

export declare function mergeAriaAttributeValues(...ariaAttributes: (string | undefined | false)[]): string | undefined;

Parameters

ariaAttributes

(string | undefined | false)[]

ARIA attributes to merge

Returns

string | undefined

mergeCustomizations(props, parentContext)

Merge props and customizations giving priority to props over context. NOTE: This function will always perform multiple merge operations. Use with caution.

export declare function mergeCustomizations(props: ICustomizerProps, parentContext: ICustomizerContext): ICustomizerContext;

Parameters

props

ICustomizerProps

New settings to merge in.

parentContext
ICustomizerContext

Context containing current settings.

Returns

Merged customizations.

mergeScopedSettings(oldSettings, newSettings)

export declare function mergeScopedSettings(oldSettings?: ISettings, newSettings?: ISettings | ISettingsFunction): ISettings;

Parameters

oldSettings

ISettings

newSettings

ISettings | ISettingsFunction

Returns

ISettings

mergeSettings(oldSettings, newSettings)

Merge new and old settings, giving priority to new settings. New settings is optional in which case oldSettings is returned as-is.

export declare function mergeSettings(oldSettings?: ISettings, newSettings?: ISettings | ISettingsFunction): ISettings;

Parameters

oldSettings

ISettings

Old settings to fall back to.

newSettings

ISettings | ISettingsFunction

New settings that will be merged over oldSettings.

Returns

ISettings

Merged settings.

modalize(target)

Call this on a target element to make it modal to screen readers. Returns a function that undoes the changes it made.

export declare function modalize(target: HTMLElement): () => void;

Parameters

target

HTMLElement

Returns

() => void

nullRender()

Simple constant function for returning null, used to render empty templates in JSX.

export declare function nullRender(): JSX.Element | null;

Returns

JSX.Element | null

omit(obj, exclusions)

Tiny helper to do the minimal amount of work in duplicating an object but omitting some props. This ends up faster than using object ...rest or reduce to filter.

This behaves very much like filteredAssign, but does not merge many objects together, uses an exclusion object map, and avoids spreads all for optimal performance.

See perf test for background: https://jsperf.com/omit-vs-rest-vs-reduce/1

export declare function omit<TObj extends Record<string, any>>(obj: TObj, exclusions: (keyof TObj)[]): TObj;

Parameters

obj

TObj

The object to clone

exclusions

(keyof TObj)[]

The array of keys to exclude

Returns

TObj

on(element, eventName, callback, options)

export declare function on(element: Element | Window | Document, eventName: string, callback: (ev: Event) => void, options?: boolean): () => void;

Parameters

element

Element | Window | Document

eventName

string

callback

(ev: Event) => void

options

boolean

Returns

() => void

precisionRound(value, precision, base)

Rounds a number to a certain level of precision. Accepts negative precision.

export declare function precisionRound(value: number, precision: number, base?: number): number;

Parameters

value

number

The value that is being rounded.

precision

number

The number of decimal places to round the number to

base

number

Returns

number

raiseClick(target)

Raises a click event.

export declare function raiseClick(target: Element): void;

Parameters

target

Element

Returns

void

removeIndex(array, index)

Given an array, it returns a new array that does not contain the item at the given index.

export declare function removeIndex<T>(array: T[], index: number): T[];

Parameters

array

T[]

The array to operate on

index

number

The index of the element to remove

Returns

T[]

replaceElement(array, newElement, index)

Given an array, this function returns a new array where the element at a given index has been replaced.

export declare function replaceElement<T>(array: T[], newElement: T, index: number): T[];

Parameters

array

T[]

The array to operate on

newElement

T

The element that will be placed in the new array

index

number

The index of the element that should be replaced

Returns

T[]

resetControlledWarnings()

Reset controlled usage warnings for testing purposes.

export declare function resetControlledWarnings(): void;

Returns

void

resetIds(counter)

Resets id counter to an (optional) number.

export declare function resetIds(counter?: number): void;

Parameters

counter

number

Returns

void

resetMemoizations()

Reset memoizations.

export declare function resetMemoizations(): void;

Returns

void

setBaseUrl(baseUrl)

Gets the current base url used for fetching images.

export declare function setBaseUrl(baseUrl: string): void;

Parameters

baseUrl

string

Returns

void

setFocusVisibility(enabled, target)

Sets the visibility of focus styling.

By default, focus styles (the box surrounding a focused Button, for example) only show up when navigational keypresses occur (through Tab, arrows, PgUp/PgDn, Home and End), and are hidden when mouse interactions occur. This API provides an imperative way to turn them on/off.

A use case might be when you have a keypress like ctrl-f6 navigate to a particular region on the page, and want focus to show up.

export declare function setFocusVisibility(enabled: boolean, target?: Element): void;

Parameters

enabled

boolean

whether to remove or add focus

target

Element

optional target

Returns

void

setLanguage(language, persistenceType)

Sets the language for the page (by adjusting the lang attribute of the html element).

export declare function setLanguage(language: string, persistenceType?: 'localStorage' | 'sessionStorage' | 'none'): void;

Parameters

language

string

Language to set.

persistenceType

'localStorage' | 'sessionStorage' | 'none'

Where to persist the value. Default is sessionStorage if available.

Returns

void

setLanguage(language, avoidPersisting)

Warning

This API is now deprecated.

Use string parameter version.

Sets the language for the page (by adjusting the lang attribute of the html element).

export declare function setLanguage(language: string, avoidPersisting?: boolean): void;

Parameters

language

string

Language to set.

avoidPersisting

boolean

If true, don't store the value.

Returns

void

setRTL(isRTL, persistSetting)

Sets the rtl state of the page (by adjusting the dir attribute of the html element.)

export declare function setRTL(isRTL: boolean, persistSetting?: boolean): void;

Parameters

isRTL

boolean

persistSetting

boolean

Returns

void

setSSR(isEnabled)

Helper to set ssr mode to simulate no window object returned from getWindow helper.

export declare function setSSR(isEnabled: boolean): void;

Parameters

isEnabled

boolean

Returns

void

setWarningCallback(warningCallback)

Configures the warning callback. Passing in undefined will reset it to use the default console.warn function.

export declare function setWarningCallback(warningCallback?: (message: string) => void): void;

Parameters

warningCallback

(message: string) => void

Callback to override the generated warnings.

Returns

void

shallowCompare(a, b)

Compares a to b and b to a.

export declare function shallowCompare<TA extends any, TB extends any>(a: TA, b: TB): boolean;

Parameters

a

TA

b

TB

Returns

boolean

shouldWrapFocus(element, noWrapDataAttribute)

Determines if an, or any of its ancestors, sepcificies that it doesn't want focus to wrap

export declare function shouldWrapFocus(element: HTMLElement, noWrapDataAttribute: 'data-no-vertical-wrap' | 'data-no-horizontal-wrap'): boolean;

Parameters

element

HTMLElement

element to start searching from

noWrapDataAttribute

'data-no-vertical-wrap' | 'data-no-horizontal-wrap'

the no wrap data attribute to match (either)

Returns

boolean

true if focus should wrap, false otherwise

styled(Component, baseStyles, getProps, customizable, pure)

The styled HOC wrapper allows you to create a functional wrapper around a given component which will resolve getStyles functional props, and mix customized props passed in using concatStyleSets.

export declare function styled<TComponentProps extends IPropsWithStyles<TStyleProps, TStyleSet>, TStyleProps, TStyleSet extends IStyleSet<TStyleSet>>(Component: React.ComponentClass<TComponentProps> | React.FunctionComponent<TComponentProps>, baseStyles: IStyleFunctionOrObject<TStyleProps, TStyleSet>, getProps?: (props: TComponentProps) => Partial<TComponentProps>, customizable?: ICustomizableProps, pure?: boolean): React.FunctionComponent<TComponentProps>;

Parameters

Component

React.ComponentClass<TComponentProps> | React.FunctionComponent<TComponentProps>

The unstyled base component to render, which receives styles.

baseStyles

IStyleFunctionOrObject<TStyleProps, TStyleSet>

The styles which should be curried with the component.

getProps

(props: TComponentProps) => Partial<TComponentProps>

A helper which provides default props.

customizable
ICustomizableProps

An object which defines which props can be customized using the Customizer.

pure

boolean

A boolean indicating if the component should avoid re-rendering when props haven't changed. Note that pure should not be used on components which allow children, or take in complex objects or arrays as props which could mutate on every render.

Returns

React.FunctionComponent<TComponentProps>

styled(Component, baseStyles, getProps, customizable, pure)

export declare function styled<TComponentProps extends IPropsWithStyles<TStyleProps, TStyleSet> & React.RefAttributes<TRef>, TStyleProps, TStyleSet extends IStyleSet<TStyleSet>, TRef = unknown>(Component: React.ComponentClass<TComponentProps> | React.FunctionComponent<TComponentProps>, baseStyles: IStyleFunctionOrObject<TStyleProps, TStyleSet>, getProps?: (props: TComponentProps) => Partial<TComponentProps>, customizable?: ICustomizableProps, pure?: boolean): React.ForwardRefExoticComponent<React.PropsWithoutRef<TComponentProps> & React.RefAttributes<TRef>>;

Parameters

Component

React.ComponentClass<TComponentProps> | React.FunctionComponent<TComponentProps>

baseStyles

IStyleFunctionOrObject<TStyleProps, TStyleSet>

getProps

(props: TComponentProps) => Partial<TComponentProps>

customizable
ICustomizableProps
pure

boolean

Returns

React.ForwardRefExoticComponent<React.PropsWithoutRef<TComponentProps> & React.RefAttributes<TRef>>

toMatrix(items, columnCount)

Convert the given array to a matrix with columnCount number of columns.

export declare function toMatrix<T>(items: T[], columnCount: number): T[][];

Parameters

items

T[]

The array to convert

columnCount

number

The number of columns for the resulting matrix

Returns

T[][]

A matrix of items

unhoistMethods(source, methodNames)

Provides a method for convenience to unhoist hoisted methods.

export declare function unhoistMethods(source: any, methodNames: string[]): void;

Parameters

source

any

The source object upon which methods were hoisted.

methodNames

string[]

An array of method names to unhoist.

Returns

void

useCustomizationSettings(properties, scopeName)

Hook to get Customizations settings from Customizations singleton or CustomizerContext. It will trigger component state update on settings change observed.

export declare function useCustomizationSettings(properties: string[], scopeName?: string): ISettings;

Parameters

properties

string[]

scopeName

string

Returns

ISettings

useFocusRects(rootRef)

Initializes the logic which:

  1. Subscribes keydown and mousedown events. (It will only do it once per window, so it's safe to call this method multiple times.) 2. When the user presses directional keyboard keys, adds the 'ms-Fabric--isFocusVisible' classname to the document body, removes the 'ms-Fabric-isFocusHidden' classname. 3. When the user clicks a mouse button, adds the 'ms-Fabric-isFocusHidden' classname to the document body, removes the 'ms-Fabric--isFocusVisible' classname.

This logic allows components on the page to conditionally render focus treatments based on the existence of global classnames, which simplifies logic overall.

export declare function useFocusRects(rootRef?: React.RefObject<HTMLElement>): void;

Parameters

rootRef

React.RefObject<HTMLElement>

A Ref object. Focus rectangle can be applied on itself and all its children.

Returns

void

values(obj)

Get all values in an object dictionary

export declare function values<T>(obj: any): T[];

Parameters

obj

any

The dictionary to get values for

Returns

T[]

warn(message)

Sends a warning to console, if the api is present.

export declare function warn(message: string): void;

Parameters

message

string

Warning message.

Returns

void

warnConditionallyRequiredProps(componentName, props, requiredProps, conditionalPropName, condition)

Warns when props are required if a condition is met.

export declare function warnConditionallyRequiredProps<P>(componentName: string, props: P, requiredProps: string[], conditionalPropName: string, condition: boolean): void;

Parameters

componentName

string

The name of the component being used.

props

P

The props passed into the component.

requiredProps

string[]

The name of the props that are required when the condition is met.

conditionalPropName

string

The name of the prop that the condition is based on.

condition

boolean

Whether the condition is met.

Returns

void

warnControlledUsage(params)

Check for and warn on the following error conditions with a form component: - A value prop is provided (indicated it's being used as controlled) without a change handler, and the component is not read-only - Both the value and defaultValue props are provided - The component is attempting to switch between controlled and uncontrolled

The messages mimic the warnings React gives for these error conditions on input elements. The warning will only be displayed once per component ID.

export declare function warnControlledUsage<P>(params: IWarnControlledUsageParams<P>): void;

Parameters

params

IWarnControlledUsageParams<P>

Returns

void

warnDeprecations(componentName, props, deprecationMap)

Warns when a deprecated props are being used.

export declare function warnDeprecations<P>(componentName: string, props: P, deprecationMap: ISettingsMap<P>): void;

Parameters

componentName

string

The name of the component being used.

props

P

The props passed into the component.

deprecationMap

ISettingsMap<P>

The map of deprecations, where key is the prop name and the value is either null or a replacement prop name.

Returns

void

warnMutuallyExclusive(componentName, props, exclusiveMap)

Warns when two props which are mutually exclusive are both being used.

export declare function warnMutuallyExclusive<P>(componentName: string, props: P, exclusiveMap: ISettingsMap<P>): void;

Parameters

componentName

string

The name of the component being used.

props

P

The props passed into the component.

exclusiveMap

ISettingsMap<P>

A map where the key is a parameter, and the value is the other parameter.

Returns

void