diff --git a/src/lib/components/chat/Chat.svelte b/src/lib/components/chat/Chat.svelte index 5639e41653..8ff4773fa8 100644 --- a/src/lib/components/chat/Chat.svelte +++ b/src/lib/components/chat/Chat.svelte @@ -3880,6 +3880,8 @@ let terminalTabs: ChatTabs; let fullWidthTabs = false; let mainChatActive = false; + let mainChatStyle = ''; + let mainChatGroupId = ''; let tabTitleEditor: import('svelte').Snippet | undefined; let tabActions: import('svelte').Snippet | undefined; @@ -5304,14 +5306,15 @@ > {/if} -
+
fullWidthTabs && terminalTabs?.focusMainChat()} + on:pointerdown={() => fullWidthTabs && terminalTabs?.focusMainChat()} id={fullWidthTabs ? 'chat-panel-main-chat-view' : undefined} role={fullWidthTabs ? 'tabpanel' : undefined} aria-labelledby={fullWidthTabs ? 'chat-panel-main-chat' : undefined} @@ -5726,6 +5729,8 @@ group.activeId === mainChatTabId); + $: mainChatGroupId = tabs.groups.find((group) => group.tabIds.includes(mainChatTabId))?.id ?? ''; + $: mainChatStyle = + fullWidth && positions.groups[mainChatGroupId] + ? paneStyle(positions.groups[mainChatGroupId], 36, footerHeight) + : ''; $: if (fullWidth !== tabs.tabs.some((tab) => tab.id === mainChatTabId)) { tabs = setFullWidthTabs(tabs, fullWidth, title); if (fullWidth) void tick().then(() => document.getElementById(domId(tabs.activeId))?.focus()); @@ -125,7 +142,35 @@ let viewportWidth = 0; let tabs = emptyTabs(); - let sideChatNumber = 0; + $: positions = largeScreen + ? panelPositions(tabs.layout) + : { + groups: { [tabs.activeGroupId]: { left: 0, top: 0, width: 1, height: 1 } }, + dividers: [] + }; + $: tabGroups = Object.fromEntries( + tabs.groups.flatMap((group) => group.tabIds.map((id) => [id, group])) + ); + $: displayedGroups = largeScreen + ? tabs.groups + : [ + { + id: tabs.activeGroupId, + tabIds: tabs.groups.flatMap((group) => group.tabIds), + activeId: tabs.activeId + } + ]; + $: visibleTabIds = new Set( + tabs.groups + .filter((group) => largeScreen || group.id === tabs.activeGroupId) + .map((group) => group.activeId) + ); + const paneStyle = (rect: PanelRect, header = 0, footer = 0) => + `position:absolute;left:${rect.left * 100}%;top:calc((100% - ${footer}px) * ${rect.top} + ${header}px);width:${rect.width * 100}%;height:calc((100% - ${footer}px) * ${rect.height} - ${header}px);`; + const focusGroup = (id: string) => { + const group = tabs.groups.find((group) => group.id === id); + if (group?.activeId) tabs = activateTab(tabs, group.activeId); + }; let terminalViews: Record = {}; export const hasTerminals = () => tabs.tabs.some((tab) => tab.kind === 'terminal'); export async function bindTerminalChat(id: string) { @@ -231,6 +276,9 @@ ); } + export const focusMainChat = () => { + tabs = activateTab(tabs, mainChatTabId); + }; const selectTab = (id: string) => { tabs = activateTab(tabs, id); showTabs.set(true); @@ -288,13 +336,17 @@ if (!availableViews.some((view) => view.kind === kind && view.available)) return; const view = availableViews.find((view) => view.kind === kind)!; if (kind === 'side') { + let sideChatNumber = 1; + while (tabs.tabs.some((tab) => tab.kind === 'side' && tab.sideChatNumber === sideChatNumber)) + sideChatNumber++; const pending = $sideChatRequest; const initialPrompt = pending?.parentId === chatId ? pending.prompt : ''; if (pending?.parentId === chatId) sideChatRequest.set(null); openPanel({ id: crypto.randomUUID(), kind, - label: `${view.label} ${++sideChatNumber}`, + label: `${view.label} ${sideChatNumber}`, + sideChatNumber, initialPrompt }); return; @@ -309,30 +361,68 @@ ) }; }; - let chatDropPreview: { left: number; top: number; width: number; height: number } | null = null; + type SplitDrop = PanelRect & { groupId: string; edge: SplitEdge | null; main: boolean }; + let chatDropPreview: SplitDrop | null = null; + let draggedTabId = ''; + let pendingTabDrop: (() => void) | null = null; const clearChatDropPreview = () => (chatDropPreview = null); const canDropChat = (event: DragEvent) => canSideChat && ($user?.role === 'admin' || !($user?.permissions?.chat?.temporary_enforced ?? false)) && event.dataTransfer?.types.includes('application/x-open-webui-chat'); - const chatDropBounds = (event: DragEvent) => { - if (!canDropChat(event) || !(event.target instanceof Element)) return null; - if (event.target.closest('[data-composer-id]')) return null; + const chatDropBounds = (event: DragEvent): SplitDrop | null => { + const internal = event.dataTransfer?.types.includes('application/x-chat-panel-tab'); + if ((!internal && !canDropChat(event)) || !(event.target instanceof Element)) return null; + if (!internal && event.target.closest('[data-composer-id]')) return null; + const group = event.target.closest('[data-panel-group]'); const panel = event.target.closest('#controls-container'); - const canvas = event.target.closest('#chat-container'); - const rect = (panel && !fullWidth ? panel : canvas)?.getBoundingClientRect(); + const main = !group && !panel; + const element = + group ?? + panel ?? + event.target.closest('[data-main-chat-pane]') ?? + event.target.closest('#chat-container'); + const rect = element?.getBoundingClientRect(); if (!rect?.width || !rect.height) return null; - if (panel) return rect; - if (event.clientX < rect.right - rect.width * 0.3) return null; - const width = largeScreen - ? Math.min(Math.max(280, controlsWidth), Math.max(280, rect.width - 360), rect.width) - : rect.width; - return { left: rect.right - width, top: rect.top, width, height: rect.height }; + const groupId = group?.dataset.panelGroup ?? (panel ? tabs.activeGroupId : ''); + const inTabBar = !!event.target.closest('[data-panel-tab-bar]'); + const edges: { edge: SplitEdge; distance: number }[] = []; + if (largeScreen && !inTabBar) { + if (event.clientX - rect.left <= rect.width * 0.3) + edges.push({ edge: 'left', distance: event.clientX - rect.left }); + if (rect.right - event.clientX <= rect.width * 0.3) + edges.push({ edge: 'right', distance: rect.right - event.clientX }); + if (event.clientY - rect.top <= rect.height * 0.3) + edges.push({ edge: 'top', distance: event.clientY - rect.top }); + if (rect.bottom - event.clientY <= rect.height * 0.3) + edges.push({ edge: 'bottom', distance: rect.bottom - event.clientY }); + } + const edge = edges.sort((a, b) => a.distance - b.distance)[0]?.edge ?? null; + if (main && !edge) return null; + const source = tabs.groups.find((item) => item.tabIds.includes(draggedTabId)); + if (internal && source?.id === groupId && (!edge || (fullWidth && source.tabIds.length === 1))) + return null; + const width = edge === 'left' || edge === 'right' ? rect.width / 2 : rect.width; + const height = edge === 'top' || edge === 'bottom' ? rect.height / 2 : rect.height; + return { + groupId, + edge, + main, + width, + height, + left: rect.left + (edge === 'right' ? width : 0), + top: rect.top + (edge === 'bottom' ? height : 0) + }; }; export const dragOverChat = (event: DragEvent) => { chatDropPreview = chatDropBounds(event); if (chatDropPreview || event.dataTransfer?.types.includes('Files')) event.preventDefault(); - if (chatDropPreview) event.dataTransfer!.dropEffect = 'copy'; + if (chatDropPreview) + event.dataTransfer!.dropEffect = event.dataTransfer!.types.includes( + 'application/x-chat-panel-tab' + ) + ? 'move' + : 'copy'; }; export const leaveChatDrop = (event: DragEvent) => { if (!(event.currentTarget as HTMLElement).contains(event.relatedTarget as Node)) @@ -342,25 +432,75 @@ const bounds = chatDropBounds(event); clearChatDropPreview(); if (event.dataTransfer?.types.includes('Files')) event.preventDefault(); - if (!bounds) return; - let item; - try { - item = JSON.parse(event.dataTransfer!.getData('text/plain')); - } catch { - return; + if (!bounds || pendingTabDrop) return; + const internalId = event.dataTransfer?.getData('application/x-chat-panel-tab'); + let savedId = ''; + if (internalId) { + if (!tabs.tabs.some((tab) => tab.id === internalId)) return; + } else { + try { + const item = JSON.parse(event.dataTransfer!.getData('text/plain')); + if (item?.type !== 'chat' || typeof item.id !== 'string' || !item.id.trim()) return; + savedId = item.id; + } catch { + return; + } } - if (item?.type !== 'chat' || typeof item.id !== 'string' || !item.id.trim()) return; event.preventDefault(); - event.stopPropagation(); - if (item.id === chatId) { - if (fullWidth) selectTab(mainChatTabId); - return; + const applyDrop = () => { + let groupId = bounds.groupId; + if (bounds.edge || bounds.main || savedId === chatId) { + expanded = true; + tabs = setFullWidthTabs(tabs, true, title); + if (bounds.main) { + groupId = tabs.groups.find((group) => group.tabIds.includes(mainChatTabId))!.id; + tabs = activateTab(tabs, mainChatTabId); + } + } + const existing = + internalId || + (savedId === chatId ? mainChatTabId : tabs.tabs.find((tab) => tab.chatId === savedId)?.id); + let id = existing; + if (!id) { + focusGroup(groupId); + id = crypto.randomUUID(); + tabs = openTab(tabs, { id, kind: 'side', label: $i18n.t('Chat'), chatId: savedId }); + } + tabs = bounds.edge + ? splitTab(tabs, id, groupId, bounds.edge) + : moveTabToGroup(tabs, id, groupId); + showTabs.set(true); + }; + if (internalId) { + // Let Sortable restore its source DOM before changing the keyed tab groups. + tabDropHandled = true; + pendingTabDrop = applyDrop; + } else { + event.stopPropagation(); + applyDrop(); } - if (!$showTabs) expanded = false; - const existing = tabs.tabs.find((tab) => tab.kind === 'side' && tab.chatId === item.id); - if (existing) selectTab(existing.id); - else - openPanel({ id: crypto.randomUUID(), kind: 'side', label: $i18n.t('Chat'), chatId: item.id }); + }; + + let resizingSplit: PanelDivider | null = null; + const startSplitResize = (event: PointerEvent, divider: PanelDivider) => { + event.preventDefault(); + resizingSplit = divider; + dragged = true; + (event.currentTarget as HTMLElement).setPointerCapture(event.pointerId); + }; + const moveSplitResize = (event: PointerEvent) => { + if (!resizingSplit || !paneCanvas) return; + const rect = paneCanvas.getBoundingClientRect(); + const split = resizingSplit; + const ratio = + split.direction === 'horizontal' + ? ((event.clientX - rect.left) / rect.width - split.left) / split.width + : ((event.clientY - rect.top) / rect.height - split.top) / split.height; + tabs = { ...tabs, layout: resizeSplit(tabs.layout, split.id, ratio) }; + }; + const endSplitResize = () => { + resizingSplit = null; + dragged = false; }; const newTerminal = () => { if (!terminalEnabled || !selectedConnection) return; @@ -459,6 +599,7 @@ closing.delete(id); } }; + let tabDropHandled = false; const sortableTabs = (node: HTMLElement) => { let nextSibling: ChildNode | null = null; const sortable = new Sortable(node, { @@ -474,21 +615,23 @@ transfer.setData('application/x-chat-panel-tab', item.dataset.panelTab ?? ''), onStart: ({ item }: { item: HTMLElement }) => { nextSibling = item.nextSibling; + tabDropHandled = false; + draggedTabId = item.dataset.panelTab ?? ''; dragged = true; }, - onEnd: ({ - item, - from, - newDraggableIndex - }: { - item: HTMLElement; - from: HTMLElement; - newDraggableIndex?: number; - }) => { + onEnd: ({ item, from }: { item: HTMLElement; from: HTMLElement }) => { + const id = item.dataset.panelTab!; + const group = tabGroups[id]; + const order = Array.from(from.querySelectorAll('[data-panel-tab]')) + .map((tab) => tab.dataset.panelTab!) + .filter((tabId) => group?.tabIds.includes(tabId)); // Restore the DOM before Svelte reconciles its keyed tabs. from.insertBefore(item, nextSibling?.parentNode === from ? nextSibling : null); - if (newDraggableIndex != null) - tabs = moveTab(tabs, item.dataset.panelTab!, newDraggableIndex + (fullWidth ? 1 : 0)); + if (!tabDropHandled) tabs = moveTab(tabs, id, order.indexOf(id)); + const drop = pendingTabDrop; + pendingTabDrop = null; + drop?.(); + draggedTabId = ''; dragged = false; } }); @@ -497,21 +640,24 @@ const navigateTabs = (event: KeyboardEvent) => { if (!(event.target instanceof HTMLElement) || event.target.getAttribute('role') !== 'tab') return; - const index = tabs.tabs.findIndex((tab) => tab.id === tabs.activeId); + const group = displayedGroups.find((group) => group.id === tabs.activeGroupId)!; + const index = group.tabIds.indexOf(tabs.activeId); if (event.altKey && event.shiftKey && ['ArrowLeft', 'ArrowRight'].includes(event.key)) { event.preventDefault(); - tabs = moveTab(tabs, tabs.activeId, index + (event.key === 'ArrowLeft' ? -1 : 1)); + const tabIndex = tabGroups[tabs.activeId].tabIds.indexOf(tabs.activeId); + tabs = moveTab(tabs, tabs.activeId, tabIndex + (event.key === 'ArrowLeft' ? -1 : 1)); return; } let next = index; - if (event.key === 'ArrowRight') next = (index + 1) % tabs.tabs.length; - else if (event.key === 'ArrowLeft') next = (index - 1 + tabs.tabs.length) % tabs.tabs.length; + if (event.key === 'ArrowRight') next = (index + 1) % group.tabIds.length; + else if (event.key === 'ArrowLeft') + next = (index - 1 + group.tabIds.length) % group.tabIds.length; else if (event.key === 'Home') next = 0; - else if (event.key === 'End') next = tabs.tabs.length - 1; + else if (event.key === 'End') next = group.tabIds.length - 1; else return; event.preventDefault(); - selectTab(tabs.tabs[next].id); - document.getElementById(domId(tabs.tabs[next].id))?.focus(); + selectTab(group.tabIds[next]); + document.getElementById(domId(group.tabIds[next]))?.focus(); }; $: hasMessages = history?.messages && Object.keys(history.messages).length > 0; @@ -687,7 +833,6 @@ $: if (chatId !== tabsChatId) { if (tabsChatId || !chatId) { tabs = setFullWidthTabs(emptyTabs(), fullWidth, title); - sideChatNumber = 0; hasOpenedTabs = false; dirtyFiles = {}; fileContexts = {}; @@ -914,12 +1059,244 @@ on:dragleave={leaveChatDrop} class:hidden={!$showTabs || !panelTarget} use:placePanel={$showTabs ? panelTarget : null} - class={fullWidth ? 'contents' : 'h-full w-full min-h-0 flex flex-col'} + class="h-full w-full min-h-0 flex flex-col {fullWidth + ? 'absolute inset-0 pointer-events-none' + : ''}" style:--chat-tabs-dark-background={'var(--color-gray-900)'} id="controls-container" > +
+ {#each displayedGroups as group (group.id)} + + {/each} + {#each positions.dividers as divider (divider.id)} + + {/each} + {#each tabs.tabs.filter((tab) => tab.kind !== 'chat') as tab (tab.id)} +
focusGroup(tabGroups[tab.id].id)} + on:pointerdown={() => focusGroup(tabGroups[tab.id].id)} + > + {#if tab.kind === 'voice'} + closeTab(tab.id)} + /> + {:else if tab.kind === 'preview'} + + {:else if tab.kind === 'artifacts'} + + {:else if tab.kind === 'side'} + updateSideChat(tab.id, chat)} + parentChatId={chatId ?? ''} + parentFolderId={folderId} + {history} + {modelId} + {systemPrompt} + initialPrompt={tab.initialPrompt ?? ''} + /> + {:else if tab.kind === 'comments' && currentComments} + {#key `${$user?.id}:${chatId}:${currentComments.comment_id ?? ''}`} + + {/key} + {:else if tab.kind === 'desktop' && tab.connection} + + {:else if tab.kind === 'browser'} + openBrowser(undefined, tab.terminalId, tab.browserBaseUrl, url)} + overlay={dragged} + onNavigate={(path, label) => { + tabs = { + ...tabs, + tabs: tabs.tabs.map((item) => + item.id === tab.id ? { ...item, path, label } : item + ) + }; + }} + /> + {:else if tab.kind === 'terminal' && tab.connection} + + {:else if tab.untitled && tab.connection} + + tabs.tabs.some( + (item) => + item.id !== tab.id && + item.kind === 'file' && + !item.untitled && + item.terminalId === tab.terminalId && + item.path === path + )} + onSaved={(path) => { + tabs = { + ...tabs, + tabs: tabs.tabs.map((item) => + item.id === tab.id + ? { + ...item, + untitled: false, + dirty: false, + path, + label: path.split('/').pop() || path + } + : item + ) + }; + }} + /> + {:else if (tab.kind === 'files' || tab.kind === 'file') && tab.terminalId} + openFile(path, tab.terminalId!, page)} + onBrowseDirectory={(path) => openFiles(tab.terminalId, path)} + {onAskFile} + overlay={dragged} + {chatId} + bind:terminalContext={fileContexts[tab.id]} + /> + {:else if tab.kind === 'files' && codeInterpreterEnabled} + + {/if} +
+ {/each} + {#if !tabs.tabs.length && canOpenNewTab}
+ {$i18n.t('Open a tab using the + menu.')} +
{/if} +
+ {#if gitConnection && tabs.tabs.length} + openFile(path, gitConnection.selector)} + onOpenDirectory={(path) => openFiles(gitConnection.selector, path)} + /> + {/if} +
+
+ +{#snippet tabBar(group: PanelGroup)} +
- {#each tabs.tabs as tab (tab.id)} + {#each group.tabIds.map((id) => tabs.tabs.find((tab) => tab.id === id)!) as tab (tab.id)}
selectTab(tab.id)} - class="panel-tab flex cursor-pointer items-center gap-1.5 ps-2.5 pe-2 h-7 rounded-lg text-sm font-normal whitespace-nowrap shrink-0 transition {tabs.activeId === + class="panel-tab flex cursor-pointer items-center gap-1.5 ps-2.5 pe-2 h-7 rounded-lg text-sm font-normal whitespace-nowrap shrink-0 transition {group.activeId === tab.id ? 'bg-gray-100/40 dark:bg-gray-800/25 text-gray-700 dark:text-gray-200' : 'text-gray-500 dark:text-gray-400 hover:bg-gray-100/30 dark:hover:bg-gray-800/20 hover:text-gray-600 dark:hover:text-gray-300'}" @@ -961,8 +1338,8 @@ : 'Alt+Shift+ArrowLeft Alt+Shift+ArrowRight'} id={domId(tab.id)} aria-controls={`${domId(tab.id)}-view`} - aria-selected={tabs.activeId === tab.id} - tabindex={tabs.activeId === tab.id ? 0 : -1} + aria-selected={group.activeId === tab.id} + tabindex={group.activeId === tab.id ? 0 : -1} title={tab.kind === 'chat' ? title : (tab.path ?? tab.label)} aria-label={tab.kind === 'chat' ? title : undefined} class="flex h-full items-center gap-1.5 min-w-0" @@ -1047,7 +1424,7 @@ {/if}
- {#if largeScreen} + {#if largeScreen && group.id === tabs.groups[0].id} {/if} - {#if !fullWidth} + {#if !fullWidth && (!largeScreen || group.id === tabs.groups[0].id)}
-
- {#each tabs.tabs.filter((tab) => tab.kind !== 'chat') as tab (tab.id)} -
- {#if tab.kind === 'voice'} - closeTab(tab.id)} - /> - {:else if tab.kind === 'preview'} - - {:else if tab.kind === 'artifacts'} - - {:else if tab.kind === 'side'} - updateSideChat(tab.id, chat)} - parentChatId={chatId ?? ''} - parentFolderId={folderId} - {history} - {modelId} - {systemPrompt} - initialPrompt={tab.initialPrompt ?? ''} - /> - {:else if tab.kind === 'comments' && currentComments} - {#key `${$user?.id}:${chatId}:${currentComments.comment_id ?? ''}`} - - {/key} - {:else if tab.kind === 'desktop' && tab.connection} - - {:else if tab.kind === 'browser'} - openBrowser(undefined, tab.terminalId, tab.browserBaseUrl, url)} - overlay={dragged} - onNavigate={(path, label) => { - tabs = { - ...tabs, - tabs: tabs.tabs.map((item) => - item.id === tab.id ? { ...item, path, label } : item - ) - }; - }} - /> - {:else if tab.kind === 'terminal' && tab.connection} - - {:else if tab.untitled && tab.connection} - - tabs.tabs.some( - (item) => - item.id !== tab.id && - item.kind === 'file' && - !item.untitled && - item.terminalId === tab.terminalId && - item.path === path - )} - onSaved={(path) => { - tabs = { - ...tabs, - tabs: tabs.tabs.map((item) => - item.id === tab.id - ? { - ...item, - untitled: false, - dirty: false, - path, - label: path.split('/').pop() || path - } - : item - ) - }; - }} - /> - {:else if (tab.kind === 'files' || tab.kind === 'file') && tab.terminalId} - openFile(path, tab.terminalId!, page)} - onBrowseDirectory={(path) => openFiles(tab.terminalId, path)} - {onAskFile} - overlay={dragged} - {chatId} - bind:terminalContext={fileContexts[tab.id]} - /> - {:else if tab.kind === 'files' && codeInterpreterEnabled} - - {/if} -
- {/each} - {#if !tabs.tabs.length && canOpenNewTab}
- {$i18n.t('Open a tab using the + menu.')} -
{/if} -
-
- {#if gitConnection && tabs.tabs.length} - openFile(path, gitConnection.selector)} - onOpenDirectory={(path) => openFiles(gitConnection.selector, path)} - /> - {/if} -
-
+{/snippet} {#if !largeScreen}
{#if fullWidth} - +
{/if} {/if} diff --git a/src/lib/components/chat/ChatTabs/tabs.ts b/src/lib/components/chat/ChatTabs/tabs.ts index e04e5f87aa..3ad38c51f8 100644 --- a/src/lib/components/chat/ChatTabs/tabs.ts +++ b/src/lib/components/chat/ChatTabs/tabs.ts @@ -19,6 +19,7 @@ export type PanelTab = { label: string; initialPrompt?: string; chatId?: string; + sideChatNumber?: number; terminalId?: string; terminalNumber?: number; path?: string; @@ -29,26 +30,71 @@ export type PanelTab = { browserBaseUrl?: string; context?: TerminalContext | null; }; -export type PanelTabs = { tabs: PanelTab[]; activeId: string; history: string[] }; - -export const emptyTabs = (): PanelTabs => ({ tabs: [], activeId: '', history: [] }); +export type PanelGroup = { id: string; tabIds: string[]; activeId: string }; +export type SplitEdge = 'left' | 'right' | 'top' | 'bottom'; +export type PanelLayout = + | { type: 'group'; groupId: string } + | { + type: 'split'; + id: string; + direction: 'horizontal' | 'vertical'; + ratio: number; + first: PanelLayout; + second: PanelLayout; + }; +export type PanelTabs = { + tabs: PanelTab[]; + activeId: string; + history: string[]; + groups: PanelGroup[]; + activeGroupId: string; + layout: PanelLayout; +}; +export type PanelRect = { left: number; top: number; width: number; height: number }; +export type PanelDivider = PanelRect & { + id: string; + direction: 'horizontal' | 'vertical'; + ratio: number; +}; +export const emptyTabs = (): PanelTabs => ({ + tabs: [], + activeId: '', + history: [], + groups: [{ id: 'default', tabIds: [], activeId: '' }], + activeGroupId: 'default', + layout: { type: 'group', groupId: 'default' } +}); export const mainChatTabId = 'main-chat'; export function setFullWidthTabs(state: PanelTabs, fullWidth: boolean, label = 'Chat'): PanelTabs { if (!fullWidth) return removeTab(state, mainChatTabId); if (state.tabs.some((tab) => tab.id === mainChatTabId)) return state; - return activateTab( - { ...state, tabs: [{ id: mainChatTabId, kind: 'chat', label }, ...state.tabs] }, - state.activeId || mainChatTabId - ); + const groupId = state.activeGroupId; + const next = { + ...state, + tabs: [{ id: mainChatTabId, kind: 'chat' as const, label }, ...state.tabs], + groups: state.groups.map((group) => + group.id === groupId + ? { + ...group, + tabIds: [mainChatTabId, ...group.tabIds], + activeId: group.activeId || mainChatTabId + } + : group + ) + }; + return activateTab(next, state.activeId || mainChatTabId); } export function activateTab(state: PanelTabs, id: string): PanelTabs { - if (!state.tabs.some((tab) => tab.id === id) || state.activeId === id) return state; + const group = state.groups.find((group) => group.tabIds.includes(id)); + if (!group || (state.activeId === id && group.activeId === id)) return state; return { ...state, activeId: id, + activeGroupId: group.id, + groups: state.groups.map((item) => (item.id === group.id ? { ...item, activeId: id } : item)), history: [ ...state.history.filter((entry) => entry !== id && entry !== state.activeId), state.activeId @@ -60,34 +106,160 @@ export function openTab(state: PanelTabs, tab: PanelTab): PanelTabs { return activateTab( state.tabs.some((item) => item.id === tab.id) ? state - : { ...state, tabs: [...state.tabs, tab] }, + : { + ...state, + tabs: [...state.tabs, tab], + groups: state.groups.map((group) => + group.id === state.activeGroupId + ? { ...group, tabIds: [...group.tabIds, tab.id] } + : group + ) + }, tab.id ); } -export function removeTab(state: PanelTabs, id: string): PanelTabs { - const tabs = state.tabs.filter((tab) => tab.id !== id); - const history = state.history.filter( - (entry) => entry !== id && tabs.some((tab) => tab.id === entry) - ); - const index = state.tabs.findIndex((tab) => tab.id === id); +function removeLayoutGroup(layout: PanelLayout, groupId: string): PanelLayout | null { + if (layout.type === 'group') return layout.groupId === groupId ? null : layout; + const first = removeLayoutGroup(layout.first, groupId); + const second = removeLayoutGroup(layout.second, groupId); + return first && second ? { ...layout, first, second } : (first ?? second); +} + +function removeFromGroup(state: PanelTabs, id: string): PanelTabs { + const source = state.groups.find((group) => group.tabIds.includes(id)); + if (!source) return state; + const tabIds = source.tabIds.filter((tabId) => tabId !== id); + const activeId = + source.activeId === id + ? ([...state.history].reverse().find((tabId) => tabIds.includes(tabId)) ?? + tabIds[Math.max(0, source.tabIds.indexOf(id) - 1)] ?? + '') + : source.activeId; + const groups = + tabIds.length || state.groups.length === 1 + ? state.groups.map((group) => + group.id === source.id ? { ...group, tabIds, activeId } : group + ) + : state.groups.filter((group) => group.id !== source.id); + const activeGroup = groups.find((group) => group.id === state.activeGroupId) ?? groups[0]; return { - tabs, - activeId: - state.activeId === id - ? (history.at(-1) ?? tabs[Math.max(0, index - 1)]?.id ?? '') - : state.activeId, - history + ...state, + groups, + activeGroupId: activeGroup.id, + activeId: activeGroup.activeId, + layout: groups.some((group) => group.id === source.id) + ? state.layout + : removeLayoutGroup(state.layout, source.id)!, + history: state.history.filter((entry) => entry !== id) }; } +export function removeTab(state: PanelTabs, id: string): PanelTabs { + if (!state.tabs.some((tab) => tab.id === id)) return state; + return { ...removeFromGroup(state, id), tabs: state.tabs.filter((tab) => tab.id !== id) }; +} + export function moveTab(state: PanelTabs, id: string, to: number): PanelTabs { - const from = state.tabs.findIndex((tab) => tab.id === id); - if (id === mainChatTabId || state.tabs[to]?.id === mainChatTabId) return state; - if (from < 0 || to < 0 || to >= state.tabs.length || from === to) return state; - const tabs = [...state.tabs]; - tabs.splice(to, 0, tabs.splice(from, 1)[0]); - return { ...state, tabs }; + const group = state.groups.find((group) => group.tabIds.includes(id)); + if (!group) return state; + const from = group.tabIds.indexOf(id); + if (to < 0 || to >= group.tabIds.length || from === to) return state; + const tabIds = [...group.tabIds]; + tabIds.splice(to, 0, tabIds.splice(from, 1)[0]); + return { + ...state, + groups: state.groups.map((item) => (item.id === group.id ? { ...item, tabIds } : item)) + }; +} + +export function moveTabToGroup(state: PanelTabs, id: string, groupId: string): PanelTabs { + const target = state.groups.find((group) => group.id === groupId); + if (!target || !state.tabs.some((tab) => tab.id === id)) return state; + if (target.tabIds.includes(id)) return activateTab(state, id); + const next = removeFromGroup(state, id); + return activateTab( + { + ...next, + groups: next.groups.map((group) => + group.id === groupId ? { ...group, tabIds: [...group.tabIds, id] } : group + ) + }, + id + ); +} + +export function splitTab( + state: PanelTabs, + id: string, + groupId: string, + edge: SplitEdge +): PanelTabs { + const source = state.groups.find((group) => group.tabIds.includes(id)); + if (!source || !state.groups.some((group) => group.id === groupId)) return state; + if (source.id === groupId && source.tabIds.length === 1) return state; + const next = removeFromGroup(state, id); + const newGroup: PanelGroup = { id: crypto.randomUUID(), tabIds: [id], activeId: id }; + const replace = (layout: PanelLayout): PanelLayout => { + if (layout.type === 'group') { + if (layout.groupId !== groupId) return layout; + const leaf: PanelLayout = { type: 'group', groupId: newGroup.id }; + const before = edge === 'left' || edge === 'top'; + return { + type: 'split', + id: crypto.randomUUID(), + direction: edge === 'left' || edge === 'right' ? 'horizontal' : 'vertical', + ratio: 0.5, + first: before ? leaf : layout, + second: before ? layout : leaf + }; + } + return { ...layout, first: replace(layout.first), second: replace(layout.second) }; + }; + return activateTab( + { ...next, groups: [...next.groups, newGroup], layout: replace(next.layout) }, + id + ); +} + +export function resizeSplit(layout: PanelLayout, id: string, ratio: number): PanelLayout { + if (layout.type === 'group') return layout; + if (layout.id === id) return { ...layout, ratio: Math.max(0.2, Math.min(0.8, ratio)) }; + return { + ...layout, + first: resizeSplit(layout.first, id, ratio), + second: resizeSplit(layout.second, id, ratio) + }; +} + +// Flat positions keep every tab view mounted when the split tree changes. +export function panelPositions(layout: PanelLayout) { + const groups: Record = {}; + const dividers: PanelDivider[] = []; + const visit = (node: PanelLayout, rect: PanelRect) => { + if (node.type === 'group') { + groups[node.groupId] = rect; + return; + } + dividers.push({ ...rect, id: node.id, direction: node.direction, ratio: node.ratio }); + if (node.direction === 'horizontal') { + visit(node.first, { ...rect, width: rect.width * node.ratio }); + visit(node.second, { + ...rect, + left: rect.left + rect.width * node.ratio, + width: rect.width * (1 - node.ratio) + }); + } else { + visit(node.first, { ...rect, height: rect.height * node.ratio }); + visit(node.second, { + ...rect, + top: rect.top + rect.height * node.ratio, + height: rect.height * (1 - node.ratio) + }); + } + }; + visit(layout, { left: 0, top: 0, width: 1, height: 1 }); + return { groups, dividers }; } export const fileTabId = (terminalId: string, path: string) =>