@uifabric/utilities
- Version 7.38.2
- Published
- 2.33 MB
- 5 dependencies
- MIT license
Install
npm i @uifabric/utilities
yarn add @uifabric/utilities
pnpm add @uifabric/utilities
Overview
Fluent UI React utilities for building components.
Index
Variables
- anchorProperties
- audioProperties
- baseElementEvents
- baseElementProperties
- buttonProperties
- colGroupProperties
- colProperties
- CustomizerContext
- DATA_IS_SCROLLABLE_ATTRIBUTE
- divProperties
- FocusRects
- formProperties
- htmlElementProperties
- iframeProperties
- imageProperties
- imgProperties
- inputProperties
- IsFocusVisibleClassName
- KeyCodes
- labelProperties
- liProperties
- olProperties
- optionProperties
- SELECTION_CHANGE
- SELECTION_ITEMS_CHANGE
- selectProperties
- tableProperties
- tdProperties
- textAreaProperties
- thProperties
- trProperties
- videoProperties
Functions
- addDirectionalKeyCode()
- addElementAtIndex()
- allowOverscrollOnElement()
- allowScrollOnElement()
- appendFunction()
- arraysEqual()
- asAsync()
- assertNever()
- assign()
- calculatePrecision()
- classNamesFunction()
- composeComponentAs()
- composeRenderFunction()
- createArray()
- createMemoizer()
- createMergedRef()
- css()
- customizable()
- disableBodyScroll()
- doesElementContainFocus()
- enableBodyScroll()
- extendComponent()
- filteredAssign()
- find()
- findIndex()
- findScrollableParent()
- fitContentToBounds()
- flatten()
- focusAsync()
- focusFirstChild()
- format()
- getDistanceBetweenPoints()
- getDocument()
- getElementIndexPath()
- getFirstFocusable()
- getFirstTabbable()
- getFocusableByIndexPath()
- getId()
- getInitials()
- getLanguage()
- getLastFocusable()
- getLastTabbable()
- getNativeElementProps()
- getNativeProps()
- getNextElement()
- getPreviousElement()
- getPropsWithDefaults()
- getRect()
- getResourceUrl()
- getRTL()
- getRTLSafeKeyCode()
- getScrollbarWidth()
- getWindow()
- hasHorizontalOverflow()
- hasOverflow()
- hasVerticalOverflow()
- hoistMethods()
- hoistStatics()
- initializeComponentRef()
- initializeFocusRects()
- isControlled()
- isDirectionalKeyCode()
- isElementFocusSubZone()
- isElementFocusZone()
- isElementTabbable()
- isElementVisible()
- isIE11()
- isIOS()
- isMac()
- mapEnumByName()
- memoize()
- memoizeFunction()
- merge()
- mergeAriaAttributeValues()
- mergeCustomizations()
- mergeScopedSettings()
- mergeSettings()
- modalize()
- nullRender()
- omit()
- on()
- precisionRound()
- raiseClick()
- removeIndex()
- replaceElement()
- resetControlledWarnings()
- resetIds()
- resetMemoizations()
- safeRequestAnimationFrame()
- safeSetTimeout()
- setBaseUrl()
- setFocusVisibility()
- setLanguage()
- setRTL()
- setSSR()
- setWarningCallback()
- shallowCompare()
- shouldWrapFocus()
- styled()
- toMatrix()
- unhoistMethods()
- useCustomizationSettings()
- useFocusRects()
- values()
- warn()
- warnConditionallyRequiredProps()
- warnControlledUsage()
- warnDeprecations()
- warnMutuallyExclusive()
Classes
Selection
- canSelectItem()
- count
- getItemIndex()
- getItems()
- getKey()
- getSelectedCount()
- getSelectedIndices()
- getSelection()
- isAllSelected()
- isIndexSelected()
- isKeySelected()
- isModal()
- isRangeSelected()
- mode
- selectToIndex()
- selectToKey()
- selectToRange()
- setAllSelected()
- setChangeEvents()
- setIndexSelected()
- setItems()
- setKeySelected()
- setModal()
- setRangeSelected()
- toggleAllSelected()
- toggleIndexSelected()
- toggleKeySelected()
- toggleRangeSelected()
Interfaces
ISelection
- canSelectItem
- count
- getItemIndex()
- getItems()
- getSelectedCount()
- getSelectedIndices()
- getSelection()
- isAllSelected()
- isIndexSelected()
- isKeySelected()
- isModal()
- isRangeSelected()
- mode
- selectToIndex()
- selectToKey()
- selectToRange()
- setAllSelected()
- setChangeEvents()
- setIndexSelected()
- setItems()
- setKeySelected()
- setModal()
- setRangeSelected()
- toggleAllSelected()
- toggleIndexSelected()
- toggleKeySelected()
- toggleRangeSelected()
Enums
Type Aliases
Variables
variable anchorProperties
const anchorProperties: Record<string, number>;
An array of A tag properties and events.
Modifiers
@public
variable audioProperties
const audioProperties: Record<string, number>;
An array of AUDIO tag properties and events.
Modifiers
@public
variable baseElementEvents
const baseElementEvents: Record<string, number>;
An array of events that are allowed on every html element type.
Modifiers
@public
variable baseElementProperties
const baseElementProperties: Record<string, number>;
An array of element attributes which are allowed on every html element type.
Modifiers
@public
variable buttonProperties
const buttonProperties: Record<string, number>;
An array of BUTTON tag properties and events.
Modifiers
@public
variable colGroupProperties
const colGroupProperties: Record<string, number>;
variable colProperties
const colProperties: Record<string, number>;
variable CustomizerContext
const CustomizerContext: React.Context<ICustomizerContext>;
variable DATA_IS_SCROLLABLE_ATTRIBUTE
const DATA_IS_SCROLLABLE_ATTRIBUTE: string;
Placing this attribute on scrollable divs optimizes detection to know if the div is scrollable or not (given we can avoid expensive operations like getComputedStyle.)
Modifiers
@public
variable divProperties
const divProperties: Record<string, number>;
An array of DIV tag properties and events.
Modifiers
@public
variable FocusRects
const FocusRects: React.FunctionComponent<{ rootRef?: React.RefObject<HTMLElement>;}>;
Function Component wrapper which enables calling
useFocusRects
hook. Renders nothing.
variable formProperties
const formProperties: Record<string, number>;
An array of FORM tag properties and events.
Modifiers
@public
variable htmlElementProperties
const htmlElementProperties: Record<string, number>;
An array of HTML element properties and events.
Modifiers
@public
variable iframeProperties
const iframeProperties: Record<string, number>;
An array of IFRAME tag properties and events.
Modifiers
@public
variable imageProperties
const imageProperties: Record<string, number>;
Deprecated
Use imgProperties for img elements.
variable imgProperties
const imgProperties: Record<string, number>;
An array of IMAGE tag properties and events.
Modifiers
@public
variable inputProperties
const inputProperties: Record<string, number>;
An array of INPUT tag properties and events.
Modifiers
@public
variable IsFocusVisibleClassName
const IsFocusVisibleClassName: string;
variable KeyCodes
const KeyCodes: { backspace: 8; tab: 9; enter: 13; shift: 16; ctrl: 17; alt: 18; pauseBreak: 19; capslock: 20; escape: 27; space: 32; pageUp: 33; pageDown: 34; end: 35; home: 36; left: 37; up: 38; right: 39; down: 40; insert: 45; del: 46; zero: 48; one: 49; two: 50; three: 51; four: 52; five: 53; six: 54; seven: 55; eight: 56; nine: 57; a: 65; b: 66; c: 67; d: 68; e: 69; f: 70; g: 71; h: 72; i: 73; j: 74; k: 75; l: 76; m: 77; n: 78; o: 79; p: 80; q: 81; r: 82; s: 83; t: 84; u: 85; v: 86; w: 87; x: 88; y: 89; z: 90; leftWindow: 91; rightWindow: 92; select: 93; zero_numpad: 96; one_numpad: 97; two_numpad: 98; three_numpad: 99; four_numpad: 100; five_numpad: 101; six_numpad: 102; seven_numpad: 103; eight_numpad: 104; nine_numpad: 105; multiply: 106; add: 107; subtract: 109; decimalPoint: 110; divide: 111; f1: 112; f2: 113; f3: 114; f4: 115; f5: 116; f6: 117; f7: 118; f8: 119; f9: 120; f10: 121; f11: 122; f12: 123; numlock: 144; scrollLock: 145; semicolon: 186; equalSign: 187; comma: 188; dash: 189; period: 190; forwardSlash: 191; graveAccent: 192; openBracket: 219; backSlash: 220; closeBracket: 221; singleQuote: 222;};
Simulated enum for keycodes. These will get inlined by uglify when used much like an enum
Modifiers
@public
variable labelProperties
const labelProperties: Record<string, number>;
An array of LABEL tag properties and events.
Modifiers
@public
variable liProperties
const liProperties: Record<string, number>;
An array of LI tag properties and events.
Modifiers
@public
variable olProperties
const olProperties: Record<string, number>;
An array of OL tag properties and events.
Modifiers
@public
variable optionProperties
const optionProperties: Record<string, number>;
variable SELECTION_CHANGE
const SELECTION_CHANGE: string;
variable SELECTION_ITEMS_CHANGE
const SELECTION_ITEMS_CHANGE: string;
variable selectProperties
const selectProperties: Record<string, number>;
An array of SELECT tag properties and events.
Modifiers
@public
variable tableProperties
const tableProperties: Record<string, number>;
An array of TABLE tag properties and events.
Modifiers
@public
variable tdProperties
const tdProperties: Record<string, number>;
An array of TD tag properties and events.
Modifiers
@public
variable textAreaProperties
const textAreaProperties: Record<string, number>;
An array of TEXTAREA tag properties and events.
Modifiers
@public
variable thProperties
const thProperties: Record<string, number>;
An array of TH tag properties and events.
Modifiers
@public
variable trProperties
const trProperties: Record<string, number>;
An array of TR tag properties and events.
Modifiers
@public
variable videoProperties
const videoProperties: Record<string, number>;
An array of VIDEO tag properties and events.
Modifiers
@public
Functions
function addDirectionalKeyCode
addDirectionalKeyCode: (which: number) => void;
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.
function addElementAtIndex
addElementAtIndex: <T>(array: T[], index: number, itemToAdd: T) => T[];
Given an array, this function returns a new array where an element has been inserted at the given index.
Parameter array
The array to operate on
Parameter index
The index where an element should be inserted
Parameter itemToAdd
The element to insert
function allowOverscrollOnElement
allowOverscrollOnElement: ( element: HTMLElement | null, events: EventGroup) => void;
Same as allowScrollOnElement but does not prevent overscrolling.
function allowScrollOnElement
allowScrollOnElement: (element: HTMLElement | null, events: EventGroup) => void;
Allows the user to scroll within a element, while preventing the user from scrolling the body
function appendFunction
appendFunction: (parent: any, ...functions: any[]) => () => void;
Returns a single function which will call each of the given functions in the context of the parent.
function arraysEqual
arraysEqual: <T>(array1: T[], array2: T[]) => boolean;
Returns a boolean indicating if the two given arrays are equal in length and values.
Parameter array1
First array to compare
Parameter array2
Second array to compare
Returns
True if the arrays are the same length and have the same values in the same positions, false otherwise.
function asAsync
asAsync: <TProps>( options: IAsAsyncOptions<TProps>) => React.ForwardRefExoticComponent<any>;
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.
function assertNever
assertNever: (x: never) => never;
AssertNever is a utility function that can be used for exhaustiveness checks in switch statements.
Modifiers
@public
function assign
assign: (target: any, ...args: any[]) => any;
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.
Parameter target
Target object to merge following object arguments into.
Parameter args
One or more objects that will be mixed into the target in the order they are provided.
Returns
Resulting merged target.
Modifiers
@public
function calculatePrecision
calculatePrecision: (value: number | string) => number;
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.
Parameter value
the value to determine the precision of
function classNamesFunction
classNamesFunction: < TStyleProps extends {}, TStyleSet extends IStyleSet<TStyleSet>>( options?: IClassNamesFunctionOptions) => ( getStyles: IStyleFunctionOrObject<TStyleProps, TStyleSet> | undefined, styleProps?: TStyleProps) => IProcessedStyleSet<TStyleSet>;
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.
function composeComponentAs
composeComponentAs: <TProps>( outer: React.ComponentType<IComponentAsProps<T>>, inner: React.ComponentType<IComponentAsProps<T>>) => React.ComponentType<IComponentAsProps<T>>;
Composes two components which conform to the
IComponentAs
specification; that is, two components which accept adefaultRender
prop, which is a 'default' implementation of a component which accepts the same overall props.Modifiers
@public
function composeRenderFunction
composeRenderFunction: <TProps>( outer: IRenderFunction<TProps>, inner: IRenderFunction<TProps>) => IRenderFunction<TProps>;
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.
Modifiers
@public
function createArray
createArray: <T>(size: number, getItem: (index: number) => T) => T[];
Creates an array of a given size and helper method to populate.
Parameter size
Size of array.
Parameter getItem
Callback to populate given cell index.
Modifiers
@public
function createMemoizer
createMemoizer: <F extends (input: any) => any>(getValue: F) => F;
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
orobject
types. To memoize functions which accept other inputs, usememoizeFunction
, which memoizes against arbitrary inputs using a lookup cache.Modifiers
@public
function createMergedRef
createMergedRef: <TType, TValue = null>( value?: TValue) => (...newRefs: any[]) => (newValue: TType | TValue) => void;
Helper to merge refs from within class components.
function css
css: (...args: ICssInput[]) => string;
Concatination helper, which can merge class names together. Skips over falsey values.
Modifiers
@public
function customizable
customizable: ( scope: string, fields: string[], concatStyles?: boolean) => <P>(ComposedComponent: React.ComponentType<P>) => any;
function disableBodyScroll
disableBodyScroll: () => void;
Disables the body scrolling.
Modifiers
@public
function doesElementContainFocus
doesElementContainFocus: (element: HTMLElement) => boolean;
Determines if an element, or any of its children, contain focus.
Modifiers
@public
function enableBodyScroll
enableBodyScroll: () => void;
Enables the body scrolling.
Modifiers
@public
function extendComponent
extendComponent: <T extends React.Component>( parent: T, methods: { [key in keyof T]?: T[key] }) => void;
Extends a component's lifetime methods by appending new functions to the existing lifetime functions.
function filteredAssign
filteredAssign: ( isAllowed: (propName: string) => boolean, target: any, ...args: any[]) => any;
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.
Parameter isAllowed
Callback to determine if the given propName is allowed in the result.
Parameter target
Target object to merge following object arguments into.
Parameter args
One or more objects that will be mixed into the target in the order they are provided.
Returns
Resulting merged target.
Modifiers
@public
function find
find: <T>(array: T[], cb: (item: T, index: number) => boolean) => T | undefined;
Helper to find the first item within an array that satisfies the callback.
Parameter array
Array to search
Parameter cb
Callback which returns true on matches
function findIndex
findIndex: <T>( array: T[], cb: (item: T, index: number) => boolean, fromIndex?: number) => number;
Helper to find the index of an item within an array, using a callback to determine the match.
Parameter array
Array to search.
Parameter cb
Callback which returns true on matches.
Parameter fromIndex
Optional index to start from (defaults to 0)
Modifiers
@public
function findScrollableParent
findScrollableParent: ( startingElement: HTMLElement | null) => HTMLElement | Window | undefined | null;
Traverses up the DOM for the element with the data-is-scrollable=true attribute, or returns document.body.
Modifiers
@public
function fitContentToBounds
fitContentToBounds: (options: IFitContentToBoundsOptions) => ISize;
Produces a proportionally-scaled version of an input content size when fit to a bounding size. Given a
contentSize
and aboundsSize
, this function scalescontentSize
proportionally using eithercontain
orcover
fit behaviors. Use this function to pre-calculate the layout for the CSSobject-fit
andbackground-fit
behaviors. Withcontain
, the output size must be the largest it can be while completely within theboundsSize
. Withcover
, the output size must be the smallest it can be while completely around theboundsSize
. By default, there is amaxScale
value of 1, which prevents thecontentSize
from being scaled larger.Parameter options
the options for the bounds fit operation
function flatten
flatten: <T>(array: (T | T[])[]) => T[];
Given an array where each element is of type T or T[], flatten it into an array of T
Parameter array
The array where each element can optionally also be an array
function focusAsync
focusAsync: ( element: HTMLElement | { focus: () => void } | undefined | null) => void;
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
Parameter element
The element to focus
function focusFirstChild
focusFirstChild: (rootElement: HTMLElement) => boolean;
Attempts to focus the first focusable element that is a child or child's child of the rootElement.
Parameter rootElement
Element to start the search for a focusable child.
Returns
True if focus was set, false if it was not.
Modifiers
@public
function format
format: (s: string, ...values: any[]) => string;
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.
Example 1
"I love {0} every {1}".format("CXP")will result in a Debug Exception.
Modifiers
@public
function getDistanceBetweenPoints
getDistanceBetweenPoints: (point1: Point, point2: Point) => number;
Determines the distance between two points.
Modifiers
@public
function getDocument
getDocument: (rootElement?: HTMLElement | null) => Document | undefined;
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.)
Modifiers
@public
function getElementIndexPath
getElementIndexPath: ( fromElement: HTMLElement, toElement: HTMLElement) => number[];
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]
.
function getFirstFocusable
getFirstFocusable: ( rootElement: HTMLElement, currentElement: HTMLElement, includeElementsInFocusZones?: boolean) => HTMLElement | null;
Gets the first focusable element.
Modifiers
@public
function getFirstTabbable
getFirstTabbable: ( rootElement: HTMLElement, currentElement: HTMLElement, includeElementsInFocusZones?: boolean, checkNode?: boolean) => HTMLElement | null;
Gets the first tabbable element. (The difference between focusable and tabbable is that tabbable elements are focusable elements that also have tabIndex != -1.)
Parameter rootElement
The parent element to search beneath.
Parameter currentElement
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.
Parameter includeElementsInFocusZones
true if traversal should go into FocusZone descendants.
Parameter checkNode
Include currentElement in search when true. Defaults to true.
Modifiers
@public
function getFocusableByIndexPath
getFocusableByIndexPath: ( parent: HTMLElement, path: number[]) => HTMLElement | undefined;
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.
function getId
getId: (prefix?: string) => string;
Generates a unique id in the global scope (this spans across duplicate copies of the same library.)
Modifiers
@public
function getInitials
getInitials: ( displayName: string | undefined | null, isRtl: boolean, allowPhoneInitials?: boolean) => string;
Get (up to 2 characters) initials based on display name of the persona.
Modifiers
@public
function getLanguage
getLanguage: ( persistenceType?: 'localStorage' | 'sessionStorage' | 'none') => string | null;
Gets the language set for the page.
Parameter persistenceType
Where to persist the value. Default is
localStorage
if available. (In version 8, the default will besessionStorage
.)
function getLastFocusable
getLastFocusable: ( rootElement: HTMLElement, currentElement: HTMLElement, includeElementsInFocusZones?: boolean) => HTMLElement | null;
Gets the last focusable element.
Modifiers
@public
function getLastTabbable
getLastTabbable: ( rootElement: HTMLElement, currentElement: HTMLElement, includeElementsInFocusZones?: boolean, checkNode?: boolean) => HTMLElement | null;
Gets the last tabbable element. (The difference between focusable and tabbable is that tabbable elements are focusable elements that also have tabIndex != -1.)
Parameter rootElement
The parent element to search beneath.
Parameter currentElement
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.
Parameter includeElementsInFocusZones
true if traversal should go into FocusZone descendants.
Parameter checkNode
Include currentElement in search when true. Defaults to true.
Modifiers
@public
function getNativeElementProps
getNativeElementProps: <TAttributes extends React.HTMLAttributes<any>>( tagName: string, props: {}, excludedPropNames?: string[]) => TAttributes;
Given an element tagname and user props, filters the props to only allowed props for the given element type.
Parameter tagName
Tag name (e.g. "div")
Parameter props
Props object
Parameter excludedPropNames
List of props to disallow
function getNativeProps
getNativeProps: <T extends Record<string, any>>( props: Record<string, any>, allowedPropNames: string[] | Record<string, number>, excludedPropNames?: string[]) => T;
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.
Parameter props
The unfiltered input props
Parameter allowedPropsNames
The array or record of allowed prop names.
Returns
The filtered props
Modifiers
@public
function getNextElement
getNextElement: ( rootElement: HTMLElement, currentElement: HTMLElement | null, checkNode?: boolean, suppressParentTraversal?: boolean, suppressChildTraversal?: boolean, includeElementsInFocusZones?: boolean, allowFocusRoot?: boolean, tabbable?: boolean) => HTMLElement | null;
Traverse to find the next focusable element. If tabbable is true, the element must have tabIndex != -1.
Parameter checkNode
Include currentElement in search when true.
Modifiers
@public
function getPreviousElement
getPreviousElement: ( rootElement: HTMLElement, currentElement: HTMLElement | null, checkNode?: boolean, suppressParentTraversal?: boolean, traverseChildren?: boolean, includeElementsInFocusZones?: boolean, allowFocusRoot?: boolean, tabbable?: boolean) => HTMLElement | null;
Traverse to find the previous element. If tabbable is true, the element must have tabIndex != -1.
Modifiers
@public
function getPropsWithDefaults
getPropsWithDefaults: <TProps extends {}>( defaultProps: Partial<TProps>, propsWithoutDefaults: TProps) => TProps;
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.Parameter defaultProps
An object with default values for various properties
Parameter propsWithoutDefaults
The props object passed into the component
function getRect
getRect: (element: HTMLElement | Window | null) => IRectangle | undefined;
Helper to get bounding client rect. Passing in window will get the window size.
Modifiers
@public
function getResourceUrl
getResourceUrl: (url: string) => string;
Sets the current base url used for fetching images.
function getRTL
getRTL: (theme?: { rtl?: boolean }) => boolean;
Gets the rtl state of the page (returns true if in rtl.)
function getRTLSafeKeyCode
getRTLSafeKeyCode: (key: number, theme?: { rtl?: boolean }) => number;
Returns the given key, but flips right/left arrows if necessary.
function getScrollbarWidth
getScrollbarWidth: () => number;
Calculates the width of a scrollbar for the browser/os.
Modifiers
@public
function getWindow
getWindow: (rootElement?: Element | null) => Window | undefined;
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.
Modifiers
@public
function hasHorizontalOverflow
hasHorizontalOverflow: (element: HTMLElement) => boolean;
Detects whether an element's content has horizontal overflow
Parameter element
Element to check for overflow
Returns
True if element's content overflows
Modifiers
@public
function hasOverflow
hasOverflow: (element: HTMLElement) => boolean;
Detects whether an element's content has overflow in any direction
Parameter element
Element to check for overflow
Returns
True if element's content overflows
Modifiers
@public
function hasVerticalOverflow
hasVerticalOverflow: (element: HTMLElement) => boolean;
Detects whether an element's content has vertical overflow
Parameter element
Element to check for overflow
Returns
True if element's content overflows
Modifiers
@public
function hoistMethods
hoistMethods: (destination: any, source: any, exclusions?: string[]) => string[];
Allows you to hoist methods, except those in an exclusion set from a source object into a destination object.
Parameter destination
The instance of the object to hoist the methods onto.
Parameter source
The instance of the object where the methods are hoisted from.
Parameter exclusions
(Optional) What methods to exclude from being hoisted.
Returns
An array of names of methods that were hoisted.
Modifiers
@public
function hoistStatics
hoistStatics: <TSource extends Object, TDest>( source: TSource, dest: TDest) => TDest;
Allows you to hoist static functions in components. Created for the purpose of fixing broken static functions in classes that utilize decorators.
Parameter source
The object where the methods are hoisted from.
Parameter dest
The object to hoist the methods onto.
Returns
The dest object with methods added
Modifiers
@public
function initializeComponentRef
initializeComponentRef: <TProps extends IBaseProps<any>, TState>( obj: React.Component<TProps, TState>) => void;
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,
function initializeFocusRects
initializeFocusRects: (window?: Window) => void;
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.
Parameter window
the window used to add the event listeners
Deprecated
Use useFocusRects hook or FocusRects component instead.
function isControlled
isControlled: <P>(props: P, valueProp: keyof P) => boolean;
Determines whether a component is controlled.
Parameter props
Component props
Parameter valueProp
Prop containing the controlled value
Returns
true if controlled, false if uncontrolled
function isDirectionalKeyCode
isDirectionalKeyCode: (which: number) => boolean;
Returns true if the keycode is a directional keyboard key.
function isElementFocusSubZone
isElementFocusSubZone: (element?: HTMLElement) => boolean;
Determines if a given element is a focus sub zone.
Modifiers
@public
function isElementFocusZone
isElementFocusZone: (element?: HTMLElement) => boolean;
Determines if a given element is a focus zone.
Modifiers
@public
function isElementTabbable
isElementTabbable: (element: HTMLElement, checkTabIndex?: boolean) => boolean;
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.
Modifiers
@public
function isElementVisible
isElementVisible: (element: HTMLElement | undefined | null) => boolean;
Determines if an element is visible.
Modifiers
@public
function isIE11
isIE11: () => boolean;
function isIOS
isIOS: () => boolean;
Returns true if and only if the user is on a iOS device. Used to determine whether iOS-specific behavior should be applied.
function isMac
isMac: (reset?: boolean) => boolean;
Returns true if the user is on a Mac. Caches the result value.
Parameter reset
Reset the cached result value (mainly for testing).
function mapEnumByName
mapEnumByName: <T>( theEnum: any, callback: (name?: string, value?: string | number) => T | undefined) => (T | undefined)[] | undefined;
Takes an enum and iterates over each value of the enum (as a string), running the callback on each, returning a mapped array.
Parameter theEnum
Enum to iterate over
Parameter callback
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).
function memoize
memoize: <T extends Function>( target: any, key: string, descriptor: TypedPropertyDescriptor<T>) => { configurable: boolean; get(): T };
Memoize decorator to be used on class methods. WARNING: the
this
reference will be inaccessible within a memoized method, given that a cached method'sthis
would not be instance-specific.Modifiers
@public
function memoizeFunction
memoizeFunction: <T extends (...args: any[]) => RetType, RetType>( cb: T, maxCacheSize?: number, ignoreNullOrUndefinedResult?: boolean) => T;
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.
Parameter cb
The function to memoize.
Parameter maxCacheSize
Max results to cache. If the cache exceeds this value, it will reset on the next call.
Parameter ignoreNullOrUndefinedResult
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
A memoized version of the function.
Modifiers
@public
function merge
merge: <T = {}>( target: Partial<T>, ...args: (Partial<T> | null | undefined | false)[]) => T;
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.
function mergeAriaAttributeValues
mergeAriaAttributeValues: ( ...ariaAttributes: (string | undefined | false)[]) => string | undefined;
ARIA helper to concatenate attributes, returning undefined if all attributes are undefined. (Empty strings are not a valid ARIA attribute value.)
Parameter ariaAttributes
ARIA attributes to merge
function mergeCustomizations
mergeCustomizations: ( props: ICustomizerProps, parentContext: ICustomizerContext) => ICustomizerContext;
Merge props and customizations giving priority to props over context. NOTE: This function will always perform multiple merge operations. Use with caution.
Parameter props
New settings to merge in.
Parameter parentContext
Context containing current settings.
Returns
Merged customizations.
function mergeScopedSettings
mergeScopedSettings: ( oldSettings?: ISettings, newSettings?: ISettings | ISettingsFunction) => ISettings;
function mergeSettings
mergeSettings: ( oldSettings?: ISettings, newSettings?: ISettings | ISettingsFunction) => ISettings;
Merge new and old settings, giving priority to new settings. New settings is optional in which case oldSettings is returned as-is.
Parameter oldSettings
Old settings to fall back to.
Parameter newSettings
New settings that will be merged over oldSettings.
Returns
Merged settings.
function modalize
modalize: (target: HTMLElement) => () => void;
Call this on a target element to make it modal to screen readers. Returns a function that undoes the changes it made.
function nullRender
nullRender: () => JSX.Element | null;
Simple constant function for returning null, used to render empty templates in JSX.
Modifiers
@public
function omit
omit: <TObj extends Record<string, any>>( obj: TObj, exclusions: (keyof TObj)[]) => TObj;
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
Parameter obj
The object to clone
Parameter exclusions
The array of keys to exclude
function on
on: ( element: Element | Window | Document, eventName: string, callback: (ev: Event) => void, options?: boolean) => () => void;
function precisionRound
precisionRound: (value: number, precision: number, base?: number) => number;
Rounds a number to a certain level of precision. Accepts negative precision.
Parameter value
The value that is being rounded.
Parameter precision
The number of decimal places to round the number to
function raiseClick
raiseClick: (target: Element) => void;
Raises a click event.
function removeIndex
removeIndex: <T>(array: T[], index: number) => T[];
Given an array, it returns a new array that does not contain the item at the given index.
Parameter array
The array to operate on
Parameter index
The index of the element to remove
function replaceElement
replaceElement: <T>(array: T[], newElement: T, index: number) => T[];
Given an array, this function returns a new array where the element at a given index has been replaced.
Parameter array
The array to operate on
Parameter newElement
The element that will be placed in the new array
Parameter index
The index of the element that should be replaced
function resetControlledWarnings
resetControlledWarnings: () => void;
Reset controlled usage warnings for testing purposes.
function resetIds
resetIds: (counter?: number) => void;
Resets id counter to an (optional) number.
Modifiers
@public
function resetMemoizations
resetMemoizations: () => void;
Reset memoizations.
function safeRequestAnimationFrame
safeRequestAnimationFrame: ( component: React.Component<{}, {}, any>) => (cb: Function) => void;
Generates a function to be attached to a React component, which can be called as a replacement to RAF. In-flight async calls will be auto canceled if the component is unmounting before the async code is executed, preventing bugs where code accesses things within the component after being unmounted.
function safeSetTimeout
safeSetTimeout: ( component: React.Component<{}, {}, any>) => (cb: Function, duration: number) => void;
Generates a function to be attached to a React component, which can be called as a replacement to setTimeout. In-flight async calls will be auto canceled if the component is unmounting before the async code is executed, preventing bugs where code accesses things within the component after being unmounted.
function setBaseUrl
setBaseUrl: (baseUrl: string) => void;
Gets the current base url used for fetching images.
function setFocusVisibility
setFocusVisibility: (enabled: boolean, target?: Element) => void;
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.
Parameter enabled
whether to remove or add focus
Parameter target
optional target
function setLanguage
setLanguage: { ( language: string, persistenceType?: 'localStorage' | 'sessionStorage' | 'none' ): void; (language: string, avoidPersisting?: boolean): void;};
Sets the language for the page (by adjusting the lang attribute of the html element).
Parameter language
Language to set.
Parameter persistenceType
Where to persist the value. Default is
localStorage
if available. (In version 8, the default will besessionStorage
.)Sets the language for the page (by adjusting the lang attribute of the html element).
Parameter language
Language to set.
Parameter avoidPersisting
If true, don't store the value.
Deprecated
Use string parameter version.
function setRTL
setRTL: (isRTL: boolean, persistSetting?: boolean) => void;
Sets the rtl state of the page (by adjusting the dir attribute of the html element.)
function setSSR
setSSR: (isEnabled: boolean) => void;
Helper to set ssr mode to simulate no window object returned from getWindow helper.
Modifiers
@public
function setWarningCallback
setWarningCallback: (warningCallback?: (message: string) => void) => void;
Configures the warning callback. Passing in undefined will reset it to use the default console.warn function.
Parameter warningCallback
Callback to override the generated warnings.
Modifiers
@public
function shallowCompare
shallowCompare: <TA extends unknown, TB extends unknown>( a: TA, b: TB) => boolean;
Compares a to b and b to a.
Modifiers
@public
function shouldWrapFocus
shouldWrapFocus: ( element: HTMLElement, noWrapDataAttribute: 'data-no-vertical-wrap' | 'data-no-horizontal-wrap') => boolean;
Determines if an, or any of its ancestors, sepcificies that it doesn't want focus to wrap
Parameter element
element to start searching from
Parameter noWrapDataAttribute
the no wrap data attribute to match (either)
Returns
true if focus should wrap, false otherwise
function styled
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>; < TComponentProps extends unknown, TStyleProps, TStyleSet extends IStyleSet<TStyleSet>, TRef = unknown >( Component: any, baseStyles: IStyleFunctionOrObject<TStyleProps, TStyleSet>, getProps?: (props: TComponentProps) => Partial<TComponentProps>, customizable?: ICustomizableProps, pure?: boolean ): React.ForwardRefExoticComponent<any>;};
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.
Parameter Component
The unstyled base component to render, which receives styles.
Parameter baseStyles
The styles which should be curried with the component.
Parameter getProps
A helper which provides default props.
Parameter customizable
An object which defines which props can be customized using the Customizer.
Parameter pure
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.
Example 1
export const Toggle = styled(ToggleBase,props => ({ root: { background: 'red' }}));
function toMatrix
toMatrix: <T>(items: T[], columnCount: number) => T[][];
Convert the given array to a matrix with columnCount number of columns.
Parameter items
The array to convert
Parameter columnCount
The number of columns for the resulting matrix
Returns
A matrix of items
Modifiers
@public
function unhoistMethods
unhoistMethods: (source: any, methodNames: string[]) => void;
Provides a method for convenience to unhoist hoisted methods.
Parameter source
The source object upon which methods were hoisted.
Parameter methodNames
An array of method names to unhoist.
Modifiers
@public
function useCustomizationSettings
useCustomizationSettings: ( properties: string[], scopeName?: string) => ISettings;
Hook to get Customizations settings from Customizations singleton or CustomizerContext. It will trigger component state update on settings change observed.
function useFocusRects
useFocusRects: (rootRef?: React.RefObject<HTMLElement>) => void;
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.
Parameter rootRef
A Ref object. Focus rectangle can be applied on itself and all its children.
function values
values: <T>(obj: any) => T[];
Get all values in an object dictionary
Parameter obj
The dictionary to get values for
function warn
warn: (message: string) => void;
Sends a warning to console, if the api is present.
Parameter message
Warning message.
Modifiers
@public
function warnConditionallyRequiredProps
warnConditionallyRequiredProps: <P>( componentName: string, props: P, requiredProps: string[], conditionalPropName: string, condition: boolean) => void;
Warns when props are required if a condition is met.
Parameter componentName
The name of the component being used.
Parameter props
The props passed into the component.
Parameter requiredProps
The name of the props that are required when the condition is met.
Parameter conditionalPropName
The name of the prop that the condition is based on.
Parameter condition
Whether the condition is met.
Modifiers
@public
function warnControlledUsage
warnControlledUsage: <P>(params: IWarnControlledUsageParams<P>) => void;
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.
function warnDeprecations
warnDeprecations: <P>( componentName: string, props: P, deprecationMap: ISettingsMap<P>) => void;
Warns when a deprecated props are being used.
Parameter componentName
The name of the component being used.
Parameter props
The props passed into the component.
Parameter deprecationMap
The map of deprecations, where key is the prop name and the value is either null or a replacement prop name.
Modifiers
@public
function warnMutuallyExclusive
warnMutuallyExclusive: <P>( componentName: string, props: P, exclusiveMap: ISettingsMap<P>) => void;
Warns when two props which are mutually exclusive are both being used.
Parameter componentName
The name of the component being used.
Parameter props
The props passed into the component.
Parameter exclusiveMap
A map where the key is a parameter, and the value is the other parameter.
Modifiers
@public
Classes
class Async
class 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.
Modifiers
@public
constructor
constructor(parent?: {}, onError?: (e: any) => void);
method cancelAnimationFrame
cancelAnimationFrame: (id: number, targetElement?: Element | null) => void;
method clearImmediate
clearImmediate: (id: number, targetElement?: Element | null) => void;
Clears the immediate.
Parameter id
Id to cancel.
Parameter targetElement
Optional target element to use for identifying the correct window.
method clearInterval
clearInterval: (id: number) => void;
Clears the interval.
Parameter id
Id to cancel.
method clearTimeout
clearTimeout: (id: number) => void;
Clears the timeout.
Parameter id
Id to cancel.
method debounce
debounce: <T extends (...args: any[]) => any>( func: T, wait?: number, options?: { leading?: boolean; maxWait?: number; trailing?: boolean }) => ICancelable<T> & T;
Creates a function that will delay the execution of func until after wait milliseconds have elapsed since the last time it was invoked. Provide an options object to indicate that func should be invoked on the leading and/or trailing edge of the wait timeout. Subsequent calls to the debounced function will return the result of the last func call.
Note: If leading and trailing options are true func will be called on the trailing edge of the timeout only if the debounced function is invoked more than once during the wait timeout.
Parameter func
The function to debounce.
Parameter wait
The number of milliseconds to delay.
Parameter options
The options object.
Returns
The new debounced function.
method dispose
dispose: () => void;
Dispose function, clears all async operations.
method requestAnimationFrame
requestAnimationFrame: ( callback: () => void, targetElement?: Element | null) => number;
method setImmediate
setImmediate: (callback: () => void, targetElement?: Element | null) => number;
SetImmediate override, which will auto cancel the immediate during dispose.
Parameter callback
Callback to execute.
Parameter targetElement
Optional target element to use for identifying the correct window.
Returns
The setTimeout id.
method setInterval
setInterval: (callback: () => void, duration: number) => number;
SetInterval override, which will auto cancel the timeout during dispose.
Parameter callback
Callback to execute.
Parameter duration
Duration in milliseconds.
Returns
The setTimeout id.
method setTimeout
setTimeout: (callback: () => void, duration: number) => number;
SetTimeout override, which will auto cancel the timeout during dispose.
Parameter callback
Callback to execute.
Parameter duration
Duration in milliseconds.
Returns
The setTimeout id.
method throttle
throttle: <T extends (...args: any[]) => any>( func: T, wait?: number, options?: { leading?: boolean; trailing?: boolean }) => T;
Creates a function that, when executed, will only call the func function at most once per every wait milliseconds. Provide an options object to indicate that func should be invoked on the leading and/or trailing edge of the wait timeout. Subsequent calls to the throttled function will return the result of the last func call.
Note: If leading and trailing options are true func will be called on the trailing edge of the timeout only if the throttled function is invoked more than once during the wait timeout.
Parameter func
The function to throttle.
Parameter wait
The number of milliseconds to throttle executions to. Defaults to 0.
Parameter options
The options object.
Returns
The new throttled function.
class AutoScroll
class 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.
Modifiers
@public
constructor
constructor(element: HTMLElement);
method dispose
dispose: () => void;
class BaseComponent
class BaseComponent< TProps extends IBaseProps = {}, TState = {}> extends React.Component<TProps, TState> {}
BaseComponent class, which provides basic helpers for all components.
Modifiers
@public
Deprecated
Do not use. We are moving away from class component.
constructor
constructor(props: IBaseProps<any>, context?: any);
BaseComponent constructor
Parameter props
The props for the component.
Parameter context
The context for the component.
property className
readonly className: string;
Gets the object's class name.
property onError
static onError: (errorMessage?: string, ex?: any) => void;
Deprecated
Use React's error boundaries instead.
method componentDidMount
componentDidMount: () => void;
When the component has mounted, update the componentRef.
method componentDidUpdate
componentDidUpdate: (prevProps: TProps, prevState: TState) => void;
When the component receives props, make sure the componentRef is updated.
method componentWillUnmount
componentWillUnmount: () => void;
If we have disposables, dispose them automatically on unmount.
class Customizations
class Customizations {}
method applyBatchedUpdates
static applyBatchedUpdates: (code: () => void, suppressUpdate?: boolean) => void;
Used to run some code that sets Customizations without triggering an update until the end. Useful for applying Customizations that don't affect anything currently rendered, or for applying many customizations at once.
Parameter suppressUpdate
Do not raise the change event at the end, preventing all updates
method applyScopedSettings
static applyScopedSettings: (scopeName: string, settings: ISettings) => void;
Apply Customizations to a particular named scope, like a component.
Example 1
Customizations.applyScopedSettings('Nav', { styles: () => {} });
method applySettings
static applySettings: (settings: ISettings) => void;
Apply global Customization settings.
Example 1
Customizations.applySettings({ theme: {...} });
method getSettings
static getSettings: ( properties: string[], scopeName?: string, localSettings?: ICustomizations) => any;
method observe
static observe: (onChange: () => void) => void;
method reset
static reset: () => void;
method unobserve
static unobserve: (onChange: () => void) => void;
class Customizer
class Customizer extends React.Component<ICustomizerProps> {}
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
Modifiers
@public
method componentDidMount
componentDidMount: () => void;
method componentWillUnmount
componentWillUnmount: () => void;
method render
render: () => React.ReactElement<{}>;
class DelayedRender
class DelayedRender extends React.Component< IDelayedRenderProps, IDelayedRenderState> {}
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.
Modifiers
@public
constructor
constructor(props: IDelayedRenderProps);
property defaultProps
static defaultProps: { delay: number };
method componentDidMount
componentDidMount: () => void;
method componentWillUnmount
componentWillUnmount: () => void;
method render
render: () => React.ReactElement<{}> | null;
class EventGroup
class 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).
Modifiers
@public
constructor
constructor(parent: any);
parent: the context in which events attached to non-HTMLElements are called
method declare
declare: (event: string | string[]) => void;
Declare an event as being supported by this instance of EventGroup.
method dispose
dispose: () => void;
method isDeclared
static isDeclared: (target: any, eventName: string) => boolean;
Check to see if the target has declared support of the given event.
method isObserved
static isObserved: (target: any, eventName: string) => boolean;
method off
off: ( target?: any, eventName?: string, callback?: (args?: any) => void, options?: boolean | AddEventListenerOptions) => void;
method on
on: ( target: any, eventName: string, callback: (args?: any) => void, options?: boolean | AddEventListenerOptions) => void;
On the target, attach an event whose handler will be called in the context of the parent of this instance of EventGroup.
method onAll
onAll: ( target: any, events: { [key: string]: (args?: any) => void }, useCapture?: boolean) => void;
On the target, attach a set of events, where the events object is a name to function mapping.
method raise
static raise: ( target: any, eventName: string, eventArgs?: any, bubbleEvent?: boolean) => boolean | undefined;
For IE8, bubbleEvent is ignored here and must be dealt with by the handler. Events raised here by default have bubbling set to false and cancelable set to true. This applies also to built-in events being raised manually here on HTMLElements, which may lead to unexpected behavior if it differs from the defaults.
Trigger the given event in the context of this instance of EventGroup.
method stopPropagation
static stopPropagation: (event: any) => void;
class FabricPerformance
class FabricPerformance {}
Performance helper class for measuring things.
Modifiers
@public
property summary
static summary: IPerfSummary;
method measure
static measure: (name: string, func: () => void) => void;
Measures execution time of the given syncronous function. If the same logic is executed multiple times, each individual measurement will be collected as well the overall numbers.
Parameter name
The name of this measurement
Parameter func
The logic to be measured for execution time
method reset
static reset: () => void;
method setPeriodicReset
static setPeriodicReset: () => void;
class GlobalSettings
class 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.
Modifiers
@public
method addChangeListener
static addChangeListener: (cb: IChangeEventCallback) => void;
method getValue
static getValue: <T>(key: string, defaultValue?: T | (() => T)) => T;
method removeChangeListener
static removeChangeListener: (cb: IChangeEventCallback) => void;
method setValue
static setValue: <T>(key: string, value: T) => T;
class Rectangle
class Rectangle {}
Rectangle helper class.
Modifiers
@public
constructor
constructor(left?: number, right?: number, top?: number, bottom?: number);
property bottom
bottom: number;
property height
readonly height: number;
Calculated automatically by subtracting the bottom from top.
property left
left: number;
property right
right: number;
property top
top: number;
property width
readonly width: number;
Calculated automatically by subtracting the right from left
method equals
equals: (rect: Rectangle) => boolean;
Tests if another rect is approximately equal to this rect (within 4 decimal places.)
class Selection
class Selection<TItem = IObjectWithKey> implements ISelection<TItem> {}
constructor
constructor( ...options: | [] | [ISelectionOptions<TItem>] | [ISelectionOptionsWithRequiredGetKey<TItem>]);
Create a new Selection. If
TItem
does not have akey
property, you must provide an options object with agetKey
implementation. Providing options is optional otherwise. (At most oneoptions
object is accepted.)
property count
count: number;
Number of items selected. Do not modify.
property mode
readonly mode: SelectionMode;
method canSelectItem
canSelectItem: (item: TItem, index?: number) => boolean;
method getItemIndex
getItemIndex: (key: string) => number;
method getItems
getItems: () => TItem[];
method getKey
getKey: (item: TItem, index?: number) => string;
method getSelectedCount
getSelectedCount: () => number;
method getSelectedIndices
getSelectedIndices: () => number[];
method getSelection
getSelection: () => TItem[];
method isAllSelected
isAllSelected: () => boolean;
method isIndexSelected
isIndexSelected: (index: number) => boolean;
method isKeySelected
isKeySelected: (key: string) => boolean;
method isModal
isModal: () => boolean;
method isRangeSelected
isRangeSelected: (fromIndex: number, count: number) => boolean;
method selectToIndex
selectToIndex: (index: number, clearSelection?: boolean) => void;
method selectToKey
selectToKey: (key: string, clearSelection?: boolean) => void;
method selectToRange
selectToRange: ( fromIndex: number, count: number, clearSelection?: boolean) => void;
method setAllSelected
setAllSelected: (isAllSelected: boolean) => void;
method setChangeEvents
setChangeEvents: (isEnabled: boolean, suppressChange?: boolean) => void;
method setIndexSelected
setIndexSelected: ( index: number, isSelected: boolean, shouldAnchor: boolean) => void;
method setItems
setItems: (items: TItem[], shouldClear?: boolean) => void;
Selection needs the items, call this method to set them. If the set of items is the same, this will re-evaluate selection and index maps. Otherwise, shouldClear should be set to true, so that selection is cleared.
method setKeySelected
setKeySelected: ( key: string, isSelected: boolean, shouldAnchor: boolean) => void;
method setModal
setModal: (isModal: boolean) => void;
method setRangeSelected
setRangeSelected: ( fromIndex: number, count: number, isSelected: boolean, shouldAnchor: boolean) => void;
method toggleAllSelected
toggleAllSelected: () => void;
method toggleIndexSelected
toggleIndexSelected: (index: number) => void;
method toggleKeySelected
toggleKeySelected: (key: string) => void;
method toggleRangeSelected
toggleRangeSelected: (fromIndex: number, count: number) => void;
Interfaces
interface IAsAsyncOptions
interface IAsAsyncOptions<TProps> {}
property load
load: () => Promise<React.ElementType<TProps>>;
Callback which returns a promise resolving an object which exports the component.
property onError
onError?: (error: Error) => void;
Callback when async loading fails.
property onLoad
onLoad?: () => void;
Callback executed when async loading is complete.
interface IBaseProps
interface IBaseProps<T = any> {}
BaseProps interface.
Modifiers
@public
property componentRef
componentRef?: IRefObject<T>;
interface IChangeDescription
interface IChangeDescription {}
Change description used for change callbacks in GlobalSettings.
Modifiers
@public
interface IChangeEventCallback
interface IChangeEventCallback {}
Change event callback.
Modifiers
@public
call signature
(changeDescription?: IChangeDescription): void;
interface IClassNamesFunctionOptions
interface IClassNamesFunctionOptions {}
property cacheSize
cacheSize?: number;
Size of the cache. It overwrites default cache size when defined.
property disableCaching
disableCaching?: boolean;
Disables class caching for scenarios where styleProp parts mutate frequently.
property useStaticStyles
useStaticStyles?: boolean;
Set to true if component base styles are implemented in scss instead of css-in-js.
interface ICustomizableProps
interface ICustomizableProps {}
interface ICustomizations
interface ICustomizations {}
property inCustomizerContext
inCustomizerContext?: boolean;
property scopedSettings
scopedSettings: { [key: string]: ISettings;};
property settings
settings: ISettings;
interface ICustomizerContext
interface ICustomizerContext {}
property customizations
customizations: ICustomizations;
interface IDelayedRenderProps
interface IDelayedRenderProps extends React.Props<{}> {}
DelayedRender component props.
Modifiers
@public
property delay
delay?: number;
Number of milliseconds to delay rendering children.
interface IDisposable
interface IDisposable {}
Disposable interface.
Modifiers
@public
property dispose
dispose: () => void;
interface IFitContentToBoundsOptions
interface IFitContentToBoundsOptions {}
Options for fitting content sizes into bounding sizes.
property boundsSize
boundsSize: ISize;
The size of the bounds.
property contentSize
contentSize: ISize;
The size of the content to fit to the bounds. The output will be proportional to this value.
property maxScale
maxScale?: number;
An optional maximum scale factor to apply. The default is 1. Use Infinity for an unbounded resize.
property mode
mode: FitMode;
The fit mode to apply, either 'contain' or 'cover'.
interface IObjectWithKey
interface IObjectWithKey {}
property key
key?: string | number;
interface IPoint
interface IPoint extends Point {}
Point interface.
Modifiers
@public
Deprecated
Use
Point
instead.
interface IPropsWithStyles
interface IPropsWithStyles<TStyleProps, TStyleSet extends IStyleSet<TStyleSet>> {}
property styles
styles?: IStyleFunctionOrObject<TStyleProps, TStyleSet>;
interface IRectangle
interface IRectangle {}
Rectangle interface.
Modifiers
@public
interface IRenderComponent
interface IRenderComponent<TProps> {}
An interface representing a component that will not output any DOM, will just render its children and pass through items to modify the children.
property children
children: (props: TProps) => JSX.Element;
JSX.Element to return in this component's render() function.
interface IRenderFunction
interface IRenderFunction<P> {}
Render function interface for providing overrideable render callbacks.
Modifiers
@public
call signature
( props?: P, defaultRender?: (props?: P) => JSX.Element | null): JSX.Element | null;
interface ISelection
interface ISelection<TItem = IObjectWithKey> {}
property canSelectItem
canSelectItem: (item: TItem, index?: number) => boolean;
property count
count: number;
property mode
mode: SelectionMode;
method getItemIndex
getItemIndex: (key: string) => number;
method getItems
getItems: () => TItem[];
method getSelectedCount
getSelectedCount: () => number;
method getSelectedIndices
getSelectedIndices: () => number[];
method getSelection
getSelection: () => TItem[];
method isAllSelected
isAllSelected: () => boolean;
method isIndexSelected
isIndexSelected: (index: number) => boolean;
method isKeySelected
isKeySelected: (key: string) => boolean;
method isModal
isModal: () => boolean;
method isRangeSelected
isRangeSelected: (fromIndex: number, count: number) => boolean;
method selectToIndex
selectToIndex: (index: number, clearSelection?: boolean) => void;
method selectToKey
selectToKey: (key: string, clearSelection?: boolean) => void;
method selectToRange
selectToRange: (index: number, count: number, clearSelection?: boolean) => void;
method setAllSelected
setAllSelected: (isAllSelected: boolean) => void;
method setChangeEvents
setChangeEvents: (isEnabled: boolean, suppressChange?: boolean) => void;
method setIndexSelected
setIndexSelected: ( index: number, isSelected: boolean, shouldAnchor: boolean) => void;
method setItems
setItems: (items: TItem[], shouldClear: boolean) => void;
method setKeySelected
setKeySelected: ( key: string, isSelected: boolean, shouldAnchor: boolean) => void;
method setModal
setModal: (isModal: boolean) => void;
method setRangeSelected
setRangeSelected: ( fromIndex: number, count: number, isSelected: boolean, shouldAnchor: boolean) => void;
method toggleAllSelected
toggleAllSelected: () => void;
method toggleIndexSelected
toggleIndexSelected: (index: number) => void;
method toggleKeySelected
toggleKeySelected: (key: string) => void;
method toggleRangeSelected
toggleRangeSelected: (fromIndex: number, count: number) => void;
interface ISelectionOptions
interface ISelectionOptions<TItem = IObjectWithKey> {}
property canSelectItem
canSelectItem?: (item: TItem, index?: number) => boolean;
property getKey
getKey?: (item: TItem, index?: number) => string | number;
Custom logic to generate item keys. Required if
TItem
does not have akey
property.
property items
items?: TItem[];
property onItemsChanged
onItemsChanged?: () => void;
property onSelectionChanged
onSelectionChanged?: () => void;
property selectionMode
selectionMode?: SelectionMode;
interface IWarnControlledUsageParams
interface IWarnControlledUsageParams<P> {}
property componentId
componentId: string;
ID of the component instance. Used to prevent showing warnings repeatedly.
property componentName
componentName: string;
Name of the component class.
property defaultValueProp
defaultValueProp: keyof P;
Name of the prop for the uncontrolled initial value.
property oldProps
oldProps?: P;
Previous props to evaluate (undefined if called in the constructor).
property onChangeProp
onChangeProp: keyof P;
Name of the change handler prop.
property props
props: P;
Current props to evaluate.
property readOnlyProp
readOnlyProp?: keyof P;
Name of the read-only prop.
property valueProp
valueProp: keyof P;
Name of the prop for the controlled value.
Enums
enum SelectionDirection
enum SelectionDirection { horizontal = 0, vertical = 1,}
member horizontal
horizontal = 0
member vertical
vertical = 1
enum SelectionMode
enum SelectionMode { none = 0, single = 1, multiple = 2,}
Type Aliases
type FitMode
type FitMode = 'contain' | 'cover';
The available fit modes. These should match the fit modes for CSS.
type ICancelable
type ICancelable<T extends (...args: any[]) => any> = { flush: () => ReturnType<T>; cancel: () => void; pending: () => boolean;};
type IClassNames
type IClassNames<T> = { [key in keyof T]: string;};
Deprecated
Use
IProcessedStyleSet
from@uifabric/styling
or@uifabric/merge-styles
instead.
type IComponentAs
type IComponentAs<T> = React.ComponentType<IComponentAsProps<T>>;
Render function interface for providing overrideable render callbacks.
Modifiers
@public
type IComponentAsProps
type IComponentAsProps<T> = T & { defaultRender?: React.ComponentType<T>;};
Properties used by render function interface for providing overrideable render callbacks.
Modifiers
@public
type ICustomizerProps
type ICustomizerProps = IBaseProps & Partial<{ /** * Settings are used as general settings for the React tree below. * Components can subscribe to receive the settings by using `customizable`. * * @example * ``` * // Settings can be represented by a plain object that contains the key value pairs. * <Customizer settings={{ color: 'red' }} /> * * // or a function that receives the current settings and returns the new ones * <Customizer settings={(currentSettings) => ({ ...currentSettings, color: 'red' })} /> * ``` */ settings: ISettings | ISettingsFunction; /** * Scoped settings are settings that are scoped to a specific scope. The * scope is the name that is passed to the `customizable` function when the * the component is customized. * * @example * ``` * // Scoped settings can be represented by a plain object that contains the key value pairs. * const myScopedSettings = { * Button: { color: 'red' }; * }; * <Customizer scopedSettings={myScopedSettings} /> * * // or a function that receives the current settings and returns the new ones * const myScopedSettings = { * Button: { color: 'red' }; * }; * <Customizer scopedSettings={(currentScopedSettings) => ({ ...currentScopedSettings, ...myScopedSettings })} /> * ``` */ scopedSettings: ISettings | ISettingsFunction; }> & { /** * Optional transform function for context. Any implementations should take care to return context without * mutating it. */ contextTransform?: ( context: Readonly<ICustomizerContext> ) => ICustomizerContext; };
type IRefObject
type IRefObject<T> = React.RefObject<T> | RefObject<T> | ((ref: T | null) => void);
type ISelectionOptionsWithRequiredGetKey
type ISelectionOptionsWithRequiredGetKey<TItem> = ISelectionOptions<TItem> & Required<Pick<ISelectionOptions<TItem>, 'getKey'>>;
Selection options with required
getKey
property.
type ISettings
type ISettings = { [key: string]: any;};
type ISettingsFunction
type ISettingsFunction = (settings: ISettings) => ISettings;
type ISettingsMap
type ISettingsMap<T> = { [P in keyof T]?: string;};
type KeyCodes
type KeyCodes = number;
type RefObject
type RefObject<T> = { (component: T | null): void; current: T | null;};
type Settings
type Settings = ISettings;
Deprecated
Use ISettings.
type SettingsFunction
type SettingsFunction = ISettingsFunction;
Deprecated
Use ISettingsFunction.
type StyleFunction
type StyleFunction<TStyleProps, TStyleSet> = IStyleFunctionOrObject< TStyleProps, TStyleSet> & { /** Cache for all style functions. */ __cachedInputs__: (IStyleFunctionOrObject<TStyleProps, TStyleSet> | undefined)[]; /** True if no styles prop or styles from Customizer is passed to wrapped component. */ __noStyleOverride__: boolean;};
Package Files (83)
- lib/Async.d.ts
- lib/AutoScroll.d.ts
- lib/BaseComponent.d.ts
- lib/BaseComponent.types.d.ts
- lib/DelayedRender.d.ts
- lib/EventGroup.d.ts
- lib/FabricPerformance.d.ts
- lib/GlobalSettings.d.ts
- lib/IClassNames.d.ts
- lib/IComponentAs.d.ts
- lib/IDisposable.d.ts
- lib/IRectangle.d.ts
- lib/IRenderComponent.d.ts
- lib/IRenderFunction.d.ts
- lib/ISize.d.ts
- lib/KeyCodes.d.ts
- lib/Point.d.ts
- lib/Rectangle.d.ts
- lib/appendFunction.d.ts
- lib/aria.d.ts
- lib/array.d.ts
- lib/asAsync.d.ts
- lib/assertNever.d.ts
- lib/classNamesFunction.d.ts
- lib/componentAs/composeComponentAs.d.ts
- lib/controlled.d.ts
- lib/createMergedRef.d.ts
- lib/createRef.d.ts
- lib/css.d.ts
- lib/customizations/Customizations.d.ts
- lib/customizations/Customizer.d.ts
- lib/customizations/Customizer.types.d.ts
- lib/customizations/CustomizerContext.d.ts
- lib/customizations/customizable.d.ts
- lib/customizations/mergeCustomizations.d.ts
- lib/customizations/mergeSettings.d.ts
- lib/customizations/useCustomizationSettings.d.ts
- lib/dom/getDocument.d.ts
- lib/dom/getRect.d.ts
- lib/dom/getWindow.d.ts
- lib/dom/on.d.ts
- lib/dom/raiseClick.d.ts
- lib/dom/setSSR.d.ts
- lib/extendComponent.d.ts
- lib/focus.d.ts
- lib/getId.d.ts
- lib/getNativeElementProps.d.ts
- lib/getPropsWithDefaults.d.ts
- lib/hoist.d.ts
- lib/hoistStatics.d.ts
- lib/ie11Detector.d.ts
- lib/index.d.ts
- lib/initializeComponentRef.d.ts
- lib/initializeFocusRects.d.ts
- lib/initials.d.ts
- lib/keyboard.d.ts
- lib/language.d.ts
- lib/math.d.ts
- lib/memoize.d.ts
- lib/merge.d.ts
- lib/mobileDetector.d.ts
- lib/modalize.d.ts
- lib/object.d.ts
- lib/osDetector.d.ts
- lib/overflow.d.ts
- lib/properties.d.ts
- lib/renderFunction/composeRenderFunction.d.ts
- lib/resources.d.ts
- lib/rtl.d.ts
- lib/safeRequestAnimationFrame.d.ts
- lib/safeSetTimeout.d.ts
- lib/scroll.d.ts
- lib/selection/Selection.d.ts
- lib/selection/Selection.types.d.ts
- lib/setFocusVisibility.d.ts
- lib/string.d.ts
- lib/styled.d.ts
- lib/useFocusRects.d.ts
- lib/warn/warn.d.ts
- lib/warn/warnConditionallyRequiredProps.d.ts
- lib/warn/warnControlledUsage.d.ts
- lib/warn/warnDeprecations.d.ts
- lib/warn/warnMutuallyExclusive.d.ts
Dependencies (5)
Dev Dependencies (20)
- @fluentui/eslint-plugin
- @types/enzyme
- @types/enzyme-adapter-react-16
- @types/jest
- @types/node
- @types/prop-types
- @types/react
- @types/react-dom
- @types/react-test-renderer
- @types/sinon
- @uifabric/build
- @uifabric/jest-serializer-merge-styles
- @uifabric/test-utilities
- enzyme
- enzyme-adapter-react-16
- react
- react-app-polyfill
- react-dom
- react-test-renderer
- sinon
Peer Dependencies (4)
Badge
To add a badge like this oneto your package's README, use the codes available below.
You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/@uifabric/utilities
.
- Markdown[![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/@uifabric/utilities)
- HTML<a href="https://www.jsdocs.io/package/@uifabric/utilities"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>
- Updated .
Package analyzed in 10478 ms. - Missing or incorrect documentation? Open an issue for this package.