feat: refine tab sorting and breadcrumb icons

Use interact.js for tab dragging, drop detection, and automatic scrolling.

Use the window icon as the breadcrumb fallback.
This commit is contained in:
XiaoDaiGua-Ray 2026-11-19 14:10:42 +08:00
parent c2019b10e6
commit 2a4a6182b0
No known key found for this signature in database
9 changed files with 576 additions and 377 deletions

View File

@ -102,6 +102,8 @@ beforeEach(async () => {
},
},
})
await import('interactjs')
await flushPromises()
})
afterEach(() => {
@ -129,6 +131,24 @@ const mouse = (element: Element, type: string, button: number) => {
)
}
const point = (element: Element, type: string, clientX: number) => {
const event = new PointerEvent(type, {
bubbles: true,
isPrimary: true,
pointerId: 2,
pointerType: 'mouse',
buttons: type === 'pointerup' ? 0 : 1,
clientX,
clientY: 16,
})
Object.defineProperties(event, {
pageX: { value: clientX },
pageY: { value: 16 },
})
element.dispatchEvent(event)
}
const openContextMenu = async (index: number) => {
const tab = wrapper.findAll('.menu-tag__tab')[index]!.element
@ -145,6 +165,10 @@ it('closes with the named native tag button without selecting the page', async (
'button.n-tag__close[aria-label="menuTag.closeNamed:Orders"]',
)
point(closeButton.element, 'pointerdown', 10)
point(closeButton.element, 'pointermove', 40)
expect(wrapper.find('[data-menu-tag-dragged]').exists()).toBe(false)
point(closeButton.element, 'pointerup', 40)
await closeButton.trigger('click', { detail: 1 })
expect(state.close).toHaveBeenCalledExactlyOnceWith(1)
@ -189,14 +213,16 @@ it.each(['button', 'Delete'])(
},
)
it('uses the native primary type only for the current page', async () => {
it('shares the native border across tabs and highlights the current page', async () => {
const tagTypes = () =>
wrapper.findAllComponents(NTag).map((tag) => tag.props('type'))
expect(tagTypes()).toEqual(['primary', 'default', 'default'])
state.tags.value[0]!.fixed = true
state.active.value = state.tags.value[1]!
await nextTick()
expect(tagTypes()).toEqual(['default', 'primary', 'default'])
expect(wrapper.findAll('.menu-tag__item .n-tag__border')).toHaveLength(3)
})
it('applies the native round style to open tags when the preference changes', async () => {
@ -243,7 +269,7 @@ it('keeps context commands tied to the selected page when the order changes', as
expect(state.toggleFixed).toHaveBeenCalledExactlyOnceWith('/reports')
})
it('updates tab indicators and actions while preferences change', async () => {
it('updates tab status and actions while preferences change', async () => {
state.tags.value[0].topped = true
state.tags.value[0].fixed = true
await openContextMenu(0)
@ -254,7 +280,12 @@ it('updates tab indicators and actions while preferences change', async () => {
?.map((option) => option.key)
expect(tab.find('.n-tag__close').exists()).toBe(false)
expect(tab.findAll('.menu-tag__indicator')).toHaveLength(2)
expect(tab.find('.n-tag__icon').exists()).toBe(false)
const label = tab.get('.menu-tag__tab')
expect(label.attributes('aria-label')).toBe(
'Reports · menuTag.topped · menuTag.fixed',
)
expect(actions()).toEqual(
expect.arrayContaining(['toggleTop', 'toggleFixed']),
)
@ -264,20 +295,26 @@ it('updates tab indicators and actions while preferences change', async () => {
state.drag.value = false
await nextTick()
expect(tab.find('.n-tag__close').exists()).toBe(true)
expect(tab.findAll('.menu-tag__indicator')).toHaveLength(0)
expect(wrapper.findAll('.menu-tag__handle')).toHaveLength(0)
expect(label.attributes('aria-label')).toBeUndefined()
expect(label.attributes('aria-keyshortcuts')).toBeUndefined()
expect(actions()).not.toContain('toggleTop')
expect(actions()).not.toContain('toggleFixed')
})
it('sends the focused handle’s keyboard reorder to the tab store', async () => {
const handle = wrapper.get(
'[data-menu-tag-path="/reports"] .menu-tag__handle',
)
it('reorders a focused protected tab with Shift and an arrow key', async () => {
state.tags.value[0].fixed = true
await nextTick()
const tab = wrapper.get('[data-menu-tag-path="/reports"]')
const button = tab.get('.menu-tag__tab')
await handle.trigger('keydown', { key: 'ArrowRight' })
expect(tab.find('.n-tag__close').exists()).toBe(false)
expect(tab.find('.r-icon').exists()).toBe(false)
expect(button.attributes('aria-keyshortcuts')).toBe(
'Shift+ArrowLeft Shift+ArrowRight',
)
await button.trigger('keydown', { key: 'ArrowRight' })
expect(state.move).not.toHaveBeenCalled()
await handle.trigger('keydown', { key: 'ArrowRight', shiftKey: true })
await button.trigger('keydown', { key: 'ArrowRight', shiftKey: true })
expect(state.move).toHaveBeenCalledExactlyOnceWith(
'/reports',
'/orders',
@ -286,65 +323,163 @@ it('sends the focused handle’s keyboard reorder to the tab store', async () =>
expect(state.navigate).not.toHaveBeenCalled()
})
it('measures a burst of pointer moves once and uses the release position', () => {
const mockTagRects = (viewportWidth = 300) => {
const row = wrapper.get<HTMLElement>('.menu-tag-wrapper').element
const scroller = row.closest('.n-scrollbar-container')!
const measure = vi.fn(() => new DOMRect(0, 0, 300, 32))
const mockRect = (element: Element, measure: () => DOMRect) => {
element.getBoundingClientRect = measure
element.getClientRects = () => [measure()] as unknown as DOMRectList
}
scroller.getBoundingClientRect = measure
row.getBoundingClientRect = () => new DOMRect(0, 0, 300, 32)
mockRect(scroller, () => new DOMRect(0, 0, viewportWidth, 32))
Object.defineProperties(scroller, {
clientWidth: { value: viewportWidth },
scrollWidth: { value: 300 },
})
mockRect(row, () => new DOMRect(-scroller.scrollLeft, 0, 300, 32))
const tags = wrapper.findAll<HTMLElement>('[data-menu-tag-path]')
tags.forEach(({ element }, index) => {
Object.defineProperties(element, {
offsetLeft: { value: index * 100 },
offsetWidth: { value: 100 },
offsetWidth: { value: 94 },
})
})
const handle = tags[0].get<HTMLButtonElement>('.menu-tag__handle').element
const release = vi.fn()
handle.setPointerCapture = vi.fn()
handle.hasPointerCapture = () => true
handle.releasePointerCapture = release
const requestFrame = vi.fn((_callback: FrameRequestCallback) => 1)
vi.stubGlobal('requestAnimationFrame', requestFrame)
const point = (type: string, clientX: number) =>
handle.dispatchEvent(
new PointerEvent(type, {
bubbles: true,
isPrimary: true,
pointerId: 2,
clientX,
clientY: 16,
}),
mockRect(
element,
() => new DOMRect(index * 100 - scroller.scrollLeft, 0, 94, 30),
)
})
point('pointerdown', 10)
point('pointermove', 110)
point('pointermove', 180)
expect(measure).not.toHaveBeenCalled()
expect(requestFrame).toHaveBeenCalledTimes(1)
return { row, scroller, tags }
}
requestFrame.mock.calls[0][0](16)
expect(measure).toHaveBeenCalledTimes(1)
expect(requestFrame).toHaveBeenCalledTimes(1)
expect(tags[2].attributes('data-menu-tag-drop')).toBe('before')
it('reorders from the tab body using the release position and ignores the drag click', async () => {
const { row, tags } = mockTagRects()
const source = tags[0].element
point(source, 'pointerdown', 10)
point(tags[1].element, 'pointermove', 180)
expect(tags[1].attributes('data-menu-tag-drop')).toBe('after')
expect(state.move).not.toHaveBeenCalled()
point('pointerup', 285)
point(tags[2].element, 'pointerup', 285)
expect(state.move).toHaveBeenCalledExactlyOnceWith(
'/reports',
'/users',
'after',
)
expect(release).toHaveBeenCalledExactlyOnceWith(2)
expect(
row.querySelector('[data-menu-tag-drop],[data-menu-tag-dragged]'),
).toBeNull()
await tags[0].trigger('click', { detail: 1 })
expect(state.navigate).not.toHaveBeenCalled()
point(source, 'pointerdown', 10)
point(source, 'pointermove', 12)
point(source, 'pointerup', 12)
await tags[0].trigger('click', { detail: 1 })
expect(state.navigate).toHaveBeenCalledExactlyOnceWith(
'/reports',
state.tags.value[0],
)
expect(state.move).toHaveBeenCalledTimes(1)
})
it.each([
{ target: 'outside the horizontal viewport', x: -10, firstTopped: false },
{ target: 'over the other tab group', x: 20, firstTopped: true },
])('rejects a drop $target', async ({ x, firstTopped }) => {
state.tags.value[0]!.topped = firstTopped
await nextTick()
const { row, tags } = mockTagRects()
const source = tags[2].element
const target = firstTopped ? tags[0].element : outside
point(source, 'pointerdown', 240)
point(target, 'pointermove', x)
expect(source.hasAttribute('data-menu-tag-dragged')).toBe(true)
expect(row.querySelector('[data-menu-tag-drop]')).toBeNull()
point(target, 'pointerup', x)
expect(state.move).not.toHaveBeenCalled()
})
it('refreshes the drop marker after a scroll with a stationary pointer', () => {
const { scroller, tags } = mockTagRects(220)
const source = tags[0].element
const requestFrame = vi.fn((_callback: FrameRequestCallback) => 1)
vi.stubGlobal('requestAnimationFrame', requestFrame)
point(source, 'pointerdown', 30)
point(tags[1].element, 'pointermove', 180)
expect(tags[1].attributes('data-menu-tag-drop')).toBe('after')
expect(requestFrame).toHaveBeenCalledTimes(1)
requestFrame.mock.calls[0][0](16)
scroller.scrollLeft = 80
scroller.dispatchEvent(new Event('scroll'))
expect(requestFrame).toHaveBeenCalledTimes(2)
requestFrame.mock.calls[1][0](32)
expect(tags[2].attributes('data-menu-tag-drop')).toBe('after')
point(tags[2].element, 'pointerup', 180)
})
it('cancels dragging with Escape and preserves keyboard activation', async () => {
const button = wrapper.get<HTMLButtonElement>(
'[data-menu-tag-path="/orders"] .menu-tag__tab',
)
point(button.element, 'pointerdown', 10)
point(button.element, 'pointermove', 60)
expect(wrapper.find('[data-menu-tag-dragged]').exists()).toBe(true)
await button.trigger('keydown', { key: 'Escape' })
point(button.element, 'pointerup', 60)
await button.trigger('click', { detail: 0 })
expect(state.navigate).toHaveBeenCalledExactlyOnceWith(
'/orders',
state.tags.value[1],
)
await button.trigger('click', { detail: 1 })
expect(state.move).not.toHaveBeenCalled()
expect(state.navigate).toHaveBeenCalledTimes(1)
})
it.each([
{ hold: 100, claimed: false },
{ hold: 400, claimed: true },
])(
'claims a horizontal touch after $hold ms: $claimed',
({ hold, claimed }) => {
const button = wrapper.get<HTMLButtonElement>('.menu-tag__tab').element
const start = new PointerEvent('pointerdown', {
bubbles: true,
isPrimary: true,
pointerId: 2,
pointerType: 'touch',
buttons: 1,
clientX: 10,
clientY: 16,
})
const move = new TouchEvent('touchmove', {
bubbles: true,
cancelable: true,
touches: [
new Touch({ identifier: 2, target: button, clientX: 30, clientY: 16 }),
],
})
Object.defineProperty(move, 'timeStamp', { value: start.timeStamp + hold })
button.dispatchEvent(start)
button.dispatchEvent(move)
expect(move.defaultPrevented).toBe(claimed)
expect(wrapper.find('[data-menu-tag-dragged]').exists()).toBe(claimed)
},
)
it.each([0, 2])(
'dismisses when mouse button %i is clicked outside the tags and menu',
async (button) => {

View File

@ -10,41 +10,10 @@
padding-inline: 4px;
}
.menu-tag__item .n-tag__content {
display: inline-flex;
align-items: center;
gap: 4px;
}
.menu-tag__handle {
display: grid;
flex: none;
place-items: center;
min-inline-size: 24px;
min-block-size: 24px;
padding: 0;
border: 0;
border-radius: var(--r-control-radius);
background: transparent;
color: var(--r-text-secondary);
touch-action: none;
.menu-tag-wrapper[data-menu-tag-sortable] .menu-tag__item {
-webkit-touch-callout: none;
-webkit-user-select: none;
user-select: none;
cursor: grab;
&:is(:hover, :focus-visible) {
background: var(--r-surface-hover);
color: var(--r-text);
}
&:focus-visible {
outline-offset: -2px;
}
}
.menu-tag__indicator {
display: inline-flex;
flex: none;
}
.menu-tag__top-icon {
@ -52,7 +21,7 @@
}
.menu-tag-wrapper--dragging,
.menu-tag-wrapper--dragging * {
.menu-tag-wrapper--dragging :is(.menu-tag__item:hover, .menu-tag__tab) {
cursor: grabbing;
}
@ -91,13 +60,6 @@
white-space: nowrap;
}
@media (hover: none) {
.menu-tag__handle {
min-inline-size: 32px;
min-block-size: 28px;
}
}
@media (forced-colors: active) {
.menu-tag__item[data-menu-tag-drop]::after {
background: Highlight;

View File

@ -320,27 +320,27 @@ export default defineComponent({
scheduleAnnouncement(message)
}
const reorder = useTagReorder(
const moveTagWithKey = useTagReorder(
getMenuTagDrag,
tagsRef,
scroller,
(path, target, handle) => {
(path, target, button) => {
if (!moveMenuTag(path, target.path, target.placement)) return
const position = getMenuTagOptions.value.findIndex(
(tag) => tag.fullPath === path,
)
const option = getMenuTagOptions.value[position]
const wasFocused = document.activeElement === handle
const wasFocused = document.activeElement === button
void nextTick(() => {
const tag = handle.closest<HTMLElement>('[data-menu-tag-path]')
const tag = button.closest<HTMLElement>('[data-menu-tag-path]')
if (!tag?.isConnected) return
revealTag(tag)
if (wasFocused) handle.focus({ preventScroll: true })
if (wasFocused) button.focus({ preventScroll: true })
announce(
t('moved', { name: tagLabel(option), position: position + 1 }),
@ -451,7 +451,7 @@ export default defineComponent({
getMenuTagDrag,
isMenuTagTopped,
isMenuTagFixed,
reorder,
moveTagWithKey,
tagLabel,
closeCurrentMenuTag,
getMenuKey,
@ -530,8 +530,10 @@ export default defineComponent({
<div
ref="tags"
class="menu-tag-wrapper"
data-menu-tag-sortable={this.getMenuTagDrag ? '' : void 0}
role="group"
aria-label={$t('menuTag.pages')}
onKeydown={this.moveTagWithKey}
>
<TransitionGroup name="menu-tag" css={false}>
{getMenuTagOptions.map((curr, idx) => {
@ -541,9 +543,6 @@ export default defineComponent({
const fixed = this.isMenuTagFixed(curr)
const topLabel = topped ? $t('menuTag.topped') : ''
const fixedLabel = fixed ? $t('menuTag.fixed') : ''
const moveLabel = this.getMenuTagDrag
? $t('menuTag.moveNamed', { name: label })
: ''
return (
<ShellTab
@ -558,6 +557,11 @@ export default defineComponent({
: topLabel || fixedLabel
}
round={this.getMenuTagRound}
keyShortcuts={
this.getMenuTagDrag
? 'Shift+ArrowLeft Shift+ArrowRight'
: void 0
}
select={() => menuTagClick(curr)}
closeLabel={$t('menuTag.closeNamed', { name: label })}
close={
@ -569,60 +573,7 @@ export default defineComponent({
contextMenu={(event) =>
menuTagContextMenu(curr.fullPath, event)
}
>
{{
prefix: () => (
<>
{this.getMenuTagDrag && (
<button
type="button"
class="menu-tag__handle"
aria-label={moveLabel}
title={moveLabel}
aria-keyshortcuts="Shift+ArrowLeft Shift+ArrowRight"
onClick={(event) => event.stopPropagation()}
onPointerdown={this.reorder.start}
onPointermove={this.reorder.track}
onPointerup={this.reorder.drop}
onPointercancel={this.reorder.cancelPointer}
onLostpointercapture={
this.reorder.cancelPointer
}
onKeydown={this.reorder.moveWithKey}
>
<RIcon
name="action/draggable"
size={14}
aria-hidden="true"
/>
</button>
)}
{topped && (
<span
class="menu-tag__indicator"
title={topLabel}
aria-hidden="true"
>
<RIcon
name="directional/expanded"
size={14}
customClassName="menu-tag__top-icon"
/>
</span>
)}
{fixed && (
<span
class="menu-tag__indicator"
title={fixedLabel}
aria-hidden="true"
>
<RIcon name="action/lock" size={14} />
</span>
)}
</>
),
}}
</ShellTab>
/>
)
})}
</TransitionGroup>

View File

@ -1,9 +1,18 @@
import type { DragEvent } from '@interactjs/actions/drag/plugin'
import type { DropEvent } from '@interactjs/actions/drop/DropEvent'
import type { PointerEvent as InteractPointerEvent } from '@interactjs/pointer-events/PointerEvent'
import { useEventListener } from '@vueuse/core'
import { onScopeDispose, watch } from 'vue'
import { watch } from 'vue'
import type { Ref } from 'vue'
type Interact = typeof import('interactjs').default
type Placement = 'before' | 'after'
const TAB_SELECTOR = '[data-menu-tag-path]'
const CLOSE_SELECTOR = '.n-tag__close'
const DRAG_SLOP = 5
const TOUCH_HOLD_DELAY = 280
interface DropTarget {
path: string
placement: Placement
@ -14,242 +23,389 @@ interface DropMarker {
placement: Placement
}
interface Drag {
wrapper: HTMLElement
handle: HTMLButtonElement
item: HTMLElement
interface Press {
down: PointerEvent
pointer: InteractPointerEvent
row: HTMLElement
tab: HTMLElement
button: HTMLButtonElement
path: string
pointer: number
startX: number
x: number
y: number
moved: boolean
lastScrollFrame?: number
}
const withinRow = ({ y }: Drag, { top, bottom }: DOMRect) =>
y >= top && y <= bottom
let activeTagDrags = 0
let previousDynamicDrop = false
const findDropMarker = (
{ wrapper, item, x }: Drag,
{ left, right }: DOMRect,
scrollDelta = 0,
): DropMarker | undefined => {
const isTop = item.hasAttribute('data-menu-tag-top')
const cursor =
Math.min(right, Math.max(left, x)) -
wrapper.getBoundingClientRect().left +
scrollDelta
const tabs = wrapper.children as HTMLCollectionOf<HTMLElement>
let first = 0
let last = tabs.length
// 置顶组先于普通组。两组各自按布局中点递增,排序动画不改变中点。
while (first < last) {
const middle = Math.floor((first + last) / 2)
const tab = tabs[middle]
const before =
tab.hasAttribute('data-menu-tag-top') === isTop
? cursor < tab.offsetLeft + tab.offsetWidth / 2
: isTop
if (before) last = middle
else first = middle + 1
const retainDynamicDrop = (interact: Interact) => {
// dynamicDrop 由同一个 interact.js 实例共享,最后一次标签拖动结束时恢复。
if (activeTagDrags === 0) {
previousDynamicDrop = interact.dynamicDrop() === true
interact.dynamicDrop(true)
}
const next = tabs[first]
const previous = tabs[first - 1]
activeTagDrags++
if (next === item || previous === item) return
return () => {
activeTagDrags--
if (next && next.hasAttribute('data-menu-tag-top') === isTop)
return { tab: next, placement: 'before' }
if (previous && previous.hasAttribute('data-menu-tag-top') === isTop)
return { tab: previous, placement: 'after' }
if (activeTagDrags === 0) interact.dynamicDrop(previousDynamicDrop)
}
}
export function useTagReorder(
enabled: Ref<boolean>,
list: Ref<HTMLElement | null>,
scroller: Ref<HTMLElement | null | undefined>,
move: (path: string, target: DropTarget, handle: HTMLButtonElement) => void,
move: (path: string, target: DropTarget, button: HTMLButtonElement) => void,
announceCancellation: () => void,
) {
let drag: Drag | undefined
let press: Press | undefined
let drag: { restoreDropMode: () => void; release?: PointerEvent } | undefined
let marker: DropMarker | undefined
let frame: number | undefined
let suppressPointerClick = false
const mark = (target?: DropMarker) => {
if (target?.tab === marker?.tab && target?.placement === marker?.placement)
return
// 临时落点由 DOM 属性绘制,避免触发整排标签的渲染和位移动画测量。
marker?.tab.removeAttribute('data-menu-tag-drop')
target?.tab.setAttribute('data-menu-tag-drop', target.placement)
marker = target
}
const clear = () => {
const current = drag
drag = void 0
const finish = () => {
press?.row.classList.remove('menu-tag-wrapper--dragging')
press?.tab.removeAttribute('data-menu-tag-dragged')
mark()
if (frame !== void 0) cancelAnimationFrame(frame)
frame = void 0
current?.wrapper.classList.remove('menu-tag-wrapper--dragging')
current?.item.removeAttribute('data-menu-tag-dragged')
if (current?.handle.hasPointerCapture(current.pointer))
current.handle.releasePointerCapture(current.pointer)
}
const updateFrame = (time: number) => {
frame = void 0
const current = drag
const element = scroller.value
if (
!current ||
!element ||
current.item.parentElement !== current.wrapper
) {
clear()
return
}
const viewport = element.getBoundingClientRect()
if (!withinRow(current, viewport)) {
current.lastScrollFrame = void 0
mark()
return
}
const edge = Math.min(36, viewport.width / 3)
const pressure =
Math.max(0, current.x - (viewport.right - edge)) -
Math.max(0, viewport.left + edge - current.x)
let offset = 0
let nextOffset = 0
if (edge > 0 && pressure !== 0) {
const elapsed = Math.min(
32,
time - (current.lastScrollFrame ?? time - 16),
)
const distance = Math.max(
1,
Math.min(1, Math.abs(pressure / edge)) * elapsed * 0.65,
)
offset = element.scrollLeft
const limit = element.scrollWidth - element.clientWidth
nextOffset = Math.max(
0,
Math.min(limit, offset + Math.sign(pressure) * distance),
)
}
const target = findDropMarker(current, viewport, nextOffset - offset)
if (!current.item.hasAttribute('data-menu-tag-dragged')) {
current.wrapper.classList.add('menu-tag-wrapper--dragging')
current.item.setAttribute('data-menu-tag-dragged', '')
}
mark(target)
if (nextOffset !== offset) {
element.scrollLeft = nextOffset
current.lastScrollFrame = time
frame = requestAnimationFrame(updateFrame)
} else {
current.lastScrollFrame = void 0
}
drag?.restoreDropMode()
drag = void 0
press = void 0
}
const cancel = () => {
if (drag?.moved) announceCancellation()
if (drag) {
press?.pointer.interaction.stop()
announceCancellation()
}
clear()
finish()
}
const start = (event: PointerEvent) => {
if (!enabled.value || drag || !event.isPrimary || event.button !== 0) return
const refreshDrop = () => {
if (!drag || frame !== void 0) return
const handle = event.currentTarget as HTMLButtonElement
const item = handle.closest<HTMLElement>('[data-menu-tag-path]')
const path = item?.dataset.menuTagPath
const wrapper = list.value
frame = requestAnimationFrame(() => {
frame = void 0
// 跳过同坐标的优化,让滚动后的落区重新参与检测。
press?.pointer.interaction.move({ skipModifiers: 1 })
})
}
if (!item || !path || !wrapper || item.parentElement !== wrapper) return
const start = ({ pointer, tab }: Press) => {
pointer.interaction.start({ name: 'drag' }, pointer.interactable, tab)
}
handle.setPointerCapture(event.pointerId)
drag = {
wrapper,
handle,
item,
path,
pointer: event.pointerId,
startX: event.clientX,
x: event.clientX,
y: event.clientY,
moved: false,
const startWithPointer = (event: PointerEvent) => {
const current = press
if (
!current ||
drag ||
event.pointerId !== current.down.pointerId ||
event.pointerType === 'touch'
)
return
const x = Math.abs(event.clientX - current.down.clientX)
const y = Math.abs(event.clientY - current.down.clientY)
if (Math.max(x, y) >= DRAG_SLOP) start(current)
}
const trackTouch = (event: TouchEvent) => {
const current = press
if (current?.down.pointerType !== 'touch') return
if (!event.cancelable || event.touches.length !== 1) {
cancel()
return
}
if (!drag) {
const touch = event.touches[0]
const x = Math.abs(touch.clientX - current.down.clientX)
const y = Math.abs(touch.clientY - current.down.clientY)
if (Math.max(x, y) < DRAG_SLOP) return
if (
event.timeStamp - current.down.timeStamp < TOUCH_HOLD_DELAY ||
y > x
) {
finish()
return
}
start(current)
}
// 普通滑动保持原生滚动,长按启动拖动后才接管触摸。
if (drag) event.preventDefault()
}
const bind = (
interact: Interact,
row: HTMLElement,
viewport: HTMLElement,
) => {
const zoneRect = (element: Element) => {
const visible = interact.getElementRect(viewport)
const origin = interact.getElementRect(row)?.left
if (!visible || origin === void 0)
return { left: 0, right: 0, top: 0, bottom: 0 }
const previous = element.previousElementSibling
const next = element.nextElementSibling
// 落区延伸到两侧相邻标签的边缘,使标签间的插入线也可以落下。
return {
left:
previous instanceof HTMLElement
? Math.max(
visible.left,
origin + previous.offsetLeft + previous.offsetWidth,
)
: visible.left,
right:
next instanceof HTMLElement
? Math.min(visible.right, origin + next.offsetLeft)
: visible.right,
top: visible.top,
bottom: visible.bottom,
}
}
const placementAt = (
event: DropEvent,
x: number,
): DropMarker | undefined => {
const { target: tab, relatedTarget: source } = event
if (!(tab instanceof HTMLElement)) return
const middle =
row.getBoundingClientRect().left + tab.offsetLeft + tab.offsetWidth / 2
const placement = x < middle ? 'before' : 'after'
const neighbor =
placement === 'before'
? tab.previousElementSibling
: tab.nextElementSibling
if (neighbor !== source) return { tab, placement }
}
const interactable = interact(TAB_SELECTOR, { context: row })
.styleCursor(false)
.preventDefault('never')
.rectChecker(zoneRect)
.draggable({
manualStart: true,
ignoreFrom: CLOSE_SELECTOR,
autoScroll: { container: viewport, margin: 36, speed: 450 },
listeners: {
start: () => {
if (!press) return
drag = { restoreDropMode: retainDynamicDrop(interact) }
suppressPointerClick = true
row.classList.add('menu-tag-wrapper--dragging')
press.tab.setAttribute('data-menu-tag-dragged', '')
refreshDrop()
},
end: finish,
},
})
.dropzone({
accept: ({ draggableElement }) =>
draggableElement.parentElement === row,
overlap: 'pointer',
checker: (
event: DragEvent,
_native,
over,
_zone,
target,
_from,
source,
) => {
if (
!drag ||
target.hasAttribute('data-menu-tag-top') !==
source.hasAttribute('data-menu-tag-top')
)
return false
if (event.type !== 'dragend') return over
const released = drag.release
if (!released) return false
if (
released.clientX === event.clientX &&
released.clientY === event.clientY
)
return over
// 1.10.28 的 dragend 坐标取自上一条 dragmove。松手坐标可能已变化。
const rect = zoneRect(target)
return (
released.pageX > rect.left &&
released.pageX < rect.right &&
released.pageY > rect.top &&
released.pageY < rect.bottom
)
},
ondropmove: (event: DropEvent) =>
mark(placementAt(event, event.dragEvent.clientX)),
ondragleave: () => mark(),
ondrop: (event: DropEvent) => {
const released = drag?.release
if (!press || !released) return
const marker = placementAt(event, released.clientX)
const path = marker?.tab.dataset.menuTagPath
if (marker && path)
move(
press.path,
{ path, placement: marker.placement },
press.button,
)
},
})
.pointerEvents({ ignoreFrom: CLOSE_SELECTOR })
.on('down', (pointer: InteractPointerEvent) => {
const event = pointer.originalEvent
const tab = pointer.currentTarget
if (
press ||
!(event instanceof PointerEvent) ||
!event.isPrimary ||
event.button !== 0 ||
!(tab instanceof HTMLElement) ||
tab.parentElement !== row
)
return
const path = tab.dataset.menuTagPath
const button = tab.querySelector<HTMLButtonElement>('.menu-tag__tab')
if (path && button)
press = { down: event, pointer, row, tab, button, path }
})
return () => {
cancel()
interactable.unset()
}
}
const updatePointer = (event: PointerEvent) => {
if (drag?.pointer !== event.pointerId) return
watch(
[enabled, list, scroller],
([allowed, row, viewport], _, onCleanup) => {
if (!allowed || !row || !viewport) return
drag.x = event.clientX
drag.y = event.clientY
drag.moved ||= Math.abs(drag.x - drag.startX) >= 5
let disposed = false
let unbind: (() => void) | undefined
return drag
}
onCleanup(() => {
disposed = true
unbind?.()
})
void import('interactjs').then(({ default: interact }) => {
if (!disposed) unbind = bind(interact, row, viewport)
})
},
{ immediate: true, flush: 'post' },
)
const track = (event: PointerEvent) => {
if (updatePointer(event)?.moved && frame === void 0)
frame = requestAnimationFrame(updateFrame)
}
useEventListener('pointermove', startWithPointer, {
capture: true,
passive: true,
})
useEventListener(
'pointerup',
(event) => {
if (press?.down.pointerId !== event.pointerId) return
const drop = (event: PointerEvent) => {
const current = updatePointer(event)
if (drag) drag.release = event
else finish()
},
{ capture: true },
)
useEventListener(
'pointercancel',
(event) => {
if (press?.down.pointerId === event.pointerId) cancel()
},
{ capture: true },
)
useEventListener(list, 'touchmove', trackTouch, { passive: false })
useEventListener(scroller, 'scroll', refreshDrop, { passive: true })
useEventListener(list, 'pointerdown', (event) => {
if (!drag && event.isPrimary && event.button === 0)
suppressPointerClick = false
})
useEventListener(
list,
'click',
(event) => {
if (!suppressPointerClick || event.detail === 0) return
if (!current) return
suppressPointerClick = false
event.preventDefault()
event.stopPropagation()
},
{ capture: true },
)
useEventListener(
list,
'contextmenu',
(event) => {
if (press?.down.pointerType !== 'touch') return
const viewport = current.moved && scroller.value?.getBoundingClientRect()
const target =
viewport &&
current.item.parentElement === current.wrapper &&
withinRow(current, viewport)
? findDropMarker(current, viewport)
: void 0
const targetPath = target?.tab.dataset.menuTagPath
event.preventDefault()
event.stopPropagation()
},
{ capture: true },
)
useEventListener(
'keydown',
(event) => {
if (event.key !== 'Escape' || !press) return
clear()
event.preventDefault()
cancel()
},
{ capture: true },
)
if (target && targetPath)
move(
current.path,
{ path: targetPath, placement: target.placement },
current.handle,
)
}
const cancelPointer = (event: PointerEvent) => {
if (drag?.pointer === event.pointerId) cancel()
}
const moveWithKey = (event: KeyboardEvent) => {
return (event: KeyboardEvent) => {
if (
!enabled.value ||
drag ||
!event.shiftKey ||
event.altKey ||
event.ctrlKey ||
@ -259,9 +415,16 @@ export function useTagReorder(
)
return
const button = event.target
if (
!(button instanceof HTMLButtonElement) ||
!button.classList.contains('menu-tag__tab')
)
return
event.preventDefault()
const handle = event.currentTarget as HTMLButtonElement
const item = handle.closest<HTMLElement>('[data-menu-tag-path]')
const item = button.closest<HTMLElement>(TAB_SELECTOR)
const placement = event.key === 'ArrowLeft' ? 'before' : 'after'
const neighbor =
placement === 'before'
@ -271,23 +434,6 @@ export function useTagReorder(
const target =
neighbor instanceof HTMLElement ? neighbor.dataset.menuTagPath : void 0
if (path && target) move(path, { path: target, placement }, handle)
if (path && target) move(path, { path: target, placement }, button)
}
useEventListener(
'keydown',
(event) => {
if (event.key !== 'Escape' || !drag) return
event.preventDefault()
cancel()
},
{ capture: true },
)
watch(enabled, (allowed) => {
if (!allowed) cancel()
})
onScopeDispose(clear)
return { start, track, drop, cancelPointer, moveWithKey }
}

View File

@ -41,7 +41,7 @@ export default defineComponent({
const icon =
option.icon?.() ??
(getBreadcrumbIconFallback.value ? (
<RIcon name="navigation/document" size="1em" />
<RIcon name="navigation/window" size="1em" />
) : null)
return (

View File

@ -15,7 +15,6 @@
"fix": "Protect tab",
"unfix": "Unprotect tab",
"fixed": "Protected",
"moveNamed": "Reorder {name} (drag or press Shift + Left/Right)",
"moved": "{name} moved to position {position}",
"moveCanceled": "Tab reordering canceled",
"scrollLeft": "Scroll tabs left",

View File

@ -15,7 +15,6 @@
"fix": "固定标签页",
"unfix": "取消固定",
"fixed": "已固定",
"moveNamed": "排序 {name}(拖拽或 Shift + ←/→)",
"moved": "{name} 已移至第 {position} 位",
"moveCanceled": "已取消标签页排序",
"scrollLeft": "向左滚动标签页",

View File

@ -43,9 +43,9 @@ updateSettingState('layoutConfig', {
### 页面标签与面包屑
- 右键点击标签或打开右侧「标签页操作」菜单,可置顶或固定标签。置顶将标签移至最左侧,取消置顶时移到普通标签组开头。固定会阻止单个关闭和批量关闭操作。
- 拖动标签左侧的手柄可以排序。也可聚焦手柄后按 Shift + ← 或 Shift + →。置顶标签和普通标签各自组内排序。顺序、置顶和固定状态随当前会话刷新恢复。
- 面包屑复用菜单配置中的图标,支持 SVG 图标名和代码路由里的图片 VNode。缺少图标时使用统一的文档图标。窄屏显示当前路径项及其图标。
- 右键点击标签或打开右侧「标签页操作」菜单,可置顶或固定标签。置顶将标签移至最左侧,取消置顶时移到普通标签组开头。固定后,关闭按钮隐藏,标签受单个关闭和批量关闭保护。
- 直接拖动标签,或聚焦标签后按 Shift + ← 或 Shift + → 即可排序。触屏上滑动标签栏可滚动,按住标签再拖动可排序。置顶标签和普通标签各自组内排序。顺序、置顶和固定状态随当前会话刷新恢复。
- 面包屑复用菜单配置中的图标,支持 SVG 图标名和代码路由里的图片 VNode。缺少图标时使用线框窗口图标。窄屏显示当前路径项及其图标。
「偏好设置 → 外观 → 界面显示」提供五个独立开关,默认全部开启。关闭固定或置顶开关会暂停对应效果并保留标签标记,重新开启后恢复生效。关闭面包屑图标开关会一并隐藏占位图标,也可单独关闭占位图标。

View File

@ -11,6 +11,7 @@ export const ShellTab = defineComponent({
round: Boolean,
statusLabel: { type: String, default: '' },
closeLabel: { type: String, default: '' },
keyShortcuts: { type: String, default: void 0 },
select: { type: Function as PropType<() => void>, required: true },
close: {
type: Function as PropType<(restoreFocus: boolean) => void>,
@ -37,7 +38,6 @@ export const ShellTab = defineComponent({
type={props.active ? 'primary' : 'default'}
size="medium"
round={props.round}
bordered={props.active}
closable={!!props.close}
{...{
onClick: props.select,
@ -47,24 +47,31 @@ export const ShellTab = defineComponent({
}}
onClose={(event) => props.close?.(event.detail === 0)}
>
{slots.prefix?.()}
<button
type="button"
class="menu-tag__tab"
aria-current={props.active ? 'page' : void 0}
aria-label={
props.statusLabel ? `${props.label} · ${props.statusLabel}` : void 0
}
title={props.label}
onKeydown={(event) => {
if (event.key === 'Delete' && props.close) {
event.preventDefault()
props.close(true)
}
}}
>
{props.label}
</button>
{{
icon: slots.prefix,
default: () => (
<button
type="button"
class="menu-tag__tab"
aria-current={props.active ? 'page' : void 0}
aria-label={
props.statusLabel
? `${props.label} · ${props.statusLabel}`
: void 0
}
aria-keyshortcuts={props.keyShortcuts}
title={props.label}
onKeydown={(event) => {
if (event.key === 'Delete' && props.close) {
event.preventDefault()
props.close(true)
}
}}
>
{props.label}
</button>
),
}}
</NTag>
)
},