diff --git a/biome.json b/biome.json index a21722b1c..83bdc99fd 100644 --- a/biome.json +++ b/biome.json @@ -1,5 +1,5 @@ { - "$schema": "https://biomejs.dev/schemas/2.6.6/schema.json", + "$schema": "https://biomejs.dev/schemas/2.6.8/schema.json", "vcs": { "enabled": true, "defaultBranch": "master", diff --git a/documentation/docs/api-reference/@react-form-builder/core/classes/Annotation.md b/documentation/docs/api-reference/@react-form-builder/core/classes/Annotation.md index edd3e314e..53762e8da 100644 --- a/documentation/docs/api-reference/@react-form-builder/core/classes/Annotation.md +++ b/documentation/docs/api-reference/@react-form-builder/core/classes/Annotation.md @@ -178,6 +178,32 @@ the properties of the component, which are available only inside Form Builder De *** +### slotConditionResolver? + +> `readonly` `optional` **slotConditionResolver?**: (`source`, `parentProps`) => `boolean` + +Evaluates the saved condition for this slot. + +#### Parameters + +##### source + +`string` + +the saved slot condition. + +##### parentProps + +`Record`\<`string`, `unknown`\> + +the current parent component properties. + +#### Returns + +`boolean` + +*** + ### type? > `readonly` `optional` **type?**: keyof SchemaTypeMap diff --git a/documentation/docs/api-reference/@react-form-builder/core/classes/ContainerAnnotation.md b/documentation/docs/api-reference/@react-form-builder/core/classes/ContainerAnnotation.md index a6e0d5e25..95afc0669 100644 --- a/documentation/docs/api-reference/@react-form-builder/core/classes/ContainerAnnotation.md +++ b/documentation/docs/api-reference/@react-form-builder/core/classes/ContainerAnnotation.md @@ -281,6 +281,36 @@ the properties of the component, which are available only inside Form Builder De *** +### slotConditionResolver? + +> `readonly` `optional` **slotConditionResolver?**: (`source`, `parentProps`) => `boolean` + +Evaluates the saved condition for this slot. + +#### Parameters + +##### source + +`string` + +the saved slot condition. + +##### parentProps + +`Record`\<`string`, `unknown`\> + +the current parent component properties. + +#### Returns + +`boolean` + +#### Inherited from + +[`Annotation`](Annotation.md).[`slotConditionResolver`](Annotation.md#slotconditionresolver) + +*** + ### type? > `readonly` `optional` **type?**: keyof SchemaTypeMap diff --git a/documentation/docs/api-reference/@react-form-builder/core/classes/EventAnnotation.md b/documentation/docs/api-reference/@react-form-builder/core/classes/EventAnnotation.md index 5ac1fb0d7..8e395f8d8 100644 --- a/documentation/docs/api-reference/@react-form-builder/core/classes/EventAnnotation.md +++ b/documentation/docs/api-reference/@react-form-builder/core/classes/EventAnnotation.md @@ -242,6 +242,36 @@ the properties of the component, which are available only inside Form Builder De *** +### slotConditionResolver? + +> `readonly` `optional` **slotConditionResolver?**: (`source`, `parentProps`) => `boolean` + +Evaluates the saved condition for this slot. + +#### Parameters + +##### source + +`string` + +the saved slot condition. + +##### parentProps + +`Record`\<`string`, `unknown`\> + +the current parent component properties. + +#### Returns + +`boolean` + +#### Inherited from + +[`Annotation`](Annotation.md).[`slotConditionResolver`](Annotation.md#slotconditionresolver) + +*** + ### type? > `readonly` `optional` **type?**: keyof SchemaTypeMap diff --git a/documentation/docs/api-reference/@react-form-builder/core/classes/Model.md b/documentation/docs/api-reference/@react-form-builder/core/classes/Model.md index 850317ea1..8d83a155d 100644 --- a/documentation/docs/api-reference/@react-form-builder/core/classes/Model.md +++ b/documentation/docs/api-reference/@react-form-builder/core/classes/Model.md @@ -14,7 +14,7 @@ the type of React component properties. ### Constructor -> **new Model**\<`T`\>(`component`, `name?`, `actionsInitializer?`, `valued?`, `valueType?`, `defaultProps?`, `css?`, `wrapperCss?`, `typeName?`, `kind?`, `readOnly?`, `propsBindingTypes?`, `uncontrolledValue?`, `disabled?`, `dataBindingType?`, `features?`): `Model`\<`T`\> +> **new Model**\<`T`\>(`component`, `name?`, `actionsInitializer?`, `valued?`, `valueType?`, `defaultProps?`, `css?`, `wrapperCss?`, `typeName?`, `kind?`, `readOnly?`, `propsBindingTypes?`, `uncontrolledValue?`, `disabled?`, `dataBindingType?`, `features?`, `slotConditionResolvers?`): `Model`\<`T`\> Creates component metadata for the form viewer. @@ -116,6 +116,12 @@ the type of component data binding. the component features that provide additional information about component's characteristic. +##### slotConditionResolvers? + +`ReadonlyMap`\<`string`, (`source`, `parentProps`) => `boolean`\> + +the condition resolvers keyed by slot name. + #### Returns `Model`\<`T`\> @@ -202,6 +208,14 @@ the name of the component property that stores the read-only flag. *** +### slotConditionResolvers? + +> `readonly` `optional` **slotConditionResolvers?**: `ReadonlyMap`\<`string`, (`source`, `parentProps`) => `boolean`\> + +the condition resolvers keyed by slot name. + +*** + ### typeName? > `readonly` `optional` **typeName?**: `string` diff --git a/documentation/docs/api-reference/@react-form-builder/core/classes/ModuleAnnotation.md b/documentation/docs/api-reference/@react-form-builder/core/classes/ModuleAnnotation.md index a4836726a..d84570eea 100644 --- a/documentation/docs/api-reference/@react-form-builder/core/classes/ModuleAnnotation.md +++ b/documentation/docs/api-reference/@react-form-builder/core/classes/ModuleAnnotation.md @@ -243,6 +243,36 @@ the properties of the component, which are available only inside Form Builder De *** +### slotConditionResolver? + +> `readonly` `optional` **slotConditionResolver?**: (`source`, `parentProps`) => `boolean` + +Evaluates the saved condition for this slot. + +#### Parameters + +##### source + +`string` + +the saved slot condition. + +##### parentProps + +`Record`\<`string`, `unknown`\> + +the current parent component properties. + +#### Returns + +`boolean` + +#### Inherited from + +[`Annotation`](Annotation.md).[`slotConditionResolver`](Annotation.md#slotconditionresolver) + +*** + ### type? > `readonly` `optional` **type?**: keyof SchemaTypeMap diff --git a/documentation/docs/api-reference/@react-form-builder/core/classes/NodeAnnotationBuilder.md b/documentation/docs/api-reference/@react-form-builder/core/classes/NodeAnnotationBuilder.md index 7cf52c6b6..5782a465c 100644 --- a/documentation/docs/api-reference/@react-form-builder/core/classes/NodeAnnotationBuilder.md +++ b/documentation/docs/api-reference/@react-form-builder/core/classes/NodeAnnotationBuilder.md @@ -622,6 +622,28 @@ the instance of the metadata property builder. *** +### withSlotConditionResolver() + +> **withSlotConditionResolver**(`slotConditionResolver`): `this` + +Registers a resolver for saved conditions on this slot. + +#### Parameters + +##### slotConditionResolver + +(`source`, `parentProps`) => `boolean` + +the resolver that evaluates the saved condition with the current parent properties. + +#### Returns + +`this` + +the instance of the metadata property builder. + +*** + ### create() > `static` **create**\<`T`\>(`editor`): [`AnnotationBuilder`](AnnotationBuilder.md)\<`T`\> diff --git a/documentation/docs/api-reference/@react-form-builder/core/classes/PropertyAnnotation.md b/documentation/docs/api-reference/@react-form-builder/core/classes/PropertyAnnotation.md index b96f4d87d..321282b22 100644 --- a/documentation/docs/api-reference/@react-form-builder/core/classes/PropertyAnnotation.md +++ b/documentation/docs/api-reference/@react-form-builder/core/classes/PropertyAnnotation.md @@ -250,6 +250,36 @@ the properties of the component, which are available only inside Form Builder De *** +### slotConditionResolver? + +> `readonly` `optional` **slotConditionResolver?**: (`source`, `parentProps`) => `boolean` + +Evaluates the saved condition for this slot. + +#### Parameters + +##### source + +`string` + +the saved slot condition. + +##### parentProps + +`Record`\<`string`, `unknown`\> + +the current parent component properties. + +#### Returns + +`boolean` + +#### Inherited from + +[`Annotation`](Annotation.md).[`slotConditionResolver`](Annotation.md#slotconditionresolver) + +*** + ### type? > `readonly` `optional` **type?**: keyof SchemaTypeMap diff --git a/documentation/docs/api-reference/@react-form-builder/core/classes/StyleAnnotation.md b/documentation/docs/api-reference/@react-form-builder/core/classes/StyleAnnotation.md index 51e07b9ad..fff999d26 100644 --- a/documentation/docs/api-reference/@react-form-builder/core/classes/StyleAnnotation.md +++ b/documentation/docs/api-reference/@react-form-builder/core/classes/StyleAnnotation.md @@ -242,6 +242,36 @@ the properties of the component, which are available only inside Form Builder De *** +### slotConditionResolver? + +> `readonly` `optional` **slotConditionResolver?**: (`source`, `parentProps`) => `boolean` + +Evaluates the saved condition for this slot. + +#### Parameters + +##### source + +`string` + +the saved slot condition. + +##### parentProps + +`Record`\<`string`, `unknown`\> + +the current parent component properties. + +#### Returns + +`boolean` + +#### Inherited from + +[`Annotation`](Annotation.md).[`slotConditionResolver`](Annotation.md#slotconditionresolver) + +*** + ### type? > `readonly` `optional` **type?**: keyof SchemaTypeMap diff --git a/documentation/docs/api-reference/@react-form-builder/core/functions/checkSlotCondition.md b/documentation/docs/api-reference/@react-form-builder/core/functions/checkSlotCondition.md index 83eb01e84..de6629916 100644 --- a/documentation/docs/api-reference/@react-form-builder/core/functions/checkSlotCondition.md +++ b/documentation/docs/api-reference/@react-form-builder/core/functions/checkSlotCondition.md @@ -1,6 +1,6 @@ # Function: checkSlotCondition() -> **checkSlotCondition**(`childStore`, `parentProps`): `boolean` +> **checkSlotCondition**(`childStore`, `parentProps`, `parentModel?`): `boolean` Performs the function of checking if the child component can be bound. **Internal use only.** @@ -18,6 +18,12 @@ the child component settings. the parent component properties. +### parentModel? + +[`Model`](../classes/Model.md)\<`any`\> + +the parent component model containing the slot resolvers. + ## Returns `boolean` diff --git a/documentation/docs/formengine-designer/features/using-tabs.md b/documentation/docs/formengine-designer/features/using-tabs.md index 405e07004..68db799d8 100644 --- a/documentation/docs/formengine-designer/features/using-tabs.md +++ b/documentation/docs/formengine-designer/features/using-tabs.md @@ -3,6 +3,7 @@ sidebar_position: 9 title: Using tabs slug: /formengine-designer/features/using-tabs description: In this guide, you will learn how to connect components with tabs +tags: [designer, tabs] --- :::info[For form authors] @@ -25,7 +26,7 @@ this [article](/formengine-designer/features/nested-components#slots). Let's create a custom component that will display tabs and different components depending on which tab is currently active. -```tsx {40,55-63,65-69,99-101} title='RsTab.tsx' showLineNumbers +```tsx title='RsTab.tsx' showLineNumbers import {array, boolean, define, node, toLabeledValues, useComponentData} from '@react-form-builder/core' import cx from 'clsx' import type {ReactNode, SyntheticEvent} from 'react' @@ -91,8 +92,7 @@ const RsTab = ({ const componentData = useComponentData() const onNavSelect = useCallback((eventKey: string, event: SyntheticEvent) => { - componentData.userDefinedProps ??= {} - componentData.userDefinedProps.activeKey = eventKey + componentData.setUserDefinedProp('activeKey', eventKey) onSelect?.(eventKey, event) }, [componentData, onSelect]) @@ -117,6 +117,19 @@ const RsTab = ({ } +const activeKeyConditionPrefix = 'return parentProps.activeKey === ' + +function resolvePaneCondition(source: string, parentProps: Record): boolean { + if (!source.startsWith(activeKeyConditionPrefix)) return false + + try { + const key: unknown = JSON.parse(source.slice(activeKeyConditionPrefix.length)) + return typeof key === 'string' && parentProps.activeKey === key + } catch { + return false + } +} + export const rsTab = define(RsTab, 'RsTab') .name('Tab') .category(structureCategory) @@ -125,67 +138,38 @@ export const rsTab = define(RsTab, 'RsTab') items: array.default(toLabeledValues(['Item1', 'Item2', 'Item3'])), showNavigation: boolean.default(true), pane: node - .withSlotConditionBuilder(props => `return parentProps.activeKey === '${props.activeKey?.value ?? props.activeKey}'`) + .withSlotConditionBuilder(props => activeKeyConditionPrefix + JSON.stringify(String(props.activeKey?.value ?? props.activeKey))) + .withSlotConditionResolver(resolvePaneCondition) .calculable(false), }) ``` -Let's take an in-depth look at how this component works. - -- Lines 28-41 define the type of properties of the `RsTabProps` component. Line 40 shows that the `pane` property is of type `ReactNode`. -- In lines 55-90, the React component `RsTab` is defined. It is a functional React component that receives properties of type `RsTabProps`. -- In line 63, the `RsTab` component uses the Form - Builder [useComponentData](/api-reference/@react-form-builder/core/variables/useComponentData) hook. This hook returns an instance of - class [ComponentData](/api-reference/@react-form-builder/core/classes/ComponentData). The `ComponentData` class is responsible for storing - all the data needed to render the component. -- The `ComponentData` contains the [userDefinedProps](/api-reference/@react-form-builder/core/classes/ComponentData#userdefinedprops) - property. You can set component properties in `userDefinedProps` to override component properties that have been computed by the Form - Builder. -- Lines 65-69 define the `onNavSelect` handler, which changes the `activeKey` property, the name of the active tab, when the tab is clicked. - The `activeKey` property is set via `userDefinedProps`. -- Lines 92-102 define the metadata of the `RsTab` component for the Form Builder. -- The `pane` property is defined on lines 99-101. -- On line 100, - the [withSlotConditionBuilder](/api-reference/@react-form-builder/core/classes/NodeAnnotationBuilder#withslotconditionbuilder) function is - called. This is where the most entertaining part starts. The `withSlotConditionBuilder` function takes as input a function that should - return a text with the source code of another function. +The `pane` property is the slot that holds the active tab's content. When a user selects a tab, `onNavSelect` updates the component's +`activeKey` through the [ComponentData](/api-reference/@react-form-builder/core/classes/ComponentData) instance returned by +[useComponentData](/api-reference/@react-form-builder/core/variables/useComponentData). ## Slot condition -The function that is passed to `withSlotConditionBuilder` receives the `props` parameter as input. **`props` are properties of the -component, which are available only inside Form Builder Designer!** - -:::info - -When you use a component inside Form Builder Designer, the function passed in `withSlotConditionBuilder` is called, and this function must -return the **text** of a function that will run in the component's display mode, that is, outside of Form Builder Designer. - -The string with the text of the conditional binding function will be calculated at the form design stage and written to the form's JSON. - -When the form is rendered, Form Builder will compile and execute a function from the saved text. If the function returns `true`, the child -component will be bound to the component slot, otherwise the component will not be rendered. -::: - -Let's take a look at the text of the function that will check the binding condition: +When a child is placed in a tab, Form Builder Designer calls the builder registered with +[withSlotConditionBuilder](/api-reference/@react-form-builder/core/classes/NodeAnnotationBuilder#withslotconditionbuilder). The builder +receives the parent's design-time props and saves a string in the child's `slotCondition` field. `JSON.stringify` escapes the tab key so +that keys containing apostrophes, quotation marks, or backslashes can be saved correctly. -```typescript {2} -withSlotConditionBuilder(props => { - return `return parentProps.activeKey === '${props.activeKey?.value ?? props.activeKey}'`; -}) -``` +Designer and FormViewer pass the saved string to the resolver registered with `withSlotConditionResolver` for the `pane` slot. The resolver +reads the saved key and returns whether it matches the parent's current `activeKey`. A match displays the child in the pane. +This comparison works under a Content Security Policy (CSP) that disallows `'unsafe-eval'`. The built-in `RsTab` also recognizes +single-quoted conditions generated by earlier versions. -This function takes as input the `parentProps` parameter, which are the properties of the component to which the child component will be -bound. That is, these are also properties of our `RsTab` component, but only used when the component is displayed, not when the component is -designed. +A registered resolver handles every saved condition for its slot and returns `false` for unsupported formats. For slots without a resolver, +FormEngine compiles the condition as JavaScript, which requires `'unsafe-eval'` when CSP restricts script execution. ## Example form For example, let's open [demo](https://demo.formengine.io/) and add a Tab component to the form. On the first tab let's add Checkbox, on the second tab add TextArea, on the third tab add Image, and look at the resulting JSON of the form: -```json {16-17,23-24,30-31} title='Form.json' showLineNumbers +```json title='Form.json' showLineNumbers { - "version": "1", "form": { "key": "Screen", "type": "Screen", @@ -201,21 +185,21 @@ second tab add TextArea, on the third tab add Image, and look at the resulting J "type": "RsCheckbox", "props": {}, "slot": "pane", - "slotCondition": "return parentProps.activeKey === 'Item1'" + "slotCondition": "return parentProps.activeKey === \"Item1\"" }, { "key": "RsTextArea 1", "type": "RsTextArea", "props": {}, "slot": "pane", - "slotCondition": "return parentProps.activeKey === 'Item2'" + "slotCondition": "return parentProps.activeKey === \"Item2\"" }, { "key": "RsImage 1", "type": "RsImage", "props": {}, "slot": "pane", - "slotCondition": "return parentProps.activeKey === 'Item3'" + "slotCondition": "return parentProps.activeKey === \"Item3\"" } ] } @@ -224,21 +208,5 @@ second tab add TextArea, on the third tab add Image, and look at the resulting J } ``` -When we added the Checkbox component to the form, the active tab in the component properties was "Item1". So Form Builder Designer -evaluated the function and got the following string as a result: `return parentProps.activeKey === 'Item1'`. This string was stored in -the `slotCondition` field, and the slot name was written to the `slot` field with the value `pane`. `pane` is a property of the component -to which the conditional binding is performed. - -The conditions were also calculated for the TextArea component - the active tab was "Item2". Therefore, the text of the check function -is `return parentProps.activeKey === 'Item2'`. - -For the Image component, the active tab at the time of form design was the "Item3" tab. The calculated text of the check function is as -follows - `return parentProps.activeKey === 'Item3'`. - -:::info - -When Form Builder displays a form, it evaluates the functions from the `slotCondition` and displays the components if the function -returned `true`. Since all three functions above are mutually exclusive, only one component, either Checkbox, TextArea or Image, will be -bound to the `pane` property and displayed. - -::: +Each child uses the `pane` slot and stores a different key in its `slotCondition`. Select `Item1` to display Checkbox, `Item2` to display +TextArea, or `Item3` to display Image. diff --git a/packages/core/src/features/annotation/types/annotations/Annotation.tsx b/packages/core/src/features/annotation/types/annotations/Annotation.tsx index 86ddf9df1..51c2bd8c6 100644 --- a/packages/core/src/features/annotation/types/annotations/Annotation.tsx +++ b/packages/core/src/features/annotation/types/annotations/Annotation.tsx @@ -106,6 +106,13 @@ export class Annotation { */ readonly slotConditionBuilder?: (props: any) => string + /** + * Evaluates the saved condition for this slot. + * @param source the saved slot condition. + * @param parentProps the current parent component properties. + */ + readonly slotConditionResolver?: (source: string, parentProps: Record) => boolean + /** * The component property binding type. */ diff --git a/packages/core/src/features/annotation/utils/builders/NodeAnnotationBuilder.ts b/packages/core/src/features/annotation/utils/builders/NodeAnnotationBuilder.ts index 34eec2534..6fd433af8 100644 --- a/packages/core/src/features/annotation/utils/builders/NodeAnnotationBuilder.ts +++ b/packages/core/src/features/annotation/utils/builders/NodeAnnotationBuilder.ts @@ -43,6 +43,15 @@ export class NodeAnnotationBuilder extends AnnotationBuilder { return this.setup({slotConditionBuilder}) } + /** + * Registers a resolver for saved conditions on this slot. + * @param slotConditionResolver the resolver that evaluates the saved condition with the current parent properties. + * @returns the instance of the metadata property builder. + */ + withSlotConditionResolver(slotConditionResolver: NonNullable): this { + return this.setup({slotConditionResolver}) + } + /** * @inheritDoc */ diff --git a/packages/core/src/features/define/utils/Definer.ts b/packages/core/src/features/define/utils/Definer.ts index 1ce6466de..0db570d19 100644 --- a/packages/core/src/features/define/utils/Definer.ts +++ b/packages/core/src/features/define/utils/Definer.ts @@ -449,6 +449,9 @@ export class Definer { } const dateProperties = propAns.filter(annotation => annotation.type === 'date').map(annotation => annotation.key) + const slotConditionResolvers = new Map( + propAns.flatMap(({key, slotConditionResolver}) => (slotConditionResolver ? [[key, slotConditionResolver] as const] : [])) + ) const model = new Model( this.data.component, @@ -466,7 +469,8 @@ export class Definer { valuedAn?.uncontrolledValue, disabledAn?.key, valuedAn?.dataBindingType, - features + features, + slotConditionResolvers ).withDateProperties(dateProperties) const insertRestriction = model.isFeatureEnabled(cfSingleton) diff --git a/packages/core/src/features/define/utils/Model.ts b/packages/core/src/features/define/utils/Model.ts index 5592be237..43839c55a 100644 --- a/packages/core/src/features/define/utils/Model.ts +++ b/packages/core/src/features/define/utils/Model.ts @@ -1,5 +1,6 @@ import {observer} from 'mobx-react' import type {ComponentType} from 'react' +import type {Annotation} from '../../annotation/types/annotations/Annotation' import type {Css} from '../../style/types' import type {SchemaType} from '../../validation/types/SchemaType' import type {ActionsInitializer, ComponentKind} from '../types' @@ -40,6 +41,7 @@ export class Model { * @param disabled the name of the component property that stores the disabled flag. * @param dataBindingType the type of component data binding. * @param features the component features that provide additional information about component's characteristic. + * @param slotConditionResolvers the condition resolvers keyed by slot name. * @template T the type of React component properties. */ constructor( @@ -58,7 +60,8 @@ export class Model { readonly uncontrolledValue?: unknown, readonly disabled?: string, readonly dataBindingType: DataBindingType = 'none', - readonly features: ComponentFeatures = {} + readonly features: ComponentFeatures = {}, + readonly slotConditionResolvers?: ReadonlyMap> ) { if (this.valued && this.dataBindingType === 'none') { this.dataBindingType = 'twoWay' diff --git a/packages/core/src/utils/getChildren.tsx b/packages/core/src/utils/getChildren.tsx index 54516f8ee..5b136f526 100644 --- a/packages/core/src/utils/getChildren.tsx +++ b/packages/core/src/utils/getChildren.tsx @@ -1,5 +1,6 @@ import type {ComponentType} from 'react' import type {ComponentTreeProps} from '../ComponentTreeProps' +import type {Model} from '../features/define/utils/Model' import type {ComponentStore} from '../stores/ComponentStore' import type {ComponentData, IComponentDataProvider} from './contexts/ComponentDataContext' import {groupBy} from './groupBy' @@ -9,37 +10,48 @@ import {needRender} from './needRender' type SlotConditionFn = (parentProps: Record) => boolean const fnCache = new Map() +const defaultContainerKey = 'children' + +function getSlot(componentStore: ComponentStore) { + return componentStore.slot || defaultContainerKey +} -function getOrCreateFn(source: string): SlotConditionFn { +function getOrCreateFn(source: string): SlotConditionFn | undefined { const fn = fnCache.get(source) if (fn) return fn - const result = new Function('parentProps', source) as SlotConditionFn - fnCache.set(source, result) - return result + try { + const result = new Function('parentProps', source) as SlotConditionFn + fnCache.set(source, result) + return result + } catch (e) { + if (!(e instanceof EvalError)) throw e + console.warn(e) + return undefined + } } /** * Performs the function of checking if the child component can be bound. **Internal use only.** * @param childStore the child component settings. * @param parentProps the parent component properties. + * @param parentModel the parent component model containing the slot resolvers. * @returns true, if the child component can be bound, false otherwise. */ -export function checkSlotCondition(childStore: ComponentStore, parentProps: any) { +export function checkSlotCondition(childStore: ComponentStore, parentProps: any, parentModel?: Model) { const fnSource = childStore.slotCondition?.trim() // it's OK - no condition to bind if (!fnSource) return true - const fn = getOrCreateFn(fnSource) + const resolver = parentModel?.slotConditionResolvers?.get(getSlot(childStore)) + const condition = resolver ? undefined : getOrCreateFn(fnSource) try { - return fn(parentProps) + return resolver ? resolver(fnSource, parentProps) : (condition?.(parentProps) ?? false) } catch (e) { console.warn(e) return false } } -const defaultContainerKey = 'children' - /** * Returns the {@link Record} with all child components. **Internal use only.** * @param data the parent component's data necessary to display the component. @@ -57,8 +69,8 @@ export function getChildren( const ComponentTree = componentTreeItem const currentProps: Record = {} - const groups = groupBy(containers, value => value.store.slot || defaultContainerKey) - const isSlotConditionSatisfied = (child: ComponentData) => checkSlotCondition(child.store, componentProps) + const groups = groupBy(containers, value => getSlot(value.store)) + const isSlotConditionSatisfied = (child: ComponentData) => checkSlotCondition(child.store, componentProps, data.model) const isNeedRender = (child: ComponentData) => needRender(child.store, data.dataRoot) for (const [key, children] of Object.entries(groups)) { diff --git a/packages/designer/src/features/dnd/components/Editable/Editable.tsx b/packages/designer/src/features/dnd/components/Editable/Editable.tsx index d3367ed38..d4aa90fb5 100644 --- a/packages/designer/src/features/dnd/components/Editable/Editable.tsx +++ b/packages/designer/src/features/dnd/components/Editable/Editable.tsx @@ -38,7 +38,7 @@ function getTemplateSlots(data: ComponentData) { const childrenSlot = 'children' function getSlot(componentStore: ComponentStore) { - return componentStore.slot ?? childrenSlot + return componentStore.slot || childrenSlot } /** @@ -60,25 +60,17 @@ export function getBuilderChildren(builderStore: BuilderStore, componentData: Co const templateSlots = getTemplateSlots(componentData) availableSlots.push(...templateSlots) - const closedSlots = visualChildren.filter(child => checkSlotCondition(child.store, componentProps)).map(child => getSlot(child.store)) - const openSlots = availableSlots.filter(an => !closedSlots.includes(an.key)) - - const groups = groupBy(visualChildren, value => getSlot(value.store)) - const isSlotConditionSatisfied = (child: ComponentData) => checkSlotCondition(child.store, componentProps) + const isSlotConditionSatisfied = (child: ComponentData) => checkSlotCondition(child.store, componentProps, componentData.model) + const groups = groupBy(visualChildren.filter(isSlotConditionSatisfied), value => getSlot(value.store)) + const openSlots = availableSlots.filter(an => !Object.hasOwn(groups, an.key)) for (const [key, children] of Object.entries(groups)) { - const filteredChildren = children.filter(isSlotConditionSatisfied) - - if (filteredChildren.length) { - currentProps[key] = - componentData.model.propsBindingTypes[key] === 'array' ? ( - filteredChildren - .map<[string, ComponentData[]]>(item => [item.id, [item]]) - .map(([id, data]) => ) - ) : ( - - ) - } + currentProps[key] = + componentData.model.propsBindingTypes[key] === 'array' ? ( + children.map<[string, ComponentData[]]>(item => [item.id, [item]]).map(([id, data]) => ) + ) : ( + + ) } openSlots.forEach(container => { diff --git a/packages/views/rsuite/src/components/RsTab.tsx b/packages/views/rsuite/src/components/RsTab.tsx index ec5226def..62b3222dc 100644 --- a/packages/views/rsuite/src/components/RsTab.tsx +++ b/packages/views/rsuite/src/components/RsTab.tsx @@ -83,6 +83,60 @@ const RsTab = ({pane, onSelect, showNavigation, items, className, ...props}: RsT ) } +const activeKeyConditionPrefix = 'return parentProps.activeKey === ' +const legacyStringLiteral = /^'((?:[^'\\\r\n]|\\(?:\r\n|.))*)'$/su +const legacyStringEscape = /\\(\r\n|x[\da-fA-F]{2}|u(?:[\da-fA-F]{4}|\{[\da-fA-F]+\})|[0-3][0-7]{0,2}|[4-7][0-7]?|.)/gsu +const legacyEscapes: Readonly> = { + b: '\b', + f: '\f', + n: '\n', + r: '\r', + t: '\t', + v: '\v', + '\r\n': '', + '\r': '', + '\n': '', + '\u2028': '', + '\u2029': '', +} + +function decodeLegacyEscape(_match: string, escape: string): string { + const first = escape[0] + if (first === 'x' || first === 'u') { + if (escape.length === 1) throw new SyntaxError('Invalid escape sequence in slot condition') + const digits = escape.startsWith('u{') ? escape.slice(2, -1) : escape.slice(1) + return String.fromCodePoint(Number.parseInt(digits, 16)) + } + if (first >= '0' && first <= '7') return String.fromCharCode(Number.parseInt(escape, 8)) + return legacyEscapes[escape] ?? escape +} + +function getActiveKey(source: string): string | undefined { + if (!source.startsWith(activeKeyConditionPrefix)) return undefined + + const literal = source.slice(activeKeyConditionPrefix.length) + try { + if (literal.startsWith('"')) { + const key: unknown = JSON.parse(literal) + return typeof key === 'string' ? key : undefined + } + + // Older RsTab forms store a single-quoted JavaScript string literal. + return legacyStringLiteral.exec(literal)?.[1].replace(legacyStringEscape, decodeLegacyEscape) + } catch { + return undefined + } +} + +function resolveTabSlotCondition(source: string, parentProps: Record): boolean { + const activeKey = getActiveKey(source) + if (activeKey === undefined) { + console.warn('Invalid RsTab pane slot condition') + return false + } + return parentProps.activeKey === activeKey +} + export const rsTab = define(RsTab, 'RsTab') .name('Tab') .category(structureCategory) @@ -91,6 +145,7 @@ export const rsTab = define(RsTab, 'RsTab') items: array.localize.default(toLabeledValues(['Item1', 'Item2', 'Item3'])), showNavigation: boolean.default(true), pane: node - .withSlotConditionBuilder(props => `return parentProps.activeKey === '${props.activeKey?.value ?? props.activeKey}'`) + .withSlotConditionBuilder(props => activeKeyConditionPrefix + JSON.stringify(String(props.activeKey?.value ?? props.activeKey))) + .withSlotConditionResolver(resolveTabSlotCondition) .calculable(false), }) diff --git a/tests/component/tests/tab-slot-condition.spec.tsx b/tests/component/tests/tab-slot-condition.spec.tsx new file mode 100644 index 000000000..528e9c05e --- /dev/null +++ b/tests/component/tests/tab-slot-condition.spec.tsx @@ -0,0 +1,89 @@ +import {rsLabel, rsTab} from '@react-form-builder/components-rsuite' +import {BuilderView, createView, define, FormViewer, node} from '@react-form-builder/core' +import {FormBuilder} from '@react-form-builder/designer' +import {fireEvent, render, screen} from '@testing-library/react' +import type {PropsWithChildren} from 'react' +import {afterEach, describe, expect, it, vi} from 'vitest' + +const ConditionalContainer = ({children}: PropsWithChildren) =>
{children}
+ +const conditionalContainer = define(ConditionalContainer, 'ConditionalContainer') + .props({children: node.withSlotConditionResolver(source => source === 'return true')}) + .build() + +const components = [conditionalContainer, rsTab.build(), rsLabel.build()] +const viewerView = createView(components.map(({model}) => model)) +const builderView = new BuilderView(components) + +const savedForm = JSON.stringify({ + form: { + key: 'Screen', + type: 'Screen', + children: [ + { + key: 'container', + type: 'ConditionalContainer', + children: [ + { + key: 'tabs', + type: 'RsTab', + slot: '', + slotCondition: 'return true', + children: [ + { + key: 'firstLabel', + type: 'RsLabel', + slot: 'pane', + slotCondition: "return parentProps.activeKey === 'Item1'", + props: {text: {value: 'First pane content'}}, + }, + { + key: 'secondLabel', + type: 'RsLabel', + slot: 'pane', + slotCondition: 'return parentProps.activeKey === "Item2"', + props: {text: {value: 'Second pane content'}}, + }, + ], + }, + ], + }, + ], + }, +}) + +const getForm = () => savedForm + +describe('saved tab content with string compilation blocked', () => { + afterEach(() => { + vi.unstubAllGlobals() + }) + + it.each([ + ['FormViewer', ], + ['FormBuilder', ], + ])('renders the active pane in %s', async (_name, form) => { + // Block slot-condition compilation while leaving test framework and DOM internals available. + vi.stubGlobal( + 'Function', + new Proxy(Function, { + construct(target, args, newTarget) { + if (args[0] === 'parentProps') throw new EvalError('String compilation blocked by Content Security Policy') + return Reflect.construct(target, args, newTarget) + }, + }) + ) + + render(form) + expect(await screen.findByText('First pane content')).toBeVisible() + expect(screen.queryByText('Second pane content')).not.toBeInTheDocument() + + fireEvent.click(screen.getByRole('tab', {name: 'Item2'})) + expect(await screen.findByText('Second pane content')).toBeVisible() + expect(screen.queryByText('First pane content')).not.toBeInTheDocument() + + fireEvent.click(screen.getByRole('tab', {name: 'Item1'})) + expect(await screen.findByText('First pane content')).toBeVisible() + expect(screen.queryByText('Second pane content')).not.toBeInTheDocument() + }) +}) diff --git a/tests/module/tests/tab-slot-condition.spec.ts b/tests/module/tests/tab-slot-condition.spec.ts new file mode 100644 index 000000000..ced752aa3 --- /dev/null +++ b/tests/module/tests/tab-slot-condition.spec.ts @@ -0,0 +1,94 @@ +import {rsTab} from '@react-form-builder/components-rsuite' +import {ComponentStore, checkSlotCondition, Model} from '@react-form-builder/core' +import {afterEach, describe, expect, it, vi} from 'vitest' + +function createPaneChild(slotCondition?: string) { + const child = new ComponentStore('input', 'RsInput') + child.slot = 'pane' + child.slotCondition = slotCondition + return child +} + +function disallowStringCompilation() { + vi.stubGlobal( + 'Function', + vi.fn(function () { + throw new EvalError('String compilation blocked by Content Security Policy') + }) + ) +} + +describe('tab slot conditions', () => { + const {meta, model} = rsTab.build() + + afterEach(() => { + vi.unstubAllGlobals() + vi.restoreAllMocks() + }) + + it.each([ + ["return parentProps.activeKey === 'Item1'", 'Item1'], + [String.raw`return parentProps.activeKey === 'Legacy\' \\ \u{1F4CB}'`, "Legacy' \\ 📋"], + ])('reads a persisted tab condition without compiling it', (condition, activeKey) => { + const child = createPaneChild(condition) + disallowStringCompilation() + + expect(checkSlotCondition(child, {activeKey}, model)).toBe(true) + expect(checkSlotCondition(child, {activeKey: 'Other tab'}, model)).toBe(false) + }) + + it.each(['', `Both "quotes" and 'apostrophes' with a \\ backslash`])( + 'generates a tab condition that works without compilation for key %j', + activeKey => { + const pane = meta.properties.find(property => property.key === 'pane') + const condition = pane?.slotConditionBuilder?.({activeKey: {value: activeKey}}) + const child = createPaneChild(condition) + disallowStringCompilation() + + expect(condition).toBeDefined() + expect(checkSlotCondition(child, {activeKey}, model)).toBe(true) + expect(checkSlotCondition(child, {activeKey: 'Other tab'}, model)).toBe(false) + } + ) + + it('rejects conditions outside the RsTab pane format even when compilation is allowed', () => { + const child = createPaneChild('return parentProps.activeKey === "Item1" || parentProps.showPane') + + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + + expect(checkSlotCondition(child, {activeKey: 'Item2', showPane: true}, model)).toBe(false) + expect(warn).toHaveBeenCalledWith('Invalid RsTab pane slot condition') + expect(checkSlotCondition(child, {activeKey: 'Item2', showPane: true})).toBe(true) + }) + + it('propagates syntax errors in custom conditions', () => { + const child = createPaneChild('return parentProps.') + + expect(() => checkSlotCondition(child, {})).toThrow(SyntaxError) + }) + + it('hides a child when CSP blocks its custom condition', () => { + const child = createPaneChild('return parentProps.showPane') + const sibling = createPaneChild() + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + disallowStringCompilation() + + expect(checkSlotCondition(child, {showPane: true})).toBe(false) + expect(checkSlotCondition(sibling, {}, model)).toBe(true) + expect(warn).toHaveBeenCalledWith(expect.any(EvalError)) + }) + + it('only resolves a tab condition on the pane slot of an RsTab parent', () => { + const otherParent = new Model(() => null) + const child = createPaneChild("return parentProps.activeKey === 'Scoped pane'") + const props = {activeKey: 'Scoped pane'} + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + disallowStringCompilation() + + expect(checkSlotCondition(child, props, model)).toBe(true) + expect(checkSlotCondition(child, props, otherParent)).toBe(false) + child.slot = 'children' + expect(checkSlotCondition(child, props, model)).toBe(false) + expect(warn).toHaveBeenCalledTimes(2) + }) +})