import type { ReactElement, ReactNode } from 'react' /** * SelectionScope (API §9) — an insertion-ordered id set with an anchor (the last * explicit pick), projected to LIVE memory nodes. A deleted node drops out of * `ids`/`nodes`, and the scope re-canonicalizes its stored set to match. Range * math stays caller-side (read `anchor`). Seats the selection context. */ import { createContext, useCallback, useEffect, useMemo, useReducer, useRef } from 'react' import type { NodeId, SelectionNode } from './live.js' import { useResolvedNodes } from './live.js' /** The value `useSelection()` returns (API §9). */ export interface Selection { /** Selected ids, insertion-ordered. A deleted node drops out. */ readonly ids: readonly NodeId[] /** LIVE nodes for `ids`, same order — a deleted node drops out here too. */ readonly nodes: readonly SelectionNode[] /** Last explicit pick; null when empty or the anchor node is gone. Range math is caller-side. */ readonly anchor: NodeId | null has(id: NodeId): boolean set(ids: readonly NodeId[]): void add(id: NodeId): void toggle(id: NodeId): void clear(): void } export interface SelectionScopeProps { /** Seed selection (deduped); read once at mount. */ initial?: readonly NodeId[] /** Fires when the selection changes — explicit ops AND liveness drops. Persist here. */ onChange?: (ids: readonly NodeId[]) => void children: ReactNode } export const SelectionContext = createContext(null) SelectionContext.displayName = 'AstraleSelectionContext' interface State { readonly ids: readonly NodeId[] readonly anchor: NodeId | null } type Action = | { readonly t: 'set'; readonly ids: readonly NodeId[] } | { readonly t: 'add'; readonly id: NodeId } | { readonly t: 'toggle'; readonly id: NodeId } | { readonly t: 'clear' } | { readonly t: 'prune'; readonly alive: readonly NodeId[] } function dedupe(ids: readonly NodeId[]): readonly NodeId[] { const seen = new Set() const out: NodeId[] = [] for (const id of ids) { if (!seen.has(id)) { seen.add(id) out.push(id) } } return out } function sameIds(a: readonly NodeId[], b: readonly NodeId[]): boolean { if (a.length !== b.length) return false for (let i = 0; i < a.length; i += 1) if (a[i] !== b[i]) return false return true } function reducer(state: State, action: Action): State { switch (action.t) { case 'set': { const ids = dedupe(action.ids) const anchor = ids.length > 0 ? ids[ids.length - 1]! : null if (sameIds(state.ids, ids) && state.anchor === anchor) return state return { ids, anchor } } case 'add': { if (state.ids.includes(action.id)) { return state.anchor === action.id ? state : { ids: state.ids, anchor: action.id } } return { ids: [...state.ids, action.id], anchor: action.id } } case 'toggle': { // Toggle-off keeps the anchor (the removed id is no longer a valid pivot). if (state.ids.includes(action.id)) { return { ids: state.ids.filter((x) => x !== action.id), anchor: state.anchor } } return { ids: [...state.ids, action.id], anchor: action.id } } case 'clear': return state.ids.length === 0 && state.anchor === null ? state : { ids: [], anchor: null } case 'prune': { const anchorAlive = state.anchor === null || action.alive.includes(state.anchor) if (sameIds(state.ids, action.alive)) { return anchorAlive ? state : { ids: state.ids, anchor: null } } return { ids: action.alive, anchor: anchorAlive ? state.anchor : null } } } } function initState(initial: readonly NodeId[] | undefined): State { return { ids: dedupe(initial ?? []), anchor: null } } export function SelectionScope(props: SelectionScopeProps): ReactElement { const { initial, onChange, children } = props const [state, dispatch] = useReducer(reducer, initial, initState) const { aliveIds, nodes, pending, error } = useResolvedNodes(state.ids) // Re-canonicalize stored state when liveness drops a node (or its anchor). useEffect(() => { const anchorDead = state.anchor !== null && !aliveIds.includes(state.anchor) if (pending || error !== undefined) return if (!sameIds(state.ids, aliveIds) || anchorDead) dispatch({ t: 'prune', alive: aliveIds }) }, [aliveIds, pending, error, state.ids, state.anchor]) // Report changes (explicit ops AND liveness drops), skipping the initial mount. const onChangeRef = useRef(onChange) onChangeRef.current = onChange const mounted = useRef(false) useEffect(() => { if (!mounted.current) { mounted.current = true return } onChangeRef.current?.(aliveIds) }, [aliveIds]) const set = useCallback((ids: readonly NodeId[]) => dispatch({ t: 'set', ids }), []) const add = useCallback((id: NodeId) => dispatch({ t: 'add', id }), []) const toggle = useCallback((id: NodeId) => dispatch({ t: 'toggle', id }), []) const clear = useCallback(() => dispatch({ t: 'clear' }), []) const aliveSet = useMemo(() => new Set(aliveIds), [aliveIds]) const aliveSetRef = useRef(aliveSet) aliveSetRef.current = aliveSet const has = useCallback((id: NodeId) => aliveSetRef.current.has(id), []) const anchor = state.anchor !== null && aliveSet.has(state.anchor) ? state.anchor : null const value = useMemo( () => ({ ids: aliveIds, nodes, anchor, has, set, add, toggle, clear }), [aliveIds, nodes, anchor, has, set, add, toggle, clear], ) return {children} }