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
11 changes: 11 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,17 @@

All notable changes to Vela, newest first.

## [Unreleased]

### Fixed

- **Open menus stay with the chart when the page scrolls.** On a page that scrolls around the
chart, an open timeframe, chart style or time zone menu stayed where it was on screen
while its button scrolled away, so it came loose from the toolbar. A right-click menu or
the alerts list jumped to the top of the window, where a page header could hide it. An
open menu now keeps its place in the chart and moves with it, as the layout menu already
did. A chart that fills its page was not affected.

## [0.10.11]

### Fixed
Expand Down
10 changes: 10 additions & 0 deletions packages/vela-ui/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,16 @@
All notable changes to `@luxalgo/vela-ui`, newest first. Vela's own changes, including how it
uses the kit, are in [Vela's changelog](../../CHANGELOG.md).

## [Unreleased]

### Fixed

- **An open menu follows its host when the page scrolls.** A dropdown menu opened from its
trigger stayed at the same place on screen while the page scrolled the trigger away. A
menu opened with `openAt`, a context menu included, jumped to the top of the window. An
open menu now keeps its place inside its host, whichever way it opened, and still stays
where it is when its trigger moves inside the host.

## [0.4.2]

### Added
Expand Down
47 changes: 36 additions & 11 deletions packages/vela-ui/src/components/dropdown-menu.ts
Original file line number Diff line number Diff line change
Expand Up @@ -394,6 +394,14 @@ interface SurfaceOptions {
submenu?: boolean;
}

/** The rectangle a menu level is placed against. */
interface AnchorRect {
x: number;
y: number;
width: number;
height: number;
}

/** How far a row sits inside its list: the list's padding (6px) plus its border (1px). */
const ROW_INSET_PX = 7;
/** The space between a submenu and the list it opened from. */
Expand All @@ -420,9 +428,12 @@ class Surface {
private items: readonly MenuItemDescriptor[] = [];
/** Branch item id → the surface it opens. */
private readonly subs = new Map<string, Surface>();
/** Trigger rect captured when this level opened — the list stays put if the
* trigger then moves (favorite chips shifting the caret). */
private pinnedAnchor: { x: number; y: number; width: number; height: number } | null = null;
/** What this level opened against, as an offset inside the host: its trigger's rect, or
* the point `openAt` was given. Held in the host's space, not the viewport's, so the list
* keeps its place in the host: a trigger that then moves leaves it still (favorite chips
* shifting the caret), and a page that scrolls the host carries it along. Null on a
* submenu, which follows its row. */
private pinnedAnchor: AnchorRect | null = null;
/** The open state last announced — see {@link announce}. */
private shown = false;
/** The list's exit animation after a close; a reopen cancels it. */
Expand Down Expand Up @@ -454,14 +465,11 @@ class Surface {
id: opts.id,
...opts.placement,
onSelect: (id) => this.onSelect(id),
getAnchorRect: () => this.pinnedAnchor,
getAnchorRect: () => this.anchorRect(),
onOpenChange: (open) => {
if (open && trigger) {
const r = trigger.getBoundingClientRect();
this.pinnedAnchor = { x: r.x, y: r.y, width: r.width, height: r.height };
} else {
this.pinnedAnchor = null;
}
// An anchor already there is the point this opening was asked at.
if (!open) this.pinnedAnchor = null;
else if (trigger && !this.pinnedAnchor) this.pin(trigger.getBoundingClientRect());
opts.onOpenChange?.(open);
},
triggerId: opts.triggerId,
Expand Down Expand Up @@ -512,6 +520,20 @@ class Surface {
return this.ctrl.connect(this.handle.service);
}

/** Anchor this level to `rect`, given in viewport coordinates. */
pin(rect: AnchorRect): void {
const origin = this.host.getBoundingClientRect();
this.pinnedAnchor = { x: rect.x - origin.x, y: rect.y - origin.y, width: rect.width, height: rect.height };
}

/** The anchor in viewport coordinates, where the host stands now. */
anchorRect(): AnchorRect | null {
const anchor = this.pinnedAnchor;
if (!anchor) return null;
const origin = this.host.getBoundingClientRect();
return { x: origin.x + anchor.x, y: origin.y + anchor.y, width: anchor.width, height: anchor.height };
}

private announce(open: boolean): void {
this.shown = open;
announceSurface(this.list, open, 'menu', this.opener);
Expand Down Expand Up @@ -742,8 +764,11 @@ export class DropdownMenu {
/** Open anchored to a viewport point (context menus). */
openAt(clientX: number, clientY: number): void {
const api = this.api;
// Queued, as the machine's own events are: a close still under way lands first, and
// must not take this anchor with it.
queueMicrotask(() => this.root.pin({ x: clientX, y: clientY, width: 0, height: 0 }));
api.setOpen(true);
api.reposition({ getAnchorRect: () => ({ x: clientX, y: clientY, width: 0, height: 0 }) });
api.reposition({ getAnchorRect: () => this.root.anchorRect() });
}

close(): void {
Expand Down
203 changes: 203 additions & 0 deletions test/dropdown-menu-anchor.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,203 @@
// @vitest-environment jsdom
// Where an open dropdown menu sits once the page moves under it. The list keeps its place
// inside its host: a page that scrolls the host carries the list along, whether it opened from
// its trigger or at a point, and a trigger that shifts inside the host leaves it still
// (starring a timeframe adds a chip and moves the caret). jsdom lays nothing out, so each test
// gives the host and the trigger their boxes and reads the offset written on the positioner;
// with no offset parent in jsdom, that offset is in viewport coordinates.
import { afterEach, beforeAll, describe, expect, it } from 'vitest';

(globalThis as { CSS?: unknown }).CSS ??= { escape: (v: string) => v };
class NoopObserver {
observe(): void {}
unobserve(): void {}
disconnect(): void {}
takeRecords(): unknown[] {
return [];
}
}
(globalThis as { ResizeObserver?: unknown }).ResizeObserver ??= NoopObserver;
(globalThis as { IntersectionObserver?: unknown }).IntersectionObserver ??= NoopObserver;

import { DropdownMenu, type MenuItemDescriptor } from '@luxalgo/vela-ui/dropdown-menu';

const ROWS: MenuItemDescriptor[] = [
{ id: '1m', label: '1m' },
{ id: '1h', label: '1h' },
];

/** The space Zag leaves between an anchor and its list. */
const GUTTER = 8;

interface Box {
x: number;
y: number;
width: number;
height: number;
}

function place(el: HTMLElement, box: Box): void {
el.getBoundingClientRect = () => ({ ...box, left: box.x, top: box.y, right: box.x + box.width, bottom: box.y + box.height, toJSON: () => box }) as DOMRect;
}

beforeAll(() => {
Element.prototype.animate ??= (() => ({ cancel() {}, finish() {}, addEventListener() {} })) as unknown as Element['animate'];
// The viewport the list is kept inside: without a size, every placement overflows.
Object.defineProperty(document.documentElement, 'clientWidth', { configurable: true, value: 1280 });
Object.defineProperty(document.documentElement, 'clientHeight', { configurable: true, value: 2000 });
});

const menus: DropdownMenu[] = [];
afterEach(() => {
for (const m of menus.splice(0)) m.destroy();
document.body.replaceChildren();
});

/** Zag applies an open, and places the list, on a later tick. */
const settled = (): Promise<void> => new Promise((r) => setTimeout(r, 50));

interface Rig {
host: HTMLElement;
trigger: HTMLButtonElement;
menu: DropdownMenu;
/** Scroll the page: the host and everything in it move by `dy` on screen. */
scrollPage(dy: number): Promise<void>;
/** Move the trigger alone, inside a host that stays where it is. */
shiftTrigger(dx: number): Promise<void>;
/** Where the list sits. */
offset(): { x: number; y: number };
}

function rig(withTrigger: boolean): Rig {
const hostBox: Box = { x: 100, y: 200, width: 800, height: 600 };
const triggerBox: Box = { x: 140, y: 210, width: 40, height: 30 };
const host = document.createElement('div');
host.className = 'vela-ui';
const trigger = document.createElement('button');
host.append(trigger);
document.body.append(host);
place(host, hostBox);
place(trigger, triggerBox);
const menu = new DropdownMenu({ host, items: ROWS, ...(withTrigger ? { trigger } : {}) });
menus.push(menu);
const positioner = host.querySelector<HTMLElement>('.vela-ui-layer')!;
// Any scroll re-places an open list; the boxes say what moved.
const replaced = async (): Promise<void> => {
window.dispatchEvent(new Event('scroll'));
await settled();
};
return {
host,
trigger,
menu,
scrollPage: (dy) => {
hostBox.y -= dy;
triggerBox.y -= dy;
return replaced();
},
shiftTrigger: (dx) => {
triggerBox.x += dx;
return replaced();
},
offset: () => ({ x: parseFloat(positioner.style.getPropertyValue('--x')), y: parseFloat(positioner.style.getPropertyValue('--y')) }),
};
}

describe('an open dropdown menu, when the page moves under it', () => {
it('opens under its trigger', async () => {
const r = rig(true);
r.menu.open();
await settled();
expect(r.menu.api.open).toBe(true);
expect(r.offset()).toEqual({ x: 140, y: 210 + 30 + GUTTER });
});

it('follows its host when the page scrolls, staying under its trigger', async () => {
const r = rig(true);
r.menu.open();
await settled();
await r.scrollPage(150);
expect(r.offset()).toEqual({ x: 140, y: 60 + 30 + GUTTER });
await r.scrollPage(-150);
expect(r.offset()).toEqual({ x: 140, y: 210 + 30 + GUTTER });
});

it('keeps its place when its trigger moves inside the host', async () => {
const r = rig(true);
r.menu.open();
await settled();
await r.shiftTrigger(36);
expect(r.offset()).toEqual({ x: 140, y: 210 + 30 + GUTTER });
// And still follows the page from there.
await r.scrollPage(150);
expect(r.offset()).toEqual({ x: 140, y: 60 + 30 + GUTTER });
});

it('takes its trigger\'s new place the next time it opens', async () => {
const r = rig(true);
r.menu.open();
await settled();
await r.shiftTrigger(36);
r.menu.close();
await settled();
r.menu.open();
await settled();
expect(r.offset()).toEqual({ x: 176, y: 210 + 30 + GUTTER });
});

it('follows its host when the page scrolls, opened at a point', async () => {
const r = rig(false);
r.menu.openAt(300, 400);
await settled();
expect(r.menu.api.open).toBe(true);
expect(r.offset()).toEqual({ x: 300, y: 400 + GUTTER });
await r.scrollPage(150);
expect(r.offset()).toEqual({ x: 300, y: 250 + GUTTER });
});

it('moves to the next point when asked again while open, and follows the page from there', async () => {
const r = rig(false);
r.menu.openAt(300, 400);
await settled();
r.menu.openAt(500, 320);
await settled();
expect(r.offset()).toEqual({ x: 500, y: 320 + GUTTER });
await r.scrollPage(150);
expect(r.offset()).toEqual({ x: 500, y: 170 + GUTTER });
});

it('opens at the point it is given, though it has a trigger', async () => {
const r = rig(true);
r.menu.openAt(300, 400);
await settled();
expect(r.offset()).toEqual({ x: 300, y: 400 + GUTTER });
await r.scrollPage(150);
expect(r.offset()).toEqual({ x: 300, y: 250 + GUTTER });
// The point is this opening's alone: the next one is the trigger's.
r.menu.close();
await settled();
r.menu.open();
await settled();
expect(r.offset()).toEqual({ x: 140, y: 60 + 30 + GUTTER });
});

it('opens at the point when a row\'s selection reopens it', async () => {
const host = document.createElement('div');
host.className = 'vela-ui';
document.body.append(host);
place(host, { x: 100, y: 200, width: 800, height: 600 });
const menu: DropdownMenu = new DropdownMenu({ host, items: ROWS, onSelect: () => menu.openAt(500, 320) });
menus.push(menu);
const positioner = host.querySelector<HTMLElement>('.vela-ui-layer')!;
menu.openAt(300, 400);
await settled();
const row = host.querySelector<HTMLElement>('[data-slot~="dropdown-menu-item"]')!;
row.dispatchEvent(new PointerEvent('pointermove', { bubbles: true, pointerType: 'mouse', clientX: 310, clientY: 420 }));
await settled();
row.click();
await settled();
expect(menu.api.open).toBe(true);
expect(parseFloat(positioner.style.getPropertyValue('--x'))).toBe(500);
expect(parseFloat(positioner.style.getPropertyValue('--y'))).toBe(320 + GUTTER);
});
});
Loading