document.addEventListener('DOMContentLoaded', function () {
const predictBtn = document.getElementById('predict-btn');
const taskInfo = document.getElementById('task-info');
// 示例路径,可以根据实际路由情况调整
const taskStatusUrl = "/task_status";
const handleRequestUrl = "/handle_alphafold_request";
const deleteTaskUrl = "/delete_task";
const getPdbUrl = "/get_pdb_url";
const showPdbUrl = "/show_pdb";
// 页面加载时获取当前任务状态
fetchTaskStatus();
document.getElementById('alphafold-form').addEventListener('submit', function (event) {
event.preventDefault(); // Prevent default form submission
// 检查 jobid 输入是否合法
const jobid = document.getElementById('jobid').value;
if (!jobid) {
alert('Job ID 不能为空。');
return;
}
// Create FormData object
const formData = new FormData(this);
// Disable button and change style
togglePredictButton(true);
// Trigger AJAX request
ajaxRequest(handleRequestUrl, 'POST', formData, false, false)
.then(data => {
const { jobid, status } = data;
addTaskStatus(jobid, 'pending');
togglePredictButton(false);
})
.catch(xhr => {
handleAjaxError(xhr, 'Error during prediction');
togglePredictButton(false);
});
});
function togglePredictButton(disable) {
predictBtn.disabled = disable;
predictBtn.classList.toggle('bg-gray-400', disable);
predictBtn.textContent = disable ? 'Predicting...' : 'Start';
}
function addTaskStatus(jobid, status) {
const statusClass = getStatusClass(status);
const taskHtml = `
<div class="flex items-center justify-between task-item mb-0.5 p-1 text-xs border border-gray-200 shadow-sm hover:bg-gray-100 transition duration-300 ease-in-out" id="task-${jobid}" data-jobid="${jobid}">
<p class="font-medium text-gray-700 flex-shrink-0 w-24 overflow-hidden whitespace-nowrap text-ellipsis"><span class="font-semibold">${jobid}</span></p>
<p class="flex-grow text-center"><span id="status-${jobid}" class="task-status ${statusClass}">${status}</span></p>
<div class="flex space-x-2">
<a id="download-btn-${jobid}" href="#" class="download-task-btn bg-green-500 text-white px-2 rounded hover:bg-green-700 transition-colors hidden" data-jobid="${jobid}">↓</a>
<button class="delete-task-btn bg-red-500 text-white px-2 rounded hover:bg-red-700 transition-colors" data-jobid="${jobid}">-</button>
</div>
</div>
`;
taskInfo.insertAdjacentHTML('beforeend', taskHtml);
updateTaskClickability(jobid, status);
bindDeleteTaskButton(jobid);
}
function updateTaskStatus(jobid, status) {
const statusClass = getStatusClass(status);
document.getElementById(`status-${jobid}`).className = `task-status ${statusClass}`;
document.getElementById(`status-${jobid}`).textContent = status;
updateTaskClickability(jobid, status);
}
function getStatusClass(status) {
switch (status) {
case 'completed':
return 'bg-green-100 text-green-800 px-2 py-0.5 rounded';
case 'pending':
return 'bg-yellow-100 text-yellow-800 px-2 py-0.5 rounded';
case 'failed':
return 'bg-red-100 text-red-800 px-2 py-0.5 rounded';
case 'running':
return 'bg-blue-100 text-blue-800 px-2 py-0.5 rounded';
default:
return '';
}
}
function updateTaskClickability(jobid, status) {
const taskItem = document.getElementById(`task-${jobid}`);
const downloadBtn = document.getElementById(`download-btn-${jobid}`);
taskItem.removeEventListener('click', fetchPdbData); // remove existing event listeners
if (status === 'completed') {
taskItem.classList.add('hover:bg-gray-100');
taskItem.addEventListener('click', () => fetchPdbData(jobid));
downloadBtn.classList.remove('hidden'); // 显示下载按钮
setupDownloadButton(jobid); // 设置下载按钮
} else {
taskItem.classList.remove('hover:bg-gray-100');
taskItem.removeEventListener('click', fetchPdbData);
downloadBtn.classList.add('hidden'); // 隐藏下载按钮
}
}
function fetchTaskStatus() {
ajaxRequest(taskStatusUrl, 'GET')
.then(data => {
for (const jobid in data) {
const status = data[jobid]['status'];
if (document.getElementById(`task-${jobid}`)) {
updateTaskStatus(jobid, status);
} else {
addTaskStatus(jobid, status);
}
}
});
}
function bindDeleteTaskButton(jobid) {
document.querySelector(`#task-${jobid} .delete-task-btn`).addEventListener('click', function () {
deleteTask(jobid);
});
}
function deleteTask(jobid) {
ajaxRequest(deleteTaskUrl, 'POST', { jobid })
.then(() => {
document.getElementById(`task-${jobid}`).remove();
})
.catch(xhr => {
handleAjaxError(xhr, 'Error deleting task');
});
}
function setupDownloadButton(jobid) {
ajaxRequest(getPdbUrl, 'GET', { jobid })
.then(data => {
const { pdb_url } = data;
const downloadBtn = document.getElementById(`download-btn-${jobid}`);
downloadBtn.setAttribute('href', pdb_url);
downloadBtn.classList.remove('hidden');
downloadBtn.addEventListener('click', (event) => {
event.stopPropagation(); // prevent event bubbling
});
})
.catch(xhr => {
console.error('Error fetching PDB URL:', xhr);
});
}
function fetchPdbData(jobid) {
showLoadingMessage();
ajaxRequest(showPdbUrl, 'GET', { jobid })
.then(data => {
displayPredictionResults(data, jobid);
hideLoadingMessage();
})
.catch(xhr => {
console.error('Error fetching PDB data:', xhr);
hideLoadingMessage();
});
}
function ajaxRequest(url, type, data = {}, processData = true, contentType = 'application/x-www-form-urlencoded') {
return $.ajax({
url,
type,
data: data instanceof FormData ? data : JSON.stringify(data),
processData,
contentType: data instanceof FormData ? false : 'application/json',
});
}
function handleAjaxError(xhr, defaultMessage) {
let errorMessage = defaultMessage;
if (xhr.responseJSON && xhr.responseJSON.error) {
errorMessage += `: ${xhr.responseJSON.error}`;
}
alert(errorMessage);
}
// 定期轮询任务状态
setInterval(fetchTaskStatus, 60000);
function displayPredictionResults(data, jobid) {
const { pdb_url, color_scheme, pae_array } = data;
// 清除之前的 NGL Stage
if (window.stage) {
window.stage.removeAllComponents();
} else {
window.stage = new NGL.Stage("ngl-viewer", { backgroundColor: "white" });
}
// 创建基于选择的着色方案
const colorScheme = color_scheme.map(scheme => [scheme[0], scheme[1]]);
colorScheme.push(["gray", "*"]); // 默认颜色为灰色
const schemeId = NGL.ColormakerRegistry.addSelectionScheme(colorScheme, "Custom Color Scheme");
window.stage.loadFile(pdb_url).then(component => {
component.addRepresentation("cartoon", { color: schemeId });
component.autoView();
}).catch(error => {
console.error('Error loading PDB file:', error);
});
// 全屏按钮事件处理程序
document.getElementById("fullscreen-btn").addEventListener("click", () => {
window.stage.toggleFullscreen();
});
// 如果存在 PAE 数组,则显示 PAE 图
if (pae_array) {
const data = [{
z: pae_array,
type: 'heatmap',
colorscale: 'Greens'
}];
// 获取容器的宽度和高度
const container = document.getElementById('pae-viewer');
container.innerHTML = ''; // 清空容器内容
const containerWidth = container.clientWidth;
const containerHeight = container.clientHeight;
// 计算最小值作为正方形的边长
const size = Math.min(containerWidth, containerHeight);
const layout = {
title: 'Predicted Aligned Error',
xaxis: { title: 'Scored Residue' },
yaxis: { title: 'Aligned Residue', autorange: 'reversed' },
autosize: false,
width: size,
height: size,
};
const config = {
displayModeBar: false // 隐藏 mode bar
};
Plotly.newPlot('pae-viewer', data, layout, config);
} else {
const container = document.getElementById('pae-viewer');
container.innerHTML = '<p class="text-center text-gray-500">No PAE data available.</p>';
}
}
function showLoadingMessage() {
document.getElementById('loading-message').classList.remove('hidden');
}
function hideLoadingMessage() {
document.getElementById('loading-message').classList.add('hidden');
}
});