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..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,9 +1,35 @@ # 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? + +> `optional` **cloneSelected?**: () => `void` + +Clones the selected component when exactly one component is selected. + +#### Returns + +`void` + +*** + +### deleteSelected? + +> `optional` **deleteSelected?**: () => `void` + +Deletes the currently selected components from the form. + +#### Returns + +`void` + +*** + ### parseForm > **parseForm**: (`text`) => `void` @@ -24,6 +50,30 @@ the form serialized in JSON. *** +### print? + +> `optional` **print?**: () => `void` + +Prints the form (switches to viewer mode for printing when needed). + +#### Returns + +`void` + +*** + +### redo? + +> `optional` **redo?**: () => `void` + +Redoes the last undone form edit. + +#### Returns + +`void` + +*** + ### reloadFormList > **reloadFormList**: () => `void` @@ -34,6 +84,41 @@ Updates the form list on the Forms tab. `void` +*** + +### save? + +> `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. + +#### 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? + +> `optional` **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", diff --git a/documentation/docs/formengine-designer/features/designer-customization.md b/documentation/docs/formengine-designer/features/designer-customization.md index e83c74fa9..41cd734b3 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,79 @@ 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 + +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 + +``` + +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 + +| 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..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' @@ -19,12 +20,14 @@ import {useBuilderStore} from './utils/BuilderStoreContext' const GlobalHotkeys = ({children}: {children: ReactNode}) => { const handleKeyDown = useHotkeys() + const hotkeysDisabled = useHotkeysProp() === 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(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. + * @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) => { + return {children} +} + +/** + * @returns the current FormBuilder `hotkeys` prop from context. + */ +export const useHotkeysProp = () => useContext(HotkeysPropContext) diff --git a/packages/designer/src/features/hotkeys/formatHotkeyShortcut.ts b/packages/designer/src/features/hotkeys/formatHotkeyShortcut.ts new file mode 100644 index 000000000..007d9b619 --- /dev/null +++ b/packages/designer/src/features/hotkeys/formatHotkeyShortcut.ts @@ -0,0 +1,23 @@ +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 = isMacPlatform()): 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/hotkeys/resolveHotkeyBindings.ts b/packages/designer/src/features/hotkeys/resolveHotkeyBindings.ts new file mode 100644 index 000000000..6990286ba --- /dev/null +++ b/packages/designer/src/features/hotkeys/resolveHotkeyBindings.ts @@ -0,0 +1,137 @@ +import type {DesignerHotkey, DesignerHotkeyAction, DesignerHotkeysProp} from './types' + +type OS = 'macos' | 'default' + +type HotkeyBinding = [DesignerHotkey, DesignerHotkeyAction] + +/** + * Hotkeys that must run even when focus is inside an input or other control. + */ +export const alwaysActiveHotkeyActions = new Set(['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' +} + +/** + * @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 + ) +} + +/** + * @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`). + */ +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 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) { + overrideBindings.push([hotkey, action]) + } + } + + const uniqueOverrides = dedupeChordsLastWins(overrideBindings) + + const result = defaults.filter(([hotkey, action]) => { + if (overriddenActions.has(action)) return false + return !uniqueOverrides.some(([overrideHotkey]) => sameChord(hotkey, overrideHotkey)) + }) + + return [...uniqueOverrides, ...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..aa453eef9 100644 --- a/packages/designer/src/features/hotkeys/useHotKeys.tsx +++ b/packages/designer/src/features/hotkeys/useHotKeys.tsx @@ -1,7 +1,9 @@ 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 {useHotkeysProp} from './HotkeysPropContext' +import {alwaysActiveHotkeyActions, resolveHotkeyBindings} from './resolveHotkeyBindings' +import type {DesignerHotkey, DesignerHotkeyAction} from './types' /** * Stop the event from propagating and prevent its default action. @@ -12,94 +14,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 +63,18 @@ const useHotkeyHandlers = (): Record => { /** * @returns the global hotkeys handler. + * When `hotkeys: false`, FormBuilder does not attach this listener. */ export const useHotkeys = () => { const handlers = useHotkeyHandlers() + const hotkeys = useHotkeysProp() + const bindings = useMemo(() => resolveHotkeyBindings(hotkeys), [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 +82,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/BuilderProviders.tsx b/packages/designer/src/features/ui/BuilderProviders.tsx index 7a64822fd..43e4a9a2d 100644 --- a/packages/designer/src/features/ui/BuilderProviders.tsx +++ b/packages/designer/src/features/ui/BuilderProviders.tsx @@ -27,6 +27,7 @@ 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' @@ -175,24 +176,26 @@ const RawProviders = ({children, props, builderStore, store}: BuilderProvidersPr return ( - - - - - - - - - {children} - - - - - - - - - + + + + + + + + + + {children} + + + + + + + + + + ) 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..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 '../printForm' +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/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..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 { /** @@ -39,4 +41,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..09a678f56 --- /dev/null +++ b/tests/component/tests/designer-hotkeys.spec.tsx @@ -0,0 +1,265 @@ +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 isMac = () => navigator.userAgent.includes('Mac') + +const firePrintHotkey = () => { + fireEvent.keyDown(document, { + key: 'p', + 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() + }) +} + +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, queryByText} = render( + + ) + + expect(await findByText('Preview')).toBeInTheDocument() + firePrintHotkey() + await flushDeferredPrint() + + 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, queryByText} = render( + + ) + + expect(await findByText('Preview')).toBeInTheDocument() + + firePrintHotkey() + await flushDeferredPrint() + expect(print).not.toHaveBeenCalled() + expect(queryByText('Edit')).not.toBeInTheDocument() + + 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, queryByText} = render( + + ) + + expect(await findByText('Preview')).toBeInTheDocument() + firePrintHotkey() + await flushDeferredPrint() + + expect(print).not.toHaveBeenCalled() + expect(queryByText('Edit')).not.toBeInTheDocument() + }) + + 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() + }) + + 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, queryByText, 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 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, queryByText, rerender} = render( + + ) + + expect(await findByText('Preview')).toBeInTheDocument() + + fireEvent.keyDown(document, {key: 'F8'}) + await flushDeferredPrint() + expect(print).not.toHaveBeenCalled() + expect(queryByText('Edit')).not.toBeInTheDocument() + + rerender( + + ) + + fireEvent.keyDown(document, {key: 'F8'}) + await waitFor(() => expect(print).toHaveBeenCalledOnce()) + }) + + it('remaps print on a mounted designer without disabling hotkeys first', async () => { + const print = vi.spyOn(window, 'print').mockImplementation(() => undefined) + 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() + 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: 'Delete'}) + + await waitFor(() => expect(print).toHaveBeenCalledOnce()) + expect(await findByText('Edit')).toBeInTheDocument() + + 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/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() 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/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') + } + }) +}) 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..860621757 --- /dev/null +++ b/tests/module/tests/resolve-hotkey-bindings.spec.ts @@ -0,0 +1,101 @@ +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, vi} 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}]) + }) + + 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([]) + }) + + 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).' + ) + }) +})