@digital-herd/content-hub-sdk
v1.2.46
Published
React helpers for External sitecore contenthub components
Downloads
86
Readme
React helpers for External sitecore contenthub components
Author
👤 Digital Herd
- Website: https://www.digital-herd.com/
- Installation
- Components
- Utilities
Installation
npm install @digital-herd/content-hub-sdk
ContenthubContext
Each Contenthub External component that uses the Digital herd sdk needs to be wrapped in the Contenthub context By using the context, you can handy utility hooks to have access to the contenhub properties, config,...
usage
In the index of your external component, you can use this provider as root
import { ContentHubContextProps, ContentHubProvider} from '@digital-herd/content-hub-sdk'
export default (container: HTMLElement) => {
const root = ReactDOM.createRoot(container);
return {
render(context: ContentHubContextProps) {
root.render(
<ContentHubProvider reactContainer={container} {...context}>
<App />
</ContentHubProvider>,
);
},
unmount() {
root.unmount();
}
};
};
By using this component, you now have access to the following hooks:
useContentHub
- A hook that returns all the
ContentHubContextProps
provided by ContentHub.
- A hook that returns all the
useContentHubConfig
- A hook for fetching component configuration, enabling the addition of default settings.
useUser
- A hook that retrieves user information.
Hook usage example
import React from "react";
import { useContentHub, useContentHubConfig, useUser } from "@digital-herd/content-hub-sdk";
const UserProfile: React.FC = () => {
// Access ContentHub context
const contentHub = useContentHub();
// Fetch configuration with default settings
const config = useContentHubConfig<{ theme: string }>({
theme: "light", // Default theme
});
// Get user information
const { user, isSuperUsersGroupMember, isAdministrator, isInGroup } = useUser();
return (
<div >
<p>theme: {config.theme}</p>
<h1>User Profile</h1>
<p>Name: {user.userName}</p>
<p>Groups: {user.userGroups.join(", ")}</p>
<p>Is Super User: {isSuperUsersGroupMember ? "Yes" : "No"}</p>
<p>Is Administrator: {isAdministrator ? "Yes" : "No"}</p>
<p>In Group "Editors": {isInGroup("Editors") ? "Yes" : "No"}</p>
</div>
);
};
export default UserProfile;
Components
We have a collection of React components that can be utilized in the Content Hub's external components. Below is an overview of these components:
ContenthubIcon
A React component that displays icons from the Contenthub icon library.
Properties
- name:
string
(required)- The name of the contenthub icon to be displayed.
- size:
number | string
(optional)- The size of the icon. Defaults to
1.5rem
.
- The size of the icon. Defaults to
- color:
string
(optional)- The color of the icon.
- otherTypographyProps:
TypographyProps
(optional)- Additional properties passed to the MUI
Typography
component.
- Additional properties passed to the MUI
Example
import React from 'react';
import { ContenthubIcon } from '@digital-herd/content-hub-sdk';
import { Box } from '@mui/material';
const MyComponent = () => {
return (
<Box>
<ContenthubIcon name="home" size="2rem" color="blue" />
<ContenthubIcon name="settings" size="1.5rem" color="green" />
</Box>
);
};
export default MyComponent;
Dropdown
A React component that creates a dropdown menu with customizable actions.
Properties
DropdownItemProps
(action)
- id:
string
(required)- The unique identifier for the dropdown item.
- label:
string
(required)- The text label for the dropdown item.
- icon:
React.ReactNode
(optional)- An icon to display alongside the label.
- loading:
boolean
(optional)- If
true
, shows a loading indicator for the item.
- If
- onClick:
DropdownItemOnClick
(optional)- A callback function that is called when the item is clicked.
- href:
string
(optional)- A URL that the item should link to. When provided, the item will render as an
<a>
element.
- A URL that the item should link to. When provided, the item will render as an
- disabled:
boolean
(optional)- If
true
, the item is disabled.
- If
- show:
boolean
(optional)- If
false
, the item is not shown.
- If
DropdownProps
- actions:
DropdownItemProps[]
(required)- An array of action items to display in the dropdown menu.
- label:
string
(optional)- The ARIA label for the dropdown button.
- onClick:
(e: React.MouseEvent<HTMLButtonElement>) => void | false
(optional)- A callback function that is called when the dropdown button is clicked.
- id:
string
(optional)- The ID of the dropdown component.
- color:
"default" | "primary" | "error"
(optional)- The color of the dropdown button. Defaults to
primary
.
- The color of the dropdown button. Defaults to
- icon:
React.ReactNode
(optional)- An icon to display in the dropdown button.
- disabled:
boolean
(optional)- If
true
, the dropdown button is disabled.
- If
- href:
string
(optional)- A URL that the dropdown button should link to. When provided, the button will render as an
<a>
element.
- A URL that the dropdown button should link to. When provided, the button will render as an
- noActionsBehavior:
"remove" | "disabled" | "normal"
(optional)- Behavior when there are no actions. Can be
remove
,disabled
, ornormal
. Defaults toremove
.
- Behavior when there are no actions. Can be
- buttonLabel:
string
(optional)- The label for the dropdown button.
Example
import React from 'react';
import { Dropdown, ContenthubIcon } from '@digital-herd/content-hub-sdk';
const MyComponent = () => {
const actions = [
{
id: '1',
label: 'Action 1',
icon: <ContenthubIcon name="icon1" />,
onClick: (event, id, onClose) => {
console.log('Action 1 clicked');
onClose();
},
},
{
id: '2',
label: 'Action 2',
icon: <ContenthubIcon name="icon2" />,
loading: true,
},
{
id: '3',
label: 'Action 3',
disabled: true,
},
];
return (
<Dropdown
actions={actions}
label="My Dropdown"
buttonLabel="Open Dropdown"
icon={<ContenthubIcon name="menu" />}
color="primary"
/>
);
};
export default MyComponent;
HtmlToMuiRenderer
A React component that converts Html content string to Material-UI.
Properties
- children:
string
(required)- The Html content string to be rendered.
Example
import React from 'react';
import { HtmlToMuiRenderer } from '@digital-herd/content-hub-sdk';
const markdownContent = `
<h1>>Heading 1</h1>
<h2>>Heading 2</h2>
<h3>>Heading 3</h3>
<h4>>Heading 4</h4>
<p>Paragrapgh</p>
`;
const MyComponent = () => {
return <HtmlToMuiRenderer>{markdownContent}</HtmlToMuiRenderer>;
};
export default MyComponent;
RelationEditorInput
A React Component that has the OOOTB Relation editor input from contenthub layout
Properties
- items:
{ value: any; label: string }[]
(required)- An array of objects representing the items to be displayed.
- value: Any value representing the item.
- label: A string representing the item's label.
- onAdd:
() => void
(required)- A callback function to be called when the add button is clicked.
- onChange:
(items: { value: any; label: string }[]) => void
(required)- A callback function to be called when the items are changed (e.g., an item is removed).
- hasError:
boolean
- An optional boolean to indicate if there is an error, which changes the border color.
Example
import React, { useState } from 'react';
import { RelationEditorInput } from '@digital-herd/content-hub-sdk';
const MyComponent = () => {
const [items, setItems] = useState([
{ value: 1, label: 'Item 1' },
{ value: 2, label: 'Item 2' },
]);
const handleAdd = () => {
const newItem = { value: Date.now(), label: `Item ${items.length + 1}` };
setItems([...items, newItem]);
};
const handleChange = (newItems) => {
setItems(newItems);
};
return (
<RelationEditorInput
items={items}
onAdd={handleAdd}
onChange={handleChange}
hasError={items.length === 0}
/>
);
};
export default MyComponent;
SearchBar
A React functional component that provides a search input field with optional debounced input handling in Contenthub style.
Properties
- onSearch:
(input: string) => void
- Optional callback function called when the search form is submitted.
- onChange:
(input: string) => void
- Optional callback function called when the input value changes.
- value:
string
- Optional controlled input value.
- debounce:
boolean
- Optional boolean to enable or disable debounced input changes. If enabled, the
onChange
callback will be called with a delay.
- Optional boolean to enable or disable debounced input changes. If enabled, the
Example
import React, { useState } from 'react';
import { SearchBar } from '@digital-herd/content-hub-sdk';
const MyComponent = () => {
const [searchResult, setSearchResult] = useState('');
const handleSearch = (input) => {
console.log('Search term submitted:', input);
// Perform search or handle search term
setSearchResult(input);
};
const handleChange = (input) => {
console.log('Search term changed:', input);
// Optionally handle input change
};
return (
<div>
<SearchBar onSearch={handleSearch} onChange={handleChange} debounce />
<p>Search Result: {searchResult}</p>
</div>
);
};
export default MyComponent;
TableRowLoader
A React functional component that renders a loading state for table rows as the Contenthub OOTB table loader.
Properties
- cols:
number
- Optional. The number of columns to display in each loading row. Defaults to
1
.
- Optional. The number of columns to display in each loading row. Defaults to
- rows:
number
- Optional. The number of loading rows to display. Defaults to
3
.
- Optional. The number of loading rows to display. Defaults to
Example
import React from 'react';
import { Table, TableBody, TableHead } from '@mui/material';
import { TableRowLoader } from '@digital-herd/content-hub-sdk';
const MyTable = ({ loading }) => {
return (
<Table>
<TableHead>
<tr>
<th>Header 1</th>
<th>Header 2</th>
<th>Header 3</th>
</tr>
</TableHead>
<TableBody>
{loading ? (
<TableRowLoader cols={3} rows={5} />
) : (
// Your table rows go here
<tr>
<td>Data 1</td>
<td>Data 2</td>
<td>Data 3</td>
</tr>
)}
</TableBody>
</Table>
);
};
export default MyTable;
Utilities
We have a collection of utilities and react hooks that can be used in the external components
- Contenthub effects
- DOM Element utilities
- Entity functions & hooks
- Content Hub Event utilities
- Modal hooks
- REST Entity Querying
- Permission & access
- Script utilities
- Search utilities
- Selection utilities
Contenthub effects
This document describes two custom React hooks: useSearchFinishedEffect
and useEntityRefreshedEffect
. These hooks are designed to interact with the Sitecore Content Hub API and handle specific events within your application.
useSearchFinishedEffect
Hook
The useSearchFinishedEffect
hook allows you to listen for the searchFinished
event from the Content Hub API and execute a callback function when the event occurs.
Signature
export const useSearchFinishedEffect(
cb: (payload: SearchFinishedPayload) => void | (() => void),
searchIdentifier: string,
deps: React.DependencyList,
active?: boolean,
): void;
Parameters
- cb ((payload: SearchFinishedPayload) => void | (() => void)): A callback function that gets executed when the searchFinished event is triggered. The function receives the payload of the event.
- searchIdentifier (string): A unique identifier to filter the search events. Only events with identifiers that start with this value will trigger the callback.
- deps (React.DependencyList): A list of dependencies that determine when the effect should re-run. If any dependency changes, the effect will re-run.
- active (boolean, optional): A flag to activate or deactivate the search event listener. Defaults to true.
Example
import { useSearchFinishedEffect } from '@digital-herd/content-hub-sdk';
const MyComponent = () => {
useSearchFinishedEffect(
(payload) => {
console.log("Search finished:", payload);
},
"my-search",
[],
true // Activate the listener
);
return <div>My Component</div>;
};
useEntityRefreshedEffect
Hook
The useEntityRefreshedEffect hook allows you to listen for the EntityRefreshed event from the Content Hub API. It executes a callback function when an entity is refreshed, ensuring that your component reacts to updates appropriately.
Signature
export const useEntityRefreshedEffect(
cb: () => any,
deps: React.DependencyList,
initialCall?: boolean,
): () => any;
Parameters
- cb (() => any): A callback function that gets executed when the EntityRefreshed event is triggered.
- deps (React.DependencyList): A list of dependencies that determine when the effect should re-run. If any dependency changes, the effect will re-run.
- initialCall (boolean, optional): A flag to indicate whether the callback should be called immediately on the first render. Defaults to true.
Example
import { useEntityRefreshedEffect } from '@digital-herd/content-hub-sdk';
const MyComponent = () => {
const manualRefresh = useEntityRefreshedEffect(() => {
console.log("Entity has been refreshed!");
}, []);
return (
<div>
My Component
<button onClick={manualRefresh}>Refresh Entity</button>
</div>
);
};
DOM Element utilities
This documentation describes a set of utility functions for observing DOM elements and a custom React hook for tracking a specific search component's table in the DOM.
watchDomElementsInContainer
This function observes a specified container for changes and triggers a callback function whenever a matching DOM element is added or removed.
Signature
export const watchDomElementsInContainer = <T = Element>(
selector: string,
cb: (element: T[]) => void,
rootElement: Element,
options?: { config: MutationObserverInit }
): (() => void);
Parameters
- selector (
string
): A CSS selector string used to find the target elements. - cb (
(element: T[]) => void
): A callback function that is called with the matched elements. - rootElement (
Element
): The DOM element to observe. - options (
{ config: MutationObserverInit }
, optional): Configuration options for the MutationObserver.
Returns
A function that, when called, disconnects the observer.
watchDomElementInContainer
This function is similar to watchDomElementsInContainer
, but it only triggers the callback with a single DOM element or null
if no matching elements are found.
Signature
export const watchDomElementInContainer = <T = Element>(
selector: string,
cb: (element: T | null) => void,
rootElement: Element,
options?: { config: MutationObserverInit }
): (() => void);
Parameters
- selector (
string
): A CSS selector string used to find the target element. - cb (
(element: T | null) => void
): A callback function that is called with the first matched element ornull
. - rootElement (
Element
): The DOM element to observe. - options (
{ config: MutationObserverInit }
, optional): Configuration options for the MutationObserver.
Returns
A function that, when called, disconnects the observer.
waitForDomElements
This function waits for specified DOM elements to appear in the DOM and executes a callback when they are found or if a timeout occurs.
Signature
export const waitForDomElements = <T = Element>(
selector: string,
cb: (element: T[] | null) => void,
rootElement?: Element,
options?: { config: MutationObserverInit },
timeoutInMs?: number
): (() => void);
Parameters
- selector (
string
): A CSS selector string used to find the target elements. - cb (
(element: T[] | null) => void
): A callback function that is called with the found elements ornull
. - rootElement (
Element
, optional): The DOM element to search within. Defaults todocument.documentElement
. - options (
{ config: MutationObserverInit }
, optional): Configuration options for the MutationObserver. - timeoutInMs (
number
, optional): The timeout duration in milliseconds. Defaults to15000
ms.
Returns
A function that, when called, disconnects the observer and clears the timeout.
waitForDomElement
This function is similar to waitForDomElements
, but it triggers the callback with only the first matched element or null
.
Signature
export const waitForDomElement = <T = Element>(
selector: string,
cb: (element: T | null) => void,
rootElement?: Element,
options?: { config: MutationObserverInit },
timeoutInMs?: number
): (() => void);
Parameters
- selector (
string
): A CSS selector string used to find the target element. - cb (
(element: T | null) => void
): A callback function that is called with the first matched element ornull
. - rootElement (
Element
, optional): The DOM element to search within. Defaults todocument.documentElement
. - options (
{ config: MutationObserverInit }
, optional): Configuration options for the MutationObserver. - timeoutInMs (
number
, optional): The timeout duration in milliseconds. Defaults to15000
ms.
Returns
A function that, when called, disconnects the observer and clears the timeout.
useWaitForDomElements
Hook
This React hook provides an easy way to wait for DOM elements to appear and returns them as state.
Signature
export const useWaitForDomElements = <T = Element>(
selector: string,
rootElement?: Element,
options?: { config: MutationObserverInit },
timeoutInMs?: number
): T[] | null;
Parameters
- selector (
string
): A CSS selector string used to find the target elements. - rootElement (
Element
, optional): The DOM element to search within. Defaults todocument.documentElement
. - options (
{ config: MutationObserverInit }
, optional): Configuration options for the MutationObserver. - timeoutInMs (
number
, optional): The timeout duration in milliseconds. Defaults to15000
ms.
Returns
An array of matched DOM elements or null
if none are found.
example
import React from "react";
import { useWaitForDomElements } from "./path-to-your-hooks";
const MyComponent: React.FC = () => {
const elements = useWaitForDomElements<HTMLDivElement>(".my-element");
return (
<div>
<h1>Waiting for elements...</h1>
{elements ? (
<div>
{elements.map((el, index) => (
<div key={index}>{el.innerText}</div>
))}
</div>
) : (
<p>No elements found yet.</p>
)}
</div>
);
};
export default MyComponent;
useWaitForDomElement
Hook
This React hook is similar to useWaitForDomElements
but returns only the first matched element or null
.
Signature
export const useWaitForDomElement = <T = Element>(
selector: string,
rootElement?: Element,
options?: { config: MutationObserverInit },
timeoutInMs?: number
): T | null;
Parameters
- selector (
string
): A CSS selector string used to find the target element. - rootElement (
Element
, optional): The DOM element to search within. Defaults todocument.documentElement
. - options (
{ config: MutationObserverInit }
, optional): Configuration options for the MutationObserver. - timeoutInMs (
number
, optional): The timeout duration in milliseconds. Defaults to15000
ms.
Returns
The first matched DOM element or null
if none are found.
Example
import React from "react";
import { useWaitForDomElement } from "./path-to-your-hooks";
const MySingleElementComponent: React.FC = () => {
const element = useWaitForDomElement<HTMLDivElement>(".my-single-element");
return (
<div>
<h1>Waiting for single element...</h1>
{element ? (
<div>{element.innerText}</div>
) : (
<p>No element found yet.</p>
)}
</div>
);
};
export default MySingleElementComponent;
useSearchTableDomElement
Hook
This hook tracks a specific search component's table DOM element by waiting for it to appear in the DOM
Signature
export const useSearchTableDomElement = (searchComponentIdentifier: string): HTMLElement | null;
Parameters
- searchComponentIdentifier (
string
): the unique identifier for the search component whose table element is being tracked.
Returns
The matched table DOM element or null
if it has not yet appeared.
example
import React from "react";
import { useSearchTableDomElement } from "./path-to-your-hooks";
const MyComponent: React.FC<{ identifier: string }> = ({ identifier }) => {
const tableElement = useSearchTableDomElement(identifier);
React.useEffect(() => {
if(!tableElement){
return;
}
console.log('Do something with tableElement')
},[tableElement])
return null;
};
export default MyComponent;
useDomElementUpdater
Hook
The useDomElementUpdater hook is a React custom hook designed to monitor and update DOM elements dynamically. This hook is particularly useful for making real-time updates to the content of OOTB contenthub components
Signature
export const useDomElementUpdater = ({
rootElement = document.documentElement,
changes,
isHtml = false,
}: {
rootElement?: string | HTMLElement;
changes: {
[key: string]: string;
};
isHtml?: boolean;
}) => void
Parameters
- rootElement: The root element to observe for changes. Defaults to document.documentElement.
- changes: An object where keys are selectors and values are the new content to replace the existing content. Supports dynamic content replacement using the ${currentText} placeholder.
- isHtml: A boolean flag indicating whether the changes should be interpreted as HTML. Defaults to false.
Example
import React from 'react';
import { useDomElementUpdater } from '@digital-herd/content-hub-sdk';
const MyComponent = () => {
useDomElementUpdater({
rootElement: '#root',
changes: {
'.example-class': 'New content for .example-class',
'#example-id:content("Old content")': 'New content for #example-id',
'p:replace("oldText")': 'Replaced text with ${currentText}',
},
isHtml: false,
});
return <div id="root">Your content here</div>;
};
export default MyComponent;
Entity functions & hooks
This document describes the utilities for rehydrating entities from the Sitecore Content Hub using the ContentHubClient
. The utilities include functions for loading single or multiple entities, obtaining labels for specific cultures, extracting entity IDs and definitions from HREFs, and a custom hook for rehydrating entities in a React component.
rehydrateEntity
Fetches a single entity from Content Hub using its ID, properties, and relations.
Signature
export const rehydrateEntity = async (
client: ContentHubClient,
id: number | string,
properties: string[] = [],
relations: string[] = [],
cultureLoadOption = new CultureLoadOption(),
) => { ... }
Description
Parameters
- client: Instance of ContentHubClient.
- id: The ID of the entity to retrieve.
- properties: An optional array of property names to load.
- relations: An optional array of relation names to load.
- cultureLoadOption: An optional CultureLoadOption instance to specify culture settings.
Returns
The entity as an IEntity object or null if not found.
rehydrateEntities
Fetches multiple entities from Content Hub based on their IDs.
Signature
export const rehydrateEntities = async (
client: ContentHubClient,
ids: number[] | string[],
properties?: string[],
relations?: string[],
cultureLoadOption = new CultureLoadOption(),
) => { ... }
Parameters:
- client: Instance of ContentHubClient.
- ids: An array of IDs for the entities to retrieve.
- properties: An optional array of property names to load.
- relations: An optional array of relation names to load.
- cultureLoadOption: An optional CultureLoadOption instance to specify culture settings.
Returns
An array of entities as IEntity objects.
getEntityIdFromIdentifier
The getEntityIdFromIdentifier function fetches the entity ID for a given identifier. It uses a cache to store previously fetched entity IDs to avoid repeated API calls for the same identifier.
Signature
export const getEntityIdFromIdentifier = async (client: ContentHubClient, identifier: string) => Promise<number>
Parameters:
- client: Instance of ContentHubClient.
- identifier: A string representing the entity identifier.
Returns
- The function returns a Promise that resolves to the entity ID corresponding to the given identifier. If the entity is not found, it returns null.
Example
import { getEntityIdFromIdentifier } from 'your-library';
const fetchEntityId = async (identifier) => {
const entityId = await getEntityIdFromIdentifier(client, identifier);
console.log('Entity ID:', entityId);
};
fetchEntityId('sample-identifier');
getEntityIdsFromIdentifiers
The getEntityIdsFromIdentifiers function fetches the entity IDs for a list of identifiers. It uses a cache to store previously fetched entity IDs to avoid redundant API calls and improves performance for bulk requests.
Signature
export const getEntityIdsFromIdentifiers = async (client: ContentHubClient, identifiers: string[]) => Promise<{ [key: string]: number }>
Parameters:
- client: Instance of ContentHubClient.
- identifiers: A array of strings representing the entity identifier.
Returns
- The function returns a Promise that resolves to an object where the keys are the entity identifiers and the values are the corresponding entity IDs.
Example
import { getEntityIdsFromIdentifiers } from 'your-library';
const fetchEntityIds = async (identifiers) => {
const entityIds = await getEntityIdsFromIdentifiers(client, identifiers);
console.log('Entity IDs:', entityIds);
};
fetchEntityIds(['identifier-1', 'identifier-2', 'identifier-3']);
useRehydrateEntity
Hook
A custom hook that rehydrates an entity and manages its state in a React component.
export const useRehydrateEntity = ({
entityId,
properties = [],
relations = [],
canBeLoaded = true,
reloadOn,
}: {
entityId?: number | string;
properties?: string[];
relations?: string[];
canBeLoaded?: boolean;
reloadOn?: ContenthubEventType[];
}) => { ... }
Parameters
- entityId: The ID of the entity to rehydrate.
- properties: An optional array of property names to load.
- relations: An optional array of relation names to load.
- canBeLoaded: A boolean to control whether the entity can be loaded.
- reloadOn: An optional array of ContenthubEventType to trigger reload on specific events.
Returns
An object containing:
- entity: The rehydrated entity or null.
- refreshEntity: A function to manually refresh the entity.
Example
const MyComponent = () => {
const { entity, refreshEntity } = useRehydrateEntity({
entityId: 123,
properties: ["name", "description"]
});
return (
<div>
<h1>{entity?.name}</h1>
<button onClick={refreshEntity}>Refresh Entity</button>
</div>
);
};
Content Hub Event utilities
This module provides functionality for handling events related to the content hub. It defines an enumeration for various event types and functions to send and listen for custom events.
Enum: ContenthubEventType
This enum defines the different types of events that are be dispatched within the content hub.
Values:
EntityChanged
: Triggered when an entity changes.SelectionChanged
: Triggered when the selection changes.EntityCreated
: Triggered when a new entity is created.EntityDeleted
: Triggered when an entity is deleted.EntitySaved
: Triggered when an entity is saved.EntityUpdated
: Triggered when an entity is updated.EntityRefreshed
: Triggered when an entity is refreshed.searchFinished
: Triggered when a search operation is completed.
sendCustomEvent
Sends a custom event so you can communicate between external components
Parameters:
eventType
:string | number
- The type of event to send. This will be appended to the event name.props
:T
(optional) - Additional properties to include in the event detail.
Example:
sendCustomEvent("custom-event", { id: 123, name: "New Entity" });
listenToCustomEvent
Listens for so you can communicate between external components
Parameters:
eventType
:string | number
- The type of event to listen for.cb
:(props: T) => void
- A callback function to be called when the event is received.
Returns:
eventDisposeFn
: A function to remove the event listener when called.
Example:
const dispose = listenToCustomEvent("custom-event", (props) => {
console.log("Entity created with props:", props);
});
// Later, to remove the listener
dispose();
listenToContenthubEvent
Listens for a specific content hub event.
Parameters:
eventType
:ContenthubEventType
- The type of content hub event to listen for.cb
:(event: CustomEvent<E>) => void
- A callback function to handle the event.
Returns:
eventDisposeFn
: A function to remove the event listener when called.
Example:
const dispose = listenToContenthubEvent(ContenthubEventType.EntityDeleted, (event) => {
console.log("Entity deleted:", event.detail);
});
// Later, to remove the listener
dispose();
Modal hooks
useModalHelper
A React hook that provides utilities for managing Contenthub dialogs, such as customizing the footer, setting full height, and handling close events where the external coponent is embeded.
usage
import { useModalHelper } from "@digital-herd/content-hub-sdk";
const { modalDom } = useModalHelper();
Parameters
- isCustomFooterComponent (optional): boolean
- Determines if the modal has a custom footer component. Defaults to false.
- fullHeight (optional): boolean
- Determines if the modal should take the full height of the screen. Defaults to false.
- onClose (optional): () => void
- A callback function that gets called when the modal is closed.
Returns
- modalDom: The root element of the modal.
- modalCloseDom: The close button element within the modal.
- getModalComponentRoot: A function to get the root element of the modal component.
- onCloseModal: A function to programmatically close the modal.
example
import React from 'react';
import { useModalHelper } from "@digital-herd/content-hub-sdk";
const MyComponent = () => {
const { onCloseModal } = useModalHelper({
isCustomFooterComponent: true,
fullHeight: true,
onClose: () => console.log('Modal closed'),
});
return (
<div>
<button onClick={onCloseModal}>Close Modal</button>
</div>
);
};
export default MyComponent;
useDisableModalClose
A hook to enable or disable the modal's close button where the external component is embeded.
usage
import { useDisableModalClose } from "@digital-herd/content-hub-sdk";
useDisableModalClose();
Parameters
- disable: boolean
- If true, hides the modal's close button. If false, shows the modal's close button.
example
import React, { useState } from 'react';
import { useDisableModalClose } from './path-to-your-hooks';
const MyComponent = () => {
const [isCloseDisabled, setIsCloseDisabled] = useState(false);
useDisableModalClose(isCloseDisabled);
return (
<div>
<button onClick={() => setIsCloseDisabled(!isCloseDisabled)}>
Toggle Close Button
</button>
</div>
);
};
export default MyComponent;
useModalTitleUpdate
A hook to update the modal's title where the external component is embeded.
usage
import { useModalTitleUpdate } from "@digital-herd/content-hub-sdk";
useModalTitleUpdate("");
Parameters
- title: string
- The new title to set for the modal.
example
import React, { useState } from 'react';
import { useModalTitleUpdate } from './path-to-your-hooks';
const MyComponent = () => {
const [title, setTitle] = useState('Initial Title');
useModalTitleUpdate(title);
return (
<div>
<input
type="text"
value={title}
onChange={(e) => setTitle(e.target.value)}
placeholder="Update Modal Title"
/>
</div>
);
};
export default MyComponent;
REST Entity Querying
This document describes the restEntityQuerying
function, which allows querying entities from the Sitecore Content Hub API.
restEntityQuerying
The restEntityQuerying
function is an asynchronous function that queries entities based on the provided parameters.
Signature
export const restEntityQuerying = async ({
client,
query,
members?: string[];
take?: number;
offset?: number;
cultures?: string[];
sort?: string;
order?: "asc" | "desc";
}: restEntityQueryingProps) => Promise<IRestQueryResult | undefined>;
Parameters
- client (ContentHubClient): The Content Hub client instance used to make API requests.
- query (string): The search query to filter entities.
- members (string[], optional): An array of member identifiers to filter the query. Defaults to an empty array.
- take (number, optional): The number of items to return. Defaults to 100.
- offset (number, optional): The number of items to skip before starting to collect the result set. Defaults to 0.
- cultures (string[], optional): An array of culture identifiers to filter the query. If not provided, defaults to - ["en-US"].
- sort (string, optional): The field by which to sort the results.
- order ("asc" | "desc", optional): The sort order. Can be either ascending or descending.
example
import { restEntityQuerying } from "@digital-herd/content-hub-sdk";
const query = "Definition.Name == 'M.Asset'";
const members = ["FileName"];
const take = 50;
async function fetchEntities(client) {
try {
const result = await restEntityQuerying({
client,
query,
members,
take,
});
console.log(result);
} catch (error) {
console.error("Error fetching entities:", error);
}
}
fetchEntities();
Permission & access
usePermissions
Hook
The usePermissions hook is a React custom hook designed to manage and check permissions for entities within the ContentHub. It retrieves the permissions for a specified entity and provides utility functions to check for specific permissions.
Signature
= ({
entityId,
canBeLoaded = true,
}: { entityId?: number | null; canBeLoaded?: boolean }) => { hasPermission: (permission:string) => boolean, permissions:string[], permissionsLoaded: boolean }
Parameters
- entityId: The ID of the entity to check permissions for. If not provided, the hook will use the default entity ID from the context.
- canBeLoaded : A boolean flag indicating whether permissions should be loaded. Defaults to true.
Returns
- hasPermission: A function that takes a permission string or Permission enum and returns a boolean indicating whether the permission is granted.
- permissions: An array of permissions for the entity.
- permissionsLoaded: A boolean indicating whether the permissions have been loaded.
Example
import React from 'react';
import { usePermissions, Permission } from 'your-library';
const MyComponent = () => {
const { hasPermission, permissions, permissionsLoaded } = usePermissions({ entityId: 123 });
if (!permissionsLoaded) {
return <div>Loading permissions...</div>;
}
return (
<div>
{hasPermission(Permission.Read) && <p>You have read permission.</p>}
{hasPermission(Permission.Update) && <p>You have update permission.</p>}
<p>All permissions: {permissions.join(', ')}</p>
</div>
);
};
export default MyComponent;
useHasEntityAccess
Hook
The useHasEntityAccess hook is a React custom hook designed to check if the current user has access to a specific entity in the ContentHub. Most used to check if you have access to a page
Signature
export const useHasEntityAccess = (identifier: string) => { hasAccess:boolean, loaded:boolean }
Parameters
- identifier: The identifier of the entity to check access for.
Returns
- hasAccess: A boolean indicating whether the user has access to the entity.
- loaded: A boolean indicating whether the access check has been completed.
Example
import React from 'react';
import { useHasEntityAccess } from 'your-library';
const MyComponent = ({ entityIdentifier }) => {
const { hasAccess, loaded } = useHasEntityAccess(entityIdentifier);
if (!loaded) {
return <div>Checking access...</div>;
}
return (
<div>
{hasAccess ? <p>You have access to this entity.</p> : <p>You do not have access to this entity.</p>}
</div>
);
};
export default MyComponent;
Script utilities
useTriggerScript
Hook
The useTriggerScript hook provides an easy way to trigger scripts on the ContentHub server. This hook handles the interaction with the ContentHub client, manages the submission state, and optionally displays success or error messages.
Hook Return Values
- triggerScript: A function to trigger a script with various options.
- submitting: A boolean indicating if a script is currently being submitted.
Parameters
The handleTrigger
function accepts the following parameters:
- scriptIdentifier: The identifier of the script to be triggered.
- body: The request body to be sent with the script execution.
- withMessages: (optional) A boolean indicating whether to show success or error messages. Default is false.
- onSuccess: (optional) A callback function to be executed when the script is successfully executed.
- onError: (optional) A callback function to be executed when the script execution fails.
- errorMessage: (optional) A custom error message to be shown when the script execution fails.
- successMessage: (optional) A custom success message to be shown when the script execution succeeds. Can be "output" to use the script's output.
- defaultErrorMessage: (optional) A default error message to be used if none is provided.
- includeUserIdInBody: (optional) A boolean indicating whether to include the user ID in the request body. Default is false.
- onFinally: (optional) A callback function to be executed after the script execution is completed, regardless of success or failure.
Example
import React from 'react';
import { useTriggerScript } from 'your-library';
const MyComponent = () => {
const { triggerScript, submitting } = useTriggerScript();
const executeScript = () => {
triggerScript({
scriptIdentifier: 'my-script-id',
body: { key: 'value' },
withMessages: true,
onSuccess: (content) => {
console.log('Script executed successfully:', content);
},
onError: (error) => {
console.error('Error executing script:', error);
},
});
};
return (
<div>
<button onClick={executeScript} disabled={submitting}>
{submitting ? 'Submitting...' : 'Execute Script'}
</button>
</div>
);
};
export default MyComponent;
Search utilities
useSearchListener
Hook
The useSearchListener hook allows you to listen for search events on specified search components within the ContentHub environment. This hook is useful for intercepting and modifying search requests before they are executed.
Parameters
The useSearchListener hook accepts the following parameters:
- cb: A callback function that will be called when the specified search event occurs. The function can return a modified SearchRequest or void. If the function returns a Promise, the hook will wait for the promise to resolve before continuing.
- config: An object containing the following configuration options:
- identifiers: A string or an array of strings representing the identifiers of the search components to listen to.
- eventName: (optional) The name of the event to listen for. Default is "BEFORE_SEARCH".
- active: (optional) A boolean indicating whether the listener is active. Default is true.
- onlyOnFirstLoad: (optional) A boolean indicating whether to only trigger the listener on the first load. Default is false.
- reactivate: (optional) A boolean indicating whether to reactivate the search components after setting the listener. Default is true.
- forceCulture: (optional) A string indicating the culture to force on the search request.
- deprecatedInterceptRequest: (optional) A boolean indicating whether to use the deprecated request interceptor. Default is false.
- deps: (optional) An array of dependencies that, when changed, will reinitialize the listener.
Example
import React from 'react';
import { useSearchListener } from 'your-library';
import { FilterOperator } from "@sitecore/sc-contenthub-webclient-sdk/dist/models/search/filter-operator";
import { RequestedFilterType } from "@sitecore/sc-contenthub-webclient-sdk/dist/models/search/requested-filter-type";
const MyComponent = () => {
useSearchListener((searchRequest, identifier) => {
// Modify the search request as needed
searchRequest.filters.push({
filterType: RequestedFilterType.InFilter,
operator: FilterOperator.AnyOf,
fieldName: `relationName`,
values: [123],
hidden: true,
});
return searchRequest;
}, {
identifiers: 'my-search-component-id',
});
return null;
};
export default MyComponent;
Selection utilities
useSelection
Hook
The useSelection hook provides a set of functions to manage the selection of items within ContentHub. This includes fetching the current selection, adding to the selection, clearing the selection, and setting a new selection.
Parameters
- selectionIdentifier: A string representing the identifier of the selection pool.
- selectionDefinition: A string representing the definition of the selection.
- subPoolId: (optional) A number representing the sub-pool ID. If null, it is ignored.
Returns
The return value of the useSelection hook is an object with the following properties:
- loading: A boolean indicating whether a selection operation is currently in progress.
- getSelection: A function to fetch the current selection.
- clearSelection: A function to clear the current selection.
- addToSelection: A function to add items to the current selection.
- setSelection: A function to set the current selection, replacing any existing selection.
- getSelectionWithEntityPermission: A function to fetch the current selection and checking provided entity permission.
Example
import React from 'react';
import { useSelection } from 'your-library';
const MyComponent = () => {
const { getSelection, addToSelection, clearSelection, setSelection, loading } = useSelection({
selectionIdentifier: 'my-selection-identifier',
selectionDefinition: 'my-selection-definition',
});
React.useEffect(() => {
getSelection().then((selection) => {
console.log('Current selection:', selection);
});
}, [getSelection]);
const handleAdd = () => {
addToSelection([123, 456]);
};
const handleClear = () => {
clearSelection();
};
const handleSet = () => {
setSelection([789]);
};
if (loading) {
return <div>Loading...</div>;
}
return (
<div>
<button onClick={handleAdd}>Add to Selection</button>
<button onClick={handleClear}>Clear Selection</button>
<button onClick={handleSet}>Set Selection</button>
</div>
);
};
export default MyComponent;
useRealtimeSelection
Hook
The useRealtimeSelection hook extends the useSelection hook by providing real-time updates to the selection state based on ContentHub events.
Parameters
- selectionIdentifier: A string representing the identifier of the selection pool.
- selectionDefinition: A string representing the definition of the selection.
- subPoolId: (optional) A number representing the sub-pool ID. If null, it is ignored.
- selectionLimitation: (optional) A number representing the maximum number of items allowed in the selection.
Returns
- selection: An array of currently selected item IDs.
- getSelection: A function to fetch the current selection.
- clearSelection: A function to clear the current selection.
- addToSelection: A function to add items to the current selection.
- setSelection: A function to set the current selection, replacing any existing selection.
- loading: A boolean indicating whether a selection operation is currently in progress.
Example
import React from 'react';
import { useRealtimeSelection } from 'your-library';
const MyComponent = () => {
const { selection, getSelection, clearSelection, addToSelection, setSelection, loading } = useRealtimeSelection({
selectionIdentifier: 'my-selection-identifier',
selectionDefinition: 'my-selection-definition',
});
React.useEffect(() => {
getSelection().then((selection) => {
console.log('Current selection:', selection);
});
}, [getSelection]);
const handleAdd = () => {
addToSelection([123, 456]);
};
const handleClear = () => {
clearSelection();
};
const handleSet = () => {
setSelection([789]);
};
if (loading) {
return <div>Loading...</div>;
}
return (
<div>
<button onClick={handleAdd}>Add to Selection</button>
<button onClick={handleClear}>Clear Selection</button>
<button onClick={handleSet}>Set Selection</button>
<div>Current Selection: {selection.join(', ')}</div>
</div>
);
};
export default MyComponent;