diff --git a/NetworkTabTemp.tsx b/NetworkTabTemp.tsx new file mode 100644 index 0000000..4aa784d --- /dev/null +++ b/NetworkTabTemp.tsx @@ -0,0 +1,260 @@ +import { useState, useEffect } from 'react'; +import { NetworkLog, networkConfig } from '../core/fetchInterceptor'; +import { theme, injectDevCompanionStyles } from './styles'; + +interface NetworkTabProps { + logs: NetworkLog[]; + onClear?: () => void; +} + +export const NetworkTab = ({ logs = [], onClear }: NetworkTabProps) => { + const [searchTerm, setSearchTerm] = useState(''); + const [selectedMethod, setSelectedMethod] = useState('ALL'); + const [isOffline, setIsOffline] = useState(networkConfig.isOffline); + const [delay, setDelay] = useState(networkConfig.delayMs); + const [copiedId, setCopiedId] = useState(null); + + useEffect(() => { + injectDevCompanionStyles(); + }, []); + + const handleToggleOffline = () => { + const nextState = !isOffline; + setIsOffline(nextState); + networkConfig.isOffline = nextState; + }; + + const handleDelayChange = (newDelay: number) => { + setDelay(newDelay); + networkConfig.delayMs = newDelay; + }; + + const filteredLogs = logs.filter((log) => { + if (!log || !log.url) return false; + const matchesSearch = log.url.toLowerCase().includes((searchTerm || '').toLowerCase()); + const matchesMethod = selectedMethod === 'ALL' || log.method === selectedMethod; + return matchesSearch && matchesMethod; + }); + + const handleCopyCurl = (log: NetworkLog) => { + const curl = `curl -X ${log.method} "${log.url}"`; + navigator.clipboard.writeText(curl); + setCopiedId(log.id); + setTimeout(() => setCopiedId(null), 1500); + }; + + const getMethodColor = (method: string) => { + switch (method?.toUpperCase()) { + case 'GET': return theme.methodGet; + case 'POST': return theme.methodPost; + case 'PUT': return theme.methodPut; + case 'DELETE': return theme.methodDelete; + default: return theme.textPrimary; + } + }; + + return ( +
+ {/* Simulation Controls */} +
+ + +
+ Delay: + +
+
+ + {/* Filters & Actions */} +
+ setSearchTerm(e.target.value)} + style={{ + flex: 1, + background: theme.cardBg, + color: theme.textPrimary, + border: `1px solid ${theme.border}`, + borderRadius: '6px', + padding: '6px 10px', + fontSize: '12px', + outline: 'none', + }} + /> + + + {onClear && ( + + )} +
+ + {/* Requests List */} +
+ {filteredLogs.length === 0 ? ( +

+ No requests captured. +

+ ) : ( + filteredLogs.map((log) => { + const isError = !log.status || log.status >= 400; + const statusColor = isError ? theme.danger : theme.success; + + return ( +
+
+ + {log.method} + + + {log.url} + +
+ +
+ {log.duration !== undefined && ( + + {log.duration}ms + + )} + + {log.status || 'ERR'} + + +
+
+ ); + }) + )} +
+
+ ); +}; \ No newline at end of file diff --git a/src/components/DevCompanion.tsx b/src/components/DevCompanion.tsx index 8b5fb10..f8d4a65 100644 --- a/src/components/DevCompanion.tsx +++ b/src/components/DevCompanion.tsx @@ -1,120 +1,158 @@ import React, { useEffect, useState } from 'react'; import { initFetchInterceptor, NetworkLog } from '../core/fetchInterceptor'; -import { StorageInspector } from './StorageInspector'; +import { StorageTab } from './StorageTab'; +import { NetworkTab } from './NetworkTab'; +import { useKeyboardShortcut } from '../hooks/useKeyboardShortcut'; +import { theme, injectDevCompanionStyles } from './styles'; -export const DevCompanion: React.FC = () => { +export interface DevCompanionProps { + position?: 'bottom-right' | 'bottom-left' | 'top-right' | 'top-left'; +} + +export const DevCompanion: React.FC = ({ position = 'bottom-right' }) => { const [isOpen, setIsOpen] = useState(false); const [activeTab, setActiveTab] = useState<'network' | 'storage'>('network'); const [logs, setLogs] = useState([]); + useEffect(() => { + injectDevCompanionStyles(); + }, []); + + useKeyboardShortcut({ key: 'd', ctrlOrCmd: true, shift: true }, () => { + setIsOpen((prev) => !prev); + }); + useEffect(() => { initFetchInterceptor((newLog: NetworkLog) => { setLogs((prev: NetworkLog[]) => [newLog, ...prev]); }); }, []); + const getPositionStyles = () => { + switch (position) { + case 'bottom-left': + return { bottom: 16, left: 16 }; + case 'top-right': + return { top: 16, right: 16 }; + case 'top-left': + return { top: 16, left: 16 }; + case 'bottom-right': + default: + return { bottom: 16, right: 16 }; + } + }; + + const posStyles = getPositionStyles(); + return ( -
+
+ {/* Floating Trigger Button */} + {/* Overlay Panel Card */} {isOpen && (
- {/* Main Panel Navigation Header */} -
- - + {/* Header */} +
+
+ + +
+ + + Ctrl+Shift+D +
- {/* Panel Content */} - {activeTab === 'network' ? ( -
- {logs.length === 0 ? ( -

No requests captured yet.

- ) : ( - logs.map((log: NetworkLog) => ( -
- - [{log.method}] - - - {log.url} - - = 400 ? '#f87171' : '#facc15' }}> - {log.status || 'PENDING'} - -
- )) - )} -
- ) : ( - - )} + {/* Content */} +
+ {activeTab === 'network' ? ( + setLogs([])} /> + ) : ( + + )} +
)}
diff --git a/src/components/NetworkTab.tsx b/src/components/NetworkTab.tsx new file mode 100644 index 0000000..4aa784d --- /dev/null +++ b/src/components/NetworkTab.tsx @@ -0,0 +1,260 @@ +import { useState, useEffect } from 'react'; +import { NetworkLog, networkConfig } from '../core/fetchInterceptor'; +import { theme, injectDevCompanionStyles } from './styles'; + +interface NetworkTabProps { + logs: NetworkLog[]; + onClear?: () => void; +} + +export const NetworkTab = ({ logs = [], onClear }: NetworkTabProps) => { + const [searchTerm, setSearchTerm] = useState(''); + const [selectedMethod, setSelectedMethod] = useState('ALL'); + const [isOffline, setIsOffline] = useState(networkConfig.isOffline); + const [delay, setDelay] = useState(networkConfig.delayMs); + const [copiedId, setCopiedId] = useState(null); + + useEffect(() => { + injectDevCompanionStyles(); + }, []); + + const handleToggleOffline = () => { + const nextState = !isOffline; + setIsOffline(nextState); + networkConfig.isOffline = nextState; + }; + + const handleDelayChange = (newDelay: number) => { + setDelay(newDelay); + networkConfig.delayMs = newDelay; + }; + + const filteredLogs = logs.filter((log) => { + if (!log || !log.url) return false; + const matchesSearch = log.url.toLowerCase().includes((searchTerm || '').toLowerCase()); + const matchesMethod = selectedMethod === 'ALL' || log.method === selectedMethod; + return matchesSearch && matchesMethod; + }); + + const handleCopyCurl = (log: NetworkLog) => { + const curl = `curl -X ${log.method} "${log.url}"`; + navigator.clipboard.writeText(curl); + setCopiedId(log.id); + setTimeout(() => setCopiedId(null), 1500); + }; + + const getMethodColor = (method: string) => { + switch (method?.toUpperCase()) { + case 'GET': return theme.methodGet; + case 'POST': return theme.methodPost; + case 'PUT': return theme.methodPut; + case 'DELETE': return theme.methodDelete; + default: return theme.textPrimary; + } + }; + + return ( +
+ {/* Simulation Controls */} +
+ + +
+ Delay: + +
+
+ + {/* Filters & Actions */} +
+ setSearchTerm(e.target.value)} + style={{ + flex: 1, + background: theme.cardBg, + color: theme.textPrimary, + border: `1px solid ${theme.border}`, + borderRadius: '6px', + padding: '6px 10px', + fontSize: '12px', + outline: 'none', + }} + /> + + + {onClear && ( + + )} +
+ + {/* Requests List */} +
+ {filteredLogs.length === 0 ? ( +

+ No requests captured. +

+ ) : ( + filteredLogs.map((log) => { + const isError = !log.status || log.status >= 400; + const statusColor = isError ? theme.danger : theme.success; + + return ( +
+
+ + {log.method} + + + {log.url} + +
+ +
+ {log.duration !== undefined && ( + + {log.duration}ms + + )} + + {log.status || 'ERR'} + + +
+
+ ); + }) + )} +
+
+ ); +}; \ No newline at end of file diff --git a/src/components/StorageTab.tsx b/src/components/StorageTab.tsx new file mode 100644 index 0000000..9d2fe81 --- /dev/null +++ b/src/components/StorageTab.tsx @@ -0,0 +1,237 @@ +import { useState, useEffect, ChangeEvent } from 'react'; +import { StorageItem, StorageType } from '../types/storage'; +import { getCookies, setCookie, deleteCookie, exportStorageJSON } from '../utils/storage'; +import { theme, injectDevCompanionStyles } from './styles'; + +export const StorageTab = () => { + const [storageType, setStorageType] = useState('localStorage'); + const [items, setItems] = useState([]); + const [editingKey, setEditingKey] = useState(null); + const [editValue, setEditValue] = useState(''); + + useEffect(() => { + injectDevCompanionStyles(); + }, []); + + const loadItems = () => { + if (typeof window === 'undefined') return; + const list: StorageItem[] = []; + + if (storageType === 'localStorage') { + for (let i = 0; i < localStorage.length; i++) { + const key = localStorage.key(i); + if (key) list.push({ key, value: localStorage.getItem(key) || '' }); + } + } else if (storageType === 'sessionStorage') { + for (let i = 0; i < sessionStorage.length; i++) { + const key = sessionStorage.key(i); + if (key) list.push({ key, value: sessionStorage.getItem(key) || '' }); + } + } else if (storageType === 'cookie') { + list.push(...getCookies()); + } + + setItems(list); + }; + + useEffect(() => { + loadItems(); + }, [storageType]); + + const handleSaveEdit = (key: string) => { + if (storageType === 'localStorage') { + localStorage.setItem(key, editValue); + } else if (storageType === 'sessionStorage') { + sessionStorage.setItem(key, editValue); + } else if (storageType === 'cookie') { + setCookie(key, editValue); + } + setEditingKey(null); + loadItems(); + }; + + const handleDelete = (key: string) => { + if (storageType === 'localStorage') { + localStorage.removeItem(key); + } else if (storageType === 'sessionStorage') { + sessionStorage.removeItem(key); + } else if (storageType === 'cookie') { + deleteCookie(key); + } + loadItems(); + }; + + const handleImportJSON = (e: ChangeEvent) => { + const file = e.target.files?.[0]; + if (!file) return; + + const reader = new FileReader(); + reader.onload = (event) => { + try { + const json = JSON.parse(event.target?.result as string); + if (json && json.data) { + Object.entries(json.data).forEach(([k, v]) => { + const strVal = typeof v === 'string' ? v : JSON.stringify(v); + if (storageType === 'localStorage') localStorage.setItem(k, strVal); + if (storageType === 'sessionStorage') sessionStorage.setItem(k, strVal); + if (storageType === 'cookie') setCookie(k, strVal); + }); + loadItems(); + } + } catch (err) { + console.error('[DevCompanion] Failed to import JSON:', err); + } + }; + reader.readAsText(file); + }; + + return ( +
+ {/* Sub-tabs & Actions */} +
+
+ {(['localStorage', 'sessionStorage', 'cookie'] as StorageType[]).map((type) => ( + + ))} +
+ + {/* Refresh + Export / Import */} +
+ + + + +
+
+ + {/* Items Table */} +
+ {items.length === 0 ? ( +

+ No items found in {storageType}. +

+ ) : ( + + + + + + + + + + {items.map((item) => ( + + + + + + ))} + +
KeyValueActions
+ {item.key} + + {editingKey === item.key ? ( + setEditValue(e.target.value)} + style={{ + width: '100%', + background: theme.bg, + color: theme.textPrimary, + border: `1px solid ${theme.accent}`, + borderRadius: '4px', + padding: '3px 6px', + fontSize: '11px', + outline: 'none', + }} + /> + ) : ( + + {item.value} + + )} + + {editingKey === item.key ? ( + + ) : ( + + )} + +
+ )} +
+
+ ); +}; \ No newline at end of file diff --git a/src/components/styles.ts b/src/components/styles.ts new file mode 100644 index 0000000..6a10d36 --- /dev/null +++ b/src/components/styles.ts @@ -0,0 +1,58 @@ +export const theme = { + bg: '#0f172a', // Slate 900 + cardBg: '#1e293b', // Slate 800 + hoverBg: '#334155', // Slate 700 + border: '#334155', // Slate 700 + borderSubtle: '#1e293b', + textPrimary: '#f8fafc', // Slate 50 + textSecondary: '#94a3b8', // Slate 400 + accent: '#0284c7', // Sky 600 + accentHover: '#0369a1', + success: '#4ade80', // Green 400 + warning: '#facc15', // Yellow 400 + danger: '#f87171', // Red 400 + methodGet: '#38bdf8', // Sky 400 + methodPost: '#4ade80', // Emerald 400 + methodPut: '#facc15', // Amber 400 + methodDelete: '#f87171',// Rose 400 +}; + +// Injeta estilos de scrollbar e animação keyframes no head do documento +export const injectDevCompanionStyles = () => { + if (typeof document === 'undefined') return; + const styleId = 'dev-companion-custom-styles'; + if (document.getElementById(styleId)) return; + + const styleEl = document.createElement('style'); + styleEl.id = styleId; + styleEl.innerHTML = ` + .dev-companion-scroll::-webkit-scrollbar { + width: 5px; + height: 5px; + } + .dev-companion-scroll::-webkit-scrollbar-track { + background: #0f172a; + } + .dev-companion-scroll::-webkit-scrollbar-thumb { + background: #334155; + border-radius: 4px; + } + .dev-companion-scroll::-webkit-scrollbar-thumb:hover { + background: #475569; + } + @keyframes devCompanionSlideUp { + from { + opacity: 0; + transform: translateY(8px) scale(0.98); + } + to { + opacity: 1; + transform: translateY(0) scale(1); + } + } + .dev-companion-panel-animate { + animation: devCompanionSlideUp 0.18s cubic-bezier(0.16, 1, 0.3, 1) forwards; + } + `; + document.head.appendChild(styleEl); +}; \ No newline at end of file diff --git a/src/core/fetchInterceptor.ts b/src/core/fetchInterceptor.ts index d32b789..ba64ee6 100644 --- a/src/core/fetchInterceptor.ts +++ b/src/core/fetchInterceptor.ts @@ -3,34 +3,92 @@ export interface NetworkLog { url: string; method: string; status?: number; + duration?: number; timestamp: string; } type LogCallback = (log: NetworkLog) => void; +let isInitialized = false; + +// Flags of Network Settings +export const networkConfig = { + isOffline: false, + delayMs: 0, +}; + export const initFetchInterceptor = (onLog: LogCallback) => { + if (isInitialized || typeof window === 'undefined') return; + isInitialized = true; + const originalFetch = window.fetch; window.fetch = async (...args) => { - const [resource, config] = args; - const url = typeof resource === 'string' ? resource : resource instanceof Request ? resource.url : String(resource); - const method = config?.method || 'GET'; + const startTime = performance.now(); + const id = Math.random().toString(36).substring(2, 9); + + let url = ''; + let method = 'GET'; + + if (typeof args[0] === 'string') { + url = args[0]; + } else if (args[0] instanceof URL) { + url = args[0].toString(); + } else if (args[0] instanceof Request) { + url = args[0].url; + method = args[0].method || 'GET'; + } + + if (args[1] && args[1].method) { + method = args[1].method.toUpperCase(); + } - const logItem: NetworkLog = { - id: Math.random().toString(36).substring(2, 9), - url, - method: method.toUpperCase(), - timestamp: new Date().toLocaleTimeString() - }; + // 1. Simulation of Network Delay (waits before firing the fetch) + if (networkConfig.delayMs > 0) { + await new Promise((resolve) => setTimeout(resolve, networkConfig.delayMs)); + } + + // 2. Simulation of Offline Mode (blocks the fetch before firing) + if (networkConfig.isOffline) { + const endTime = performance.now(); + onLog({ + id, + url, + method, + status: 0, // 0 = Failed / Aborted + duration: Math.round(endTime - startTime), + timestamp: new Date().toLocaleTimeString(), + }); + + throw new TypeError('Failed to fetch (Simulated Offline Mode)'); + } try { const response = await originalFetch(...args); - logItem.status = response.status; - onLog(logItem); + const endTime = performance.now(); + + onLog({ + id, + url, + method, + status: response.status, + duration: Math.round(endTime - startTime), + timestamp: new Date().toLocaleTimeString(), + }); + return response; } catch (error) { - logItem.status = 0; - onLog(logItem); + const endTime = performance.now(); + + onLog({ + id, + url, + method, + status: 0, + duration: Math.round(endTime - startTime), + timestamp: new Date().toLocaleTimeString(), + }); + throw error; } }; diff --git a/src/hooks/useKeyboardShortcut.ts b/src/hooks/useKeyboardShortcut.ts new file mode 100644 index 0000000..4a7d2db --- /dev/null +++ b/src/hooks/useKeyboardShortcut.ts @@ -0,0 +1,19 @@ +import { useEffect } from 'react'; + +export const useKeyboardShortcut = (keyCombo: { key: string; ctrlOrCmd?: boolean; shift?: boolean }, callback: () => void) => { + useEffect(() => { + const handleKeyDown = (event: KeyboardEvent) => { + const isCmdOrCtrl = keyCombo.ctrlOrCmd ? (event.metaKey || event.ctrlKey) : true; + const isShift = keyCombo.shift ? event.shiftKey : true; + const isKey = event.key.toLowerCase() === keyCombo.key.toLowerCase(); + + if (isCmdOrCtrl && isShift && isKey) { + event.preventDefault(); + callback(); + } + }; + + window.addEventListener('keydown', handleKeyDown); + return () => window.removeEventListener('keydown', handleKeyDown); + }, [keyCombo, callback]); +}; \ No newline at end of file diff --git a/src/types/storage.ts b/src/types/storage.ts new file mode 100644 index 0000000..0aba0b0 --- /dev/null +++ b/src/types/storage.ts @@ -0,0 +1,12 @@ +export type StorageType = 'localStorage' | 'sessionStorage' | 'cookie'; + +export interface StorageItem { + key: string; + value: string; +} + +export interface StorageExportData { + type: StorageType; + data: Record; + timestamp: string; +} \ No newline at end of file diff --git a/src/utils/storage.ts b/src/utils/storage.ts new file mode 100644 index 0000000..b51ca66 --- /dev/null +++ b/src/utils/storage.ts @@ -0,0 +1,51 @@ +import { StorageItem, StorageType } from '../types/storage'; + +// Lê cookies formatados como key/value +export const getCookies = (): StorageItem[] => { + if (typeof document === 'undefined' || !document.cookie) return []; + return document.cookie.split('; ').map((cookieStr) => { + const [key, ...val] = cookieStr.split('='); + return { key, value: decodeURIComponent(val.join('=')) }; + }); +}; + +// Salva ou remove cookie +export const setCookie = (key: string, value: string, days = 7) => { + if (typeof document === 'undefined') return; + const expires = new Date(Date.now() + days * 864e5).toUTCString(); + document.cookie = `${encodeURIComponent(key)}=${encodeURIComponent(value)}; expires=${expires}; path=/`; +}; + +export const deleteCookie = (key: string) => { + if (typeof document === 'undefined') return; + document.cookie = `${encodeURIComponent(key)}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/`; +}; + +// Exportar Storage para arquivo JSON +export const exportStorageJSON = (type: StorageType) => { + let data: Record = {}; + + if (type === 'localStorage') { + data = { ...localStorage }; + } else if (type === 'sessionStorage') { + data = { ...sessionStorage }; + } else if (type === 'cookie') { + getCookies().forEach((item) => { + data[item.key] = item.value; + }); + } + + const payload = { + type, + timestamp: new Date().toISOString(), + data, + }; + + const blob = new Blob([JSON.stringify(payload, null, 2)], { type: 'application/json' }); + const url = URL.createObjectURL(blob); + const a = document.createElement('a'); + a.href = url; + a.download = `dev-companion-${type}-${Date.now()}.json`; + a.click(); + URL.revokeObjectURL(url); +}; \ No newline at end of file diff --git a/tsconfig.json b/tsconfig.json index a58b35a..60cb166 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -13,7 +13,8 @@ "jsx": "react-jsx", "strict": true, "declaration": true, - "types": ["node"] + "types": ["node"], + "forceConsistentCasingInFileNames": true }, "include": ["src/**/*", "vite.config.ts"] } \ No newline at end of file