import { useCallback, useSyncExternalStore } from 'react';
import { WeBObservableSetRead } from '../../buttercup/observable';

/**
 * Subscribe to a WeBObservableSet (the selection, the emphasised records)
 * and re-render when it changes.
 *
 * `values` is replaced (never mutated) on change, so it's safe as a
 * dependency or a memo key, and a mutation that changes nothing doesn't
 * notify — a marquee sweeping over already-selected records re-renders nobody.
 *
 * @param observable - the set to observe
 * @return the current values, in insertion order
 */
export const useObservableSet = < Value extends string | number >(
	observable: WeBObservableSetRead< Value >
) => {
	const subscribe = useCallback(
		( onChange: () => void ) => observable.observe( onChange ),
		[ observable ]
	);

	return useSyncExternalStore( subscribe, () => observable.values );
};
