From e5de12fae4066652ffb60a4049567c8aaf149d02 Mon Sep 17 00:00:00 2001 From: Alexey Cherepanov Date: Thu, 26 Nov 2026 12:12:58 +0300 Subject: [PATCH 01/13] #23 Add designer hotkey disable, remapping, and imperative actions --- .../features/designer-customization.md | 72 +++++++++++- packages/designer/index.ts | 6 + packages/designer/src/FormBuilder.tsx | 5 +- packages/designer/src/FormBuilderProps.tsx | 9 ++ .../features/hotkeys/resolveHotkeyBindings.ts | 69 ++++++++++++ .../designer/src/features/hotkeys/types.ts | 47 ++++++++ .../src/features/hotkeys/useHotKeys.tsx | 103 +++++------------- .../Header/components => print}/printForm.ts | 0 .../designer/src/features/ui/CentralPanel.tsx | 2 +- .../components/menu-items/PrintButton.tsx | 2 +- packages/designer/src/stores/BuilderStore.ts | 34 +++++- .../designer/src/stores/FormBuilderImpl.ts | 42 +++++++ packages/designer/src/utils/types.ts | 33 ++++++ .../component/tests/designer-hotkeys.spec.tsx | 86 +++++++++++++++ .../tests/accordion-child-wrapper.spec.tsx | 4 +- .../tests/resolve-hotkey-bindings.spec.ts | 73 +++++++++++++ 16 files changed, 505 insertions(+), 82 deletions(-) create mode 100644 packages/designer/src/features/hotkeys/resolveHotkeyBindings.ts create mode 100644 packages/designer/src/features/hotkeys/types.ts rename packages/designer/src/features/{ui/Header/components => print}/printForm.ts (100%) create mode 100644 tests/component/tests/designer-hotkeys.spec.tsx create mode 100644 tests/module/tests/resolve-hotkey-bindings.spec.ts diff --git a/documentation/docs/formengine-designer/features/designer-customization.md b/documentation/docs/formengine-designer/features/designer-customization.md index e83c74fa9..708a339bc 100644 --- a/documentation/docs/formengine-designer/features/designer-customization.md +++ b/documentation/docs/formengine-designer/features/designer-customization.md @@ -24,8 +24,8 @@ its [customizable key](/api-reference/@react-form-builder/designer/type-aliases/ You can manage the FormBuilder and get its state in custom components using [useFormBuilder](/api-reference/@react-form-builder/designer/variables/useFormBuilder). It provides access -to [IFormBuilder](/api-reference/@react-form-builder/designer/interfaces/IFormBuilder). The management options are limited at the moment, -but they will be expanded in the future. +to [IFormBuilder](/api-reference/@react-form-builder/designer/interfaces/IFormBuilder), including imperative shortcut +actions such as save, print, undo, and redo. See [Designer hotkeys](#designer-hotkeys) for embedding details. Another option for customizing the component is to use pure CSS. Each component has a static CSS class named with the component's name prefixed by `FE_`. This class is applied to the same element as the style or className attributes, utilizing @@ -386,5 +386,73 @@ const FormBuilderApp = () => { } ``` +## Designer hotkeys + +By default the FormBuilder registers global keyboard shortcuts (delete, duplicate, save, print, undo, and redo). +When you embed the designer inside a host application, those shortcuts can conflict with the browser or the host +(especially Ctrl/Cmd+S and Ctrl/Cmd+P). + +Use the [hotkeys](/api-reference/@react-form-builder/designer/interfaces/FormBuilderProps#hotkeys) prop to disable or +remap them, and call the matching methods on [IFormBuilder](/api-reference/@react-form-builder/designer/interfaces/IFormBuilder) +when the host owns the keyboard. + +### Disable all built-in hotkeys + +```tsx +import {FormBuilder, type IFormBuilder} from '@react-form-builder/designer' +import {useEffect, useRef} from 'react' + +const EmbeddedDesigner = () => { + const builderRef = useRef(null) + + useEffect(() => { + const onKeyDown = (event: KeyboardEvent) => { + if (!(event.ctrlKey || event.metaKey) || event.key.toLowerCase() !== 's') return + event.preventDefault() + void builderRef.current?.save() + } + globalThis.addEventListener('keydown', onKeyDown) + return () => globalThis.removeEventListener('keydown', onKeyDown) + }, []) + + return +} +``` + +### Remap or disable individual shortcuts + +```tsx + +``` + +Action ids: `deleteSelected`, `cloneSelected`, `save`, `print`, `undo`, `redo`. +Pass an array of chords when one action should accept multiple bindings. +On macOS prefer `meta`; on Windows and Linux prefer `ctrl`. + +### Imperative actions + +| Method | Same core behavior as | Notes | +| ------------------- | ----------------------------------------------------------- | --------------------------------------------- | +| `deleteSelected()` | Delete | | +| `cloneSelected()` | Ctrl/Cmd+D (no-op unless exactly one component is selected) | | +| `save()` | Ctrl/Cmd+S form persistence | Silent: no designer toast (host can show one) | +| `print()` | Ctrl/Cmd+P | | +| `undo()` / `redo()` | Undo / redo | | + +Built-in Ctrl/Cmd+S and the Save menu item still show the designer success/error toast. +`IFormBuilder.save()` only persists the form so embedders can own feedback when they register external shortcuts. + +These methods are available on the object returned by `useFormBuilder()` and through the `builderRef` prop. + [formStorage]: /formengine-designer/features/form-storage/ [jsonSchema]: /formengine-designer/features/forms-json/#json-schema diff --git a/packages/designer/index.ts b/packages/designer/index.ts index d3ff197c7..0eee6cd9c 100644 --- a/packages/designer/index.ts +++ b/packages/designer/index.ts @@ -16,6 +16,12 @@ export type {CustomizationMap} from './src/features/customization/CustomizationM export type {Options} from './src/features/customization/Options' export type {CustomizableKey} from './src/features/customization/types' export {CustomizableZone} from './src/features/customization/types' +export type { + DesignerHotkey, + DesignerHotkeyAction, + DesignerHotkeysOptions, + DesignerHotkeysProp, +} from './src/features/hotkeys/types' export {verifyDomain} from './src/features/license/domain' export {isElectron} from './src/features/license/isElectron' export type {StylesProviderProps} from './src/features/localization/components/StylesProviderProps' diff --git a/packages/designer/src/FormBuilder.tsx b/packages/designer/src/FormBuilder.tsx index 37b3aa2f1..370a6c8c6 100644 --- a/packages/designer/src/FormBuilder.tsx +++ b/packages/designer/src/FormBuilder.tsx @@ -18,13 +18,16 @@ import {RightPanel} from './features/ui/RightPanel/RightPanel' import {useBuilderStore} from './utils/BuilderStoreContext' const GlobalHotkeys = ({children}: {children: ReactNode}) => { + const builderStore = useBuilderStore() const handleKeyDown = useHotkeys() + const hotkeysDisabled = builderStore.props.hotkeys === false // we need this effect to be inside Suspense useEffect(() => { + if (hotkeysDisabled) return globalThis.addEventListener('keydown', handleKeyDown) return () => globalThis.removeEventListener('keydown', handleKeyDown) - }, [handleKeyDown]) + }, [handleKeyDown, hotkeysDisabled]) return
{children}
} diff --git a/packages/designer/src/FormBuilderProps.tsx b/packages/designer/src/FormBuilderProps.tsx index 288dd34fa..7786010cf 100644 --- a/packages/designer/src/FormBuilderProps.tsx +++ b/packages/designer/src/FormBuilderProps.tsx @@ -12,6 +12,7 @@ import type {ComponentType, ForwardedRef} from 'react' import type {FormBuilderTheme} from './FormBuilderTheme' import type {AnnotationEditorProps} from './features/annotation-editors/AnnotationEditorProps' import type {CustomizationMap} from './features/customization/CustomizationMap' +import type {DesignerHotkeysProp} from './features/hotkeys/types' import type {StylesProviderProps} from './features/localization/components/StylesProviderProps' import type {FormBuilderI18n} from './features/localization/FormBuilderLanguage' import type {IPresetComponentOptions} from './features/preset-component/IPresetComponentOptions' @@ -87,6 +88,14 @@ export interface FormBuilderProps extends Omit(['print']) + +const defaultHotKeys: Record = { + default: [ + [{key: 'Delete'}, 'deleteSelected'], + [{key: 'd', ctrl: true}, 'cloneSelected'], + [{key: 's', ctrl: true}, 'save'], + [{key: 'p', ctrl: true}, 'print'], + [{key: 'z', ctrl: true}, 'undo'], + [{key: 'z', ctrl: true, shift: true}, 'redo'], + [{key: 'y', ctrl: true}, 'redo'], + ], + macos: [ + [{key: 'Delete'}, 'deleteSelected'], + [{key: 'd', meta: true}, 'cloneSelected'], + [{key: 's', meta: true}, 'save'], + [{key: 'p', meta: true}, 'print'], + [{key: 'z', meta: true, shift: true}, 'redo'], + [{key: 'z', meta: true}, 'undo'], + ], +} + +/** + * @returns the OS key used to select the default hotkey map. + */ +const getHotkeyOs = (): OS => { + return navigator.userAgent.indexOf('Mac') === -1 ? 'default' : 'macos' +} + +/** + * Resolves the effective hotkey bindings for the designer. + * @param hotkeys the FormBuilder `hotkeys` prop value. + * @param os the OS key map to start from. Defaults to the current user agent. + * @returns the binding list. Empty when all hotkeys are disabled (`hotkeys: false`). + */ +export const resolveHotkeyBindings = (hotkeys: DesignerHotkeysProp | undefined, os: OS = getHotkeyOs()): HotkeyBinding[] => { + if (hotkeys === false) return [] + + const defaults = defaultHotKeys[os] + const overrides = hotkeys?.bindings + if (!overrides) return defaults + + const overriddenActions = new Set() + for (const action of Object.keys(overrides) as DesignerHotkeyAction[]) { + if (overrides[action] !== undefined) overriddenActions.add(action) + } + + const result: HotkeyBinding[] = defaults.filter(([, action]) => !overriddenActions.has(action)) + + for (const action of overriddenActions) { + const binding = overrides[action] + if (binding === false || binding === undefined) continue + const list = Array.isArray(binding) ? binding : [binding] + for (const hotkey of list) { + result.push([hotkey, action]) + } + } + + return result +} diff --git a/packages/designer/src/features/hotkeys/types.ts b/packages/designer/src/features/hotkeys/types.ts new file mode 100644 index 000000000..a1eec640a --- /dev/null +++ b/packages/designer/src/features/hotkeys/types.ts @@ -0,0 +1,47 @@ +/** + * Designer actions that can be bound to keyboard shortcuts or invoked via the form builder ref. + */ +export type DesignerHotkeyAction = 'deleteSelected' | 'cloneSelected' | 'save' | 'print' | 'undo' | 'redo' + +/** + * A single keyboard chord for a designer hotkey. + */ +export type DesignerHotkey = { + /** + * Whether the Alt key must be pressed. + */ + alt?: boolean + /** + * Whether the Shift key must be pressed. + */ + shift?: boolean + /** + * Whether the Control key must be pressed. + */ + ctrl?: boolean + /** + * Whether the Meta (Command) key must be pressed. + */ + meta?: boolean + /** + * The keyboard event `key` value, e.g. `'s'` or `'Delete'`. + */ + key: string +} + +/** + * Options for remapping or disabling individual designer hotkeys. + */ +export type DesignerHotkeysOptions = { + /** + * Per-action binding overrides. A value of `false` disables that action’s shortcuts. + * An unspecified action keeps the built-in default chords. + */ + bindings?: Partial> +} + +/** + * Controls the FormBuilder global keyboard shortcuts. + * Pass `false` to disable all built-in global hotkeys so the host can register its own. + */ +export type DesignerHotkeysProp = false | DesignerHotkeysOptions diff --git a/packages/designer/src/features/hotkeys/useHotKeys.tsx b/packages/designer/src/features/hotkeys/useHotKeys.tsx index 0f15e691e..3f535e863 100644 --- a/packages/designer/src/features/hotkeys/useHotKeys.tsx +++ b/packages/designer/src/features/hotkeys/useHotKeys.tsx @@ -1,7 +1,8 @@ import {useCallback, useMemo} from 'react' import {useBuilderStore} from '../../utils/BuilderStoreContext' -import {printForm} from '../ui/Header/components/printForm' import {useSaveForm} from '../ui/Header/components/useSaveForm' +import {alwaysActiveHotkeyActions, resolveHotkeyBindings} from './resolveHotkeyBindings' +import type {DesignerHotkey, DesignerHotkeyAction} from './types' /** * Stop the event from propagating and prevent its default action. @@ -12,94 +13,47 @@ const stopEvent = (event: KeyboardEvent) => { event.stopPropagation() } -type HotkeyAction = 'deleteSelectedAction' | 'cloneOneSelectedAction' | 'saveFormAction' | 'printFormAction' | 'undoAction' | 'redoAction' - -type OS = 'macos' | 'default' - -type Hotkey = { - alt?: boolean - shift?: boolean - ctrl?: boolean - meta?: boolean - key: string -} - type HotkeyHandler = () => void -/** - * Hotkeys that must run even when focus is inside an input or other control. - */ -const alwaysActiveActions = new Set(['printFormAction']) - -const hotKeys: Record> = { - default: [ - [{key: 'Delete'}, 'deleteSelectedAction'], - [{key: 'd', ctrl: true}, 'cloneOneSelectedAction'], - [{key: 's', ctrl: true}, 'saveFormAction'], - [{key: 'p', ctrl: true}, 'printFormAction'], - [{key: 'z', ctrl: true}, 'undoAction'], - [{key: 'z', ctrl: true, shift: true}, 'redoAction'], - [{key: 'y', ctrl: true}, 'redoAction'], - ], - macos: [ - [{key: 'Delete'}, 'deleteSelectedAction'], - [{key: 'd', meta: true}, 'cloneOneSelectedAction'], - [{key: 's', meta: true}, 'saveFormAction'], - [{key: 'p', meta: true}, 'printFormAction'], - [{key: 'z', meta: true, shift: true}, 'redoAction'], - [{key: 'z', meta: true}, 'undoAction'], - ], -} - -const getOs = (): OS => { - const ua = navigator.userAgent - return ua.indexOf('Mac') === -1 ? 'default' : 'macos' +const matchesHotkey = (hotkey: DesignerHotkey, event: KeyboardEvent) => { + return !( + hotkey.key.toLowerCase() !== event.key.toLowerCase() || + !!hotkey.alt !== event.altKey || + !!hotkey.shift !== event.shiftKey || + !!hotkey.ctrl !== event.ctrlKey || + !!hotkey.meta !== event.metaKey + ) } -const findHotkeyAction = (event: KeyboardEvent) => { +const findHotkeyAction = (event: KeyboardEvent, bindings: Array<[DesignerHotkey, DesignerHotkeyAction]>) => { if (!event.key) return - - const os = getOs() - - const keys = hotKeys[os] - const item = keys.find(([hotkey]) => { - return !( - hotkey.key.toLowerCase() !== event.key.toLowerCase() || - !!hotkey.alt !== event.altKey || - !!hotkey.shift !== event.shiftKey || - !!hotkey.ctrl !== event.ctrlKey || - !!hotkey.meta !== event.metaKey - ) - }) + const item = bindings.find(([hotkey]) => matchesHotkey(hotkey, event)) return item?.[1] } -const useHotkeyHandlers = (): Record => { +const useHotkeyHandlers = (): Record => { const builderStore = useBuilderStore() const onSave = useSaveForm() return useMemo( () => ({ - deleteSelectedAction: () => { - builderStore.deleteSelectedComponents() + deleteSelected: () => { + builderStore.deleteSelected() }, - cloneOneSelectedAction: () => { - const oneSelected = builderStore.oneSelected - if (oneSelected) { - builderStore.clone(oneSelected) - } + cloneSelected: () => { + builderStore.cloneSelected() }, - saveFormAction: () => { + save: () => { onSave() }, - printFormAction: () => { - printForm(builderStore) + print: () => { + builderStore.print() }, - undoAction: () => { - builderStore.undoer.undo() + undo: () => { + builderStore.undo() }, - redoAction: () => { - builderStore.undoer.redo() + redo: () => { + builderStore.redo() }, }), [builderStore, onSave] @@ -108,15 +62,18 @@ const useHotkeyHandlers = (): Record => { /** * @returns the global hotkeys handler. + * When `hotkeys: false`, FormBuilder does not attach this listener. */ export const useHotkeys = () => { + const builderStore = useBuilderStore() const handlers = useHotkeyHandlers() + const bindings = useMemo(() => resolveHotkeyBindings(builderStore.props.hotkeys), [builderStore.props.hotkeys]) return useCallback( (event: KeyboardEvent) => { - const action = findHotkeyAction(event) + const action = findHotkeyAction(event, bindings) if (!action) return - if (!alwaysActiveActions.has(action) && document.activeElement !== document.body) return + if (!alwaysActiveHotkeyActions.has(action) && document.activeElement !== document.body) return const handler = handlers[action] if (handler) { @@ -124,6 +81,6 @@ export const useHotkeys = () => { handler() } }, - [handlers] + [bindings, handlers] ) } diff --git a/packages/designer/src/features/ui/Header/components/printForm.ts b/packages/designer/src/features/print/printForm.ts similarity index 100% rename from packages/designer/src/features/ui/Header/components/printForm.ts rename to packages/designer/src/features/print/printForm.ts diff --git a/packages/designer/src/features/ui/CentralPanel.tsx b/packages/designer/src/features/ui/CentralPanel.tsx index 64d7497ad..309368427 100644 --- a/packages/designer/src/features/ui/CentralPanel.tsx +++ b/packages/designer/src/features/ui/CentralPanel.tsx @@ -8,9 +8,9 @@ import {customizableObserver} from '../customization/customizableObserver' import {CanvasAutoScrollOnDrag} from '../dnd/components/CanvasAutoScrollOnDrag' import {EditableWrapper} from '../dnd/components/Editable/Editable' import {TrialMessage} from '../license/TrialMessage' +import {usePrintWhenViewerReady} from '../print/printForm' import styles from './CentralPanel.module.css' import {ErrorFormWrapper} from './ErrorFormWrapper' -import {usePrintWhenViewerReady} from './Header/components/printForm' import {Header} from './Header/Header' import {NonVisualBar} from './NonVisualBar/NonVisualBar' import {PanelContainer} from './Panel' diff --git a/packages/designer/src/features/ui/Header/components/menu-items/PrintButton.tsx b/packages/designer/src/features/ui/Header/components/menu-items/PrintButton.tsx index a016ad2a7..56bd2e41b 100644 --- a/packages/designer/src/features/ui/Header/components/menu-items/PrintButton.tsx +++ b/packages/designer/src/features/ui/Header/components/menu-items/PrintButton.tsx @@ -5,7 +5,7 @@ import {useBuilderStore} from '../../../../../utils/BuilderStoreContext' import {FaIcon} from '../../../../components/Icons' import {customizable} from '../../../../customization/customizable' import {useTranslationPart} from '../../../../localization/hooks' -import {printForm} from '../printForm' +import {printForm} from '../../../../print/printForm' import type {CustomizableMenuItemProps} from './CustomizableMenuItemProps' const printIcon = diff --git a/packages/designer/src/stores/BuilderStore.ts b/packages/designer/src/stores/BuilderStore.ts index 9d4bfb0b1..899bc27c3 100644 --- a/packages/designer/src/stores/BuilderStore.ts +++ b/packages/designer/src/stores/BuilderStore.ts @@ -45,6 +45,7 @@ import type {FormBuilderI18nData} from '../features/localization/FormBuilderLang import {builtInLanguages, loadTranslation, resolveBuilderUiLanguage} from '../features/localization/languageUtils' import {BuilderPresetComponentOptions} from '../features/preset-component/BuilderPresetComponentOptions' import {removePresetLocalization} from '../features/preset-component/removePresetLocalization' +import {printForm} from '../features/print/printForm' import {LeftPanelChrome} from '../features/ui/LeftPanel/LeftPanelChrome' import type {PanelPlacement} from '../features/ui/PanelPlacement' import type {PromptDialogProps} from '../features/ui/PromptDialogProps' @@ -705,6 +706,35 @@ export class BuilderStore implements IFormBuilder, IComponentMetadataProvider { this.formListLastReloadTime = new Date() } + /** + * @inheritDoc + */ + cloneSelected() { + const oneSelected = this.oneSelected + if (oneSelected) this.clone(oneSelected) + } + + /** + * @inheritDoc + */ + print() { + printForm(this) + } + + /** + * @inheritDoc + */ + undo() { + this.undoer.undo() + } + + /** + * @inheritDoc + */ + redo() { + this.undoer.redo() + } + /** * Clones the component and adds the clone to the component tree. * @param source the cloning component. @@ -1371,9 +1401,9 @@ export class BuilderStore implements IFormBuilder, IComponentMetadataProvider { } /** - * Deletes the selected components from the component tree. + * @inheritDoc */ - deleteSelectedComponents() { + deleteSelected() { const selectedComponents = [...this.selected] if (selectedComponents.length <= 0) return diff --git a/packages/designer/src/stores/FormBuilderImpl.ts b/packages/designer/src/stores/FormBuilderImpl.ts index ae3d0cb26..516788a06 100644 --- a/packages/designer/src/stores/FormBuilderImpl.ts +++ b/packages/designer/src/stores/FormBuilderImpl.ts @@ -50,4 +50,46 @@ export class FormBuilderImpl implements IFormBuilder { reloadFormList() { this.builderStore.reloadFormList() } + + /** + * @inheritDoc + */ + deleteSelected() { + this.builderStore.deleteSelected() + } + + /** + * @inheritDoc + */ + cloneSelected() { + this.builderStore.cloneSelected() + } + + /** + * @inheritDoc + */ + save(formName?: string) { + return this.builderStore.save(formName) + } + + /** + * @inheritDoc + */ + print() { + this.builderStore.print() + } + + /** + * @inheritDoc + */ + undo() { + this.builderStore.undo() + } + + /** + * @inheritDoc + */ + redo() { + this.builderStore.redo() + } } diff --git a/packages/designer/src/utils/types.ts b/packages/designer/src/utils/types.ts index 10d7c2ac8..a8f528ec3 100644 --- a/packages/designer/src/utils/types.ts +++ b/packages/designer/src/utils/types.ts @@ -39,4 +39,37 @@ export interface IFormBuilder { * Updates the form list on the Forms tab. */ reloadFormList: () => void + + /** + * Deletes the currently selected components from the form. + */ + deleteSelected: () => void + + /** + * Clones the selected component when exactly one component is selected. + */ + cloneSelected: () => void + + /** + * Saves the current form to form storage without showing the designer toast. + * Built-in Ctrl/Cmd+S and the Save menu still show success/error toasts via the UI layer. + * @param formName the optional form name. When omitted, the active form name is used. + * @returns the promise that resolves when the form is saved. + */ + save: (formName?: string) => Promise + + /** + * Prints the form (switches to viewer mode for printing when needed). + */ + print: () => void + + /** + * Undoes the last form edit. + */ + undo: () => void + + /** + * Redoes the last undone form edit. + */ + redo: () => void } diff --git a/tests/component/tests/designer-hotkeys.spec.tsx b/tests/component/tests/designer-hotkeys.spec.tsx new file mode 100644 index 000000000..6870f16eb --- /dev/null +++ b/tests/component/tests/designer-hotkeys.spec.tsx @@ -0,0 +1,86 @@ +import {builderViewWithCss} from '@react-form-builder/components-rsuite' +import {FormBuilder, type IFormBuilder} from '@react-form-builder/designer' +import {generatedLicenseKey} from '@react-form-builder/tests-common/lib/designer/utils/license' +import {act, fireEvent, render, waitFor} from '@testing-library/react' +import {createRef} from 'react' +import {afterEach, describe, expect, it, vi} from 'vitest' +import form from './forms/designer-form.json' + +const getFormFn = () => JSON.stringify(form) + +const firePrintHotkey = () => { + const isMac = navigator.userAgent.includes('Mac') + fireEvent.keyDown(document, { + key: 'p', + ctrlKey: !isMac, + metaKey: isMac, + }) +} + +describe('Designer hotkeys', () => { + afterEach(() => { + vi.restoreAllMocks() + }) + + it('does not intercept Ctrl/Cmd+P when hotkeys are disabled', async () => { + const print = vi.spyOn(window, 'print').mockImplementation(() => undefined) + const {findByText} = render( + + ) + + expect(await findByText('Preview')).toBeInTheDocument() + firePrintHotkey() + + await waitFor(() => expect(print).not.toHaveBeenCalled()) + }) + + it('uses a remapped print binding and ignores the default chord', async () => { + const print = vi.spyOn(window, 'print').mockImplementation(() => undefined) + const {findByText} = render( + + ) + + expect(await findByText('Preview')).toBeInTheDocument() + + firePrintHotkey() + await waitFor(() => expect(print).not.toHaveBeenCalled()) + + fireEvent.keyDown(document, {key: 'p', altKey: true}) + await waitFor(() => expect(print).toHaveBeenCalledOnce()) + }) + + it('disables a single action binding while keeping others', async () => { + const print = vi.spyOn(window, 'print').mockImplementation(() => undefined) + const {findByText} = render( + + ) + + expect(await findByText('Preview')).toBeInTheDocument() + firePrintHotkey() + + await waitFor(() => expect(print).not.toHaveBeenCalled()) + }) + + it('invokes print through IFormBuilder when hotkeys are disabled', async () => { + const print = vi.spyOn(window, 'print').mockImplementation(() => undefined) + const builderRef = createRef() + const {findByText} = render( + + ) + + expect(await findByText('Preview')).toBeInTheDocument() + await waitFor(() => expect(builderRef.current).not.toBeNull()) + + act(() => { + builderRef.current?.print() + }) + + await waitFor(() => expect(print).toHaveBeenCalledOnce()) + expect(await findByText('Edit')).toBeInTheDocument() + }) +}) diff --git a/tests/module/tests/accordion-child-wrapper.spec.tsx b/tests/module/tests/accordion-child-wrapper.spec.tsx index 1d66935ec..84cc9f41e 100644 --- a/tests/module/tests/accordion-child-wrapper.spec.tsx +++ b/tests/module/tests/accordion-child-wrapper.spec.tsx @@ -989,14 +989,14 @@ describe('Accordion BuilderStore integration', () => { }) describe('multi-select remove and clone', () => { - it('reindexes and retargets activeKey when deleteSelectedComponents removes multiple panels including the active one', () => { + it('reindexes and retargets activeKey when deleteSelected removes multiple panels including the active one', () => { builderStore.parseForm(JSON.stringify(threePanelAccordionForm('2', '2'))) const accordion = find('accordion') builderStore.selected.clear() builderStore.selectNode(find('panel1'), true) builderStore.selectNode(find('panel2'), true) - builderStore.deleteSelectedComponents() + builderStore.deleteSelected() expect(panelKeys()).toEqual(['panel3']) expect(panelEventKeys()).toEqual(['1']) diff --git a/tests/module/tests/resolve-hotkey-bindings.spec.ts b/tests/module/tests/resolve-hotkey-bindings.spec.ts new file mode 100644 index 000000000..08e8d5f41 --- /dev/null +++ b/tests/module/tests/resolve-hotkey-bindings.spec.ts @@ -0,0 +1,73 @@ +import {resolveHotkeyBindings} from '@react-form-builder/designer/src/features/hotkeys/resolveHotkeyBindings' +import type {DesignerHotkeyAction} from '@react-form-builder/designer/src/features/hotkeys/types' +import {describe, expect, it} from 'vitest' + +const actionsFor = (bindings: ReturnType) => bindings.map(([, action]) => action) + +const chordFor = (bindings: ReturnType, action: DesignerHotkeyAction) => + bindings.filter(([, boundAction]) => boundAction === action).map(([hotkey]) => hotkey) + +describe('resolveHotkeyBindings', () => { + it('returns default Windows/Linux chords when hotkeys are unset', () => { + const bindings = resolveHotkeyBindings(undefined, 'default') + + expect(actionsFor(bindings)).toEqual(['deleteSelected', 'cloneSelected', 'save', 'print', 'undo', 'redo', 'redo']) + expect(chordFor(bindings, 'save')).toEqual([{key: 's', ctrl: true}]) + expect(chordFor(bindings, 'redo')).toEqual([ + {key: 'z', ctrl: true, shift: true}, + {key: 'y', ctrl: true}, + ]) + }) + + it('returns default macOS chords when os is macos', () => { + const bindings = resolveHotkeyBindings(undefined, 'macos') + + expect(chordFor(bindings, 'save')).toEqual([{key: 's', meta: true}]) + expect(chordFor(bindings, 'redo')).toEqual([{key: 'z', meta: true, shift: true}]) + expect(bindings.some(([hotkey]) => hotkey.key.toLowerCase() === 'y')).toBe(false) + }) + + it('returns an empty list when hotkeys are disabled', () => { + expect(resolveHotkeyBindings(false, 'default')).toEqual([]) + }) + + it('disables a single action and keeps the rest', () => { + const bindings = resolveHotkeyBindings({bindings: {print: false}}, 'default') + + expect(chordFor(bindings, 'print')).toEqual([]) + expect(chordFor(bindings, 'save')).toEqual([{key: 's', ctrl: true}]) + }) + + it('replaces an action chord and drops its defaults', () => { + const bindings = resolveHotkeyBindings({bindings: {save: {key: 's', alt: true}}}, 'default') + + expect(chordFor(bindings, 'save')).toEqual([{key: 's', alt: true}]) + }) + + it('accepts multiple chords for one action', () => { + const bindings = resolveHotkeyBindings( + { + bindings: { + undo: [ + {key: 'z', ctrl: true}, + {key: 'u', alt: true}, + ], + }, + }, + 'default' + ) + + expect(chordFor(bindings, 'undo')).toEqual([ + {key: 'z', ctrl: true}, + {key: 'u', alt: true}, + ]) + }) + + it('keeps unspecified actions on their defaults when remapping others', () => { + const bindings = resolveHotkeyBindings({bindings: {cloneSelected: {key: 'd', alt: true}}}, 'macos') + + expect(chordFor(bindings, 'cloneSelected')).toEqual([{key: 'd', alt: true}]) + expect(chordFor(bindings, 'deleteSelected')).toEqual([{key: 'Delete'}]) + expect(chordFor(bindings, 'print')).toEqual([{key: 'p', meta: true}]) + }) +}) From f6bfcb522e6280f5ceaf6e17ff54981665cc54c0 Mon Sep 17 00:00:00 2001 From: Alexey Cherepanov Date: Thu, 26 Nov 2026 13:45:51 +0300 Subject: [PATCH 02/13] fix doc --- .../features/designer-customization.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/documentation/docs/formengine-designer/features/designer-customization.md b/documentation/docs/formengine-designer/features/designer-customization.md index 708a339bc..b8c0798f0 100644 --- a/documentation/docs/formengine-designer/features/designer-customization.md +++ b/documentation/docs/formengine-designer/features/designer-customization.md @@ -421,13 +421,17 @@ const EmbeddedDesigner = () => { ### Remap or disable individual shortcuts +Only the actions you list under `bindings` change. Every other action keeps its built-in default chords. +For a listed action, the value **replaces** that action’s defaults (it does not add to them). Use `false` to turn that +action’s shortcuts off while leaving the rest unchanged. + ```tsx Date: Thu, 26 Nov 2026 16:12:26 +0300 Subject: [PATCH 03/13] regenerate typedoc-sidebar.cjs --- .../@react-form-builder/designer/index.md | 4 + .../designer/interfaces/FormBuilderProps.md | 11 +++ .../designer/interfaces/IFormBuilder.md | 83 +++++++++++++++++++ .../designer/type-aliases/DesignerHotkey.md | 45 ++++++++++ .../type-aliases/DesignerHotkeyAction.md | 5 ++ .../type-aliases/DesignerHotkeysOptions.md | 14 ++++ .../type-aliases/DesignerHotkeysProp.md | 6 ++ .../docs/api-reference/typedoc-sidebar.cjs | 20 +++++ 8 files changed, 188 insertions(+) create mode 100644 documentation/docs/api-reference/@react-form-builder/designer/type-aliases/DesignerHotkey.md create mode 100644 documentation/docs/api-reference/@react-form-builder/designer/type-aliases/DesignerHotkeyAction.md create mode 100644 documentation/docs/api-reference/@react-form-builder/designer/type-aliases/DesignerHotkeysOptions.md create mode 100644 documentation/docs/api-reference/@react-form-builder/designer/type-aliases/DesignerHotkeysProp.md diff --git a/documentation/docs/api-reference/@react-form-builder/designer/index.md b/documentation/docs/api-reference/@react-form-builder/designer/index.md index a60f171ed..e9394eacb 100644 --- a/documentation/docs/api-reference/@react-form-builder/designer/index.md +++ b/documentation/docs/api-reference/@react-form-builder/designer/index.md @@ -31,6 +31,10 @@ - [ComputeTypeParams](type-aliases/ComputeTypeParams.md) - [CustomizableKey](type-aliases/CustomizableKey.md) - [CustomizationMap](type-aliases/CustomizationMap.md) +- [DesignerHotkey](type-aliases/DesignerHotkey.md) +- [DesignerHotkeyAction](type-aliases/DesignerHotkeyAction.md) +- [DesignerHotkeysOptions](type-aliases/DesignerHotkeysOptions.md) +- [DesignerHotkeysProp](type-aliases/DesignerHotkeysProp.md) - [FormBuilderI18n](type-aliases/FormBuilderI18n.md) - [FormBuilderI18nData](type-aliases/FormBuilderI18nData.md) - [FormBuilderTheme](type-aliases/FormBuilderTheme.md) diff --git a/documentation/docs/api-reference/@react-form-builder/designer/interfaces/FormBuilderProps.md b/documentation/docs/api-reference/@react-form-builder/designer/interfaces/FormBuilderProps.md index 2b720d0b7..34ce806e9 100644 --- a/documentation/docs/api-reference/@react-form-builder/designer/interfaces/FormBuilderProps.md +++ b/documentation/docs/api-reference/@react-form-builder/designer/interfaces/FormBuilderProps.md @@ -213,6 +213,17 @@ the string or Promise with the form. *** +### hotkeys? + +> `optional` **hotkeys?**: [`DesignerHotkeysProp`](../type-aliases/DesignerHotkeysProp.md) + +Controls the FormBuilder global keyboard shortcuts. +Pass `false` to disable all built-in global hotkeys so the host can register its own +and invoke actions through [IFormBuilder](IFormBuilder.md). Pass an options object to remap or +disable individual actions. + +*** + ### i18n? > `optional` **i18n?**: [`FormBuilderI18n`](../type-aliases/FormBuilderI18n.md) diff --git a/documentation/docs/api-reference/@react-form-builder/designer/interfaces/IFormBuilder.md b/documentation/docs/api-reference/@react-form-builder/designer/interfaces/IFormBuilder.md index a9ab521bf..8e2991b03 100644 --- a/documentation/docs/api-reference/@react-form-builder/designer/interfaces/IFormBuilder.md +++ b/documentation/docs/api-reference/@react-form-builder/designer/interfaces/IFormBuilder.md @@ -4,6 +4,30 @@ The form builder settings interface. ## Properties +### cloneSelected + +> **cloneSelected**: () => `void` + +Clones the selected component when exactly one component is selected. + +#### Returns + +`void` + +*** + +### deleteSelected + +> **deleteSelected**: () => `void` + +Deletes the currently selected components from the form. + +#### Returns + +`void` + +*** + ### parseForm > **parseForm**: (`text`) => `void` @@ -24,6 +48,30 @@ the form serialized in JSON. *** +### print + +> **print**: () => `void` + +Prints the form (switches to viewer mode for printing when needed). + +#### Returns + +`void` + +*** + +### redo + +> **redo**: () => `void` + +Redoes the last undone form edit. + +#### Returns + +`void` + +*** + ### reloadFormList > **reloadFormList**: () => `void` @@ -34,6 +82,41 @@ Updates the form list on the Forms tab. `void` +*** + +### save + +> **save**: (`formName?`) => `Promise`\<`void`\> + +Saves the current form to form storage without showing the designer toast. +Built-in Ctrl/Cmd+S and the Save menu still show success/error toasts via the UI layer. + +#### Parameters + +##### formName? + +`string` + +the optional form name. When omitted, the active form name is used. + +#### Returns + +`Promise`\<`void`\> + +the promise that resolves when the form is saved. + +*** + +### undo + +> **undo**: () => `void` + +Undoes the last form edit. + +#### Returns + +`void` + ## Accessors ### builderMode diff --git a/documentation/docs/api-reference/@react-form-builder/designer/type-aliases/DesignerHotkey.md b/documentation/docs/api-reference/@react-form-builder/designer/type-aliases/DesignerHotkey.md new file mode 100644 index 000000000..bf72cce7e --- /dev/null +++ b/documentation/docs/api-reference/@react-form-builder/designer/type-aliases/DesignerHotkey.md @@ -0,0 +1,45 @@ +# Type Alias: DesignerHotkey + +> **DesignerHotkey** = `object` + +A single keyboard chord for a designer hotkey. + +## Properties + +### alt? + +> `optional` **alt?**: `boolean` + +Whether the Alt key must be pressed. + +*** + +### ctrl? + +> `optional` **ctrl?**: `boolean` + +Whether the Control key must be pressed. + +*** + +### key + +> **key**: `string` + +The keyboard event `key` value, e.g. `'s'` or `'Delete'`. + +*** + +### meta? + +> `optional` **meta?**: `boolean` + +Whether the Meta (Command) key must be pressed. + +*** + +### shift? + +> `optional` **shift?**: `boolean` + +Whether the Shift key must be pressed. diff --git a/documentation/docs/api-reference/@react-form-builder/designer/type-aliases/DesignerHotkeyAction.md b/documentation/docs/api-reference/@react-form-builder/designer/type-aliases/DesignerHotkeyAction.md new file mode 100644 index 000000000..a027c2893 --- /dev/null +++ b/documentation/docs/api-reference/@react-form-builder/designer/type-aliases/DesignerHotkeyAction.md @@ -0,0 +1,5 @@ +# Type Alias: DesignerHotkeyAction + +> **DesignerHotkeyAction** = `"cloneSelected"` \| `"deleteSelected"` \| `"print"` \| `"redo"` \| `"save"` \| `"undo"` + +Designer actions that can be bound to keyboard shortcuts or invoked via the form builder ref. diff --git a/documentation/docs/api-reference/@react-form-builder/designer/type-aliases/DesignerHotkeysOptions.md b/documentation/docs/api-reference/@react-form-builder/designer/type-aliases/DesignerHotkeysOptions.md new file mode 100644 index 000000000..d81581158 --- /dev/null +++ b/documentation/docs/api-reference/@react-form-builder/designer/type-aliases/DesignerHotkeysOptions.md @@ -0,0 +1,14 @@ +# Type Alias: DesignerHotkeysOptions + +> **DesignerHotkeysOptions** = `object` + +Options for remapping or disabling individual designer hotkeys. + +## Properties + +### bindings? + +> `optional` **bindings?**: `Partial`\<`Record`\<[`DesignerHotkeyAction`](DesignerHotkeyAction.md), [`DesignerHotkey`](DesignerHotkey.md)[] \| [`DesignerHotkey`](DesignerHotkey.md) \| `false`\>\> + +Per-action binding overrides. A value of `false` disables that action’s shortcuts. +An unspecified action keeps the built-in default chords. diff --git a/documentation/docs/api-reference/@react-form-builder/designer/type-aliases/DesignerHotkeysProp.md b/documentation/docs/api-reference/@react-form-builder/designer/type-aliases/DesignerHotkeysProp.md new file mode 100644 index 000000000..f95c79eac --- /dev/null +++ b/documentation/docs/api-reference/@react-form-builder/designer/type-aliases/DesignerHotkeysProp.md @@ -0,0 +1,6 @@ +# Type Alias: DesignerHotkeysProp + +> **DesignerHotkeysProp** = [`DesignerHotkeysOptions`](DesignerHotkeysOptions.md) \| `false` + +Controls the FormBuilder global keyboard shortcuts. +Pass `false` to disable all built-in global hotkeys so the host can register its own. diff --git a/documentation/docs/api-reference/typedoc-sidebar.cjs b/documentation/docs/api-reference/typedoc-sidebar.cjs index b78b25f93..f7905f551 100644 --- a/documentation/docs/api-reference/typedoc-sidebar.cjs +++ b/documentation/docs/api-reference/typedoc-sidebar.cjs @@ -3277,6 +3277,26 @@ const typedocSidebar = { id: "api-reference/@react-form-builder/designer/type-aliases/CustomizationMap", label: "CustomizationMap" }, + { + type: "doc", + id: "api-reference/@react-form-builder/designer/type-aliases/DesignerHotkey", + label: "DesignerHotkey" + }, + { + type: "doc", + id: "api-reference/@react-form-builder/designer/type-aliases/DesignerHotkeyAction", + label: "DesignerHotkeyAction" + }, + { + type: "doc", + id: "api-reference/@react-form-builder/designer/type-aliases/DesignerHotkeysOptions", + label: "DesignerHotkeysOptions" + }, + { + type: "doc", + id: "api-reference/@react-form-builder/designer/type-aliases/DesignerHotkeysProp", + label: "DesignerHotkeysProp" + }, { type: "doc", id: "api-reference/@react-form-builder/designer/type-aliases/FormBuilderI18n", From 8b14dab62ec36cc5aa585deec9c02ceecef98825 Mon Sep 17 00:00:00 2001 From: Alexey Cherepanov Date: Thu, 26 Nov 2026 23:05:28 +0300 Subject: [PATCH 04/13] fix: apply hotkeys prop changes without remount BuilderStore keeps mount-time props, so toggling hotkeys after mount had no effect. Provide the live hotkeys prop through React context for listener registration and binding resolution. --- packages/designer/src/FormBuilder.tsx | 4 +- .../features/hotkeys/HotkeysPropContext.tsx | 25 +++++++++++ .../src/features/hotkeys/useHotKeys.tsx | 5 ++- .../src/features/ui/BuilderProviders.tsx | 39 +++++++++-------- .../component/tests/designer-hotkeys.spec.tsx | 42 +++++++++++++++++++ 5 files changed, 93 insertions(+), 22 deletions(-) create mode 100644 packages/designer/src/features/hotkeys/HotkeysPropContext.tsx diff --git a/packages/designer/src/FormBuilder.tsx b/packages/designer/src/FormBuilder.tsx index 370a6c8c6..7a1c62b77 100644 --- a/packages/designer/src/FormBuilder.tsx +++ b/packages/designer/src/FormBuilder.tsx @@ -6,6 +6,7 @@ import {Loader} from 'rsuite' import styles from './FormBuilder.module.css' import type {FormBuilderProps} from './FormBuilderProps' import {customizableObserver} from './features/customization/customizableObserver' +import {useHotkeysProp} from './features/hotkeys/HotkeysPropContext' import {useHotkeys} from './features/hotkeys/useHotKeys' import {useLicense} from './features/license/LicenseContext' import {BottomPanel} from './features/ui/BottomPanel/BottomPanel' @@ -18,9 +19,8 @@ import {RightPanel} from './features/ui/RightPanel/RightPanel' import {useBuilderStore} from './utils/BuilderStoreContext' const GlobalHotkeys = ({children}: {children: ReactNode}) => { - const builderStore = useBuilderStore() const handleKeyDown = useHotkeys() - const hotkeysDisabled = builderStore.props.hotkeys === false + const hotkeysDisabled = useHotkeysProp() === false // we need this effect to be inside Suspense useEffect(() => { diff --git a/packages/designer/src/features/hotkeys/HotkeysPropContext.tsx b/packages/designer/src/features/hotkeys/HotkeysPropContext.tsx new file mode 100644 index 000000000..1c11481d9 --- /dev/null +++ b/packages/designer/src/features/hotkeys/HotkeysPropContext.tsx @@ -0,0 +1,25 @@ +import type {ReactNode} from 'react' +import {createContext, useContext} from 'react' +import type {DesignerHotkeysProp} from './types' + +const HotkeysPropContext = createContext(undefined) + +type HotkeysPropProviderProps = { + value: DesignerHotkeysProp | undefined + children: ReactNode +} + +/** + * Provides the current FormBuilder `hotkeys` prop to descendants. + * BuilderStore keeps the mount-time props object; this context tracks live updates. + * @param props the provider properties. + * @returns the React element. + */ +export const HotkeysPropProvider = ({value, children}: HotkeysPropProviderProps) => { + return {children} +} + +/** + * @returns the current FormBuilder `hotkeys` prop from context. + */ +export const useHotkeysProp = () => useContext(HotkeysPropContext) diff --git a/packages/designer/src/features/hotkeys/useHotKeys.tsx b/packages/designer/src/features/hotkeys/useHotKeys.tsx index 3f535e863..aa453eef9 100644 --- a/packages/designer/src/features/hotkeys/useHotKeys.tsx +++ b/packages/designer/src/features/hotkeys/useHotKeys.tsx @@ -1,6 +1,7 @@ import {useCallback, useMemo} from 'react' import {useBuilderStore} from '../../utils/BuilderStoreContext' import {useSaveForm} from '../ui/Header/components/useSaveForm' +import {useHotkeysProp} from './HotkeysPropContext' import {alwaysActiveHotkeyActions, resolveHotkeyBindings} from './resolveHotkeyBindings' import type {DesignerHotkey, DesignerHotkeyAction} from './types' @@ -65,9 +66,9 @@ const useHotkeyHandlers = (): Record => { * When `hotkeys: false`, FormBuilder does not attach this listener. */ export const useHotkeys = () => { - const builderStore = useBuilderStore() const handlers = useHotkeyHandlers() - const bindings = useMemo(() => resolveHotkeyBindings(builderStore.props.hotkeys), [builderStore.props.hotkeys]) + const hotkeys = useHotkeysProp() + const bindings = useMemo(() => resolveHotkeyBindings(hotkeys), [hotkeys]) return useCallback( (event: KeyboardEvent) => { diff --git a/packages/designer/src/features/ui/BuilderProviders.tsx b/packages/designer/src/features/ui/BuilderProviders.tsx index 7a64822fd..e2c330e9d 100644 --- a/packages/designer/src/features/ui/BuilderProviders.tsx +++ b/packages/designer/src/features/ui/BuilderProviders.tsx @@ -30,6 +30,7 @@ import {getBuilderChildren} from '../dnd/components/Editable/Editable' import {LicenseManager} from '../license/LicenseManager' import {LocalizationProvider} from '../localization/components/LocalizationProvider' import {resolveBuilderUiLanguage} from '../localization/languageUtils' +import {HotkeysPropProvider} from '../hotkeys/HotkeysPropContext' import {BuiltinPropertyEditorsProvider} from './BuiltinPropertyEditorsProvider' import {FormBuilderContextProvider} from './FormBuilderContextProvider' import {StylesProvider} from './StylesProvider' @@ -175,24 +176,26 @@ const RawProviders = ({children, props, builderStore, store}: BuilderProvidersPr return ( - - - - - - - - - {children} - - - - - - - - - + + + + + + + + + + {children} + + + + + + + + + + ) diff --git a/tests/component/tests/designer-hotkeys.spec.tsx b/tests/component/tests/designer-hotkeys.spec.tsx index 6870f16eb..9b15d7a17 100644 --- a/tests/component/tests/designer-hotkeys.spec.tsx +++ b/tests/component/tests/designer-hotkeys.spec.tsx @@ -83,4 +83,46 @@ describe('Designer hotkeys', () => { await waitFor(() => expect(print).toHaveBeenCalledOnce()) expect(await findByText('Edit')).toBeInTheDocument() }) + + it('stops intercepting Ctrl/Cmd+P after rerendering with hotkeys={false}', async () => { + const print = vi.spyOn(window, 'print').mockImplementation(() => undefined) + const {findByText, rerender} = render() + + expect(await findByText('Preview')).toBeInTheDocument() + + firePrintHotkey() + await waitFor(() => expect(print).toHaveBeenCalledOnce()) + print.mockClear() + fireEvent(window, new Event('afterprint')) + expect(await findByText('Preview')).toBeInTheDocument() + + rerender() + + firePrintHotkey() + await waitFor(() => expect(print).not.toHaveBeenCalled()) + }) + + it('activates a remapped print chord after enabling hotkeys on a mounted designer', async () => { + const print = vi.spyOn(window, 'print').mockImplementation(() => undefined) + const {findByText, rerender} = render( + + ) + + expect(await findByText('Preview')).toBeInTheDocument() + + fireEvent.keyDown(document, {key: 'F8'}) + await waitFor(() => expect(print).not.toHaveBeenCalled()) + + rerender( + + ) + + fireEvent.keyDown(document, {key: 'F8'}) + await waitFor(() => expect(print).toHaveBeenCalledOnce()) + }) }) From af7fc6396c3a0a4d7c8e2628df7cdde1b3b885d6 Mon Sep 17 00:00:00 2001 From: Alexey Cherepanov Date: Thu, 26 Nov 2026 23:08:40 +0300 Subject: [PATCH 05/13] fix: let remapped hotkey chords override defaults When Print was bound to Delete, the default Delete binding still matched first and removed the selection. Drop conflicting default chords and prefer overrides in the resolved list. --- .../features/hotkeys/resolveHotkeyBindings.ts | 28 ++++++++++++++++--- .../component/tests/designer-hotkeys.spec.tsx | 18 ++++++++++++ .../tests/resolve-hotkey-bindings.spec.ts | 7 +++++ 3 files changed, 49 insertions(+), 4 deletions(-) diff --git a/packages/designer/src/features/hotkeys/resolveHotkeyBindings.ts b/packages/designer/src/features/hotkeys/resolveHotkeyBindings.ts index 56f7cf9bc..ed7e51cdb 100644 --- a/packages/designer/src/features/hotkeys/resolveHotkeyBindings.ts +++ b/packages/designer/src/features/hotkeys/resolveHotkeyBindings.ts @@ -42,6 +42,21 @@ const getHotkeyOs = (): OS => { * @param os the OS key map to start from. Defaults to the current user agent. * @returns the binding list. Empty when all hotkeys are disabled (`hotkeys: false`). */ +/** + * @param left the first chord. + * @param right the second chord. + * @returns whether both chords require the same key and modifiers. + */ +const sameChord = (left: DesignerHotkey, right: DesignerHotkey) => { + return ( + left.key.toLowerCase() === right.key.toLowerCase() && + !!left.alt === !!right.alt && + !!left.shift === !!right.shift && + !!left.ctrl === !!right.ctrl && + !!left.meta === !!right.meta + ) +} + export const resolveHotkeyBindings = (hotkeys: DesignerHotkeysProp | undefined, os: OS = getHotkeyOs()): HotkeyBinding[] => { if (hotkeys === false) return [] @@ -54,16 +69,21 @@ export const resolveHotkeyBindings = (hotkeys: DesignerHotkeysProp | undefined, if (overrides[action] !== undefined) overriddenActions.add(action) } - const result: HotkeyBinding[] = defaults.filter(([, action]) => !overriddenActions.has(action)) - + const overrideBindings: HotkeyBinding[] = [] for (const action of overriddenActions) { const binding = overrides[action] if (binding === false || binding === undefined) continue const list = Array.isArray(binding) ? binding : [binding] for (const hotkey of list) { - result.push([hotkey, action]) + overrideBindings.push([hotkey, action]) } } - return result + // Overrides win chords: drop defaults that share a chord so find() cannot hit Delete before Print. + const result = defaults.filter(([hotkey, action]) => { + if (overriddenActions.has(action)) return false + return !overrideBindings.some(([overrideHotkey]) => sameChord(hotkey, overrideHotkey)) + }) + + return [...overrideBindings, ...result] } diff --git a/tests/component/tests/designer-hotkeys.spec.tsx b/tests/component/tests/designer-hotkeys.spec.tsx index 9b15d7a17..63e5ba3b7 100644 --- a/tests/component/tests/designer-hotkeys.spec.tsx +++ b/tests/component/tests/designer-hotkeys.spec.tsx @@ -125,4 +125,22 @@ describe('Designer hotkeys', () => { fireEvent.keyDown(document, {key: 'F8'}) await waitFor(() => expect(print).toHaveBeenCalledOnce()) }) + + it('prints on Delete when print is remapped onto that chord', async () => { + const print = vi.spyOn(window, 'print').mockImplementation(() => undefined) + const {findByText} = render( + + ) + + expect(await findByText('Preview')).toBeInTheDocument() + fireEvent.keyDown(document, {key: 'Delete'}) + + await waitFor(() => expect(print).toHaveBeenCalledOnce()) + expect(await findByText('Edit')).toBeInTheDocument() + }) }) diff --git a/tests/module/tests/resolve-hotkey-bindings.spec.ts b/tests/module/tests/resolve-hotkey-bindings.spec.ts index 08e8d5f41..1ae835eec 100644 --- a/tests/module/tests/resolve-hotkey-bindings.spec.ts +++ b/tests/module/tests/resolve-hotkey-bindings.spec.ts @@ -70,4 +70,11 @@ describe('resolveHotkeyBindings', () => { expect(chordFor(bindings, 'deleteSelected')).toEqual([{key: 'Delete'}]) expect(chordFor(bindings, 'print')).toEqual([{key: 'p', meta: true}]) }) + + it('drops default chords that conflict with an override so the override wins', () => { + const bindings = resolveHotkeyBindings({bindings: {print: {key: 'Delete'}}}, 'default') + + expect(chordFor(bindings, 'print')).toEqual([{key: 'Delete'}]) + expect(chordFor(bindings, 'deleteSelected')).toEqual([]) + }) }) From b6158c4d11552f33d996e0170a5d8f01e22d1796 Mon Sep 17 00:00:00 2001 From: Alexey Cherepanov Date: Thu, 26 Nov 2026 23:09:21 +0300 Subject: [PATCH 06/13] fix: derive Print menu shortcut from hotkeys config Hard-coded Ctrl/Cmd+P stayed visible when print was disabled or remapped. Show the resolved print chord, or omit the hint when there is none. --- .../features/hotkeys/formatHotkeyShortcut.ts | 21 +++++++ .../components/menu-items/PrintButton.tsx | 13 ++++- tests/component/tests/print-button.spec.tsx | 55 +++++++++++++++++-- 3 files changed, 82 insertions(+), 7 deletions(-) create mode 100644 packages/designer/src/features/hotkeys/formatHotkeyShortcut.ts diff --git a/packages/designer/src/features/hotkeys/formatHotkeyShortcut.ts b/packages/designer/src/features/hotkeys/formatHotkeyShortcut.ts new file mode 100644 index 000000000..3fe35109e --- /dev/null +++ b/packages/designer/src/features/hotkeys/formatHotkeyShortcut.ts @@ -0,0 +1,21 @@ +import type {DesignerHotkey} from './types' + +/** + * Formats a designer hotkey chord for menu hints. + * @param hotkey the chord to format. + * @param isMac whether to use macOS modifier glyphs. + * @returns a short shortcut label such as `Ctrl+P`, `⌘P`, or `F8`. + */ +export const formatHotkeyShortcut = (hotkey: DesignerHotkey, isMac = navigator.userAgent.includes('Mac')): string => { + const parts: string[] = [] + if (hotkey.ctrl) parts.push(isMac ? '⌃' : 'Ctrl') + if (hotkey.alt) parts.push(isMac ? '⌥' : 'Alt') + if (hotkey.shift) parts.push(isMac ? '⇧' : 'Shift') + if (hotkey.meta) parts.push('⌘') + + const keyLabel = hotkey.key.length === 1 ? hotkey.key.toUpperCase() : hotkey.key + if (isMac && parts.length > 0) { + return `${parts.join('')}${keyLabel}` + } + return [...parts, keyLabel].join('+') +} diff --git a/packages/designer/src/features/ui/Header/components/menu-items/PrintButton.tsx b/packages/designer/src/features/ui/Header/components/menu-items/PrintButton.tsx index 56bd2e41b..8d979e699 100644 --- a/packages/designer/src/features/ui/Header/components/menu-items/PrintButton.tsx +++ b/packages/designer/src/features/ui/Header/components/menu-items/PrintButton.tsx @@ -1,22 +1,29 @@ import {faPrint} from '@fortawesome/free-solid-svg-icons' -import {useCallback} from 'react' +import {useCallback, useMemo} from 'react' import {Dropdown} from 'rsuite' import {useBuilderStore} from '../../../../../utils/BuilderStoreContext' import {FaIcon} from '../../../../components/Icons' import {customizable} from '../../../../customization/customizable' +import {formatHotkeyShortcut} from '../../../../hotkeys/formatHotkeyShortcut' +import {useHotkeysProp} from '../../../../hotkeys/HotkeysPropContext' +import {resolveHotkeyBindings} from '../../../../hotkeys/resolveHotkeyBindings' import {useTranslationPart} from '../../../../localization/hooks' import {printForm} from '../../../../print/printForm' import type {CustomizableMenuItemProps} from './CustomizableMenuItemProps' const printIcon = -const printShortcut = typeof navigator !== 'undefined' && navigator.userAgent.includes('Mac') ? '⌘P' : 'Ctrl+P' - const RawPrintButton = ({className}: CustomizableMenuItemProps) => { const store = useBuilderStore() const t = useTranslationPart('leftMenu') + const hotkeys = useHotkeysProp() const onSelect = useCallback(() => printForm(store), [store]) + const printShortcut = useMemo(() => { + const printBinding = resolveHotkeyBindings(hotkeys).find(([, action]) => action === 'print')?.[0] + return printBinding ? formatHotkeyShortcut(printBinding) : undefined + }, [hotkeys]) + return ( {t('print')} diff --git a/tests/component/tests/print-button.spec.tsx b/tests/component/tests/print-button.spec.tsx index 40b62c1df..c5f1dcd96 100644 --- a/tests/component/tests/print-button.spec.tsx +++ b/tests/component/tests/print-button.spec.tsx @@ -29,19 +29,66 @@ describe('Designer print', () => { expect(await findByText('Preview')).toBeInTheDocument() }) + const openMainMenu = async (container: HTMLElement) => { + const mainMenuDropdown = container.querySelector('.FE_MainMenu_Dropdown') as HTMLElement + const mainMenuButton = mainMenuDropdown.querySelector('.FE_MainMenu_Button > button') as HTMLElement + fireEvent.click(mainMenuButton) + } + it('shows the print hotkey hint in the main menu', async () => { const {container, findByText} = render() const isMac = navigator.userAgent.includes('Mac') expect(await findByText('Preview')).toBeInTheDocument() - - const mainMenuDropdown = container.querySelector('.FE_MainMenu_Dropdown') as HTMLElement - const mainMenuButton = mainMenuDropdown.querySelector('.FE_MainMenu_Button > button') as HTMLElement - fireEvent.click(mainMenuButton) + await openMainMenu(container) expect(await findByText(isMac ? '⌘P' : 'Ctrl+P')).toBeInTheDocument() }) + it('omits the print shortcut hint when hotkeys are disabled', async () => { + const {container, findByText, queryByText} = render( + + ) + const isMac = navigator.userAgent.includes('Mac') + + expect(await findByText('Preview')).toBeInTheDocument() + await openMainMenu(container) + + expect(await findByText('Print')).toBeInTheDocument() + expect(queryByText(isMac ? '⌘P' : 'Ctrl+P')).not.toBeInTheDocument() + }) + + it('omits the print shortcut hint when the print binding is disabled', async () => { + const {container, findByText, queryByText} = render( + + ) + const isMac = navigator.userAgent.includes('Mac') + + expect(await findByText('Preview')).toBeInTheDocument() + await openMainMenu(container) + + expect(await findByText('Print')).toBeInTheDocument() + expect(queryByText(isMac ? '⌘P' : 'Ctrl+P')).not.toBeInTheDocument() + }) + + it('shows the remapped print shortcut hint', async () => { + const {container, findByText, queryByText} = render( + + ) + const isMac = navigator.userAgent.includes('Mac') + + expect(await findByText('Preview')).toBeInTheDocument() + await openMainMenu(container) + + expect(await findByText('F8')).toBeInTheDocument() + expect(queryByText(isMac ? '⌘P' : 'Ctrl+P')).not.toBeInTheDocument() + }) + it('intercepts Ctrl/Cmd+P and prints through viewer mode', async () => { const print = vi.spyOn(window, 'print').mockImplementation(() => undefined) const {findByText} = render() From f5b7ce111ec5ce9b0f9a8f7c7edc4593e006d07e Mon Sep 17 00:00:00 2001 From: Alexey Cherepanov Date: Thu, 26 Nov 2026 23:09:32 +0300 Subject: [PATCH 07/13] docs: use F8 for the Save hotkey remap example MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Option+S is layout-dependent on macOS US (produces ß), so the example could not trigger Save. Prefer a non-character chord. --- .../formengine-designer/features/designer-customization.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/documentation/docs/formengine-designer/features/designer-customization.md b/documentation/docs/formengine-designer/features/designer-customization.md index b8c0798f0..b5ca85964 100644 --- a/documentation/docs/formengine-designer/features/designer-customization.md +++ b/documentation/docs/formengine-designer/features/designer-customization.md @@ -429,8 +429,9 @@ action’s shortcuts off while leaving the rest unchanged. Date: Thu, 26 Nov 2026 23:12:13 +0300 Subject: [PATCH 08/13] chore: fix JSDoc and import order for hotkeys changes --- .../src/features/hotkeys/HotkeysPropContext.tsx | 2 ++ .../src/features/hotkeys/resolveHotkeyBindings.ts | 12 ++++++------ .../designer/src/features/ui/BuilderProviders.tsx | 2 +- 3 files changed, 9 insertions(+), 7 deletions(-) diff --git a/packages/designer/src/features/hotkeys/HotkeysPropContext.tsx b/packages/designer/src/features/hotkeys/HotkeysPropContext.tsx index 1c11481d9..24298981c 100644 --- a/packages/designer/src/features/hotkeys/HotkeysPropContext.tsx +++ b/packages/designer/src/features/hotkeys/HotkeysPropContext.tsx @@ -13,6 +13,8 @@ type HotkeysPropProviderProps = { * Provides the current FormBuilder `hotkeys` prop to descendants. * BuilderStore keeps the mount-time props object; this context tracks live updates. * @param props the provider properties. + * @param props.value the current FormBuilder `hotkeys` prop. + * @param props.children the React child nodes. * @returns the React element. */ export const HotkeysPropProvider = ({value, children}: HotkeysPropProviderProps) => { diff --git a/packages/designer/src/features/hotkeys/resolveHotkeyBindings.ts b/packages/designer/src/features/hotkeys/resolveHotkeyBindings.ts index ed7e51cdb..c5218b04c 100644 --- a/packages/designer/src/features/hotkeys/resolveHotkeyBindings.ts +++ b/packages/designer/src/features/hotkeys/resolveHotkeyBindings.ts @@ -36,12 +36,6 @@ const getHotkeyOs = (): OS => { return navigator.userAgent.indexOf('Mac') === -1 ? 'default' : 'macos' } -/** - * Resolves the effective hotkey bindings for the designer. - * @param hotkeys the FormBuilder `hotkeys` prop value. - * @param os the OS key map to start from. Defaults to the current user agent. - * @returns the binding list. Empty when all hotkeys are disabled (`hotkeys: false`). - */ /** * @param left the first chord. * @param right the second chord. @@ -57,6 +51,12 @@ const sameChord = (left: DesignerHotkey, right: DesignerHotkey) => { ) } +/** + * Resolves the effective hotkey bindings for the designer. + * @param hotkeys the FormBuilder `hotkeys` prop value. + * @param os the OS key map to start from. Defaults to the current user agent. + * @returns the binding list. Empty when all hotkeys are disabled (`hotkeys: false`). + */ export const resolveHotkeyBindings = (hotkeys: DesignerHotkeysProp | undefined, os: OS = getHotkeyOs()): HotkeyBinding[] => { if (hotkeys === false) return [] diff --git a/packages/designer/src/features/ui/BuilderProviders.tsx b/packages/designer/src/features/ui/BuilderProviders.tsx index e2c330e9d..43e4a9a2d 100644 --- a/packages/designer/src/features/ui/BuilderProviders.tsx +++ b/packages/designer/src/features/ui/BuilderProviders.tsx @@ -27,10 +27,10 @@ import {TooltipPlacementProvider} from '../../utils/TooltipPlacementContext' import {EditorMap} from '../annotation-editors/EditorMap' import {CustomDragLayer} from '../dnd/components/CustomDragLayer' import {getBuilderChildren} from '../dnd/components/Editable/Editable' +import {HotkeysPropProvider} from '../hotkeys/HotkeysPropContext' import {LicenseManager} from '../license/LicenseManager' import {LocalizationProvider} from '../localization/components/LocalizationProvider' import {resolveBuilderUiLanguage} from '../localization/languageUtils' -import {HotkeysPropProvider} from '../hotkeys/HotkeysPropContext' import {BuiltinPropertyEditorsProvider} from './BuiltinPropertyEditorsProvider' import {FormBuilderContextProvider} from './FormBuilderContextProvider' import {StylesProvider} from './StylesProvider' From 8d78998e2ee9e88516a58917b610adc1553f785e Mon Sep 17 00:00:00 2001 From: Alexey Cherepanov Date: Fri, 27 Nov 2026 07:09:20 +0300 Subject: [PATCH 09/13] clean --- packages/designer/src/features/hotkeys/resolveHotkeyBindings.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/packages/designer/src/features/hotkeys/resolveHotkeyBindings.ts b/packages/designer/src/features/hotkeys/resolveHotkeyBindings.ts index c5218b04c..152ecab44 100644 --- a/packages/designer/src/features/hotkeys/resolveHotkeyBindings.ts +++ b/packages/designer/src/features/hotkeys/resolveHotkeyBindings.ts @@ -79,7 +79,6 @@ export const resolveHotkeyBindings = (hotkeys: DesignerHotkeysProp | undefined, } } - // Overrides win chords: drop defaults that share a chord so find() cannot hit Delete before Print. const result = defaults.filter(([hotkey, action]) => { if (overriddenActions.has(action)) return false return !overrideBindings.some(([overrideHotkey]) => sameChord(hotkey, overrideHotkey)) From c30477a90166f87d14d64c8ffe625084ad2cd75a Mon Sep 17 00:00:00 2001 From: Alexey Cherepanov Date: Fri, 27 Nov 2026 07:15:11 +0300 Subject: [PATCH 10/13] test: harden hotkey coverage from review findings Assert Preview/Edit mode after deferred print flush so disabled-hotkey checks cannot false-pass, cover live remap and Ctrl/Cmd+S, prove Delete override keeps the selection, and guard formatHotkeyShortcut navigator. --- .../features/hotkeys/formatHotkeyShortcut.ts | 4 +- .../component/tests/designer-hotkeys.spec.tsx | 114 +++++++++++++++--- .../tests/format-hotkey-shortcut.spec.ts | 25 ++++ 3 files changed, 126 insertions(+), 17 deletions(-) create mode 100644 tests/module/tests/format-hotkey-shortcut.spec.ts diff --git a/packages/designer/src/features/hotkeys/formatHotkeyShortcut.ts b/packages/designer/src/features/hotkeys/formatHotkeyShortcut.ts index 3fe35109e..007d9b619 100644 --- a/packages/designer/src/features/hotkeys/formatHotkeyShortcut.ts +++ b/packages/designer/src/features/hotkeys/formatHotkeyShortcut.ts @@ -1,12 +1,14 @@ import type {DesignerHotkey} from './types' +const isMacPlatform = () => typeof navigator !== 'undefined' && navigator.userAgent.includes('Mac') + /** * Formats a designer hotkey chord for menu hints. * @param hotkey the chord to format. * @param isMac whether to use macOS modifier glyphs. * @returns a short shortcut label such as `Ctrl+P`, `⌘P`, or `F8`. */ -export const formatHotkeyShortcut = (hotkey: DesignerHotkey, isMac = navigator.userAgent.includes('Mac')): string => { +export const formatHotkeyShortcut = (hotkey: DesignerHotkey, isMac = isMacPlatform()): string => { const parts: string[] = [] if (hotkey.ctrl) parts.push(isMac ? '⌃' : 'Ctrl') if (hotkey.alt) parts.push(isMac ? '⌥' : 'Alt') diff --git a/tests/component/tests/designer-hotkeys.spec.tsx b/tests/component/tests/designer-hotkeys.spec.tsx index 63e5ba3b7..ca3e706c2 100644 --- a/tests/component/tests/designer-hotkeys.spec.tsx +++ b/tests/component/tests/designer-hotkeys.spec.tsx @@ -8,12 +8,34 @@ import form from './forms/designer-form.json' const getFormFn = () => JSON.stringify(form) +const isMac = () => navigator.userAgent.includes('Mac') + const firePrintHotkey = () => { - const isMac = navigator.userAgent.includes('Mac') fireEvent.keyDown(document, { key: 'p', - ctrlKey: !isMac, - metaKey: isMac, + ctrlKey: !isMac(), + metaKey: isMac(), + }) +} + +const fireSaveHotkey = () => { + const event = new KeyboardEvent('keydown', { + key: 's', + ctrlKey: !isMac(), + metaKey: isMac(), + bubbles: true, + cancelable: true, + }) + window.dispatchEvent(event) + return event +} + +/** + * Flush microtasks/layout so a deferred window.print from usePrintWhenViewerReady would have run. + */ +const flushDeferredPrint = async () => { + await act(async () => { + await Promise.resolve() }) } @@ -24,19 +46,21 @@ describe('Designer hotkeys', () => { it('does not intercept Ctrl/Cmd+P when hotkeys are disabled', async () => { const print = vi.spyOn(window, 'print').mockImplementation(() => undefined) - const {findByText} = render( + const {findByText, queryByText} = render( ) expect(await findByText('Preview')).toBeInTheDocument() firePrintHotkey() + await flushDeferredPrint() - await waitFor(() => expect(print).not.toHaveBeenCalled()) + expect(print).not.toHaveBeenCalled() + expect(queryByText('Edit')).not.toBeInTheDocument() }) it('uses a remapped print binding and ignores the default chord', async () => { const print = vi.spyOn(window, 'print').mockImplementation(() => undefined) - const {findByText} = render( + const {findByText, queryByText} = render( { expect(await findByText('Preview')).toBeInTheDocument() firePrintHotkey() - await waitFor(() => expect(print).not.toHaveBeenCalled()) + await flushDeferredPrint() + expect(print).not.toHaveBeenCalled() + expect(queryByText('Edit')).not.toBeInTheDocument() fireEvent.keyDown(document, {key: 'p', altKey: true}) await waitFor(() => expect(print).toHaveBeenCalledOnce()) @@ -56,14 +82,16 @@ describe('Designer hotkeys', () => { it('disables a single action binding while keeping others', async () => { const print = vi.spyOn(window, 'print').mockImplementation(() => undefined) - const {findByText} = render( + const {findByText, queryByText} = render( ) expect(await findByText('Preview')).toBeInTheDocument() firePrintHotkey() + await flushDeferredPrint() - await waitFor(() => expect(print).not.toHaveBeenCalled()) + expect(print).not.toHaveBeenCalled() + expect(queryByText('Edit')).not.toBeInTheDocument() }) it('invokes print through IFormBuilder when hotkeys are disabled', async () => { @@ -84,9 +112,11 @@ describe('Designer hotkeys', () => { expect(await findByText('Edit')).toBeInTheDocument() }) - it('stops intercepting Ctrl/Cmd+P after rerendering with hotkeys={false}', async () => { + it('stops intercepting Ctrl/Cmd+P and Ctrl/Cmd+S after rerendering with hotkeys={false}', async () => { const print = vi.spyOn(window, 'print').mockImplementation(() => undefined) - const {findByText, rerender} = render() + const {findByText, queryByText, rerender} = render( + + ) expect(await findByText('Preview')).toBeInTheDocument() @@ -99,19 +129,26 @@ describe('Designer hotkeys', () => { rerender() firePrintHotkey() - await waitFor(() => expect(print).not.toHaveBeenCalled()) + await flushDeferredPrint() + expect(print).not.toHaveBeenCalled() + expect(queryByText('Edit')).not.toBeInTheDocument() + + const saveEvent = fireSaveHotkey() + expect(saveEvent.defaultPrevented).toBe(false) }) it('activates a remapped print chord after enabling hotkeys on a mounted designer', async () => { const print = vi.spyOn(window, 'print').mockImplementation(() => undefined) - const {findByText, rerender} = render( + const {findByText, queryByText, rerender} = render( ) expect(await findByText('Preview')).toBeInTheDocument() fireEvent.keyDown(document, {key: 'F8'}) - await waitFor(() => expect(print).not.toHaveBeenCalled()) + await flushDeferredPrint() + expect(print).not.toHaveBeenCalled() + expect(queryByText('Edit')).not.toBeInTheDocument() rerender( { await waitFor(() => expect(print).toHaveBeenCalledOnce()) }) - it('prints on Delete when print is remapped onto that chord', async () => { + it('remaps print on a mounted designer without disabling hotkeys first', async () => { const print = vi.spyOn(window, 'print').mockImplementation(() => undefined) - const {findByText} = render( + const {findByText, queryByText, rerender} = render( + + ) + + expect(await findByText('Preview')).toBeInTheDocument() + + rerender( + ) + + firePrintHotkey() + await flushDeferredPrint() + expect(print).not.toHaveBeenCalled() + expect(queryByText('Edit')).not.toBeInTheDocument() + + fireEvent.keyDown(document, {key: 'F8'}) + await waitFor(() => expect(print).toHaveBeenCalledOnce()) + }) + + it('runs print when remapped to Delete instead of removing the selection', async () => { + const print = vi.spyOn(window, 'print').mockImplementation(() => undefined) + const getConflictForm = () => + JSON.stringify({ + form: { + key: 'Screen', + type: 'Screen', + children: [{key: 'nestedButton', type: 'RsButton', props: {children: {value: 'Nested'}}}], + }, + }) + const {findByTestId, findByText} = render( + ) expect(await findByText('Preview')).toBeInTheDocument() + await act(async () => { + fireEvent.click(await findByTestId('nestedButton-editable-wrapper')) + }) + await act(async () => { + ;(document.activeElement as HTMLElement | null)?.blur() + }) + expect(document.activeElement).toBe(document.body) + fireEvent.keyDown(document, {key: 'Delete'}) await waitFor(() => expect(print).toHaveBeenCalledOnce()) expect(await findByText('Edit')).toBeInTheDocument() + + fireEvent(window, new Event('afterprint')) + expect(await findByTestId('nestedButton-editable-wrapper')).toBeInTheDocument() }) }) diff --git a/tests/module/tests/format-hotkey-shortcut.spec.ts b/tests/module/tests/format-hotkey-shortcut.spec.ts new file mode 100644 index 000000000..35df465da --- /dev/null +++ b/tests/module/tests/format-hotkey-shortcut.spec.ts @@ -0,0 +1,25 @@ +import {formatHotkeyShortcut} from '@react-form-builder/designer/src/features/hotkeys/formatHotkeyShortcut' +import {describe, expect, it} from 'vitest' + +describe('formatHotkeyShortcut', () => { + it('formats Windows/Linux chords with plus separators', () => { + expect(formatHotkeyShortcut({key: 'p', ctrl: true}, false)).toBe('Ctrl+P') + expect(formatHotkeyShortcut({key: 'F8'}, false)).toBe('F8') + }) + + it('formats macOS chords with modifier glyphs', () => { + expect(formatHotkeyShortcut({key: 'p', meta: true}, true)).toBe('⌘P') + expect(formatHotkeyShortcut({key: 's', alt: true}, true)).toBe('⌥S') + }) + + it('defaults isMac without throwing when navigator is unavailable', () => { + const descriptor = Object.getOwnPropertyDescriptor(globalThis, 'navigator') + Object.defineProperty(globalThis, 'navigator', {configurable: true, value: undefined}) + try { + expect(formatHotkeyShortcut({key: 'p', ctrl: true})).toBe('Ctrl+P') + } finally { + if (descriptor) Object.defineProperty(globalThis, 'navigator', descriptor) + else Reflect.deleteProperty(globalThis, 'navigator') + } + }) +}) From a650316f75ed97c104d1d16871e434769d169760 Mon Sep 17 00:00:00 2001 From: Alexey Cherepanov Date: Fri, 27 Nov 2026 07:40:55 +0300 Subject: [PATCH 11/13] fix: avoid nested await inside act in Delete hotkey test React 18 treated the license/SearchForm updates from that pattern as console errors under vitest-fail-on-console. --- tests/component/tests/designer-hotkeys.spec.tsx | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/tests/component/tests/designer-hotkeys.spec.tsx b/tests/component/tests/designer-hotkeys.spec.tsx index ca3e706c2..860174033 100644 --- a/tests/component/tests/designer-hotkeys.spec.tsx +++ b/tests/component/tests/designer-hotkeys.spec.tsx @@ -209,9 +209,8 @@ describe('Designer hotkeys', () => { ) expect(await findByText('Preview')).toBeInTheDocument() - await act(async () => { - fireEvent.click(await findByTestId('nestedButton-editable-wrapper')) - }) + const nestedButton = await findByTestId('nestedButton-editable-wrapper') + fireEvent.click(nestedButton) await act(async () => { ;(document.activeElement as HTMLElement | null)?.blur() }) From 146eeb1dc92135368fd187f64d0395483e1a29ee Mon Sep 17 00:00:00 2001 From: Alexey Cherepanov Date: Fri, 27 Nov 2026 12:09:11 +0300 Subject: [PATCH 12/13] fix: duplicate keys --- .../features/designer-customization.md | 3 +- .../features/hotkeys/resolveHotkeyBindings.ts | 53 ++++++++++++++++++- packages/designer/src/utils/types.ts | 14 ++--- .../component/tests/designer-hotkeys.spec.tsx | 40 +++++++++++++- .../tests/resolve-hotkey-bindings.spec.ts | 23 +++++++- 5 files changed, 122 insertions(+), 11 deletions(-) diff --git a/documentation/docs/formengine-designer/features/designer-customization.md b/documentation/docs/formengine-designer/features/designer-customization.md index b5ca85964..41cd734b3 100644 --- a/documentation/docs/formengine-designer/features/designer-customization.md +++ b/documentation/docs/formengine-designer/features/designer-customization.md @@ -409,7 +409,7 @@ const EmbeddedDesigner = () => { const onKeyDown = (event: KeyboardEvent) => { if (!(event.ctrlKey || event.metaKey) || event.key.toLowerCase() !== 's') return event.preventDefault() - void builderRef.current?.save() + void builderRef.current?.save?.() } globalThis.addEventListener('keydown', onKeyDown) return () => globalThis.removeEventListener('keydown', onKeyDown) @@ -442,6 +442,7 @@ action’s shortcuts off while leaving the rest unchanged. Action ids: `deleteSelected`, `cloneSelected`, `save`, `print`, `undo`, `redo`. Pass an array of chords when one action should accept multiple bindings. +If two actions claim the same chord, the later entry in `bindings` wins and the earlier action loses that chord. On macOS prefer `meta`; on Windows and Linux prefer `ctrl`. Use function keys when the chord must be layout-independent. ### Imperative actions diff --git a/packages/designer/src/features/hotkeys/resolveHotkeyBindings.ts b/packages/designer/src/features/hotkeys/resolveHotkeyBindings.ts index 152ecab44..6990286ba 100644 --- a/packages/designer/src/features/hotkeys/resolveHotkeyBindings.ts +++ b/packages/designer/src/features/hotkeys/resolveHotkeyBindings.ts @@ -51,8 +51,55 @@ const sameChord = (left: DesignerHotkey, right: DesignerHotkey) => { ) } +/** + * @param hotkey the chord to identify. + * @returns a stable id for key + modifiers. + */ +const chordId = (hotkey: DesignerHotkey) => { + return `${hotkey.key.toLowerCase()}|${+!!hotkey.alt}|${+!!hotkey.shift}|${+!!hotkey.ctrl}|${+!!hotkey.meta}` +} + +/** + * @param hotkey the chord to describe. + * @returns a plain shortcut label for warning messages. + */ +const formatChordForWarn = (hotkey: DesignerHotkey) => { + const parts: string[] = [] + if (hotkey.ctrl) parts.push('Ctrl') + if (hotkey.alt) parts.push('Alt') + if (hotkey.shift) parts.push('Shift') + if (hotkey.meta) parts.push('Meta') + const keyLabel = hotkey.key.length === 1 ? hotkey.key.toUpperCase() : hotkey.key + return [...parts, keyLabel].join('+') +} + +/** + * Keeps one binding per chord. Later entries replace earlier ones for the same chord. + * @param bindings the bindings in declaration order. + * @returns the bindings with unique chords. + */ +const dedupeChordsLastWins = (bindings: HotkeyBinding[]): HotkeyBinding[] => { + const winners = new Map() + const order: string[] = [] + for (const binding of bindings) { + const id = chordId(binding[0]) + const previous = winners.get(id) + if (previous && previous[1] !== binding[1]) { + console.warn( + `FormBuilder hotkeys: chord "${formatChordForWarn(binding[0])}" is bound to both ` + + `"${previous[1]}" and "${binding[1]}". Using "${binding[1]}" (later binding wins).` + ) + } + if (!winners.has(id)) order.push(id) + winners.set(id, binding) + } + return order.map(id => winners.get(id)!) +} + /** * Resolves the effective hotkey bindings for the designer. + * When two overrides claim the same chord, the later binding in `bindings` wins. + * Defaults that share a chord with an override are dropped. * @param hotkeys the FormBuilder `hotkeys` prop value. * @param os the OS key map to start from. Defaults to the current user agent. * @returns the binding list. Empty when all hotkeys are disabled (`hotkeys: false`). @@ -79,10 +126,12 @@ export const resolveHotkeyBindings = (hotkeys: DesignerHotkeysProp | undefined, } } + const uniqueOverrides = dedupeChordsLastWins(overrideBindings) + const result = defaults.filter(([hotkey, action]) => { if (overriddenActions.has(action)) return false - return !overrideBindings.some(([overrideHotkey]) => sameChord(hotkey, overrideHotkey)) + return !uniqueOverrides.some(([overrideHotkey]) => sameChord(hotkey, overrideHotkey)) }) - return [...overrideBindings, ...result] + return [...uniqueOverrides, ...result] } diff --git a/packages/designer/src/utils/types.ts b/packages/designer/src/utils/types.ts index a8f528ec3..eabb79020 100644 --- a/packages/designer/src/utils/types.ts +++ b/packages/designer/src/utils/types.ts @@ -12,6 +12,8 @@ export type Device = 'any' | ViewMode /** * The form builder settings interface. + * Imperative action methods are optional for backward-compatible mocks and custom + * implementations; the designer `builderRef` / `useFormBuilder()` instance always provides them. */ export interface IFormBuilder { /** @@ -43,12 +45,12 @@ export interface IFormBuilder { /** * Deletes the currently selected components from the form. */ - deleteSelected: () => void + deleteSelected?: () => void /** * Clones the selected component when exactly one component is selected. */ - cloneSelected: () => void + cloneSelected?: () => void /** * Saves the current form to form storage without showing the designer toast. @@ -56,20 +58,20 @@ export interface IFormBuilder { * @param formName the optional form name. When omitted, the active form name is used. * @returns the promise that resolves when the form is saved. */ - save: (formName?: string) => Promise + save?: (formName?: string) => Promise /** * Prints the form (switches to viewer mode for printing when needed). */ - print: () => void + print?: () => void /** * Undoes the last form edit. */ - undo: () => void + undo?: () => void /** * Redoes the last undone form edit. */ - redo: () => void + redo?: () => void } diff --git a/tests/component/tests/designer-hotkeys.spec.tsx b/tests/component/tests/designer-hotkeys.spec.tsx index 860174033..09a678f56 100644 --- a/tests/component/tests/designer-hotkeys.spec.tsx +++ b/tests/component/tests/designer-hotkeys.spec.tsx @@ -105,7 +105,7 @@ describe('Designer hotkeys', () => { await waitFor(() => expect(builderRef.current).not.toBeNull()) act(() => { - builderRef.current?.print() + builderRef.current?.print?.() }) await waitFor(() => expect(print).toHaveBeenCalledOnce()) @@ -224,4 +224,42 @@ describe('Designer hotkeys', () => { fireEvent(window, new Event('afterprint')) expect(await findByTestId('nestedButton-editable-wrapper')).toBeInTheDocument() }) + + it('runs print when F8 is claimed by deleteSelected then print', async () => { + const print = vi.spyOn(window, 'print').mockImplementation(() => undefined) + vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const getConflictForm = () => + JSON.stringify({ + form: { + key: 'Screen', + type: 'Screen', + children: [{key: 'nestedButton', type: 'RsButton', props: {children: {value: 'Nested'}}}], + }, + }) + const {findByTestId, findByText} = render( + + ) + + expect(await findByText('Preview')).toBeInTheDocument() + expect(await findByText('F8')).toBeInTheDocument() + const nestedButton = await findByTestId('nestedButton-editable-wrapper') + fireEvent.click(nestedButton) + await act(async () => { + ;(document.activeElement as HTMLElement | null)?.blur() + }) + expect(document.activeElement).toBe(document.body) + + fireEvent.keyDown(document, {key: 'F8'}) + + await waitFor(() => expect(print).toHaveBeenCalledOnce()) + expect(await findByText('Edit')).toBeInTheDocument() + + fireEvent(window, new Event('afterprint')) + expect(await findByTestId('nestedButton-editable-wrapper')).toBeInTheDocument() + }) }) diff --git a/tests/module/tests/resolve-hotkey-bindings.spec.ts b/tests/module/tests/resolve-hotkey-bindings.spec.ts index 1ae835eec..860621757 100644 --- a/tests/module/tests/resolve-hotkey-bindings.spec.ts +++ b/tests/module/tests/resolve-hotkey-bindings.spec.ts @@ -1,6 +1,6 @@ import {resolveHotkeyBindings} from '@react-form-builder/designer/src/features/hotkeys/resolveHotkeyBindings' import type {DesignerHotkeyAction} from '@react-form-builder/designer/src/features/hotkeys/types' -import {describe, expect, it} from 'vitest' +import {describe, expect, it, vi} from 'vitest' const actionsFor = (bindings: ReturnType) => bindings.map(([, action]) => action) @@ -77,4 +77,25 @@ describe('resolveHotkeyBindings', () => { expect(chordFor(bindings, 'print')).toEqual([{key: 'Delete'}]) expect(chordFor(bindings, 'deleteSelected')).toEqual([]) }) + + it('gives the later override the chord when two actions claim the same key', () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + + const bindings = resolveHotkeyBindings( + { + bindings: { + deleteSelected: {key: 'F8'}, + print: {key: 'F8'}, + }, + }, + 'default' + ) + + expect(chordFor(bindings, 'print')).toEqual([{key: 'F8'}]) + expect(chordFor(bindings, 'deleteSelected')).toEqual([]) + expect(bindings.filter(([hotkey]) => hotkey.key.toLowerCase() === 'f8')).toHaveLength(1) + expect(warn).toHaveBeenCalledWith( + 'FormBuilder hotkeys: chord "F8" is bound to both "deleteSelected" and "print". Using "print" (later binding wins).' + ) + }) }) From d625a3ab3d60010a2afaa341cc9427c6e61095d0 Mon Sep 17 00:00:00 2001 From: Aleksandr Shalugin Date: Fri, 27 Nov 2026 16:42:01 +0300 Subject: [PATCH 13/13] Update IFormBuilder.md --- .../designer/interfaces/IFormBuilder.md | 26 ++++++++++--------- 1 file changed, 14 insertions(+), 12 deletions(-) diff --git a/documentation/docs/api-reference/@react-form-builder/designer/interfaces/IFormBuilder.md b/documentation/docs/api-reference/@react-form-builder/designer/interfaces/IFormBuilder.md index 8e2991b03..017f4763f 100644 --- a/documentation/docs/api-reference/@react-form-builder/designer/interfaces/IFormBuilder.md +++ b/documentation/docs/api-reference/@react-form-builder/designer/interfaces/IFormBuilder.md @@ -1,12 +1,14 @@ # Interface: IFormBuilder The form builder settings interface. +Imperative action methods are optional for backward-compatible mocks and custom +implementations; the designer `builderRef` / `useFormBuilder()` instance always provides them. ## Properties -### cloneSelected +### cloneSelected? -> **cloneSelected**: () => `void` +> `optional` **cloneSelected?**: () => `void` Clones the selected component when exactly one component is selected. @@ -16,9 +18,9 @@ Clones the selected component when exactly one component is selected. *** -### deleteSelected +### deleteSelected? -> **deleteSelected**: () => `void` +> `optional` **deleteSelected?**: () => `void` Deletes the currently selected components from the form. @@ -48,9 +50,9 @@ the form serialized in JSON. *** -### print +### print? -> **print**: () => `void` +> `optional` **print?**: () => `void` Prints the form (switches to viewer mode for printing when needed). @@ -60,9 +62,9 @@ Prints the form (switches to viewer mode for printing when needed). *** -### redo +### redo? -> **redo**: () => `void` +> `optional` **redo?**: () => `void` Redoes the last undone form edit. @@ -84,9 +86,9 @@ Updates the form list on the Forms tab. *** -### save +### save? -> **save**: (`formName?`) => `Promise`\<`void`\> +> `optional` **save?**: (`formName?`) => `Promise`\<`void`\> Saves the current form to form storage without showing the designer toast. Built-in Ctrl/Cmd+S and the Save menu still show success/error toasts via the UI layer. @@ -107,9 +109,9 @@ the promise that resolves when the form is saved. *** -### undo +### undo? -> **undo**: () => `void` +> `optional` **undo?**: () => `void` Undoes the last form edit.