diff --git a/docs/content/1.guide/18.hub-initiate.md b/docs/content/1.guide/18.hub-initiate.md index e8381b47..2d5051dd 100644 --- a/docs/content/1.guide/18.hub-initiate.md +++ b/docs/content/1.guide/18.hub-initiate.md @@ -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). diff --git a/packages/hub-ui/src/client/components/dock/DockGroupSidebar.vue b/packages/hub-ui/src/client/components/dock/DockGroupSidebar.vue index fa3a6fe2..26378c32 100644 --- a/packages/hub-ui/src/client/components/dock/DockGroupSidebar.vue +++ b/packages/hub-ui/src/client/components/dock/DockGroupSidebar.vue @@ -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' @@ -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. @@ -123,7 +126,7 @@ const dragOverId = ref(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)) diff --git a/packages/hub-ui/src/client/components/views-builtin/SettingsDocks.vue b/packages/hub-ui/src/client/components/views-builtin/SettingsDocks.vue index e81fdb82..7ca55630 100644 --- a/packages/hub-ui/src/client/components/views-builtin/SettingsDocks.vue +++ b/packages/hub-ui/src/client/components/views-builtin/SettingsDocks.vue @@ -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' @@ -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 @@ -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] ?? [] } diff --git a/packages/hub-ui/src/client/components/views-builtin/SettingsShortcuts.vue b/packages/hub-ui/src/client/components/views-builtin/SettingsShortcuts.vue index 3e7c88fd..79b22265 100644 --- a/packages/hub-ui/src/client/components/views-builtin/SettingsShortcuts.vue +++ b/packages/hub-ui/src/client/components/views-builtin/SettingsShortcuts.vue @@ -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<{ @@ -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 ?? [] } diff --git a/packages/hub-ui/src/client/state/commands.test.ts b/packages/hub-ui/src/client/state/commands.test.ts index 7dc0f8ad..a8d33f8b 100644 --- a/packages/hub-ui/src/client/state/commands.test.ts +++ b/packages/hub-ui/src/client/state/commands.test.ts @@ -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' @@ -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({ initialValue: { @@ -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) @@ -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): 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 { + return createSharedState({ + 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' }, + ]) + }) +}) diff --git a/packages/hub-ui/src/client/state/commands.ts b/packages/hub-ui/src/client/state/commands.ts index c1b3a2a5..9aafc758 100644 --- a/packages/hub-ui/src/client/state/commands.ts +++ b/packages/hub-ui/src/client/state/commands.ts @@ -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() @@ -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 @@ -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 ?? [] } diff --git a/packages/hub-ui/src/client/state/context.ts b/packages/hub-ui/src/client/state/context.ts index d9a31396..66cf74e1 100644 --- a/packages/hub-ui/src/client/state/context.ts +++ b/packages/hub-ui/src/client/state/context.ts @@ -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() @@ -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 diff --git a/packages/hub-ui/src/client/state/dock-settings.test.ts b/packages/hub-ui/src/client/state/dock-settings.test.ts index 0ac06352..22ba4c37 100644 --- a/packages/hub-ui/src/client/state/dock-settings.test.ts +++ b/packages/hub-ui/src/client/state/dock-settings.test.ts @@ -443,12 +443,12 @@ describe('resolveGroupMemberMove', () => { iframe('x', { groupId: 'g', category: 'other' }), ] - function move(fromId: string, toId: string, docksCustomOrder: Record = {}) { + function move(fromId: string, toId: string, docksCustomOrder: Record = {}, fallbackCustomOrder: Record = {}) { 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] @@ -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(), diff --git a/packages/hub-ui/src/client/state/dock-settings.ts b/packages/hub-ui/src/client/state/dock-settings.ts index e704a7fe..d85004d1 100644 --- a/packages/hub-ui/src/client/state/dock-settings.ts +++ b/packages/hub-ui/src/client/state/dock-settings.ts @@ -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 { const isDefault = ids.length === defaultIds.length && ids.every((id, i) => id === defaultIds[i]) @@ -237,6 +241,11 @@ 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[], @@ -244,6 +253,7 @@ export function resolveGroupMemberMove( settings: Immutable, fromId: string, toId: string, + fallbackCustomOrder: Immutable['docksCustomOrder'] = {}, ): Record | null { if (fromId === toId) return null @@ -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) diff --git a/packages/hub-ui/src/client/state/settings-defaults.test.ts b/packages/hub-ui/src/client/state/settings-defaults.test.ts new file mode 100644 index 00000000..61d97b6e --- /dev/null +++ b/packages/hub-ui/src/client/state/settings-defaults.test.ts @@ -0,0 +1,124 @@ +import type { DevframeDockEntry } from '@devframes/hub' +import type { DocksContext } from '@devframes/hub/client' +import type { DevframeConnectionConfigsRegistry } from 'devframe/types' +import { DEFAULT_STATE_USER_SETTINGS } from '@devframes/hub/constants' +import { createSharedState } from 'devframe/utils/shared-state' +import { describe, expect, it } from 'vitest' +import { applyCustomOrderPatch, getGroupMembersGrouped, resolveGroupMemberMove } from './dock-settings' +import { useSettings } from './settings-defaults' + +/** A context whose connection meta carries the host-published `ui` config. */ +function createContext(ui?: DevframeConnectionConfigsRegistry['ui']): DocksContext { + const context = { + rpc: { + connectionMeta: { + configs: ui + ? { ui } + : {}, + }, + }, + docks: { + settings: createSharedState({ + initialValue: DEFAULT_STATE_USER_SETTINGS(), + }), + }, + } + // eslint-disable-next-line slop/no-chained-type-assertions -- `useSettings` reads only `rpc.connectionMeta` and `docks.settings`, so the fixture carries just those. + return context as unknown as DocksContext +} + +/** A dock entry that lives inside the group `g`. */ +function member(id: string, defaultOrder: number): DevframeDockEntry { + return { + id, + type: 'iframe', + url: '/', + title: id.toUpperCase(), + icon: 'ph:cube-duotone', + groupId: 'g', + defaultOrder, + } +} + +describe('settings defaults published by the host', () => { + it('keeps a seeded dock order as the default a reorder falls back to', () => { + expect.assertions(3) + + const entries: DevframeDockEntry[] = [ + { + id: 'g', + type: 'group', + title: 'G', + icon: 'ph:folder-duotone', + }, + member('a', 1), + member('b', 2), + member('c', 3), + ] + const seed = { b: 0, a: 1, c: 2 } + const context = createContext({ + settingsDefaults: { docksCustomOrder: seed }, + }) + function order() { + return getGroupMembersGrouped(entries, 'g', useSettings(context).value, { includeHidden: true }) + .find(([category]) => category === 'default')![1] + .map(item => item.id) + } + + expect(order()).toEqual(['b', 'a', 'c']) + + // "Move down" on the seeded-first member b. It lands on the declared order, + // which still has to be written: a deleted write would let the seed put b + // back at the top. + const patch = resolveGroupMemberMove(entries, 'g', useSettings(context).value, 'b', 'a', seed) + context.docks.settings.mutate(state => applyCustomOrderPatch(state, patch!)) + expect(order()).toEqual(['a', 'b', 'c']) + + // Reset drops the visitor's own order and returns to the seed. + context.docks.settings.mutate((state) => { + state.docksCustomOrder = {} + }) + expect(order()).toEqual(['b', 'a', 'c']) + }) + + it('applies the host default under the stored value', () => { + expect.assertions(2) + + const context = createContext({ + settingsDefaults: { + docksRecentLimit: 0, + docksCustomOrder: { 'dock-a': 1 }, + }, + }) + context.docks.settings.mutate((state) => { + state.docksCustomOrder['dock-b'] = 2 + }) + + expect(useSettings(context).value.docksRecentLimit).toBe(0) + expect(useSettings(context).value.docksCustomOrder).toEqual({ 'dock-a': 1, 'dock-b': 2 }) + }) + + it('lets the visitor\'s own value win over the host default', () => { + expect.assertions(1) + + const context = createContext({ + settingsDefaults: { docksRecentLimit: 0 }, + }) + context.docks.settings.mutate((state) => { + state.docksRecentLimit = 5 + }) + + expect(useSettings(context).value.docksRecentLimit).toBe(5) + }) + + it('keeps the built-in hub-ui defaults when the host publishes nothing', () => { + expect.assertions(3) + + const context = createContext() + const settings = useSettings(context).value + + expect(settings.docksRecentLimit).toBe(3) + expect(settings.autoCollapseEdgeToolbar).toBe(true) + expect(settings.showDevframeInspector).toBe(false) + }) +}) diff --git a/packages/hub-ui/src/client/state/settings-defaults.ts b/packages/hub-ui/src/client/state/settings-defaults.ts index e115b80d..a584c4fd 100644 --- a/packages/hub-ui/src/client/state/settings-defaults.ts +++ b/packages/hub-ui/src/client/state/settings-defaults.ts @@ -1,6 +1,9 @@ import type { DevframeDocksUserSettings } from '@devframes/hub' import type { DocksContext } from '@devframes/hub/client' +import type { ConnectionMeta } from 'devframe/types' +import type { Immutable } from 'devframe/utils/shared-state' import type { ComputedRef } from 'vue' +import type { DocksUserSettingsDefaults } from '../../types' import { computed } from 'vue' import { sharedStateToRef } from './docks' // Registers hub-ui's own settings fields onto DevframeDocksUserSettings. @@ -45,6 +48,65 @@ const HUB_UI_SETTINGS_DEFAULTS: Required = Object.freeze({ expandGroupSidebar: false, }) +/** + * Read the host-published settings defaults off the connection meta. + * + * `configs` is a one-way, boot-time channel, so this is a plain lookup with no + * subscription: the value is fixed for the life of the page. + */ +export function resolveSettingsDefaults(configs: ConnectionMeta['configs'] | undefined): DocksUserSettingsDefaults { + return configs?.ui?.settingsDefaults ?? {} +} + +/** + * The `docksCustomOrder` a container falls back to when the visitor has not + * reordered it: the host seed, or an empty map (the declared order) when the + * host seeds none. + * + * This is the baseline a reorder is compared against. Comparing against the + * declared order instead would read a move that lands there as "no change" and + * delete it, and the seed would put the dock straight back. + */ +export function resolveDefaultDocksCustomOrder(configs: ConnectionMeta['configs'] | undefined): Record { + return resolveSettingsDefaults(configs).docksCustomOrder ?? {} +} + +/** Drop `undefined` values so a partial seed never clobbers a lower layer. */ +function omitUndefined(value: T): Partial { + return Object.fromEntries( + Object.entries(value).filter(([, entry]) => entry !== undefined), + ) as Partial +} + +/** + * The one place the settings layers stack: built-in hub-ui defaults, then the + * host's published defaults, then whatever the visitor stored. The stored + * value wins because a choice made in Settings means more than the project's + * suggestion, and "absent" stays the stored representation of "default" so a + * materialised value is never written back. + * + * `docksCustomOrder` stacks per key rather than as a whole object: the stored + * side is always `{}` at first, so a flat spread would drop every seeded order + * the moment the visitor reordered one dock. `commandShortcuts` resolves the + * same way, per command id, in the commands context: the shortcut settings + * page needs the visitor's own overrides apart from the seeded default, so + * this merged view deliberately leaves it out. + */ +export function resolveUserSettings( + stored: Immutable, + defaults: DocksUserSettingsDefaults = {}, +): ResolvedDocksUserSettings { + return { + ...HUB_UI_SETTINGS_DEFAULTS, + ...omitUndefined(defaults), + ...stored, + docksCustomOrder: { + ...defaults.docksCustomOrder, + ...stored.docksCustomOrder, + }, + } as ResolvedDocksUserSettings +} + /** * Read one hub-ui setting off a settings object that may not be resolved. * @@ -83,10 +145,8 @@ export function useSettings(context: DocksContext): ComputedRef ({ - ...HUB_UI_SETTINGS_DEFAULTS, - ...stored.value, - })) + const defaults = resolveSettingsDefaults(context.rpc.connectionMeta.configs) + settings = computed(() => resolveUserSettings(stored.value, defaults)) settingsByContext.set(context, settings) } return settings diff --git a/packages/hub-ui/src/client/types.ts b/packages/hub-ui/src/client/types.ts index 356dc3c2..59daeb2f 100644 --- a/packages/hub-ui/src/client/types.ts +++ b/packages/hub-ui/src/client/types.ts @@ -1,51 +1,12 @@ import type { DevframeViewLauncher } from '@devframes/hub/types' +// Applies src/types.ts, which owns the published `createUi()` config types and +// registers hub-ui's own settings fields on `DevframeDocksUserSettings`. +import '../types' // Registers the json-render `'json-render'` dock entry on the hub's open dock // union via declaration merging. Must be a value import (TS rejects a type-only // side-effect import), but is fully erased since nothing in dist references it. import '@devframes/json-render/hub' -/** - * hub-ui's own reference-UI settings, merged onto the hub's generic - * {@link DevframeDocksUserSettings}; the hub core stays unaware of them. - * Every field is optional so the hub's `DEFAULT_STATE_USER_SETTINGS()` (which - * knows nothing about them) stays assignable; what an absent value means lives - * in one place, `HUB_UI_SETTINGS_DEFAULTS` (`state/settings-defaults.ts`), - * merged in once by `useSettings()` so readers see resolved values rather than - * repeating a per-call-site fallback. - */ -declare module '@devframes/hub/types' { - interface DevframeDocksUserSettings { - /** Show the address-bar chrome on iframe dock views. */ - showIframeAddressBar?: boolean - /** Close the floating dock panel when clicking outside it. */ - closeOnOutsideClick?: boolean - /** - * Auto-collapse the edge-mode toolbar to a small handle when idle (no - * hover or drag) and the panel content is closed, instead of permanently - * spanning the full edge. - */ - autoCollapseEdgeToolbar?: boolean - /** - * Reveal the Devframe Inspector dock (the "devtools for the devtools" - * meta-introspection panel) on the dock bar. Users opt in from - * Settings → Advanced. - */ - showDevframeInspector?: boolean - /** - * How many recently opened docks the float bar keeps in their own slots - * after its visible items. Only docks opened from beyond the bar (the - * overflow popover or a group popover) take a slot. `0` turns the slots - * off. - */ - docksRecentLimit?: number - /** - * Widen the group sidebar so each member shows its title next to its - * icon, instead of an icon-only rail with hover tooltips. - */ - expandGroupSidebar?: boolean - } -} - /** * A selectable launch root offered by a launcher dock entry. * diff --git a/packages/hub-ui/src/index.test.ts b/packages/hub-ui/src/index.test.ts index 61fe25ec..833bd7bc 100644 --- a/packages/hub-ui/src/index.test.ts +++ b/packages/hub-ui/src/index.test.ts @@ -103,3 +103,26 @@ describe('createUi branding background', () => { expect(ui.viewer).toBeUndefined() }) }) + +describe('createUi user settings defaults', () => { + it('publishes the host defaults to the connection meta', () => { + expect.assertions(1) + + const context = createContext() + const settingsDefaults = { + commandShortcuts: { 'devframes:toggle-palette': [] }, + } + createUi({ settingsDefaults }).setup?.(context) + + expect(context.staticConfig.ui).toEqual({ branding: {}, settingsDefaults }) + }) + + it('omits the field when the host publishes none', () => { + expect.assertions(1) + + const context = createContext() + createUi().setup?.(context) + + expect(context.staticConfig.ui).not.toHaveProperty('settingsDefaults') + }) +}) diff --git a/packages/hub-ui/src/index.ts b/packages/hub-ui/src/index.ts index a4b950dd..7b5d9124 100644 --- a/packages/hub-ui/src/index.ts +++ b/packages/hub-ui/src/index.ts @@ -1,6 +1,6 @@ import type { DevframeHubUi } from '@devframes/hub/initiate' import type { HubUiLocale } from './locales' -import type { DevframeBranding, DevframeDockPreferences, EmbeddedVisibility } from './types' +import type { DevframeBranding, DevframeDockPreferences, DocksUserSettingsDefaults, EmbeddedVisibility } from './types' import { existsSync } from 'node:fs' import { join } from 'node:path' import { fileURLToPath } from 'node:url' @@ -15,6 +15,15 @@ declare module 'devframe/types' { branding?: DevframeBranding embeddedVisibility?: EmbeddedVisibility dockPreferences?: DevframeDockPreferences + /** + * User settings the reference UI resolves *below* the visitor's own + * stored value: `createUi({ settingsDefaults })` publishes the project's + * idea of the panel defaults (a disabled shortcut, a different + * recent-dock limit, the default order of the dock bar), which a choice + * in Settings then overrides. Absent fields fall back to the UI's + * built-in defaults. + */ + settingsDefaults?: DocksUserSettingsDefaults /** * The hub UI language. `createUi({ locale })` publishes the host's * default; the running hub UI then overwrites it with the language it @@ -76,6 +85,18 @@ export interface CreateUiOptions { * user-overridable preference the visitor's own choice then wins. */ dockPreferences?: DevframeDockPreferences + /** + * Seed the user settings the reference UI resolves below the visitor's own + * stored value. Use it for defaults that belong to the project rather than + * the person: leaving `Mod+K` unbound + * (`{ commandShortcuts: { 'devframes:toggle-palette': [] } }`), ordering the + * dock bar, or a different recent-dock limit. + * + * Published as `ConnectionMeta.configs.ui.settingsDefaults`. Settings the + * visitor changed themselves win, and a reset in Settings returns to these + * defaults rather than to the built-in ones. + */ + settingsDefaults?: DocksUserSettingsDefaults /** * Default UI language, one of {@link HUB_UI_LOCALES}. Published as * `ConnectionMeta.configs.ui.locale` and, like the dock mode, only a @@ -133,6 +154,9 @@ export function createUi(options: CreateUiOptions = {}): DevframeHubUi { ...(options.dockPreferences ? { dockPreferences: options.dockPreferences } : {}), + ...(options.settingsDefaults + ? { settingsDefaults: options.settingsDefaults } + : {}), ...(options.locale ? { locale: options.locale } : {}), diff --git a/packages/hub-ui/src/types.ts b/packages/hub-ui/src/types.ts index 74347e4d..f5fd3099 100644 --- a/packages/hub-ui/src/types.ts +++ b/packages/hub-ui/src/types.ts @@ -4,7 +4,13 @@ * surface. Client modules that need these types import them *from* here * (never the reverse); see `client/state/branding.ts`, * `client/embedded/visibility.ts`. + * + * The node entry must also stay off the client graph for another reason: the + * client types register optional peer packages (`@devframes/json-render`) by + * side-effect import, and a declaration file that references one of those + * makes TS2882 fire for a consumer that never installed it. */ +import type { DevframeDocksUserSettings } from '@devframes/hub/types' /** * A logo asset: a single URL/data-URI, or per-color-scheme variants. The dark @@ -98,3 +104,67 @@ export interface DevframeDockPreferences { * visitor's own reveal/hide wins from then on. */ export type EmbeddedVisibility = 'normal' | 'passive' | 'hidden' + +/** + * hub-ui's own reference-UI settings, merged onto the hub's generic + * {@link DevframeDocksUserSettings}; the hub core stays unaware of them. + * Every field is optional so the hub's `DEFAULT_STATE_USER_SETTINGS()` (which + * knows nothing about them) stays assignable; what an absent value means lives + * in one place, `HUB_UI_SETTINGS_DEFAULTS` (`client/state/settings-defaults.ts`), + * merged in once by `useSettings()` so readers see resolved values rather than + * repeating a per-call-site fallback. + * + * Lives here, not in `client/types.ts`, so the published `createUi()` types can + * name these fields without the node entry importing the client graph. + */ +declare module '@devframes/hub/types' { + interface DevframeDocksUserSettings { + /** Show the address-bar chrome on iframe dock views. */ + showIframeAddressBar?: boolean + /** Close the floating dock panel when clicking outside it. */ + closeOnOutsideClick?: boolean + /** + * Auto-collapse the edge-mode toolbar to a small handle when idle (no + * hover or drag) and the panel content is closed, instead of permanently + * spanning the full edge. + */ + autoCollapseEdgeToolbar?: boolean + /** + * Reveal the Devframe Inspector dock (the "devtools for the devtools" + * meta-introspection panel) on the dock bar. Users opt in from + * Settings → Advanced. + */ + showDevframeInspector?: boolean + /** + * How many recently opened docks the float bar keeps in their own slots + * after its visible items. Only docks opened from beyond the bar (the + * overflow popover or a group popover) take a slot. `0` turns the slots + * off. + */ + docksRecentLimit?: number + /** + * Widen the group sidebar so each member shows its title next to its + * icon, instead of an icon-only rail with hover tooltips. + */ + expandGroupSidebar?: boolean + } +} + +/** + * The user-settings seed a host publishes through + * `createUi({ settingsDefaults })` → `ConnectionMeta.configs.ui.settingsDefaults`. + * + * Every field is optional: a seed names only what the project wants to differ + * from the built-in defaults, and whatever it leaves out keeps falling back. + * + * The three list fields (`docksHidden`, `docksCategoriesHidden`, `docksPinned`) + * are left out on purpose. The stored list is always present, so a seeded list + * would only win by overriding the visitor's forever, and a developer could + * hide an entry the project seeded while never unhiding one. Records + * (`commandShortcuts`, `docksCustomOrder`) merge per key instead, so a seeded + * entry and a stored entry coexist and the stored one wins where they collide. + */ +export type DocksUserSettingsDefaults = Omit< + Partial, + 'docksHidden' | 'docksCategoriesHidden' | 'docksPinned' +> diff --git a/tests/__snapshots__/tsnapi/@devframes/hub-ui/index.snapshot.d.ts b/tests/__snapshots__/tsnapi/@devframes/hub-ui/index.snapshot.d.ts index 0be3cd60..52fbb58d 100644 --- a/tests/__snapshots__/tsnapi/@devframes/hub-ui/index.snapshot.d.ts +++ b/tests/__snapshots__/tsnapi/@devframes/hub-ui/index.snapshot.d.ts @@ -8,6 +8,7 @@ export interface CreateUiOptions { branding?: DevframeBranding; embeddedVisibility?: EmbeddedVisibility; dockPreferences?: DevframeDockPreferences; + settingsDefaults?: DocksUserSettingsDefaults; locale?: HubUiLocale; } export interface DevframeBranding { @@ -65,4 +66,5 @@ type BrandingLogo = string | { light: string; dark: string; }; +type DocksUserSettingsDefaults = Omit, 'docksHidden' | 'docksCategoriesHidden' | 'docksPinned'>; // #endregion \ No newline at end of file diff --git a/tests/published-declarations.test.ts b/tests/published-declarations.test.ts new file mode 100644 index 00000000..62a17fbe --- /dev/null +++ b/tests/published-declarations.test.ts @@ -0,0 +1,27 @@ +import { readFileSync } from 'node:fs' +import { fileURLToPath } from 'node:url' +import { describe, expect, it } from 'vitest' + +/** + * A declaration file that side-effect imports an optional peer makes TS2882 + * ("Cannot find module or type declarations for side-effect import of ...") + * fire for a consumer that installed the package without that peer. + * + * The registrations live in the client graph (`packages/hub-ui/src/client/types.ts` + * imports `@devframes/json-render/hub`), so the node entry's declaration rollup + * must not import any client module. + */ +describe('published declarations never require an optional peer', () => { + it('keeps @devframes/hub-ui\'s node entry off the client type graph', () => { + const dts = readFileSync( + fileURLToPath(new URL('../packages/hub-ui/dist/index.d.mts', import.meta.url)), + 'utf8', + ) + const sideEffectImports = dts + .split('\n') + .filter(line => /^import\s+["']/.test(line)) + .filter(line => /@devframes\/json-render|@devframes\/hub\/client/.test(line)) + + expect(sideEffectImports).toEqual([]) + }) +})