Skip to content
Original file line number Diff line number Diff line change
Expand Up @@ -7,21 +7,25 @@ import {
EuiCode,
UseEuiTheme,
EuiTitle,
useEuiMemoizedStyles, EuiLink,
useEuiMemoizedStyles,
EuiLink,
} from '@elastic/eui';
import { ProcessedComponent, ProcessedComponentProp } from '@elastic/eui-docgen';
import {
ProcessedComponent,
ProcessedComponentProp,
} from '@elastic/eui-docgen';
import { useCallback, useMemo } from 'react';
import { css } from '@emotion/react';
import { PropTableExtendedTypes } from './extended_types';

export interface PropTableProps {
definition: ProcessedComponent;
headingLevel?: 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6';
showTitle?: boolean;
}

const getPropId = (prop: ProcessedComponentProp, componentName: string) => (
`${encodeURIComponent(componentName)}-prop-${prop.name}`
);
const getPropId = (prop: ProcessedComponentProp, componentName: string) =>
`${encodeURIComponent(componentName)}-prop-${prop.name}`;

const getPropTableStyles = ({ euiTheme }: UseEuiTheme) => ({
propTable: css`
Expand Down Expand Up @@ -74,23 +78,28 @@ const getPropTableStyles = ({ euiTheme }: UseEuiTheme) => ({
export const PropTable = ({
definition,
headingLevel: HeadingLevel = 'h3',
showTitle = true,
}: PropTableProps) => {
const styles = useEuiMemoizedStyles(getPropTableStyles);

const tableItems = useMemo<Array<ProcessedComponentProp>>(
() => Object.values(definition.props).sort(
(a, b) => +b.isRequired - +a.isRequired
),
[definition.props],
() =>
Object.values(definition.props).sort(
(a, b) => +b.isRequired - +a.isRequired
),
[definition.props]
);

const columns = useMemo<Array<EuiBasicTableColumn<ProcessedComponentProp>>>(
() => ([
() => [
{
field: 'name',
name: 'Prop',
width: "150",
render(value: ProcessedComponentProp['name'], prop: ProcessedComponentProp) {
width: '150',
render(
value: ProcessedComponentProp['name'],
prop: ProcessedComponentProp
) {
return (
<span css={styles.propName}>
{value}
Expand All @@ -110,44 +119,59 @@ export const PropTable = ({
{
field: 'description',
name: 'Description and type',
render(value: ProcessedComponentProp['description'], prop: ProcessedComponentProp) {
render(
value: ProcessedComponentProp['description'],
prop: ProcessedComponentProp
) {
return (
<EuiFlexGroup direction="column" alignItems="flexStart" gutterSize="s">
<EuiFlexGroup
direction="column"
alignItems="flexStart"
gutterSize="s"
>
{value?.trim() && (
<EuiMarkdownFormat css={styles.description}>{value}</EuiMarkdownFormat>
<EuiMarkdownFormat css={styles.description}>
{value}
</EuiMarkdownFormat>
)}
{prop.type && (
<span css={styles.type}>
Type: {' '}
Type:{' '}
<EuiCode language="ts">
{prop.type.raw || prop.type.name}
</EuiCode>
</span>
)}
</EuiFlexGroup>
);
}
},
},
{
field: 'defaultValue',
name: 'Default value',
width: "120",
render(value: ProcessedComponentProp['defaultValue'], prop: ProcessedComponentProp) {
width: '120',
render(
value: ProcessedComponentProp['defaultValue'],
prop: ProcessedComponentProp
) {
if (prop.isRequired && !value?.trim().length) {
return <EuiTextColor css={styles.required}>Required</EuiTextColor>
return <EuiTextColor css={styles.required}>Required</EuiTextColor>;
}

return value && <EuiCode>{value}</EuiCode>;
},
}
]),
[],
},
],
[]
);

const rowProps = useCallback((item: ProcessedComponentProp) => ({
id: getPropId(item, definition.displayName),
css: styles.tableRow,
}), [definition.displayName]);
const rowProps = useCallback(
(item: ProcessedComponentProp) => ({
id: getPropId(item, definition.displayName),
css: styles.tableRow,
}),
[definition.displayName]
);

return (
<EuiFlexGroup
Expand All @@ -157,9 +181,11 @@ export const PropTable = ({
css={styles.propTable}
>
<header css={styles.header}>
<EuiTitle size="m">
<HeadingLevel>{definition.displayName}</HeadingLevel>
</EuiTitle>
{showTitle && (
<EuiTitle size="m">
<HeadingLevel>{definition.displayName}</HeadingLevel>
</EuiTitle>
)}
<PropTableExtendedTypes definition={definition} />
</header>
<EuiBasicTable
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -97,3 +97,16 @@ export const usePropsWithComponentDefaults = <
[componentDefaults, props]
);
};

/*
* Utilities
*/

/**
* Used only to generate prop type definitions (via `@elastic/eui-docgen`) to document `EuiComponentDefaults` in a props table.
*
* @see https://github.com/elastic/eui/issues/8388
*/
export const EuiProviderComponentDefaultsProps: FunctionComponent<
EuiComponentDefaults
> = () => <></>;
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ EUI's class names are not a guaranteed API and are prone to change, which will r

:::

While EUI's styles are generally low in [specificity](https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity) due to our usage of CSS-in-JS, you may need to ensure that your CSS is defined after ours in your `<head>`. See [**EuiProvider's** cache customization for more style injection options](/utilities/provider#cache-customization).
While EUI's styles are generally low in <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity" target="_blank" rel="noopener noreferrer">**specificity**</a> due to our usage of CSS-in-JS, you may need to ensure that your CSS is defined after ours in your `<head>`. See [**EuiProvider's** cache customization for more style injection options](../utilities/provider.mdx#emotioncache-customization).

```tsx
import React from 'react';
Expand Down Expand Up @@ -222,7 +222,7 @@ import { findByTestSubject, render, screen } from '@elastic/eui/lib/test/rtl'; /

## Customizing component defaults

While all props can be individually customized via props, some components can have their default props customized globally via **EuiProvider's** `componentDefaults` API. [Read more in EuiProvider's documentation](/docs/utilities/provider#component-defaults).
While all props can be individually customized via props, some components can have their default props customized globally via **EuiProvider's** `componentDefaults` API. [Read more in EuiProvider's documentation](../utilities/provider.mdx#component-defaults).

```tsx
<EuiProvider
Expand Down
180 changes: 180 additions & 0 deletions packages/website/docs/components/utilities/provider.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@
---
slug: /utilities/provider
id: utilities_provider
---

import { EuiBetaBadge, EuiSpacer } from '@elastic/eui';

# Provider

**EuiProvider** contains all necessary context providers required for full functionality and styling of EUI. A single instance of **EuiProvider** should exist at the top level of your app, where functionality will flow down the component tree.

## Basic setup

For EUI to work correctly, set up **EuiProvider** at the root of your application:

```jsx
import { EuiProvider } from '@elastic/eui';

const MyApp = () => (
<EuiProvider>
{/* Content */}
</EuiProvider>
);
```

**EuiProvider** includes global reset and utilities styles and other app-wide contexts, functionality, and configuration options. It should only be instantiated **once**. This requirement is enforced internally - if another nested instance of **EuiProvider** is detected, that instance will return early without further processing, and will [warn if configured to do so](#enforce-usage). Nested instances of **EuiThemeProvider**, however, are valid.

## Theming and global styles

To customize the global theme of your app, use the `theme`, `colorMode`, and `modify` props (documented in [EuiThemeProvider](../theming/theme_provider.mdx)). For instance, it's likely that you will want to implement color mode switching at the top level:

```jsx
<EuiProvider colorMode={isDark ? 'dark' : 'light'} />
```
Comment thread
weronikaolejniczak marked this conversation as resolved.
Resolved

If you do not wish your app to include EUI's default global reset CSS or [utility CSS classes](./css_utility_classes.mdx), this is configurable via the `globalStyles` or `utilityClasses` props. You can either pass in your own as a React component returning an <a href="https://emotion.sh/docs/globals" target="_blank" rel="noopener noreferrer">**Emotion Global**</a>, or remove them completely by setting the props to `false`:

```jsx
<EuiProvider globalStyles={false} utilityClasses={false} />
```

### `@emotion/cache` customization

The <a href="https://emotion.sh/docs/@emotion/cache" target="_blank" rel="noopener noreferrer">**@emotion/cache**</a> library provides extra configuration options for EUI's CSS-in-JS behavior:

* **Browser prefixing**: By default, EUI uses CSS browser prefixes based on our <a href="https://www.elastic.co/support/matrix#matrix_browsers" target="_blank" rel="noopener noreferrer">**supported browsers matrix**</a> (latest evergreen only). Should you need to customize this, you can pass in your own prefix plugin via the `stylisPlugins` option.

* **Injection location**: In the case that your app has its own static stylesheet, Emotion's styles may not be injected into the correct location in the `<head>`, causing unintentional overrides or unapplied styles. You can use the `container` option and `<meta>` tags to achieve this.

Comment thread
weronikaolejniczak marked this conversation as resolved.
Resolved
<EuiSpacer />

```html
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<title>My App</title>
<meta name="eui-style-insert">
<link name="compiled-css-here" />
</head>
<body>
<div id="root"></div>
</body>
</html>
```

<EuiSpacer />

```jsx
// App.js
import { EuiProvider, euiStylisPrefixer } from '@elastic/eui'

import createCache from '@emotion/cache';

const euiCache = createCache({
key: 'eui',
stylisPlugins: [euiStylisPrefixer],
container: document.querySelector('meta[name="eui-style-insert"]'),
});

euiCache.compat = true;

<EuiProvider cache={euiCache}>
{/* Content */}
</EuiProvider>
```

For most applications, the above configuration will be enough to have styles ordered correctly. In advanced more cases, you may use the `default`, `global`, and `utility` properties on the `cache` prop to further define where specific styles should be inserted. See [the props documentation](#props) for details.

Any other options available with <a href="https://emotion.sh/docs/@emotion/cache#createcache" target="_blank" rel="noopener noreferrer">**the createCache API**</a> will be respected by EUI. Note that EUI does not include the `@emotion/cache` library, so you will need to add it to your application dependencies.

## Component defaults <EuiBetaBadge alignment="middle" label="Beta" size="s" color="accent" />

:::info Beta status

This functionality is still currently in beta, and the list of components as well as defaults that EUI will be supporting is still under consideration. If you have a component you would like to see added, feel free to <a href="https://github.com/elastic/eui/discussions/6922" target="_blank" rel="noopener noreferrer">**discuss that request in EUI's GitHub repo**</a>.
:::

All EUI components ship with a set of baseline defaults that can usually be configured via props. For example, [EuiFocusTrap](./focus_trap.mdx) defaults to `crossFrame={false}` - i.e., it does not trap focus between iframes. If you wanted to change that behavior in your app across all instances of **EuiFocusTrap**, you would be stuck manually passing that prop over and over again, including in higher-level components (like modals, popovers, and flyouts) that utilize focus traps.

**EuiProvider** allows overriding some component defaults across all component usages globally via the `componentDefaults` prop like so:

```jsx
<EuiProvider
componentDefaults={{
EuiTable: { responsiveBreakpoint: 's', },
EuiTablePagination: { itemsPerPage: 20, },
EuiFocusTrap: { crossFrame: true },
EuiPortal: { insert },
}}
>
<App />
</EuiProvider>
```

The above example would override EUI's default table pagination size (50) across all usages of EUI tables and data grids, all EUI focus traps would trap focus even from iframes, and all EUI portals would be inserted at a specified position (instead of the end of the document body).

The current list of supported components and the prop defaults they accept are:

import componentDefaultsDocgen from '@elastic/eui-docgen/dist/components/provider/component_defaults';

<PropTable definition={componentDefaultsDocgen.EuiProviderComponentDefaultsProps} showTitle={false} />

## Enforce usage

For complex applications with multiple mount points or template wrappers, it may be beneficial to enable logging. Doing so will allow you to see warnings for duplicate **EuiProviders**, as well as when components do not have access to a parent **EuiProvider**. To enable logging or erroring, use `setEuiDevProviderWarning`:

```jsx
import { setEuiDevProviderWarning } from '@elastic/eui';

setEuiDevProviderWarning('warn');
```

Examples of apps that would cause warnings:

```jsx
const AppWithMissingProvider = () => (
<EuiPageTemplate>
{/* Will render, but will warn about missing EuiProvider */}
</EuiPageTemplate>
);

const App = () => (
<EuiProvider>
{/* Content */}
</EuiProvider>
);

const AppWithDuplicateProvider = () => (
<EuiProvider>
{/* Will warn about multiple providers */}
<App />
</EuiProvider>
)
```

`setEuiDevProviderWarning` accepts three levels:

* `'log'`: uses `console.log`
* `'warn'`: uses `console.warn`
* `'error'`: `Throw`s an exception

It also accepts a callback function instead of a default warning level. The warning message string will be passed to your callback, where any custom action can be performed on it. Example usage:

```jsx
import { setEuiDevProviderWarning } from '@elastic/eui';

const customWarningHandler = (message: string) => {
sendWarningToTelemetryService(message);
console.debug(message);
};

setEuiDevProviderWarning(customWarningHandler);
```

## Props

import providerDocgen from '@elastic/eui-docgen/dist/components/provider';

<PropTable definition={providerDocgen.EuiProvider} />