Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions .github/workflows/clean-urls.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
name: Clean URLs

on:
pull_request:
push:
branches: [main]
workflow_dispatch:
inputs:
deploy:
description: 'Publish _site only after an approved switch to Pages GitHub Actions'
type: boolean
default: false

permissions:
contents: read

concurrency:
group: clean-urls-${{ github.ref }}
cancel-in-progress: false

jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
- run: npm run build
- run: npm run test:urls
- run: npm run validate:urls
- run: npm run validate:events
- uses: actions/upload-pages-artifact@v4
with:
path: _site

# Raw main/root publication remains supported until an approved Pages cutover.
deploy:
if: github.event_name == 'workflow_dispatch' && inputs.deploy && github.ref == 'refs/heads/main'
needs: build
runs-on: ubuntu-latest
permissions:
pages: write
id-token: write
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
steps:
- uses: actions/deploy-pages@v4
id: deployment
2 changes: 2 additions & 0 deletions .github/workflows/update-search-index.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ on:
- "data/events.json"
- "data/news.json"
- "scripts/build-search-index.mjs"
- "scripts/site-routes.mjs"
- "js/site-urls.js"

permissions:
contents: write
Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
_site/
4 changes: 4 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"liveServer.settings.root": "/_site",
"liveServer.settings.port": 5500
}
2 changes: 1 addition & 1 deletion html/components/header.html
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<header class="header" style="background-color: #ffffff; background-image: none; -webkit-backdrop-filter: none; backdrop-filter: none;">
<div class="logo">
<a href="index.html">
<a href="/">
<img src="images/Imageomics-logo.png" alt="Imageomics Institute logo" />
</a>
</div>
Expand Down
11 changes: 8 additions & 3 deletions js/events.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ document.addEventListener('DOMContentLoaded', async () => {

let eventItems;
try {
const response = await fetch("../data/events.json");
const response = await fetch("/data/events.json");
if (!response.ok) throw new Error(`Request failed with status ${response.status}`);

eventItems = await response.json();
Expand Down Expand Up @@ -96,7 +96,12 @@ document.addEventListener('DOMContentLoaded', async () => {
};

const COURSE_SESSION_URL_MARKER = 'ai-and-ecology-course-';
const COURSE_SERIES_URL = 'tools-resources/experiential-introduction-ai-ecology-course-2026-2027.html';
const COURSE_SERIES_URL = window.ImageomicsUrls
? '/tools-resources/experiential-introduction-ai-ecology-course-2026-2027/'
: 'tools-resources/experiential-introduction-ai-ecology-course-2026-2027.html';
const CONFERENCE_URL = window.ImageomicsUrls
? '/events/2027-imageomics-conference/'
: 'events/2027-imageomics-conference.html';
const FEATURED_UPCOMING_WINDOW_DAYS = 14;
const MILLISECONDS_PER_DAY = 24 * 60 * 60 * 1000;

Expand Down Expand Up @@ -156,7 +161,7 @@ document.addEventListener('DOMContentLoaded', async () => {
const today = getToday();
const featureCandidates = items.flatMap((item) => item.seriesItems?.length ? item.seriesItems : [item]);
const conference = featureCandidates.find((item) =>
item.url === 'events/2027-imageomics-conference.html' && !isPastEvent(item));
item.url === CONFERENCE_URL && !isPastEvent(item));
if (conference) {
return { item: conference, status: 'Save the Date!' };
}
Expand Down
7 changes: 4 additions & 3 deletions js/homepage.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@

function getPageUrl(item) {
if (/^https?:\/\//.test(item.url || '')) return item.url;
return `html/${String(item.url || '').replace(/^\/?html\//, '')}`;
return window.ImageomicsUrls?.page(item.url) || `html/${String(item.url || '').replace(/^\/?html\//, '')}`;
}

function makeSnippet(value, maximumLength = 135) {
Expand Down Expand Up @@ -237,7 +237,8 @@
if (!upcomingEvent) return [...featuredItems];

const conference = featuredItems.find((item) => item.url === 'events/2027-imageomics-conference.html');
if (upcomingEvent.url === conference?.url) return [...featuredItems];
const comparableUrl = (url) => window.ImageomicsUrls?.page(url) || url;
if (comparableUrl(upcomingEvent.url) === comparableUrl(conference?.url)) return [...featuredItems];

return [
...(conference ? [conference] : []),
Expand Down Expand Up @@ -275,7 +276,7 @@

const getStoryUrl = (story) => {
if (/^https?:\/\//.test(story.url || '')) return story.url;
return `html/${String(story.url || '').replace(/^\/?html\//, '')}`;
return window.ImageomicsUrls?.page(story.url) || `html/${String(story.url || '').replace(/^\/?html\//, '')}`;
};

const createSlide = (story, isClone = false) => {
Expand Down
53 changes: 18 additions & 35 deletions js/load-components.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,35 +2,10 @@
(function() {
'use strict';

const COMPONENT_CACHE_VERSION = '14';
const COMPONENT_CACHE_VERSION = 'clean-urls-2';

function getPathPrefix() {
const path = window.location.pathname;

if (path.endsWith('/') || (path.endsWith('/index.html') && !path.includes('/html/'))) {
return '';
}

const htmlIndex = path.indexOf('/html/');
if (htmlIndex !== -1) {
const afterHtml = path.substring(htmlIndex + 6);
const depth = (afterHtml.match(/\//g) || []).length;
return '../'.repeat(depth + 1);
}

return '../';
}

function adjustPaths(html, prefix) {
if (!prefix) return html;

html = html.replace(/src="(images|css|js|html)\//g, `src="${prefix}$1/`);
html = html.replace(/href="(images|css|js|html)\//g, `href="${prefix}$1/`);
html = html.replace(/href="index\.html"/g, `href="${prefix}index.html"`);
html = html.replace(/href="\.\.\/index\.html"/g, `href="${prefix}index.html"`);

return html;
}
const script = document.querySelector('script[src*="js/load-components.js"]');
const siteRoot = new URL('../', script?.src || new URL('/js/load-components.js', window.location.href));

function getCachedComponent(url) {
try {
Expand Down Expand Up @@ -62,8 +37,17 @@
return;
}

const prefix = getPathPrefix();
target.innerHTML = adjustPaths(html, prefix);
target.innerHTML = html;
// Source fragments use root-relative authoring paths; generated fragments
// already have absolute paths. Both must work from nested pages.
target.querySelectorAll('[href], [src]').forEach((element) => {
for (const attribute of ['href', 'src']) {
const value = element.getAttribute(attribute);
if (!value || /^(?:[a-z][a-z\d+.-]*:|\/|#)/i.test(value)) continue;
const url = new URL(value, siteRoot);
element.setAttribute(attribute, url.pathname + url.search + url.hash);
}
});

if (targetId === 'header-placeholder') {
if (typeof window.initHamburger === 'function') {
Expand Down Expand Up @@ -115,21 +99,20 @@
});
}

function ensureFavicon(prefix) {
function ensureFavicon() {
if (document.querySelector('link[rel~="icon"]')) return;

const favicon = document.createElement('link');
favicon.rel = 'icon';
favicon.type = 'image/png';
favicon.href = `${prefix}images/Imageomics-logo.png`;
favicon.href = new URL('images/Imageomics-logo.png', siteRoot).href;
document.head.appendChild(favicon);
}

function initComponents() {
const prefix = getPathPrefix();
const componentsPath = `${prefix}html/components/`;
const componentsPath = new URL('html/components/', siteRoot).href;

ensureFavicon(prefix);
ensureFavicon();
loadComponent(`${componentsPath}header.html`, 'header-placeholder');
loadComponent(`${componentsPath}footer.html`, 'footer-placeholder');
}
Expand Down
2 changes: 1 addition & 1 deletion js/news.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ document.addEventListener('DOMContentLoaded', async () => {

let unsortedNewsItems;
try {
const response = await fetch("../data/news.json");
const response = await fetch("/data/news.json");
if (!response.ok) throw new Error(`Request failed with status ${response.status}`);

unsortedNewsItems = await response.json();
Expand Down
9 changes: 9 additions & 0 deletions js/redirect.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
// Runs before meta refresh. Retain query strings/fragments and avoid a Back loop.
(function () {
'use strict';
const canonical = document.querySelector('link[rel="canonical"]');
if (!canonical) return;
const target = new URL(canonical.href);
const destination = target.pathname + (window.location.search || target.search) + (window.location.hash || target.hash);
if (destination !== window.location.pathname + window.location.search + window.location.hash) window.location.replace(destination);
})();
17 changes: 9 additions & 8 deletions js/script.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,8 @@ document.addEventListener('DOMContentLoaded', () => {
const wholeTermPattern = (term) => `(?<![a-z0-9])${term}(?![a-z0-9])`;

const getSectionLabel = (url) => {
if (url === 'index.html') return 'Home';
const section = url.split('/')[1] || '';
if (url === '/' || url === 'index.html') return 'Home';
const section = url.replace(/^\/?html\//, '').replace(/^\//, '').split('/')[0].replace(/\.html$/, '');
return {
about: 'About',
conference: 'Conference',
Expand Down Expand Up @@ -443,7 +443,7 @@ document.addEventListener('DOMContentLoaded', () => {
section.textContent = page.section;
const path = document.createElement('span');
path.className = 'search-result-path';
path.textContent = page.url === 'index.html' ? 'imageomics.org' : page.url.replace(/^html\//, '').replace(/\.html$/, '');
path.textContent = page.url === '/' || page.url === 'index.html' ? 'imageomics.org' : page.url.replace(/^html\//, '').replace(/\.html$/, '');
meta.append(section, path);

const title = document.createElement('div');
Expand Down Expand Up @@ -521,7 +521,7 @@ document.addEventListener('DOMContentLoaded', () => {
links[activeResultIndex >= 0 ? activeResultIndex : 0].click();
} else if (searchBar.value.trim()) {
window.clearTimeout(searchTimer);
const target = new URL('html/search.html', siteRootUrl);
const target = new URL(window.ImageomicsUrls ? 'search/' : 'html/search.html', siteRootUrl);
target.searchParams.set('q', searchBar.value.trim());
window.location.assign(target.href);
} else {
Expand Down Expand Up @@ -821,12 +821,13 @@ document.addEventListener('DOMContentLoaded', () => {
if (!navMenu) return;

const currentUrl = new URL(window.location.href);
const currentPath = currentUrl.pathname.replace(/\/index\.html$/, '/');
const normalizeNavPath = (pathname) => pathname.replace(/^\/html\//, '/').replace(/\/index\.html$/, '/').replace(/\.html$/, '/');
const currentPath = normalizeNavPath(currentUrl.pathname);
const links = navMenu.querySelectorAll('a[href]');

const getLinkPath = (link) => {
const linkUrl = new URL(link.getAttribute('href'), window.location.href);
return linkUrl.pathname.replace(/\/index\.html$/, '/');
return normalizeNavPath(linkUrl.pathname);
};

links.forEach((link) => {
Expand All @@ -843,7 +844,7 @@ document.addEventListener('DOMContentLoaded', () => {
}
});

const sectionMatch = currentPath.match(/\/html\/(about|research|tools-resources|events|news|conference)(?:\/|\.html$)/);
const sectionMatch = currentPath.match(/^\/(about|research|tools-resources|events|news|conference)\//);
if (!sectionMatch) return;

const section = sectionMatch[1] === 'conference' ? 'events' : sectionMatch[1];
Expand All @@ -858,7 +859,7 @@ document.addEventListener('DOMContentLoaded', () => {
return;
}

const sectionIndexPath = `/html/${section}.html`;
const sectionIndexPath = `/${section}/`;
const sectionLink = Array.from(links).find((link) => getLinkPath(link).endsWith(sectionIndexPath));
if (sectionLink) {
sectionLink.classList.add('is-current');
Expand Down
27 changes: 27 additions & 0 deletions js/site-urls.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
// Shared by Node build tools and browser code; no runtime dependencies.
(function (root) {
'use strict';
function cleanPath(pathname) {
if (pathname.startsWith('/html/components/')) return pathname;
const page = pathname.replace(/^\/html\//, '/');
if (page.endsWith('/index.html')) return page.slice(0, -10);
if (page.endsWith('.html')) return page.slice(0, -5) + '/';
return page;
}
function page(value) {
if (!value || /^(?:[a-z][a-z\d+.-]*:|\/\/|#)/i.test(value)) return value;
const url = new URL(value, 'https://imageomics.org/html/');
return cleanPath(url.pathname) + url.search + url.hash;
}
function normalizeIndex(location) {
if (location.pathname.endsWith('/index.html')) {
location.replace(location.pathname.slice(0, -10) + location.search + location.hash);
}
}
const api = { cleanPath, page, normalizeIndex };
if (typeof module !== 'undefined' && module.exports) module.exports = api;
else {
root.ImageomicsUrls = api;
normalizeIndex(root.location);
}
})(typeof window === 'undefined' ? globalThis : window);
6 changes: 4 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
{
"private": true,
"scripts": {
"build": "npm run build:search",
"build": "node scripts/build-site.mjs && node scripts/build-search-index.mjs _site/data/search-index.json",
"build:search": "node scripts/build-search-index.mjs",
"validate:events": "node scripts/validate-events.mjs"
"validate:events": "node scripts/validate-events.mjs",
"validate:urls": "node scripts/validate-site.mjs",
"test:urls": "node --test scripts/clean-urls.test.mjs"
}
}
16 changes: 11 additions & 5 deletions scripts/build-search-index.mjs
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
import { readdir, readFile, writeFile } from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { readRoutes, origin as siteOrigin } from './site-routes.mjs';

const projectRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const outputPath = path.join(projectRoot, 'data', 'search-index.json');
const outputPath = process.argv[2] ? path.resolve(process.argv[2]) : path.join(projectRoot, 'data', 'search-index.json');
const cleanUrls = Boolean(process.argv[2]);
const routes = await readRoutes();
const canonicalSources = new Map([...routes.values()].filter((route) => !route.alias).map((route) => [route.url, route.source.slice(1)]));
const structuredContentPaths = [
path.join(projectRoot, 'data', 'events.json'),
path.join(projectRoot, 'data', 'news.json')
Expand Down Expand Up @@ -110,19 +114,20 @@ for (const filePath of htmlFiles.sort()) {
const relativePath = path.relative(projectRoot, filePath).split(path.sep).join('/');
const html = await readFile(filePath, 'utf8');
markupByUrl.set(relativePath, html);
if (excludedPaths.has(relativePath)) continue;
if (excludedPaths.has(relativePath) || routes.get('/' + relativePath)?.alias) continue;

documents.push(extractDocument(html, relativePath));
}

const siteOrigin = 'https://imageomics.org';
function resolvePageUrl(value, sourcePath) {
try {
const url = new URL(decodeEntities(value), `${siteOrigin}/${sourcePath}`);
if (url.origin !== siteOrigin) return null;
let pagePath = decodeURIComponent(url.pathname).replace(/^\/+/, '');
if (!pagePath || pagePath.endsWith('/')) pagePath += 'index.html';
return markupByUrl.has(pagePath) ? pagePath : null;
const route = routes.get('/' + pagePath);
const clean = route ? route.target : url.pathname;
return canonicalSources.get(clean) || (markupByUrl.has(pagePath) ? pagePath : null);
} catch {
return null;
}
Expand Down Expand Up @@ -176,6 +181,7 @@ while (pending.length) {
pending.push(...(listingLinks.get(pagePath) || []));
}

const linkedDocuments = documents.filter((document) => reachable.has(document.url));
const linkedDocuments = documents.filter((document) => reachable.has(document.url))
.map((document) => ({ ...document, url: cleanUrls ? routes.get('/' + document.url).target : document.url }));
await writeFile(outputPath, `${JSON.stringify(linkedDocuments)}\n`, 'utf8');
console.log(`Indexed ${linkedDocuments.length} linked HTML pages in ${path.relative(projectRoot, outputPath)}; excluded ${documents.length - linkedDocuments.length} unlinked pages.`);
Loading
Loading