How to modify this code so it uses data.csv and not the sample: // Application State
let appState = {
rawData: [],
filteredData: [],
currentPage: 1,
itemsPerPage: 50,
totalPages: 0,
activeFilters: {
search: '',
consultancy: '',
tags: new Set(),
sort: 'high-to-low'
},
currentView: 'upload', // 'upload', 'explorer', 'detail'
currentDetailItem: null
};
// Sample data for demonstration
const sampleData = [
{
"Name": "European Tech Alliance",
"Acronym": "ETA",
"Website URL": "https://eurotech-alliance.eu",
"Goals": "Promoting digital innovation and technology adoption across European Union member states through policy advocacy and industry collaboration.",
"EU legislative proposals/policies": "Actively involved in shaping the Digital Services Act, AI Act, and Data Governance Act. Provides expert consultation on emerging technology regulations and standards.",
"Number of EP accredited Person": "12",
"Field of interest": "Digital Policy,Artificial Intelligence,Data Protection,Innovation",
"AI Prediction": "87",
"Annual cost for register activity or total budget": "€2,500,000",
"Have a consultancy": "Yes",
"Name of consultancy": "TechPolicy Consulting Group"
},
{
"Name": "Green Energy Coalition",
"Acronym": "GEC",
"Website URL": "https://green-energy-coalition.org",
"Goals": "Advancing renewable energy adoption and sustainable practices throughout Europe while supporting climate neutrality goals by 2050.",
"EU legislative proposals/policies": "Leading advocate for the European Green Deal implementation, Renewable Energy Directive updates, and carbon border adjustment mechanisms.",
"Number of EP accredited Person": "8",
"Field of interest": "Climate Change,Renewable Energy,Environmental Policy,Sustainability",
"AI Prediction": "92",
"Annual cost for register activity or total budget": "€1,800,000",
"Have a consultancy": "No",
"Name of consultancy": ""
},
{
"Name": "Healthcare Innovation Network",
"Acronym": "HIN",
"Website URL": "https://healthcare-innovation.eu",
"Goals": "Improving healthcare delivery through digital transformation, medical device innovation, and cross-border healthcare coordination.",
"EU legislative proposals/policies": "Contributing to Medical Device Regulation implementation, European Health Data Space development, and pharmaceutical strategy initiatives.",
"Number of EP accredited Person": "15",
"Field of interest": "Healthcare,Digital Health,Medical Devices,Pharmaceuticals",
"AI Prediction": "78",
"Annual cost for register activity or total budget": "€3,200,000",
"Have a consultancy": "Yes",
"Name of consultancy": "HealthTech Advisory Services"
},
{
"Name": "Financial Services Forum",
"Acronym": "FSF",
"Website URL": "https://financial-services-forum.eu",
"Goals": "Ensuring stable and innovative financial markets while protecting consumer interests and promoting financial inclusion across the EU.",
"EU legislative proposals/policies": "Engaged in MiCA regulation development, Digital Finance Strategy, and Banking Union completion discussions.",
"Number of EP accredited Person": "20",
"Field of interest": "Financial Services,Digital Currency,Banking,Consumer Protection",
"AI Prediction": "85",
"Annual cost for register activity or total budget": "€4,100,000",
"Have a consultancy": "Yes",
"Name of consultancy": "FinTech Policy Solutions"
},
{
"Name": "Agricultural Sustainability Network",
"Acronym": "ASN",
"Website URL": "https://agri-sustainability.eu",
"Goals": "Supporting sustainable agriculture practices, food security, and rural development while adapting to climate change challenges.",
"EU legislative proposals/policies": "Active in Common Agricultural Policy reform, Farm to Fork Strategy implementation, and sustainable agriculture transition support.",
"Number of EP accredited Person": "6",
"Field of interest": "Agriculture,Food Security,Rural Development,Climate Adaptation",
"AI Prediction": "74",
"Annual cost for register activity or total budget": "€1,200,000",
"Have a consultancy": "No",
"Name of consultancy": ""
}
];
// Cache DOM elements
function cacheElements() {
elements = {
// Loading
loadingOverlay: document.getElementById('loading-overlay'),
progressFill: document.getElementById('progress-fill'),
progressText: document.getElementById('progress-text'),
// Drag and Drop
elements.dropZone.addEventListener('dragover', handleDragOver);
elements.dropZone.addEventListener('dragleave', handleDragLeave);
elements.dropZone.addEventListener('drop', handleFileDrop);
function loadSampleData() {
// Pre-load sample data for demonstration without showing loading
appState.rawData = [...sampleData];
applyFilters();
// Show explorer view if there's sample data and no hash route
if (!window.location.hash || window.location.hash === '#/') {
showView('explorer');
window.location.hash = '#/explorer';
}
}
// Loading States
function showLoading(show) {
elements.loadingOverlay.classList.toggle('hidden', !show);
if (!show) {
elements.progressFill.style.width = '0%';
elements.progressText.textContent = '0%';
}
}
Okay, to modify the code to use data.csv instead of the hardcoded sampleData, we'll make the following changes:
Remove sampleData: The sampleData array will be deleted.
Create parseCSVText function: This new helper function will take CSV text as input and parse it, including the progress simulation. This allows us to reuse the parsing logic for both uploaded files and fetched files.
Modify parseCSVFile: This function will now use FileReader to get the text from the user-uploaded file and then pass it to parseCSVText.
Replace loadSampleData with loadDefaultCSVData:
This new asynchronous function will attempt to fetch('data.csv').
If data.csv is successfully fetched, its text content will be passed to parseCSVText.
Upon successful parsing, appState.rawData will be populated, filters applied, and the UI updated. If no specific URL hash is present, it will navigate to the explorer view.
If data.csv cannot be fetched (e.g., 404 error) or if parsing fails, the application will gracefully handle it, typically by remaining on the 'upload' view or respecting the current URL hash, allowing the user to upload a CSV manually.
Update init(): It will call setupRouter() first, then loadDefaultCSVData(). setupRouter() calls handleRouteChange() once to handle any initial URL hash. loadDefaultCSVData() will then load data asynchronously, and if successful, it will update the application state and call handleRouteChange() again to ensure the view reflects the loaded data.
Here's the modified code:
javascript
// Application State
let appState = {
rawData: [],
filteredData: [],
currentPage: 1,
itemsPerPage: 50,
totalPages: 0,
activeFilters: {
search: '',
consultancy: '',
tags: new Set(),
sort: 'high-to-low'
},
currentView: 'upload', // 'upload', 'explorer', 'detail'
currentDetailItem: null
};
// REMOVED: const sampleData = [...]
// DOM Elements
let elements = {};
// Initialize Application
function init() {
cacheElements();
setupEventListeners();
// Setup router first to handle initial hash
setupRouter();
// Then attempt to load default data.csv
loadDefaultCSVData();
}
// Cache DOM elements
function cacheElements() {
elements = {
// Loading
loadingOverlay: document.getElementById('loading-overlay'),
progressFill: document.getElementById('progress-fill'),
progressText: document.getElementById('progress-text'),
// Upload Section
uploadSection: document.getElementById('upload-section'),
dropZone: document.getElementById('drop-zone'),
fileInput: document.getElementById('file-input'),
browseBtn: document.getElementById('browse-btn'),
// Explorer Section
explorerSection: document.getElementById('explorer-section'),
uploadNewBtn: document.getElementById('upload-new-btn'),
searchInput: document.getElementById('search-input'),
consultancyFilter: document.getElementById('consultancy-filter'),
sortSelect: document.getElementById('sort-select'),
clearFiltersBtn: document.getElementById('clear-filters'),
activeTagsContainer: document.getElementById('active-tags-container'),
cardsContainer: document.getElementById('cards-container'),
currentRange: document.getElementById('current-range'),
totalCount: document.getElementById('total-count'),
// Pagination
paginationContainer: document.getElementById('pagination-container'),
prevBtn: document.getElementById('prev-btn'),
nextBtn: document.getElementById('next-btn'),
pageNumbers: document.getElementById('page-numbers'),
// Detail Section
detailSection: document.getElementById('detail-section'),
backBtn: document.getElementById('back-btn'),
detailContent: document.getElementById('detail-content')
};
}
// Setup Event Listeners
function setupEventListeners() {
// File Upload
elements.browseBtn.addEventListener('click', () => elements.fileInput.click());
elements.fileInput.addEventListener('change', handleFileSelect);
elements.dropZone.addEventListener('click', () => elements.fileInput.click());
// Drag and Drop
elements.dropZone.addEventListener('dragover', handleDragOver);
elements.dropZone.addEventListener('dragleave', handleDragLeave);
elements.dropZone.addEventListener('drop', handleFileDrop);
// Navigation
elements.uploadNewBtn.addEventListener('click', () => {
window.location.hash = '#/upload'; // Or showView('upload') directly if no hash change desired
});
elements.backBtn.addEventListener('click', () => {
window.location.hash = '#/explorer'; // Or showView('explorer')
});
// Filters and Search
elements.searchInput.addEventListener('input', handleSearch);
elements.consultancyFilter.addEventListener('change', handleConsultancyFilter);
elements.sortSelect.addEventListener('change', handleSort);
elements.clearFiltersBtn.addEventListener('click', clearAllFilters);
// Pagination
elements.prevBtn.addEventListener('click', () => changePage(appState.currentPage - 1));
elements.nextBtn.addEventListener('click', () => changePage(appState.currentPage + 1));
}
// Router Setup
function setupRouter() {
window.addEventListener('hashchange', handleRouteChange);
handleRouteChange(); // Handle initial route
}
function handleRouteChange() {
const hash = window.location.hash;
if (hash.startsWith('#/detail/')) {
const itemIdString = hash.replace('#/detail/', '');
const itemId = parseInt(itemIdString);
if (!isNaN(itemId)) {
// Only show detail page if data is loaded, otherwise it might be an invalid index
if (appState.rawData.length > 0 && itemId < appState.filteredData.length) {
showDetailPage(itemId);
} else if (appState.rawData.length === 0) {
// If data isn't loaded yet, defer or show placeholder
// For now, let's assume data will be loaded by loadDefaultCSVData or upload
// If it's a direct link and data fails to load, this won't show the detail.
// We could potentially store the intended detail view and try again after data load.
console.warn("Attempted to show detail page before data was ready or item index is out of bounds.");
// Fallback to explorer or upload if detail can't be shown
showView(appState.rawData.length > 0 ? 'explorer' : 'upload');
} else {
showView('explorer'); // Item index out of bounds for current filters
}
} else {
console.warn("Invalid item ID in URL hash for detail page.");
showView('explorer');
}
} else if (hash === '#/explorer') {
showView('explorer');
} else { // Includes '#', '#/upload', or empty hash
showView('upload');
}
}
// File Handling
function handleDragOver(e) {
e.preventDefault();
elements.dropZone.classList.add('drag-over');
}
function handleDragLeave(e) {
e.preventDefault();
elements.dropZone.classList.remove('drag-over');
}
function handleFileDrop(e) {
e.preventDefault();
elements.dropZone.classList.remove('drag-over');
const files = e.dataTransfer.files;
if (files.length > 0) {
processFile(files[0]);
}
}
function handleFileSelect(e) {
const file = e.target.files[0];
if (file) {
processFile(file);
}
}
function processFile(file) {
if (!file.name.toLowerCase().endsWith('.csv')) {
alert('Please select a CSV file.');
return;
}
if (file.size > 50 * 1024 * 1024) { // 50MB
if (!confirm('This file is quite large. Processing may take some time. Continue?')) {
return;
}
}
showLoading(true);
updateProgress(0); // Reset progress for new file
const reader = new FileReader();
reader.onload = function(e) {
const text = e.target.result;
parseCSVText(
text,
updateProgress,
(parsedData) => { // onComplete
finishProcessing(parsedData);
},
(errorMessage) => { // onError
showError(errorMessage); // showError already calls showLoading(false)
}
);
};
reader.onerror = function() {
showError('Error reading file.');
};
reader.readAsText(file);
}
// NEW function to parse CSV text (reusable for fetch and file upload)
function parseCSVText(csvText, onProgress, onComplete, onError) {
const lines = csvText.split('\n').filter(line => line.trim());
if (lines.length < 2) { // Must have at least a header and one data row
if (onError) onError('CSV file appears to be empty or lacks data rows.');
return;
}
const headers = parseCSVLine(lines[0]);
const data = [];
const numDataLines = lines.length - 1;
let dataLinesProcessed = 0;
const batchSize = 1000; // Process in batches to keep UI responsive
function processBatch() {
const currentBatchEnd = Math.min(dataLinesProcessed + batchSize, numDataLines);
for (let i = dataLinesProcessed; i < currentBatchEnd; i++) {
// lines[0] is header, so data lines are lines[i+1]
const lineContent = lines[i + 1];
if (lineContent && lineContent.trim() !== '') {
const values = parseCSVLine(lineContent);
const record = {};
headers.forEach((header, index) => {
record[header.trim()] = values[index] || ''; // Trim header
});
data.push(record);
}
}
dataLinesProcessed = currentBatchEnd;
const progress = numDataLines > 0 ? (dataLinesProcessed / numDataLines) * 100 : 100;
if (onProgress) onProgress(progress);
if (dataLinesProcessed < numDataLines) {
setTimeout(processBatch, 10); // Allow UI to update
} else {
if (onComplete) onComplete(data);
}
}
// Start the first batch
if (numDataLines === 0 && lines.length === 1) { // Only header row
if (onError) onError('CSV file only contains a header row.');
return;
}
processBatch();
}
function parseCSVLine(line) {
const result = [];
let current = '';
let inQuotes = false;
for (let i = 0; i < line.length; i++) {
const char = line[i];
if (char === '"' && i + 1 < line.length && line[i+1] === '"') { // Escaped quote
current += '"';
i++; // Skip next quote
} else if (char === '"') {
inQuotes = !inQuotes;
} else if (char === ',' && !inQuotes) {
result.push(current); // Don't trim here, let trim happen on header or as needed
current = '';
} else {
current += char;
}
}
result.push(current);
// Remove surrounding quotes only if they exist, and unescape double quotes
return result.map(field => {
let f = field.trim();
if (f.startsWith('"') && f.endsWith('"')) {
f = f.substring(1, f.length - 1);
}
return f.replace(/""/g, '"');
});
}
function finishProcessing(data) {
appState.rawData = data;
applyFilters(); // This will also set currentPage to 1 and update UI
showLoading(false);
if (appState.currentView !== 'explorer' && appState.currentView !== 'detail') {
window.location.hash = '#/explorer'; // Navigate to explorer after successful upload
} else {
handleRouteChange(); // Re-render current view (explorer or detail) with new data
}
}
// MODIFIED: Replaced loadSampleData with loadDefaultCSVData
async function loadDefaultCSVData() {
showLoading(true);
updateProgress(0);
try {
const response = await fetch('data.csv'); // Assumes data.csv is in the same public path as index.html
if (!response.ok) {
// Not a fatal error, just means no default data. User can still upload.
console.warn(`Default data.csv not found or failed to load: ${response.status}. App will rely on user uploads or current hash.`);
showLoading(false);
// handleRouteChange (called by setupRouter) would have already set an initial view.
// If it was '#/upload', it stays there. If '#/explorer', it shows empty.
// If current hash is empty or '#/', handleRouteChange defaults to 'upload'.
if (!window.location.hash || window.location.hash === '#/' || window.location.hash === '#/upload') {
showView('upload'); // Explicitly ensure upload view if no data and no specific other hash
} else {
handleRouteChange(); // Refresh view based on hash, which might show empty explorer
}
return;
}
const csvText = await response.text();
parseCSVText(
csvText,
updateProgress,
(parsedData) => { // onComplete
appState.rawData = parsedData;
applyFilters(); // This sets filteredData, totalPages, currentPage=1
showLoading(false);
// If current hash is empty, default or upload, and data loaded, go to explorer.
// Otherwise, respect the current hash (e.g. a bookmarked detail page)
// by calling handleRouteChange to re-render with the new data.
if (!window.location.hash || window.location.hash === '#/' || window.location.hash === '#/upload') {
window.location.hash = '#/explorer';
} else {
handleRouteChange(); // Re-process route now that data is available
}
},
(errorMessage) => { // onError (parsing data.csv)
showError(`Error parsing default data.csv: ${errorMessage}`);
// showError calls showLoading(false)
if (!window.location.hash || window.location.hash === '#/' || window.location.hash === '#/upload') {
showView('upload');
} else {
handleRouteChange();
}
}
);
} catch (error) { // Network or other fetch errors
console.error("Error fetching default data.csv:", error);
showLoading(false);
// Similar to 404, not fatal.
if (!window.location.hash || window.location.hash === '#/' || window.location.hash === '#/upload') {
showView('upload');
} else {
handleRouteChange();
}
}
}
// Loading States
function showLoading(show) {
elements.loadingOverlay.classList.toggle('hidden', !show);
if (show) { // Reset progress when showing loading
elements.progressFill.style.width = '0%';
elements.progressText.textContent = '0%';
}
}
function updateProgress(percent) {
elements.progressFill.style.width = percent + '%';
elements.progressText.textContent = Math.round(percent) + '%';
}
function showError(message) {
showLoading(false); // Always hide loading on error
alert(message); // In a real app, use a nicer modal or notification
// Potentially reset file input if it's related to an upload
if (elements.fileInput) {
elements.fileInput.value = '';
}
}
// View Management
function showView(view) {
// Only switch if view actually changes, or if forced (e.g. data loaded)
// if (appState.currentView === view && view !== 'explorer' && view !== 'detail') return;
appState.currentView = view;
elements.uploadSection.classList.toggle('hidden', view !== 'upload');
elements.explorerSection.classList.toggle('hidden', view !== 'explorer');
elements.detailSection.classList.toggle('hidden', view !== 'detail');
if (view === 'explorer') {
// Ensure filters are applied if rawData exists but filteredData might be stale
// This is mostly handled by applyFilters directly when data changes.
// if (appState.rawData.length > 0 && appState.filteredData.length === 0 && !appState.activeFilters.search) {
// applyFilters(); // Apply if rawData exists but filtered is empty (e.g. initial load)
// }
renderCurrentPage();
updatePagination(); // Ensure pagination is correct for explorer view
updateCounts();
} else if (view === 'detail') {
// Detail rendering is handled by showDetailPage -> renderDetailPage
} else if (view === 'upload') {
// Reset file input when navigating to upload view explicitly
if (elements.fileInput) elements.fileInput.value = '';
}
}
// Filtering and Search
function handleSearch(e) {
appState.activeFilters.search = e.target.value.toLowerCase().trim();
applyFilters();
}
function handleConsultancyFilter(e) {
appState.activeFilters.consultancy = e.target.value;
applyFilters();
}
function handleSort(e) {
appState.activeFilters.sort = e.target.value;
applyFilters();
}
function handleTagClick(tag) {
if (appState.activeFilters.tags.has(tag)) {
appState.activeFilters.tags.delete(tag);
} else {
appState.activeFilters.tags.add(tag);
}
applyFilters();
updateActiveTagsDisplay();
}
function removeTagFilter(tag) {
appState.activeFilters.tags.delete(tag);
applyFilters();
updateActiveTagsDisplay();
}
function clearAllFilters() {
appState.activeFilters = {
search: '',
consultancy: '',
tags: new Set(),
sort: 'high-to-low'
};
elements.searchInput.value = '';
elements.consultancyFilter.value = '';
elements.sortSelect.value = 'high-to-low';
applyFilters();
updateActiveTagsDisplay();
}
function applyFilters() {
let filtered = [...appState.rawData]; // Start with all raw data
// Apply search filter
if (appState.activeFilters.search) {
const searchTerm = appState.activeFilters.search;
filtered = filtered.filter(item => {
// Search across all string values in the item
return Object.values(item).some(value =>
typeof value === 'string' && value.toLowerCase().includes(searchTerm)
);
});
}
// Apply consultancy filter
if (appState.activeFilters.consultancy) {
filtered = filtered.filter(item =>
item['Have a consultancy'] === appState.activeFilters.consultancy
);
}
// Apply tag filters
if (appState.activeFilters.tags.size > 0) {
filtered = filtered.filter(item => {
const itemTags = (item['Field of interest'] || '').toLowerCase().split(',').map(tag => tag.trim());
return Array.from(appState.activeFilters.tags).every(filterTag =>
itemTags.some(itemTag => itemTag.includes(filterTag.toLowerCase())) // Use includes for partial match within a tag
);
});
}
// Apply sorting
filtered.sort((a, b) => {
const scoreA = parseInt(a['AI Prediction']) || 0;
const scoreB = parseInt(b['AI Prediction']) || 0;
if (appState.activeFilters.sort === 'high-to-low') {
return scoreB - scoreA;
} else if (appState.activeFilters.sort === 'low-to-high') { // Ensure this value matches select option
return scoreA - scoreB;
}
return 0;
});
appState.filteredData = filtered;
appState.totalPages = Math.ceil(filtered.length / appState.itemsPerPage);
// If current page becomes invalid after filtering, reset to 1
if (appState.currentPage > appState.totalPages && appState.totalPages > 0) {
appState.currentPage = appState.totalPages;
} else if (appState.totalPages === 0) {
appState.currentPage = 1;
}
// If current page is 0 and there are pages, set to 1
if (appState.currentPage < 1 && appState.totalPages > 0) {
appState.currentPage = 1;
}
// Update UI elements that depend on filtered data
// Only call renderCurrentPage if the current view is explorer
if (appState.currentView === 'explorer') {
renderCurrentPage();
updatePagination();
updateCounts();
} else if (appState.currentView === 'detail' && appState.currentDetailItem) {
// If on detail page, check if currentDetailItem is still in filteredData
// This is complex: re-filtering might remove the item or change its index.
// For simplicity, we might just re-render the detail if item still exists,
// or navigate back to explorer if it's gone.
// Current implementation: showDetailPage uses index from filteredData.
// If filters change, the detail page might become invalid.
// Simplest is that filters apply to explorer. If user is on detail, they see old data until they go back.
// Or, upon filter change, if on detail, force back to explorer:
// if (appState.currentView === 'detail') window.location.hash = '#/explorer';
}
}
// Rendering
function renderCurrentPage() {
if (appState.currentView !== 'explorer') return; // Should only render if in explorer view
const startIndex = (appState.currentPage - 1) * appState.itemsPerPage;
const endIndex = startIndex + appState.itemsPerPage;
// Ensure pageData is derived from appState.filteredData
const pageData = appState.filteredData.slice(startIndex, endIndex);
elements.cardsContainer.innerHTML = ''; // Clear previous cards
if (pageData.length === 0 && appState.filteredData.length === 0 && appState.rawData.length > 0) { // No results from filter
elements.cardsContainer.innerHTML = `
<div class="empty-state">
<div class="empty-state-icon">📭</div>
<h3>No results found</h3>
<p>Try adjusting your search or filter criteria.</p>
</div>
`;
} else if (appState.rawData.length === 0) { // No data loaded at all
elements.cardsContainer.innerHTML = `
<div class="empty-state">
<div class="empty-state-icon">📄</div>
<h3>No data loaded</h3>
<p>Please upload a CSV file to get started, or try reloading if a default file was expected.</p>
</div>
`;
} else {
pageData.forEach((item, indexInPage) => {
// The actual index in filteredData is startIndex + indexInPage
const overallIndex = startIndex + indexInPage;
const card = createCard(item, overallIndex);
elements.cardsContainer.appendChild(card);
});
}
updateCounts(); // Update counts after rendering
updatePagination(); // Update pagination state
}
function createCard(item, overallIndex) { // overallIndex is the item's index in appState.filteredData
const card = document.createElement('div');
card.className = 'data-card fade-in';
// Use overallIndex for navigation to detail page
card.addEventListener('click', () => {
window.location.hash = `#/detail/${overallIndex}`;
});
const tags = (item['Field of interest'] || '').split(',').map(tag => tag.trim()).filter(tag => tag);
const predictionScore = parseInt(item['AI Prediction']) || 0;
const predictionPercentage = Math.max(0, Math.min(100, predictionScore)); // Clamp between 0-100
let predictionClass = 'prediction-low';
if (predictionScore >= 80) predictionClass = 'prediction-high';
else if (predictionScore >= 60) predictionClass = 'prediction-medium';
const hasConsultancy = item['Have a consultancy'] === 'Yes';
card.innerHTML = `
<div class="card-header">
<h3 class="card-title">${escapeHtml(item.Name || 'Unnamed Organization')}</h3>
${item.Acronym ? `<div class="card-acronym">${escapeHtml(item.Acronym)}</div>` : ''}
</div>
<div class="card-body">
${hasConsultancy ? '<div class="consultancy-badge">Has Consultancy</div>' : ''}
<div class="card-tags">
${tags.map(tag => `
<span class="tag" onclick="event.stopPropagation(); handleTagClick('${escapeHtml(tag.replace(/'/g, "\\'"))}')">${escapeHtml(tag)}</span>
`).join('')}
</div>
<div class="prediction-container">
<div class="prediction-label">
<span>AI Prediction</span>
<span class="prediction-score">${predictionScore}/100</span>
</div>
<div class="prediction-bar">
<div class="prediction-fill ${predictionClass}" style="width: ${predictionPercentage}%"></div>
</div>
</div>
</div>
`;
return card;
}
// Detail Page
function showDetailPage(itemIndexInFilteredData) {
// itemIndexInFilteredData is the index of the item in appState.filteredData
if (itemIndexInFilteredData < 0 || itemIndexInFilteredData >= appState.filteredData.length) {
console.error("Invalid item index for detail page:", itemIndexInFilteredData);
window.location.hash = '#/explorer'; // Go back to explorer if item not found
return;
}
const item = appState.filteredData[itemIndexInFilteredData];
if (!item) {
console.error("Item not found for detail page at index:", itemIndexInFilteredData);
window.location.hash = '#/explorer';
return;
}
appState.currentDetailItem = item;
// Ensure hash is set correctly by router or direct navigation,
// showView will be called by handleRouteChange.
// window.location.hash = `#/detail/${itemIndexInFilteredData}`;
showView('detail'); // Explicitly show detail view
renderDetailPage(item);
}
function renderDetailPage(item) {
const tags = (item['Field of interest'] || '').split(',').map(tag => tag.trim()).filter(tag => tag);
const predictionScore = parseInt(item['AI Prediction']) || 0;
const predictionPercentage = Math.max(0, Math.min(100, predictionScore));
let predictionClass = 'prediction-low';
if (predictionScore >= 80) predictionClass = 'prediction-high';
else if (predictionScore >= 60) predictionClass = 'prediction-medium';
elements.detailContent.innerHTML = `
<div class="detail-header">
<h1 class="detail-title">${escapeHtml(item.Name || 'Unnamed Organization')}</h1>
${item.Acronym ? `<div class="detail-acronym">${escapeHtml(item.Acronym)}</div>` : ''}
${item['Website URL'] ? `
<a href="${escapeHtml(item['Website URL'])}" target="_blank" rel="noopener noreferrer" class="detail-website">
🌐 Visit Website
</a>
` : ''}
</div>
<div class="detail-sections">
<div class="detail-section-card">
<h2 class="section-title">📋 Basic Information</h2>
<div class="section-content">
${item.Goals ? `
<div class="detail-field">
<div class="field-label">Goals</div>
<div class="field-value">${escapeHtml(item.Goals)}</div>
</div>
` : ''}
${item['EU legislative proposals/policies'] ? `
<div class="detail-field">
<div class="field-label">EU Legislative Proposals/Policies</div>
<div class="field-value">${escapeHtml(item['EU legislative proposals/policies'])}</div>
</div>
` : ''}
</div>
</div>
<div class="detail-section-card">
<h2 class="section-title">📊 Statistics & Classification</h2>
<div class="section-content">
${item['Number of EP accredited Person'] ? `
<div class="detail-field">
<div class="field-label">Number of EP Accredited Persons</div>
<div class="field-value">${escapeHtml(item['Number of EP accredited Person'])}</div>
</div>
` : ''}
<div class="detail-field">
<div class="field-label">AI Prediction Score</div>
<div class="score-display">
<div class="score-number">${predictionScore}/100</div>
<div class="score-bar">
<div class="score-fill ${predictionClass}" style="width: ${predictionPercentage}%"></div>
</div>
</div>
</div>
${tags.length > 0 ? `
<div class="detail-field">
<div class="field-label">Field of Interest</div>
<div class="detail-tags">
${tags.map(tag => `<span class="detail-tag">${escapeHtml(tag)}</span>`).join('')}
</div>
</div>
` : ''}
${item['Annual cost for register activity or total budget'] ? `
<div class="detail-field">
<div class="field-label">Annual Cost/Total Budget</div>
<div class="field-value">${escapeHtml(item['Annual cost for register activity or total budget'])}</div>
</div>
` : ''}
</div>
</div>
<div class="detail-section-card">
<h2 class="section-title">🏢 Consultancy Information</h2>
<div class="section-content">
<div class="detail-field">
<div class="field-label">Has Consultancy</div>
<div class="field-value">
<span class="status ${item['Have a consultancy'] === 'Yes' ? 'status--success' : 'status--info'}">
${escapeHtml(item['Have a consultancy'] || 'No')}
</span>
</div>
</div>
${item['Name of consultancy'] ? `
<div class="detail-field">
<div class="field-label">Consultancy Name</div>
<div class="field-value">${escapeHtml(item['Name of consultancy'])}</div>
</div>
` : ''}
</div>
</div>
</div>
`;
}
// Pagination
function changePage(page) {
if (page < 1 && appState.totalPages > 0) page = 1; // Sanitize
if (page > appState.totalPages && appState.totalPages > 0) page = appState.totalPages; // Sanitize
if (appState.totalPages === 0) page = 1; // If no pages, current page is 1
if (page === appState.currentPage && appState.totalPages > 0) return; // No change if already on this page
appState.currentPage = page;
renderCurrentPage(); // This will render cards for the new page
updatePagination(); // This will update buttons and page numbers
// Scroll to top of cards container or window
elements.cardsContainer.scrollTo({ top: 0, behavior: 'smooth' });
// Or window.scrollTo({ top: elements.explorerSection.offsetTop, behavior: 'smooth' });
}
function updatePagination() {
if (!elements.prevBtn || !elements.nextBtn || !elements.pageNumbers) return;
elements.prevBtn.disabled = appState.currentPage <= 1;
elements.nextBtn.disabled = appState.currentPage >= appState.totalPages || appState.totalPages === 0;
elements.paginationContainer.classList.toggle('hidden', appState.totalPages <= 1);
renderPageNumbers();
}
function renderPageNumbers() {
if (!elements.pageNumbers) return;
elements.pageNumbers.innerHTML = '';
if (appState.totalPages <= 1) return;
const maxVisiblePages = 5; // Show up to 5 page numbers (e.g., Prev 1 ... 3 4 5 ... 10 Next)
let startPage, endPage;
if (appState.totalPages <= maxVisiblePages) {
startPage = 1;
endPage = appState.totalPages;
} else {
const maxPagesBeforeCurrent = Math.floor((maxVisiblePages -1) / 2); // -1 for current page itself
const maxPagesAfterCurrent = Math.ceil((maxVisiblePages -1) / 2) -1; // -1 because we add first/last page
if (appState.currentPage <= maxPagesBeforeCurrent +1) { // Near the start
startPage = 1;
endPage = maxVisiblePages -1; // Show first few pages
addPageButton(1);
for (let i = 2; i <= endPage; i++) {
addPageButton(i);
}
elements.pageNumbers.appendChild(createEllipsis());
addPageButton(appState.totalPages);
} else if (appState.currentPage + maxPagesAfterCurrent >= appState.totalPages) { // Near the end
startPage = appState.totalPages - maxVisiblePages + 2;
addPageButton(1);
elements.pageNumbers.appendChild(createEllipsis());
for (let i = startPage; i <= appState.totalPages; i++) {
addPageButton(i);
}
} else { // In the middle
startPage = appState.currentPage - maxPagesBeforeCurrent +1;
endPage = appState.currentPage + maxPagesAfterCurrent -1;
addPageButton(1);
elements.pageNumbers.appendChild(createEllipsis());
for (let i = startPage; i <= endPage; i++) {
addPageButton(i);
}
elements.pageNumbers.appendChild(createEllipsis());
addPageButton(appState.totalPages);
}
return; // Handled by specific logic above for many pages
}
// Fallback for simpler cases or if above logic is too complex to fit all numbers
// The logic above should cover it, this is more of a basic loop.
// Let's refine the above for clarity and ensure it shows current page within the visible set.
// Simpler pagination number logic:
elements.pageNumbers.innerHTML = ''; // Clear again
if (appState.totalPages <= 1) return;
const K = 2; // Number of page links around current page
const pagesToShow = [];
// Always show first page
pagesToShow.push(1);
// Calculate range around current page
let Pmin = appState.currentPage - K;
let Pmax = appState.currentPage + K;
for (let i = Math.max(2, Pmin) ; i <= Math.min(appState.totalPages - 1, Pmax); i++) {
pagesToShow.push(i);
}
// Always show last page (if not 1)
if (appState.totalPages > 1) {
pagesToShow.push(appState.totalPages);
}
// Add pages with ellipsis
let lastPageAdded = 0;
pagesToShow.filter((p, i, self) => self.indexOf(p) === i).sort((a,b) => a-b) // Unique sorted
.forEach(p => {
if (lastPageAdded > 0 && p > lastPageAdded + 1) {
elements.pageNumbers.appendChild(createEllipsis());
}
addPageButton(p);
lastPageAdded = p;
});
}
function addPageButton(page) {
const button = document.createElement('button');
button.className = `page-btn ${page === appState.currentPage ? 'active' : ''}`;
button.textContent = page;
button.addEventListener('click', () => changePage(page));
elements.pageNumbers.appendChild(button);
}
function createEllipsis() {
const span = document.createElement('span');
span.textContent = '...';
span.className = 'page-ellipsis';
return span;
}
// UI Updates
function updateCounts() {
if (!elements.currentRange || !elements.totalCount) return;
const totalFiltered = appState.filteredData.length;
const itemsPerPage = appState.itemsPerPage;
const currentPage = appState.currentPage;
let startItem, endItem;
if (totalFiltered === 0) {
startItem = 0;
endItem = 0;
} else {
startItem = (currentPage - 1) * itemsPerPage + 1;
endItem = Math.min(currentPage * itemsPerPage, totalFiltered);
}
elements.currentRange.textContent = totalFiltered === 0 ? '0' : `${startItem}-${endItem}`;
elements.totalCount.textContent = totalFiltered;
}
function updateActiveTagsDisplay() {
if (!elements.activeTagsContainer) return;
elements.activeTagsContainer.innerHTML = '';
Array.from(appState.activeFilters.tags).forEach(tag => {
const tagElement = document.createElement('span');
tagElement.className = 'active-tag';
tagElement.innerHTML = `
${escapeHtml(tag)}
<button onclick="removeTagFilter('${escapeHtml(tag.replace(/'/g, "\\'"))}')" aria-label="Remove ${escapeHtml(tag)} filter">×</button>
`;
elements.activeTagsContainer.appendChild(tagElement);
});
}
// Utility Functions
function escapeHtml(text) {
if (typeof text !== 'string') {
if (text === null || typeof text === 'undefined') return '';
text = String(text);
}
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
// Global Functions (for onclick handlers in dynamically generated HTML)
window.handleTagClick = handleTagClick;
window.removeTagFilter = removeTagFilter;
// Initialize Application on DOMContentLoaded
document.addEventListener('DOMContentLoaded', init);
To make this work:
Save the code above as your Javascript file (e.g., app.js).
Make sure you have a data.csv file in the same directory as your index.html file (or adjust the path in the fetch('data.csv') call if it's located elsewhere).
The data.csv file should have a header row, and subsequent rows should match the structure expected by your application (e.g., "Name", "Acronym", "AI Prediction", "Field of interest", etc.).
The CSV parsing in parseCSVLine has been made slightly more robust to handle quotes and escaped quotes within fields, but complex CSVs might still need a more advanced library.
This revised code will first attempt to load and parse data.csv. If successful, that data will be used. If data.csv is not found or fails to load/parse, the application will start in the "upload" state, allowing the user to upload their own CSV file. The progress bar will now also work for the initial loading of data.csv.