refactor(client): ♻️ move handlers at the top of the document

This commit is contained in:
Julien Oculi 2024-06-25 13:19:07 +02:00
parent 0fdbeaf258
commit 61cc89e48c

View file

@ -65,6 +65,46 @@
</p>
</body>
<script type="module">
// Input handlers
document
.querySelector('move-input')
.addEventListener('change', (event) =>
assignCommands('backward', 'forward', event)
)
document
.querySelector('rotate-input')
.addEventListener('change', (event) =>
assignCommands('left', 'right', event)
)
// Keyboard handler
document.addEventListener('keydown', (event) => {
const key = event.keyCode
const { command, value } = keyMap[key]
const endpoint = getEndpoint()
sendCommand(endpoint, command, value)
})
// Settings handler
document
.querySelector('#settings')
.addEventListener('submit', async (event) => {
// Don't interrupt event if not form submitting
if (!(event instanceof SubmitEvent)) return true
if (event.target === null) return true
// Disable form sending
event.preventDefault()
const form = new FormData(event.target)
const ipAddress = form.get('ip-address')
if (ipAddress === null) return
const endpoint = `http://${ipAddress}`
await testEndpoint(endpoint)
setEndpoint(endpoint)
})
/**
* A command string.
* @typedef {('forward' | 'backward' | 'left' | 'right' | 'stop')} Command
@ -114,25 +154,6 @@
sessionStorage.setItem('robot-endpoint')
}
document
.querySelector('#settings')
.addEventListener('submit', async (event) => {
// Don't interrupt event if not form submitting
if (!(event instanceof SubmitEvent)) return true
if (event.target === null) return true
// Disable form sending
event.preventDefault()
const form = new FormData(event.target)
const ipAddress = form.get('ip-address')
if (ipAddress === null) return
const endpoint = `http://${ipAddress}`
await testEndpoint(endpoint)
setEndpoint(endpoint)
})
/**
* Test connection to endpoint.
*
@ -153,17 +174,6 @@
}
}
document
.querySelector('move-input')
.addEventListener('change', (event) =>
assignCommands('backward', 'forward', event)
)
document
.querySelector('rotate-input')
.addEventListener('change', (event) =>
assignCommands('left', 'right', event)
)
/**
* Assign a command to an input.
* Do negative command if value < 0 else do positive command.
@ -188,13 +198,6 @@
return sendCommand(endpoint, positiveCommand, value)
}
document.addEventListener('keydown', (event) => {
const key = event.keyCode
const { command, value } = keyMap[key]
const endpoint = getEndpoint()
sendCommand(endpoint, command, value)
})
function storeInput() {
ipInput = document.getElementById('ip').value
valueRot = document.getElementById('valueRot').value