Files
screw-bardo/website/static/script.js
2024-10-15 20:45:01 -04:00

81 lines
2.8 KiB
JavaScript

document.addEventListener("DOMContentLoaded", (event) => {
const response_area = document.getElementById('response-area');
const submit_button = document.getElementById('submit')
submit_button.addEventListener('click', function() {
var url = document.getElementById('url_box').value;
if (!url) {
response_area.innerText = 'Please enter a URL.';
return;
}
else {
document.getElementById('url_box').value = "";
}
// First, process the URL
fetch('/process_url', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams({ url: url })
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
// Extract the text from the response body
return response.text(); // Use .json() if the response is JSON
})
.then(text => {
submit_button.style.display = "none";
if (text === "Processing started. Check /stream_output for updates.") {
streamOutput(response_area);
} else {
response_area.innerText = text; // Show any other response message
submit_button.style.display = "flex";
}
})
.catch(error => {
console.error('Error processing URL:', error);
response_area.innerText = 'Error processing URL: ' + error.message;
submit_button.style.display = "flex";
});
});
});
function streamOutput(response_area) {
// Fetch the streaming output
const streamResponsePromise = fetch('/stream_output');
response_area.innerHTML = ""
streamResponsePromise
.then(response => {
const reader = response.body.getReader();
const decoder = new TextDecoder("utf-8");
function readStream() {
reader.read().then(({ done, value }) => {
if(done) {
document.getElementById('submit').style.display = "flex";
return
}
// Decode and process the chunk
const chunk = decoder.decode(value, { stream: true });
response_area.innerHTML += chunk;
response_area.scrollTop = response_area.scrollHeight
// Continue reading
readStream();
});
}
// Start reading the stream
readStream();
})
.catch(error => {
console.error('Error fetching stream:', error);
response_area.innerText = 'Error fetching stream: ' + error.message;
});
}