-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdebug-log.tsx
More file actions
281 lines (252 loc) · 6.62 KB
/
Copy pathdebug-log.tsx
File metadata and controls
281 lines (252 loc) · 6.62 KB
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
import * as React from 'react';
import {
Pressable,
ScrollView,
StyleSheet,
Text,
View,
type ViewStyle,
} from 'react-native';
import { useShowLogs } from '@/components/settings-store';
type Level = 'log' | 'warn' | 'error' | 'fatal';
type Entry = {
id: number;
ts: number;
level: Level;
text: string;
};
const MAX_ENTRIES = 300;
const buffer: Entry[] = [];
const listeners = new Set<() => void>();
let nextId = 0;
let installed = false;
function notify() {
listeners.forEach((l) => l());
}
function safeStringify(value: unknown): string {
if (value instanceof Error) {
return value.stack ?? `${value.name}: ${value.message}`;
}
if (typeof value === 'string') return value;
try {
return JSON.stringify(value);
} catch {
return String(value);
}
}
function format(args: unknown[]): string {
return args.map(safeStringify).join(' ');
}
export function pushLog(level: Level, text: string): void {
buffer.push({ id: nextId++, ts: Date.now(), level, text });
if (buffer.length > MAX_ENTRIES) buffer.shift();
notify();
}
export function clearLogs(): void {
buffer.length = 0;
notify();
}
export function installDebugLogger(): void {
if (installed) return;
installed = true;
const originalLog = console.log.bind(console);
const originalWarn = console.warn.bind(console);
const originalError = console.error.bind(console);
console.log = (...args: unknown[]) => {
pushLog('log', format(args));
originalLog(...args);
};
console.warn = (...args: unknown[]) => {
pushLog('warn', format(args));
originalWarn(...args);
};
console.error = (...args: unknown[]) => {
pushLog('error', format(args));
originalError(...args);
};
const eu = (globalThis as { ErrorUtils?: {
getGlobalHandler?: () => (error: unknown, isFatal?: boolean) => void;
setGlobalHandler?: (h: (error: unknown, isFatal?: boolean) => void) => void;
} }).ErrorUtils;
const prev = eu?.getGlobalHandler?.();
eu?.setGlobalHandler?.((error, isFatal) => {
pushLog(isFatal ? 'fatal' : 'error', `[global] ${safeStringify(error)}`);
prev?.(error, isFatal);
});
pushLog('log', '[debug-log] installed');
}
function useEntries(): Entry[] {
return React.useSyncExternalStore(
React.useCallback((onChange) => {
listeners.add(onChange);
return () => listeners.delete(onChange);
}, []),
() => buffer,
() => buffer
);
}
interface DebugLogOverlayProps {
style?: ViewStyle;
}
export function DebugLogOverlay({ style }: DebugLogOverlayProps): React.JSX.Element | null {
const entries = useEntries();
const showLogs = useShowLogs();
const [expanded, setExpanded] = React.useState(true);
const scrollRef = React.useRef<ScrollView>(null);
React.useEffect(() => {
if (expanded && showLogs) {
requestAnimationFrame(() => scrollRef.current?.scrollToEnd({ animated: false }));
}
}, [entries, expanded, showLogs]);
if (!showLogs) return null;
return (
<View pointerEvents="box-none" style={[styles.overlay, style]}>
<View style={styles.headerRow}>
<Pressable onPress={() => setExpanded((v) => !v)} style={styles.headerBtn}>
<Text style={styles.headerBtnText}>
{expanded ? 'Hide logs' : `Show logs (${entries.length})`}
</Text>
</Pressable>
{expanded ? (
<Pressable onPress={clearLogs} style={styles.headerBtn}>
<Text style={styles.headerBtnText}>Clear</Text>
</Pressable>
) : null}
</View>
{expanded ? (
<View style={styles.panel}>
<ScrollView
ref={scrollRef}
style={styles.scroll}
contentContainerStyle={styles.scrollContent}
>
{entries.length === 0 ? (
<Text style={styles.emptyText}>No logs yet.</Text>
) : (
entries.map((e) => (
<Text key={e.id} style={[styles.line, levelStyle(e.level)]}>
{`[${e.level}] ${e.text}`}
</Text>
))
)}
</ScrollView>
</View>
) : null}
</View>
);
}
interface ErrorBoundaryProps {
label: string;
children: React.ReactNode;
fallback?: React.ReactNode;
}
interface ErrorBoundaryState {
error: Error | null;
}
export class DebugErrorBoundary extends React.Component<ErrorBoundaryProps, ErrorBoundaryState> {
state: ErrorBoundaryState = { error: null };
static getDerivedStateFromError(error: Error): ErrorBoundaryState {
return { error };
}
componentDidCatch(error: Error, info: React.ErrorInfo): void {
pushLog('fatal', `[boundary:${this.props.label}] ${error.message}\n${info.componentStack ?? ''}`);
}
render(): React.ReactNode {
if (this.state.error) {
return (
this.props.fallback ?? (
<View style={styles.boundaryFallback}>
<Text style={styles.boundaryTitle}>Render error in {this.props.label}</Text>
<Text style={styles.boundaryMsg}>{this.state.error.message}</Text>
</View>
)
);
}
return this.props.children;
}
}
function levelStyle(level: Level) {
switch (level) {
case 'warn':
return styles.warn;
case 'error':
return styles.error;
case 'fatal':
return styles.fatal;
default:
return styles.log;
}
}
const styles = StyleSheet.create({
overlay: {
position: 'absolute',
left: 8,
right: 8,
bottom: 8,
gap: 6,
},
headerRow: {
flexDirection: 'row',
gap: 8,
alignSelf: 'flex-end',
},
headerBtn: {
paddingVertical: 6,
paddingHorizontal: 12,
borderRadius: 8,
backgroundColor: 'rgba(0,0,0,0.65)',
borderWidth: 1,
borderColor: 'rgba(255,255,255,0.2)',
},
headerBtnText: {
color: '#ffffff',
fontSize: 12,
fontWeight: '600',
},
panel: {
height: 220,
backgroundColor: 'rgba(0,0,0,0.78)',
borderRadius: 10,
borderWidth: 1,
borderColor: 'rgba(255,255,255,0.18)',
padding: 8,
},
scroll: {
flex: 1,
},
scrollContent: {
gap: 2,
},
emptyText: {
color: 'rgba(255,255,255,0.45)',
fontSize: 12,
fontStyle: 'italic',
},
line: {
color: '#e6e6f0',
fontSize: 11,
fontFamily: 'Courier',
},
log: { color: '#cfd2e6' },
warn: { color: '#ffcc66' },
error: { color: '#ff8080' },
fatal: { color: '#ff4d4d', fontWeight: '700' },
boundaryFallback: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
padding: 24,
backgroundColor: '#1a0a0a',
gap: 8,
},
boundaryTitle: {
color: '#ff8080',
fontSize: 16,
fontWeight: '700',
},
boundaryMsg: {
color: '#ffcccc',
fontSize: 13,
textAlign: 'center',
},
});