From 229ac7c92935bbcc1128796f996d6350d53cebbf Mon Sep 17 00:00:00 2001 From: Dinislam Khusainov Date: Thu, 3 Dec 2026 12:27:12 +0300 Subject: [PATCH 1/8] CSP RsTab.tsx --- packages/core/src/utils/getChildren.tsx | 57 ++++++++++++++- .../views/rsuite/src/components/RsTab.tsx | 4 +- tests/module/tests/tab-slot-condition.spec.ts | 69 +++++++++++++++++++ 3 files changed, 126 insertions(+), 4 deletions(-) create mode 100644 tests/module/tests/tab-slot-condition.spec.ts diff --git a/packages/core/src/utils/getChildren.tsx b/packages/core/src/utils/getChildren.tsx index 54516f8ee..d094aaef0 100644 --- a/packages/core/src/utils/getChildren.tsx +++ b/packages/core/src/utils/getChildren.tsx @@ -9,12 +9,64 @@ import {needRender} from './needRender' type SlotConditionFn = (parentProps: Record) => boolean const fnCache = new Map() +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) + if (literal.startsWith('"')) { + try { + const key: unknown = JSON.parse(literal) + return typeof key === 'string' ? key : undefined + } catch { + return undefined + } + } + + // Older RsTab forms store a single-quoted JavaScript string literal. + return legacyStringLiteral.exec(literal)?.[1].replace(legacyStringEscape, decodeLegacyEscape) +} + +function createSlotConditionFn(source: string): SlotConditionFn { + const activeKey = getActiveKey(source) + if (activeKey === undefined) { + return new Function('parentProps', source) as SlotConditionFn + } + return parentProps => parentProps.activeKey === activeKey +} function getOrCreateFn(source: string): SlotConditionFn { const fn = fnCache.get(source) if (fn) return fn - const result = new Function('parentProps', source) as SlotConditionFn + const result = createSlotConditionFn(source) fnCache.set(source, result) return result } @@ -29,9 +81,8 @@ export function checkSlotCondition(childStore: ComponentStore, parentProps: any) const fnSource = childStore.slotCondition?.trim() // it's OK - no condition to bind if (!fnSource) return true - const fn = getOrCreateFn(fnSource) try { - return fn(parentProps) + return getOrCreateFn(fnSource)(parentProps) } catch (e) { console.warn(e) return false diff --git a/packages/views/rsuite/src/components/RsTab.tsx b/packages/views/rsuite/src/components/RsTab.tsx index ec5226def..d4d94ab1e 100644 --- a/packages/views/rsuite/src/components/RsTab.tsx +++ b/packages/views/rsuite/src/components/RsTab.tsx @@ -91,6 +91,8 @@ 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 => `return parentProps.activeKey === ${JSON.stringify(String(props.activeKey?.value ?? props.activeKey))}` + ) .calculable(false), }) 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..a3cd76fd7 --- /dev/null +++ b/tests/module/tests/tab-slot-condition.spec.ts @@ -0,0 +1,69 @@ +import {rsTab} from '@react-form-builder/components-rsuite' +import {ComponentStore, checkSlotCondition} 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', () => { + 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})).toBe(true) + expect(checkSlotCondition(child, {activeKey: 'Other tab'})).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 = rsTab.build().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})).toBe(true) + expect(checkSlotCondition(child, {activeKey: 'Other tab'})).toBe(false) + } + ) + + it('evaluates a custom condition containing a tab comparison when compilation is allowed', () => { + const child = createPaneChild('return parentProps.activeKey === "Item1" || parentProps.showPane') + + expect(checkSlotCondition(child, {activeKey: 'Item2', showPane: true})).toBe(true) + expect(checkSlotCondition(child, {activeKey: 'Item2', showPane: false})).toBe(false) + }) + + 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, {})).toBe(true) + expect(warn).toHaveBeenCalledWith(expect.any(EvalError)) + }) +}) From 32c60d0c23b706cff61f2f7887778ba401911eec Mon Sep 17 00:00:00 2001 From: Dinislam Khusainov Date: Thu, 3 Dec 2026 17:07:00 +0300 Subject: [PATCH 2/8] CSP RsTab.tsx --- .../features/using-tabs.md | 108 +++++++----------- .../types/annotations/Annotation.tsx | 6 + .../utils/builders/NodeAnnotationBuilder.ts | 9 ++ .../core/src/features/define/utils/Definer.ts | 6 +- .../core/src/features/define/utils/Model.ts | 5 +- packages/core/src/utils/getChildren.tsx | 69 ++--------- .../dnd/components/Editable/Editable.tsx | 6 +- .../views/rsuite/src/components/RsTab.tsx | 57 ++++++++- .../tests/tab-slot-condition.spec.tsx | 89 +++++++++++++++ tests/module/tests/tab-slot-condition.spec.ts | 36 ++++-- 10 files changed, 247 insertions(+), 144 deletions(-) create mode 100644 tests/component/tests/tab-slot-condition.spec.tsx diff --git a/documentation/docs/formengine-designer/features/using-tabs.md b/documentation/docs/formengine-designer/features/using-tabs.md index 405e07004..e4caeb78c 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,21 @@ const RsTab = ({ } +const activeKeyConditionPrefix = 'return parentProps.activeKey === ' + +function resolvePaneCondition(source: string) { + if (!source.startsWith(activeKeyConditionPrefix)) return undefined + + try { + const key: unknown = JSON.parse(source.slice(activeKeyConditionPrefix.length)) + if (typeof key !== 'string') return undefined + + return (parentProps: Record) => parentProps.activeKey === key + } catch { + return undefined + } +} + export const rsTab = define(RsTab, 'RsTab') .name('Tab') .category(structureCategory) @@ -125,67 +140,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. +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. -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. -::: +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 a predicate that compares it with 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. -Let's take a look at the text of the function that will check the binding condition: - -```typescript {2} -withSlotConditionBuilder(props => { - return `return parentProps.activeKey === '${props.activeKey?.value ?? props.activeKey}'`; -}) -``` - -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. +If a slot has no resolver or its resolver returns `undefined`, FormEngine falls back to compiling the condition as JavaScript. +That fallback 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 +187,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 +210,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..d71a11bf2 100644 --- a/packages/core/src/features/annotation/types/annotations/Annotation.tsx +++ b/packages/core/src/features/annotation/types/annotations/Annotation.tsx @@ -106,6 +106,12 @@ export class Annotation { */ readonly slotConditionBuilder?: (props: any) => string + /** + * Resolves a saved condition for this slot to a predicate, or returns undefined to use the default evaluator. + * @param source the saved slot condition. + */ + readonly slotConditionResolver?: (source: string) => ((parentProps: Record) => boolean) | undefined + /** * 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..09e8104ef 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 returns a predicate, or undefined to use the default evaluator. + * @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 d094aaef0..f7b5de12a 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,64 +10,17 @@ import {needRender} from './needRender' type SlotConditionFn = (parentProps: Record) => boolean const fnCache = new Map() -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) - if (literal.startsWith('"')) { - try { - const key: unknown = JSON.parse(literal) - return typeof key === 'string' ? key : undefined - } catch { - return undefined - } - } +const defaultContainerKey = 'children' - // Older RsTab forms store a single-quoted JavaScript string literal. - return legacyStringLiteral.exec(literal)?.[1].replace(legacyStringEscape, decodeLegacyEscape) -} - -function createSlotConditionFn(source: string): SlotConditionFn { - const activeKey = getActiveKey(source) - if (activeKey === undefined) { - return new Function('parentProps', source) as SlotConditionFn - } - return parentProps => parentProps.activeKey === activeKey +function getSlot(componentStore: ComponentStore) { + return componentStore.slot || defaultContainerKey } function getOrCreateFn(source: string): SlotConditionFn { const fn = fnCache.get(source) if (fn) return fn - const result = createSlotConditionFn(source) + const result = new Function('parentProps', source) as SlotConditionFn fnCache.set(source, result) return result } @@ -75,22 +29,23 @@ function getOrCreateFn(source: string): SlotConditionFn { * 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 try { - return getOrCreateFn(fnSource)(parentProps) + const resolver = parentModel?.slotConditionResolvers?.get(getSlot(childStore)) + const condition = resolver?.(fnSource) ?? getOrCreateFn(fnSource) + return condition(parentProps) } 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. @@ -108,8 +63,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..e1e2d9e75 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,11 +60,11 @@ 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 isSlotConditionSatisfied = (child: ComponentData) => checkSlotCondition(child.store, componentProps, componentData.model) + const closedSlots = visualChildren.filter(isSlotConditionSatisfied).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) for (const [key, children] of Object.entries(groups)) { const filteredChildren = children.filter(isSlotConditionSatisfied) diff --git a/packages/views/rsuite/src/components/RsTab.tsx b/packages/views/rsuite/src/components/RsTab.tsx index d4d94ab1e..d9c27eed1 100644 --- a/packages/views/rsuite/src/components/RsTab.tsx +++ b/packages/views/rsuite/src/components/RsTab.tsx @@ -83,6 +83,58 @@ 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) { + const activeKey = getActiveKey(source) + if (activeKey === undefined) return undefined + + return (parentProps: Record) => parentProps.activeKey === activeKey +} + export const rsTab = define(RsTab, 'RsTab') .name('Tab') .category(structureCategory) @@ -91,8 +143,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 === ${JSON.stringify(String(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..28d976fd4 --- /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' ? () => true : undefined))}) + .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 index a3cd76fd7..7c5601c13 100644 --- a/tests/module/tests/tab-slot-condition.spec.ts +++ b/tests/module/tests/tab-slot-condition.spec.ts @@ -1,5 +1,5 @@ import {rsTab} from '@react-form-builder/components-rsuite' -import {ComponentStore, checkSlotCondition} from '@react-form-builder/core' +import {ComponentStore, checkSlotCondition, Model} from '@react-form-builder/core' import {afterEach, describe, expect, it, vi} from 'vitest' function createPaneChild(slotCondition?: string) { @@ -19,6 +19,8 @@ function disallowStringCompilation() { } describe('tab slot conditions', () => { + const {meta, model} = rsTab.build() + afterEach(() => { vi.unstubAllGlobals() vi.restoreAllMocks() @@ -31,29 +33,29 @@ describe('tab slot conditions', () => { const child = createPaneChild(condition) disallowStringCompilation() - expect(checkSlotCondition(child, {activeKey})).toBe(true) - expect(checkSlotCondition(child, {activeKey: 'Other tab'})).toBe(false) + 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 = rsTab.build().meta.properties.find(property => property.key === 'pane') + 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})).toBe(true) - expect(checkSlotCondition(child, {activeKey: 'Other tab'})).toBe(false) + expect(checkSlotCondition(child, {activeKey}, model)).toBe(true) + expect(checkSlotCondition(child, {activeKey: 'Other tab'}, model)).toBe(false) } ) it('evaluates a custom condition containing a tab comparison when compilation is allowed', () => { const child = createPaneChild('return parentProps.activeKey === "Item1" || parentProps.showPane') - expect(checkSlotCondition(child, {activeKey: 'Item2', showPane: true})).toBe(true) - expect(checkSlotCondition(child, {activeKey: 'Item2', showPane: false})).toBe(false) + expect(checkSlotCondition(child, {activeKey: 'Item2', showPane: true}, model)).toBe(true) + expect(checkSlotCondition(child, {activeKey: 'Item2', showPane: false}, model)).toBe(false) }) it('hides a child when CSP blocks its custom condition', () => { @@ -62,8 +64,22 @@ describe('tab slot conditions', () => { const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) disallowStringCompilation() - expect(checkSlotCondition(child, {showPane: true})).toBe(false) - expect(checkSlotCondition(sibling, {})).toBe(true) + expect(checkSlotCondition(child, {showPane: true}, model)).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) + }) }) From 4987bff953f00630ad71fb8a95a616bd8a805554 Mon Sep 17 00:00:00 2001 From: Aleksandr Shalugin Date: Fri, 4 Dec 2026 13:15:47 +0300 Subject: [PATCH 3/8] Scope slot condition evaluation to registered resolvers --- .../features/using-tabs.md | 16 ++++++------- .../types/annotations/Annotation.tsx | 5 ++-- .../utils/builders/NodeAnnotationBuilder.ts | 2 +- packages/core/src/utils/getChildren.tsx | 20 ++++++++++------ .../dnd/components/Editable/Editable.tsx | 24 +++++++------------ .../views/rsuite/src/components/RsTab.tsx | 10 ++++---- .../tests/tab-slot-condition.spec.tsx | 2 +- tests/module/tests/tab-slot-condition.spec.ts | 17 +++++++++---- 8 files changed, 52 insertions(+), 44 deletions(-) diff --git a/documentation/docs/formengine-designer/features/using-tabs.md b/documentation/docs/formengine-designer/features/using-tabs.md index e4caeb78c..68db799d8 100644 --- a/documentation/docs/formengine-designer/features/using-tabs.md +++ b/documentation/docs/formengine-designer/features/using-tabs.md @@ -119,16 +119,14 @@ const RsTab = ({ const activeKeyConditionPrefix = 'return parentProps.activeKey === ' -function resolvePaneCondition(source: string) { - if (!source.startsWith(activeKeyConditionPrefix)) return undefined +function resolvePaneCondition(source: string, parentProps: Record): boolean { + if (!source.startsWith(activeKeyConditionPrefix)) return false try { const key: unknown = JSON.parse(source.slice(activeKeyConditionPrefix.length)) - if (typeof key !== 'string') return undefined - - return (parentProps: Record) => parentProps.activeKey === key + return typeof key === 'string' && parentProps.activeKey === key } catch { - return undefined + return false } } @@ -158,12 +156,12 @@ receives the parent's design-time props and saves a string in the child's `slotC that keys containing apostrophes, quotation marks, or backslashes can be saved correctly. 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 a predicate that compares it with the parent's current `activeKey`. A match displays the child in the pane. +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. -If a slot has no resolver or its resolver returns `undefined`, FormEngine falls back to compiling the condition as JavaScript. -That fallback requires `'unsafe-eval'` when CSP restricts script execution. +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 diff --git a/packages/core/src/features/annotation/types/annotations/Annotation.tsx b/packages/core/src/features/annotation/types/annotations/Annotation.tsx index d71a11bf2..51c2bd8c6 100644 --- a/packages/core/src/features/annotation/types/annotations/Annotation.tsx +++ b/packages/core/src/features/annotation/types/annotations/Annotation.tsx @@ -107,10 +107,11 @@ export class Annotation { readonly slotConditionBuilder?: (props: any) => string /** - * Resolves a saved condition for this slot to a predicate, or returns undefined to use the default evaluator. + * 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) | undefined + 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 09e8104ef..6fd433af8 100644 --- a/packages/core/src/features/annotation/utils/builders/NodeAnnotationBuilder.ts +++ b/packages/core/src/features/annotation/utils/builders/NodeAnnotationBuilder.ts @@ -45,7 +45,7 @@ export class NodeAnnotationBuilder extends AnnotationBuilder { /** * Registers a resolver for saved conditions on this slot. - * @param slotConditionResolver the resolver that returns a predicate, or undefined to use the default evaluator. + * @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 { diff --git a/packages/core/src/utils/getChildren.tsx b/packages/core/src/utils/getChildren.tsx index f7b5de12a..5b136f526 100644 --- a/packages/core/src/utils/getChildren.tsx +++ b/packages/core/src/utils/getChildren.tsx @@ -16,13 +16,19 @@ 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 + } } /** @@ -36,10 +42,10 @@ export function checkSlotCondition(childStore: ComponentStore, parentProps: any, const fnSource = childStore.slotCondition?.trim() // it's OK - no condition to bind if (!fnSource) return true + const resolver = parentModel?.slotConditionResolvers?.get(getSlot(childStore)) + const condition = resolver ? undefined : getOrCreateFn(fnSource) try { - const resolver = parentModel?.slotConditionResolvers?.get(getSlot(childStore)) - const condition = resolver?.(fnSource) ?? getOrCreateFn(fnSource) - return condition(parentProps) + return resolver ? resolver(fnSource, parentProps) : (condition?.(parentProps) ?? false) } catch (e) { console.warn(e) return false diff --git a/packages/designer/src/features/dnd/components/Editable/Editable.tsx b/packages/designer/src/features/dnd/components/Editable/Editable.tsx index e1e2d9e75..d4aa90fb5 100644 --- a/packages/designer/src/features/dnd/components/Editable/Editable.tsx +++ b/packages/designer/src/features/dnd/components/Editable/Editable.tsx @@ -61,24 +61,16 @@ export function getBuilderChildren(builderStore: BuilderStore, componentData: Co availableSlots.push(...templateSlots) const isSlotConditionSatisfied = (child: ComponentData) => checkSlotCondition(child.store, componentProps, componentData.model) - const closedSlots = visualChildren.filter(isSlotConditionSatisfied).map(child => getSlot(child.store)) - const openSlots = availableSlots.filter(an => !closedSlots.includes(an.key)) - - const groups = groupBy(visualChildren, value => getSlot(value.store)) + 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 d9c27eed1..62b3222dc 100644 --- a/packages/views/rsuite/src/components/RsTab.tsx +++ b/packages/views/rsuite/src/components/RsTab.tsx @@ -128,11 +128,13 @@ function getActiveKey(source: string): string | undefined { } } -function resolveTabSlotCondition(source: string) { +function resolveTabSlotCondition(source: string, parentProps: Record): boolean { const activeKey = getActiveKey(source) - if (activeKey === undefined) return undefined - - return (parentProps: Record) => parentProps.activeKey === activeKey + if (activeKey === undefined) { + console.warn('Invalid RsTab pane slot condition') + return false + } + return parentProps.activeKey === activeKey } export const rsTab = define(RsTab, 'RsTab') diff --git a/tests/component/tests/tab-slot-condition.spec.tsx b/tests/component/tests/tab-slot-condition.spec.tsx index 28d976fd4..528e9c05e 100644 --- a/tests/component/tests/tab-slot-condition.spec.tsx +++ b/tests/component/tests/tab-slot-condition.spec.tsx @@ -8,7 +8,7 @@ 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' ? () => true : undefined))}) + .props({children: node.withSlotConditionResolver(source => source === 'return true')}) .build() const components = [conditionalContainer, rsTab.build(), rsLabel.build()] diff --git a/tests/module/tests/tab-slot-condition.spec.ts b/tests/module/tests/tab-slot-condition.spec.ts index 7c5601c13..ced752aa3 100644 --- a/tests/module/tests/tab-slot-condition.spec.ts +++ b/tests/module/tests/tab-slot-condition.spec.ts @@ -51,11 +51,20 @@ describe('tab slot conditions', () => { } ) - it('evaluates a custom condition containing a tab comparison when compilation is allowed', () => { + it('rejects conditions outside the RsTab pane format even when compilation is allowed', () => { const child = createPaneChild('return parentProps.activeKey === "Item1" || parentProps.showPane') - expect(checkSlotCondition(child, {activeKey: 'Item2', showPane: true}, model)).toBe(true) - expect(checkSlotCondition(child, {activeKey: 'Item2', showPane: false}, model)).toBe(false) + 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', () => { @@ -64,7 +73,7 @@ describe('tab slot conditions', () => { const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) disallowStringCompilation() - expect(checkSlotCondition(child, {showPane: true}, model)).toBe(false) + expect(checkSlotCondition(child, {showPane: true})).toBe(false) expect(checkSlotCondition(sibling, {}, model)).toBe(true) expect(warn).toHaveBeenCalledWith(expect.any(EvalError)) }) From eaa9be700015de79f0a8d4a41f360b3b836f9bf3 Mon Sep 17 00:00:00 2001 From: Aleksandr Shalugin Date: Fri, 4 Dec 2026 13:16:39 +0300 Subject: [PATCH 4/8] Update biome.json --- biome.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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", From 125b24d4d7d5bc9bd439566a05fe6ad38a051020 Mon Sep 17 00:00:00 2001 From: Aleksandr Shalugin Date: Fri, 4 Dec 2026 13:28:42 +0300 Subject: [PATCH 5/8] Enable strict CSP in the example Designer --- packages/apps/example-builder/package.json | 2 +- packages/apps/example-builder/vite.config.ts | 20 +++++++++++++++++++- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/packages/apps/example-builder/package.json b/packages/apps/example-builder/package.json index 29c95de66..df32f8703 100644 --- a/packages/apps/example-builder/package.json +++ b/packages/apps/example-builder/package.json @@ -12,7 +12,7 @@ "email": "support@optimajet.com" }, "scripts": { - "start": "vite --open --host", + "start": "vite --open \"/?form=empty\" --host", "dev": "vite --host" }, "dependencies": { diff --git a/packages/apps/example-builder/vite.config.ts b/packages/apps/example-builder/vite.config.ts index a3457ea77..09257d383 100644 --- a/packages/apps/example-builder/vite.config.ts +++ b/packages/apps/example-builder/vite.config.ts @@ -1,5 +1,23 @@ +import {randomBytes} from 'node:crypto' import {defineConfig, mergeConfig} from 'vite' import base from '../../../vite.config.ts' -export default defineConfig(env => mergeConfig(base(env), {})) +export default defineConfig(env => { + // Vite uses the nonce for its inline React Refresh preamble. + const nonce = randomBytes(16).toString('base64') + const policy = [ + "default-src 'self'", + `script-src 'self' 'nonce-${nonce}'`, + "style-src 'self' 'unsafe-inline'", + "img-src 'self' data: blob:", + "font-src 'self' data:", + "worker-src 'self' blob:", + "object-src 'none'", + "base-uri 'none'", + "form-action 'self'", + ].join('; ') + const headers = {'Content-Security-Policy': policy} + + return mergeConfig(base(env), {html: {cspNonce: nonce}, server: {headers}}) +}) From 5075b6cf13eee88f452fa081b4c9ffd800a0c69e Mon Sep 17 00:00:00 2001 From: Aleksandr Shalugin Date: Fri, 4 Dec 2026 13:35:12 +0300 Subject: [PATCH 6/8] Update package.json --- packages/apps/example-builder/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/apps/example-builder/package.json b/packages/apps/example-builder/package.json index df32f8703..29c95de66 100644 --- a/packages/apps/example-builder/package.json +++ b/packages/apps/example-builder/package.json @@ -12,7 +12,7 @@ "email": "support@optimajet.com" }, "scripts": { - "start": "vite --open \"/?form=empty\" --host", + "start": "vite --open --host", "dev": "vite --host" }, "dependencies": { From bfd629d8115f6dd4e9ff256d5d7de8c69a3a1d4f Mon Sep 17 00:00:00 2001 From: Aleksandr Shalugin Date: Fri, 4 Dec 2026 13:35:43 +0300 Subject: [PATCH 7/8] Update vite.config.ts --- packages/apps/example-builder/vite.config.ts | 20 +------------------- 1 file changed, 1 insertion(+), 19 deletions(-) diff --git a/packages/apps/example-builder/vite.config.ts b/packages/apps/example-builder/vite.config.ts index 09257d383..a3457ea77 100644 --- a/packages/apps/example-builder/vite.config.ts +++ b/packages/apps/example-builder/vite.config.ts @@ -1,23 +1,5 @@ -import {randomBytes} from 'node:crypto' import {defineConfig, mergeConfig} from 'vite' import base from '../../../vite.config.ts' -export default defineConfig(env => { - // Vite uses the nonce for its inline React Refresh preamble. - const nonce = randomBytes(16).toString('base64') - const policy = [ - "default-src 'self'", - `script-src 'self' 'nonce-${nonce}'`, - "style-src 'self' 'unsafe-inline'", - "img-src 'self' data: blob:", - "font-src 'self' data:", - "worker-src 'self' blob:", - "object-src 'none'", - "base-uri 'none'", - "form-action 'self'", - ].join('; ') - const headers = {'Content-Security-Policy': policy} - - return mergeConfig(base(env), {html: {cspNonce: nonce}, server: {headers}}) -}) +export default defineConfig(env => mergeConfig(base(env), {})) From 6d56854cb32ad33ce1d4726093a1275a6a71fc9d Mon Sep 17 00:00:00 2001 From: Aleksandr Shalugin Date: Fri, 4 Dec 2026 13:41:11 +0300 Subject: [PATCH 8/8] - docs --- .../core/classes/Annotation.md | 26 ++++++++++++++++ .../core/classes/ContainerAnnotation.md | 30 +++++++++++++++++++ .../core/classes/EventAnnotation.md | 30 +++++++++++++++++++ .../@react-form-builder/core/classes/Model.md | 16 +++++++++- .../core/classes/ModuleAnnotation.md | 30 +++++++++++++++++++ .../core/classes/NodeAnnotationBuilder.md | 22 ++++++++++++++ .../core/classes/PropertyAnnotation.md | 30 +++++++++++++++++++ .../core/classes/StyleAnnotation.md | 30 +++++++++++++++++++ .../core/functions/checkSlotCondition.md | 8 ++++- 9 files changed, 220 insertions(+), 2 deletions(-) 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`