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 | 24x 24x 139x 138x 139x 139x 139x 148x 139x 139x 139x 37x 37x 711x 711x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 24x 34x 34x 136x 136x 136x 136x 34x 34x 34x 34x 37x 37x 148x 139x 148x 37x 34x 136x 136x 136x | /**
* @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>`
: '';
// Server-side rendered accessibility table — always present when a radar
// is emitted, so screen readers (and users without JavaScript) still get
// the numeric impact distribution that the canvas visualises. The table
// is hidden from sighted users by default via the `.sr-only` utility;
// it becomes visible when CSS hides the canvas on narrow viewports.
const fallbackTable = radarConfig
? renderSwotFallbackTable(data, lbl, titleText)
: '';
const html = `<section class="swot-analysis" aria-label="${escapeHtml(titleText)}">
<h2>${escapeHtml(titleText)}</h2>
${subjectLine} <div class="swot-grid">
${grid}
</div>${radarBlock}${fallbackTable}${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,
};
/**
* Render a server-side accessibility fallback table matching the radar's
* data. Each quadrant contributes one row summarising item count and
* weighted impact score. The table is emitted with `class="swot-radar-fallback sr-only"`
* so it's reachable by assistive technology and becomes visible via CSS
* on narrow viewports (where the radar is hidden because labels overlap).
*/
function renderSwotFallbackTable(
data: SwotData,
lbl: (key: string) => string,
titleText: string,
): string {
const rows = [
{ label: lbl('swotStrengths'), entries: data.strengths },
{ label: lbl('swotWeaknesses'), entries: data.weaknesses },
{ label: lbl('swotOpportunities'), entries: data.opportunities },
{ label: lbl('swotThreats'), entries: data.threats },
];
const bodyRows = rows.map(r => {
const entries = r.entries ?? [];
const count = entries.length;
const score = entries.reduce((sum, e) => sum + (IMPACT_WEIGHTS[e.impact ?? 'medium'] ?? 2), 0);
return ` <tr>
<th scope="row">${escapeHtml(r.label)}</th>
<td>${count}</td>
<td>${score}</td>
</tr>`;
}).join('\n');
// Header labels: localise count/score via the impact label strings where
// possible; fall back to English headings when keys are missing.
const countHead = lbl('swotItemsCount') || 'Items';
const scoreHead = lbl('swotImpactScore') || 'Impact score';
const quadrantHead = lbl('swotQuadrant') || 'Quadrant';
return `\n <table class="swot-radar-fallback sr-only">
<caption>${escapeHtml(titleText)} — ${escapeHtml(countHead)} / ${escapeHtml(scoreHead)}</caption>
<thead>
<tr>
<th scope="col">${escapeHtml(quadrantHead)}</th>
<th scope="col">${escapeHtml(countHead)}</th>
<th scope="col">${escapeHtml(scoreHead)}</th>
</tr>
</thead>
<tbody>
${bodyRows}
</tbody>
</table>`;
}
/**
* 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 } },
},
},
},
};
}
|