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
8 changes: 5 additions & 3 deletions docs/widgets/dropdown.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,12 +36,12 @@ ui.dropdown({

- **Arrow keys** navigate items. **Enter** selects the highlighted item.
- The current selection is visually highlighted.
- Long menus render a deterministic visible window and keep the highlighted item in view as you navigate.
- **Mouse click** on an item selects it and fires the `onSelect` callback.
- **Clicking outside** the dropdown closes it (calls `onClose`).
- Dropdown overlays register in the shared `LayerRegistry`, so z-order and
hit-testing behavior is consistent with modal/layer overlays.
- Item `shortcut` text is a display hint. Register actual key combos with
`app.keys()` and route to the same action handlers.
- Item `shortcut` bindings are active for the topmost open dropdown and trigger the same selection/close path as keyboard or mouse activation.

## Notes

Expand All @@ -62,11 +62,13 @@ ui.dropdown({
})
```

Pair the labels with explicit bindings:
Optional app-level bindings for the same actions:

```ts
app.keys({
"ctrl+s": () => runCommand("save"),
"ctrl+q": () => runCommand("quit"),
})
```

Use `app.keys()` for app-level shortcuts that should work even when the dropdown is closed.
6 changes: 6 additions & 0 deletions packages/core/src/app/widgetRenderer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -980,6 +980,7 @@ export class WidgetRenderer<S> {
private onCloseByLayerId: ReadonlyMap<string, () => void> = new Map<string, () => void>();
private dropdownStack: readonly string[] = Object.freeze([]);
private readonly dropdownSelectedIndexById = new Map<string, number>();
private readonly dropdownWindowStartById = new Map<string, number>();
private overlayShortcutOwners: readonly OverlayShortcutOwner[] = Object.freeze([]);
private readonly overlayShortcutBySequence = new Map<string, OverlayShortcutBinding>();
private overlayShortcutTrie = buildTrie<OverlayShortcutContext>(Object.freeze([]));
Expand Down Expand Up @@ -1493,6 +1494,7 @@ export class WidgetRenderer<S> {
this.commandPaletteLoadingById,
this.toolApprovalFocusedActionById,
this.dropdownSelectedIndexById,
this.dropdownWindowStartById,
this.diffViewerFocusedHunkById,
this.diffViewerExpandedHunksById,
this.tableRenderCacheById,
Expand Down Expand Up @@ -1754,6 +1756,7 @@ export class WidgetRenderer<S> {
toastContainers: this.toastContainers,
toastActionByFocusId: this.toastActionByFocusId,
dropdownSelectedIndexById: this.dropdownSelectedIndexById,
dropdownWindowStartById: this.dropdownWindowStartById,
toolApprovalFocusedActionById: this.toolApprovalFocusedActionById,
diffViewerFocusedHunkById: this.diffViewerFocusedHunkById,
diffViewerExpandedHunksById: this.diffViewerExpandedHunksById,
Expand Down Expand Up @@ -3328,6 +3331,7 @@ export class WidgetRenderer<S> {
loadedTreeChildrenByTreeId: this.loadedTreeChildrenByTreeId,
treeLoadTokenByTreeAndKey: this.treeLoadTokenByTreeAndKey,
dropdownSelectedIndexById: this.dropdownSelectedIndexById,
dropdownWindowStartById: this.dropdownWindowStartById,
pressedVirtualList: this.pressedVirtualList,
pressedFileTree: this.pressedFileTree,
lastFileTreeClick: this.lastFileTreeClick,
Expand Down Expand Up @@ -3569,6 +3573,7 @@ export class WidgetRenderer<S> {
this.commandPaletteLoadingById,
this.toolApprovalFocusedActionById,
this.dropdownSelectedIndexById,
this.dropdownWindowStartById,
this.diffViewerFocusedHunkById,
this.diffViewerExpandedHunksById,
this.tableRenderCacheById,
Expand Down Expand Up @@ -3608,6 +3613,7 @@ export class WidgetRenderer<S> {
commandPaletteLoadingById: this.commandPaletteLoadingById,
toolApprovalFocusedActionById: this.toolApprovalFocusedActionById,
dropdownSelectedIndexById: this.dropdownSelectedIndexById,
dropdownWindowStartById: this.dropdownWindowStartById,
diffViewerFocusedHunkById: this.diffViewerFocusedHunkById,
diffViewerExpandedHunksById: this.diffViewerExpandedHunksById,
focusAnnouncement,
Expand Down
22 changes: 20 additions & 2 deletions packages/core/src/app/widgetRenderer/mouseRouting.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { ZrevEvent } from "../../events.js";
import { ZR_MOD_CTRL, ZR_MOD_SHIFT } from "../../keybindings/keyCodes.js";
import { computeDropdownWindow } from "../../layout/dropdownGeometry.js";
import { measureTextCells } from "../../layout/textMeasure.js";
import type { Rect } from "../../layout/types.js";
import type { FocusManagerState } from "../../runtime/focus.js";
Expand Down Expand Up @@ -88,6 +89,7 @@ type RouteDropdownMouseContext = Readonly<{
dropdownStack: readonly string[];
dropdownById: ReadonlyMap<string, DropdownProps>;
dropdownSelectedIndexById: Map<string, number>;
dropdownWindowStartById: Map<string, number>;
pressedDropdown: Readonly<{ id: string; itemId: string }> | null;
setPressedDropdown: (next: Readonly<{ id: string; itemId: string }> | null) => void;
computeDropdownRect: (props: DropdownProps) => Rect | null;
Expand Down Expand Up @@ -325,12 +327,19 @@ export function routeDropdownMouse(
const contentY = dropdownRect.y + 1;
const contentW = Math.max(0, dropdownRect.w - 2);
const contentH = Math.max(0, dropdownRect.h - 2);
const window = computeDropdownWindow(
dropdown.items.length,
ctx.dropdownSelectedIndexById.get(topDropdownId) ?? 0,
contentH,
ctx.dropdownWindowStartById.get(topDropdownId) ?? 0,
);
const itemAreaW = window.overflow ? Math.max(0, contentW - 1) : contentW;
const inContent =
event.x >= contentX &&
event.x < contentX + contentW &&
event.x < contentX + itemAreaW &&
event.y >= contentY &&
event.y < contentY + contentH;
const itemIndex = inContent ? event.y - contentY : null;
const itemIndex = inContent ? window.startIndex + (event.y - contentY) : null;

const MOUSE_KIND_DOWN = 3;
const MOUSE_KIND_UP = 4;
Expand All @@ -355,6 +364,15 @@ export function routeDropdownMouse(
if (item && !item.divider && item.disabled !== true) {
const prevSelected = ctx.dropdownSelectedIndexById.get(topDropdownId) ?? 0;
ctx.dropdownSelectedIndexById.set(topDropdownId, itemIndex);
ctx.dropdownWindowStartById.set(
topDropdownId,
computeDropdownWindow(
dropdown.items.length,
itemIndex,
contentH,
ctx.dropdownWindowStartById.get(topDropdownId) ?? 0,
).startIndex,
);
ctx.setPressedDropdown(Object.freeze({ id: topDropdownId, itemId: item.id }));
return Object.freeze({ needsRender: itemIndex !== prevSelected });
}
Expand Down
17 changes: 13 additions & 4 deletions packages/core/src/app/widgetRenderer/overlayShortcuts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,15 @@ const EMPTY_COMMAND_ITEMS: readonly CommandItem[] = Object.freeze([]);

function noopOverlayShortcutHandler(_ctx: OverlayShortcutContext): void {}

function describeThrown(value: unknown): string {
if (value instanceof Error) return `${value.name}: ${value.message}`;
try {
return String(value);
} catch {
return "[unstringifiable thrown value]";
}
}

export function selectDropdownShortcutItem(
ctx: SelectDropdownShortcutContext,
dropdownId: string,
Expand All @@ -99,14 +108,14 @@ export function selectDropdownShortcutItem(
try {
dropdown.onSelect(item);
} catch (e) {
warnDev(`[rezi] onSelect callback threw: ${e instanceof Error ? e.message : String(e)}`);
warnDev(`[rezi] onSelect callback threw: ${describeThrown(e)}`);
}
}
if (dropdown.onClose) {
try {
dropdown.onClose();
} catch (e) {
warnDev(`[rezi] onClose callback threw: ${e instanceof Error ? e.message : String(e)}`);
warnDev(`[rezi] onClose callback threw: ${describeThrown(e)}`);
}
}
return true;
Expand All @@ -127,12 +136,12 @@ export function selectCommandPaletteShortcutItem(
try {
palette.onSelect(item);
} catch (e) {
warnDev(`[rezi] onSelect callback threw: ${e instanceof Error ? e.message : String(e)}`);
warnDev(`[rezi] onSelect callback threw: ${describeThrown(e)}`);
}
try {
palette.onClose();
} catch (e) {
warnDev(`[rezi] onClose callback threw: ${e instanceof Error ? e.message : String(e)}`);
warnDev(`[rezi] onClose callback threw: ${describeThrown(e)}`);
}
return true;
}
Expand Down
4 changes: 4 additions & 0 deletions packages/core/src/app/widgetRenderer/overlayState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,7 @@ type CleanupRoutingStateParams = RoutingWidgetMaps &
loadedTreeChildrenByTreeId: Map<string, ReadonlyMap<string, readonly unknown[]>>;
treeLoadTokenByTreeAndKey: Map<string, number>;
dropdownSelectedIndexById: Map<string, number>;
dropdownWindowStartById: Map<string, number>;
pressedVirtualList: Readonly<{ id: string; index: number }> | null;
pressedFileTree: Readonly<{ id: string; nodeIndex: number; nodeKey: string }> | null;
lastFileTreeClick: Readonly<{
Expand Down Expand Up @@ -813,6 +814,9 @@ export function cleanupRoutingStateAfterRebuild(
for (const dropdownId of params.dropdownSelectedIndexById.keys()) {
if (!params.dropdownById.has(dropdownId)) params.dropdownSelectedIndexById.delete(dropdownId);
}
for (const dropdownId of params.dropdownWindowStartById.keys()) {
if (!params.dropdownById.has(dropdownId)) params.dropdownWindowStartById.delete(dropdownId);
}

for (const virtualListId of params.virtualListStore.keys()) {
if (!params.virtualListById.has(virtualListId)) params.virtualListStore.delete(virtualListId);
Expand Down
14 changes: 14 additions & 0 deletions packages/core/src/app/widgetRenderer/routeEngineEvent.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { ZrevEvent } from "../../events.js";
import { ZR_MOD_CTRL } from "../../keybindings/keyCodes.js";
import type { LayoutOverflowMetadata } from "../../layout/constraints.js";
import { computeDropdownWindow } from "../../layout/dropdownGeometry.js";
import { hitTestAnyId, hitTestFocusable } from "../../layout/hitTest.js";
import type { LayoutTree } from "../../layout/layout.js";
import type { Rect } from "../../layout/types.js";
Expand Down Expand Up @@ -221,6 +222,7 @@ export type RouteEngineEventContext = Readonly<{
toastContainers: readonly Readonly<{ rect: Rect; props: ToastContainerProps }>[];
toastActionByFocusId: ReadonlyMap<string, () => void>;
dropdownSelectedIndexById: Map<string, number>;
dropdownWindowStartById: Map<string, number>;
toolApprovalFocusedActionById: Map<string, "allow" | "deny" | "allowSession">;
diffViewerFocusedHunkById: Map<string, number>;
diffViewerExpandedHunksById: Map<string, ReadonlySet<number>>;
Expand Down Expand Up @@ -310,6 +312,17 @@ export function routeEngineEventImpl(
});
if (dropdownResult.nextSelectedIndex !== undefined) {
ctx.dropdownSelectedIndexById.set(topDropdownId, dropdownResult.nextSelectedIndex);
const dropdownRect = ctx.computeDropdownRect(dropdown);
const visibleRows = Math.max(0, (dropdownRect?.h ?? 0) - 2);
ctx.dropdownWindowStartById.set(
topDropdownId,
computeDropdownWindow(
dropdown.items.length,
dropdownResult.nextSelectedIndex,
visibleRows,
ctx.dropdownWindowStartById.get(topDropdownId) ?? 0,
).startIndex,
);
}
if (dropdownResult.consumed) return ROUTE_RENDER;
}
Expand All @@ -329,6 +342,7 @@ export function routeEngineEventImpl(
dropdownStack: ctx.dropdownStack,
dropdownById: ctx.dropdownById,
dropdownSelectedIndexById: ctx.dropdownSelectedIndexById,
dropdownWindowStartById: ctx.dropdownWindowStartById,
pressedDropdown: state.pressedDropdown,
setPressedDropdown: (next) => {
state.pressedDropdown = next;
Expand Down
22 changes: 21 additions & 1 deletion packages/core/src/layout/__tests__/dropdownGeometry.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { assert, describe, test } from "@rezi-ui/testkit";
import type { DropdownProps } from "../../widgets/types.js";
import { computeDropdownGeometry } from "../dropdownGeometry.js";
import { computeDropdownGeometry, computeDropdownWindow } from "../dropdownGeometry.js";
import type { Rect } from "../types.js";

function dropdownProps(items: DropdownProps["items"]): DropdownProps {
Expand Down Expand Up @@ -80,4 +80,24 @@ describe("dropdownGeometry", () => {
assert.equal(rect.w, 3);
assert.equal(rect.h, 2);
});

test("computeDropdownWindow preserves the previous window while selection stays visible", () => {
assert.deepEqual(computeDropdownWindow(12, 6, 4, 4), {
startIndex: 4,
endIndex: 8,
visibleRows: 4,
selectedIndex: 6,
overflow: true,
});
});

test("computeDropdownWindow advances only when selection leaves the visible window", () => {
assert.deepEqual(computeDropdownWindow(12, 8, 4, 4), {
startIndex: 5,
endIndex: 9,
visibleRows: 4,
selectedIndex: 8,
overflow: true,
});
});
});
54 changes: 54 additions & 0 deletions packages/core/src/layout/dropdownGeometry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,60 @@ import { calculateAnchorPosition } from "./positioning.js";
import { measureTextCells } from "./textMeasure.js";
import type { Rect } from "./types.js";

export type DropdownWindow = Readonly<{
startIndex: number;
endIndex: number;
visibleRows: number;
selectedIndex: number;
overflow: boolean;
}>;

function clampIndex(value: number, min: number, max: number): number {
if (!Number.isFinite(value)) return min;
const truncated = Math.trunc(value);
if (truncated <= min) return min;
if (truncated >= max) return max;
return truncated;
}

export function computeDropdownWindow(
itemCount: number,
selectedIndex: number,
maxVisibleRows: number,
previousStartIndex = 0,
): DropdownWindow {
if (itemCount <= 0 || maxVisibleRows <= 0) {
return Object.freeze({
startIndex: 0,
endIndex: 0,
visibleRows: 0,
selectedIndex: 0,
overflow: false,
});
}

const visibleRows = Math.min(itemCount, Math.max(0, Math.trunc(maxVisibleRows)));
const normalizedSelectedIndex = clampIndex(selectedIndex, 0, itemCount - 1);
const maxStartIndex = Math.max(0, itemCount - visibleRows);
let startIndex = clampIndex(previousStartIndex, 0, maxStartIndex);

if (normalizedSelectedIndex < startIndex) {
startIndex = normalizedSelectedIndex;
} else if (normalizedSelectedIndex >= startIndex + visibleRows) {
startIndex = normalizedSelectedIndex - visibleRows + 1;
}

if (startIndex > maxStartIndex) startIndex = maxStartIndex;

return Object.freeze({
startIndex,
endIndex: startIndex + visibleRows,
visibleRows,
selectedIndex: normalizedSelectedIndex,
overflow: itemCount > visibleRows,
});
}

export function computeDropdownGeometry(
props: DropdownProps,
anchorRect: Rect | null,
Expand Down
39 changes: 39 additions & 0 deletions packages/core/src/renderer/__tests__/overlay.edge.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,16 @@ import { type VNode, createDrawlistBuilder } from "../../index.js";
import { layout } from "../../layout/layout.js";
import { commitVNodeTree } from "../../runtime/commit.js";
import { createInstanceIdAllocator } from "../../runtime/instance.js";
import { ui } from "../../widgets/ui.js";
import { renderToDrawlist } from "../renderToDrawlist.js";

function renderStrings(
vnode: VNode,
viewport: Readonly<{ cols: number; rows: number }>,
opts: Readonly<{
dropdownSelectedIndexById?: ReadonlyMap<string, number>;
dropdownWindowStartById?: ReadonlyMap<string, number>;
}> = {},
): readonly string[] {
const allocator = createInstanceIdAllocator(1);
const commitRes = commitVNodeTree(null, vnode, { allocator });
Expand All @@ -33,6 +38,12 @@ function renderStrings(
viewport,
focusState: Object.freeze({ focusedId: null }),
builder,
...(opts.dropdownSelectedIndexById
? { dropdownSelectedIndexById: opts.dropdownSelectedIndexById }
: {}),
...(opts.dropdownWindowStartById
? { dropdownWindowStartById: opts.dropdownWindowStartById }
: {}),
});
const built = builder.build();
assert.equal(built.ok, true, "drawlist build should succeed");
Expand Down Expand Up @@ -101,4 +112,32 @@ describe("overlay rendering edge cases", () => {
const strings = renderStrings(malformed, { cols: 10, rows: 3 });
assert.ok(Array.isArray(strings));
});

test("overflowing dropdown renders only the active visible window", () => {
const vnode = ui.layers([
ui.button({ id: "anchor", label: "Anchor" }),
ui.dropdown({
id: "menu",
anchorId: "anchor",
items: Array.from({ length: 8 }, (_, index) => ({
id: `item-${String(index)}`,
label: `Item ${String(index)}`,
})),
}),
]);

const strings = renderStrings(
vnode,
{ cols: 14, rows: 5 },
{
dropdownSelectedIndexById: new Map([["menu", 6]]),
dropdownWindowStartById: new Map([["menu", 4]]),
},
);

assert.equal(strings.includes("Item 0"), false);
assert.equal(strings.includes("Item 4"), true);
assert.equal(strings.includes("Item 6"), true);
assert.equal(strings.includes("Item 7"), false);
});
});
Loading
Loading