Skip to content

Commit

Permalink
feat(trace): added debug option for logging results
Browse files Browse the repository at this point in the history
  • Loading branch information
andrewcourtice committed Sep 8, 2021
1 parent 6ff7abd commit d241bea
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 0 deletions.
25 changes: 25 additions & 0 deletions extensions/trace/src/constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import type {
TraceGate,
} from './types';

export const GATE_COLOUR = {
default: {
foreground: '#FFFFFF',
background: '#6B7280',
},
get: {
foreground: '#FFFFFF',
background: '#10B981',
},
set: {
foreground: '#FFFFFF',
background: '#3B82F6',
},
deleteProperty: {
foreground: '#FFFFFF',
background: '#EF4444',
},
} as Record<TraceGate<any> | 'default', {
foreground: string;
background: string;
}>;
28 changes: 28 additions & 0 deletions extensions/trace/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
import {
GATE_COLOUR,
} from './constants';

import {
EVENTS,
BaseState,
Expand All @@ -18,6 +22,7 @@ import type {
TraceGate,
TraceListener,
TraceOptions,
TraceResult,
} from './types';

export * from './types';
Expand Down Expand Up @@ -107,11 +112,30 @@ function trace<TValue extends object>(value: TValue, gates: TraceGate<TValue> |
});
}

function logResult<TValue extends object>({ gate, path }: TraceResult<TValue>) {
const {
foreground,
background,
} = (GATE_COLOUR[gate] || GATE_COLOUR.default);

const style = [
'padding: 3px',
'font-weight: bold',
'border-radius: 3px',
`color: ${foreground}`,
`background-color: ${background}`,
].join(';');

console.log(`%c${gate}%c ${path}`, style, '');
}

export default function traceExtension<TState extends BaseState>(options?: Partial<Options>) {
const {
autoStart,
debug,
} = {
autoStart: false,
debug: false,
...options,
} as Options;

Expand All @@ -120,6 +144,10 @@ export default function traceExtension<TState extends BaseState>(options?: Parti

function startTrace(gates: TraceGate<TState> | TraceGate<TState>[] = 'set') {
store.provider('write', state => trace(state, gates, result => {
if (debug) {
logResult(result);
}

traceCallbacks.forEach(callback => callback(result));
}));
}
Expand Down
1 change: 1 addition & 0 deletions extensions/trace/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,5 @@ export interface TraceListener {

export interface Options {
autoStart: boolean;
debug: boolean;
}

0 comments on commit d241bea

Please sign in to comment.