466 lines
19 KiB
Svelte
466 lines
19 KiB
Svelte
<script lang="ts">
|
||
import { t } from "$lib/i18n";
|
||
import { onDestroy, tick } from "svelte";
|
||
import { actionMenu, type ActionMenuItem } from "$lib/ui/actionMenu";
|
||
import { actionIcons } from "$lib/ui/actionIcons";
|
||
import TabIcon from "$lib/ui/TabIcon.svelte";
|
||
import { attachTooltip } from "$lib/ui/tooltip";
|
||
|
||
function tabTooltip(node: HTMLElement, label: string) {
|
||
let text = label;
|
||
const dispose = attachTooltip(node, () => text);
|
||
return { update(value: string) { text = value; }, destroy: dispose };
|
||
}
|
||
import { tabsToClose, type TabCloseScope } from "$lib/workspace/tabActions";
|
||
import type { WorkbenchTab } from "$lib/workspace/workbenchTabs";
|
||
|
||
type Props = {
|
||
tabs: WorkbenchTab[];
|
||
activePath: string | null;
|
||
onSelect: (relPath: string) => void;
|
||
onClose: (relPath: string) => void;
|
||
onMove: (relPath: string, index: number) => void;
|
||
onCloseTabs: (relPath: string, scope: TabCloseScope) => void;
|
||
onPin: (relPath: string) => void;
|
||
fileActions: (tab: WorkbenchTab) => ActionMenuItem[];
|
||
tabActions?: (tab: WorkbenchTab) => ActionMenuItem[];
|
||
tabDragData?: (tab: WorkbenchTab) => string | undefined;
|
||
onDropTab?: (data: string, index: number) => void;
|
||
onDetach?: (tab: WorkbenchTab) => void;
|
||
};
|
||
|
||
let { tabs, activePath, onSelect, onClose, onMove, onCloseTabs, onPin, fileActions, tabActions = () => [], tabDragData = () => undefined, onDropTab, onDetach }: Props = $props();
|
||
const transferType = "application/x-runestone-tab";
|
||
let bar: HTMLDivElement;
|
||
let dragged = $state<string | null>(null);
|
||
let dropBefore = $state<string | null>(null);
|
||
let dropAfter = $state<string | null>(null);
|
||
let announcement = $state("");
|
||
let cancelDrag = () => {};
|
||
let suppressClick = false;
|
||
let menu: HTMLElement | undefined;
|
||
let menuAnchor: HTMLButtonElement | undefined;
|
||
let menuPath = $state<string | null>(null);
|
||
let receiving = $state(false);
|
||
let transferFrame = 0;
|
||
let transferX = 0;
|
||
|
||
function scrollTransfer() {
|
||
if (!receiving) { transferFrame = 0; return; }
|
||
const bounds = bar.getBoundingClientRect();
|
||
const speed = transferX < bounds.left + 28 ? -10 : transferX > bounds.right - 28 ? 10 : 0;
|
||
if (speed) { bar.scrollLeft += speed; transferIndex(transferX); }
|
||
transferFrame = requestAnimationFrame(scrollTransfer);
|
||
}
|
||
|
||
function startTabTransfer(event: DragEvent, tab: WorkbenchTab) {
|
||
const data = tabDragData(tab);
|
||
if (!data || !event.dataTransfer) { event.preventDefault(); return; }
|
||
cancelDrag(); closeMenu();
|
||
dragged = tab.relPath;
|
||
suppressClick = true;
|
||
event.dataTransfer.effectAllowed = "move";
|
||
event.dataTransfer.setData(transferType, data);
|
||
}
|
||
|
||
function transferIndex(x: number) {
|
||
const others = [...bar.querySelectorAll<HTMLElement>(".tab")].filter(row => row.dataset.path !== dragged);
|
||
const before = others.findIndex(row => { const bounds = row.getBoundingClientRect(); return x < bounds.left + bounds.width / 2; });
|
||
dropBefore = before < 0 ? null : others[before].dataset.path!;
|
||
dropAfter = before < 0 ? others.at(-1)?.dataset.path ?? null : null;
|
||
return before < 0 ? others.length : before;
|
||
}
|
||
|
||
function dragOver(event: DragEvent) {
|
||
if (!event.dataTransfer?.types.includes(transferType) || (!dragged && !onDropTab)) return;
|
||
event.preventDefault();
|
||
event.dataTransfer.dropEffect = "move";
|
||
receiving = true;
|
||
transferX = event.clientX;
|
||
if (!transferFrame) transferFrame = requestAnimationFrame(scrollTransfer);
|
||
const bounds = bar.getBoundingClientRect();
|
||
if (event.clientX < bounds.left + 28) bar.scrollLeft -= 10;
|
||
else if (event.clientX > bounds.right - 28) bar.scrollLeft += 10;
|
||
transferIndex(event.clientX);
|
||
}
|
||
|
||
function finishTabTransfer() {
|
||
dragged = dropBefore = dropAfter = null; receiving = false; suppressClick = false;
|
||
cancelAnimationFrame(transferFrame); transferFrame = 0;
|
||
}
|
||
|
||
function clearTransferTarget() {
|
||
receiving = false; dropBefore = dropAfter = null;
|
||
cancelAnimationFrame(transferFrame); transferFrame = 0;
|
||
}
|
||
|
||
function nearRibbon(event: DragEvent) {
|
||
if (dragged || !onDropTab || !event.dataTransfer?.types.includes(transferType)) return false;
|
||
const header = bar?.closest(".header");
|
||
if (!header || (event.target instanceof Element && event.target.closest(".window-controls"))) return false;
|
||
const bounds = header.getBoundingClientRect();
|
||
return event.clientX >= bounds.left && event.clientX <= bounds.right
|
||
&& event.clientY >= bounds.top && event.clientY <= bounds.bottom + 24;
|
||
}
|
||
|
||
function ribbonDragOver(event: DragEvent) {
|
||
if (event.defaultPrevented) {
|
||
if (!(event.target instanceof Node) || !bar.contains(event.target)) clearTransferTarget();
|
||
return;
|
||
}
|
||
if (!nearRibbon(event)) { clearTransferTarget(); return; }
|
||
event.preventDefault();
|
||
event.dataTransfer!.dropEffect = "move";
|
||
clearTransferTarget();
|
||
receiving = true;
|
||
// The wider target accepts a transfer at the end. Tabs retain precise ordering.
|
||
dropAfter = tabs.at(-1)?.relPath ?? null;
|
||
}
|
||
|
||
function ribbonDrop(event: DragEvent) {
|
||
if (event.defaultPrevented || !nearRibbon(event)) { clearTransferTarget(); return; }
|
||
const data = event.dataTransfer?.getData(transferType);
|
||
if (!data) { clearTransferTarget(); return; }
|
||
event.preventDefault(); event.stopPropagation();
|
||
const index = tabs.length;
|
||
finishTabTransfer();
|
||
onDropTab?.(data, index);
|
||
}
|
||
|
||
function dropTab(event: DragEvent) {
|
||
const data = event.dataTransfer?.getData(transferType);
|
||
if (!data) return;
|
||
event.preventDefault(); event.stopPropagation();
|
||
const path = dragged, index = transferIndex(event.clientX);
|
||
finishTabTransfer();
|
||
if (path) void move(path, index);
|
||
else onDropTab?.(data, index);
|
||
}
|
||
|
||
$effect(() => {
|
||
if (menuPath && !tabs.some(tab => tab.relPath === menuPath)) closeMenu();
|
||
// A successful transfer can remove the drag source before dragend arrives.
|
||
if (dragged && !tabs.some(tab => tab.relPath === dragged)) finishTabTransfer();
|
||
});
|
||
|
||
function tabButton(path: string) {
|
||
return [...bar.querySelectorAll<HTMLButtonElement>('[role="tab"]')].find(button => button.dataset.path === path);
|
||
}
|
||
|
||
$effect(() => {
|
||
const path = activePath;
|
||
if (path) void tick().then(() => tabButton(path)?.scrollIntoView({ block: "nearest", inline: "nearest" }));
|
||
});
|
||
|
||
async function move(path: string, index: number) {
|
||
onMove(path, index);
|
||
await tick();
|
||
tabButton(path)?.focus();
|
||
const position = tabs.findIndex(tab => tab.relPath === path);
|
||
if (position >= 0) announcement = `${tabs[position].name}, position ${position + 1} of ${tabs.length}`;
|
||
}
|
||
|
||
function closeMenu(restoreFocus = false) {
|
||
menu?.remove();
|
||
menu = undefined;
|
||
menuPath = null;
|
||
if (restoreFocus) menuAnchor?.focus();
|
||
}
|
||
|
||
function showMenu(button: HTMLButtonElement, path: string, x: number, y: number) {
|
||
cancelDrag();
|
||
closeMenu();
|
||
menuAnchor = button;
|
||
const index = tabs.findIndex(tab => tab.relPath === path);
|
||
if (index < 0) return;
|
||
menuPath = path;
|
||
const run = (action: () => void) => () => { closeMenu(true); action(); };
|
||
const closing = (label: string, scope: TabCloseScope): ActionMenuItem => ({
|
||
label, icon: "close", disabled: !tabsToClose(tabs, path, scope).length,
|
||
run: run(() => onCloseTabs(path, scope)),
|
||
});
|
||
const wrapActions = (items: ActionMenuItem[]): ActionMenuItem[] => items.map(item => {
|
||
if ("separator" in item) return item;
|
||
return { ...item, run: item.run ? run(item.run) : undefined,
|
||
children: item.children ? wrapActions(item.children) : undefined };
|
||
});
|
||
menu = actionMenu(x, y, [
|
||
closing($t("Close"), "one"),
|
||
closing($t("Close others"), "others"),
|
||
closing($t("Close tabs after"), "after"),
|
||
closing($t("Close all"), "all"),
|
||
...(tabs[index].pinned !== undefined ? [
|
||
{ separator: true as const },
|
||
{ label: tabs[index].pinned ? $t("Unpin") : $t("Pin"), icon: "pin" as const, run: run(() => onPin(path)) },
|
||
] : []),
|
||
...wrapActions(tabActions(tabs[index])),
|
||
...(path === activePath ? wrapActions(fileActions(tabs[index])) : []),
|
||
{ separator: true },
|
||
{ label: $t("Move tab"), icon: "swap", children: [
|
||
{ label: $t("Move tab left"), icon: "move-left", disabled: index <= 0,
|
||
run: run(() => { void move(path, index - 1); }) },
|
||
{ label: $t("Move tab right"), icon: "move-right", disabled: index === tabs.length - 1,
|
||
run: run(() => { void move(path, index + 1); }) },
|
||
] },
|
||
], () => closeMenu(true), $t("Tab actions"));
|
||
menu.classList.add("tab-menu");
|
||
}
|
||
|
||
function onKey(event: KeyboardEvent, path: string) {
|
||
if (event.key === "Enter" || event.key === " ") suppressClick = false;
|
||
const index = tabs.findIndex(tab => tab.relPath === path);
|
||
if (event.key === "ContextMenu" || (event.shiftKey && event.key === "F10")) {
|
||
event.preventDefault();
|
||
event.stopPropagation();
|
||
const button = event.currentTarget as HTMLButtonElement, bounds = button.getBoundingClientRect();
|
||
showMenu(button, path, bounds.left, bounds.bottom);
|
||
} else if (["ArrowLeft", "ArrowRight", "Home", "End"].includes(event.key) && !event.ctrlKey && !event.metaKey) {
|
||
event.preventDefault();
|
||
event.stopPropagation();
|
||
const next = event.key === "Home" ? 0 : event.key === "End" ? tabs.length - 1
|
||
: Math.max(0, Math.min(tabs.length - 1, index + (event.key === "ArrowLeft" ? -1 : 1)));
|
||
if (event.altKey && event.shiftKey) void move(path, next);
|
||
else if (!event.altKey && !event.shiftKey) {
|
||
onSelect(tabs[next].relPath);
|
||
tabButton(tabs[next].relPath)?.focus();
|
||
}
|
||
}
|
||
}
|
||
|
||
function startDrag(event: PointerEvent, path: string) {
|
||
if (event.button !== 0 || !event.isPrimary) return;
|
||
cancelDrag();
|
||
closeMenu();
|
||
suppressClick = false;
|
||
const pointerTarget = event.currentTarget as HTMLElement;
|
||
pointerTarget.setPointerCapture(event.pointerId);
|
||
const startX = event.clientX, startY = event.clientY, pointerId = event.pointerId;
|
||
let x = startX, y = startY, started = false, destination: number | null = null, frame = 0;
|
||
const update = () => {
|
||
dropBefore = dropAfter = null;
|
||
destination = null;
|
||
const bounds = bar.getBoundingClientRect();
|
||
if (y < bounds.top || y > bounds.bottom) return;
|
||
const others = [...bar.querySelectorAll<HTMLElement>(".tab")].filter(row => row.dataset.path !== path);
|
||
const before = others.findIndex(row => { const rect = row.getBoundingClientRect(); return x < rect.left + rect.width / 2; });
|
||
destination = before < 0 ? others.length : before;
|
||
if (destination === tabs.findIndex(tab => tab.relPath === path)) return;
|
||
if (before >= 0) dropBefore = others[before].dataset.path!;
|
||
else dropAfter = others.at(-1)?.dataset.path ?? null;
|
||
};
|
||
const scroll = () => {
|
||
if (!started) return;
|
||
const bounds = bar.getBoundingClientRect();
|
||
if (y >= bounds.top && y <= bounds.bottom) {
|
||
const speed = x < bounds.left + 28 ? -10 : x > bounds.right - 28 ? 10 : 0;
|
||
if (speed) { bar.scrollLeft += speed; update(); }
|
||
}
|
||
frame = requestAnimationFrame(scroll);
|
||
};
|
||
const clean = () => {
|
||
if (pointerTarget.hasPointerCapture(pointerId)) pointerTarget.releasePointerCapture(pointerId);
|
||
cancelAnimationFrame(frame);
|
||
dragged = dropBefore = dropAfter = null;
|
||
window.removeEventListener("pointermove", onMovePointer);
|
||
window.removeEventListener("pointerup", onUp);
|
||
window.removeEventListener("pointercancel", clean);
|
||
window.removeEventListener("blur", clean);
|
||
window.removeEventListener("keydown", onEscape, true);
|
||
cancelDrag = () => {};
|
||
};
|
||
const onMovePointer = (e: PointerEvent) => {
|
||
if (e.pointerId !== pointerId) return;
|
||
x = e.clientX; y = e.clientY;
|
||
if (!started && Math.hypot(x - startX, y - startY) < 5) return;
|
||
e.preventDefault();
|
||
if (!started) { started = true; suppressClick = true; dragged = path; frame = requestAnimationFrame(scroll); }
|
||
update();
|
||
};
|
||
const onUp = (e: PointerEvent) => {
|
||
if (e.pointerId !== pointerId) return;
|
||
x = e.clientX; y = e.clientY;
|
||
if (started) update();
|
||
const target = destination;
|
||
clean();
|
||
if (started && target !== null) void move(path, target);
|
||
else if (started && (x < 0 || y < 0 || x > window.innerWidth || y > window.innerHeight)) {
|
||
const tab = tabs.find(tab => tab.relPath === path);
|
||
if (tab) onDetach?.(tab);
|
||
}
|
||
};
|
||
const onEscape = (e: KeyboardEvent) => {
|
||
if (e.key === "Escape") { e.preventDefault(); e.stopPropagation(); clean(); }
|
||
};
|
||
cancelDrag = clean;
|
||
window.addEventListener("pointermove", onMovePointer, { passive: false });
|
||
window.addEventListener("pointerup", onUp);
|
||
window.addEventListener("pointercancel", clean);
|
||
window.addEventListener("blur", clean);
|
||
window.addEventListener("keydown", onEscape, true);
|
||
}
|
||
|
||
onDestroy(() => { cancelDrag(); finishTabTransfer(); closeMenu(); });
|
||
|
||
function onMiddleDown(event: MouseEvent) {
|
||
if (event.button === 1) {
|
||
event.preventDefault();
|
||
}
|
||
}
|
||
|
||
function onMiddleUp(event: MouseEvent, relPath: string) {
|
||
if (event.button === 1) {
|
||
event.preventDefault();
|
||
event.stopPropagation();
|
||
onClose(relPath);
|
||
}
|
||
}
|
||
</script>
|
||
|
||
<svelte:window onpointerdown={(event) => { if (menu && !menu.contains(event.target as Node)) closeMenu(); }} onresize={() => closeMenu()}
|
||
ondragover={ribbonDragOver} ondrop={ribbonDrop}
|
||
ondragleave={(event) => { if (!event.relatedTarget) clearTransferTarget(); }}
|
||
ondragend={clearTransferTarget} />
|
||
|
||
<div bind:this={bar} class="tabs" class:receiving role="tablist" aria-label={$t("Working tabs")} tabindex="-1"
|
||
ondragover={dragOver} ondrop={dropTab}
|
||
ondragleave={(event) => { if (!(event.relatedTarget instanceof Node) || !bar.contains(event.relatedTarget)) { receiving = false; dropBefore = dropAfter = null; } }}>
|
||
{#each tabs as tab (tab.id)}
|
||
<div class="tab" data-path={tab.relPath} class:active={tab.relPath === activePath} class:dragging={dragged === tab.relPath}
|
||
class:drop-before={dropBefore === tab.relPath} class:drop-after={dropAfter === tab.relPath}>
|
||
<button
|
||
type="button"
|
||
role="tab"
|
||
data-path={tab.relPath}
|
||
tabindex={tab.relPath === activePath ? 0 : -1}
|
||
aria-selected={tab.relPath === activePath}
|
||
aria-controls={tab.panelId}
|
||
aria-describedby={tab.pinned ? `tab-pin-${tab.id}` : undefined}
|
||
aria-keyshortcuts="Alt+Shift+ArrowLeft Alt+Shift+ArrowRight"
|
||
use:tabTooltip={`${tab.title}\n${tab.draggable ? $t("Drag to reorder or move to another RuneStone window.") : $t("Drag to reorder.")} ${$t("Right-click for tab actions.")}`}
|
||
onclick={() => { if (suppressClick) { suppressClick = false; return; } onSelect(tab.relPath); }}
|
||
onpointerdown={(event) => { if (!tab.draggable) startDrag(event, tab.relPath); else suppressClick = false; }}
|
||
draggable={!!tab.draggable}
|
||
ondragstart={(event) => startTabTransfer(event, tab)}
|
||
ondragend={(event) => {
|
||
const outside = event.clientX < 0 || event.clientY < 0 || event.clientX > window.innerWidth || event.clientY > window.innerHeight;
|
||
if (dragged && event.dataTransfer?.dropEffect === "none" && outside) onDetach?.(tab);
|
||
finishTabTransfer();
|
||
}}
|
||
onkeydown={(event) => onKey(event, tab.relPath)}
|
||
oncontextmenu={(event) => { event.preventDefault(); event.stopPropagation(); showMenu(event.currentTarget, tab.relPath, event.clientX, event.clientY); }}
|
||
onmousedown={onMiddleDown}
|
||
onmouseup={(event) => onMiddleUp(event, tab.relPath)}
|
||
>
|
||
{#if tab.pinned}<svg class="pin" viewBox="0 0 24 24" aria-hidden="true">{@html actionIcons.pin}</svg>{/if}
|
||
<TabIcon image={tab.iconImage} icon={tab.icon} />
|
||
<span class="tab-label">{tab.name}{tab.dirty ? " •" : ""}</span>
|
||
</button>
|
||
{#if tab.pinned}<span class="sr-only" id={`tab-pin-${tab.id}`}>{$t("Pinned tab")}</span>{/if}
|
||
<button
|
||
class="close"
|
||
type="button"
|
||
aria-label={$t("Close {name}", { name: tab.name })}
|
||
use:tabTooltip={$t("Close {name}", { name: tab.name })}
|
||
onclick={() => onClose(tab.relPath)}
|
||
onmousedown={onMiddleDown}
|
||
onmouseup={(event) => onMiddleUp(event, tab.relPath)}
|
||
>
|
||
×
|
||
</button>
|
||
</div>
|
||
{/each}
|
||
</div>
|
||
<span class="sr-only" role="status">{announcement}</span>
|
||
|
||
<style>
|
||
.tabs {
|
||
display: flex;
|
||
min-height: 32px;
|
||
overflow-x: auto;
|
||
background: var(--rs-bg-elevated);
|
||
box-shadow: inset 0 -1px var(--rs-border);
|
||
}
|
||
.tabs:empty { min-width: 80px; }
|
||
.tabs.receiving, .tabs.receiving .tab { box-shadow: inset 0 -2px var(--rs-accent); }
|
||
|
||
.tab {
|
||
position: relative;
|
||
display: flex;
|
||
align-items: center;
|
||
max-width: 220px;
|
||
flex-shrink: 0;
|
||
border-radius: var(--rs-item-selection-radius) var(--rs-item-selection-radius) 0 0;
|
||
border-right: 1px solid var(--rs-border);
|
||
background: transparent;
|
||
border-bottom: 1px solid var(--rs-border);
|
||
}
|
||
|
||
.tab.active {
|
||
background: var(--rs-bg);
|
||
border-bottom-color: transparent;
|
||
}
|
||
|
||
.tab:focus-within { box-shadow: inset 0 0 0 var(--rs-item-selection-width) var(--rs-item-selection-border); }
|
||
.tab:not(.active):hover { background: var(--rs-bg-active); }
|
||
.tab.dragging { opacity: 0.5; }
|
||
.tabs:has(.dragging) .tab > button:first-child { cursor: grabbing; }
|
||
.tab.drop-before::before, .tab.drop-after::after {
|
||
content: "";
|
||
position: absolute;
|
||
top: 3px;
|
||
bottom: 3px;
|
||
width: 3px;
|
||
border-radius: var(--rs-control-radius);
|
||
background: var(--rs-accent);
|
||
pointer-events: none;
|
||
}
|
||
.tab.drop-before::before { left: 0; }
|
||
.tab.drop-after::after { right: 0; }
|
||
.sr-only { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); }
|
||
|
||
.tab > button:first-child {
|
||
display: flex;
|
||
align-items: center;
|
||
gap: 7px;
|
||
border-radius: var(--rs-control-radius);
|
||
touch-action: none;
|
||
user-select: none;
|
||
cursor: grab;
|
||
flex: 1;
|
||
min-width: 0;
|
||
border: 0;
|
||
background: transparent;
|
||
color: var(--rs-text-dim);
|
||
text-align: left;
|
||
padding: 0 8px 0 12px;
|
||
height: 32px;
|
||
overflow: hidden;
|
||
text-overflow: ellipsis;
|
||
white-space: nowrap;
|
||
}
|
||
|
||
.tab.active > button:first-child {
|
||
color: var(--rs-text-strong);
|
||
}
|
||
|
||
.tab-label { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||
.tab :global(svg) { width: 16px; height: 16px; flex-shrink: 0; }
|
||
.pin { fill: none; stroke: currentColor; stroke-width: 1.6; stroke-linecap: round; stroke-linejoin: round; }
|
||
|
||
.close {
|
||
border: 0;
|
||
border-radius: var(--rs-control-radius);
|
||
background: transparent;
|
||
color: var(--rs-text-dim);
|
||
width: 22px;
|
||
height: 22px;
|
||
margin-right: 4px;
|
||
flex: 0 0 22px;
|
||
}
|
||
|
||
.close:hover {
|
||
color: var(--rs-text-strong);
|
||
background: var(--rs-bg);
|
||
}
|
||
</style>
|