All files / templates article-template.ts

100% Statements 48/48
100% Branches 20/20
100% Functions 9/9
100% Lines 47/47

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306                                                11x     11x                       352x 4x     348x 4x     344x 344x   344x 4816x 4816x 4816x 4816x 4816x 4816x                       1376x                         344x 4816x 4816x 4816x 4816x 4816x                                           352x   352x 352x     352x           352x 352x 352x 352x 352x 352x 352x 352x 352x     352x 352x 449x 352x     352x                                             352x                                                                                                                                                                                                                                                       344x 271x     73x             146x 146x 146x                
// SPDX-FileCopyrightText: 2024-2026 Hack23 AB
// SPDX-License-Identifier: Apache-2.0
 
/**
 * @module Templates/ArticleTemplate
 * @description Generates HTML templates for news articles with proper structure and metadata
 */
 
import type { ArticleOptions, ArticleSource, ArticleCategoryLabels } from '../types/index.js';
import {
  ALL_LANGUAGES,
  LANGUAGE_FLAGS,
  LANGUAGE_NAMES,
  ARTICLE_TYPE_LABELS,
  READ_TIME_LABELS,
  BACK_TO_NEWS_LABELS,
  ARTICLE_NAV_LABELS,
  SKIP_LINK_TEXTS,
  getLocalizedString,
  getTextDirection,
} from '../constants/languages.js';
import { escapeHTML, isSafeURL } from '../utils/file-utils.js';
 
/** Pattern for valid article dates (YYYY-MM-DD) */
const DATE_PATTERN = /^\d{4}-\d{2}-\d{2}$/u;
 
/** Pattern for valid article slugs (lowercase letters, digits, hyphens) */
const SLUG_PATTERN = /^[a-z0-9-]+$/u;
 
/**
 * Build the article language switcher nav HTML.
 * Links to the same article in all 14 languages using the filename pattern {date}-{slug}-{lang}.html.
 *
 * @param date - Article date (YYYY-MM-DD)
 * @param slug - Article slug
 * @param currentLang - Active language code
 * @returns HTML string
 */
function buildArticleLangSwitcher(date: string, slug: string, currentLang: string): string {
  if (!DATE_PATTERN.test(date)) {
    throw new Error(`Invalid article date format: "${date}"`);
  }
 
  if (!SLUG_PATTERN.test(slug)) {
    throw new Error(`Invalid article slug format: "${slug}"`);
  }
 
  const safeDate = escapeHTML(date);
  const safeSlug = escapeHTML(slug);
 
  return ALL_LANGUAGES.map((code) => {
    const flag = getLocalizedString(LANGUAGE_FLAGS, code);
    const name = getLocalizedString(LANGUAGE_NAMES, code);
    const active = code === currentLang ? ' active' : '';
    const href = `${safeDate}-${safeSlug}-${code}.html`;
    const safeTitle = escapeHTML(name);
    return `<a href="${href}" class="lang-link${active}" hreflang="${code}" lang="${code}" title="${safeTitle}">${flag} ${code.toUpperCase()}</a>`;
  }).join('\n        ');
}
 
/**
 * Build a single footer section with title and content.
 *
 * @param title - Section heading text
 * @param content - Inner HTML content
 * @returns HTML string for one footer section
 */
function buildFooterSection(title: string, content: string): string {
  return `<div class="footer-section">
        <h3>${title}</h3>
        ${content}
      </div>`;
}
 
/**
 * Build the language grid for the article footer.
 *
 * @param currentLang - Active language code
 * @returns HTML string for the language grid
 */
function buildArticleFooterLanguageGrid(currentLang: string): string {
  return ALL_LANGUAGES.map((code) => {
    const flag = getLocalizedString(LANGUAGE_FLAGS, code);
    const safeName = escapeHTML(getLocalizedString(LANGUAGE_NAMES, code));
    const href = code === 'en' ? '../index.html' : `../index-${code}.html`;
    const active = code === currentLang ? ' class="active"' : '';
    return `<a href="${href}"${active} hreflang="${code}">${flag} ${safeName}</a>`;
  }).join('\n            ');
}
 
/**
 * Generate complete HTML for a news article
 *
 * @param options - Article generation options
 * @returns Complete HTML document string
 */
export function generateArticleHTML(options: ArticleOptions): string {
  const {
    slug,
    title,
    subtitle,
    date,
    category,
    readTime,
    lang,
    content,
    keywords = [],
    sources = [],
  } = options;
 
  const dir = getTextDirection(lang);
  const year = new Date().getFullYear();
 
  // Format date for display
  const displayDate = new Date(date).toLocaleDateString(lang, {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
  });
 
  const languageName = getLocalizedString(LANGUAGE_NAMES, lang);
  const categoryLabels = getLocalizedString(ARTICLE_TYPE_LABELS, lang) as ArticleCategoryLabels;
  const categoryLabel = categoryLabels[category] ?? category;
  const readTimeFormatter = getLocalizedString(READ_TIME_LABELS, lang);
  const readTimeLabel = readTimeFormatter(readTime);
  const backLabel = getLocalizedString(BACK_TO_NEWS_LABELS, lang);
  const articleNavLabel = getLocalizedString(ARTICLE_NAV_LABELS, lang);
  const skipLinkText = getLocalizedString(SKIP_LINK_TEXTS, lang);
  const indexHref = lang === 'en' ? '../index.html' : `../index-${lang}.html`;
 
  // Escape values for safe HTML embedding
  const safeTitle = escapeHTML(title);
  const safeSubtitle = escapeHTML(subtitle);
  const safeKeywords = keywords.map((k) => escapeHTML(k)).join(', ');
  const safeCategoryLabel = escapeHTML(categoryLabel);
 
  // Build JSON-LD as object for safe serialization
  const jsonLd = JSON.stringify(
    {
      '@context': 'https://schema.org',
      '@type': 'NewsArticle',
      headline: title,
      description: subtitle,
      datePublished: date,
      inLanguage: lang,
      author: {
        '@type': 'Organization',
        name: 'EU Parliament Monitor',
      },
      publisher: {
        '@type': 'Organization',
        name: 'EU Parliament Monitor',
        url: 'https://euparliamentmonitor.com',
      },
      keywords: keywords.join(', '),
    },
    null,
    4
  );
 
  return `<!DOCTYPE html>
<html lang="${lang}" dir="${dir}">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-Content-Type-Options" content="nosniff">
  <meta name="referrer" content="no-referrer">
  <title>${safeTitle} | EU Parliament Monitor</title>
  <meta name="description" content="${safeSubtitle}">
  <meta name="keywords" content="${safeKeywords}">
  <meta name="author" content="EU Parliament Monitor">
  <meta name="date" content="${date}">
  <meta name="article:published_time" content="${date}">
  <meta name="article:author" content="EU Parliament Monitor">
  
  <!-- Open Graph -->
  <meta property="og:type" content="article">
  <meta property="og:title" content="${safeTitle}">
  <meta property="og:description" content="${safeSubtitle}">
  <meta property="og:site_name" content="EU Parliament Monitor">
  <meta property="og:locale" content="${lang}">
  
  <!-- Twitter Card -->
  <meta name="twitter:card" content="summary_large_image">
  <meta name="twitter:title" content="${safeTitle}">
  <meta name="twitter:description" content="${safeSubtitle}">
  
  <link rel="stylesheet" href="../styles.css">
  
  <!-- Schema.org structured data -->
  <script type="application/ld+json">
  ${jsonLd}
  </script>
</head>
<body>
  <div class="reading-progress" aria-hidden="true"></div>
  <a href="#main" class="skip-link">${skipLinkText}</a>
 
  <header class="site-header" role="banner">
    <div class="site-header__inner">
      <a href="${indexHref}" class="site-header__brand" aria-label="EU Parliament Monitor">
        <span class="site-header__flag" aria-hidden="true">🇪🇺</span>
        <span>
          <span class="site-header__title">EU Parliament Monitor</span>
          <span class="site-header__subtitle">European Parliament Intelligence</span>
        </span>
      </a>
    </div>
  </header>
 
  <nav class="language-switcher" role="navigation" aria-label="Language selection">
    ${buildArticleLangSwitcher(date, slug, lang)}
  </nav>
 
  <nav class="article-top-nav" aria-label="${escapeHTML(articleNavLabel)}">
    <a href="${indexHref}" class="back-to-news">${backLabel}</a>
  </nav>
 
  <main id="main" class="site-main">
  <article class="news-article" lang="${lang}">
    <header class="article-header">
      <div class="article-meta">
        <span class="article-type">${safeCategoryLabel}</span>
        <span class="article-date">${displayDate}</span>
        <span class="article-read-time">${readTimeLabel}</span>
        <span class="article-lang">${languageName}</span>
      </div>
      <h1>${safeTitle}</h1>
      <p class="article-subtitle">${safeSubtitle}</p>
    </header>
    
    ${content}
    
    ${renderSourcesSection(sources)}
    
    <nav class="article-nav" aria-label="${escapeHTML(articleNavLabel)}">
      <a href="${indexHref}" class="back-to-news">${backLabel}</a>
    </nav>
  </article>
  </main>
 
  <footer class="site-footer" role="contentinfo">
    <div class="footer-content">
      ${buildFooterSection('About EU Parliament Monitor', '<p>European Parliament Intelligence Platform — monitoring political activity with systematic transparency. Powered by European Parliament open data.</p>')}
      ${buildFooterSection(
        'Quick Links',
        `<ul>
          <li><a href="../index.html">Home</a></li>
          <li><a href="https://github.com/Hack23/euparliamentmonitor">GitHub Repository</a></li>
          <li><a href="https://github.com/Hack23/euparliamentmonitor/blob/main/LICENSE">Apache-2.0 License</a></li>
          <li><a href="https://www.europarl.europa.eu/">European Parliament</a></li>
        </ul>`
      )}
      ${buildFooterSection(
        'Built by Hack23 AB',
        `<ul>
          <li><a href="https://hack23.com">hack23.com</a></li>
          <li><a href="https://www.linkedin.com/company/hack23">LinkedIn</a></li>
          <li><a href="https://github.com/Hack23/ISMS-PUBLIC">Security &amp; Privacy Policy</a></li>
          <li><a href="mailto:james@hack23.com">Contact</a></li>
        </ul>`
      )}
      ${buildFooterSection(
        'Languages',
        `<div class="language-grid">
          ${buildArticleFooterLanguageGrid(lang)}
        </div>`
      )}
    </div>
    <div class="footer-bottom">
      <p>&copy; 2008-${year} <a href="https://hack23.com">Hack23 AB</a> (Org.nr 5595347807) | Gothenburg, Sweden</p>
    </div>
  </footer>
</body>
</html>`;
}
 
/**
 * Render the sources section if sources are provided
 *
 * @param sources - Article source references
 * @returns HTML string for sources section or empty string
 */
function renderSourcesSection(sources: ArticleSource[]): string {
  if (sources.length === 0) {
    return '';
  }
 
  return `
    <footer class="article-footer">
      <section class="article-sources">
        <h2>Sources</h2>
        <ul>
          ${sources
            .map((source) => {
              const safeSourceTitle = escapeHTML(source.title);
              const href = isSafeURL(source.url) ? escapeHTML(source.url) : '#';
              return `<li><a href="${href}" target="_blank" rel="noopener noreferrer">${safeSourceTitle}</a></li>`;
            })
            .join('\n          ')}
        </ul>
      </section>
    </footer>
    `;
}