Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(files): support dragging into starred folders (#110704)

Marius Andradf1f461c1bea
diff --git a/frontend/src/layout/panel-layout/ProjectTree/ProjectTree.tsx b/frontend/src/layout/panel-layout/ProjectTree/ProjectTree.tsx
index 31c4ad1ff2f9..8c9617b0f7ee 100644
--- a/frontend/src/layout/panel-layout/ProjectTree/ProjectTree.tsx
+++ b/frontend/src/layout/panel-layout/ProjectTree/ProjectTree.tsx
@@ -46,7 +46,7 @@ import { projectTreeLogic } from './projectTreeLogic'
import { TreeFiltersDropdownMenu } from './TreeFiltersDropdownMenu'
import { TreeSearchField } from './TreeSearchField'
import { TreeSortMenuItems } from './TreeSortMenuItems'
-import { calculateMovePath } from './utils'
+import { calculateMovePath, resolveProjectTreeDrop } from './utils'
interface ProjectTreeBaseProps {
layout?: 'panel' | 'inline'
@@ -56,6 +56,7 @@ interface ProjectTreeBaseProps {
logicKey?: string // key override?
root?: string
shortcutScope?: 'products' | 'files'
+ shareDragAndDropContext?: boolean
showRecents?: boolean // whether to show recents in the tree
searchPlaceholder?: string
treeSize?: LemonTreeSize
@@ -141,8 +142,9 @@ export function ProjectTree(props: ProjectTreeProps): JSX.Element {
isActiveInPanel,
} = props
const [uniqueKey] = useState(() => `project-tree-${counter++}`)
- const { viableItems, shortcutEntryIdMap, currentHomeFolder } = useValues(projectTreeDataLogic)
- const { reorderShortcutByDrag, setStarredNavigationRef } = useActions(projectTreeDataLogic)
+ const { viableItems, shortcutData, shortcutEntryIdMap, currentHomeFolder } = useValues(projectTreeDataLogic)
+ const { addShortcutItem, moveShortcutToFolder, reorderShortcutByDrag, setStarredNavigationRef } =
+ useActions(projectTreeDataLogic)
const projectTreeLogicProps = { key: logicKey ?? uniqueKey, root, shortcutScope, isActiveInPanel }
const {
fullFileSystemFiltered,
@@ -337,40 +339,37 @@ export function ProjectTree(props: ProjectTreeProps): JSX.Element {
expandedItemIds={searchTerm ? expandedSearchFolders : expandedFolders}
onSetExpandedItemIds={searchTerm ? setExpandedSearchFolders : setExpandedFolders}
enableDragAndDrop={!sortMethod || sortMethod === 'folder'}
+ dragAndDropScope={props.shareDragAndDropContext ? (logicKey ?? uniqueKey) : undefined}
+ rootDropId={root === 'shortcuts://' ? 'shortcuts://' : ''}
onDragEnd={(dragEvent) => {
- const itemToId = (item: FileSystemEntry): string =>
- item.type === 'folder' ? 'project://' + item.path : 'project/' + item.id
- const oldId = dragEvent.active.id as string
- const newId = dragEvent.over?.id
- if (oldId === newId) {
- return false
+ const oldId = String(dragEvent.active.id)
+ const drop = resolveProjectTreeDrop(
+ oldId,
+ dragEvent.over ? String(dragEvent.over.id) : null,
+ searchTerm && searchResults.results ? [...searchResults.results, ...viableItems] : viableItems,
+ shortcutData,
+ dragEvent.position
+ )
+ if (!drop) {
+ return
}
-
- // Sibling reorder within the Starred (shortcuts://) list. All the index/position
- // math lives in the kea logic so the component can stay focused on rendering.
- if (
- typeof oldId === 'string' &&
- typeof newId === 'string' &&
- shortcutEntryIdMap.has(oldId) &&
- shortcutEntryIdMap.has(newId)
- ) {
- const position = dragEvent.position === 'after' ? 'after' : 'before'
- reorderShortcutByDrag(oldId, newId, position)
+ if (drop.type === 'reorder') {
+ reorderShortcutByDrag(
+ drop.activeId,
+ drop.overId,
+ dragEvent.position === 'after' ? 'after' : 'before'
+ )
return
}
-
- const items = searchTerm && searchResults.results ? searchResults.results : viableItems
- const oldItem = items.find((i) => itemToId(i) === oldId)
- const newItem = items.find((i) => itemToId(i) === newId)
- if (oldItem === newItem || !oldItem) {
- return false
+ if (drop.type === 'move-shortcut') {
+ moveShortcutToFolder(drop.item, drop.folder, logicKey ?? uniqueKey)
+ return
}
-
- const folder = newItem
- ? newItem.path || ''
- : newId && String(newId).startsWith('project://')
- ? String(newId).substring(10)
- : ''
+ if (drop.type === 'star') {
+ addShortcutItem(drop.item)
+ return
+ }
+ const { item: oldItem, folder } = drop
if (checkedItems[oldId]) {
moveCheckedItems(folder)
@@ -392,7 +391,15 @@ export function ProjectTree(props: ProjectTreeProps): JSX.Element {
}
return (item.id.startsWith('project/') || item.id.startsWith('project://')) && item.record?.path
}}
- getItemDropMode={(item) => (shortcutEntryIdMap.has(item.id) ? 'reorder' : 'onto')}
+ getItemDropMode={(item, activeId) =>
+ shortcutEntryIdMap.has(item.id)
+ ? item.record?.type === 'folder'
+ ? 'onto-or-reorder'
+ : activeId && shortcutEntryIdMap.has(activeId)
+ ? 'reorder'
+ : 'onto'
+ : 'onto'
+ }
isItemDroppable={(item) => {
const path = item.record?.path || ''
diff --git a/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.test.ts b/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.test.ts
index eed67ee8e01c..0e5a28cc7904 100644
--- a/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.test.ts
+++ b/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.test.ts
@@ -390,6 +390,34 @@ describe('projectTreeDataLogic', () => {
})
})
+ it.each(['notebook', 'folder'])(
+ 'moves the underlying %s from a shortcut even when its parent has not been loaded',
+ async (type) => {
+ const item = { id: 'real-file', type, ref: 'notes-ref', path: 'Research/Notes' }
+ const shortcut = {
+ id: 'star-note',
+ type,
+ path: 'Pinned notes',
+ ref: type === 'folder' ? item.path : item.ref,
+ }
+ const move = jest.spyOn(api.fileSystem, 'move').mockResolvedValue({ ...item, path: 'Users/Alex/Notes' })
+ const createShortcut = jest.spyOn(api.fileSystemShortcuts, 'create')
+ jest.spyOn(api.fileSystem, 'count').mockResolvedValue({ count: 1, entries: [item], has_more: false })
+ jest.mocked(api.fileSystem.list).mockResolvedValue({ count: 1, results: [item], users: [] })
+
+ await expectLogic(logic, () => {
+ logic.actions.moveShortcutToFolder(shortcut, 'Users/Alex', 'test')
+ }).toFinishAllListeners()
+
+ expect(api.fileSystem.list).toHaveBeenCalledWith(
+ type === 'folder' ? { type: 'folder', path: 'Research/Notes' } : { type: 'notebook', ref: 'notes-ref' }
+ )
+ expect(move).toHaveBeenCalledWith('real-file', 'Users/Alex/Notes')
+ expect(createShortcut).not.toHaveBeenCalled()
+ expect(logic.values.viableItems).toContainEqual({ ...item, path: 'Users/Alex/Notes' })
+ }
+ )
+
it('reports a bulk move once, with an undo that reverts every item', async () => {
const success = jest.spyOn(lemonToast, 'success').mockReturnValue('' as any)
const move = jest.spyOn(api.fileSystem, 'move').mockResolvedValue({} as any)
diff --git a/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.tsx b/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.tsx
index 845cf1a8189a..2c0bb2afe330 100644
--- a/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.tsx
+++ b/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.tsx
@@ -36,6 +36,7 @@ import { RecentResults, SearchResults, projectTreeLogic } from '~/layout/panel-l
import { FolderState, ProjectTreeAction } from '~/layout/panel-layout/ProjectTree/types'
import {
appendResultsToFolders,
+ calculateMovePath,
convertFileSystemEntryToTreeDataItem,
escapePath,
formatUrlAsName,
@@ -477,6 +478,15 @@ export interface projectTreeDataLogicActions {
}[]
projectTreeLogicKey: string
}
+ moveShortcutToFolder: (
+ shortcut: FileSystemEntry,
+ folder: string,
+ projectTreeLogicKey: string
+ ) => {
+ folder: string
+ projectTreeLogicKey: string
+ shortcut: FileSystemEntry
+ }
movedItem: (
item: FileSystemEntry,
oldPath: string,
@@ -696,6 +706,11 @@ export const projectTreeDataLogic = kea<projectTreeDataLogicType>([
force,
projectTreeLogicKey,
}),
+ moveShortcutToFolder: (shortcut: FileSystemEntry, folder: string, projectTreeLogicKey: string) => ({
+ shortcut,
+ folder,
+ projectTreeLogicKey,
+ }),
// Prefer this over looping `moveItem`, which would report each move separately (see MoveBatch).
moveItems: (
moves: { item: FileSystemEntry; newPath: string }[],
@@ -1900,6 +1915,33 @@ export const projectTreeDataLogic = kea<projectTreeDataLogicType>([
projectTreeLogicKey
)
},
+ moveShortcutToFolder: async ({ shortcut, folder, projectTreeLogicKey }) => {
+ const { ref, type } = shortcut
+ if (!ref || !type) {
+ return
+ }
+ try {
+ const response = await api.fileSystem.list(
+ type === 'folder' ? { type: 'folder', path: ref } : { ...refTypeParams(type), ref }
+ )
+ const item = response.results.find((entry) =>
+ type === 'folder'
+ ? entry.type === 'folder' && entry.path === ref
+ : matchesRefType(entry.type, type) && entry.ref === ref
+ )
+ if (!item) {
+ lemonToast.error('Could not find the starred item. Refresh the page and try again.')
+ return
+ }
+ const { newPath, isValidMove } = calculateMovePath(item, folder)
+ if (isValidMove) {
+ actions.createSavedItem(item)
+ actions.moveItem(item, newPath, false, projectTreeLogicKey)
+ }
+ } catch {
+ lemonToast.error('Could not load the starred item. Try again.')
+ }
+ },
moveItem: ({ item, newPath, force, projectTreeLogicKey }) => {
actions.moveItems([{ item, newPath }], force, projectTreeLogicKey)
},
diff --git a/frontend/src/layout/panel-layout/ProjectTree/utils.test.ts b/frontend/src/layout/panel-layout/ProjectTree/utils.test.ts
index 5a640cca9a65..1012ea6c85fc 100644
--- a/frontend/src/layout/panel-layout/ProjectTree/utils.test.ts
+++ b/frontend/src/layout/panel-layout/ProjectTree/utils.test.ts
@@ -11,6 +11,7 @@ import {
joinPath,
matchesRefType,
reparentPath,
+ resolveProjectTreeDrop,
splitPath,
} from './utils'
@@ -19,6 +20,86 @@ const catalogProducts = [...getDefaultTreeProducts(), ...getDefaultTreeData()].f
)
describe('project tree utils', () => {
+ describe('resolveProjectTreeDrop', () => {
+ const note: FileSystemEntry = { id: 'note', type: 'notebook', ref: 'note-ref', path: 'Research/Notes' }
+ const folder: FileSystemEntry = { id: 'folder', type: 'folder', path: 'Research' }
+ const shortcuts: FileSystemEntry[] = [
+ { id: 'home', type: 'folder', path: 'My home', ref: 'Users/Alex' },
+ { id: 'overview', type: 'dashboard', path: 'Overview', ref: 'overview-ref' },
+ ]
+
+ it.each([
+ ['shortcuts://My home', 'Users/Alex'],
+ ['project://Research', 'Research'],
+ ['project://', ''],
+ ['', ''],
+ ])('resolves a drop on %s to its real folder', (overId, destination) => {
+ expect(resolveProjectTreeDrop('project/note', overId, [note, folder], shortcuts)).toEqual({
+ type: 'move',
+ item: note,
+ folder: destination,
+ })
+ })
+
+ it.each([
+ ['shortcuts://', 'onto'],
+ ['shortcuts/overview', 'onto'],
+ ['shortcuts://My home', 'before'],
+ ['shortcuts://My home', 'after'],
+ ] as const)('stars a nested file dropped on %s (%s) without moving it', (overId, position) => {
+ expect(resolveProjectTreeDrop('project/note', overId, [note], shortcuts, position)).toEqual({
+ type: 'star',
+ item: note,
+ })
+ expect(
+ resolveProjectTreeDrop(
+ 'project/note',
+ overId,
+ [note],
+ [...shortcuts, { id: 'star-note', type: 'notebook', ref: 'note-ref', path: 'Notes' }],
+ position
+ )
+ ).toBeNull()
+ })
+
+ it.each([null, 'missing', 'shortcuts/missing', 'project/note', 'project://missing'])(
+ 'does not move a file to the project root for an invalid target %s',
+ (overId) => {
+ expect(resolveProjectTreeDrop('project/note', overId, [note], shortcuts)).toBeNull()
+ }
+ )
+
+ it.each(['project/note', 'shortcuts/star-note'])(
+ 'moves %s into a starred folder without adding a shortcut',
+ (activeId) => {
+ const starredNote = { id: 'star-note', type: 'notebook', ref: 'note-ref', path: 'Notes' }
+ expect(
+ resolveProjectTreeDrop(activeId, 'shortcuts://My home', [note], [...shortcuts, starredNote], 'onto')
+ ).toEqual({
+ type: activeId.startsWith('shortcuts/') ? 'move-shortcut' : 'move',
+ item: activeId.startsWith('shortcuts/') ? starredNote : note,
+ folder: 'Users/Alex',
+ })
+ expect(resolveProjectTreeDrop(activeId, 'shortcuts://', [note], [...shortcuts, starredNote])).toBeNull()
+ }
+ )
+
+ it('reorders starred folders without moving their contents', () => {
+ expect(
+ resolveProjectTreeDrop('shortcuts/overview', 'shortcuts://My home', [], shortcuts, 'before')
+ ).toEqual({
+ type: 'reorder',
+ activeId: 'shortcuts/overview',
+ overId: 'shortcuts://My home',
+ })
+ expect(resolveProjectTreeDrop('shortcuts://My home', 'project://Research', [folder], shortcuts)).toEqual({
+ type: 'move-shortcut',
+ item: shortcuts[0],
+ folder: 'Research',
+ })
+ })
+ })
+
describe('escapePath', () => {
it('escapes paths as expected', () => {
expect(escapePath('a/b')).toEqual('a\\/b')
diff --git a/frontend/src/layout/panel-layout/ProjectTree/utils.tsx b/frontend/src/layout/panel-layout/ProjectTree/utils.tsx
index 605ebca2d416..fd7edb209ffe 100644
--- a/frontend/src/layout/panel-layout/ProjectTree/utils.tsx
+++ b/frontend/src/layout/panel-layout/ProjectTree/utils.tsx
@@ -61,6 +61,59 @@ export function getItemId(item: FileSystemImport | FileSystemEntry, protocol = '
return item.type === 'folder' ? `${root}://${item.path}` : `${root}/${item.id || item.path}`
}
+type ProjectTreeDrop =
+ | { type: 'reorder'; activeId: string; overId: string }
+ | { type: 'star'; item: FileSystemEntry }
+ | { type: 'move'; item: FileSystemEntry; folder: string }
+ | { type: 'move-shortcut'; item: FileSystemEntry; folder: string }
+
+export function resolveProjectTreeDrop(
+ activeId: string,
+ overId: string | null,
+ items: FileSystemEntry[],
+ shortcuts: FileSystemEntry[],
+ position: 'onto' | 'before' | 'after' = 'onto'
+): ProjectTreeDrop | null {
+ if (overId === null || activeId === overId) {
+ return null
+ }
+ const activeShortcut = shortcuts.find((item) => getItemId(item, 'shortcuts://') === activeId)
+ const overShortcut = shortcuts.find((item) => getItemId(item, 'shortcuts://') === overId)
+ const item = activeShortcut ?? items.find((entry) => getItemId(entry) === activeId)
+ if (!item) {
+ return null
+ }
+ if (overShortcut?.type === 'folder' && position === 'onto') {
+ // A shortcut's path is its label; ref points to the real folder, including unloaded home folders.
+ return overShortcut.ref && (!activeShortcut || activeShortcut.ref)
+ ? { type: activeShortcut ? 'move-shortcut' : 'move', item, folder: overShortcut.ref }
+ : null
+ }
+ const folder =
+ overId === '' || overId === 'project://'
+ ? ''
+ : items.find((entry) => entry.type === 'folder' && getItemId(entry) === overId)?.path
+ if (folder !== undefined) {
+ return !activeShortcut || activeShortcut.ref
+ ? { type: activeShortcut ? 'move-shortcut' : 'move', item, folder }
+ : null
+ }
+ if (activeShortcut) {
+ return overShortcut ? { type: 'reorder', activeId, overId } : null
+ }
+ if (overShortcut || overId === 'shortcuts://') {
+ const shortcut = shortcutFromEntry(item)
+ return shortcuts.some(
+ (entry) =>
+ entry.type === shortcut.type &&
+ (shortcut.ref ? entry.ref === shortcut.ref : entry.href === shortcut.href)
+ )
+ ? null
+ : { type: 'star', item }
+ }
+ return null
+}
+
export function protocolTitle(str: string): string {
return (str.charAt(0).toUpperCase() + str.slice(1)).replaceAll('-', ' ')
}
diff --git a/frontend/src/layout/panel-layout/navbar/tabs/NavTabFiles.tsx b/frontend/src/layout/panel-layout/navbar/tabs/NavTabFiles.tsx
index ac4ab46121ed..de1f50c83ae6 100644
--- a/frontend/src/layout/panel-layout/navbar/tabs/NavTabFiles.tsx
+++ b/frontend/src/layout/panel-layout/navbar/tabs/NavTabFiles.tsx
@@ -1,8 +1,10 @@
+import { DndContext, MouseSensor, TouchSensor, useSensor, useSensors } from '@dnd-kit/core'
import { useActions, useValues } from 'kea'
import { Spinner } from '@posthog/lemon-ui'
import { ScrollableShadows } from 'lib/components/ScrollableShadows/ScrollableShadows'
+import { TreeNodeDroppable } from 'lib/lemon-ui/LemonTree/LemonTreeUtils'
import { panelLayoutLogic } from '../../panelLayoutLogic'
import { ProjectTree } from '../../ProjectTree/ProjectTree'
@@ -15,6 +17,10 @@ import { navRecentsLogic } from './navRecentsLogic'
import { NavTabSection } from './NavTabSection'
export function NavTabFiles(): JSX.Element {
+ const sensors = useSensors(
+ useSensor(MouseSensor, { activationConstraint: { distance: 10 } }),
+ useSensor(TouchSensor, { activationConstraint: { delay: 250, tolerance: 5 } })
+ )
const { navExperimentActiveTab } = useValues(panelLayoutLogic)
const { shortcutDataHasLoaded } = useValues(projectTreeDataLogic)
const { searchTerm, folderRevealCount } = useValues(navFilesTabLogic)
@@ -26,72 +32,81 @@ export function NavTabFiles(): JSX.Element {
const showStarred = !searchTerm.trim() || !shortcutDataHasLoaded || starredFiles.length > 0
return (
- <div
- className="flex flex-col h-full min-h-0 group/colorful-product-icons colorful-product-icons-true"
- data-attr="nav-panel-files"
- >
- <ScrollableShadows
- direction="vertical"
- className="flex-1 min-h-0"
- innerClassName="relative px-1"
- styledScrollbars
+ <DndContext sensors={sensors}>
+ <div
+ className="flex flex-col h-full min-h-0 group/colorful-product-icons colorful-product-icons-true"
+ data-attr="nav-panel-files"
>
- <div className="absolute top-0 right-1 z-10">
- <NavFilesMenu />
- </div>
- {showStarred && (
- <div className="pb-2">
- <NavTabSection
- label="Starred"
- dataAttr="nav-files-starred-toggle"
- key={`starred-${!!searchTerm.trim()}`}
- actions={<span className="size-6.5 shrink-0" aria-hidden />}
- >
- {!shortcutDataHasLoaded ? (
- <Spinner className="m-2" />
- ) : starredFiles.length > 0 ? (
- <ProjectTree
- root="shortcuts://"
- shortcutScope="files"
- logicKey={FILES_STARRED_TREE_KEY}
- onlyTree
- showShortcutHelp={false}
- />
- ) : (
- <p className="text-xs text-tertiary px-2 py-1 mb-0">
- Star files or folders to keep them here.
- </p>
- )}
- </NavTabSection>
+ <ScrollableShadows
+ direction="vertical"
+ className="flex-1 min-h-0"
+ innerClassName="relative px-1"
+ styledScrollbars
+ >
+ <div className="absolute top-0 right-1 z-10">
+ <NavFilesMenu />
</div>
- )}
- {/* Recents list what you viewed, not what matches the search, so a search hides them. */}
- {!searchTerm.trim() && (
- <div className="pb-2">
- <NavTabSection
- label="Recents"
- dataAttr="nav-recents-toggle"
- open={!recentsCollapsed}
- onOpenChange={(open) => setRecentsCollapsed(!open)}
+ {showStarred && (
+ <TreeNodeDroppable
+ id="shortcuts://"
+ scope={`${FILES_STARRED_TREE_KEY}-section`}
+ isDroppable
+ className="pb-2"
>
- <NavRecentItems />
- </NavTabSection>
- </div>
- )}
- <NavTabSection
- label="Files"
- dataAttr="nav-files-project-toggle"
- key={`files-${!!searchTerm.trim()}-${folderRevealCount}`}
- actions={!showStarred && <span className="size-6.5 shrink-0" aria-hidden />}
- >
- <ProjectTree
- root="project://"
- logicKey={FILES_TREE_KEY}
- onlyTree
- isActiveInPanel={navExperimentActiveTab === 'files'}
- />
- </NavTabSection>
- </ScrollableShadows>
- </div>
+ <NavTabSection
+ label="Starred"
+ dataAttr="nav-files-starred-toggle"
+ key={`starred-${!!searchTerm.trim()}`}
+ actions={<span className="size-6.5 shrink-0" aria-hidden />}
+ >
+ {!shortcutDataHasLoaded ? (
+ <Spinner className="m-2" />
+ ) : starredFiles.length > 0 ? (
+ <ProjectTree
+ root="shortcuts://"
+ shortcutScope="files"
+ logicKey={FILES_STARRED_TREE_KEY}
+ shareDragAndDropContext
+ onlyTree
+ showShortcutHelp={false}
+ />
+ ) : (
+ <p className="text-xs text-tertiary px-2 py-1 mb-0">
+ Star files or folders to keep them here.
+ </p>
+ )}
+ </NavTabSection>
+ </TreeNodeDroppable>
+ )}
+ {/* Recents list what you viewed, not what matches the search, so a search hides them. */}
+ {!searchTerm.trim() && (
+ <div className="pb-2">
+ <NavTabSection
+ label="Recents"
+ dataAttr="nav-recents-toggle"
+ open={!recentsCollapsed}
+ onOpenChange={(open) => setRecentsCollapsed(!open)}
+ >
+ <NavRecentItems />
+ </NavTabSection>
+ </div>
+ )}
+ <NavTabSection
+ label="Files"
+ dataAttr="nav-files-project-toggle"
+ key={`files-${!!searchTerm.trim()}-${folderRevealCount}`}
+ actions={!showStarred && <span className="size-6.5 shrink-0" aria-hidden />}
+ >
+ <ProjectTree
+ root="project://"
+ logicKey={FILES_TREE_KEY}
+ shareDragAndDropContext
+ onlyTree
+ isActiveInPanel={navExperimentActiveTab === 'files'}
+ />
+ </NavTabSection>
+ </ScrollableShadows>
+ </div>
+ </DndContext>
)
}
diff --git a/frontend/src/lib/lemon-ui/LemonTree/LemonTree.tsx b/frontend/src/lib/lemon-ui/LemonTree/LemonTree.tsx
index ffeddadab49a..cc4023f3e5b9 100644
--- a/frontend/src/lib/lemon-ui/LemonTree/LemonTree.tsx
+++ b/frontend/src/lib/lemon-ui/LemonTree/LemonTree.tsx
@@ -6,6 +6,7 @@ import {
DragStartEvent,
MouseSensor,
TouchSensor,
+ useDndContext,
useSensor,
useSensors,
} from '@dnd-kit/core'
@@ -35,6 +36,7 @@ import { ContextMenu, ContextMenuContent, ContextMenuTrigger } from '../../ui/Co
import { SideAction } from '../LemonButton'
import { Link } from '../Link/Link'
import { Spinner } from '../Spinner/Spinner'
+import { LemonTreeDndMonitor } from './LemonTreeDndMonitor'
import {
InlineEditField,
TreeDropPosition,
@@ -107,6 +109,9 @@ type LemonTreeBaseProps = Omit<
showFolderActiveState?: boolean
/** Whether to enable drag and drop of items. */
enableDragAndDrop?: boolean
+ /** Share a parent DndContext; the scope keeps duplicate rows in sibling trees distinct. */
+ dragAndDropScope?: string
+ rootDropId?: string
/** The select mode of the tree. */
selectMode?: LemonTreeSelectMode
/** Whether the item is active, useful for highlighting the current item against a URL path,
@@ -118,8 +123,9 @@ type LemonTreeBaseProps = Omit<
isItemDroppable?: (item: TreeDataItem) => boolean
/** Drop mode for the item when used as a drop target. 'reorder' renders an insertion
* line above or below the row based on pointer position. 'onto' (default) highlights
- * the whole row — appropriate for dropping *into* folders. */
- getItemDropMode?: (item: TreeDataItem) => 'onto' | 'reorder'
+ * the whole row — appropriate for dropping *into* folders. 'onto-or-reorder' reserves
+ * the middle half for folder drops and the edges for inserting siblings. */
+ getItemDropMode?: (item: TreeDataItem, activeId?: string) => 'onto' | 'reorder' | 'onto-or-reorder'
/** The side action to render for the item. */
itemSideAction?: (item: TreeDataItem) => React.ReactNode | undefined
/** The button to render for the item's side action. */
@@ -274,6 +280,7 @@ const LemonTreeItemRow = forwardRef<HTMLDivElement, LemonTreeItemRowProps>(
isItemDraggable,
isItemDroppable,
getItemDropMode,
+ dragAndDropScope,
onReorderPositionChange,
depth = 0,
itemSideAction,
@@ -293,6 +300,8 @@ const LemonTreeItemRow = forwardRef<HTMLDivElement, LemonTreeItemRowProps>(
},
ref
): JSX.Element => {
+ const { active } = useDndContext()
+ const activeId = active ? String(active.data.current?.treeId ?? active.id) : undefined
const DEPTH_OFFSET = 16 * depth
const [isContextMenuOpenForItem, setIsContextMenuOpenForItem] = useState<string | undefined>(undefined)
@@ -468,7 +477,12 @@ const LemonTreeItemRow = forwardRef<HTMLDivElement, LemonTreeItemRowProps>(
if (enableDragAndDrop && isItemDraggable?.(item) && item.id) {
button = (
- <TreeNodeDraggable id={item.id} enableDragging className="h-[var(--lemon-tree-button-height)]">
+ <TreeNodeDraggable
+ id={item.id}
+ scope={dragAndDropScope}
+ enableDragging
+ className="h-[var(--lemon-tree-button-height)]"
+ >
{button}
</TreeNodeDraggable>
)
@@ -508,85 +522,76 @@ const LemonTreeItemRow = forwardRef<HTMLDivElement, LemonTreeItemRowProps>(
)
) : null
- const content = (
- <AccordionPrimitive.Item
- value={item.id}
- disabled={!!item.disabledReason}
- className="flex flex-col w-full gap-y-px"
+ let row = (
+ <AccordionPrimitive.Trigger
+ className={cn('flex items-center gap-2 w-full', isEmptyFolder ? 'h-auto' : 'h-8')}
+ asChild
>
- <AccordionPrimitive.Trigger
- className={cn('flex items-center gap-2 w-full', isEmptyFolder ? 'h-auto' : 'h-8')}
- asChild
+ <ButtonGroupPrimitive
+ fullWidth
+ className={cn(
+ 'group/lemon-tree-button-group relative bg-transparent',
+ isEmptyFolder ? 'h-auto' : 'h-[var(--lemon-tree-button-height)]',
+ className
+ )}
>
- <ButtonGroupPrimitive
- fullWidth
- className={cn(
- 'group/lemon-tree-button-group relative bg-transparent',
- isEmptyFolder ? 'h-auto' : 'h-[var(--lemon-tree-button-height)]',
- className
- )}
- >
- <TreeNodeDisplayCheckbox
- item={item}
- handleCheckedChange={(checked, shift) => {
- onItemChecked?.(item.id, checked, shift)
+ <TreeNodeDisplayCheckbox
+ item={item}
+ handleCheckedChange={(checked, shift) => {
+ onItemChecked?.(item.id, checked, shift)
+ }}
+ className={cn('absolute z-2', {
+ hidden: selectMode !== 'multi',
+ })}
+ style={{
+ left: `${firstColumnOffset - 20}px`,
+ }}
+ />
+
+ {isItemEditing?.(item) ? (
+ <InlineEditField
+ value={item.name}
+ handleSubmit={(value) => {
+ onItemNameChange?.(item, value)
+ disableKeyboardInput?.(false)
}}
- className={cn('absolute z-2', {
- hidden: selectMode !== 'multi',
- })}
+ className="z-1"
style={{
- left: `${firstColumnOffset - 20}px`,
+ width:
+ selectMode === 'multi' && !item.disableSelect
+ ? `${emptySpaceOffset + 26}px`
+ : `${emptySpaceOffset}px`,
}}
- />
-
- {isItemEditing?.(item) ? (
- <InlineEditField
- value={item.name}
- handleSubmit={(value) => {
- onItemNameChange?.(item, value)
- disableKeyboardInput?.(false)
- }}
- className="z-1"
- style={{
- width:
- selectMode === 'multi' && !item.disableSelect
- ? `${emptySpaceOffset + 26}px`
- : `${emptySpaceOffset}px`,
- }}
- >
- {renderItemIcon ? (
- renderItemIcon?.(item)
- ) : (
- <TreeNodeDisplayIcon
- item={item}
- expandedItemIds={expandedItemIds ?? []}
- defaultNodeIcon={defaultNodeIcon}
- />
- )}
- </InlineEditField>
- ) : (
- button
- )}
-
- {sideAction}
- </ButtonGroupPrimitive>
- </AccordionPrimitive.Trigger>
+ >
+ {renderItemIcon ? (
+ renderItemIcon?.(item)
+ ) : (
+ <TreeNodeDisplayIcon
+ item={item}
+ expandedItemIds={expandedItemIds ?? []}
+ defaultNodeIcon={defaultNodeIcon}
+ />
+ )}
+ </InlineEditField>
+ ) : (
+ button
+ )}
- {childrenContent}
- </AccordionPrimitive.Item>
+ {sideAction}
+ </ButtonGroupPrimitive>
+ </AccordionPrimitive.Trigger>
)
- let wrappedContent = content
-
if (isItemDroppable?.(item)) {
- wrappedContent = (
+ row = (
<TreeNodeDroppable
id={item.id}
+ scope={dragAndDropScope}
isDroppable={!!isItemDroppable?.(item)}
- dropMode={getItemDropMode?.(item) ?? 'onto'}
+ dropMode={getItemDropMode?.(item, activeId) ?? 'onto'}
onPositionChange={onReorderPositionChange}
>
- {wrappedContent}
+ {row}
</TreeNodeDroppable>
)
}
@@ -605,7 +610,14 @@ const LemonTreeItemRow = forwardRef<HTMLDivElement, LemonTreeItemRowProps>(
: undefined
}
>
- {wrappedContent}
+ <AccordionPrimitive.Item
+ value={item.id}
+ disabled={!!item.disabledReason}
+ className="flex flex-col w-full gap-y-px"
+ >
+ {row}
+ {childrenContent}
+ </AccordionPrimitive.Item>
</div>
)
}
@@ -695,6 +707,7 @@ const LemonTree = forwardRef<LemonTreeRef, LemonTreeProps>(
isItemDraggable,
isItemDroppable,
getItemDropMode,
+ dragAndDropScope,
itemSideAction,
isItemEditing,
onItemNameChange,
@@ -711,6 +724,7 @@ const LemonTree = forwardRef<LemonTreeRef, LemonTreeProps>(
virtualizedRowHeight = 31,
virtualizedOverscan = 20,
virtualizationScrollContainerRef,
+ rootDropId = '',
...props
},
ref: ForwardedRef<LemonTreeRef>
@@ -1578,8 +1592,11 @@ const LemonTree = forwardRef<LemonTreeRef, LemonTreeProps>(
return undefined
}
+ const DragContext = dragAndDropScope ? LemonTreeDndMonitor : DndContext
+
return (
- <DndContext
+ <DragContext
+ scope={dragAndDropScope ?? ''}
sensors={sensors}
onDragStart={(event) => {
setIsDragging(true)
@@ -1600,8 +1617,14 @@ const LemonTree = forwardRef<LemonTreeRef, LemonTreeProps>(
dragEvent.activatorEvent.stopPropagation()
} else {
const overItem = over ? findItem(data, String(over)) : undefined
- const overMode = overItem ? (getItemDropMode?.(overItem) ?? 'onto') : 'onto'
- const position: TreeDropPosition = overMode === 'reorder' ? dropPositionRef.current : 'onto'
+ const overMode =
+ dragEvent.over?.data.current?.dropMode ??
+ (overItem ? (getItemDropMode?.(overItem, String(active)) ?? 'onto') : 'onto')
+ const position: TreeDropPosition =
+ overMode !== 'onto'
+ ? (dragEvent.over?.data.current?.position ??
+ (overMode === 'onto-or-reorder' ? 'onto' : dropPositionRef.current))
+ : 'onto'
onDragEnd?.(Object.assign(dragEvent, { position }))
}
dropPositionRef.current = 'onto'
@@ -1643,7 +1666,13 @@ const LemonTree = forwardRef<LemonTreeRef, LemonTreeProps>(
} as CSSProperties
}
>
- <TreeNodeDroppable id="" isDroppable={enableDragAndDrop} isRoot isDragging={isDragging}>
+ <TreeNodeDroppable
+ id={rootDropId}
+ scope={dragAndDropScope}
+ isDroppable={enableDragAndDrop}
+ isRoot
+ isDragging={isDragging}
+ >
<div ref={virtualizationAnchorRef}>
{virtualized ? (
<AccordionPrimitive.Root
@@ -1695,6 +1724,7 @@ const LemonTree = forwardRef<LemonTreeRef, LemonTreeProps>(
isItemDraggable={isItemDraggable}
isItemDroppable={isItemDroppable}
getItemDropMode={getItemDropMode}
+ dragAndDropScope={dragAndDropScope}
onReorderPositionChange={handleReorderPositionChange}
enableDragAndDrop={enableDragAndDrop}
disableKeyboardInput={(disable) => {
@@ -1739,6 +1769,7 @@ const LemonTree = forwardRef<LemonTreeRef, LemonTreeProps>(
isItemDraggable={isItemDraggable}
isItemDroppable={isItemDroppable}
getItemDropMode={getItemDropMode}
+ dragAndDropScope={dragAndDropScope}
onReorderPositionChange={handleReorderPositionChange}
enableDragAndDrop={enableDragAndDrop}
disableKeyboardInput={(disable) => {
@@ -1794,7 +1825,7 @@ const LemonTree = forwardRef<LemonTreeRef, LemonTreeProps>(
</ButtonPrimitive>
)}
</DragOverlay>
- </DndContext>
+ </DragContext>
)
}
)
diff --git a/frontend/src/lib/lemon-ui/LemonTree/LemonTreeDndMonitor.tsx b/frontend/src/lib/lemon-ui/LemonTree/LemonTreeDndMonitor.tsx
new file mode 100644
index 000000000000..36580b30d5e9
--- /dev/null
+++ b/frontend/src/lib/lemon-ui/LemonTree/LemonTreeDndMonitor.tsx
@@ -0,0 +1,39 @@
+import { DndContextProps, useDndMonitor } from '@dnd-kit/core'
+import { ReactNode } from 'react'
+
+export function LemonTreeDndMonitor({
+ scope,
+ children,
+ onDragStart,
+ onDragOver,
+ onDragEnd,
+ onDragCancel,
+}: DndContextProps & { scope: string; children: ReactNode }): JSX.Element {
+ useDndMonitor({
+ onDragStart: (event) => {
+ if (event.active.data.current?.treeScope === scope) {
+ onDragStart?.({ ...event, active: { ...event.active, id: event.active.data.current.treeId } })
+ }
+ },
+ onDragOver: (event) => {
+ if (event.active.data.current?.treeScope === scope) {
+ onDragOver?.(event)
+ }
+ },
+ onDragEnd: (event) => {
+ if (event.active.data.current?.treeScope === scope) {
+ onDragEnd?.({
+ ...event,
+ active: { ...event.active, id: event.active.data.current.treeId },
+ over: event.over?.data.current ? { ...event.over, id: event.over.data.current.treeId } : null,
+ })
+ }
+ },
+ onDragCancel: (event) => {
+ if (event.active.data.current?.treeScope === scope) {
+ onDragCancel?.(event)
+ }
+ },
+ })
+ return <>{children}</>
+}
diff --git a/frontend/src/lib/lemon-ui/LemonTree/LemonTreeUtils.tsx b/frontend/src/lib/lemon-ui/LemonTree/LemonTreeUtils.tsx
index 0ee4eeeec51d..87197cd6e5e1 100644
--- a/frontend/src/lib/lemon-ui/LemonTree/LemonTreeUtils.tsx
+++ b/frontend/src/lib/lemon-ui/LemonTree/LemonTreeUtils.tsx
@@ -1,4 +1,5 @@
-import { useDraggable, useDroppable } from '@dnd-kit/core'
+import { useDndContext, useDraggable, useDroppable } from '@dnd-kit/core'
+import { getEventCoordinates } from '@dnd-kit/utilities'
import { CSSProperties, useEffect, useRef, useState } from 'react'
import { IconChevronRight, IconCircleDashed, IconDocument, IconFolder, IconFolderOpenFilled } from '@posthog/icons'
@@ -144,6 +145,7 @@ export const TreeNodeDisplayIcon = ({
type DragAndDropProps = {
id: string
+ scope?: string
children: React.ReactNode
}
type DraggableProps = DragAndDropProps & {
@@ -157,7 +159,8 @@ export const TreeNodeDraggable = (props: DraggableProps): JSX.Element => {
listeners: originalListeners,
setNodeRef,
} = useDraggable({
- id: props.id,
+ id: props.scope ? `${props.scope}::${props.id}` : props.id,
+ data: { treeId: props.id, treeScope: props.scope },
})
// Filter out the Enter key from drag listeners
@@ -205,21 +208,26 @@ type DroppableProps = DragAndDropProps & {
style?: CSSProperties
// When 'reorder', render an insertion line above/below the row based on pointer position
// and report which side was targeted. Defaults to 'onto' (ring highlight on the whole row).
- dropMode?: 'onto' | 'reorder'
+ dropMode?: 'onto' | 'reorder' | 'onto-or-reorder'
onPositionChange?: (id: string, position: TreeDropPosition) => void
}
export const TreeNodeDroppable = (props: DroppableProps): JSX.Element => {
- const { setNodeRef, isOver } = useDroppable({ id: props.id })
const nodeRef = useRef<HTMLDivElement | null>(null)
- const [reorderSide, setReorderSide] = useState<'before' | 'after' | null>(null)
+ const { active, activatorEvent } = useDndContext()
+ const [dropPosition, setDropPosition] = useState<TreeDropPosition | null>(null)
+ const { setNodeRef, isOver } = useDroppable({
+ id: props.scope ? `${props.scope}::${props.id}` : props.id,
+ disabled: !props.isDroppable,
+ data: { treeId: props.id, treeScope: props.scope, dropMode: props.dropMode, position: dropPosition },
+ })
const setRefs = (el: HTMLDivElement | null): void => {
nodeRef.current = el
setNodeRef(el)
}
- const isReorder = props.dropMode === 'reorder' && props.isDroppable
+ const isReorder = (props.dropMode === 'reorder' || props.dropMode === 'onto-or-reorder') && props.isDroppable
const onPositionChange = props.onPositionChange
const propsId = props.id
@@ -229,7 +237,7 @@ export const TreeNodeDroppable = (props: DroppableProps): JSX.Element => {
// drag preview briefly covers the row.
useEffect(() => {
if (!isReorder || !isOver) {
- setReorderSide(null)
+ setDropPosition(null)
return
}
// 2px deadband around the midpoint so hovering exactly on the line doesn't
@@ -241,11 +249,18 @@ export const TreeNodeDroppable = (props: DroppableProps): JSX.Element => {
}
const rect = nodeRef.current.getBoundingClientRect()
const midY = rect.top + rect.height / 2
- if (Math.abs(clientY - midY) < DEADBAND) {
+ if (props.dropMode === 'reorder' && Math.abs(clientY - midY) < DEADBAND) {
return
}
- const side: 'before' | 'after' = clientY < midY ? 'before' : 'after'
- setReorderSide((prev) => {
+ const side: TreeDropPosition =
+ props.dropMode === 'onto-or-reorder' &&
+ clientY > rect.top + rect.height / 4 &&
+ clientY < rect.bottom - rect.height / 4
+ ? 'onto'
+ : clientY < midY
+ ? 'before'
+ : 'after'
+ setDropPosition((prev) => {
if (prev !== side) {
onPositionChange?.(propsId, side)
return side
@@ -253,14 +268,23 @@ export const TreeNodeDroppable = (props: DroppableProps): JSX.Element => {
return prev
})
}
+ const start = activatorEvent ? getEventCoordinates(activatorEvent) : null
+ const initial = active?.rect.current.initial
+ const translated = active?.rect.current.translated
+ if (start && initial && translated) {
+ updateFromClientY(start.y + translated.top - initial.top)
+ }
const handleMove = (e: PointerEvent): void => updateFromClientY(e.clientY)
document.addEventListener('pointermove', handleMove)
return () => document.removeEventListener('pointermove', handleMove)
- }, [isReorder, isOver, onPositionChange, propsId])
-
- const showRing = props.isDroppable && isOver && !isReorder
- const showLineBefore = isReorder && isOver && reorderSide === 'before'
- const showLineAfter = isReorder && isOver && reorderSide === 'after'
+ }, [isReorder, isOver, onPositionChange, propsId, props.dropMode, active, activatorEvent])
+
+ const showRing =
+ props.isDroppable &&
+ isOver &&
+ (!isReorder || (props.dropMode === 'onto-or-reorder' && (!dropPosition || dropPosition === 'onto')))
+ const showLineBefore = isReorder && isOver && dropPosition === 'before'
+ const showLineAfter = isReorder && isOver && dropPosition === 'after'
return (
<div