All files / scripts/article-template template.ts

100% Statements 16/16
98.07% Branches 51/52
100% Functions 5/5
100% Lines 16/16

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 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354                                                                                                              663x     663x   663x 663x 663x     663x             663x                   663x     663x 663x 663x   663x                                                     1091x                               9282x                                                                                                                                                                   1091x                                                                                                                                                                                                                                 42x                                                    
/**
 * @module article-template/template
 * @description Main article HTML template generator producing complete
 * HTML5 documents with Schema.org structured data, Open Graph / Twitter
 * Card metadata, hreflang tags, and 14-language support.
 *
 * @author Hack23 AB
 * @license Apache-2.0
 */
 
import { escapeHtml } from '../html-utils.js';
import { CONTENT_LABELS } from '../data-transformers.js';
import type { Language } from '../types/language.js';
import type { ArticleData, EventGridItem, WatchPoint, TemplateSection } from '../types/article.js';
import { SITE_TAGLINE, OG_LOCALE_MAP, TYPE_LABELS, ALL_LANG_CODES } from './constants.js';
import { getStyleClass } from './registry.js';
import { ARTICLE_TYPE_NAMES } from './types.js';
import {
  getBreadcrumbName,
  getFooterLabel,
  getNewsIndexFilename,
  sanitizeArticleBody,
  fixHtmlNesting,
  formatDate,
  generateEventCalendar,
  generateWatchSection,
  generateArticleLanguageSwitcher,
  generateSiteFooter,
  hreflangCode,
} from './helpers.js';
 
/**
 * Generate complete article HTML document.
 *
 * @param data - Article data including title, subtitle, content, events, watchPoints, etc.
 * @returns Complete HTML5 document string
 */
export function generateArticleHTML(data: ArticleData): string {
  const {
    slug,
    title,
    subtitle,
    date,
    type,
    articleType,
    readTime = '5 min read',
    lang = 'en',
    locale,
    content,
    events = [],
    watchPoints = [],
    sources = [],
    keywords = [],
    tags = [],
    sections = [],
  } = data;
 
  // Use proper OG locale for the language
  const ogLocale: string = locale || OG_LOCALE_MAP[lang] || 'en_US';
 
  const dateObj: Date = new Date(date);
  const formattedDate: string = formatDate(dateObj, lang);
  const isoDate: string = dateObj.toISOString().split('T')[0] ?? '';
 
  // Fix invalid HTML nesting once so both the rendered body and JSON-LD are consistent
  const fixedContent: string = fixHtmlNesting(content);
 
  // Fall back to English labels if language not supported.
  // When articleType is set, prefer the per-type localized name from
  // ARTICLE_TYPE_NAMES (e.g. "Propositioner") over the category label
  // from TYPE_LABELS (e.g. "Analysis").  Fall back to TYPE_LABELS when
  // articleType is omitted or has no entry.
  const typeLabel: string = (articleType && ARTICLE_TYPE_NAMES[articleType]?.[lang])
    || (articleType && ARTICLE_TYPE_NAMES[articleType]?.['en'])
    || TYPE_LABELS[lang]?.[type]
    || TYPE_LABELS.en[type]
    || 'News';
 
  // Derive the per-type CSS class from the registry (e.g. 'article-type-propositions')
  // Only apply when articleType is explicitly set — ArticleCategory values are not
  // valid ArticleType keys, so falling back to `type` would silently resolve to
  // the 'breaking' default.  When omitted, keep the base `.news-article` styling.
  const articleTypeClass: string = articleType ? ` ${getStyleClass(articleType)}` : '';
 
  // Generate hreflang tags for all available language variants
  const isRTL: boolean = lang === 'ar' || lang === 'he';
  const dirAttr: string = isRTL ? ' dir="rtl"' : '';
  const baseSlug: string = slug.replace(`-${lang}.html`, '');
 
  return `<!DOCTYPE html>
<html lang="${hreflangCode(lang)}"${dirAttr}>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="Content-Security-Policy" content="default-src 'self' https:; script-src 'self' 'unsafe-inline' https:; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data: https:; connect-src 'self' https:; base-uri 'self'; form-action 'self'">
  <title>${escapeHtml(title)}</title>
  <meta name="description" content="${escapeHtml(subtitle).substring(0, 160)}">
  <meta name="keywords" content="${keywords.join(', ')}">
  <meta name="author" content="James Pether Sörling, CISSP, CISM">
  <link rel="canonical" href="https://riksdagsmonitor.com/news/${slug}">
  
  <!-- Open Graph / Social Media -->
  <meta property="og:title" content="${escapeHtml(title)}">
  <meta property="og:description" content="${escapeHtml(subtitle).substring(0, 200)}">
  <meta property="og:type" content="article">
  <meta property="og:url" content="https://riksdagsmonitor.com/news/${slug}">
  <meta property="og:image" content="https://riksdagsmonitor.com/images/og-image-news.webp">
  <meta property="og:image:width" content="1200">
  <meta property="og:image:height" content="630">
  <meta property="og:image:alt" content="Riksdagsmonitor - Swedish Parliament Intelligence">
  <meta property="og:locale" content="${ogLocale}">
  <meta property="og:site_name" content="Riksdagsmonitor - Swedish Parliament Intelligence">
  <meta property="article:published_time" content="${dateObj.toISOString()}">
  <meta property="article:modified_time" content="${dateObj.toISOString()}">
  <meta property="article:author" content="James Pether Sörling">
  <meta property="article:section" content="${typeLabel}">
${tags.map(tag => `  <meta property="article:tag" content="${escapeHtml(tag)}">`).join('\n')}
  
  <!-- Twitter Card -->
  <meta name="twitter:card" content="summary_large_image">
  <meta name="twitter:title" content="${escapeHtml(title)}">
  <meta name="twitter:description" content="${escapeHtml(subtitle).substring(0, 200)}">
  <meta name="twitter:image" content="https://riksdagsmonitor.com/images/og-image-news.webp">
  <meta name="twitter:image:alt" content="Riksdagsmonitor - Swedish Parliament Intelligence">
  <meta name="twitter:site" content="@riksdagsmonitor">
  <meta name="twitter:creator" content="@jamessorling">
  <meta name="twitter:label1" content="${CONTENT_LABELS[lang]?.twitterLabel1 ?? CONTENT_LABELS.en.twitterLabel1}">
  <meta name="twitter:data1" content="${readTime}">
  <meta name="twitter:label2" content="${CONTENT_LABELS[lang]?.twitterLabel2 ?? CONTENT_LABELS.en.twitterLabel2}">
  <meta name="twitter:data2" content="${typeLabel}">
  
  <!-- Hreflang for language alternatives -->
${ALL_LANG_CODES.map(l => `  <link rel="alternate" hreflang="${hreflangCode(l)}" href="https://riksdagsmonitor.com/news/${baseSlug}-${l}.html">`).join('\n')}
  <link rel="alternate" hreflang="x-default" href="https://riksdagsmonitor.com/news/${baseSlug}-en.html">
  
  <!-- Favicons -->
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16.png">
  <link rel="icon" type="image/png" sizes="96x96" href="/images/favicon-96x96.png">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon.png">
  <link rel="icon" href="/favicon.ico" sizes="48x48">
  <link rel="manifest" href="/site.webmanifest">
  <meta name="theme-color" content="#0a0e27">
  
  <!-- Google Fonts -->
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
  <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Orbitron:wght@500;600;700&family=Share+Tech+Mono&display=swap" media="print" onload="this.media='all'">
  <noscript><link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Orbitron:wght@500;600;700&family=Share+Tech+Mono&display=swap"></noscript>
  
  <!-- Main stylesheet — includes all article styles + component/theme imports -->
  <link rel="stylesheet" href="../styles.css">
  
  <!-- Anti-flash: apply saved theme before first paint -->
  <script>(function(){var key='riksdagsmonitor-theme';var t=null;try{t=localStorage.getItem(key);}catch(e){}if(t!=='dark'&&t!=='light'){if(t!==null){try{localStorage.removeItem(key);}catch(e){}}t=(window.matchMedia&&window.matchMedia('(prefers-color-scheme: dark)').matches)?'dark':'light';}document.documentElement.setAttribute('data-theme',t);}());</script>
  
  <!-- Schema.org NewsArticle structured data -->
  <script type="application/ld+json">
  {
    "@context": "https://schema.org",
    "@type": "NewsArticle",
    "headline": "${escapeHtml(title)}",
    "alternativeHeadline": "${escapeHtml(subtitle).substring(0, 100)}",
    "description": "${escapeHtml(subtitle).substring(0, 200)}",
    "datePublished": "${dateObj.toISOString()}",
    "dateModified": "${dateObj.toISOString()}",
    "author": {
      "@type": "Person",
      "name": "James Pether Sörling",
      "jobTitle": "${CONTENT_LABELS[lang]?.jobTitle ?? CONTENT_LABELS.en.jobTitle}",
      "affiliation": {
        "@type": "Organization",
        "name": "Hack23 AB"
      },
      "url": "https://riksdagsmonitor.com"
    },
    "publisher": {
      "@type": "Organization",
      "name": "Riksdagsmonitor",
      "url": "https://riksdagsmonitor.com",
      "logo": {
        "@type": "ImageObject",
        "url": "https://riksdagsmonitor.com/images/android-chrome-512x512.png",
        "width": 512,
        "height": 512
      }
    },
    "image": {
      "@type": "ImageObject",
      "url": "https://riksdagsmonitor.com/images/og-image-news.webp",
      "width": 1200,
      "height": 630
    },
    "articleSection": "${typeLabel}",
    "articleBody": "${sanitizeArticleBody(escapeHtml(fixedContent))}...",
    "wordCount": ${Math.ceil(fixedContent.length / 5)},
    "inLanguage": "${hreflangCode(lang)}",
    "keywords": "${keywords.join(', ')}",
    "about": {
      "@type": "Thing",
      "name": "Swedish Parliament",
      "sameAs": "https://www.wikidata.org/wiki/Q1968818"
    },
    "isAccessibleForFree": true,
    "isPartOf": {
      "@type": "WebSite",
      "name": "Riksdagsmonitor",
      "url": "https://riksdagsmonitor.com"
    },
    "mainEntityOfPage": {
      "@type": "WebPage",
      "@id": "https://riksdagsmonitor.com/news/${slug}"
    }${tags.length > 0 ? `,
    "mentions": [${tags.map(tag => `
      {
        "@type": "Thing",
        "name": "${escapeHtml(tag)}"
      }`).join(',')}
    ]` : ''}
  }
  </script>
  
  <!-- BreadcrumbList structured data -->
  <script type="application/ld+json">
  {
    "@context": "https://schema.org",
    "@type": "BreadcrumbList",
    "itemListElement": [
      {
        "@type": "ListItem",
        "position": 1,
        "name": "${getBreadcrumbName(lang, 'home')}",
        "item": "https://riksdagsmonitor.com/"
      },
      {
        "@type": "ListItem",
        "position": 2,
        "name": "${getBreadcrumbName(lang, 'news')}",
        "item": "https://riksdagsmonitor.com/news/index.html"
      },
      {
        "@type": "ListItem",
        "position": 3,
        "name": "${escapeHtml(title).substring(0, 50)}",
        "item": "https://riksdagsmonitor.com/news/${slug}"
      }
    ]
  }
  </script>
  
  <!-- Organization structured data -->
  <script type="application/ld+json">
  {
    "@context": "https://schema.org",
    "@type": "Organization",
    "name": "Riksdagsmonitor",
    "url": "https://riksdagsmonitor.com",
    "logo": "https://riksdagsmonitor.com/images/android-chrome-512x512.png",
    "description": "${CONTENT_LABELS[lang]?.siteDescription ?? CONTENT_LABELS.en.siteDescription}",
    "foundingDate": "2020",
    "founder": {
      "@type": "Person",
      "name": "James Pether Sörling"
    },
    "sameAs": [
      "https://github.com/Hack23/riksdagsmonitor"
    ],
    "contactPoint": {
      "@type": "ContactPoint",
      "contactType": "Technical Support",
      "url": "https://github.com/Hack23/riksdagsmonitor/issues"
    }
  }
  </script>
  
</head>
<body>
<a href="#main-content" class="skip-link">${getFooterLabel(lang, 'skipToContent')}</a>
<button id="theme-toggle" class="theme-toggle-btn" type="button"
        aria-pressed="false"
        aria-label="${getFooterLabel(lang, 'themeToDark')}"
        title="${getFooterLabel(lang, 'themeToDark')}"
        data-label-dark="${getFooterLabel(lang, 'themeToLight')}"
        data-label-light="${getFooterLabel(lang, 'themeToDark')}">
  <span class="theme-icon" aria-hidden="true">🌙</span>
</button>
${generateArticleLanguageSwitcher(baseSlug, lang)}
 
<div class="article-top-nav">
  <a href="${getNewsIndexFilename(ALL_LANG_CODES.includes(lang as Language) ? lang : 'en')}" class="back-to-news">
    \u2190 ${getFooterLabel(lang, 'backToNews')}
  </a>
</div>
 
<article id="main-content" class="news-article${articleTypeClass}">
  <header class="article-header">
    <div class="hero-banner">
      <img src="../images/riksdagsmonitornews-banner.webp" alt="" class="hero-banner-bg" width="1536" height="1024" loading="eager" aria-hidden="true">
    </div>
    <div class="hero-header-text">
      <h1>${escapeHtml(title)}</h1>
      <div class="site-tagline">${SITE_TAGLINE[lang] || SITE_TAGLINE.en}</div>
    </div>
    <a href="${getNewsIndexFilename(ALL_LANG_CODES.includes(lang as Language) ? lang : 'en')}" aria-label="Riksdagsmonitor News">
      <img src="../images/riksdagsmonitornews-logo.webp" alt="Riksdagsmonitor News" class="article-site-logo" width="100" height="100" loading="eager">
    </a>
    <div class="article-meta">
      <time datetime="${isoDate}">${formattedDate}</time>
      <span class="separator">•</span>
      <span class="type-badge">${typeLabel}</span>
      <span class="separator">•</span>
      <span>${readTime}</span>
    </div>
  </header>
 
${events.length > 0 ? generateEventCalendar(events as ReadonlyArray<EventGridItem>, lang) : ''}
 
  <div class="article-content prose">
    <p class="lede">
      ${escapeHtml(subtitle)}
    </p>
 
${fixedContent}
 
${watchPoints.length > 0 ? generateWatchSection(watchPoints as ReadonlyArray<WatchPoint>, lang) : ''}
 
${(sections as TemplateSection[]).length > 0 ? (sections as TemplateSection[]).map(s => `<div id="${escapeHtml(s.id)}" class="${escapeHtml(s.className ?? 'article-section')}">${s.html}</div>`).join('\n') : ''}
  </div>
 
  <footer class="article-footer">
    <div class="article-sources">
      <h3>${getFooterLabel(lang, 'sourcesTitle')}</h3>
      <p><strong>${getFooterLabel(lang, 'dataSources')}:</strong> ${sources.join(', ')}</p>
      <p><strong>${getFooterLabel(lang, 'generatedBy')}:</strong> ${getFooterLabel(lang, 'generatedByValue')}</p>
      <p><strong>${getFooterLabel(lang, 'analysisTools')}:</strong> ${getFooterLabel(lang, 'analysisToolsValue')}</p>
    </div>
    
    <div class="article-nav">
      <a href="${getNewsIndexFilename(ALL_LANG_CODES.includes(lang as Language) ? lang : 'en')}" class="back-to-news">
        \u2190 ${getFooterLabel(lang, 'backToNews')}
      </a>
    </div>
  </footer>
</article>
 
${generateSiteFooter(lang)}
 
<script type="module" src="../scripts/back-to-top.ts"></script>
<script src="../js/theme-toggle.js"></script>
</body>
</html>`;
}