Hooks
useNavigation
Allows navigating when we are inside a Page loader, or it can be simply used to know if the component is inside a Page loader
useStudioPanel
A hook that provides state information and actions for managing Qodly Studio panel in a web form editor. Qodly Studio panel represents a dynamic side panel that displays information related to the selected element or component.
Returns
{StudioPanelReturnType} - An object containing the type, open state, current state, and actions to manipulate Qodly Studio panel.
The useStudioPanel function returns an object with properties type, isOpen, current, and actions to manipulate Qodly Studio panel state.
The actions object includes methods for updating the state, setting the current type and value, closing, opening, and opening with a specific type and current value.
useRenderer
A hook that facilitates rendering and event handling for a Craft.js node. It manages server-side references (ssRef) and auto-binds events to the corresponding DOM element.
Parameters
| param | description |
|---|---|
| autoBindEvents | Specifies whether events should be auto-bound. |
| omittedEvents | An array of event names to be omitted. |
Returns
{[HTMLElement | null, { connectRenderer, eventsToHandle, emit} ] } - An object with methods for connecting, handling events, and emitting custom events.
The useRenderer function returns a tuple with two elements:
-
HTMLElement | null: The current DOM element or null. This represents the element to which the renderer is currently connected. -
An object providing methods to:
-
Connect the renderer
-
eventsToHandle: An object mapping event names to their corresponding handler functions. -
emit: A function to emit a custom event with the specified name and payload.
useLayout
A hook that provides methods and properties related to the layout mode of a Page.
Returns
{LayoutReturnType} - An object containing properties and methods related to the layout mode.
The useLayout function returns an object with properties layout and isAiryMode, along with methods getClassName and toggle.
- Example 1
Basic usage:
import { useLayout } from "@ws-ui/webform-editor";
const Example = () => {
highlight-next-line
const { layout, isAiryMode, getClassName } = useLayout();
return (
<div>
<p>Current Layout: {layout}</p>
<p>Is Airy Mode: {isAiryMode ? 'Yes' : 'No'}</p>
<p>Modified Class Name: {getClassName('my-container')}</p>
</div>
);
}
useDatasourceSub
A hook that subscribes to changes in datasources and performs replacements in the webform based on specified actions.
- Example 1
import useDatasourceSub from "@ws-ui/webform-editor"
const ExampleComponent = () => {
highlight-next-line
useDatasourceSub();
};
useSources
A hook that facilitates managing datasources and current elements associated with a web form. It provides methods for setting, fetching, and listening to changes in datasource values.
Parameters
| param | description |
|---|---|
| options | UseSourcesOptions An object allowing configuration of the hook behavior. Includes options such as datasourceChange, currentElementChange and acceptIteratorSel. |
Returns
{UseSourcesReturnType} - An object containing datasources, current elements, and methods for manipulating their values.
The useSources function returns an object with the following structure:
sources: An object containingdatasourceandcurrentElement, representing the current values of datasources and current elements.actions: An object containing methods for manipulating datasource values, includingsetDatasourceValue,setCurrentElementValue,fetchDatasourceValue, andfetchCurrentElementValue.
useEnhancedNode
A hook that enhances the functionality of a Craft.js node, providing features for handling data transfer, managing datasources, and styling components.
Parameters
| param | description |
|---|---|
| collector | (optional) (args: Node) => K |
| options | (optional) { stopPropagation?: (data: IDataTransfer) => boolean; onDrop?: (e: any) => void; } |
Returns
{UseEnhancedNodeReturnType} - An object containing enhanced node information, connectors, and actions.
- Example 1
- Example 2
Basic usage:
import { useEnhancedNode } from '@ws-ui/webform-editor';
import { useState, useEffect } from 'react';
const ExampleDelayedState = () => {
const { actions, connectors, linkedNodes } = useEnhancedNode((node) => ({
nodes: node.data.nodes,
linkedNodes: node.data.linkedNodes,
node,
}));
const [delayedState, setDelayedState] = useState(null);
useEffect(() => {
const fetchData = async () => {
// Fetch your data, e.g., from an API
const result = await fetch('https://api.example.com/data');
const data = await result.json();
setDelayedState(data);
actions.setDatasourceValue({ key: 'yourDatasourceKey', value: data });
};
fetchData();
}, [actions]);
return (
<div ref={connectors.connect}>
{delayedState && (
<div>
{JSON.stringify(delayedState)}
</div>
)}
</div>
);
};
Handling drop events:
import { useEnhancedNode } from '@ws-ui/webform-editor';
const DraggableComponent = () => {
const { actions, connectors, linkedNodes } = useEnhancedNode((node) => ({
nodes: node.data.nodes,
linkedNodes: node.data.linkedNodes,
node,
}), {
onDrop: (event) => {
console.log('Dropped:', event);
},
});
return (
<div
ref={connectors.connect}
draggable
onDragStart={(event) => {
event.dataTransfer.setData('text', 'your data here');
}}
>
</div>
);
};
The useEnhancedNode function returns an object with the following structure:
- id: The ID of the node.
- store: The store associated with the node.
- connectors: Object containing connectors to interact with the Craft.js editor.
- ...collected: Additional data collected by the collector function.
- actions: An object containing methods for manipulating node values, including
setProp,setStyle,setDatasource, andsetIterator.
useEnhancedEditor
A Hook that provides methods and state information associated with the entire editor.
Parameters
| param | description |
|---|---|
| collect | A function that collects relevant state information from the editor state. The component will re-render when the values returned by this function changes. |
Returns
{useEditorReturnType<S>}
- Example 1
- Example 2
- Example 3
Basic usage:
import { useEnhancedEditor } from "@ws-ui/webform-editor";
const BasicUsageExample = () => {
const { isActive, enabled, canvas } = useEnhancedEditor();
// Your component logic based on the editor state
return (
<div>
<p>Is Active: {isActive ? 'Yes' : 'No'}</p>
<p>Editor Enabled: {enabled ? 'Yes' : 'No'}</p>
<p>Canvas Element: {canvas}</p>
// Additional logic and components based on the editor state
</div>
);
};
Basic usage with collector:
import { useEnhancedEditor } from "@ws-ui/webform-editor";
const CollectorUsageExample = () => {
const collect = (state, query) => ({
enabled: state.options.enabled,
isActive: query.getEvent('selected').some(),
});
const { isActive, enabled, actions } = useEnhancedEditor(collect);
// Your component logic based on the collected data
return (
<div>
<p>Is Active: {isActive ? 'Yes' : 'No'}</p>
<p>Editor Enabled: {enabled ? 'Yes' : 'No'}</p>
// Additional logic and components based on the collected data
</div>
);
};
Usage with a custom collector function:
import { useEnhancedEditor } from "@ws-ui/webform-editor";
const CustomUsageExample = ({ id }) => {
const { hidden, selected, hovered, topLevel } =
useEnhancedEditor((state, query) => {
const node = state.nodes[id];
const nodeActions = query.node(id);
return {
hidden: node?.data.hidden,
selected: state.events.selected.has(id),
topLevel: node ? nodeActions.isTopLevelCanvas() : false,
hovered: state.events.hovered.has(id),
};
});
// Your component logic based on the useEnhancedEditor results
return (
<div>
<p>Is Hidden: {hidden ? 'Yes' : 'No'}</p>
<p>Is Selected: {selected ? 'Yes' : 'No'}</p>
<p>Is Top Level: {topLevel ? 'Yes' : 'No'}</p>
<p>Is Hovered: {hovered ? 'Yes' : 'No'}</p>
</div>
);
};
useDataLoader
Returns an easy to use API to fecth a page(s) of data
Parameters
| param | description |
|---|---|
| props | An object containing source i.e the datasource and the initial step |
Returns
{page: IPage; entities: datasources.IEntity[]; setStep: (step: IStep) => void; fetchIndex: (index: number) => void; } - DataLoader return type
- Example 1
- Example 2
This example is using useSource and useDataloader to fetch simple list of people with firstName and lastName
import {
useDataLoader,
useSources,
} from "@ws-ui/webform-editor";
import { FC } from "react";
type Person = {
firstName: string;
lastName: string;
id: string
}
const Example: FC = () => {
const {
sources: { datasource: ds },
} = useSources();
const { entities } = useDataLoader<Person>({
source: ds,
});
// assuming that the source has two attributes firstName and lastName
return (
<div className="flex">
{entities.map((entity, index) => (
<div key={entity.id} className="flex items-center">
<span>{entity.firstName}</span> -
<span>{entity.lastName}</span>
</div>
))}
</div>
);
};
export default Example;
This example is using useSource and useDataloader and fetches the initial entities for the first Index
import {
useDataLoader,
useSources,
} from "@ws-ui/webform-editor";
import { FC, useEffect } from "react";
type Person = {
firstName: string;
lastName: string;
id: string
}
const Example: FC = () => {
const {
sources: { datasource: ds },
} = useSources();
const { entities } = useDataLoader<Person>({
source: ds,
});
// fetch the first page of entities on component mount
useEffect(() => {
fetchIndex(0)
}, [])
return (
<div className="flex">
{entities.map((entity, index) => (
<div key={entity.id} className="flex items-center">
<span>{entity.firstName}</span> -
<span>{entity.lastName}</span>
</div>
))}
</div>
);
};
export default Example;
The useDataLoader hook returns an object containing:
page: object containing the info about the current page of entities
- start: start index
- end: end index
- fetching: wether the it's fetching new pages or not, useful to render loading states using JSX
setStep: a function to set the current step of tha page, takes an object with start and end properties
fetchIndex: a function that fetches the page containg for the specified index, takes an index as its parameter
useEntity
Gets current entity context from parant Element
Returns
{EntityContextType} - Entity information including index, selection, current, iterator and parent