| 1 | import { shortcut } from "./platform.mjs"; |
| 2 | import React, { useEffect, useRef, useState } from "react"; |
| 3 | import { createPortal } from "react-dom"; |
| 4 | import { |
| 5 | FileCode2, |
| 6 | Archive, |
| 7 | LoaderCircle, |
| 8 | ChevronDown, |
| 9 | Globe2, |
| 10 | Settings, |
| 11 | Pencil, |
| 12 | Pin, |
| 13 | PinOff, |
| 14 | TerminalSquare, |
| 15 | X, |
| 16 | } from "lucide-react"; |
| 17 | import { tabName } from "./workspace-state.mjs"; |
| 18 | import { AgentIcon } from "./agent-icon"; |
| 19 | |
| 20 | export function TabIcon({ kind, favicon, agent, accountNumber, size = 16 }) { |
| 21 | const [failed, setFailed] = useState(""); |
| 22 | if (kind === "terminal" && agent) return <AgentIcon accountNumber={accountNumber} size={Math.max(20, size)} />; |
| 23 | if (kind === "terminal") return <TerminalSquare size={Math.max(20, size)} />; |
| 24 | if (kind === "editor") return <FileCode2 size={size} />; |
| 25 | if (kind === "browser-settings") return <Settings size={size} />; |
| 26 | if (typeof favicon === "string" && favicon.length <= 8192 && |
| 27 | /^data:image\/png;base64,[A-Za-z0-9+/=]+$/.test(favicon) && failed !== favicon) |
| 28 | return <img src={favicon} className="tab-favicon" alt="" width={size} height={size} |
| 29 | draggable={false} onError={() => setFailed(favicon)} />; |
| 30 | return <Globe2 size={size} />; |
| 31 | } |
| 32 | |
| 33 | function TerminalAction({ label, icon: Icon, disabled, onClick }) { |
| 34 | return ( |
| 35 | <button className="icon-button" aria-label={label} disabled={disabled} onClick={onClick}> |
| 36 | <span className="terminal-action-label" aria-hidden="true">{label}</span> |
| 37 | <Icon size={14} /> |
| 38 | </button> |
| 39 | ); |
| 40 | } |
| 41 | |
| 42 | |
| 43 | |
| 44 | export function WorkspaceTabs({ |
| 45 | tabs, |
| 46 | saved, |
| 47 | active, |
| 48 | label, |
| 49 | horizontal = false, |
| 50 | vertical = false, |
| 51 | busy, |
| 52 | ready, |
| 53 | onSelect, |
| 54 | onClose, |
| 55 | onRename, |
| 56 | onPin, |
| 57 | onReorder, |
| 58 | splitDrag, |
| 59 | openingSession, |
| 60 | sessionOpenError, |
| 61 | }) { |
| 62 | const [menu, setMenu] = useState(null); |
| 63 | const [drag, setDrag] = useState(null); |
| 64 | const [allOpen, setAllOpen] = useState(false); |
| 65 | const [query, setQuery] = useState(""); |
| 66 | const [width, setWidth] = useState(0); |
| 67 | const pointer = useRef(null); |
| 68 | const suppressClick = useRef(false); |
| 69 | const trigger = useRef(); |
| 70 | const list = useRef(); |
| 71 | useEffect(() => { |
| 72 | if (!horizontal || !list.current) return; |
| 73 | const observer = new ResizeObserver(([entry]) => |
| 74 | setWidth(entry.contentRect.width), |
| 75 | ); |
| 76 | observer.observe(list.current); |
| 77 | return () => observer.disconnect(); |
| 78 | }, [horizontal]); |
| 79 | const gap = tabs.length > 20 ? 1 : 4; |
| 80 | const available = Math.max(0, width - gap * Math.max(0, tabs.length - 1)); |
| 81 | const regularWidth = Math.min(220, available / Math.max(1, tabs.length)); |
| 82 | const activeWidth = |
| 83 | tabs.length > 1 && tabs.some((tab) => tab.id === active) |
| 84 | ? Math.min(220, Math.max(regularWidth, Math.min(160, available * 0.4))) |
| 85 | : regularWidth; |
| 86 | const otherWidth = Math.max( |
| 87 | 0, |
| 88 | (available - activeWidth) / Math.max(1, tabs.length - 1), |
| 89 | ); |
| 90 | const tabWidth = (id) => |
| 91 | id === active ? activeWidth : Math.min(220, otherWidth); |
| 92 | const matchingTabs = tabs.filter((tab) => |
| 93 | `${tabName(tab, saved)} ${tab.url || ""}` |
| 94 | .toLowerCase() |
| 95 | .includes(query.toLowerCase()), |
| 96 | ); |
| 97 | const firstFocusable = tabs.findIndex(tab => tab.historySession |
| 98 | ? !busy && openingSession !== tab.cli_session_id && !tab.sessionRunningElsewhere |
| 99 | : ready || tab.kind === "terminal"); |
| 100 | const finishDrag = (commit, event) => { |
| 101 | const current = pointer.current; |
| 102 | pointer.current = null; |
| 103 | setDrag(null); |
| 104 | splitDrag.clear(); |
| 105 | if (!current?.moved) return; |
| 106 | suppressClick.current = true; |
| 107 | if (!commit) return; |
| 108 | const { clientX, clientY } = event; |
| 109 | if (!tabs.find(tab => tab.id === current.id)?.historySession && splitDrag.drop(current.id, clientX, clientY)) return; |
| 110 | const over = document.elementFromPoint(clientX, clientY); |
| 111 | if (!list.current?.contains(over)) return; |
| 112 | if (horizontal) onReorder(current.id, null, current.order); |
| 113 | else { |
| 114 | const target = over?.closest("[data-tab-id]")?.dataset.tabId; |
| 115 | if (target && target !== current.id) onReorder(current.id, target); |
| 116 | } |
| 117 | }; |
| 118 | useEffect(() => { |
| 119 | if (!drag) return; |
| 120 | const cancel = (event) => { |
| 121 | if (event.key !== "Escape") return; |
| 122 | event.preventDefault(); |
| 123 | event.stopImmediatePropagation(); |
| 124 | finishDrag(false); |
| 125 | }; |
| 126 | document.addEventListener("keydown", cancel, true); |
| 127 | return () => document.removeEventListener("keydown", cancel, true); |
| 128 | }, [Boolean(drag)]); |
| 129 | useEffect(() => () => splitDrag.clear(), []); |
| 130 | const startDrag = (event, tab) => { |
| 131 | suppressClick.current = false; |
| 132 | if (busy || (!ready && tab.kind !== "terminal") || event.button !== 0 || |
| 133 | !event.isPrimary || event.target.closest(".tab-close, .terminal-row-actions")) return; |
| 134 | const items = [...list.current.querySelectorAll(":scope > [data-tab-id]")].map((node) => ({ |
| 135 | id: node.dataset.tabId, |
| 136 | left: node.offsetLeft, |
| 137 | width: node.getBoundingClientRect().width, |
| 138 | })); |
| 139 | const group = horizontal || vertical ? items.filter(item => |
| 140 | Boolean(saved[item.id]?.pinned) === Boolean(saved[tab.id]?.pinned)) : items; |
| 141 | pointer.current = { |
| 142 | id: tab.id, startX: event.clientX, startY: event.clientY, |
| 143 | items, group, order: items.map(item => item.id), moved: false, |
| 144 | }; |
| 145 | (event.target.closest("button") || event.currentTarget).setPointerCapture(event.pointerId); |
| 146 | }; |
| 147 | const moveDrag = (event) => { |
| 148 | const current = pointer.current; |
| 149 | if (!current) return; |
| 150 | if (!event.buttons) return finishDrag(false); |
| 151 | let dx = event.clientX - current.startX; |
| 152 | if (!current.moved && Math.hypot(dx, event.clientY - current.startY) < 5) return; |
| 153 | current.moved = true; |
| 154 | const dropSide = tabs.find(tab => tab.id === current.id)?.historySession ? null : splitDrag.hover(current.id, event.clientX, event.clientY); |
| 155 | if (!horizontal || dropSide) { |
| 156 | setDrag({ id: current.id, offsets: {}, widths: {} }); |
| 157 | return; |
| 158 | } |
| 159 | const item = current.items.find(item => item.id === current.id); |
| 160 | |
| 161 | const center = item.left + item.width / 2 + dx; |
| 162 | dx = Math.max( |
| 163 | current.group[0].left - item.left, |
| 164 | Math.min( |
| 165 | dx, |
| 166 | current.group.at(-1).left + |
| 167 | current.group.at(-1).width - |
| 168 | item.left - |
| 169 | item.width, |
| 170 | ), |
| 171 | ); |
| 172 | const rest = current.group.filter((other) => other.id !== item.id); |
| 173 | const target = rest.filter( |
| 174 | (other) => center > other.left + other.width / 2, |
| 175 | ).length; |
| 176 | const groupOrder = rest.map((other) => other.id); |
| 177 | groupOrder.splice(target, 0, item.id); |
| 178 | let at = 0; |
| 179 | current.order = current.items.map((other) => |
| 180 | current.group.includes(other) ? groupOrder[at++] : other.id, |
| 181 | ); |
| 182 | let left = current.items[0].left; |
| 183 | const offsets = {}; |
| 184 | for (const id of current.order) { |
| 185 | const original = current.items.find((other) => other.id === id); |
| 186 | offsets[id] = id === item.id ? dx : left - original.left; |
| 187 | left += original.width + gap; |
| 188 | } |
| 189 | setDrag({ |
| 190 | id: item.id, |
| 191 | offsets, |
| 192 | widths: Object.fromEntries( |
| 193 | current.items.map((item) => [item.id, item.width]), |
| 194 | ), |
| 195 | }); |
| 196 | }; |
| 197 | const showMenu = (tab, event) => { |
| 198 | event.preventDefault(); |
| 199 | if (!horizontal && !vertical) { |
| 200 | event.currentTarget.focus(); |
| 201 | event.currentTarget.parentElement.querySelector(".terminal-row-actions button:not(:disabled)")?.focus(); |
| 202 | return; |
| 203 | } |
| 204 | trigger.current = event.currentTarget; |
| 205 | const rect = event.currentTarget.getBoundingClientRect(); |
| 206 | setMenu({ |
| 207 | tab, |
| 208 | left: Math.max(8, Math.min(rect.left, window.innerWidth - 224)), |
| 209 | top: Math.max(8, Math.min(rect.bottom + 4, window.innerHeight - 152)), |
| 210 | }); |
| 211 | }; |
| 212 | useEffect(() => { |
| 213 | if (horizontal) return; |
| 214 | list.current |
| 215 | ?.querySelector('[aria-selected="true"]') |
| 216 | ?.scrollIntoView({ block: "nearest", inline: "nearest" }); |
| 217 | }, [active, horizontal, tabs.length]); |
| 218 | useEffect(() => { |
| 219 | if (!menu && !allOpen) return; |
| 220 | const dismiss = (event) => { |
| 221 | if (event.key === "Escape") { |
| 222 | event.stopPropagation(); |
| 223 | setMenu(null); |
| 224 | setAllOpen(false); |
| 225 | trigger.current?.focus(); |
| 226 | } |
| 227 | }; |
| 228 | const outside = (event) => { |
| 229 | if (event.target.closest(".all-tabs-menu") || trigger.current?.contains(event.target)) return; |
| 230 | setAllOpen(false); |
| 231 | }; |
| 232 | document.addEventListener("keydown", dismiss); |
| 233 | document.addEventListener("click", outside, true); |
| 234 | return () => { |
| 235 | document.removeEventListener("keydown", dismiss); |
| 236 | document.removeEventListener("click", outside, true); |
| 237 | }; |
| 238 | }, [menu, allOpen]); |
| 239 | const actions = menu && ( |
| 240 | <div className="menu workspace-tab-menu" |
| 241 | style={{ top: menu.top, left: menu.left }} |
| 242 | role="menu" aria-label="标签操作"> |
| 243 | <button |
| 244 | role="menuitem" |
| 245 | onClick={() => { |
| 246 | setMenu(null); |
| 247 | onRename(menu.tab); |
| 248 | }} |
| 249 | > |
| 250 | 重命名标签 |
| 251 | </button> |
| 252 | <button |
| 253 | role="menuitem" |
| 254 | onClick={() => { |
| 255 | setMenu(null); |
| 256 | onPin(menu.tab.id); |
| 257 | }} |
| 258 | > |
| 259 | <Pin size={14} /> |
| 260 | {saved[menu.tab.id]?.pinned ? "取消置顶" : "置顶标签"} |
| 261 | </button> |
| 262 | <button |
| 263 | role="menuitem" |
| 264 | onClick={() => { |
| 265 | setMenu(null); |
| 266 | onClose(menu.tab); |
| 267 | }} |
| 268 | > |
| 269 | <X size={15} /> |
| 270 | 关闭标签<kbd>{shortcut("⌘W")}</kbd> |
| 271 | </button> |
| 272 | </div> |
| 273 | ); |
| 274 | return ( |
| 275 | <> |
| 276 | <div |
| 277 | ref={list} |
| 278 | role="tablist" |
| 279 | aria-label={label} |
| 280 | aria-orientation={horizontal ? "horizontal" : "vertical"} |
| 281 | className={ |
| 282 | horizontal || vertical |
| 283 | ? `browser-tabs ${vertical ? "browser-tabs-vertical" : ""} ${drag ? "is-dragging" : ""}` |
| 284 | : "sidebar-tabs" |
| 285 | } |
| 286 | style={ |
| 287 | horizontal |
| 288 | ? { |
| 289 | gap, |
| 290 | width: tabs.length * 220 + gap * Math.max(0, tabs.length - 1), |
| 291 | flex: "0 1 auto", |
| 292 | } |
| 293 | : undefined |
| 294 | } |
| 295 | > |
| 296 | {tabs.map((tab, index) => { |
| 297 | const title = tabName(tab, saved); |
| 298 | const opening = Boolean(openingSession) && openingSession === tab.cli_session_id; |
| 299 | const runningElsewhere = tab.sessionRunningElsewhere; |
| 300 | const runningNotice = "其他窗口运行中,退出原会话后可在 Cage 接续"; |
| 301 | const openError = tab.historySession && sessionOpenError?.id === tab.cli_session_id ? sessionOpenError.message : ""; |
| 302 | const errorID = `session-open-error-${tab.cli_session_id}`; |
| 303 | return ( |
| 304 | <React.Fragment key={tab.id}> |
| 305 | <div |
| 306 | data-tab-id={tab.id} |
| 307 | title={runningElsewhere ? runningNotice : undefined} |
| 308 | className={`${horizontal || vertical ? "browser-tab" : "sidebar-tab"} ${tab.id === active ? "active" : ""} ${tab.closed ? "ended" : ""} ${drag?.id === tab.id ? "dragging" : ""} ${horizontal && tabWidth(tab.id) < 96 ? "compact" : ""} ${horizontal && tabWidth(tab.id) < 40 ? "tiny" : ""} ${horizontal && tabWidth(tab.id) < 24 ? "sliver" : ""}`} |
| 309 | style={ |
| 310 | horizontal |
| 311 | ? { |
| 312 | width: drag?.widths[tab.id] ?? tabWidth(tab.id), |
| 313 | transform: drag |
| 314 | ? `translateX(${drag.offsets[tab.id] || 0}px)` |
| 315 | : undefined, |
| 316 | } |
| 317 | : undefined |
| 318 | } |
| 319 | onPointerDown={(event) => startDrag(event, tab)} |
| 320 | onPointerMove={moveDrag} |
| 321 | onPointerUp={(event) => finishDrag(true, event)} |
| 322 | onPointerCancel={() => finishDrag(false)} |
| 323 | onLostPointerCapture={() => { |
| 324 | if (pointer.current) finishDrag(false); |
| 325 | }} |
| 326 | onClickCapture={(event) => { |
| 327 | if (suppressClick.current) { |
| 328 | event.preventDefault(); |
| 329 | event.stopPropagation(); |
| 330 | suppressClick.current = false; |
| 331 | } |
| 332 | }} |
| 333 | > |
| 334 | <button |
| 335 | role={tab.historySession ? undefined : "tab"} |
| 336 | className={tab.historySession ? "sidebar-session" : undefined} |
| 337 | aria-busy={opening || undefined} |
| 338 | aria-describedby={openError ? errorID : undefined} |
| 339 | aria-description={runningElsewhere ? runningNotice : undefined} |
| 340 | aria-label={tab.claudeLabel ? `${title} · ${tab.claudeLabel}` : title} |
| 341 | aria-selected={tab.historySession ? undefined : tab.id === active} |
| 342 | tabIndex={ |
| 343 | tab.id === active || |
| 344 | (!tabs.some((t) => t.id === active) && index === firstFocusable) |
| 345 | ? 0 |
| 346 | : -1 |
| 347 | } |
| 348 | disabled={tab.historySession ? busy || opening || runningElsewhere : !ready && tab.kind !== "terminal"} |
| 349 | title={runningElsewhere ? `${title}\n${runningNotice}` : tab.url ? `${title}\n${tab.url}` : [title, tab.claudeAccountNumber && `账号 ${tab.claudeAccountNumber}`, tab.claudeLabel].filter(Boolean).join(" · ")} |
| 350 | onClick={() => onSelect(tab.id)} |
| 351 | onContextMenu={(event) => showMenu(tab, event)} |
| 352 | onKeyDown={(event) => { |
| 353 | if (!horizontal && !vertical && event.altKey && ["ArrowUp", "ArrowDown"].includes(event.key)) { |
| 354 | event.preventDefault(); |
| 355 | const target = tabs[index + (event.key === "ArrowUp" ? -1 : 1)]; |
| 356 | if (target) onReorder(tab.id, target.id); |
| 357 | return; |
| 358 | } |
| 359 | if (event.key === "F10" && event.shiftKey) { |
| 360 | showMenu(tab, event); |
| 361 | return; |
| 362 | } |
| 363 | const prev = horizontal ? "ArrowLeft" : "ArrowUp"; |
| 364 | const next = horizontal ? "ArrowRight" : "ArrowDown"; |
| 365 | if (![prev, next, "Home", "End"].includes(event.key)) return; |
| 366 | event.preventDefault(); |
| 367 | const buttons = [...list.current.querySelectorAll('[role="tab"], .sidebar-session')]; |
| 368 | const enabled = buttons.map((button, at) => ({button, at})).filter(item => !item.button.disabled); |
| 369 | const from = enabled.findIndex(item => item.at === index); |
| 370 | const target = enabled[ |
| 371 | event.key === "Home" |
| 372 | ? 0 |
| 373 | : event.key === "End" |
| 374 | ? enabled.length - 1 |
| 375 | : (from + |
| 376 | (event.key === prev ? -1 : 1) + |
| 377 | enabled.length) % |
| 378 | enabled.length]; |
| 379 | target?.button.focus(); |
| 380 | if (target && !tabs[target.at].historySession) onSelect(tabs[target.at].id, false); |
| 381 | }} |
| 382 | > |
| 383 | <TabIcon kind={tab.kind} favicon={tab.favicon} size={15} |
| 384 | agent={tab.terminalKind === "claude" || tab.terminalKind === "claude-login" || Boolean(tab.cli_session_id) || Boolean(tab.claude_account_id)} |
| 385 | accountNumber={tab.claudeAccountNumber} /> |
| 386 | <span>{title}</span> |
| 387 | {tab.claudeLabel && <small className="claude-tab-profile">{tab.claudeLabel}</small>} |
| 388 | {saved[tab.id]?.pinned && <Pin size={11} className="tab-pin" />} |
| 389 | {!horizontal && !vertical && (runningElsewhere || tab.sessionActive || opening) && |
| 390 | <LoaderCircle size={13} className="spin session-activity" role="img" aria-label={runningElsewhere ? "其他窗口运行中" : opening ? "正在打开会话" : "会话正在运行"} />} |
| 391 | </button> |
| 392 | {horizontal || vertical ? ( |
| 393 | <button |
| 394 | className="tab-close icon-button" |
| 395 | aria-label={`关闭 ${title}`} |
| 396 | disabled={busy} |
| 397 | onClick={() => onClose(tab)} |
| 398 | > |
| 399 | <X size={14} /> |
| 400 | </button> |
| 401 | ) : ( |
| 402 | <div className="terminal-row-actions" role="group" aria-label={`${title} 的操作`}> |
| 403 | <TerminalAction label={saved[tab.id]?.pinned ? "取消置顶" : "置顶"} |
| 404 | icon={saved[tab.id]?.pinned ? PinOff : Pin} disabled={busy} onClick={() => onPin(tab.id)} /> |
| 405 | <TerminalAction label="重命名" icon={Pencil} disabled={busy} onClick={() => onRename(tab)} /> |
| 406 | <TerminalAction label={tab.cli_session_id ? "归档" : "关闭终端"} icon={tab.cli_session_id ? Archive : X} disabled={busy} onClick={event => onClose(tab, event.currentTarget)} /> |
| 407 | </div> |
| 408 | )} |
| 409 | </div> |
| 410 | {openError && <p id={errorID} className="sidebar-session-open-error" role="alert">{openError}</p>} |
| 411 | </React.Fragment> |
| 412 | ); |
| 413 | })} |
| 414 | </div> |
| 415 | {horizontal && ( |
| 416 | <div className="browser-all-tabs"> |
| 417 | <button |
| 418 | className="icon-button" |
| 419 | aria-label="搜索标签页" |
| 420 | title="搜索标签页" |
| 421 | aria-expanded={allOpen} |
| 422 | onClick={(event) => { |
| 423 | trigger.current = event.currentTarget; |
| 424 | setAllOpen(!allOpen); |
| 425 | setQuery(""); |
| 426 | }} |
| 427 | > |
| 428 | <ChevronDown size={16} /> |
| 429 | </button> |
| 430 | {allOpen && ( |
| 431 | <> |
| 432 | |
| 433 | <div |
| 434 | className="menu all-tabs-menu" |
| 435 | role="dialog" |
| 436 | aria-label="搜索标签页" |
| 437 | > |
| 438 | <input |
| 439 | autoFocus |
| 440 | aria-label="搜索已打开的标签页" |
| 441 | placeholder="搜索标签页" |
| 442 | value={query} |
| 443 | onChange={(event) => setQuery(event.target.value)} |
| 444 | /> |
| 445 | <div className="all-tabs-results"> |
| 446 | {matchingTabs.length === 0 && ( |
| 447 | <p className="favorites-empty">没有匹配的标签页</p> |
| 448 | )} |
| 449 | {matchingTabs.map((tab) => ( |
| 450 | <button |
| 451 | key={tab.id} |
| 452 | title={tab.url} |
| 453 | onClick={() => { |
| 454 | setAllOpen(false); |
| 455 | onSelect(tab.id); |
| 456 | }} |
| 457 | > |
| 458 | <TabIcon kind={tab.kind} favicon={tab.favicon} |
| 459 | agent={tab.terminalKind === "claude" || tab.terminalKind === "claude-login" || Boolean(tab.cli_session_id) || Boolean(tab.claude_account_id)} |
| 460 | accountNumber={tab.claudeAccountNumber} /> |
| 461 | <span>{tabName(tab, saved)}</span> |
| 462 | {tab.id === active && ( |
| 463 | <span className="current-tab-marker">当前</span> |
| 464 | )} |
| 465 | </button> |
| 466 | ))} |
| 467 | </div> |
| 468 | </div> |
| 469 | </> |
| 470 | )} |
| 471 | </div> |
| 472 | )} |
| 473 | {menu && |
| 474 | createPortal( |
| 475 | <> |
| 476 | <div className="menu-dismiss" onClick={() => setMenu(null)} /> |
| 477 | {actions} |
| 478 | </>, |
| 479 | document.body, |
| 480 | )} |
| 481 | </> |
| 482 | ); |
| 483 | } |