-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathclient-config.tsx
More file actions
434 lines (387 loc) · 15.8 KB
/
client-config.tsx
File metadata and controls
434 lines (387 loc) · 15.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
import React, { useEffect, useState, MouseEvent, PropsWithChildren, useRef } from 'react'
import { IconContext } from 'react-icons'
import { IoCloseCircle, IoCloseCircleOutline } from 'react-icons/io5'
import { ChromePicker } from 'react-color'
import { AppContextProvider, useAppContext } from './app-context'
import { GameRenderer } from './playback/GameRenderer'
import { NumInput } from './components/forms'
import {
Colors,
currentColors,
updateGlobalColor,
getGlobalColor,
resetGlobalColors,
DEFAULT_GLOBAL_COLORS
} from './colors'
import { BrightButton, Button } from './components/button'
import { useKeyboard } from './util/keyboard'
import { SectionHeader } from './components/section-header'
export type ClientConfig = typeof DEFAULT_CONFIG
interface Props {
open: boolean
}
const DEFAULT_CONFIG = {
showAllIndicators: false,
showAllRobotRadii: false,
showTimelineMarkers: true,
showHealthBars: true,
showPaintBars: true,
showPaintMarkers: true,
showSRPOutlines: true,
showSRPText: false,
showExceededBytecode: false,
showMapXY: true,
focusRobotTurn: true,
enableFancyPaint: true,
streamRunnerGames: true,
populateRunnerGames: true,
profileGames: false,
validateMaps: false,
resolutionScale: 100,
colors: {
[Colors.TEAM_ONE]: '#cdcdcc',
[Colors.TEAM_TWO]: '#fee493',
[Colors.PAINT_TEAMONE_ONE]: '#666666',
[Colors.PAINT_TEAMONE_TWO]: '#565656',
[Colors.PAINT_TEAMTWO_ONE]: '#b28b52',
[Colors.PAINT_TEAMTWO_TWO]: '#997746',
[Colors.WALLS_COLOR]: '#547f31',
[Colors.TILE_COLOR]: '#4c301e',
[Colors.GAMEAREA_BACKGROUND]: '#2e2323',
[Colors.SIDEBAR_BACKGROUND]: '#3f3131'
} as Record<Colors, string>
}
const configDescription: Record<keyof ClientConfig, string> = {
showAllIndicators: 'Show all indicator dots and lines',
showAllRobotRadii: 'Show all robot view and attack radii',
showTimelineMarkers: 'Show user-generated markers on the timeline',
showHealthBars: 'Show health bars below all robots',
showPaintBars: 'Show paint bars below all robots',
showPaintMarkers: 'Show paint markers created using mark()',
showSRPOutlines: 'Show outlines around active SRPs',
showSRPText: 'Show remaining rounds in the center of inactive SRPs',
showExceededBytecode: 'Show a red highlight over bots that exceeded their bytecode limit',
showMapXY: 'Show X,Y when hovering a tile',
focusRobotTurn: 'Focus the robot when performing their turn during turn-stepping mode',
enableFancyPaint: 'Enable fancy paint rendering',
streamRunnerGames: 'Stream each round from the runner live as the game is being played',
populateRunnerGames: 'Display the finished game immediately when the runner is finished running',
profileGames: 'Enable saving profiling data when running games',
validateMaps: 'Validate maps before running a game',
resolutionScale: 'Resolution scale for the game area. Decrease to help performance.',
colors: ''
}
const configCategories: Record<keyof ClientConfig, string> = {
// Game Visualization
showAllIndicators: 'Game Visualization',
showAllRobotRadii: 'Game Visualization',
showSRPOutlines: 'Game Visualization',
showSRPText: 'Game Visualization',
showMapXY: 'Game Visualization',
enableFancyPaint: 'Game Visualization',
// Robot Display & Status
showHealthBars: 'Robot Display & Status',
showPaintBars: 'Robot Display & Status',
showExceededBytecode: 'Robot Display & Status',
focusRobotTurn: 'Robot Display & Status',
// Markers & Paint Debugging
showTimelineMarkers: 'Markers & Paint Debugging',
showPaintMarkers: 'Markers & Paint Debugging',
// Game Playback
streamRunnerGames: 'Game Playback',
populateRunnerGames: 'Game Playback',
// Developer & Validation Tools
profileGames: 'Developer Tools',
validateMaps: 'Developer Tools',
// Mischellanous
resolutionScale: '',
colors: ''
}
export function getDefaultConfig(): ClientConfig {
const config: ClientConfig = { ...DEFAULT_CONFIG }
for (const key in config) {
const value = localStorage.getItem('config' + key)
if (value) {
;(config[key as keyof ClientConfig] as any) = JSON.parse(value)
}
}
for (const key in config.colors) {
const value = localStorage.getItem('config-colors' + key)
if (value) {
config.colors[key as Colors] = JSON.parse(value)
updateGlobalColor(key as Colors, JSON.parse(value))
}
}
return config
}
export const ConfigPage: React.FC<Props> = (props) => {
const context = useAppContext()
const keyboard = useKeyboard()
const [input, setInput] = useState('')
const [isSearchFocused, setIsSearchFocused] = useState(false)
const [shouldForceOpen, setShouldForceOpen] = useState(false)
const sidebarColor = context.state.config.colors[Colors.SIDEBAR_BACKGROUND]
useEffect(() => {
if (context.state.disableHotkeys || isSearchFocused) return
if (keyboard.keyCode === 'KeyF')
context.updateConfigValue('focusRobotTurn', !context.state.config.focusRobotTurn)
if (keyboard.keyCode === 'KeyI')
context.updateConfigValue('showAllIndicators', !context.state.config.showAllIndicators)
}, [keyboard.keyCode])
if (!props.open) return null
const configEntries = Object.keys(DEFAULT_CONFIG).map((key) => ({
key: key as keyof ClientConfig,
category: configCategories[key as keyof ClientConfig],
value: DEFAULT_CONFIG[key as keyof ClientConfig]
}))
const filteredEntries = configEntries.filter(({ key, category }) => {
if (!input.trim()) return true
const s = input.toLowerCase()
const description = configDescription[key]?.toLowerCase() || ''
return key.toLowerCase().includes(s) || description.includes(s)
})
const groupedCategories = filteredEntries.reduce(
(acc, { category, key }) => {
if (!acc[category]) acc[category] = []
acc[category].push(key)
return acc
},
{} as Record<string, Array<keyof ClientConfig>>
)
return (
<div className={'flex flex-col'}>
<div className="mb-2">Edit Client Config:</div>
<input
type="text"
placeholder="Search Configs..."
className="w-full mb-3 px-3 py-2 border border-white shadow-lg rounded-xl"
value={input}
onChange={(e) => {
setInput(e.target.value)
setShouldForceOpen(true)
}}
onFocus={(e) => {
setIsSearchFocused(true)
setTimeout(() => e.target.select(), 0)
}}
onBlur={() => {
setIsSearchFocused(false)
setShouldForceOpen(false)
}}
autoCapitalize="off"
autoCorrect="off"
autoComplete="off"
style={{
backgroundColor: sidebarColor
}}
/>
{Object.entries(groupedCategories)
.filter(([category]) => category !== '')
.map(([category, keys]) => (
<ConfigCategoryDropdown
key={category}
title={category}
keys={keys}
forceOpen={shouldForceOpen && !!input.trim()}
hasInput={!!input.trim()}
/>
))}
{groupedCategories[''] && (
<div className="mb-3">
{groupedCategories[''].map((key) => {
const value = DEFAULT_CONFIG[key]
if (key === 'colors') return null
if (typeof value === 'number') return <ConfigNumberElement configKey={key} key={key} />
return null
})}
</div>
)}
<ColorConfig />
</div>
)
}
const ColorConfig = () => {
const context = useAppContext()
/* TODO: [future] do this dynamically rather than hardcoding sections */
return (
<>
<div className="m-0 mt-4">
Customize Colors:
<div className="text-sm pb-1 pt-1">Interface</div>
<SingleColorPicker displayName={'Background'} colorName={Colors.GAMEAREA_BACKGROUND} />
<SingleColorPicker displayName={'Sidebar'} colorName={Colors.SIDEBAR_BACKGROUND} />
<div className="text-sm pb-1">General</div>
<SingleColorPicker displayName={'Walls'} colorName={Colors.WALLS_COLOR} />
<SingleColorPicker displayName={'Tiles'} colorName={Colors.TILE_COLOR} />
<div className="text-sm pb-1">Silver</div>
<SingleColorPicker displayName={'Text'} colorName={Colors.TEAM_ONE} />
<SingleColorPicker displayName={'Primary Paint'} colorName={Colors.PAINT_TEAMONE_ONE} />
<SingleColorPicker displayName={'Secondary Paint'} colorName={Colors.PAINT_TEAMONE_TWO} />
<div className="text-sm pb-1">Gold</div>
<SingleColorPicker displayName={'Text'} colorName={Colors.TEAM_TWO} />
<SingleColorPicker displayName={'Primary Paint'} colorName={Colors.PAINT_TEAMTWO_ONE} />
<SingleColorPicker displayName={'Secondary Paint'} colorName={Colors.PAINT_TEAMTWO_TWO} />
</div>
<div className="flex flex-row mt-8">
<BrightButton
className=""
onClick={() => {
resetGlobalColors()
context.setState((prevState) => ({
...prevState,
config: { ...prevState.config, colors: { ...DEFAULT_GLOBAL_COLORS } }
}))
}}
>
Reset Colors
</BrightButton>
</div>
</>
)
}
const SingleColorPicker = (props: { displayName: string; colorName: Colors }) => {
const context = useAppContext()
const value = context.state.config.colors[props.colorName]
const ref = useRef<HTMLDivElement>(null)
const buttonRef = useRef<HTMLButtonElement>(null)
const [hoveredClose, setHoveredClose] = useState(false)
const [displayColorPicker, setDisplayColorPicker] = useState(false)
const handleClick = () => {
setDisplayColorPicker(!displayColorPicker)
}
const handleClose = () => {
setDisplayColorPicker(false)
}
const handleClickOutside = (event: any) => {
if (
ref.current &&
buttonRef.current &&
!ref.current.contains(event.target) &&
!buttonRef.current.contains(event.target)
) {
handleClose()
}
}
const onChange = (newColor: any) => {
updateGlobalColor(props.colorName, newColor.hex)
context.setState((prevState) => ({
...prevState,
config: { ...prevState.config, colors: { ...prevState.config.colors, [props.colorName]: newColor.hex } }
}))
// hopefully after the setState is done
setTimeout(() => GameRenderer.render(), 10)
}
const resetColor = () => {
onChange({ hex: DEFAULT_GLOBAL_COLORS[props.colorName as Colors] })
}
useEffect(() => {
window.addEventListener('mousedown', handleClickOutside)
return () => window.removeEventListener('mousedown', handleClickOutside)
}, [])
return (
<>
<div className={'ml-2 mb-2 text-xs flex flex-start justify-start items-center'}>
{/*Background:*/}
{props.displayName}:
<button
ref={buttonRef}
className={'text-xs ml-2 px-4 py-3 mr-2 flex flex-row hover:bg-cyanDark rounded-md text-white'}
style={{ backgroundColor: value, border: '2px solid white' }}
onClick={handleClick}
></button>
<div
className="rounded-full overflow-clip"
onClick={() => resetColor()}
onMouseEnter={() => setHoveredClose(true)}
onMouseLeave={() => setHoveredClose(false)}
>
<IconContext.Provider
value={{
color: 'white',
className: 'w-5 h-5'
}}
>
{hoveredClose ? <IoCloseCircle /> : <IoCloseCircleOutline />}
</IconContext.Provider>
</div>
</div>
<div ref={ref} className={'width: w-min'}>
{displayColorPicker && <ChromePicker color={value} onChange={onChange} />}
</div>
</>
)
}
const ConfigCategoryDropdown: React.FC<{
title: string
keys: Array<keyof ClientConfig>
forceOpen?: boolean
hasInput?: boolean
}> = ({ title, keys, forceOpen, hasInput }) => {
const [open, setOpen] = useState<boolean>(false)
useEffect(() => {
if (forceOpen) {
setOpen(true)
} else if (!hasInput) {
setOpen(false)
}
}, [forceOpen, hasInput])
const onClick = () => {
setOpen(!open)
}
return (
<div className="mb-3">
<SectionHeader title={title} open={open} onClick={onClick} children={<div></div>}></SectionHeader>
{open && (
<div className=" px-3 py-2">
{keys.map((key) => {
const value = DEFAULT_CONFIG[key]
if (typeof value === 'boolean') return <ConfigBooleanElement configKey={key} key={key} />
if (typeof value === 'number') return <ConfigNumberElement configKey={key} key={key} />
if (typeof value === 'string') return <ConfigStringElement configKey={key} key={key} />
return null
})}
</div>
)}
</div>
)
}
const ConfigBooleanElement: React.FC<{ configKey: keyof ClientConfig }> = ({ configKey }) => {
const context = useAppContext()
const value = context.state.config[configKey] as boolean
return (
<div className={'flex flex-row items-center mb-2'}>
<input
type={'checkbox'}
checked={value as any}
onChange={(e) => context.updateConfigValue(configKey, e.target.checked)}
/>
<div className={'ml-2 text-xs'}>{configDescription[configKey] ?? configKey}</div>
</div>
)
}
const ConfigStringElement: React.FC<{ configKey: string }> = ({ configKey }) => {
const context = useAppContext()
const value = context.state.config[configKey as keyof ClientConfig]
return <div className={'flex flex-row items-center'}>Todo</div>
}
const ConfigNumberElement: React.FC<{ configKey: keyof ClientConfig }> = ({ configKey }) => {
const context = useAppContext()
const value = context.state.config[configKey as keyof ClientConfig] as number
return (
<div className={'flex flex-row items-center mb-2'}>
<NumInput
value={value}
changeValue={(newVal) => {
context.updateConfigValue(configKey, newVal)
if (configKey === 'resolutionScale') {
// Trigger canvas dimension update to ensure resolution is updated
GameRenderer.onMatchChange()
}
}}
min={10}
max={200}
/>
<div className={'ml-2 text-xs'}>{configDescription[configKey] ?? configKey}</div>
</div>
)
}