MQTTDebugModal.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
  2. import { useTranslation } from 'react-i18next';
  3. import { X, Play, Square, Trash2, RefreshCw, ArrowDown, ArrowUp, Search } from 'lucide-react';
  4. import { api, type MQTTLogEntry } from '../api/client';
  5. import { Button } from './Button';
  6. import { useState, useEffect, useRef, useMemo } from 'react';
  7. interface MQTTDebugModalProps {
  8. printerId: number;
  9. printerName: string;
  10. onClose: () => void;
  11. }
  12. export function MQTTDebugModal({ printerId, printerName, onClose }: MQTTDebugModalProps) {
  13. const { t } = useTranslation();
  14. const queryClient = useQueryClient();
  15. const [autoScroll, setAutoScroll] = useState(true);
  16. const [expandedLogs, setExpandedLogs] = useState<Set<number>>(new Set());
  17. const [searchQuery, setSearchQuery] = useState('');
  18. const [directionFilter, setDirectionFilter] = useState<'all' | 'in' | 'out'>('all');
  19. const logContainerRef = useRef<HTMLDivElement>(null);
  20. const { data, isLoading, refetch } = useQuery({
  21. queryKey: ['mqtt-logs', printerId],
  22. queryFn: () => api.getMQTTLogs(printerId),
  23. refetchInterval: 1000, // Poll every second when logging is enabled
  24. });
  25. const enableMutation = useMutation({
  26. mutationFn: () => api.enableMQTTLogging(printerId),
  27. onSuccess: () => {
  28. queryClient.invalidateQueries({ queryKey: ['mqtt-logs', printerId] });
  29. },
  30. });
  31. const disableMutation = useMutation({
  32. mutationFn: () => api.disableMQTTLogging(printerId),
  33. onSuccess: () => {
  34. queryClient.invalidateQueries({ queryKey: ['mqtt-logs', printerId] });
  35. },
  36. });
  37. const clearMutation = useMutation({
  38. mutationFn: () => api.clearMQTTLogs(printerId),
  39. onSuccess: () => {
  40. queryClient.invalidateQueries({ queryKey: ['mqtt-logs', printerId] });
  41. },
  42. });
  43. // Close on Escape key
  44. useEffect(() => {
  45. const handleKeyDown = (e: KeyboardEvent) => {
  46. if (e.key === 'Escape') onClose();
  47. };
  48. window.addEventListener('keydown', handleKeyDown);
  49. return () => window.removeEventListener('keydown', handleKeyDown);
  50. }, [onClose]);
  51. // Auto-scroll to bottom when new logs arrive
  52. useEffect(() => {
  53. if (autoScroll && logContainerRef.current) {
  54. logContainerRef.current.scrollTop = logContainerRef.current.scrollHeight;
  55. }
  56. }, [data?.logs, autoScroll]);
  57. const toggleExpand = (index: number) => {
  58. setExpandedLogs((prev) => {
  59. const newSet = new Set(prev);
  60. if (newSet.has(index)) {
  61. newSet.delete(index);
  62. } else {
  63. newSet.add(index);
  64. }
  65. return newSet;
  66. });
  67. };
  68. const formatTimestamp = (timestamp: string) => {
  69. const date = new Date(timestamp);
  70. return date.toLocaleTimeString('en-US', { hour12: false, fractionalSecondDigits: 3 });
  71. };
  72. const formatPayload = (payload: unknown, expanded: boolean): string => {
  73. if (payload === undefined || payload === null) {
  74. return '<empty>';
  75. }
  76. // If payload is already a string, parse it first to format nicely
  77. const obj = typeof payload === 'string' ? JSON.parse(payload) : payload;
  78. const json = JSON.stringify(obj, null, expanded ? 2 : 0);
  79. if (!expanded && json.length > 100) {
  80. return json.substring(0, 100) + '...';
  81. }
  82. return json;
  83. };
  84. const loggingEnabled = data?.logging_enabled ?? false;
  85. const logs = useMemo(() => data?.logs ?? [], [data?.logs]);
  86. // Filter logs based on search query and direction filter
  87. const filteredLogs = useMemo(() => {
  88. return logs.filter((log) => {
  89. // Direction filter
  90. if (directionFilter !== 'all' && log.direction !== directionFilter) {
  91. return false;
  92. }
  93. // Search filter
  94. if (searchQuery.trim()) {
  95. const query = searchQuery.toLowerCase();
  96. const topicMatch = log.topic.toLowerCase().includes(query);
  97. const payloadStr = JSON.stringify(log.payload).toLowerCase();
  98. const payloadMatch = payloadStr.includes(query);
  99. return topicMatch || payloadMatch;
  100. }
  101. return true;
  102. });
  103. }, [logs, searchQuery, directionFilter]);
  104. return (
  105. <div className="fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4">
  106. <div className="bg-bambu-dark-secondary rounded-lg max-w-4xl w-full max-h-[85vh] flex flex-col">
  107. {/* Header */}
  108. <div className="flex items-center justify-between p-4 border-b border-bambu-dark-tertiary">
  109. <div>
  110. <h2 className="text-lg font-semibold text-white">{t('mqttDebug.title')}</h2>
  111. <p className="text-sm text-bambu-gray">{printerName}</p>
  112. </div>
  113. <button
  114. onClick={onClose}
  115. className="text-bambu-gray hover:text-white transition-colors"
  116. >
  117. <X className="w-5 h-5" />
  118. </button>
  119. </div>
  120. {/* Controls */}
  121. <div className="flex flex-col gap-2 p-4 border-b border-bambu-dark-tertiary">
  122. <div className="flex items-center gap-2">
  123. {loggingEnabled ? (
  124. <Button
  125. size="sm"
  126. variant="secondary"
  127. onClick={() => disableMutation.mutate()}
  128. disabled={disableMutation.isPending}
  129. >
  130. <Square className="w-4 h-4" />
  131. {t('mqttDebug.stopLogging')}
  132. </Button>
  133. ) : (
  134. <Button
  135. size="sm"
  136. onClick={() => enableMutation.mutate()}
  137. disabled={enableMutation.isPending}
  138. >
  139. <Play className="w-4 h-4" />
  140. {t('mqttDebug.startLogging')}
  141. </Button>
  142. )}
  143. <Button
  144. size="sm"
  145. variant="secondary"
  146. onClick={() => clearMutation.mutate()}
  147. disabled={clearMutation.isPending || logs.length === 0}
  148. >
  149. <Trash2 className="w-4 h-4" />
  150. {t('mqttDebug.clearLog')}
  151. </Button>
  152. <Button
  153. size="sm"
  154. variant="secondary"
  155. onClick={() => refetch()}
  156. disabled={isLoading}
  157. >
  158. <RefreshCw className={`w-4 h-4 ${isLoading ? 'animate-spin' : ''}`} />
  159. </Button>
  160. <div className="flex-1" />
  161. <label className="flex items-center gap-2 text-sm text-bambu-gray cursor-pointer">
  162. <input
  163. type="checkbox"
  164. checked={autoScroll}
  165. onChange={(e) => setAutoScroll(e.target.checked)}
  166. className="rounded border-bambu-dark-tertiary"
  167. />
  168. Auto-scroll
  169. </label>
  170. <span className="text-sm text-bambu-gray">
  171. {filteredLogs.length}/{logs.length}
  172. </span>
  173. </div>
  174. {/* Search and Filter Row */}
  175. <div className="flex items-center gap-2">
  176. <div className="relative flex-1">
  177. <Search className="absolute left-2.5 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray" />
  178. <input
  179. type="text"
  180. placeholder={t('mqttDebug.searchPlaceholder')}
  181. value={searchQuery}
  182. onChange={(e) => setSearchQuery(e.target.value)}
  183. className="w-full pl-8 pr-3 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"
  184. />
  185. {searchQuery && (
  186. <button
  187. onClick={() => setSearchQuery('')}
  188. className="absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white"
  189. >
  190. <X className="w-4 h-4" />
  191. </button>
  192. )}
  193. </div>
  194. <div className="flex items-center gap-1 bg-bambu-dark rounded border border-bambu-dark-tertiary">
  195. <button
  196. onClick={() => setDirectionFilter('all')}
  197. className={`px-2 py-1.5 text-xs rounded-l transition-colors ${
  198. directionFilter === 'all'
  199. ? 'bg-bambu-green text-white'
  200. : 'text-bambu-gray hover:text-white'
  201. }`}
  202. >
  203. {t('mqttDebug.all')}
  204. </button>
  205. <button
  206. onClick={() => setDirectionFilter('in')}
  207. className={`px-2 py-1.5 text-xs transition-colors flex items-center gap-1 ${
  208. directionFilter === 'in'
  209. ? 'bg-blue-500 text-white'
  210. : 'text-bambu-gray hover:text-white'
  211. }`}
  212. >
  213. <ArrowDown className="w-3 h-3" />
  214. {t('mqttDebug.incoming')}
  215. </button>
  216. <button
  217. onClick={() => setDirectionFilter('out')}
  218. className={`px-2 py-1.5 text-xs rounded-r transition-colors flex items-center gap-1 ${
  219. directionFilter === 'out'
  220. ? 'bg-green-500 text-white'
  221. : 'text-bambu-gray hover:text-white'
  222. }`}
  223. >
  224. <ArrowUp className="w-3 h-3" />
  225. {t('mqttDebug.outgoing')}
  226. </button>
  227. </div>
  228. </div>
  229. </div>
  230. {/* Log Content */}
  231. <div
  232. ref={logContainerRef}
  233. className="flex-1 overflow-auto p-4 font-mono text-xs bg-black min-h-[400px]"
  234. >
  235. {logs.length === 0 ? (
  236. <div className="flex flex-col items-center justify-center h-full text-bambu-gray">
  237. <p className="mb-2">{t('mqttDebug.noMessages')}</p>
  238. {!loggingEnabled && (
  239. <p className="text-sm">{t('mqttDebug.startLoggingHint')}</p>
  240. )}
  241. </div>
  242. ) : filteredLogs.length === 0 ? (
  243. <div className="flex flex-col items-center justify-center h-full text-bambu-gray">
  244. <p className="mb-2">{t('mqttDebug.noMessagesMatch')}</p>
  245. <p className="text-sm">{t('mqttDebug.adjustFilterHint')}</p>
  246. </div>
  247. ) : (
  248. <div className="space-y-1">
  249. {filteredLogs.map((log: MQTTLogEntry, index: number) => {
  250. const isExpanded = expandedLogs.has(index);
  251. const isIncoming = log.direction === 'in';
  252. return (
  253. <div
  254. key={index}
  255. className={`p-2 rounded cursor-pointer hover:bg-bambu-dark-secondary transition-colors ${
  256. isExpanded ? 'bg-bambu-dark-secondary' : ''
  257. }`}
  258. onClick={() => toggleExpand(index)}
  259. >
  260. <div className="flex items-start gap-2">
  261. <span className="text-bambu-gray shrink-0">
  262. {formatTimestamp(log.timestamp)}
  263. </span>
  264. <span
  265. className={`shrink-0 ${
  266. isIncoming ? 'text-blue-400' : 'text-green-400'
  267. }`}
  268. title={isIncoming ? t('mqttDebug.incoming') : t('mqttDebug.outgoing')}
  269. >
  270. {isIncoming ? (
  271. <ArrowDown className="w-3 h-3" />
  272. ) : (
  273. <ArrowUp className="w-3 h-3" />
  274. )}
  275. </span>
  276. <span className="text-purple-400 shrink-0">{log.topic}</span>
  277. </div>
  278. {isExpanded ? (
  279. <pre className="mt-2 p-3 bg-gray-900 border border-gray-700 rounded text-green-400 overflow-x-auto whitespace-pre-wrap break-all max-h-96 overflow-y-auto text-xs">
  280. {formatPayload(log.payload, true)}
  281. </pre>
  282. ) : (
  283. <pre className="mt-1 text-white/80 truncate">
  284. {formatPayload(log.payload, false)}
  285. </pre>
  286. )}
  287. </div>
  288. );
  289. })}
  290. </div>
  291. )}
  292. </div>
  293. {/* Footer */}
  294. <div className="flex items-center justify-between p-4 border-t border-bambu-dark-tertiary">
  295. <div className="text-sm text-bambu-gray">
  296. {loggingEnabled ? (
  297. <span className="flex items-center gap-2">
  298. <span className="w-2 h-2 bg-green-500 rounded-full animate-pulse" />
  299. {t('mqttDebug.loggingActive')}
  300. </span>
  301. ) : (
  302. <span>{t('mqttDebug.loggingStopped')}</span>
  303. )}
  304. </div>
  305. <Button variant="secondary" onClick={onClose}>
  306. {t('common.close')}
  307. </Button>
  308. </div>
  309. </div>
  310. </div>
  311. );
  312. }