export type KeyedDocumentRoute = { key: string }; export type DocumentRouteSwap = { current: T; pending?: T; previous?: T; }; export function initialDocumentRouteSwap( current: T, ): DocumentRouteSwap { return { current }; } export function requestDocumentRoute( state: DocumentRouteSwap, requested: T, ): DocumentRouteSwap { if (requested.key === state.current.key) { return state.pending ? { current: state.current, previous: state.previous } : state; } if (requested.key === state.previous?.key) { return { current: state.previous, previous: state.current }; } return { ...state, pending: requested }; } export function resolveDocumentRoute( state: DocumentRouteSwap, key: string, ): DocumentRouteSwap { if (state.pending?.key !== key) return state; return { current: state.pending, previous: state.current }; } export function closeDocumentRoute( state: DocumentRouteSwap, key: string, ): DocumentRouteSwap { return state.previous?.key === key ? { current: state.current, pending: state.pending } : state; }