Skip to content
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
.draggableBody {
position: absolute;
inset: 0;
z-index: 7;
z-index: 10;
}

.container:has(.container) > .draggableBody {
pointer-events: none;
}

.uncoverOverflow {
Expand Down Expand Up @@ -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;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
Original file line number Diff line number Diff line change
@@ -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 {
Expand All @@ -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)
Expand All @@ -25,10 +26,50 @@ const AddButton = ({slot, slotCondition}: {slot?: string; slotCondition?: string
)
}, [builderStore, target, slot, slotCondition])

const plusIcon = useMemo(() => <PlusIcon />, [])
// 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<HTMLSpanElement>) => {
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<HTMLSpanElement>) => {
stopEvent(event)
openModal()
},
[openModal]
)

const handleKeyDown = useCallback(
(event: KeyboardEvent<HTMLSpanElement>) => {
if (event.key === 'Enter' || event.key === ' ') {
stopEvent(event)
openModal()
}
},
[openModal]
)

return (
<IconButton onClick={handleClick} icon={plusIcon} color="green" data-testid="add-button" appearance={'primary'} circle size={'xs'} />
<span
role="button"
tabIndex={0}
className={styles.addControl}
onMouseDown={handleMouseDown}
onClick={handleClick}
onKeyDown={handleKeyDown}
data-testid="add-button"
aria-label="Add component"
>
<PlusIcon className={styles.addIcon} />
</span>
)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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]) {
Expand All @@ -38,6 +40,13 @@
.title {
display: inline;
padding-inline-start: 5px;
pointer-events: none;
}

.items,
.actions,
.strip {
pointer-events: none;
}

.items {
Expand All @@ -52,6 +61,13 @@
align-items: center;
}

.hub,
.item,
.actionButton,
.toggle {
pointer-events: auto;
}

.hub {
position: relative;
width: 24px;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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 : <label className={cx(styles.title, className)}>{storeKey}</label>
}
Expand Down Expand Up @@ -250,7 +261,13 @@ const RawToolbar = ({compact, className, anchor}: ToolbarProps) => {
useToolbarPosition(ref, anchor, compact, isRTL, expanded, setExpanded)

return createPortal(
<div ref={ref} className={cx(styles.container, toolbarClassname, className, {[styles.rtl]: isRTL})} {...{[toolbarHostAttr]: ''}}>
<div
ref={ref}
style={toolbarPassThroughStyle}
className={cx(styles.container, toolbarClassname, className, {[styles.rtl]: isRTL})}
onMouseDown={stopMouseDownPropagation}
{...{[toolbarHostAttr]: ''}}
>
<ToolbarItems {...customizationProps}>
<ToolbarTitle {...customizationProps} />
{actions.length > 0 && (
Expand Down
Original file line number Diff line number Diff line change
@@ -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<HTMLElement>()
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
}
Original file line number Diff line number Diff line change
@@ -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
}
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -21,9 +22,10 @@ export const useDragWithPreview = (type: ItemType): [DragState, RefCallback<HTML
() => ({
type,
item,
canDrag: () => canDragOwned(item.key),
collect: monitor => ({isDragging: monitor.isDragging()}),
}),
[]
[item.key]
)

useEffect(() => {
Expand Down
Loading