Skip to content

Commit

Permalink
Merge pull request #48 from oss-slu/rerum-tools-js
Browse files Browse the repository at this point in the history
Issue #45 - Refactoring Javascript Code
  • Loading branch information
alar12 authored Nov 19, 2024
2 parents eeea8bd + a553046 commit f366b8b
Show file tree
Hide file tree
Showing 6 changed files with 381 additions and 384 deletions.
4 changes: 2 additions & 2 deletions web/js/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
* There should be no functions or HTML template literals here.
*
*/
import ToolsCatalog from './tools.js';
import ToolsCatalog from './toolsCatalog.js';

export default {
URLS: {
Expand Down Expand Up @@ -40,7 +40,7 @@ export default {
//Then just adding one of these things to the repos will make it show up in the playground. Just a thought for now.
TOOLS:{
id : "tool_set",
catalog : ToolsCatalog // importing the tool catalog from tools.js
catalog : ToolsCatalog // importing the tool catalog from toolsCatalog.js
},

// What are these here for? Do the users know about these?
Expand Down
224 changes: 0 additions & 224 deletions web/js/playground.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,230 +3,6 @@
*/

// Playground scripting utilities. Will be available as github CDN.
import { default as UTILS } from 'https://centerfordigitalhumanities.github.io/rerum-playground/web/js/utilities.js'

import PLAYGROUND from './config.js';
import ToolsCatalog from './tools.js';
import { storeManifestLink, getStoredManifestLinks } from './manifestStorage.js';

const RECENTLY_USED_KEY = 'recentlyUsedTools';

console.log("script is loading...");

/**
* Retrieve recently used tools from local storage.
*/
function getRecentlyUsedTools() {
const recentTools = localStorage.getItem(RECENTLY_USED_KEY);
return recentTools ? JSON.parse(recentTools) : [];
}

/**
* Save recently used tools to local storage.
*/
function saveRecentlyUsedTools(recentTools) {
console.log("Saving recent tools:", recentTools);
localStorage.setItem(RECENTLY_USED_KEY, JSON.stringify(recentTools));
}

/**
* Update recently used tools, move the clicked tool to the top.
*/
function updateRecentlyUsedTools(clickedTool) {
// const recentTools = getRecentlyUsedTools();
// const existingIndex = recentTools.findIndex(tool => tool.label.toLowerCase() === clickedTool.label.toLowerCase());

// if (existingIndex !== -1) {
// recentTools.splice(existingIndex, 1);
// }
console.log("updateRecentlyUsedTools called with:", clickedTool);
let recentTools = getRecentlyUsedTools();

// Remove the tool if it exists in recentTools, then add it to the top
recentTools = recentTools.filter(tool => tool.label.toLowerCase() !== clickedTool.label.toLowerCase());
recentTools.unshift(clickedTool);

const topThreeTools = recentTools.slice(0, 3);
saveRecentlyUsedTools(topThreeTools);
console.log("updated recent tools after click:", topThreeTools);
}

/**
* Landing behavior for interfaces. This should populate the set of available interfaces to the DOM.
*/
function initializeInterfaces(config) {
return new Promise((res) => {
let setContainer = document.getElementById(config.id)
Array.from(config.catalog).forEach(inter => {
setContainer.innerHTML += UTILS.thumbnailGenerator(inter)
})
UTILS.broadcast(undefined, PLAYGROUND.EVENTS.LOADED, setContainer, {})
/**
* Really each render should be a promise and we should return a Promise.all() here of some kind.
* That would only work if PlaygroundRender resulted in a Promise where we could return Promise.all(renderPromises).
*/
setTimeout(res, 200) //A small hack to ensure all the HTML generated by processing the views enters the DOM before this says it has resolved.
})
}

/**
* Landing behavior for technologies. This should populate the technologies to the DOM.
*/
function initializeTechnologies(config) {
return new Promise((res) => {
let setContainer = document.getElementById(config.id)
Array.from(config.catalog).forEach(tech => {
setContainer.innerHTML += UTILS.thumbnailGenerator(tech)
})
UTILS.broadcast(undefined, PLAYGROUND.EVENTS.LOADED, setContainer, {})
/**
* Really each render should be a promise and we should return a Promise.all() here of some kind.
* That would only work if PlaygroundRender resulted in a Promise where we could return Promise.all(renderPromises).
*/
setTimeout(res, 200) //A small hack to ensure all the HTML generated by processing the views enters the DOM before this says it has resolved.
})
}

/**
* Render tools, higlighting recently used ones.
*/
function renderTools() {
console.log("renderTools is running");
const toolSetContainer = document.getElementById('tool_set');
if (!toolSetContainer) {
console.error("Tool set container not found.");
return;
}

toolSetContainer.innerHTML = '';

const recentTools = getRecentlyUsedTools();
const hasRecentlyUsedTools = recentTools.length > 0;

// Divide ToolsCatalog into recently used tools and non-recently-used tools
const recentlyUsedLabels = recentTools.map(tool => tool.label.toLowerCase());
const recentToolsSet = new Set(recentlyUsedLabels);

const recentlyUsedTools = ToolsCatalog.filter(tool =>
recentToolsSet.has(tool.label.toLowerCase())
);

const nonRecentlyUsedTools = ToolsCatalog.filter(tool =>
!recentToolsSet.has(tool.label.toLowerCase())
);

// Sort recently used tools based on their order in recentTools array
const sortedRecentlyUsedTools = recentlyUsedTools.sort(
(a, b) =>
recentToolsSet.has(a.label.toLowerCase()) - recentToolsSet.has(b.label.toLowerCase())
);

// Combine sorted recently used tools and non-recently-used tools
const sortedTools = [...sortedRecentlyUsedTools, ...nonRecentlyUsedTools];

const toolsWrapper = document.createElement('div');

sortedTools.forEach((tool, index) => {
const isRecentlyUsed = hasRecentlyUsedTools && index < 3 && recentToolsSet.has(tool.label.toLowerCase()) ? `<span class="recent-badge">Recently used</span>` : '';
const toolHTML = `
<a href="${tool.view}" target="_blank" class="catalogEntry">
<figure class="thumb">
${isRecentlyUsed}
<label>${tool.label}</label>
<img src="${tool.icon}" alt="${tool.label}" />
<figcaption>${tool.description}</figcaption>
</figure>
</a>
`;
toolsWrapper.innerHTML += toolHTML;
});

toolSetContainer.appendChild(toolsWrapper);

// Add event listeners after elements are created
const toolLinks = toolSetContainer.querySelectorAll('a.catalogEntry');
toolLinks.forEach(link => {
link.addEventListener('click', function (e) {
e.preventDefault();
const toolLabel = this.querySelector('label').innerText;
handleToolClick(toolLabel);
});
});

console.log("rendered tool order:", sortedTools.map(tool => tool.label));
}

/**
* Render stored manifest links.
*/
function renderStoredManifests() {
const manifestContainer = document.getElementById('stored_manifest_links');
const storedManifests = getStoredManifestLinks();

if (!manifestContainer) {
console.error("Manifest set container not found.");
return;
}

manifestContainer.innerHTML = '';

if (storedManifests.length === 0) {
manifestContainer.innerHTML = '<p>No stored manifest links.</p>';
return;
}

storedManifests.forEach(manifestLink => {
const manifestHTML = `
<a href="${manifestLink}" target="_blank" class="manifestLink">
<p>${manifestLink}</p>
</a>
`;
manifestContainer.innerHTML += manifestHTML;
});
}


/**
* Handle tool click event to manage recently used logic and allow default navigation
*/
function handleToolClick(toolLabel) {
console.log("handleToolClick called with:", toolLabel);
const clickedTool = ToolsCatalog.find(tool => tool.label === toolLabel);
if (clickedTool) {
updateRecentlyUsedTools(clickedTool);
renderTools();
setTimeout(() => {
window.open(clickedTool.view, '_blank');
}, 100);
} else {
console.error('Clicked tool not found:', toolLabel);
}
}

/**
* Update tool order when a tool is clicked.
*/
window.updateToolOrder = function(toolLabel) {
const clickedTool = ToolsCatalog.find(tool => tool.label === toolLabel);
if (clickedTool) {
updateRecentlyUsedTools(clickedTool);
renderTools();
}
}

document.addEventListener('DOMContentLoaded', () => {
/**
* These are promises so we can control the chaining how we like, if necessary.
*/
try {
initializeInterfaces(PLAYGROUND.INTERFACES)
initializeTechnologies(PLAYGROUND.TECHNOLOGIES)
renderTools();
renderStoredManifests();
} catch (err) {
console.error("Error initializing the playground: ", err);
}
});

//fetch footer
fetch('footer.html')
Expand Down
113 changes: 0 additions & 113 deletions web/js/tool.js

This file was deleted.

Loading

0 comments on commit f366b8b

Please sign in to comment.