Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | 1x 1x 1x 1x 1x 1x 29x 29x 6x 6x 6x 6x 6x 21x 41x 2x 41x 39x 39x 21x 21x 21x 21x 21x 21x 1x 2x 2x 1x | import { anchor } from './anchor.ts';
import { ANCHOR_SETTINGS } from './constant.js';
import { captureStack } from './exception.ts';
import { onCleanup } from './lifecycle.ts';
import { subscribe } from './subscription.ts';
import type { StateInspector } from './types.ts';
/**
* Implementation of the StateInspector interface.
* This function allows you to subscribe to state changes and log or trace them.
* This function only works in development mode.
*
* @param state - The state object to inspect
* @param trace - Optional flag to enable stack tracing for state changes (default: false)
* @returns A cleanup function to unsubscribe from state changes
*/
const inspectFn = ((state, trace?: boolean) => {
if (ANCHOR_SETTINGS.production) return () => {};
// Check if the provided state is a valid state object
if (!anchor.has(state)) {
const error = new Error('Invalid state.');
captureStack.error.argument('The given state is not a valid state object.', error, inspectFn.trace, inspectFn);
console.log(state);
return () => {};
}
// Subscribe to the state changes
const unsubscribe = subscribe(state, (target, event) => {
if (trace) {
// Log with stack trace when trace is enabled
console.trace(`[${event.type}]: `, target, event);
} else {
// Just log the state change
console.log(`[${event.type}]: `, target, event);
}
});
// Clean up the subscription when the component is destroyed
onCleanup(() => {
unsubscribe();
});
return unsubscribe;
}) as StateInspector;
// Add the trace method to the inspectFn
inspectFn.trace = ((state) => {
// Call the main function with trace enabled
return (inspectFn as (state: unknown, trace: unknown) => unknown)(state, true);
}) as StateInspector['trace'];
export const inspect = inspectFn as StateInspector;
|