1import React from 'react';
2import { Platform } from 'react-native';
3
4import { LogBoxLog } from './LogBoxLog';
5
6// Context provider for Array<LogBoxLog>
7
8export const LogContext = React.createContext<{
9  selectedLogIndex: number;
10  isDisabled: boolean;
11  logs: LogBoxLog[];
12} | null>(null);
13
14export function useLogs(): {
15  selectedLogIndex: number;
16  isDisabled: boolean;
17  logs: LogBoxLog[];
18} {
19  const logs = React.useContext(LogContext);
20  if (!logs) {
21    if (Platform.OS === 'web' && typeof window !== 'undefined') {
22      // Logbox data that is pre-fetched on the dev server and rendered here.
23      const expoCliStaticErrorElement = document.getElementById('_expo-static-error');
24      if (expoCliStaticErrorElement?.textContent) {
25        const raw = JSON.parse(expoCliStaticErrorElement.textContent);
26        return {
27          ...raw,
28          logs: raw.logs.map((raw: any) => new LogBoxLog(raw)),
29        };
30      }
31    }
32
33    throw new Error('useLogs must be used within a LogProvider');
34  }
35  return logs;
36}
37
38export function useSelectedLog() {
39  const { selectedLogIndex, logs } = useLogs();
40  return logs[selectedLogIndex];
41}
42