Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion docs/content/1.guide/16.hub.md
Original file line number Diff line number Diff line change
Expand Up @@ -272,11 +272,12 @@ The first time any member of a group opens in a session, the hub also loads the

Declare `defaultChildId` when one member is the natural landing spot; leave it off when the members are peers.

### Pinned and recent tools
### Pinned, reordered, and recent tools

The reference hub UI (`@devframes/hub-ui`) lets users reach a group member in one click. A devframe does not need to set anything for this.

- **Pin.** Right-click a dock button (on the bar, in a group popover, or in the group sidebar) and pick **Pin**. Keyboard users press Shift+F10 or the Menu key on a focused button. A pinned entry moves to the front of the bar. A pinned group member also gets its own bar button, and it still leads inside its group. Opening it opens that member, and its group button shows as active. Pins are stored in the `docksPinned` user setting.
- **Reorder.** Drag a tool up or down in the group sidebar to change its place. Keyboard users press Alt+ArrowUp or Alt+ArrowDown on a focused tool. A tool moves only inside its own sub-category. The order is stored in the `docksCustomOrder` user setting, the same one **Settings > Docks** edits.
- **Recent.** When a user opens a tool from a group popover or the overflow menu, the float bar keeps it in a slot after the bar items, newest first. The slots are added on top of the bar's capacity, so opening a tool never pushes another button into the overflow. A tool that is already on the bar (for example a pinned member) does not take a slot. The list is kept per browser tab, in the `recentDockIds` field of the session store.

The `docksRecentLimit` user setting sets how many recent slots the bar keeps. The default is `3`. `0` turns the slots off. Users change it under **Settings > Appearance > Recent tools on the dock bar**. The edge-mode toolbar shows pinned entries but no recent slots.
Expand Down
122 changes: 118 additions & 4 deletions packages/hub-ui/src/client/components/dock/DockGroupSidebar.vue
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@
import type { DevframeDockEntry, DevframeViewGroup } from '@devframes/hub'
import type { DocksContext } from '@devframes/hub/client'
import { watchDebounced } from '@vueuse/core'
import { computed, h, ref, useTemplateRef, watch } from 'vue'
import { computed, h, nextTick, ref, useTemplateRef, watch } from 'vue'
import { t } from '../../i18n'
import { deriveSidebarCapacity, docksSplitGroupsWithCapacity, getGroupMembersGrouped } from '../../state/dock-settings'
import { applyCustomOrderPatch, deriveSidebarCapacity, docksSplitGroupsWithCapacity, getGroupMembersGrouped, resolveGroupMemberMove } from '../../state/dock-settings'
import { getCurrentDockId } from '../../state/docks'
import { dockTooltipContent, setDocksSidebarOverflowPanel, setFloatingTooltip, useDocksSidebarOverflowPanel } from '../../state/floating-tooltip'
import { useSettings } from '../../state/settings-defaults'
Expand Down Expand Up @@ -101,10 +101,112 @@ const currentInOverflow = computed(() =>
const selectedInOverflow = computed(() =>
!!props.selectedId && overflowGroups.value.some(([, items]) => items.some(m => m.id === props.selectedId)))

// Set when a drag ends, so the click that follows it does not open the member.
let suppressClick = false

function select(id: string) {
if (suppressClick) {
suppressClick = false
return
}
props.context.docks.switchEntry(id)
}

// --- Reorder ---
// Drag a member up or down within its sub-category, or press Alt+ArrowUp /
// Alt+ArrowDown on it. The order is saved to `docksCustomOrder`, the same
// setting the Docks settings page edits. Pointer capture keeps the drag alive
// while the pointer crosses the panel's iframe.
const DRAG_THRESHOLD = 4
const draggingId = ref<string | null>(null)
const dragOverId = ref<string | null>(null)
let dragStart: { id: string, y: number } | null = null

function moveMember(fromId: string, toId: string): boolean {
const patch = resolveGroupMemberMove(props.context.docks.entries, props.group.id, settings.value, fromId, toId)
if (!patch)
return false
props.context.docks.settings.mutate(state => applyCustomOrderPatch(state, patch))
return true
}

function findSubcategory(id: string) {
return visibleGroups.value.find(([, items]) => items.some(m => m.id === id))
}

// Where the drop line shows on the hovered member: the dragged member takes
// the hovered member's slot, so it lands before it when moving up and after
// it when moving down.
const dropSide = computed<'before' | 'after' | null>(() => {
if (!draggingId.value || !dragOverId.value)
return null
const items = findSubcategory(draggingId.value)?.[1] ?? []
const from = items.findIndex(m => m.id === draggingId.value)
const to = items.findIndex(m => m.id === dragOverId.value)
return from > to
? 'before'
: 'after'
})

function onMemberPointerDown(event: PointerEvent, id: string) {
hideTooltip()
suppressClick = false
if (event.button !== 0)
return
dragStart = { id, y: event.clientY }
;(event.currentTarget as HTMLElement).setPointerCapture(event.pointerId)
}

function onMemberPointerMove(event: PointerEvent) {
if (!dragStart)
return
if (!draggingId.value) {
if (Math.abs(event.clientY - dragStart.y) < DRAG_THRESHOLD)
return
draggingId.value = dragStart.id
}
const peers = findSubcategory(dragStart.id)?.[1] ?? []
const target = peers.find((m) => {
const rect = sidebar.value?.querySelector(`[data-dock-id="${CSS.escape(m.id)}"]`)?.getBoundingClientRect()
return rect && event.clientY >= rect.top && event.clientY <= rect.bottom
})
dragOverId.value = target && target.id !== dragStart.id
? target.id
: null
}

function onMemberPointerUp() {
if (draggingId.value) {
// A drag is not a click, even when it ends on the start button.
suppressClick = true
if (dragOverId.value)
moveMember(draggingId.value, dragOverId.value)
}
resetDrag()
}

function resetDrag() {
dragStart = null
draggingId.value = null
dragOverId.value = null
}

async function onMemberKeydown(event: KeyboardEvent, id: string) {
if (!event.altKey || (event.key !== 'ArrowUp' && event.key !== 'ArrowDown'))
return
event.preventDefault()
const items = findSubcategory(id)?.[1] ?? []
const index = items.findIndex(m => m.id === id)
const neighbor = items[index + (event.key === 'ArrowUp'
? -1
: 1)]
if (!neighbor || !moveMember(id, neighbor.id))
return
// Moving the focused button in the DOM can drop focus, so put it back.
await nextTick()
sidebar.value?.querySelector<HTMLElement>(`[data-dock-id="${CSS.escape(id)}"]`)?.focus()
}

function showTooltip(event: PointerEvent, entry: { title: string, description?: string }) {
setFloatingTooltip({
content: dockTooltipContent(entry),
Expand Down Expand Up @@ -212,19 +314,31 @@ const moreButtonActive = computed(() => selectedInOverflow.value || isOverflowPa
<button
v-for="member of members"
:key="member.id"
:data-dock-id="member.id"
:aria-label="member.title"
:aria-current="currentId === member.id ? 'page' : undefined"
class="relative flex items-center h-8 rounded-lg transition"
:class="[
expanded ? 'gap-2 px1.5' : 'justify-center w-8',
selectedId === member.id ? 'text-primary bg-active' : 'op60 hover:op100 hover:bg-active',
draggingId === member.id ? 'op30!' : '',
]"
@pointerenter="showTooltip($event, member)"
@pointerenter="draggingId || showTooltip($event, member)"
@pointerleave="hideTooltip"
@pointerdown="hideTooltip"
@pointerdown="onMemberPointerDown($event, member.id)"
@pointermove="onMemberPointerMove"
@pointerup="onMemberPointerUp"
@pointercancel="resetDrag"
@click="select(member.id)"
@keydown="onMemberKeydown($event, member.id)"
@contextmenu="openContextMenu($event, member)"
>
<!-- Drop line: where the dragged member will land -->
<div
v-if="dragOverId === member.id"
class="absolute inset-x-1 h-0.5 rounded-full bg-primary pointer-events-none"
:class="dropSide === 'before' ? '-top-0.5' : '-bottom-0.5'"
/>
<DockIcon :icon="member.icon" class="w-5 h-5 flex-none" />
<span v-if="expanded" class="flex-1 min-w-0 text-left text-sm truncate">{{ member.title }}</span>
<div
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import type { DevframeDockEntriesGrouped } from '../../state/dock-settings'
import { useDraggable } from '@vueuse/core'
import { computed, ref, useTemplateRef } from 'vue'
import { t } from '../../i18n'
import { docksGroupByCategories, getCategoryLabel, getGroupMembers, getGroupMembersGrouped, isCategoryHideable } from '../../state/dock-settings'
import { applyCustomOrderPatch, docksGroupByCategories, getCategoryLabel, getGroupMembers, getGroupMembersGrouped, isCategoryHideable, resolveCustomOrderPatch } from '../../state/dock-settings'
import { useSettings } from '../../state/settings-defaults'
import HashBadge from '../display/HashBadge.vue'
import DockIcon from '../dock/DockIcon.vue'
Expand Down Expand Up @@ -104,16 +104,11 @@ function isInteractiveElement(el: HTMLElement | null): boolean {
}

function applyOrder(container: string, items: DevframeDockEntry[]) {
const def = defaultItemsOfContainer(container).map(i => i.id)
const isDefault = items.length === def.length && items.every((item, i) => item.id === def[i])
settingsStore.mutate((state) => {
items.forEach((item, index) => {
if (isDefault)
delete state.docksCustomOrder[item.id]
else
state.docksCustomOrder[item.id] = index
})
})
const patch = resolveCustomOrderPatch(
items.map(i => i.id),
defaultItemsOfContainer(container).map(i => i.id),
)
settingsStore.mutate(state => applyCustomOrderPatch(state, patch))
}

useDraggable(sortContainerEl, {
Expand Down
64 changes: 63 additions & 1 deletion packages/hub-ui/src/client/state/dock-settings.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import type { DevframeDockEntriesGrouped, DevframeDockEntry, DevframeViewGroup }
import type { WhenContext } from 'devframe/utils/when'
import { DEFAULT_STATE_USER_SETTINGS } from '@devframes/hub/constants'
import { describe, expect, it } from 'vitest'
import { docksGroupByCategories, docksSplitGroupsBySize, docksSplitGroupsWithCapacity, getGroupMembersGrouped, resolveGroupPreferredChild, resolveNextRecentDockIds, resolveRecentDockEntries } from './dock-settings'
import { applyCustomOrderPatch, docksGroupByCategories, docksSplitGroupsBySize, docksSplitGroupsWithCapacity, getGroupMembersGrouped, resolveCustomOrderPatch, resolveGroupMemberMove, resolveGroupPreferredChild, resolveNextRecentDockIds, resolveRecentDockEntries } from './dock-settings'

function iframe(id: string, extra: Partial<DevframeDockEntry> = {}): DevframeDockEntry {
return {
Expand Down Expand Up @@ -423,3 +423,65 @@ describe('resolveRecentDockEntries', () => {
expect(resolve(['d'], 0)).toEqual([])
})
})

describe('resolveCustomOrderPatch', () => {
it('maps each id to its index', () => {
expect(resolveCustomOrderPatch(['b', 'a'], ['a', 'b'])).toEqual({ b: 0, a: 1 })
})

it('clears the custom order when the order matches the default', () => {
expect(resolveCustomOrderPatch(['a', 'b'], ['a', 'b'])).toEqual({ a: undefined, b: undefined })
})
})

describe('resolveGroupMemberMove', () => {
const entries = [
group('g'),
iframe('a', { groupId: 'g', defaultOrder: 1 }),
iframe('b', { groupId: 'g', defaultOrder: 2 }),
iframe('c', { groupId: 'g', defaultOrder: 3 }),
iframe('x', { groupId: 'g', category: 'other' }),
]

function move(fromId: string, toId: string, docksCustomOrder: Record<string, number> = {}) {
const settings = {
...DEFAULT_STATE_USER_SETTINGS(),
docksCustomOrder,
}
const patch = resolveGroupMemberMove(entries, 'g', settings, fromId, toId)
if (patch)
applyCustomOrderPatch(settings, patch)
const order = getGroupMembersGrouped(entries, 'g', settings).find(([category]) => category === 'default')![1]
return {
patch,
order: order.map(item => item.id),
}
}

it('moves a member down into the slot of the target', () => {
expect(move('a', 'c').order).toEqual(['b', 'c', 'a'])
})

it('moves a member up into the slot of the target', () => {
expect(move('c', 'a').order).toEqual(['c', 'a', 'b'])
})

it('clears the custom order when the move restores the default', () => {
const { patch, order } = move('a', 'b', { b: 0, a: 1, c: 2 })
expect(order).toEqual(['a', 'b', 'c'])
expect(patch).toEqual({ a: undefined, b: undefined, c: undefined })
})

it('counts hidden members so their place stays stable', () => {
const settings = {
...DEFAULT_STATE_USER_SETTINGS(),
docksHidden: ['b'],
}
expect(resolveGroupMemberMove(entries, 'g', settings, 'c', 'a')).toEqual({ c: 0, a: 1, b: 2 })
})

it('refuses a move across sub-categories', () => {
expect(move('a', 'x').patch).toBeNull()
expect(move('a', 'a').patch).toBeNull()
})
})
55 changes: 55 additions & 0 deletions packages/hub-ui/src/client/state/dock-settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,61 @@ export function getGroupMembers(
return getGroupMembersGrouped(entries, groupId, settings, options).flatMap(([, items]) => items)
}

/**
* The `docksCustomOrder` writes that store `ids` as the order of one container
* (a category, or one sub-category of a group). Each id maps to its new index.
* When `ids` already matches `defaultIds`, each id maps to `undefined` instead,
* which means "delete the custom order", so the default order applies again.
*/
export function resolveCustomOrderPatch(ids: readonly string[], defaultIds: readonly string[]): Record<string, number | undefined> {
const isDefault = ids.length === defaultIds.length && ids.every((id, i) => id === defaultIds[i])
return Object.fromEntries(ids.map((id, index) => [
id,
isDefault ? undefined : index,
]))
}

/** Write a {@link resolveCustomOrderPatch} result into a settings draft. */
export function applyCustomOrderPatch(state: DevframeDocksUserSettings, patch: Record<string, number | undefined>): void {
for (const [id, index] of Object.entries(patch)) {
if (index === undefined)
delete state.docksCustomOrder[id]
else
state.docksCustomOrder[id] = index
}
}

/**
* Move the group member `fromId` to the slot that `toId` holds, and return the
* `docksCustomOrder` writes for it (see {@link resolveCustomOrderPatch}). Both
* members must be in the same in-group sub-category, else this returns `null`.
* Hidden members count too, so their saved order stays stable.
*/
export function resolveGroupMemberMove(
entries: DevframeDockEntry[],
groupId: string,
settings: Immutable<DevframeDocksUserSettings>,
fromId: string,
toId: string,
): Record<string, number | undefined> | null {
if (fromId === toId)
return null
const found = getGroupMembersGrouped(entries, groupId, settings, { includeHidden: true })
.find(([, items]) => items.some(item => item.id === fromId))
if (!found)
return null
const [subcategory, items] = found
const ids = items.map(item => item.id)
const toIndex = ids.indexOf(toId)
if (toIndex === -1)
return null
ids.splice(toIndex, 0, ids.splice(ids.indexOf(fromId), 1)[0]!)
const defaultIds = getGroupMembersGrouped(entries, groupId, { ...settings, docksCustomOrder: {} }, { includeHidden: true })
.find(([category]) => category === subcategory)?.[1]
.map(item => item.id) ?? []
return resolveCustomOrderPatch(ids, defaultIds)
}

/**
* Resolve a group's `defaultChildId` to its target member, for the "clicking
* the group button jumps straight to this member" behavior (the dock-bar
Expand Down
Loading