import { Input } from "@/components/ui/input" import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select" import SwitchText from '@/components/SwitchText' import InlineCode from '@/components/InlineCode' import { AdvancedDivider, SettingItem, SettingItemDesc } from '../settingsItems' import { useState, useEffect, useRef, useMemo, useReducer } from "react" import { getConfigEmptyState, getConfigAccessors, SettingsCardProps, getPageConfig, configsReducer, getConfigDiff, type PageConfigReducerAction } from "../utils" import { PlusIcon, TrashIcon, Undo2Icon, XIcon } from "lucide-react" import { Button } from "@/components/ui/button" import { TimeInputDialog } from "@/components/TimeInputDialog" import TxAnchor from "@/components/TxAnchor" import { useAutoAnimate } from "@formkit/auto-animate/react" import SettingsCardShell from "../SettingsCardShell" import { cn } from "@/lib/utils" import { txToast } from "@/components/TxToaster" import { useBackendApi } from "@/hooks/fetch" import { useAdminPerms } from "@/hooks/auth" import { useLocation } from "wouter" import type { ResetServerDataPathResp } from "@shared/otherTypes" import { useOpenConfirmDialog } from "@/hooks/dialogs" // Remove duplicates and sort times function sanitizeTimes(times: string[]): string[] { const uniqueTimes = Array.from(new Set(times)); return uniqueTimes.sort((a, b) => { const [aHours, aMinutes] = a.split(':').map(Number); const [bHours, bMinutes] = b.split(':').map(Number); return aHours - bHours || aMinutes - bMinutes; }); } type RestartScheduleBoxProps = { restartTimes: string[] | undefined; setRestartTimes: (val: PageConfigReducerAction['configValue']) => void; disabled?: boolean; }; function RestartScheduleBox({ restartTimes, setRestartTimes, disabled }: RestartScheduleBoxProps) { const [isTimeInputOpen, setIsTimeInputOpen] = useState(false); const [animationParent] = useAutoAnimate(); const addTime = (time: string) => { if (!restartTimes || disabled) return; setRestartTimes(prev => sanitizeTimes([...prev ?? [], time])); }; const removeTime = (index: number) => { if (!restartTimes || disabled) return; setRestartTimes(prev => sanitizeTimes((prev ?? []).filter((_, i) => i !== index))); }; const applyPreset = (presetTimes: string[]) => { if (!restartTimes || disabled) return; setRestartTimes(presetTimes); }; const clearTimes = () => { if (disabled) return; setRestartTimes([]); }; const presetSpanClasses = cn( 'text-muted-foreground', disabled && 'opacity-50 cursor-not-allowed' ) return (
{restartTimes && restartTimes.length === 0 && (
No schedule set. Click on the + button to add a time.

{'Presets: '} applyPreset(['00:00'])} className="cursor-pointer text-sm text-primary hover:underline" > 1x/day {', '} applyPreset(['00:00', '12:00'])} className="cursor-pointer text-sm text-primary hover:underline" > 2x/day {', '} applyPreset(['00:00', '08:00', '16:00'])} className="cursor-pointer text-sm text-primary hover:underline" > 3x/day {', '} applyPreset(['00:00', '06:00', '12:00', '18:00'])} className="cursor-pointer text-sm text-primary hover:underline" > 4x/day

)} {restartTimes && restartTimes.map((time, index) => (
{time} {!disabled && }
))}
setIsTimeInputOpen(false)} onSubmit={addTime} />
) } const getServerDataPlaceholder = (hostSuggested?: string) => { if (hostSuggested) { const withoutTailSlash = hostSuggested.replace(/\/$/, ''); return `${withoutTailSlash}/CFXDefault`; } else if (window.txConsts.isWindows) { return 'C:/Users/Admin/Desktop/CFXDefault'; } else { return '/root/fivem/txData/CFXDefault'; } } // Check if the browser timezone is different from the server timezone function TimeZoneWarning() { try { const browserTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone; if (window.txConsts.serverTimezone !== browserTimezone) { return ( Warning: Your server timezone is set to {window.txConsts.serverTimezone}, but your browser timezone is {browserTimezone}. Make sure to configure the time according to the server timezone. ); } } catch (error) { console.error(error); } return null; } export const pageConfigs = { dataPath: getPageConfig('server', 'dataPath'), restarterSchedule: getPageConfig('restarter', 'schedule'), quietMode: getPageConfig('server', 'quiet'), cfgPath: getPageConfig('server', 'cfgPath', true), startupArgs: getPageConfig('server', 'startupArgs', true), onesync: getPageConfig('server', 'onesync', true), autoStart: getPageConfig('server', 'autoStart', true), resourceTolerance: getPageConfig('restarter', 'resourceStartingTolerance', true), } as const; export default function ConfigCardFxserver({ cardCtx, pageCtx }: SettingsCardProps) { const [showAdvanced, setShowAdvanced] = useState(false); const [isResettingServerData, setIsResettingServerData] = useState(false); const { hasPerm } = useAdminPerms(); const setLocation = useLocation()[1]; const openConfirmDialog = useOpenConfirmDialog(); const [states, dispatch] = useReducer( configsReducer, null, () => getConfigEmptyState(pageConfigs), ); const cfg = useMemo(() => { return getConfigAccessors(cardCtx.cardId, pageConfigs, pageCtx.apiData, dispatch); }, [pageCtx.apiData, dispatch]); //Effects - handle changes and reset advanced settings useEffect(() => { updatePageState(); }, [states]); useEffect(() => { if (showAdvanced) return; Object.values(cfg).forEach(c => c.isAdvanced && c.state.discard()); }, [showAdvanced]); //Refs for configs that don't use state const dataPathRef = useRef(null); const cfgPathRef = useRef(null); const startupArgsRef = useRef(null); const forceQuietMode = pageCtx.apiData?.forceQuietMode; //Marshalling Utils const selectNumberUtil = { toUi: (num?: number) => num ? num.toString() : undefined, toCfg: (str?: string) => str ? parseInt(str) : undefined, } const inputArrayUtil = { toUi: (args?: string[]) => args ? args.join(' ') : '', toCfg: (str?: string) => str ? str.trim().split(/\s+/) : [], } const emptyToNull = (str?: string) => { if (str === undefined) return undefined; const trimmed = str.trim(); return trimmed.length ? trimmed : null; }; //Processes the state of the page and sets the card as pending save if needed const updatePageState = () => { let currStartupArgs; if (startupArgsRef.current) { currStartupArgs = inputArrayUtil.toCfg(startupArgsRef.current.value); } let currDataPath; if (dataPathRef.current?.value) { currDataPath = dataPathRef.current.value.replace(/\\/g, '/').replace(/\/\/+/, '/'); if (currDataPath.endsWith('/')) { currDataPath = currDataPath.slice(0, -1); } } const overwrites = { dataPath: emptyToNull(dataPathRef.current?.value), cfgPath: cfgPathRef.current?.value, startupArgs: currStartupArgs, }; const res = getConfigDiff(cfg, states, overwrites, showAdvanced); pageCtx.setCardPendingSave(res.hasChanges ? cardCtx : null); return res; } //Validate changes (for UX only) and trigger the save API const handleOnSave = () => { const { hasChanges, localConfigs } = updatePageState(); if (!hasChanges) return; if (!localConfigs.server?.dataPath) { return txToast.error({ title: 'The Server Data Folder is required.', md: true, msg: 'If you want to return to the Setup page, click on the "Reset" button instead.', }); } if (localConfigs.server.cfgPath !== undefined && !localConfigs.server.cfgPath) { return txToast.error({ title: 'The CFG File Path is required.', md: true, msg: 'The value should probably be `server.cfg`.', }); } if ( Array.isArray(localConfigs.server?.startupArgs) && localConfigs.server.startupArgs.some((arg) => arg.toLowerCase() === 'onesync') ) { return txToast.error({ title: 'You cannot set OneSync in Startup Arguments.', md: true, msg: 'Please use the selectbox below it.', }); } pageCtx.saveChanges(cardCtx, localConfigs); } //Card content stuff const serverDataPlaceholder = useMemo( () => getServerDataPlaceholder(pageCtx.apiData?.dataPath), [pageCtx.apiData] ); //Reset server server data button const resetServerDataApi = useBackendApi({ method: 'POST', path: `/settings/resetServerDataPath`, throwGenericErrors: true, }); const handleResetServerData = () => { openConfirmDialog({ title: 'Reset Server Data Path', message: (<> Are you sure you want to reset the server data path?

This will not delete any resource files or database, but just reset the txAdmin configuration, allowing you to go back to the Setup page.
If you want, you can set the path back to the current value later.

Warning: take note of the current path before proceeding, so you can set it back later if you need to. Current path: ), onConfirm: () => { setIsResettingServerData(true); resetServerDataApi({ toastLoadingMessage: 'Resetting server data path...', success: (data, toastId) => { if (data.type === 'success') { setLocation('/server/setup'); } }, finally: () => setIsResettingServerData(false), }); }, }); } // cfg.restarterSchedule.state.set(['00:00', '12:00']) // cfg.restarterSchedule.state.set([]) // cfg.restarterSchedule.state.set(undefined) return (
The full path of the folder that contains the resources folder, usually it's the same place that contains your server.cfg.
Resetting this value will allow you to go back to the Setup page, without deleting any files. {pageCtx.apiData?.dataPath && pageCtx.apiData?.hasCustomDataPath && (<>
{window.txConsts.hostConfigSource}: This path should start with {pageCtx.apiData.dataPath} . )}
At which times of day to restart the server.
Note: Make sure your schedule matches your server time and not your local time.
Do not print FXServer's output to the terminal.
You will still be able to use the Live Console. {forceQuietMode && (<>
{window.txConsts.hostConfigSource}: This setting is locked and cannot be changed. )}
{showAdvanced && } The path to your server config file, probably named server.cfg.
This can either be absolute, or relative to the Server Data folder.
Additional command-line arguments to pass to the FXServer instance such as NodeJS CLI flags.
Warning: You almost certainly should not use this option, commands and convars should be placed in your server.cfg instead.
Most servers should be using OneSync On.
The other options are considered deprecated and should not be used unless you know what you're doing. For more information, please read the documentation.
Start the server automatically after txAdmin starts. At server boot, how much time to wait for any single resource to start before restarting the server.
Note: If you are getting failed to start in time errors, increase this value.
) }