All files / scripts/data-transformers/content-generators swot-section.ts

100% Statements 42/42
87.5% Branches 28/32
100% Functions 12/12
100% Lines 36/36

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                                            22x           22x             126x 125x 126x 126x 126x               132x 126x 126x   126x                                                                                               33x   33x 424x 424x     33x 33x 33x       33x             33x 33x         33x 33x       33x             33x                       22x                           33x             33x 132x 126x       132x 33x   31x     124x             124x 124x                                            
/**
 * @module data-transformers/content-generators/swot-section
 * @description Generates an embeddable SWOT analysis HTML section that can be
 * injected into any article type via the `TemplateSection` extensibility pattern.
 *
 * Agentic workflows call `generateSwotSection()` with structured data sourced
 * from MCP servers or CIA-data and append the returned `TemplateSection` to the
 * article's `sections` array.
 *
 * @author Hack23 AB
 * @license Apache-2.0
 */
 
import { escapeHtml } from '../../html-utils.js';
import type { Language } from '../../types/language.js';
import type { TemplateSection, SwotData, SwotEntry, SwotImpact } from '../../types/article.js';
import { L } from '../helpers.js';
 
// ---------------------------------------------------------------------------
// Impact badge helper
// ---------------------------------------------------------------------------
 
const IMPACT_CLASSES: Readonly<Record<SwotImpact, string>> = {
  high: 'swot-impact--high',
  medium: 'swot-impact--medium',
  low: 'swot-impact--low',
};
 
const IMPACT_LABEL_KEYS: Readonly<Record<SwotImpact, string>> = {
  high: 'swotImpactHigh',
  medium: 'swotImpactMedium',
  low: 'swotImpactLow',
};
 
function impactBadge(impact: SwotImpact | undefined, lbl: (key: string) => string): string {
  if (!impact) return '';
  const impactClass = IMPACT_CLASSES[impact] ?? IMPACT_CLASSES.medium;
  const labelKey = IMPACT_LABEL_KEYS[impact] ?? IMPACT_LABEL_KEYS.medium;
  const label = lbl(labelKey);
  return ` <span class="swot-impact ${impactClass}">[${escapeHtml(label)}]</span>`;
}
 
// ---------------------------------------------------------------------------
// Quadrant renderer
// ---------------------------------------------------------------------------
 
function renderQuadrant(heading: string, entries: SwotEntry[], cssClass: string, lbl: (key: string) => string): string {
  if (!entries || entries.length === 0) return '';
  const items = entries
    .map(e => `      <li>${escapeHtml(e.text)}${impactBadge(e.impact, lbl)}</li>`)
    .join('\n');
  return `    <div class="swot-quadrant ${cssClass}">
      <h3>${escapeHtml(heading)}</h3>
      <ul>
${items}
      </ul>
    </div>`;
}
 
// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------
 
/**
 * Options for the SWOT section generator.
 */
export interface SwotSectionOptions {
  /** Structured SWOT data */
  data: SwotData;
  /** Target language for labels */
  lang: Language | string;
}
 
/**
 * Generate an embeddable SWOT analysis section.
 *
 * Returns a `TemplateSection` that can be appended to `ArticleData.sections`.
 * The section renders as a 2×2 CSS Grid matrix styled to match the existing
 * cyberpunk article theme.
 *
 * @example
 * ```ts
 * import { generateSwotSection } from './content-generators/swot-section.js';
 *
 * const section = generateSwotSection({
 *   data: {
 *     subject: 'Socialdemokraterna (S)',
 *     strengths: [{ text: 'Largest party', impact: 'high' }],
 *     weaknesses: [{ text: 'Internal divisions', impact: 'medium' }],
 *     opportunities: [{ text: 'Rising voter concern on welfare', impact: 'high' }],
 *     threats: [{ text: 'Coalition fragmentation', impact: 'medium' }],
 *   },
 *   lang: 'en',
 * });
 *
 * articleData.sections = [...(articleData.sections ?? []), section];
 * ```
 */
export function generateSwotSection(opts: SwotSectionOptions): TemplateSection {
  const { data, lang } = opts;
 
  const lbl = (key: string): string => {
    const val = L(lang, key);
    return typeof val === 'string' ? val : key;
  };
 
  const titleText = lbl('swotAnalysis');
  const trimmedSubject = (data.subject ?? '').trim();
  const subjectLine = trimmedSubject
    ? `    <p class="swot-subject"><strong>${escapeHtml(trimmedSubject)}</strong></p>\n`
    : '';
 
  const grid = [
    renderQuadrant(lbl('swotStrengths'), data.strengths, 'swot-strengths', lbl),
    renderQuadrant(lbl('swotWeaknesses'), data.weaknesses, 'swot-weaknesses', lbl),
    renderQuadrant(lbl('swotOpportunities'), data.opportunities, 'swot-opportunities', lbl),
    renderQuadrant(lbl('swotThreats'), data.threats, 'swot-threats', lbl),
  ].filter(Boolean).join('\n');
 
  const rawContext = data.context?.trim();
  const contextBlock = rawContext
    ? `\n    <p class="swot-context"><em>${escapeHtml(lbl('swotContext'))}:</em> ${escapeHtml(rawContext)}</p>`
    : '';
 
  // Generate SWOT radar chart config for impact visualization
  const radarConfig = buildSwotRadarConfig(data, lbl);
  const radarBlock = radarConfig
    ? `\n    <div class="swot-radar-wrapper">\n      <canvas class="swot-radar" role="img" aria-label="${escapeHtml(titleText)}" data-chart-config="${escapeHtml(JSON.stringify(radarConfig))}"></canvas>\n    </div>`
    : '';
 
  const html = `<section class="swot-analysis" aria-label="${escapeHtml(titleText)}">
    <h2>${escapeHtml(titleText)}</h2>
${subjectLine}    <div class="swot-grid">
${grid}
    </div>${radarBlock}${contextBlock}
  </section>`;
 
  return {
    id: 'swot-analysis',
    html,
    className: 'swot-analysis-section',
  };
}
 
// ---------------------------------------------------------------------------
// SWOT Radar chart builder
// ---------------------------------------------------------------------------
 
/** Impact weight mapping for radar visualization */
const IMPACT_WEIGHTS: Readonly<Record<string, number>> = {
  high: 3,
  medium: 2,
  low: 1,
};
 
/**
 * Build a Chart.js radar config summarising SWOT impact distribution.
 * Returns null when all quadrants are empty.
 */
function buildSwotRadarConfig(
  data: SwotData,
  lbl: (key: string) => string,
): Record<string, unknown> | null {
  const quadrants = [
    { entries: data.strengths, label: lbl('swotStrengths'), color: '#83cf39' },
    { entries: data.weaknesses, label: lbl('swotWeaknesses'), color: '#ff006e' },
    { entries: data.opportunities, label: lbl('swotOpportunities'), color: '#00d9ff' },
    { entries: data.threats, label: lbl('swotThreats'), color: '#ffbe0b' },
  ];
 
  const scores = quadrants.map(q => {
    if (!q.entries || q.entries.length === 0) return 0;
    return q.entries.reduce((sum, e) => sum + (IMPACT_WEIGHTS[e.impact ?? 'medium'] ?? 2), 0);
  });
 
  // Only render radar when there's meaningful data in at least 2 quadrants
  const nonZero = scores.filter(s => s > 0).length;
  if (nonZero < 2) return null;
 
  return {
    type: 'radar',
    data: {
      labels: quadrants.map(q => q.label),
      datasets: [{
        label: data.subject ?? 'SWOT',
        data: scores,
        backgroundColor: 'rgba(0, 217, 255, 0.15)',
        borderColor: '#00d9ff',
        borderWidth: 2,
        pointBackgroundColor: quadrants.map(q => q.color),
        pointBorderColor: quadrants.map(q => q.color),
        pointRadius: 5,
      }],
    },
    options: {
      responsive: true,
      plugins: {
        title: { display: false },
        legend: { labels: { color: '#e0e0e0' } },
        tooltip: { backgroundColor: 'rgba(10,14,39,0.95)', titleColor: '#00d9ff', bodyColor: '#e0e0e0', borderColor: '#00d9ff', borderWidth: 1 },
      },
      scales: {
        r: {
          grid: { color: 'rgba(255,255,255,0.1)' },
          angleLines: { color: 'rgba(255,255,255,0.1)' },
          ticks: { color: '#b0b0b0', backdropColor: 'transparent' },
          pointLabels: { color: '#e0e0e0', font: { size: 12 } },
        },
      },
    },
  };
}