@bento/environment
v0.1.4
Published
Setup a custom environment for your Bento application
Readme
Environment
The @bento/environment package allows you to setup a custom environment for
your components. It allows you to replace any Bento based component with a
custom implementation as well as provide custom properties to the components.
Installation
npm install --save @bento/environmentProps
The Environment component is the main entry point for configuring Bento
components in your application. It allows you to set up global configurations,
such as components, and other settings that will be applied throughout your
application.
import { Environment } from '@bento/environment';The Environment component accepts the following props:
| Prop | Type | Required | Description |
|------|------|----------|------------|
| root | Document \| Node \| ShadowRoot | No | The root node (Document, ShadowRoot, or Node) to use for the environment context.
This will automatically update the window and document props. |
| children | ReactElement<any, string \| JSXElementConstructor<any>> | Yes | The child components that will have access to the configured context. |
| components | Record<string, ComponentType<any> \| { props: Record<string, any>; }> | No | Object that contains components that should be replaced. |
| window | () => Window & typeof globalThis | No | Get the window object for the rendering context. |
| document | () => Document | No | Get the document object for the rendering context. |
| sprite | string | No | External sprite URL. |
Example
The components prop allows you to override the default components used by
Bento. This is useful when you want to customize the behavior or appearance of a
specific component. You can pass a mapping of component names to their
corresponding components.
import { Environment } from '@bento/environment';
import { withSlots } from '@bento/slots';
/* v8 ignore next */
import React from 'react';
/**
* Interface for example component props.
*
* @interface Example
* @public
*/
interface Example {
[key: string]: any;
}
/* c8 ignore start */
const Button: React.FC<Example> = withSlots('OverrideExample.CustomButton', function Button() {
throw new Error('This button should not render as we are overriding it');
});
/* c8 ignore end */
const Link = withSlots('BentoLink', function Link(args: object) {
return <a href="#" className="button-link" {...args} />;
});
/**
* Example component demonstrating environment overrides.
*
* @param {Example} args - The component props.
* @returns {JSX.Element} The rendered component.
* @public
*/
export const Override: React.FC<Example> = withSlots('MyOverrideContainer', function Containers() {
return (
<Environment components={{ 'OverrideExample.CustomButton': Link }}>
<div>
<Button href="foo.html">foo</Button>
<div>
<Button href="bar.html">bar</Button>
</div>
</div>
</Environment>
);
});Shadow DOM, Iframes, and other rendering contexts
Our components are designed to work in a variety of rendering contexts. This
includes the browser, Shadow DOM, and Iframes. The root prop allows you to
specify the root node for the environment context. This allows our components
to correctly access the window and document objects for the rendering
context.
In the example below we are using the react-frame-component package to render
our components in an iframe. By passing the new document object as root
prop, we can ensure that the components that reference the document and
window objects will correctly access the new document and window objects.
/* v8 ignore next */
import Frame, { FrameContextConsumer } from 'react-frame-component';
/* v8 ignore next */
import React, { useContext, useState } from 'react';
import { Environment } from '@bento/environment';
import { withSlots } from '@bento/slots';
import { Box } from '@bento/box';
/**
* Interface for example component props.
*
* @interface Example
* @public
*/
interface Example {
[key: string]: any;
}
/**
* Button component that demonstrates accessing window and document through Box context.
* This shows how components can interact with the correct DOM context when rendered in iframes.
*
* @param {object} args - The component props.
* @returns {JSX.Element} The rendered button.
* @public
*/
const IframeButton: React.FC<Example> = withSlots('IframeButton', function IframeButton(args: object) {
const [clickCount, setClickCount] = useState(0);
const { env } = useContext(Box);
/**
* Handles button click events and demonstrates DOM manipulation within iframe context.
* Updates the click count and changes the background color of the document body.
*
* @returns {void}
* @public
*/
function handleClick() {
// Access the correct document for this context
const doc = env.document();
// Update click count
setClickCount((prev) => prev + 1);
doc.body.style.backgroundColor = clickCount % 2 === 0 ? 'lightblue' : 'lightgreen';
}
return (
<button className="iframe-button" onClick={handleClick} {...args}>
Click me ({clickCount} clicks)
</button>
);
});
/**
* Example component demonstrating iframe rendering with Environment configuration.
* This shows how to use Environment with iframe context and how components can
* access the correct window and document through Box context.
*
* @returns {JSX.Element} The rendered component with iframe content.
* @public
*/
export function IframeRenderingExample() {
return (
<Frame style={{ width: '100%', height: '200px', border: '1px solid #ccc' }}>
<FrameContextConsumer>
{({ document }) => (
<Environment root={document}>
<div style={{ padding: '20px' }}>
<h2>Inside Iframe</h2>
<p>
The button below uses Box context to access the iframe's document and demonstrates DOM manipulation.
</p>
<IframeButton>Click me</IframeButton>
</div>
</Environment>
)}
</FrameContextConsumer>
</Frame>
);
}Component replacement
The components prop can also be used to replace the default components with
your own custom components. This is useful when you want to make a change
to a component that is used in many different places in your application
without having to modify every single instance of the component.
An example use case for this is experimentation. Instead of modifying the
application code, and shared components, you can leverage the components prop
to introduce new components without modifying the application code.
In the example below, we're replacing the default BentoButton component with a custom button component.
import { Environment } from '@bento/environment';
import { withSlots } from '@bento/slots';
/* v8 ignore next */
import React, { useMemo } from 'react';
/**
* Interface for component props.
*
* @interface ComponentProps
* @public
*/
interface ComponentProps {
[key: string]: any;
}
/**
* Original Bento button component that will be replaced.
*
* @param {ComponentProps} props - The component props.
* @returns {JSX.Element} The rendered button.
* @public
*/
/* c8 ignore start */
const BentoButton = withSlots('CustomButtonExample.BentoButton', function BentoButton(props: ComponentProps) {
return <button className="bento-button" {...props} />;
});
/* c8 ignore end */
/**
* Bento card component used as a container.
*
* @param {ComponentProps} props - The component props.
* @returns {JSX.Element} The rendered card container.
* @public
*/
const BentoCard = withSlots('CustomButtonExample.BentoCard', function BentoCard(props: ComponentProps) {
return <div className="bento-card" {...props} />;
});
/**
* Bento text component for displaying content.
*
* @param {ComponentProps} props - The component props.
* @returns {JSX.Element} The rendered text element.
* @public
*/
const BentoText = withSlots('CustomButtonExample.BentoText', function BentoText(props: ComponentProps) {
return <p className="bento-text" {...props} />;
});
/**
* Custom button component that will replace the Bento button.
* This component demonstrates how to create a custom implementation
* that can be used to replace the default Bento button.
*
* @param {ComponentProps} props - The component props.
* @returns {JSX.Element} The rendered custom button.
* @public
*/
const CustomButton = withSlots('CustomButtonExample.CustomButton', function CustomButton(props: ComponentProps) {
return (
<button
className="custom-button"
style={{
backgroundColor: 'blue',
color: 'white'
}}
{...props}
/>
);
});
/**
* Main application component that contains the UI structure.
* This component is wrapped by the Environment component to enable
* component replacement functionality.
*
* @returns {JSX.Element} The rendered application UI.
* @public
*/
const App: React.FC = function App() {
return (
<div className="example-container">
<BentoCard>
<BentoText>This text will be rendered with default styling</BentoText>
<BentoButton>This button will be replaced with a custom one</BentoButton>
</BentoCard>
</div>
);
};
/**
* Example component demonstrating how to use Environment to replace components.
* This example shows how you can replace the default Bento button with
* a custom implementation while maintaining the slot-based architecture.
*
* The key points demonstrated are:
* 1. How to create a custom component that can replace a Bento component
* 2. How to use Environment to manage component replacements
* 3. How to properly memoize the components object to prevent unnecessary re-renders
*
* @returns {JSX.Element} The rendered component with custom button.
* @public
*/
export const CustomButtonExample: React.FC = function CustomButtonExample() {
const components = useMemo(function memo() {
//
// We never want to introduce objects as props to components as new
// instances of the object will be created for each render causing
// unwanted re-renders in your application tree.
//
// Either use the `useMemo` hook to memoize the object or define the
// object outside of the component.
//
return {
'CustomButtonExample.BentoButton': CustomButton
};
}, []);
return (
<Environment components={components}>
<App />
</Environment>
);
};Introducing new props
As the example above shows, you can completely replace any component in the system with a custom implementation. This works well for A/B testing, but sometimes you don't need such a drastic or invasive change. Instead of providing a new component, you can also provide a set of props that should be applied to the component.
By providing the props object, you can introduce new props to the component
without replacing it entirely. This is useful when you want to change the
default behavior of a component without replacing it entirely. For example, if
you want to change the default mode of the BentoIcon component to "sprite", you
can do it like this:
import { Environment } from '@bento/environment';
import { Icon, set } from '@bento/icon';
/* v8 ignore next */
import React from 'react';
//
// Uses the exposed `set` method to introduce the icons and their content to
// the icon store.
//
set({
'my-icon': (
<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
<path d="M3 22v-20l18 10-18 10z" />
</svg>
)
});
/**
* Example component demonstrating component-level overrides.
*
* @returns {JSX.Element} The rendered component with overridden icon.
* @public
*/
export const ComponentLevelExample: React.FC = function ComponentLevelExample() {
return (
<Environment
components={{
BentoIcon: {
props: { mode: 'sprite' }
}
}}
>
<div>
<Icon
height={48}
width={48}
icon="my-icon"
title="In this example it should be rendered as sprite through environment level configuration"
/>
<p>This icon will be loaded as sprite, even though the mode is not specified.</p>
</div>
</Environment>
);
};