/* eslint-disable @typescript-eslint/naming-convention */ import { memo, useCallback, useEffect, useRef, useState } from 'react' import { Button, ScrollArea, useClipboard } from '@janhq/joi' import { useAtomValue } from 'jotai' import { FolderIcon, CheckIcon, CopyIcon } from 'lucide-react' import { twMerge } from 'tailwind-merge' import { useLogs } from '@/hooks/useLogs' import { usePath } from '@/hooks/usePath' import { serverEnabledAtom } from '@/helpers/atoms/LocalServer.atom' import { showScrollBarAtom } from '@/helpers/atoms/Setting.atom' type ServerLogsProps = { limit?: number; withCopy?: boolean } const ServerLogs = (props: ServerLogsProps) => { const { limit = 0, withCopy } = props const { getLogs } = useLogs() const serverEnabled = useAtomValue(serverEnabledAtom) const [logs, setLogs] = useState([]) const listRef = useRef(null) const prevScrollTop = useRef(0) const isUserManuallyScrollingUp = useRef(false) const showScrollBar = useAtomValue(showScrollBarAtom) const updateLogs = useCallback( () => getLogs('app').then((log) => { if (typeof log?.split === 'function') { setLogs( log.split(/\r?\n|\r|\n/g).filter((e) => e.includes('[SERVER]::')) ) } }), // eslint-disable-next-line react-hooks/exhaustive-deps [] ) useEffect(() => { if (serverEnabled) { updateLogs() } }, [serverEnabled, updateLogs]) useEffect(() => { updateLogs() // Log polling interval const intervalId = setInterval(() => { updateLogs() }, window.core?.api?.pollingInterval ?? 1200) // clean up interval return () => clearInterval(intervalId) }, [updateLogs]) const { onRevealInFinder } = usePath() const clipboard = useClipboard({ timeout: 1000 }) const handleScroll = useCallback((event: React.UIEvent) => { const currentScrollTop = event.currentTarget.scrollTop if (prevScrollTop.current > currentScrollTop) { isUserManuallyScrollingUp.current = true } else { const currentScrollTop = event.currentTarget.scrollTop const scrollHeight = event.currentTarget.scrollHeight const clientHeight = event.currentTarget.clientHeight if (currentScrollTop + clientHeight >= scrollHeight) { isUserManuallyScrollingUp.current = false } } if (isUserManuallyScrollingUp.current === true) { event.preventDefault() event.stopPropagation() } prevScrollTop.current = currentScrollTop }, []) useEffect(() => { if (isUserManuallyScrollingUp.current === true || !listRef.current) return const scrollHeight = listRef.current?.scrollHeight ?? 0 listRef.current?.scrollTo({ top: scrollHeight, behavior: 'instant', }) }, [listRef.current?.scrollHeight, isUserManuallyScrollingUp, logs]) return ( <>
{withCopy && (
)}
{logs.length > 0 ? ( {logs.slice(-limit).map((log, i) => { return (

{log}

) })}
) : (

Empty logs

)}
) } export default memo(ServerLogs)