Skip to content

Commit abe2626

Browse files
authored
feat(hub-ui): reorder tools in the group sidebar (#499)
* feat(hub-ui): reorder tools in the group sidebar Drag a tool up or down in the group sidebar, or press Alt+ArrowUp / Alt+ArrowDown on it, to change its place inside its sub-category. The order is saved to docksCustomOrder, the setting Settings > Docks edits. The patch logic moves to dock-settings so both surfaces share it. * docs(hub): document reordering tools in the group sidebar
1 parent 26e0d45 commit abe2626

5 files changed

Lines changed: 244 additions & 17 deletions

File tree

‎docs/content/1.guide/16.hub.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -272,11 +272,12 @@ The first time any member of a group opens in a session, the hub also loads the
272272

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

275-
### Pinned and recent tools
275+
### Pinned, reordered, and recent tools
276276

277277
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.
278278

279279
- **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.
280+
- **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.
280281
- **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.
281282

282283
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.

‎packages/hub-ui/src/client/components/dock/DockGroupSidebar.vue‎

Lines changed: 118 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,9 @@
22
import type { DevframeDockEntry, DevframeViewGroup } from '@devframes/hub'
33
import type { DocksContext } from '@devframes/hub/client'
44
import { watchDebounced } from '@vueuse/core'
5-
import { computed, h, ref, useTemplateRef, watch } from 'vue'
5+
import { computed, h, nextTick, ref, useTemplateRef, watch } from 'vue'
66
import { t } from '../../i18n'
7-
import { deriveSidebarCapacity, docksSplitGroupsWithCapacity, getGroupMembersGrouped } from '../../state/dock-settings'
7+
import { applyCustomOrderPatch, deriveSidebarCapacity, docksSplitGroupsWithCapacity, getGroupMembersGrouped, resolveGroupMemberMove } from '../../state/dock-settings'
88
import { getCurrentDockId } from '../../state/docks'
99
import { dockTooltipContent, setDocksSidebarOverflowPanel, setFloatingTooltip, useDocksSidebarOverflowPanel } from '../../state/floating-tooltip'
1010
import { useSettings } from '../../state/settings-defaults'
@@ -101,10 +101,112 @@ const currentInOverflow = computed(() =>
101101
const selectedInOverflow = computed(() =>
102102
!!props.selectedId && overflowGroups.value.some(([, items]) => items.some(m => m.id === props.selectedId)))
103103
104+
// Set when a drag ends, so the click that follows it does not open the member.
105+
let suppressClick = false
106+
104107
function select(id: string) {
108+
if (suppressClick) {
109+
suppressClick = false
110+
return
111+
}
105112
props.context.docks.switchEntry(id)
106113
}
107114
115+
// --- Reorder ---
116+
// Drag a member up or down within its sub-category, or press Alt+ArrowUp /
117+
// Alt+ArrowDown on it. The order is saved to `docksCustomOrder`, the same
118+
// setting the Docks settings page edits. Pointer capture keeps the drag alive
119+
// while the pointer crosses the panel's iframe.
120+
const DRAG_THRESHOLD = 4
121+
const draggingId = ref<string | null>(null)
122+
const dragOverId = ref<string | null>(null)
123+
let dragStart: { id: string, y: number } | null = null
124+
125+
function moveMember(fromId: string, toId: string): boolean {
126+
const patch = resolveGroupMemberMove(props.context.docks.entries, props.group.id, settings.value, fromId, toId)
127+
if (!patch)
128+
return false
129+
props.context.docks.settings.mutate(state => applyCustomOrderPatch(state, patch))
130+
return true
131+
}
132+
133+
function findSubcategory(id: string) {
134+
return visibleGroups.value.find(([, items]) => items.some(m => m.id === id))
135+
}
136+
137+
// Where the drop line shows on the hovered member: the dragged member takes
138+
// the hovered member's slot, so it lands before it when moving up and after
139+
// it when moving down.
140+
const dropSide = computed<'before' | 'after' | null>(() => {
141+
if (!draggingId.value || !dragOverId.value)
142+
return null
143+
const items = findSubcategory(draggingId.value)?.[1] ?? []
144+
const from = items.findIndex(m => m.id === draggingId.value)
145+
const to = items.findIndex(m => m.id === dragOverId.value)
146+
return from > to
147+
? 'before'
148+
: 'after'
149+
})
150+
151+
function onMemberPointerDown(event: PointerEvent, id: string) {
152+
hideTooltip()
153+
suppressClick = false
154+
if (event.button !== 0)
155+
return
156+
dragStart = { id, y: event.clientY }
157+
;(event.currentTarget as HTMLElement).setPointerCapture(event.pointerId)
158+
}
159+
160+
function onMemberPointerMove(event: PointerEvent) {
161+
if (!dragStart)
162+
return
163+
if (!draggingId.value) {
164+
if (Math.abs(event.clientY - dragStart.y) < DRAG_THRESHOLD)
165+
return
166+
draggingId.value = dragStart.id
167+
}
168+
const peers = findSubcategory(dragStart.id)?.[1] ?? []
169+
const target = peers.find((m) => {
170+
const rect = sidebar.value?.querySelector(`[data-dock-id="${CSS.escape(m.id)}"]`)?.getBoundingClientRect()
171+
return rect && event.clientY >= rect.top && event.clientY <= rect.bottom
172+
})
173+
dragOverId.value = target && target.id !== dragStart.id
174+
? target.id
175+
: null
176+
}
177+
178+
function onMemberPointerUp() {
179+
if (draggingId.value) {
180+
// A drag is not a click, even when it ends on the start button.
181+
suppressClick = true
182+
if (dragOverId.value)
183+
moveMember(draggingId.value, dragOverId.value)
184+
}
185+
resetDrag()
186+
}
187+
188+
function resetDrag() {
189+
dragStart = null
190+
draggingId.value = null
191+
dragOverId.value = null
192+
}
193+
194+
async function onMemberKeydown(event: KeyboardEvent, id: string) {
195+
if (!event.altKey || (event.key !== 'ArrowUp' && event.key !== 'ArrowDown'))
196+
return
197+
event.preventDefault()
198+
const items = findSubcategory(id)?.[1] ?? []
199+
const index = items.findIndex(m => m.id === id)
200+
const neighbor = items[index + (event.key === 'ArrowUp'
201+
? -1
202+
: 1)]
203+
if (!neighbor || !moveMember(id, neighbor.id))
204+
return
205+
// Moving the focused button in the DOM can drop focus, so put it back.
206+
await nextTick()
207+
sidebar.value?.querySelector<HTMLElement>(`[data-dock-id="${CSS.escape(id)}"]`)?.focus()
208+
}
209+
108210
function showTooltip(event: PointerEvent, entry: { title: string, description?: string }) {
109211
setFloatingTooltip({
110212
content: dockTooltipContent(entry),
@@ -212,19 +314,31 @@ const moreButtonActive = computed(() => selectedInOverflow.value || isOverflowPa
212314
<button
213315
v-for="member of members"
214316
:key="member.id"
317+
:data-dock-id="member.id"
215318
:aria-label="member.title"
216319
:aria-current="currentId === member.id ? 'page' : undefined"
217320
class="relative flex items-center h-8 rounded-lg transition"
218321
:class="[
219322
expanded ? 'gap-2 px1.5' : 'justify-center w-8',
220323
selectedId === member.id ? 'text-primary bg-active' : 'op60 hover:op100 hover:bg-active',
324+
draggingId === member.id ? 'op30!' : '',
221325
]"
222-
@pointerenter="showTooltip($event, member)"
326+
@pointerenter="draggingId || showTooltip($event, member)"
223327
@pointerleave="hideTooltip"
224-
@pointerdown="hideTooltip"
328+
@pointerdown="onMemberPointerDown($event, member.id)"
329+
@pointermove="onMemberPointerMove"
330+
@pointerup="onMemberPointerUp"
331+
@pointercancel="resetDrag"
225332
@click="select(member.id)"
333+
@keydown="onMemberKeydown($event, member.id)"
226334
@contextmenu="openContextMenu($event, member)"
227335
>
336+
<!-- Drop line: where the dragged member will land -->
337+
<div
338+
v-if="dragOverId === member.id"
339+
class="absolute inset-x-1 h-0.5 rounded-full bg-primary pointer-events-none"
340+
:class="dropSide === 'before' ? '-top-0.5' : '-bottom-0.5'"
341+
/>
228342
<DockIcon :icon="member.icon" class="w-5 h-5 flex-none" />
229343
<span v-if="expanded" class="flex-1 min-w-0 text-left text-sm truncate">{{ member.title }}</span>
230344
<div

‎packages/hub-ui/src/client/components/views-builtin/SettingsDocks.vue‎

Lines changed: 6 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import type { DevframeDockEntriesGrouped } from '../../state/dock-settings'
55
import { useDraggable } from '@vueuse/core'
66
import { computed, ref, useTemplateRef } from 'vue'
77
import { t } from '../../i18n'
8-
import { docksGroupByCategories, getCategoryLabel, getGroupMembers, getGroupMembersGrouped, isCategoryHideable } from '../../state/dock-settings'
8+
import { applyCustomOrderPatch, docksGroupByCategories, getCategoryLabel, getGroupMembers, getGroupMembersGrouped, isCategoryHideable, resolveCustomOrderPatch } from '../../state/dock-settings'
99
import { useSettings } from '../../state/settings-defaults'
1010
import HashBadge from '../display/HashBadge.vue'
1111
import DockIcon from '../dock/DockIcon.vue'
@@ -104,16 +104,11 @@ function isInteractiveElement(el: HTMLElement | null): boolean {
104104
}
105105
106106
function applyOrder(container: string, items: DevframeDockEntry[]) {
107-
const def = defaultItemsOfContainer(container).map(i => i.id)
108-
const isDefault = items.length === def.length && items.every((item, i) => item.id === def[i])
109-
settingsStore.mutate((state) => {
110-
items.forEach((item, index) => {
111-
if (isDefault)
112-
delete state.docksCustomOrder[item.id]
113-
else
114-
state.docksCustomOrder[item.id] = index
115-
})
116-
})
107+
const patch = resolveCustomOrderPatch(
108+
items.map(i => i.id),
109+
defaultItemsOfContainer(container).map(i => i.id),
110+
)
111+
settingsStore.mutate(state => applyCustomOrderPatch(state, patch))
117112
}
118113
119114
useDraggable(sortContainerEl, {

‎packages/hub-ui/src/client/state/dock-settings.test.ts‎

Lines changed: 63 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import type { DevframeDockEntriesGrouped, DevframeDockEntry, DevframeViewGroup }
22
import type { WhenContext } from 'devframe/utils/when'
33
import { DEFAULT_STATE_USER_SETTINGS } from '@devframes/hub/constants'
44
import { describe, expect, it } from 'vitest'
5-
import { docksGroupByCategories, docksSplitGroupsBySize, docksSplitGroupsWithCapacity, getGroupMembersGrouped, resolveGroupPreferredChild, resolveNextRecentDockIds, resolveRecentDockEntries } from './dock-settings'
5+
import { applyCustomOrderPatch, docksGroupByCategories, docksSplitGroupsBySize, docksSplitGroupsWithCapacity, getGroupMembersGrouped, resolveCustomOrderPatch, resolveGroupMemberMove, resolveGroupPreferredChild, resolveNextRecentDockIds, resolveRecentDockEntries } from './dock-settings'
66

77
function iframe(id: string, extra: Partial<DevframeDockEntry> = {}): DevframeDockEntry {
88
return {
@@ -423,3 +423,65 @@ describe('resolveRecentDockEntries', () => {
423423
expect(resolve(['d'], 0)).toEqual([])
424424
})
425425
})
426+
427+
describe('resolveCustomOrderPatch', () => {
428+
it('maps each id to its index', () => {
429+
expect(resolveCustomOrderPatch(['b', 'a'], ['a', 'b'])).toEqual({ b: 0, a: 1 })
430+
})
431+
432+
it('clears the custom order when the order matches the default', () => {
433+
expect(resolveCustomOrderPatch(['a', 'b'], ['a', 'b'])).toEqual({ a: undefined, b: undefined })
434+
})
435+
})
436+
437+
describe('resolveGroupMemberMove', () => {
438+
const entries = [
439+
group('g'),
440+
iframe('a', { groupId: 'g', defaultOrder: 1 }),
441+
iframe('b', { groupId: 'g', defaultOrder: 2 }),
442+
iframe('c', { groupId: 'g', defaultOrder: 3 }),
443+
iframe('x', { groupId: 'g', category: 'other' }),
444+
]
445+
446+
function move(fromId: string, toId: string, docksCustomOrder: Record<string, number> = {}) {
447+
const settings = {
448+
...DEFAULT_STATE_USER_SETTINGS(),
449+
docksCustomOrder,
450+
}
451+
const patch = resolveGroupMemberMove(entries, 'g', settings, fromId, toId)
452+
if (patch)
453+
applyCustomOrderPatch(settings, patch)
454+
const order = getGroupMembersGrouped(entries, 'g', settings).find(([category]) => category === 'default')![1]
455+
return {
456+
patch,
457+
order: order.map(item => item.id),
458+
}
459+
}
460+
461+
it('moves a member down into the slot of the target', () => {
462+
expect(move('a', 'c').order).toEqual(['b', 'c', 'a'])
463+
})
464+
465+
it('moves a member up into the slot of the target', () => {
466+
expect(move('c', 'a').order).toEqual(['c', 'a', 'b'])
467+
})
468+
469+
it('clears the custom order when the move restores the default', () => {
470+
const { patch, order } = move('a', 'b', { b: 0, a: 1, c: 2 })
471+
expect(order).toEqual(['a', 'b', 'c'])
472+
expect(patch).toEqual({ a: undefined, b: undefined, c: undefined })
473+
})
474+
475+
it('counts hidden members so their place stays stable', () => {
476+
const settings = {
477+
...DEFAULT_STATE_USER_SETTINGS(),
478+
docksHidden: ['b'],
479+
}
480+
expect(resolveGroupMemberMove(entries, 'g', settings, 'c', 'a')).toEqual({ c: 0, a: 1, b: 2 })
481+
})
482+
483+
it('refuses a move across sub-categories', () => {
484+
expect(move('a', 'x').patch).toBeNull()
485+
expect(move('a', 'a').patch).toBeNull()
486+
})
487+
})

‎packages/hub-ui/src/client/state/dock-settings.ts‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -208,6 +208,61 @@ export function getGroupMembers(
208208
return getGroupMembersGrouped(entries, groupId, settings, options).flatMap(([, items]) => items)
209209
}
210210

211+
/**
212+
* The `docksCustomOrder` writes that store `ids` as the order of one container
213+
* (a category, or one sub-category of a group). Each id maps to its new index.
214+
* When `ids` already matches `defaultIds`, each id maps to `undefined` instead,
215+
* which means "delete the custom order", so the default order applies again.
216+
*/
217+
export function resolveCustomOrderPatch(ids: readonly string[], defaultIds: readonly string[]): Record<string, number | undefined> {
218+
const isDefault = ids.length === defaultIds.length && ids.every((id, i) => id === defaultIds[i])
219+
return Object.fromEntries(ids.map((id, index) => [
220+
id,
221+
isDefault ? undefined : index,
222+
]))
223+
}
224+
225+
/** Write a {@link resolveCustomOrderPatch} result into a settings draft. */
226+
export function applyCustomOrderPatch(state: DevframeDocksUserSettings, patch: Record<string, number | undefined>): void {
227+
for (const [id, index] of Object.entries(patch)) {
228+
if (index === undefined)
229+
delete state.docksCustomOrder[id]
230+
else
231+
state.docksCustomOrder[id] = index
232+
}
233+
}
234+
235+
/**
236+
* Move the group member `fromId` to the slot that `toId` holds, and return the
237+
* `docksCustomOrder` writes for it (see {@link resolveCustomOrderPatch}). Both
238+
* members must be in the same in-group sub-category, else this returns `null`.
239+
* Hidden members count too, so their saved order stays stable.
240+
*/
241+
export function resolveGroupMemberMove(
242+
entries: DevframeDockEntry[],
243+
groupId: string,
244+
settings: Immutable<DevframeDocksUserSettings>,
245+
fromId: string,
246+
toId: string,
247+
): Record<string, number | undefined> | null {
248+
if (fromId === toId)
249+
return null
250+
const found = getGroupMembersGrouped(entries, groupId, settings, { includeHidden: true })
251+
.find(([, items]) => items.some(item => item.id === fromId))
252+
if (!found)
253+
return null
254+
const [subcategory, items] = found
255+
const ids = items.map(item => item.id)
256+
const toIndex = ids.indexOf(toId)
257+
if (toIndex === -1)
258+
return null
259+
ids.splice(toIndex, 0, ids.splice(ids.indexOf(fromId), 1)[0]!)
260+
const defaultIds = getGroupMembersGrouped(entries, groupId, { ...settings, docksCustomOrder: {} }, { includeHidden: true })
261+
.find(([category]) => category === subcategory)?.[1]
262+
.map(item => item.id) ?? []
263+
return resolveCustomOrderPatch(ids, defaultIds)
264+
}
265+
211266
/**
212267
* Resolve a group's `defaultChildId` to its target member, for the "clicking
213268
* the group button jumps straight to this member" behavior (the dock-bar

0 commit comments

Comments
 (0)