Skip to content

The agent that grows with you

14.8 KB
Raw Blame
/**
 * Sidebar session drag — the session RESOLVER over the shared pointer drag
 * session (pane-shell drag-session.ts). Same machinery as a pane drag
 * (threshold, rAF moves, snapshots, Esc-as-top-layer with synchronous
 * teardown), session-specific targeting:
 *
 *   - a chat zone's TAB STRIP  → stack: open the session as a tab at the
 *     divider's slot (the strip caret shows it);
 *   - a chat zone's EDGE band  → split: open the session as a tile docked on
 *     that edge (the zone sheet morphs to the half);
 *   - a chat zone's CENTER / the composer → link: insert an `@session` chip
 *     into that surface's composer (ChatDropOverlay owns the visual);
 *   - a sidebar PROJECT ROW → move: re-home the session under that project
 *     (same call the row's own "Move to project" menu item makes);
 *   - the sidebar PINNED section → pin: same call as the row's "Pin" menu
 *     item (a row already in Pinned isn't a pin target — it reorders there);
 *   - a sidebar SESSION LIST, from a pinned row → unpin: same call as the
 *     row's "Unpin" menu item;
 *   - anything else (terminal, gutters) → deny.
 *
 * Zones that don't host a chat surface are NOT targets — the overlay never
 * lights them, so a release there must not commit either (one truth).
 *
 * This replaced the native-HTML5 drag + SessionTileDropBridge: riding the
 * native DnD layer meant macOS's cancel snap-back animation, a `dragend`
 * held hostage until that animation finished, an Esc the page never even
 * saw, and window-level armor against react-dnd/dnd-kit. A pointer session
 * has none of those failure modes. Native DnD remains only at the true OS
 * boundary (Finder file drops). Known trade: a session can no longer be
 * dragged into a separate BrowserWindow (native DnD was the only transport
 * that crossed windows).
 */

import type { PointerEvent as ReactPointerEvent } from 'react'

import { queryAllVisible } from '@/components/pane-shell/pane-visibility'
import {
  rectContains,
  slotBefore,
  snapshotStrips,
  snapshotZones,
  startDragSession,
  type StripSnapshot,
  subZonePosition
} from '@/components/pane-shell/tree/renderer/drag-session'
import {
  $treeDragging,
  closeTreePane,
  type DropHint,
  revealTreePane,
  SESSION_TILE_DRAG
} from '@/components/pane-shell/tree/store'
import type { EngineZone, ZoneRect } from '@/components/pane-shell/tree/zones-engine'
import { translateNow } from '@/i18n'
import { $pinnedSessionIds, pinSession, unpinSession } from '@/store/layout'
import { notifyError } from '@/store/notifications'
import { requestFreshSession } from '@/store/profile'
import { moveSessionToProject, projectIdForCwd } from '@/store/projects'
import { $selectedStoredSessionId, $sessions, sessionMatchesStoredId, sessionPinId } from '@/store/session'
import { $sessionTiles, nextSessionTileForWorkspace, openSessionTile, type TileDock } from '@/store/session-states'

import { requestComposerInsertRefs } from './composer/focus'
import { type SessionDragPayload, sessionInlineRef, sessionLabel } from './composer/inline-refs'
import { NO_PROJECT_ID } from './sidebar/projects/workspace-groups'
import { tileZoneHost } from './tile-zone-host'

const PROJECT_ROW_DROP_ATTR = 'data-session-drop-hover'
const PIN_DROP_SELECTOR = '[data-session-pin-drop]'
const UNPIN_DROP_SELECTOR = '[data-session-unpin-drop]'

/** A sidebar project row's drop geometry — tagged by `ProjectOverviewRow` via
 *  `data-sessions-project`. */
interface ProjectRowSnapshot {
  el: HTMLElement
  id: string
  rect: ZoneRect
}

function snapshotProjectRows(excludeId: null | string): ProjectRowSnapshot[] {
  return (
    queryAllVisible<HTMLElement>('[data-sessions-project]')
      .map(el => ({ el, id: el.dataset.sessionsProject || '', rect: snapRect(el) }))
      // Home (no folder to move into) and the session's own current project
      // (nothing to move) aren't drop targets — same exclusion the row's
      // "Move to project" menu applies to its own list.
      .filter(row => row.id !== NO_PROJECT_ID && row.id !== excludeId)
  )
}

/** A chat surface's drag-start geometry: the anchor pane id it advertises
 *  (`data-session-anchor`) and the composer a link drop routes to
 *  (`data-composer-target`). */
interface SurfaceSnapshot {
  anchor: string
  composerTarget: string
  rect: ZoneRect
}

const snapRect = (el: HTMLElement): ZoneRect => {
  const r = el.getBoundingClientRect()

  return { left: r.left, top: r.top, right: r.right, bottom: r.bottom }
}

/** Chat surfaces the pointer can land on. Inactive tabs are excluded: they stay
 *  mounted with their layout box intact, so their rect is identical to the
 *  visible tab's and a hit-test alone would pick whichever came first. */
function snapshotSurfaces(): SurfaceSnapshot[] {
  return queryAllVisible('[data-session-anchor]').map(el => ({
    anchor: el.dataset.sessionAnchor || 'workspace',
    composerTarget: el.dataset.composerTarget || 'main',
    rect: snapRect(el)
  }))
}

/** A session may land in any zone hosting a MAIN tile — another chat stack, a
 *  Browser tile, a page — never the sidebar/terminal zones. Resolves via the
 *  shared {@link tileZoneHost} (tile-zone-host.ts) so the eligibility answer
 *  is byte-identical to what the zone overlay paints. */

/**
 * Begin dragging a session — a sidebar row OR a tile's own tab (same drop
 * language either way: stack, split, or composer link). Sub-threshold releases
 * stay ordinary clicks, so `opts.onTap` (activate the tile) rides the tab's
 * gesture; Esc aborts instantly. A stack/split commits through
 * `openSessionTile`, which OPENS a new tile from a sidebar row and MOVES the
 * existing one when its tab is the drag source.
 */
export function startSessionDrag(
  payload: SessionDragPayload,
  e: ReactPointerEvent<HTMLElement>,
  opts?: { onTap?: () => void }
) {
  let zones: EngineZone[] = []
  let strips: StripSnapshot[] = []
  let surfaces: SurfaceSnapshot[] = []
  let composers: ZoneRect[] = []
  let zoneHost = new Map<string, ReturnType<typeof tileZoneHost>>()
  let projectRows: ProjectRowSnapshot[] = []
  let pinTarget: { el: HTMLElement; rect: ZoneRect } | null = null
  let unpinTargets: { el: HTMLElement; rect: ZoneRect }[] = []

  // Commit intent, updated per resolved move (the machinery flushes the final
  // move before commit, so these always match the released-at position).
  let split: { anchor: string; before?: null | string; pos: TileDock } | null = null
  let link: null | string = null
  let moveToProject: null | string = null
  let pin = false
  let unpin = false
  let hoveredUnpin: HTMLElement | null = null
  // The project row currently painted as the drop target, so a move to a
  // different row (or off any row) clears the one it left — imperative like
  // the source's own opacity, not React state (a repaint here shouldn't
  // re-render the sidebar on every pixel of pointer travel).
  let hoveredProjectRow: HTMLElement | null = null

  const clearProjectHover = () => {
    hoveredProjectRow?.removeAttribute(PROJECT_ROW_DROP_ATTR)
    hoveredProjectRow = null
  }

  const setUnpinHover = (el: HTMLElement | null) => {
    unpin = el !== null

    if (hoveredUnpin !== el) {
      hoveredUnpin?.removeAttribute(PROJECT_ROW_DROP_ATTR)
      el?.setAttribute(PROJECT_ROW_DROP_ATTR, 'true')
      hoveredUnpin = el
    }
  }

  const setPinHover = (on: boolean) => {
    pin = on

    if (on) {
      pinTarget?.el.setAttribute(PROJECT_ROW_DROP_ATTR, 'true')
    } else {
      pinTarget?.el.removeAttribute(PROJECT_ROW_DROP_ATTR)
    }
  }

  // The drag SOURCE (sidebar row or tile tab). Captured synchronously — React
  // clears `currentTarget` after the pointerdown handler returns, but this runs
  // inside it. Dimmed while lifted so the source reads as "picked up" — the
  // same in-place feedback pane-tab drags use, replacing the old cursor chip.
  const source = e.currentTarget
  const restoreOpacity = source?.style.opacity ?? ''

  startDragSession(e, {
    ghost: { label: sessionLabel(payload) },
    onTap: opts?.onTap,

    onEngage() {
      zones = snapshotZones()
      strips = snapshotStrips()
      surfaces = snapshotSurfaces()
      composers = queryAllVisible('[data-slot="composer-root"]').map(snapRect)
      zoneHost = new Map(zones.map(zone => [zone.id, tileZoneHost(zone.id)]))
      // Resolved fresh per drag (not passed in as payload): a stale value would
      // survive the row's own reorder/rename churn while a drag is armed.
      const draggedSession = $sessions.get().find(s => sessionMatchesStoredId(s, payload.id))
      const cwd = draggedSession?.cwd?.trim() || ''
      projectRows = snapshotProjectRows(cwd ? projectIdForCwd(cwd) : null)
      // A row dragged out of Pinned has nothing to pin (it reorders there) —
      // instead the session lists become unpin targets. Any other row gets
      // Pinned as its pin target.
      const fromPinned = Boolean(source?.closest(PIN_DROP_SELECTOR))

      // A session that's already pinned (e.g. dragged from its tile tab) has
      // nothing to pin either: pinSession would re-append it to the bottom.
      const alreadyPinned = draggedSession
        ? $pinnedSessionIds.get().includes(sessionPinId(draggedSession))
        : $pinnedSessionIds.get().includes(payload.id)

      const pinEl = fromPinned || alreadyPinned ? null : queryAllVisible<HTMLElement>(PIN_DROP_SELECTOR)[0]
      pinTarget = pinEl ? { el: pinEl, rect: snapRect(pinEl) } : null
      unpinTargets = fromPinned
        ? queryAllVisible<HTMLElement>(UNPIN_DROP_SELECTOR).map(el => ({ el, rect: snapRect(el) }))
        : []
      source?.style.setProperty('opacity', '0.45')
      // The same sentinel the zone overlay + chat surfaces key off — the
      // whole drop language (sheets, pills, caret, link overlay) lights up.
      $treeDragging.set(SESSION_TILE_DRAG)
    },

    onEnd() {
      if (source) {
        source.style.opacity = restoreOpacity
      }

      clearProjectHover()
      setPinHover(false)
      setUnpinHover(null)
    },

    resolveMove(x, y): DropHint | null {
      if (pinTarget && rectContains(pinTarget.rect, x, y)) {
        split = null
        link = null
        moveToProject = null
        clearProjectHover()
        setPinHover(true)

        return null
      }

      setPinHover(false)

      // The sidebar hosts no MAIN tile, so it's outside every pane-shell
      // zone — a project row is the one thing in that dead space a session
      // drop still resolves against. Checked first: it's a flat, disjoint
      // hit-test, not a fallback off the zone lookup below.
      const projectRow = projectRows.find(p => rectContains(p.rect, x, y))

      if (projectRow) {
        split = null
        link = null
        moveToProject = projectRow.id

        if (hoveredProjectRow !== projectRow.el) {
          clearProjectHover()
          hoveredProjectRow = projectRow.el
          hoveredProjectRow.setAttribute(PROJECT_ROW_DROP_ATTR, 'true')
        }

        return null
      }

      moveToProject = null
      clearProjectHover()

      const unpinTarget = unpinTargets.find(t => rectContains(t.rect, x, y))
      setUnpinHover(unpinTarget?.el ?? null)

      if (unpinTarget) {
        split = null
        link = null

        return null
      }

      const zone = zones.find(z => rectContains(z.rect, x, y))
      const host = zone ? zoneHost.get(zone.id) : null

      if (!zone || !host) {
        split = null
        link = null

        return null
      }

      // The zone's TAB STRIP stacks the session at the divider's slot.
      const strip = strips.find(s => s.groupId === zone.id && rectContains(s.rect, x, y))

      if (strip) {
        // Exclude the tile's OWN tab from the slots so re-dropping it in its
        // home strip reorders cleanly (a no-op for a sidebar-row drag).
        const stack = slotBefore(strip.slots, x, `session-tile:${payload.id}`)
        split = { anchor: host.pane, before: stack.before, pos: 'center' }
        link = null

        return { kind: 'group', groupId: zone.id, groupIds: [zone.id], pos: 'center', stack }
      }

      // The composer (and everything in it) is always the link/attach drop;
      // elsewhere the shared radial targeting decides center vs edge.
      const pos = composers.some(rect => rectContains(rect, x, y)) ? 'center' : subZonePosition(zones, zone.id, x, y)
      const surface = surfaces.find(s => rectContains(s.rect, x, y))

      if (pos === 'center' && host.chat) {
        split = null
        link = surface?.composerTarget ?? 'main'
      } else if (pos === 'center') {
        // A preview/page zone has no composer to link to — its center stacks
        // the session as a tab, same as dropping on the strip's tail.
        split = { anchor: host.pane, pos: 'center' }
        link = null
      } else {
        split = { anchor: surface?.anchor ?? host.pane, pos }
        link = null
      }

      return { kind: 'group', groupId: zone.id, groupIds: [zone.id], pos }
    },

    onCommit() {
      if (split) {
        const fromMain = payload.id === $selectedStoredSessionId.get()

        openSessionTile(payload.id, split.pos, split.anchor, split.before)
        // A tile for this session may already exist (openSessionTile is
        // idempotent — e.g. persisted from an earlier run): a drop must never
        // feel dead, so front/unhide/un-dismiss it either way.
        revealTreePane(`session-tile:${payload.id}`)

        // Dragging MAIN's own tab out is a MOVE. A session lives in exactly one
        // surface (two panes on one runtime would fight over it), so once the
        // tile exists main lets go the way its Close does: the next stacked
        // tab shifts in, else a fresh draft. Never promote the tile just
        // minted — that would pull the chat straight back and read as a dead
        // drop.
        if (fromMain && $sessionTiles.get().some(t => t.storedSessionId === payload.id)) {
          const next = nextSessionTileForWorkspace()

          if (next && next !== payload.id) {
            closeTreePane('workspace')
          } else {
            requestFreshSession()
          }
        }
      } else if (link) {
        // The "link to chat" drop: an @session chip in that surface's composer.
        requestComposerInsertRefs([sessionInlineRef(payload)], { target: link })
      } else if (pin || unpin) {
        // Same store calls as the row's own "Pin" / "Unpin" menu items.
        const session = $sessions.get().find(s => sessionMatchesStoredId(s, payload.id))
        const pinId = session ? sessionPinId(session) : payload.id

        if (pin) {
          pinSession(pinId)
        } else {
          unpinSession(pinId)
        }
      } else if (moveToProject) {
        // Same RPC the row's own "Move to project" menu item calls — the drop
        // is a shortcut onto that existing path, not a parallel one.
        void moveSessionToProject(payload.id, moveToProject, payload.profile).catch(err =>
          notifyError(err, translateNow('sidebar.projects.moveFailed'))
        )
      }
    }
  })
}