## Use case Environment toggle buttons get a red border when the environment pipeline contains a failed or unfinished step. The state updates with WebSocket environment updates and does not disable the toggle. ## Verification - `node --check frontend/app.js` - `git diff --check` - `27 passed, 1 skipped`; 4 Playwright tests blocked by unavailable `/var/run/docker.sock` --------- Co-authored-by: rudolf <rudolfss13@gmail.com> Reviewed-on: #82 Co-authored-by: hermes <rudolfss13+hermes@gmail.com>
601 lines
27 KiB
JavaScript
601 lines
27 KiB
JavaScript
// Placeholder for frontend JS logic
|
|
// You can add your Socket.IO and UI code here
|
|
console.log('app.js loaded');
|
|
|
|
// WebSocket endpoint
|
|
const WS_URL = '/ws';
|
|
|
|
// DOM refs
|
|
const branchesList = document.getElementById('branches-list');
|
|
const statusBar = document.getElementById('status-bar');
|
|
const statusMessage = document.getElementById('status-message');
|
|
const closeStatus = document.getElementById('close-status');
|
|
const refreshBranchesBtn = document.getElementById('refresh-branches');
|
|
const applyChangesBtn = document.getElementById('apply-changes');
|
|
const branchFilter = document.getElementById('branch-filter');
|
|
const envFilterToggles = document.getElementById('env-filter-toggles');
|
|
const appVersion = document.getElementById('app-version');
|
|
|
|
// Branches list (flattened) for UI rendering: [{ envId, envName, branch, commits: [] }]
|
|
let branches = [];
|
|
let filteredBranches = [];
|
|
|
|
// Toggle state: show all branches or filtered
|
|
let showAllBranches = false;
|
|
const activeEnvFilters = new Set();
|
|
|
|
// Environment runtime state storage:
|
|
// environmentsRaw: array as received from backend: [ [envObj, jobsArr], ... ]
|
|
let environmentsRaw = [];
|
|
|
|
// Per-environment maps
|
|
// selectedBranchesByEnv: envId -> Array<[branch, desiredCommit]>
|
|
const selectedBranchesByEnv = {};
|
|
// serverSelectedBranchesByEnv mirrors server's last known selection for diffing
|
|
const serverSelectedBranchesByEnv = {};
|
|
// serverTokenByEnv tracks current optimistic concurrency token per environment
|
|
const serverTokenByEnv = {};
|
|
// columnsByEnv: envId -> { columnName: { branchName: value } }
|
|
// Populated from any step result that contains a `columns` key (e.g. GitUnmerge)
|
|
const columnsByEnv = {};
|
|
|
|
// Per-environment dry run state: envId -> bool
|
|
const dryRunByEnv = {};
|
|
|
|
// Single WebSocket connection
|
|
let ws = null;
|
|
|
|
function showStatus(message, isError = false) {
|
|
statusMessage.textContent = message;
|
|
statusBar.classList.remove('hidden');
|
|
statusBar.style.background = isError ? '#f8d7da' : '#e9ecef';
|
|
statusMessage.style.color = isError ? '#721c24' : '#333';
|
|
}
|
|
|
|
closeStatus.onclick = () => statusBar.classList.add('hidden');
|
|
|
|
function isChangesPending() {
|
|
// Determine if any environment has changed selections
|
|
return Object.keys(selectedBranchesByEnv).some(envId => {
|
|
const localSel = [...(selectedBranchesByEnv[envId] || [])].sort();
|
|
const serverSel = [...(serverSelectedBranchesByEnv[envId] || [])].sort();
|
|
return JSON.stringify(localSel) !== JSON.stringify(serverSel);
|
|
});
|
|
}
|
|
function checkForPendingChanges() {
|
|
if (isChangesPending()) applyChangesBtn.classList.remove('hidden');
|
|
else applyChangesBtn.classList.add('hidden');
|
|
}
|
|
|
|
function filterBranches() {
|
|
const filterText = branchFilter.value.toLowerCase().trim();
|
|
filteredBranches = branches.filter(({envId, branch, commits}) => {
|
|
if (activeEnvFilters.size > 0 && !activeEnvFilters.has(envId)) return false;
|
|
const selList = selectedBranchesByEnv[envId] || [];
|
|
const isSelected = selList.some(([b]) => b === branch);
|
|
// Always show branches that appear in any column (e.g. deployed branches from GitUnmerge)
|
|
const envCols = columnsByEnv[envId] || {};
|
|
const isInColumns = Object.values(envCols).some(colData => branch in colData);
|
|
const isFiltered = !!filterText && branch.toLowerCase().includes(filterText);
|
|
const isFilteredByCommit = !!filterText && Array.isArray(commits) && commits.some(c => {
|
|
const shortHash = c.hexsha ? c.hexsha.substring(0, 8).toLowerCase() : '';
|
|
return (c.hexsha && c.hexsha.toLowerCase().includes(filterText)) ||
|
|
shortHash.includes(filterText) ||
|
|
(c.message && c.message.toLowerCase().includes(filterText)) ||
|
|
(c.author && c.author.toLowerCase().includes(filterText));
|
|
});
|
|
return showAllBranches || isSelected || isInColumns || isFiltered || isFilteredByCommit;
|
|
});
|
|
renderBranches();
|
|
}
|
|
|
|
function environmentHasPipelineProblem(envObj) {
|
|
return Array.isArray(envObj.pipeline) && envObj.pipeline.some(job =>
|
|
job && (job.error || job.is_running)
|
|
);
|
|
}
|
|
|
|
function renderEnvironmentFilters() {
|
|
const environments = environmentsRaw
|
|
.filter(envObj => envObj && (envObj.id || envObj.name))
|
|
.map(envObj => ({id: envObj.id || envObj.name, name: envObj.name || envObj.id}))
|
|
.sort((a, b) => a.name.localeCompare(b.name));
|
|
const environmentIds = new Set(environments.map(env => env.id));
|
|
[...activeEnvFilters].forEach(envId => {
|
|
if (!environmentIds.has(envId)) activeEnvFilters.delete(envId);
|
|
});
|
|
envFilterToggles.innerHTML = environments.map(({id, name}) => {
|
|
const hasPipelineProblem = environmentHasPipelineProblem(
|
|
environmentsRaw.find(envObj => (envObj.id || envObj.name) === id) || {}
|
|
);
|
|
return `
|
|
<button type="button" class="env-filter-toggle${activeEnvFilters.has(id) ? ' active' : ''}${hasPipelineProblem ? ' has-pipeline-problem' : ''}" data-env="${escapeHtml(id)}" aria-pressed="${activeEnvFilters.has(id)}"${hasPipelineProblem ? ' title="Pipeline has failed or unfinished steps"' : ''}>${escapeHtml(name)}</button>
|
|
`;
|
|
}).join('');
|
|
envFilterToggles.querySelectorAll('.env-filter-toggle').forEach(button => {
|
|
button.onclick = () => {
|
|
const envId = button.dataset.env;
|
|
if (activeEnvFilters.has(envId)) activeEnvFilters.delete(envId);
|
|
else activeEnvFilters.add(envId);
|
|
renderEnvironmentFilters();
|
|
filterBranches();
|
|
renderJobs();
|
|
};
|
|
});
|
|
}
|
|
|
|
function getCommitDropdownOptions(envId, branchName, desiredCommit) {
|
|
const branchObj = branches.find(b => b.envId === envId && b.branch === branchName);
|
|
let options = '';
|
|
const commits = branchObj && Array.isArray(branchObj.commits) ? branchObj.commits : [];
|
|
|
|
if (commits.length) {
|
|
const head = commits[0];
|
|
const headShort = head.hexsha ? head.hexsha.substring(0, 8) : '';
|
|
const headMsg = escapeHtml(head.message || '');
|
|
options += `<option value="HEAD" ${desiredCommit === 'HEAD' ? 'selected' : ''}>HEAD (${headShort} - ${(head.author || '').substring(0, 25)} - ${headMsg ? headMsg.substring(0, 50) + (headMsg.length > 50 ? '...' : '') : ''})</option>`;
|
|
commits.forEach(c => {
|
|
const full = c.hexsha;
|
|
const shortHash = full ? full.substring(0, 8) : '';
|
|
const isSelected = desiredCommit === full || desiredCommit === shortHash;
|
|
const cMsg = escapeHtml(c.message || '');
|
|
options += `<option value="${full}" ${isSelected ? 'selected' : ''}>${shortHash} - ${(c.author || '').substring(0, 25)} - ${cMsg ? cMsg.substring(0, 50) + (cMsg.length > 50 ? '...' : '') : ''}</option>`;
|
|
});
|
|
} else {
|
|
options += `<option value="HEAD" ${desiredCommit === 'HEAD' ? 'selected' : ''}>HEAD (no commits)</option>`;
|
|
}
|
|
|
|
const hasMatch = commits.some(c => {
|
|
const full = c.hexsha;
|
|
const shortHash = full ? full.substring(0, 8) : '';
|
|
return desiredCommit === full || desiredCommit === shortHash || desiredCommit === 'HEAD';
|
|
});
|
|
const isCustom = desiredCommit && desiredCommit !== 'HEAD' && !hasMatch;
|
|
options += `<option value="custom" ${isCustom ? 'selected' : ''}>Custom Commit</option>`;
|
|
return options;
|
|
}
|
|
|
|
function branchHasCommit(envId, branchName, commit) {
|
|
if (commit === 'HEAD') return true;
|
|
const branchObj = branches.find(b => b.envId === envId && b.branch === branchName);
|
|
if (!branchObj) return false;
|
|
return branchObj.commits?.some(c => {
|
|
const full = c.hexsha;
|
|
const shortHash = full ? full.substring(0, 8) : '';
|
|
return commit === full || commit === shortHash;
|
|
}) || false;
|
|
}
|
|
|
|
function escapeHtml(str) {
|
|
return String(str)
|
|
.replace(/&/g, '&')
|
|
.replace(/</g, '<')
|
|
.replace(/>/g, '>')
|
|
.replace(/"/g, '"')
|
|
.replace(/'/g, ''');
|
|
}
|
|
|
|
let renderedBranches = []
|
|
let renderedDryRunState = {}
|
|
let renderedColumnsSignature = ''
|
|
|
|
function getColumnsSignature() {
|
|
return JSON.stringify(columnsByEnv);
|
|
}
|
|
|
|
function renderBranches() {
|
|
const columnsSignature = getColumnsSignature();
|
|
if (
|
|
JSON.stringify(filteredBranches) === JSON.stringify(renderedBranches) &&
|
|
JSON.stringify(dryRunByEnv) === JSON.stringify(renderedDryRunState) &&
|
|
columnsSignature === renderedColumnsSignature
|
|
) {
|
|
return
|
|
}
|
|
checkForPendingChanges();
|
|
|
|
const branchesToShow = filteredBranches.length > 0 || branchFilter.value.trim() || activeEnvFilters.size > 0 ? filteredBranches : branches;
|
|
// Group by envId for clearer separation
|
|
const groups = branchesToShow.reduce((acc, b) => {
|
|
acc[b.envId] = acc[b.envId] || {envName: b.envName, rows: []};
|
|
acc[b.envId].rows.push(b);
|
|
return acc;
|
|
}, {});
|
|
|
|
environmentsRaw
|
|
.filter(envObj => envObj && (activeEnvFilters.size === 0 || activeEnvFilters.has(envObj.id || envObj.name)))
|
|
.forEach(envObj => {
|
|
const envId = envObj.id || envObj.name;
|
|
if (!groups[envId]) groups[envId] = {envName: envObj.name || envId, rows: []};
|
|
});
|
|
|
|
if (!Object.keys(groups).length) {
|
|
branchesList.innerHTML = '<p class="loading">No branches found.</p>';
|
|
return;
|
|
}
|
|
|
|
branchesList.innerHTML = Object.entries(groups).map(([envId, {envName, rows}]) => {
|
|
const envCols = columnsByEnv[envId] || {};
|
|
const colNames = Object.keys(envCols);
|
|
return `
|
|
<div class="env-block">
|
|
<h3 class="env-title">
|
|
Environment: ${escapeHtml(envName || envId)}
|
|
<button class="dry-run-btn ${dryRunByEnv[envId] ? 'dry-run-active' : ''}" data-env="${envId}" title="${dryRunByEnv[envId] ? 'Dry run on — click to resume' : 'Running — click to pause (dry run)'}">
|
|
${dryRunByEnv[envId] ? '▶' : '⏸'}
|
|
</button>
|
|
</h3>
|
|
${rows.length ? `<table class="branches-table">
|
|
<thead>
|
|
<tr>
|
|
<th>Deploy</th>
|
|
<th>Branch</th>
|
|
<th>Desired Commit</th>
|
|
${colNames.map(n => `<th>${escapeHtml(n)}</th>`).join('')}
|
|
</tr>
|
|
</thead>
|
|
<tbody>
|
|
${rows.map(({envId: eId, branch}) => {
|
|
const selList = selectedBranchesByEnv[eId] || [];
|
|
const pair = selList.find(([b]) => b === branch);
|
|
const desiredCommit = pair ? pair[1] : 'HEAD';
|
|
const hasCommit = branchHasCommit(eId, branch, desiredCommit);
|
|
return `
|
|
<tr class="branch-row" data-env="${eId}" data-branch="${branch}">
|
|
<td><input type="checkbox" value="${branch}" data-env="${eId}" ${pair ? 'checked' : ''}></td>
|
|
<td>${branch}</td>
|
|
<td>
|
|
<select class="desired-commit" data-branch="${branch}" data-env="${eId}">
|
|
${getCommitDropdownOptions(eId, branch, desiredCommit)}
|
|
</select>
|
|
<input type="text" class="commit-input" data-branch="${branch}" data-env="${eId}"
|
|
value="${desiredCommit !== 'HEAD' && !hasCommit ? desiredCommit : ''}"
|
|
placeholder="Enter commit ID" style="display: ${desiredCommit !== 'HEAD' && !hasCommit ? 'inline-block' : 'none'};" />
|
|
</td>
|
|
${colNames.map(n => `<td>${escapeHtml((envCols[n] && envCols[n][branch]) || '')}</td>`).join('')}
|
|
</tr>`;
|
|
}).join('')}
|
|
</tbody>
|
|
</table>` : '<p class="loading">No branches found.</p>'}
|
|
</div>`;
|
|
}).join('');
|
|
// Event wiring
|
|
branchesList.querySelectorAll('input[type="checkbox"]').forEach(cb => {
|
|
cb.onchange = e => {
|
|
const branch = e.target.value;
|
|
const envId = e.target.dataset.env;
|
|
selectedBranchesByEnv[envId] = selectedBranchesByEnv[envId] || [];
|
|
if (e.target.checked) {
|
|
if (!selectedBranchesByEnv[envId].some(([b]) => b === branch)) {
|
|
selectedBranchesByEnv[envId].push([branch, 'HEAD']);
|
|
}
|
|
} else {
|
|
selectedBranchesByEnv[envId] = selectedBranchesByEnv[envId].filter(([b]) => b !== branch);
|
|
}
|
|
checkForPendingChanges();
|
|
};
|
|
});
|
|
branchesList.querySelectorAll('.desired-commit').forEach(sel => {
|
|
sel.onchange = e => {
|
|
const branch = e.target.dataset.branch;
|
|
const envId = e.target.dataset.env;
|
|
const commitInput = branchesList.querySelector(`.commit-input[data-env="${envId}"][data-branch="${branch}"]`);
|
|
if (e.target.value === 'custom') {
|
|
commitInput.style.display = 'inline-block';
|
|
commitInput.focus();
|
|
} else if (e.target.value === 'HEAD') {
|
|
commitInput.style.display = 'none';
|
|
updateBranchCommit(envId, branch, 'HEAD');
|
|
} else {
|
|
commitInput.style.display = 'none';
|
|
updateBranchCommit(envId, branch, e.target.value);
|
|
}
|
|
};
|
|
});
|
|
branchesList.querySelectorAll('.commit-input').forEach(input => {
|
|
input.onchange = input.onblur = e => {
|
|
const branch = e.target.dataset.branch;
|
|
const envId = e.target.dataset.env;
|
|
const commitId = e.target.value.trim();
|
|
updateBranchCommit(envId, branch, commitId || 'HEAD');
|
|
};
|
|
});
|
|
branchesList.querySelectorAll('.dry-run-btn').forEach(btn => {
|
|
btn.onclick = e => {
|
|
const envId = e.currentTarget.dataset.env;
|
|
if (ws && ws.readyState === WebSocket.OPEN) {
|
|
ws.send(JSON.stringify({ update: { id: envId, dry: !dryRunByEnv[envId], token: serverTokenByEnv[envId] } }));
|
|
}
|
|
filterBranches();
|
|
};
|
|
});
|
|
renderedBranches = [...filteredBranches];
|
|
renderedDryRunState = {...dryRunByEnv};
|
|
renderedColumnsSignature = columnsSignature;
|
|
}
|
|
|
|
function updateBranchCommit(envId, branch, commit) {
|
|
selectedBranchesByEnv[envId] = selectedBranchesByEnv[envId] || [];
|
|
const idx = selectedBranchesByEnv[envId].findIndex(([b]) => b === branch);
|
|
if (idx !== -1) selectedBranchesByEnv[envId][idx] = [branch, commit];
|
|
checkForPendingChanges();
|
|
}
|
|
|
|
function renderJobs() {
|
|
const jobsList = document.getElementById('jobs-list');
|
|
if (!jobsList) return;
|
|
if (!Array.isArray(environmentsRaw) || environmentsRaw.length === 0) {
|
|
jobsList.innerHTML = '<p class="loading">No jobs found.</p>';
|
|
return;
|
|
}
|
|
const visibleEnvironments = environmentsRaw.filter(envObj => activeEnvFilters.size === 0 || activeEnvFilters.has(envObj.id || envObj.name));
|
|
if (visibleEnvironments.length === 0) {
|
|
jobsList.innerHTML = '<p class="loading">No jobs found.</p>';
|
|
return;
|
|
}
|
|
jobsList.innerHTML = visibleEnvironments
|
|
.slice()
|
|
.sort((a, b) => (a.name || a.id || '').localeCompare(b.name || b.id || ''))
|
|
.map((envObj) => {
|
|
var linksHtml = ""
|
|
const jobsArr = envObj.pipeline || [];
|
|
if (Array.isArray(jobsArr)) {
|
|
linksHtml = jobsArr.flatMap(job => {
|
|
const userLinks = [];
|
|
const extractUserLinks = (obj) => {
|
|
if (!obj || typeof obj !== 'object') return;
|
|
if (obj.userLinks && typeof obj.userLinks === 'object') {
|
|
userLinks.push(...Object.entries(obj.userLinks));
|
|
}
|
|
for (const key in obj) {
|
|
if (typeof obj[key] === 'object') {
|
|
extractUserLinks(obj[key]);
|
|
}
|
|
}
|
|
};
|
|
extractUserLinks(job.status);
|
|
return userLinks.map(([title, url]) =>
|
|
`<a href="${url}" target="_blank" rel="noopener noreferrer">${title}</a>`
|
|
)
|
|
})
|
|
.join(' | ');
|
|
}
|
|
|
|
return `
|
|
<div class="env-jobs">
|
|
<h4>Environment: ${envObj.name || envObj.id || ''}</h4>
|
|
${linksHtml ? `<div style="float:right">${linksHtml}</div>` : ''}
|
|
${Array.isArray(jobsArr) && jobsArr.length > 0
|
|
? jobsArr.map(job => {
|
|
let statusDisplay = `<pre>` + JSON.stringify(job.status, null, 2) + `</pre>`;
|
|
statusDisplay = statusDisplay.replace(
|
|
/(https?:\/\/[^\s"']+)/g,
|
|
url => `<a href="${url}" target="_blank" rel="noopener noreferrer">${url}</a>`
|
|
);
|
|
const key = `${envObj.id}::${job.name}`;
|
|
const storageKey = 'jobSpoiler:' + key;
|
|
const safeId = 'spoiler-' + encodeURIComponent(key).replace(/[^a-zA-Z0-9_-]/g, '_');
|
|
const isError = job.error;
|
|
const isWarning = job.warning;
|
|
const isRunning = !!job.is_running;
|
|
const openByDefault = isError || (window._jobSpoilerState && window._jobSpoilerState[storageKey] === 'open');
|
|
|
|
return `
|
|
<div class="job-item">
|
|
<div class="job-header" style="cursor:pointer;font-weight:bold;"
|
|
onclick="toggleJobSpoiler('${key}', '${safeId}')">
|
|
${isRunning
|
|
? `<span class="step-spinner" title="Running"></span>`
|
|
: isError
|
|
? `<span style="color:#dc3545;font-weight:bold;margin-right:6px;" title="Error">!</span>`
|
|
: isWarning
|
|
? `<span style="color:#d99700;font-weight:bold;margin-right:6px;" title="Warning">⚠</span>`
|
|
: `<span style="color:#28a745;font-weight:bold;margin-right:6px;" title="OK">✔</span>`}
|
|
${envObj.id} - ${job.name}
|
|
</div>
|
|
<div id="${safeId}" class="job-spoiler" style="display: ${openByDefault ? 'block' : 'none'}; margin-top:8px;">
|
|
${statusDisplay}
|
|
</div>
|
|
</div>`;
|
|
}).join('')
|
|
: '<div class="job-item">No jobs found.</div>'}
|
|
</div>`;
|
|
}).join('');
|
|
}
|
|
|
|
toggleJobSpoiler = function (key, safeId) {
|
|
try {
|
|
const el = document.getElementById(safeId);
|
|
if (!el) return;
|
|
const storageKey = 'jobSpoiler:' + key;
|
|
const isHidden = window.getComputedStyle(el).display === 'none';
|
|
window._jobSpoilerState = window._jobSpoilerState || {};
|
|
if (isHidden) {
|
|
el.style.display = 'block';
|
|
window._jobSpoilerState[storageKey] = 'open';
|
|
} else {
|
|
el.style.display = 'none';
|
|
window._jobSpoilerState[storageKey] = 'closed';
|
|
}
|
|
} catch (err) {
|
|
console.error('toggleJobSpoiler error', err);
|
|
}
|
|
};
|
|
refreshBranchesBtn.onclick = () => {
|
|
if (ws && ws.readyState === WebSocket.OPEN) {
|
|
ws.send(JSON.stringify({ update: { id: "" } }));
|
|
}
|
|
showStatus('Refreshing...');
|
|
};
|
|
|
|
// Filter event handler
|
|
branchFilter.oninput = () => {
|
|
filterBranches();
|
|
};
|
|
|
|
// Toggle show all button handler
|
|
const toggleShowAllBtn = document.getElementById('toggle-show-all');
|
|
if (toggleShowAllBtn) {
|
|
toggleShowAllBtn.onclick = () => {
|
|
showAllBranches = !showAllBranches;
|
|
toggleShowAllBtn.textContent = showAllBranches ? 'Show Filtered' : 'Show All';
|
|
filterBranches();
|
|
};
|
|
}
|
|
|
|
// Apply changes button handler
|
|
applyChangesBtn.onclick = () => {
|
|
updateEnvironment();
|
|
};
|
|
|
|
// Single WebSocket setup
|
|
function setupWebSockets() {
|
|
// Close existing connection before reconnecting
|
|
if (ws && ws.readyState !== WebSocket.CLOSED) {
|
|
ws.onclose = null; // Prevent recursive reconnect
|
|
ws.close();
|
|
}
|
|
|
|
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
|
|
const host = window.location.host;
|
|
|
|
ws = new WebSocket(`${protocol}//${host}${WS_URL}`);
|
|
ws.onopen = () => console.log('WebSocket connected');
|
|
ws.onmessage = (event) => {
|
|
try {
|
|
const message = JSON.parse(event.data);
|
|
if ('branches' in message) {
|
|
const data = message.branches;
|
|
// data: { envId: { branchName: commits[] } }
|
|
branches = Object.entries(data).flatMap(([envId, branchMap]) =>
|
|
Object.entries(branchMap).map(([branchName, commitList]) => {
|
|
const envObj = (environmentsRaw.find((e) => e.id === envId) || [null])[0];
|
|
return { envId, envName: envObj ? (envObj.name || envObj.id) : envId, branch: branchName, commits: commitList };
|
|
})
|
|
);
|
|
filterBranches();
|
|
showStatus('Branches updated.');
|
|
} else if ('environments' in message) {
|
|
const data = message.environments;
|
|
payload = data || {};
|
|
environmentsRaw = Object.values(payload);
|
|
renderEnvironmentFilters();
|
|
|
|
// Sync selections and column data per environment
|
|
environmentsRaw.forEach((envObj) => {
|
|
if (!envObj) return;
|
|
const envId = envObj.id || envObj.name || 'unknown';
|
|
// Server state is the source of truth for dry-run rendering.
|
|
dryRunByEnv[envId] = !!envObj.dry;
|
|
if (typeof envObj.branches_token === 'string') {
|
|
serverTokenByEnv[envId] = envObj.branches_token;
|
|
}
|
|
if (!isChangesPending()) {
|
|
if (Array.isArray(envObj.branches) && envObj.branches.length > 0) {
|
|
if (Array.isArray(envObj.branches[0])) {
|
|
selectedBranchesByEnv[envId] = [...envObj.branches];
|
|
} else {
|
|
selectedBranchesByEnv[envId] = envObj.branches.map(b => [b, 'HEAD']);
|
|
}
|
|
serverSelectedBranchesByEnv[envId] = [...selectedBranchesByEnv[envId]];
|
|
} else if (!selectedBranchesByEnv[envId]) {
|
|
selectedBranchesByEnv[envId] = [];
|
|
serverSelectedBranchesByEnv[envId] = [];
|
|
}
|
|
}
|
|
// Extract columns from all job statuses
|
|
columnsByEnv[envId] = {};
|
|
const jobsArr = envObj.pipeline || [];
|
|
if (Array.isArray(jobsArr)) {
|
|
jobsArr.forEach(job => {
|
|
if (job.status == null || job.error) return;
|
|
const status = job.status;
|
|
// New structured format: status is an object with a `columns` key
|
|
if (typeof status === 'object' && !Array.isArray(status) && status.columns &&
|
|
typeof status.columns === 'object') {
|
|
Object.entries(status.columns).forEach(([colName, colData]) => {
|
|
if (colData && typeof colData === 'object' && !Array.isArray(colData)) {
|
|
columnsByEnv[envId][colName] = {...colData};
|
|
}
|
|
});
|
|
}
|
|
});
|
|
}
|
|
});
|
|
|
|
// Rebuild branches list environment names for rows already present
|
|
branches = branches.map(b => {
|
|
const envEntry = environmentsRaw.find((e) => (e.id || e.name) === b.envId);
|
|
return { ...b, envName: envEntry ? (envEntry.name || envEntry.id) : b.envName };
|
|
});
|
|
|
|
filterBranches();
|
|
renderJobs();
|
|
showStatus('Environments updated.');
|
|
} else if ('version' in message) {
|
|
appVersion.textContent = `Version: ${message.version || 'unknown'}`;
|
|
} else if ('error' in message) {
|
|
console.error('Error from server:', message.error);
|
|
if (message.error && message.error.code === 'BRANCH_STATE_CONFLICT' && message.error.envId) {
|
|
const envId = message.error.envId;
|
|
const current = message.error.current_state || {};
|
|
const hadLocalSelection = Object.prototype.hasOwnProperty.call(selectedBranchesByEnv, envId);
|
|
if (Array.isArray(current.branches)) {
|
|
serverSelectedBranchesByEnv[envId] = [...current.branches];
|
|
// Preserve the user's pending edits if they already changed selection locally.
|
|
if (!hadLocalSelection) {
|
|
selectedBranchesByEnv[envId] = [...current.branches];
|
|
}
|
|
}
|
|
if (typeof current.token === 'string') {
|
|
serverTokenByEnv[envId] = current.token;
|
|
}
|
|
filterBranches();
|
|
}
|
|
showStatus(message.error.message || 'Unknown error', true);
|
|
}
|
|
checkForPendingChanges();
|
|
} catch (e) {
|
|
console.error('Error processing WebSocket message:', e);
|
|
}
|
|
};
|
|
ws.onclose = () => {
|
|
showStatus('Disconnected from server.', true);
|
|
setTimeout(() => setupWebSockets(), 5000);
|
|
};
|
|
ws.onerror = (error) => {
|
|
console.error('WebSocket error:', error);
|
|
};
|
|
}
|
|
|
|
function updateEnvironment() {
|
|
// Emit updates only for environments whose selection changed
|
|
Object.keys(selectedBranchesByEnv).forEach(envId => {
|
|
const localSel = [...(selectedBranchesByEnv[envId] || [])].sort();
|
|
const serverSel = [...(serverSelectedBranchesByEnv[envId] || [])].sort();
|
|
if (JSON.stringify(localSel) !== JSON.stringify(serverSel)) {
|
|
if (ws && ws.readyState === WebSocket.OPEN) {
|
|
ws.send(JSON.stringify({ update: { id: envId, branches: selectedBranchesByEnv[envId], token: serverTokenByEnv[envId] } }));
|
|
// Keep pending-state tracking aligned with what we just submitted.
|
|
serverSelectedBranchesByEnv[envId] = [...(selectedBranchesByEnv[envId] || [])];
|
|
}
|
|
branchFilter.value = '';
|
|
}
|
|
});
|
|
checkForPendingChanges();
|
|
showStatus('Changes applied (pending server confirmation).');
|
|
}
|
|
// Initial load
|
|
(function applyUrlFilter() {
|
|
const params = new URLSearchParams(window.location.search);
|
|
const initialFilter = params.get('filter');
|
|
if (initialFilter && branchFilter) {
|
|
branchFilter.value = initialFilter;
|
|
filterBranches();
|
|
}
|
|
})();
|
|
setupWebSockets();
|
|
showStatus('Loading branches...');
|
|
renderBranches();
|
|
renderJobs();
|