loopable / web /src /ui /useRailSelection.ts
fsanyoto's picture
Deploy AIOS web (React glide grid + FastAPI slice)
bdac669 verified
Raw History Blame Contribute Delete
2.67 kB
import { useCallback, useMemo, useState } from "react";
export type RailClickModifiers = { shiftKey: boolean; ctrlKey: boolean; metaKey: boolean };
type RailSelectionState = { selected: readonly string[]; anchorId: string | null };
// The rule takes plain values so the node gate can run and mutate it without a DOM.
export function railSelectionAfterClick(
ids: readonly string[],
selected: readonly string[],
anchorId: string | null,
id: string,
mods: RailClickModifiers,
): RailSelectionState {
if (mods.shiftKey) {
const from = anchorId === null ? -1 : ids.indexOf(anchorId);
const to = ids.indexOf(id);
if (from >= 0 && to >= 0) {
const lo = Math.min(from, to);
const hi = Math.max(from, to);
return { selected: ids.slice(lo, hi + 1), anchorId };
}
return { selected: [], anchorId: id };
}
if (mods.ctrlKey || mods.metaKey) {
return {
selected: selected.includes(id) ? selected.filter((value) => value !== id) : [...selected, id],
anchorId: id,
};
}
// A plain click on a rail row or home tile opens the item, so it must not show bulk Delete.
// Regression: AutoWiki/waves/wave61/shots/W61-T18-probe.png.
return { selected: [], anchorId: id };
}
export function visibleSelection(
ids: readonly string[], selected: readonly string[],
): readonly string[] {
const chosen = new Set(selected);
return [...new Set(ids)].filter((id) => chosen.has(id));
}
export function useRailSelection(ids: readonly string[]): {
selected: readonly string[];
anchorId: string | null;
onRowClick(id: string, event: RailClickModifiers): void;
clear(): void;
isSelected(id: string): boolean;
} {
const [state, setState] = useState<RailSelectionState>({ selected: [], anchorId: null });
const raw = state.selected;
const onRowClick = useCallback((id: string, event: RailClickModifiers) => {
const mods = { shiftKey: event.shiftKey, ctrlKey: event.ctrlKey, metaKey: event.metaKey };
setState((previous) => railSelectionAfterClick(ids, previous.selected, previous.anchorId, id, mods));
}, [ids]);
const clear = useCallback(() => setState({ selected: [], anchorId: null }), []);
// selected returns the ordered intersection with ids (so every count in the bar matches what
// is rendered), while isSelected(id) answers from the RAW set (so a row hidden by a collapsed
// folder or a search stays selected and comes back selected).
const selected = useMemo(() => visibleSelection(ids, raw), [ids, raw]);
const isSelected = useCallback((id: string) => raw.includes(id), [raw]);
return { selected, anchorId: state.anchorId, onRowClick, clear, isSelected };
}