fix(ui): release dashboard refs and drag listeners

Use React Aria ref composition to honor React 19 cleanup for object and callback refs. Keep one pending WebKit press repair across repeated keyboard drags so document listeners do not accumulate. Cover both resource lifecycles with regressions.
This commit is contained in:
Zakk committed 2026-10-28 06:58:10 +00:00
1 parent 93ae4422c9
commit 4773fd8581
4 files changed
+86 -20

No files matched your search

+5 -17
View File
@@ -1,4 +1,5 @@
import {createContext, useCallback, useLayoutEffect, useRef, useState, type ReactNode, type Ref, type RefObject} from 'react';
import {createContext, useCallback, useLayoutEffect, useMemo, useRef, useState, type ReactNode, type Ref, type RefObject} from 'react';
import {mergeRefs} from 'react-aria';
import {packSection} from './packing';
// A section packs as it mounts, before its first paint, and keeps packing until it unmounts.
@@ -28,7 +29,8 @@ export const sectionGrid = (tiles: readonly TileProps[]) => (tiles.some(tile =>
// Auto card's renderer draws the statistics its footprint has room for, and only then.
export const WideCell = createContext(false);
// A ref for the cell, or for an element inside it (`cellOf`), and whether that cell is marked wide.
function useWideMark(cellOf: (node: HTMLElement) => Element | null = node => node) {
const ownCell = (node: HTMLElement) => node;
function useWideMark(cellOf: (node: HTMLElement) => Element | null = ownCell) {
const [wide, setWide] = useState(false);
const ref = useCallback(
(node: HTMLElement | null) => {
@@ -47,21 +49,7 @@ function useWideMark(cellOf: (node: HTMLElement) => Element | null = node => nod
export function DashboardTile({tile, visible, targetRef, children}: {tile: TileProps; visible: boolean; targetRef: Ref<HTMLDivElement>; children: ReactNode}) {
const [mark, wide] = useWideMark();
const ref = useCallback(
(node: HTMLDivElement | null) => {
const unmark = mark(node);
if (typeof targetRef !== 'function') {
if (targetRef) targetRef.current = node;
return unmark;
}
const release = targetRef(node);
return () => {
unmark?.();
if (typeof release === 'function') release();
};
},
[mark, targetRef]
);
const ref = useMemo(() => mergeRefs<HTMLDivElement>(mark, targetRef), [mark, targetRef]);
return (
<div ref={ref} className="rp-dashboard-cell" data-visible={visible} {...tileAttributes(tile)}>
<WideCell value={wide}>{children}</WideCell>
+34 -2
View File
@@ -1,7 +1,39 @@
import {expect, it} from 'vitest';
import {reorderKeys} from './SortableCanvas';
import {createElement} from 'react';
import {renderToStaticMarkup} from 'react-dom/server';
import {expect, it, vi} from 'vitest';
import {SortableCanvas, reorderKeys} from './SortableCanvas';
import {useDragAndDrop} from './dragAndDrop';
vi.mock(import('./dragAndDrop'), {spy: true});
it('moves stable keys together and cancels a drop onto the dragged item', () => {
const ids = ['a', 'b', 'c', 'd'];
expect(reorderKeys(ids, new Set(['a', 'c']), 'd', 'after')).toEqual(['b', 'd', 'a', 'c']);
expect(reorderKeys(ids, new Set(['a']), 'a', 'before')).toBe(ids);
});
it('keeps one pending press repair across repeated keyboard drags', () => {
renderToStaticMarkup(
createElement(SortableCanvas, {label: 'Canvas', items: [], textValue: () => '', dragLabel: () => '', onPlace: () => {}, children: () => null})
);
const end = vi.mocked(useDragAndDrop).mock.calls.at(-1)![0].onDragEnd!;
const listeners = new Map<string, Set<EventListener>>();
vi.stubGlobal('document', {
addEventListener(type: string, listener: EventListener) {
if (!listeners.has(type)) listeners.set(type, new Set());
listeners.get(type)!.add(listener);
},
removeEventListener(type: string, listener: EventListener) {
listeners.get(type)?.delete(listener);
}
});
try {
end({} as never);
end({} as never);
expect(listeners.get('pointerdown')?.size).toBe(1);
expect(listeners.get('mousedown')?.size).toBe(1);
} finally {
for (const done of listeners.get('pointerdown') ?? []) done(new Event('pointerdown'));
vi.unstubAllGlobals();
}
});
+4
View File
@@ -15,10 +15,13 @@ export type CanvasPlace = {target?: string; after?: boolean};
// After a native drag ends, WebKit skips the pointerdown of the next press while its mousedown, pointerup and click
// still arrive, so React Aria's press handlers ignore that press and the first button pressed after a drop does
// nothing. Once per drag, a mousedown without a pointerdown before it gets the pointerdown WebKit left out.
let cancelPressRepair: (() => void) | undefined;
function repairNextPress() {
cancelPressRepair?.();
const done = () => {
document.removeEventListener('pointerdown', done, true);
document.removeEventListener('mousedown', repair, true);
cancelPressRepair = undefined;
};
const repair = (event: MouseEvent) => {
done();
@@ -35,6 +38,7 @@ function repairNextPress() {
})
);
};
cancelPressRepair = done;
document.addEventListener('pointerdown', done, true);
document.addEventListener('mousedown', repair, true);
}
+43 -1
View File
@@ -1,8 +1,10 @@
import type {RefCallback} from 'react';
import {renderToStaticMarkup} from 'react-dom/server';
import {expect, it} from 'vitest';
import {expect, it, vi} from 'vitest';
import {WidgetGrid, WidgetCell} from './WidgetGrid';
import {WidgetGalleryTile} from './WidgetGalleryTile';
import {FloatingPanel} from './FloatingPanel';
import {DashboardTile} from './DashboardTile';
import {anchorPanelOffset, clampPanelSize, defaultPanelWidth, edgePlacement, fitPanelOffset, minPanelSize, nearestEdge, resizePanel} from './panelSize';
const panel = {label: 'honk', resizeLabel: 'Resize', moveLabel: 'Move', movedText: 'Moved', onResize: () => {}, onMove: () => {}, header: 'head'};
it('renders widget size metadata', () => {
@@ -133,3 +135,43 @@ it.each([
['left over bottom', {left: 0, top: 600, width: 320, height: 300}, 'left'],
['bottom over top', {left: 560, top: 0, width: 320, height: 900}, 'bottom']
] as const)('a tie: %s', (_name, box, edge) => expect(nearestEdge(box, view)).toBe(edge));
it.each(['object', 'callback', 'cleanup'] as const)('releases a dashboard tile’s %s ref and width observer', kind => {
const disconnect = vi.fn();
vi.stubGlobal(
'MutationObserver',
class {
observe() {}
disconnect = disconnect;
}
);
try {
let current: HTMLDivElement | null = null;
const object = {current};
const cleanup = vi.fn(() => {
current = null;
});
const targetRef =
kind === 'object'
? object
: (node: HTMLDivElement | null) => {
current = node;
if (kind === 'cleanup') return cleanup;
};
let attach: RefCallback<HTMLDivElement> | undefined;
function Probe() {
const element = DashboardTile({tile: {id: 'cpu', module: 'cpu', size: 'small'}, visible: true, targetRef, children: null});
attach = element.props.ref;
return element;
}
renderToStaticMarkup(<Probe />);
const node = {hasAttribute: () => false} as unknown as HTMLDivElement;
const release = attach!(node);
expect(kind === 'object' ? object.current : current).toBe(node);
if (typeof release === 'function') release();
expect(kind === 'object' ? object.current : current).toBeNull();
expect(disconnect).toHaveBeenCalledOnce();
expect(cleanup).toHaveBeenCalledTimes(kind === 'cleanup' ? 1 : 0);
} finally {
vi.unstubAllGlobals();
}
});