Skip to content
Open
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
1 change: 1 addition & 0 deletions docs/content/1.guide/18.hub-initiate.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ interface DevframeHubUi {
- **`viewer`**: set to `false` to disable the standalone viewer.
- **`branding`**: rebrand the UI (logo, name, primary color). `background` accepts any CSS `background` value (color, gradient, image, or `transparent`) or `{ light, dark }` variants. These flat forms apply everywhere. Use `{ standalone, iframe? }` to specialize the framed viewer; an omitted `iframe` value falls back to `standalone`. Built-in devframe panels read `branding.primaryColor` from the existing connection metadata at startup and map it to CSS primary tokens. Standalone SPAs keep their default accent; status and preview palettes remain independent. Reload panels after changing startup branding.
- **`dockPreferences`** tunes the dock rail: `categoryOrder`, floating-dock `maxVisibleItems`, first-run `defaultMode` (`'float'`/`'edge'`) and `defaultPosition`.
- **`settingsDefaults`** seeds the settings the UI resolves below the visitor's own stored value, for defaults that belong to the project rather than the person. `commandShortcuts` takes the same overrides the Shortcuts settings page writes, with an empty array unbinding a command (`{ commandShortcuts: { 'devframes:toggle-palette': [] } }` leaves `Mod+K` free), and `docksCustomOrder`, `docksRecentLimit`, `showIframeAddressBar`, `closeOnOutsideClick`, `autoCollapseEdgeToolbar`, `expandGroupSidebar` and `showDevframeInspector` take their usual values. A setting the visitor changed wins over the seed, and a reset returns to the seed. `docksCustomOrder` merges per dock, so a dock the visitor reordered keeps the visitor's place when the project changes the seed later. The dock lists (`docksHidden`, `docksCategoriesHidden`, `docksPinned`) stay visitor-owned.
- **`embeddedVisibility`** sets the floating dock's reveal policy:
- `'normal'` (default): shows immediately.
- `'passive'`: hidden until `Shift+Alt+D`, then persisted per-origin (later browser sessions start shown).
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { t } from '../../i18n'
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'
import { resolveDefaultDocksCustomOrder, useSettings } from '../../state/settings-defaults'
import { accentVarStyle } from '../../utils/accent-color'
import { openDockContextMenu } from './DockContextMenu'
import DockGroupPopover from './DockGroupPopover.vue'
Expand All @@ -31,6 +31,9 @@ const DIVIDER_HEIGHT = 7 // 5 divider + 2 gap
const RESERVED_HEIGHT = 53

const settings = useSettings(props.context)
// What a sub-category falls back to when the visitor has not reordered it: the
// host seed over the declared order, not the declared order alone.
const fallbackCustomOrder = resolveDefaultDocksCustomOrder(props.context.rpc.connectionMeta.configs)

// Expanded: a wider rail with each member's title next to its icon. Row
// heights stay the same, so the capacity math below holds in both modes.
Expand Down Expand Up @@ -123,7 +126,7 @@ 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)
const patch = resolveGroupMemberMove(props.context.docks.entries, props.group.id, settings.value, fromId, toId, fallbackCustomOrder)
if (!patch)
return false
props.context.docks.settings.mutate(state => applyCustomOrderPatch(state, patch))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { useDraggable } from '@vueuse/core'
import { computed, ref, useTemplateRef } from 'vue'
import { t } from '../../i18n'
import { applyCustomOrderPatch, docksGroupByCategories, getCategoryLabel, getGroupMembers, getGroupMembersGrouped, isCategoryHideable, resolveCustomOrderPatch } from '../../state/dock-settings'
import { useSettings } from '../../state/settings-defaults'
import { resolveDefaultDocksCustomOrder, useSettings } from '../../state/settings-defaults'
import HashBadge from '../display/HashBadge.vue'
import DockIcon from '../dock/DockIcon.vue'

Expand All @@ -16,6 +16,9 @@ const props = defineProps<{

const settings = useSettings(props.context)
const settingsStore = props.context.docks.settings
// What a container's order falls back to when the visitor has not reordered
// it. Seeded by the host, so "the default order" is not the declared order.
const fallbackCustomOrder = resolveDefaultDocksCustomOrder(props.context.rpc.connectionMeta.configs)

// Top-level rows are grouped by category with members collapsed under their
// group button. A group's members are split by their in-group sub-category, and
Expand Down Expand Up @@ -64,14 +67,14 @@ function itemsOfContainer(container: string): DevframeDockEntry[] {
}

function defaultItemsOfContainer(container: string): DevframeDockEntry[] {
const noCustomOrder = { ...settings.value, docksCustomOrder: {} }
const fallback = { ...settings.value, docksCustomOrder: fallbackCustomOrder }
if (container.startsWith('grp:')) {
const { groupId, subcategory } = parseGroupContainer(container)
return getGroupMembersGrouped(props.context.docks.entries, groupId, noCustomOrder, { includeHidden: true })
return getGroupMembersGrouped(props.context.docks.entries, groupId, fallback, { includeHidden: true })
.find(([cat]) => cat === subcategory)?.[1] ?? []
}
const category = container.slice(4)
return docksGroupByCategories(props.context.docks.entries, noCustomOrder, { includeHidden: true, collapseGroups: true })
return docksGroupByCategories(props.context.docks.entries, fallback, { includeHidden: true, collapseGroups: true })
.find(([cat]) => cat === category)?.[1] ?? []
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import DisplayKbd from '@antfu/design/components/Display/DisplayKbd.vue'
import { computed, nextTick, ref, watch } from 'vue'
import { t } from '../../i18n'
import { filterCommandsByWhen, findCommandDeep, findKeybindingConflict, formatKeybinding, getShortcutRows, isKeybindingOverrideDifferentFromDefault, isMac, KNOWN_BROWSER_SHORTCUTS } from '../../state/keybindings'
import { useSettings } from '../../state/settings-defaults'
import { resolveSettingsDefaults, useSettings } from '../../state/settings-defaults'
import DockIcon from '../dock/DockIcon.vue'

const props = defineProps<{
Expand Down Expand Up @@ -67,7 +67,16 @@ function isOverridden(id: string): boolean {
return isKeybindingOverrideDifferentFromDefault(shortcutOverrides.value[id], getDefaultKeybindings(id))
}

/**
* What a reset returns to: the host's published default for this command
* (`createUi({ settingsDefaults })`), else the command's own binding. Comparing
* against it rather than against the declared binding keeps a seeded shortcut
* from reading as "overridden", and makes the clear button put the seed back.
*/
function getDefaultKeybindings(id: string): DevframeCommandKeybinding[] {
const seeded = resolveSettingsDefaults(props.context.rpc.connectionMeta.configs).commandShortcuts?.[id]
if (seeded !== undefined)
return seeded
return findCommandDeep(commandsCtx.commands, id)?.keybindings ?? []
}

Expand Down
113 changes: 111 additions & 2 deletions packages/hub-ui/src/client/state/commands.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { DevframeDocksUserSettings, DevframeServerCommandEntry } from '@devframes/hub'
import type { DevframeRpcClient } from '@devframes/hub/client'
import type { SharedState } from 'devframe/utils/shared-state'
import { DEFAULT_STATE_USER_SETTINGS, HUB_EVENTS } from '@devframes/hub/constants'
import { createSharedState } from 'devframe/utils/shared-state'
import { afterEach, describe, expect, it, vi } from 'vitest'
Expand All @@ -25,11 +26,12 @@ it.each(['standalone', 'shadow-root', 'popup'] as const)('leaves recording keyst
vi.mocked(useDockPopupWindow).mockReturnValue(popup)
const scope = effectScope()
try {
// eslint-disable-next-line slop/no-chained-type-assertions -- only sharedState is used by this command context fixture.
// eslint-disable-next-line slop/no-chained-type-assertions -- only sharedState and the connection meta are read by this command context fixture.
const rpc = {
sharedState: {
get: async () => createSharedState({ initialValue: [] }),
},
connectionMeta: { configs: {} },
} as unknown as DevframeRpcClient
const settings = createSharedState<DevframeDocksUserSettings>({
initialValue: {
Expand Down Expand Up @@ -123,12 +125,13 @@ describe('command shortcut eligibility', () => {
},
})
const call = vi.fn()
// eslint-disable-next-line slop/no-chained-type-assertions -- the command context only needs these two RPC APIs.
// eslint-disable-next-line slop/no-chained-type-assertions -- the command context only needs these two RPC APIs and the connection meta.
const rpc = {
sharedState: {
get: async () => serverState,
},
call,
connectionMeta: { configs: {} },
} as unknown as DevframeRpcClient
const window = new EventTarget()
vi.stubGlobal('window', window)
Expand Down Expand Up @@ -169,3 +172,109 @@ describe('command shortcut eligibility', () => {
expect(call).toHaveBeenCalledExactlyOnceWith(HUB_EVENTS.rpc.commandsExecute, command.id, 'src/main.ts')
})
})

describe('keybindings seeded by the host', () => {
/** An RPC fixture that answers with no server commands and carries the host's `ui` config. */
function createRpc(settingsDefaults?: Partial<DevframeDocksUserSettings>): DevframeRpcClient {
// eslint-disable-next-line slop/no-chained-type-assertions -- only shared state and the connection meta are read while the context boots.
return {
sharedState: {
get: async () => createSharedState({ initialValue: [] }),
},
connectionMeta: {
configs: settingsDefaults
? {
ui: { settingsDefaults },
}
: {},
},
} as unknown as DevframeRpcClient
}

function createSettings(): SharedState<DevframeDocksUserSettings> {
return createSharedState<DevframeDocksUserSettings>({
initialValue: DEFAULT_STATE_USER_SETTINGS(),
})
}

it('binds a command to the host default when the user has no override', async () => {
expect.assertions(1)

const settings = createSettings()
const context = await createCommandsContext(
'standalone',
createRpc({
commandShortcuts: {
'test:seeded': [
{ key: 'Mod+J' },
],
},
}),
settings,
)
context.register({
id: 'test:seeded',
source: 'client',
title: 'Seeded',
keybindings: [
{ key: 'Mod+K' },
],
action: () => {},
})

expect(context.getKeybindings('test:seeded')).toEqual([
{ key: 'Mod+J' },
])
})

it('lets a user override win over the host default', async () => {
expect.assertions(1)

const settings = createSettings()
const context = await createCommandsContext(
'standalone',
createRpc({
commandShortcuts: {
'test:seeded': [
{ key: 'Mod+J' },
],
},
}),
settings,
)
context.register({
id: 'test:seeded',
source: 'client',
title: 'Seeded',
keybindings: [
{ key: 'Mod+K' },
],
action: () => {},
})
settings.mutate((state) => {
state.commandShortcuts['test:seeded'] = []
})

expect(context.getKeybindings('test:seeded')).toEqual([])
})

it('keeps the declared keybinding when the host seeds nothing', async () => {
expect.assertions(1)

const settings = createSettings()
const context = await createCommandsContext('standalone', createRpc(), settings)
context.register({
id: 'test:declared',
source: 'client',
title: 'Declared',
keybindings: [
{ key: 'Mod+K' },
],
action: () => {},
})

expect(context.getKeybindings('test:declared')).toEqual([
{ key: 'Mod+K' },
])
})
})
9 changes: 9 additions & 0 deletions packages/hub-ui/src/client/state/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { sharedStateToRef } from './docks'
import { collectAllKeybindings, filterCommandsByWhen, findCommandDeep, normalizeKeyEvent } from './keybindings'
import { localizeCommand } from './locale'
import { useDockPopupWindow, useIsDockPopupOpen } from './popup'
import { resolveSettingsDefaults } from './settings-defaults'

const commandsContextByRpc = new WeakMap<DevframeRpcClient, CommandsContext>()

Expand All @@ -32,6 +33,10 @@ export async function createCommandsContext(
// Shortcut overrides from user settings
const settings = sharedStateToRef(settingsState)
const shortcutOverrides = computed(() => settings.value.commandShortcuts ?? {})
// The host's published defaults sit between a user override and the
// command's declared keybinding, so a project can leave a shortcut unbound
// for everyone while a developer who binds it themselves still wins.
const seededShortcuts = computed(() => resolveSettingsDefaults(rpc.connectionMeta.configs).commandShortcuts ?? {})

const paletteOpen = ref(false)
// See `CommandsContext.paletteScopeId` for the contract; the palette owns
Expand Down Expand Up @@ -117,6 +122,10 @@ export async function createCommandsContext(
if (overrides !== undefined)
return overrides

const seeded = seededShortcuts.value[id]
if (seeded !== undefined)
return seeded

return cmd?.keybindings ?? []
}

Expand Down
13 changes: 9 additions & 4 deletions packages/hub-ui/src/client/state/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import { localizeTitle } from './locale'
import { createClientMessagesClient } from './messages-client'
import { dockCommandId } from './palette'
import { registerMainFrameDockActionHandler, triggerMainFrameDockAction, useIsDockPopupOpen } from './popup'
import { resolveSettingsDefaults, resolveUserSettings } from './settings-defaults'
import { clientScriptOf, executeSetupScript } from './setup-script'

const docksContextByRpc = new WeakMap<DevframeRpcClient, DocksContext>()
Expand Down Expand Up @@ -217,10 +218,14 @@ export async function createDocksContext(
// Get settings store ahead of `switchEntry`, whose group→member resolution
// needs `getWhenContext` to honor a `defaultChildId` target's `when` clause.
const settingsStore = markRaw(await getSettingsStore())
// Raw, not `useSettings`: the context this would key off doesn't exist yet,
// and the only consumers are the `dock-settings.ts` helpers below, which
// resolve hub-ui's own defaults themselves.
const settings = sharedStateToRef(settingsStore)
// Resolved, not raw: the dock grouping below and the `dock-settings.ts`
// helpers read a settings object directly, so the host's published defaults
// (`createUi({ settingsDefaults })`) and hub-ui's fallbacks are merged in
// first. Writes keep going to `settingsStore`, never to this view.
// `sharedStateToRef` registers a listener per call, so it stays outside.
const storedSettings = sharedStateToRef(settingsStore)
const settingsDefaults = resolveSettingsDefaults(rpc.connectionMeta.configs)
const settings = computed(() => resolveUserSettings(storedSettings.value, settingsDefaults))

// Shared when-context provider, used by both commands and docks
let commandsContext: CommandsContext
Expand Down
14 changes: 12 additions & 2 deletions packages/hub-ui/src/client/state/dock-settings.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -443,12 +443,12 @@ describe('resolveGroupMemberMove', () => {
iframe('x', { groupId: 'g', category: 'other' }),
]

function move(fromId: string, toId: string, docksCustomOrder: Record<string, number> = {}) {
function move(fromId: string, toId: string, docksCustomOrder: Record<string, number> = {}, fallbackCustomOrder: Record<string, number> = {}) {
const settings = {
...DEFAULT_STATE_USER_SETTINGS(),
docksCustomOrder,
}
const patch = resolveGroupMemberMove(entries, 'g', settings, fromId, toId)
const patch = resolveGroupMemberMove(entries, 'g', settings, fromId, toId, fallbackCustomOrder)
if (patch)
applyCustomOrderPatch(settings, patch)
const order = getGroupMembersGrouped(entries, 'g', settings).find(([category]) => category === 'default')![1]
Expand All @@ -472,6 +472,16 @@ describe('resolveGroupMemberMove', () => {
expect(patch).toEqual({ a: undefined, b: undefined, c: undefined })
})

it('writes a move off the seeded order even when it matches the declared order', () => {
// The host seeds b,a,c. Moving b back under a lands on the declared order,
// but it is still the visitor's choice, so it has to be written down:
// deleting it would let the seed put b first again.
const seeded = { b: 0, a: 1, c: 2 }
const { patch, order } = move('b', 'a', seeded, seeded)
expect(order).toEqual(['a', 'b', 'c'])
expect(patch).toEqual({ a: 0, b: 1, c: 2 })
})

it('counts hidden members so their place stays stable', () => {
const settings = {
...DEFAULT_STATE_USER_SETTINGS(),
Expand Down
12 changes: 11 additions & 1 deletion packages/hub-ui/src/client/state/dock-settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,10 @@ export function getGroupMembers(
* (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.
*
* `defaultIds` is the order the container falls back to, which includes the
* host seed (see `resolveDefaultDocksCustomOrder`), not the declared order
* alone.
*/
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])
Expand All @@ -237,13 +241,19 @@ export function applyCustomOrderPatch(state: DevframeDocksUserSettings, patch: R
* `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.
*
* `fallbackCustomOrder` is what the sub-category falls back to when the visitor
* has not reordered it (the host seed, `resolveDefaultDocksCustomOrder`). A
* move that lands on the declared order is still a move when the seed put the
* members elsewhere, so this must not default to the declared order.
*/
export function resolveGroupMemberMove(
entries: DevframeDockEntry[],
groupId: string,
settings: Immutable<DevframeDocksUserSettings>,
fromId: string,
toId: string,
fallbackCustomOrder: Immutable<DevframeDocksUserSettings>['docksCustomOrder'] = {},
): Record<string, number | undefined> | null {
if (fromId === toId)
return null
Expand All @@ -257,7 +267,7 @@ export function resolveGroupMemberMove(
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 })
const defaultIds = getGroupMembersGrouped(entries, groupId, { ...settings, docksCustomOrder: fallbackCustomOrder }, { includeHidden: true })
.find(([category]) => category === subcategory)?.[1]
.map(item => item.id) ?? []
return resolveCustomOrderPatch(ids, defaultIds)
Expand Down
Loading
Loading