diff --git a/packages/designer/src/features/dnd/components/Editable/components/Draggable.module.css b/packages/designer/src/features/dnd/components/Editable/components/Draggable.module.css index 39b9fc619..acad46b75 100644 --- a/packages/designer/src/features/dnd/components/Editable/components/Draggable.module.css +++ b/packages/designer/src/features/dnd/components/Editable/components/Draggable.module.css @@ -1,7 +1,11 @@ .draggableBody { position: absolute; inset: 0; - z-index: 7; + z-index: 10; +} + +.container:has(.container) > .draggableBody { + pointer-events: none; } .uncoverOverflow { @@ -69,6 +73,11 @@ transition: padding 200ms ease-in-out; } +/* Nested editables must sit above the parent's drag overlay, same idea as DropView. */ +.container .container { + z-index: 11; +} + .container:global(.isDraggingCurrent) { opacity: 0.4; } diff --git a/packages/designer/src/features/dnd/components/Editable/components/DropView.module.css b/packages/designer/src/features/dnd/components/Editable/components/DropView.module.css index a8eda8d92..23f582a96 100644 --- a/packages/designer/src/features/dnd/components/Editable/components/DropView.module.css +++ b/packages/designer/src/features/dnd/components/Editable/components/DropView.module.css @@ -9,6 +9,39 @@ align-items: center; justify-content: center; outline: 1px solid var(--rs-btn-default-disabled-text); + pointer-events: auto; +} + +.addControl { + display: inline-flex; + align-items: center; + justify-content: center; + flex-shrink: 0; + width: 24px; + height: 24px; + padding: 0; + border: none; + border-radius: 50%; + background-color: var(--rs-green-500, #4caf50); + color: #fff; + cursor: pointer; + line-height: 0; + pointer-events: auto; +} + +.addControl:hover { + background-color: var(--rs-green-700, #22a12a); +} + +.addControl:focus-visible { + outline: 2px solid var(--rs-primary-500, #3498ff); + outline-offset: 2px; +} + +.addControl :global(.rs-icon), +.addIcon { + font-size: 12px; + pointer-events: none; } .innerContainer:global(.isActive) { diff --git a/packages/designer/src/features/dnd/components/Editable/components/DropView.tsx b/packages/designer/src/features/dnd/components/Editable/components/DropView.tsx index 4c9e3d764..325dc5d03 100644 --- a/packages/designer/src/features/dnd/components/Editable/components/DropView.tsx +++ b/packages/designer/src/features/dnd/components/Editable/components/DropView.tsx @@ -1,10 +1,11 @@ import {useComponentData} from '@react-form-builder/core' import {Plus as PlusIcon} from '@rsuite/icons' import cx from 'clsx' -import type {HTMLAttributes} from 'react' -import {forwardRef, useCallback, useMemo} from 'react' -import {IconButton} from 'rsuite' +import type {HTMLAttributes, KeyboardEvent, MouseEvent} from 'react' +import {forwardRef, useCallback} from 'react' import {useBuilderStore} from '../../../../../utils/BuilderStoreContext' +import {stopEvent} from '../../../../../utils/stopEvent' +import {disarmOtherDraggables} from '../disarmDraggableAncestors' import styles from './DropView.module.css' interface DropViewProps { @@ -16,7 +17,7 @@ interface DropViewProps { const AddButton = ({slot, slotCondition}: {slot?: string; slotCondition?: string}) => { const builderStore = useBuilderStore() const target = useComponentData() - const handleClick = useCallback(() => { + const openModal = useCallback(() => { builderStore.showComponentsModal( source => { builderStore.add(source, target, 'inner', slot, slotCondition) @@ -25,10 +26,50 @@ const AddButton = ({slot, slotCondition}: {slot?: string; slotCondition?: string ) }, [builderStore, target, slot, slotCondition]) - const plusIcon = useMemo(() => , []) + // Open on mousedown inside HTML5 drag hosts: the browser cancels click when a drag starts. + // preventDefault suppresses the follow-up click so we do not open twice. + const handleMouseDown = useCallback( + (event: MouseEvent) => { + if (event.button !== 0) return + stopEvent(event) + disarmOtherDraggables(event.currentTarget) + openModal() + }, + [openModal] + ) + + // Programmatic .click() / fireEvent.click does not fire mousedown. + const handleClick = useCallback( + (event: MouseEvent) => { + stopEvent(event) + openModal() + }, + [openModal] + ) + + const handleKeyDown = useCallback( + (event: KeyboardEvent) => { + if (event.key === 'Enter' || event.key === ' ') { + stopEvent(event) + openModal() + } + }, + [openModal] + ) return ( - + + + ) } diff --git a/packages/designer/src/features/dnd/components/Editable/components/Toolbar.module.css b/packages/designer/src/features/dnd/components/Editable/components/Toolbar.module.css index 7ea341066..277297171 100644 --- a/packages/designer/src/features/dnd/components/Editable/components/Toolbar.module.css +++ b/packages/designer/src/features/dnd/components/Editable/components/Toolbar.module.css @@ -12,6 +12,8 @@ font-size: 16px; display: flex; align-items: center; + /* Let select/drag reach nested slot children under the floating chrome. */ + pointer-events: none; } .container:not([data-fe-toolbar-ready]) { @@ -38,6 +40,13 @@ .title { display: inline; padding-inline-start: 5px; + pointer-events: none; +} + +.items, +.actions, +.strip { + pointer-events: none; } .items { @@ -52,6 +61,13 @@ align-items: center; } +.hub, +.item, +.actionButton, +.toggle { + pointer-events: auto; +} + .hub { position: relative; width: 24px; diff --git a/packages/designer/src/features/dnd/components/Editable/components/Toolbar.tsx b/packages/designer/src/features/dnd/components/Editable/components/Toolbar.tsx index 1193fb438..3f59b6042 100644 --- a/packages/designer/src/features/dnd/components/Editable/components/Toolbar.tsx +++ b/packages/designer/src/features/dnd/components/Editable/components/Toolbar.tsx @@ -3,7 +3,7 @@ import {faClone, faTrashAlt as faTrash} from '@fortawesome/free-regular-svg-icon import {faBars, faCrosshairs} from '@fortawesome/free-solid-svg-icons' import {cfDisableComponentRemove, cfDisableToolbarAdd, cfSingleton, useComponentData} from '@react-form-builder/core' import cx from 'clsx' -import type {MouseEventHandler, ReactElement, ReactNode} from 'react' +import type {CSSProperties, MouseEventHandler, ReactElement, ReactNode} from 'react' import {useCallback, useMemo, useRef, useState} from 'react' import {createPortal} from 'react-dom' import {useBuilderStore} from '../../../../../utils/BuilderStoreContext' @@ -54,6 +54,17 @@ interface ToolbarItemProps extends ToolbarProps { const menuIcon = faBars +/** Pass events through chrome so nested slot children under the toolbar stay selectable/draggable. */ +const toolbarPassThroughStyle: CSSProperties = {pointerEvents: 'none'} + +/** + * Keeps toolbar mousedown from React-bubbling to ancestor editables (portaled, still in React tree). + * @param e the mouse event. + */ +const stopMouseDownPropagation: MouseEventHandler = e => { + e.stopPropagation() +} + const RawToolbarTitle = ({compact, storeKey, className}: ToolbarItemProps) => { return compact ? null : } @@ -250,7 +261,13 @@ const RawToolbar = ({compact, className, anchor}: ToolbarProps) => { useToolbarPosition(ref, anchor, compact, isRTL, expanded, setExpanded) return createPortal( -
+
{actions.length > 0 && ( diff --git a/packages/designer/src/features/dnd/components/Editable/disarmDraggableAncestors.ts b/packages/designer/src/features/dnd/components/Editable/disarmDraggableAncestors.ts new file mode 100644 index 000000000..9a869d517 --- /dev/null +++ b/packages/designer/src/features/dnd/components/Editable/disarmDraggableAncestors.ts @@ -0,0 +1,77 @@ +/** + * Temporarily clears `draggable` on every HTML5 drag source except `current` + * (and its descendants) so nested select/drag is not stolen by another wrapper. + * MutationObserver re-applies until dragstart/mouseup/dragend — never a rAF pulse + * (that fought react-dnd reconnects after drop and hung the page). + * @param current the element that should remain the only drag source for this gesture. + * @returns a restore function that re-enables the disarmed elements. + */ +export function disarmOtherDraggables(current: HTMLElement): () => void { + let active = true + let applying = false + const disarmed = new Set() + const testId = current.getAttribute('data-testid') + const refs: {observer?: MutationObserver} = {} + + const liveCurrent = (): HTMLElement | null => { + if (current.isConnected) return current + if (!testId) return null + const next = document.querySelector(`[data-testid="${CSS.escape(testId)}"]`) + return next instanceof HTMLElement ? next : null + } + + const stopObserver = () => { + refs.observer?.disconnect() + refs.observer = undefined + } + + const restore = () => { + if (!active) return + active = false + stopObserver() + for (const el of disarmed) { + if (el.isConnected) el.setAttribute('draggable', 'true') + } + disarmed.clear() + window.removeEventListener('mouseup', restore) + window.removeEventListener('dragend', restore) + window.removeEventListener('dragstart', stopObserver, true) + } + + const apply = () => { + if (!active || applying) return + applying = true + try { + const live = liveCurrent() + if (!live) { + restore() + return + } + if (live.getAttribute('draggable') !== 'true') { + live.setAttribute('draggable', 'true') + } + for (const node of document.querySelectorAll('[draggable="true"]')) { + if (!(node instanceof HTMLElement)) continue + if (node === live || live.contains(node)) continue + if (node.getAttribute('draggable') !== 'false') { + node.setAttribute('draggable', 'false') + } + disarmed.add(node) + } + } finally { + applying = false + } + } + + refs.observer = new MutationObserver(() => { + if (!applying) apply() + }) + refs.observer.observe(document.body, {subtree: true, attributes: true, attributeFilter: ['draggable']}) + + apply() + // Once HTML5 drag owns the gesture, stop observing so drop re-renders cannot thrash. + window.addEventListener('dragstart', stopObserver, {capture: true, once: true}) + window.addEventListener('mouseup', restore) + window.addEventListener('dragend', restore) + return restore +} diff --git a/packages/designer/src/features/dnd/components/Editable/dragOwner.ts b/packages/designer/src/features/dnd/components/Editable/dragOwner.ts new file mode 100644 index 000000000..4e6e358d8 --- /dev/null +++ b/packages/designer/src/features/dnd/components/Editable/dragOwner.ts @@ -0,0 +1,56 @@ +/** + * Nested HTML5 drag sources (e.g. MtCheckbox inside MtButton) compete for dragstart. + * The pressed editable claims ownership so ancestors' canDrag returns false and DOM + * disarm can leave only this key's wrapper draggable. + */ + +let ownerKey: string | null = null +let dragStarted = false +let onDragStarted: (() => void) | null = null + +const onDragStartCapture = () => { + dragStarted = true + onDragStarted?.() + onDragStarted = null +} + +const release = () => { + ownerKey = null + dragStarted = false + onDragStarted = null + window.removeEventListener('mouseup', release) + window.removeEventListener('dragend', release) + window.removeEventListener('dragstart', onDragStartCapture, true) +} + +/** + * Claims exclusive drag ownership for the given editable key until mouseup/dragend. + * @param key the component key that should own the gesture. + * @param whenDragStarts optional callback once HTML5 dragstart fires (e.g. apply deferred selection). + */ +export function claimDragOwner(key: string, whenDragStarts?: () => void): void { + ownerKey = key + dragStarted = false + onDragStarted = whenDragStarts ?? null + window.removeEventListener('mouseup', release) + window.removeEventListener('dragend', release) + window.removeEventListener('dragstart', onDragStartCapture, true) + window.addEventListener('mouseup', release) + window.addEventListener('dragend', release) + window.addEventListener('dragstart', onDragStartCapture, true) +} + +/** + * @param key the component key that wants to drag. + * @returns true when no owner is set or this key owns the gesture. + */ +export function canDragOwned(key: string): boolean { + return ownerKey === null || ownerKey === key +} + +/** + * @returns true if an HTML5 dragstart fired during the current ownership gesture. + */ +export function didDragStart(): boolean { + return dragStarted +} diff --git a/packages/designer/src/features/dnd/components/Editable/hooks/useDragWithPreview.ts b/packages/designer/src/features/dnd/components/Editable/hooks/useDragWithPreview.ts index ec6c4f095..1e0e6ed8e 100644 --- a/packages/designer/src/features/dnd/components/Editable/hooks/useDragWithPreview.ts +++ b/packages/designer/src/features/dnd/components/Editable/hooks/useDragWithPreview.ts @@ -4,6 +4,7 @@ import {useEffect} from 'react' import {useDrag} from 'react-dnd' import {getEmptyImage} from 'react-dnd-html5-backend' import type {ItemType} from '../../../consts' +import {canDragOwned} from '../dragOwner' import {useConnectAsRef} from './useConnectAsRef' interface DragState { @@ -21,9 +22,10 @@ export const useDragWithPreview = (type: ItemType): [DragState, RefCallback ({ type, item, + canDrag: () => canDragOwned(item.key), collect: monitor => ({isDragging: monitor.isDragging()}), }), - [] + [item.key] ) useEffect(() => { diff --git a/packages/designer/src/features/dnd/components/Editable/hooks/useSelection.tsx b/packages/designer/src/features/dnd/components/Editable/hooks/useSelection.tsx index fb4793f0b..ca6e376ab 100644 --- a/packages/designer/src/features/dnd/components/Editable/hooks/useSelection.tsx +++ b/packages/designer/src/features/dnd/components/Editable/hooks/useSelection.tsx @@ -5,6 +5,8 @@ import {useCallback, useMemo, useState} from 'react' import {useDragLayer} from 'react-dnd' import {useBuilderStore} from '../../../../../utils/BuilderStoreContext' import {stopEvent} from '../../../../../utils/stopEvent' +import {disarmOtherDraggables} from '../disarmDraggableAncestors' +import {claimDragOwner, didDragStart} from '../dragOwner' /** * Represents the selection state of the component. @@ -29,6 +31,11 @@ interface SelectionHandlers { * @param e the original mouse event. */ onClick: (e: MouseEvent) => void + /** + * Claims drag ownership / disarms ancestors on mousedown; selects when safe. + * @param e the original mouse event. + */ + onMouseDown: (e: MouseEvent) => void /** * The callback function called when the mouse hits the component area. * @param e the original mouse event. @@ -45,6 +52,37 @@ interface SelectionHandlers { */ type ClassName = string +/** Skip click-select after a mousedown gesture (parent must not steal on mouseup/click). */ +let suppressClickSelect = false + +type PendingSelect = { + select: () => void +} + +let pendingSelect: PendingSelect | null = null + +const gestureWindow = { + /** HTML5 drag skips mouseup; clear flags on dragend so the next click is not swallowed. */ + afterDrag() { + suppressClickSelect = false + pendingSelect = null + gestureWindow.removeListeners() + }, + flushIfIdle() { + const pending = pendingSelect + pendingSelect = null + gestureWindow.removeListeners() + if (!pending) return + // Selecting on mousedown re-renders and races HTML5 dragstart; apply after the gesture if no drag. + // Keep suppressClickSelect so the following click cannot retarget selection to a parent. + if (!didDragStart()) pending.select() + }, + removeListeners() { + window.removeEventListener('mouseup', gestureWindow.flushIfIdle) + window.removeEventListener('dragend', gestureWindow.afterDrag) + }, +} + /** * @returns the array [{@link SelectionState}, {@link SelectionHandlers}, {@link ClassName}] with component selection data. */ @@ -62,7 +100,43 @@ export const useSelection = (): [SelectionState, SelectionHandlers, ClassName] = const onClick = useCallback( (event: MouseEvent) => { stopEvent(event) - store.selectNode(data, event.ctrlKey || event.shiftKey) + if (suppressClickSelect) { + suppressClickSelect = false + gestureWindow.flushIfIdle() + return + } + if (event.ctrlKey || event.shiftKey) return + const target = event.target + if (target instanceof Element && event.currentTarget instanceof Element) { + const nested = target.closest('[data-testid$="-editable-wrapper"]') + if (nested && nested !== event.currentTarget) return + } + store.selectNode(data, false) + }, + [data, store] + ) + + // Disarm + claim ownership on mousedown; defer store selection until click/mouseup/dragstart + // so React re-render cannot re-arm parent drag sources before HTML5 dragstart. + const onMouseDown = useCallback( + (event: MouseEvent) => { + if (event.button !== 0) return + event.stopPropagation() + if (event.currentTarget instanceof HTMLElement) { + disarmOtherDraggables(event.currentTarget) + } + suppressClickSelect = true + const multi = event.ctrlKey || event.shiftKey + const select = () => store.selectNode(data, multi) + pendingSelect = {select} + claimDragOwner(data.key, () => { + // Drag already started — safe to select now. + pendingSelect = null + select() + }) + gestureWindow.removeListeners() + window.addEventListener('mouseup', gestureWindow.flushIfIdle) + window.addEventListener('dragend', gestureWindow.afterDrag) }, [data, store] ) @@ -87,5 +161,5 @@ export const useSelection = (): [SelectionState, SelectionHandlers, ClassName] = [finalHovered, selected, isDragging] ) - return [{hovered: finalHovered, selected}, {onClick, onMouseOver, onMouseOut}, className] + return [{hovered: finalHovered, selected}, {onClick, onMouseDown, onMouseOver, onMouseOut}, className] } diff --git a/packages/views/mantine/src/components/MtButton.tsx b/packages/views/mantine/src/components/MtButton.tsx index 57bd21c97..c93bbdab9 100644 --- a/packages/views/mantine/src/components/MtButton.tsx +++ b/packages/views/mantine/src/components/MtButton.tsx @@ -1,11 +1,27 @@ import type {ButtonProps} from '@mantine/core' import {Button} from '@mantine/core' -import {boolean, define, disabled, event, oneOf, oneOfStrict, string} from '@react-form-builder/core' +import {boolean, define, disabled, event, node, oneOf, oneOfStrict, string, useBuilderMode} from '@react-form-builder/core' import type {ComponentProps, FC} from 'react' import {buttonsCategory} from './internal/categories' import {mantineColor} from './internal/mantineColor' -export const mtButton = define(Button as FC>, 'MtButton') +type MtButtonProps = ButtonProps & ComponentProps<'button'> + +/** + * Renders as a div in the designer so section dropzones stay clickable and droppable. + * Nested interactive designer chrome inside a real button is ignored by browsers. + * @param props the Mantine button props. + * @returns the button element. + */ +const MtButton = (props: MtButtonProps) => { + const mode = useBuilderMode() + if (mode === 'builder') { + return + ) +} + +const buttonHost = define(ButtonHost, 'ButtonHost') + .category('test') + .name('Button host') + .props({ + children: string.default('Host'), + leftSection: node, + }) + +const components = [...rSuiteComponents, buttonHost].map(d => d.build()) +const view = new BuilderView(components) + +const overlayOf = (wrapper: HTMLElement): HTMLElement => { + const overlay = wrapper.querySelector(':scope > [data-fe-drag-overlay]') + if (!(overlay instanceof HTMLElement)) throw new Error('Expected a drag overlay') + return overlay +} + +describe('node picker inside button host', () => { + it('renders a non-button add control so the host stays valid HTML', async () => { + const getForm = () => JSON.stringify(emptySectionForm) + const {findByTestId, findByRole} = render() + + const host = await findByTestId('button-host') + expect(host.tagName).toBe('BUTTON') + + const dropzone = await within(host).findByTestId('inner-dropzone') + const addControl = await within(dropzone).findByTestId('add-button') + + // Host is still a real