/** Observable Plot enhancement for existing sourced editorial figures. * The original SVG/HTML bar remains visible if plotting is unavailable. * Read only figures carrying explicit published numbers; never infer data from * drawn path geometry, CSS widths, or editorial prose. */ import {renderSitePlot} from './components/site-plot.mjs'; export function parsePublishedNumber(raw){ const m=String(raw??'').replace(/[₹$,]/g,'').replace(/−/g,'-').match(/-?\d+(?:\.\d+)?/); return m?Number(m[0]):NaN; } export function parseCircleTitle(raw){ const m=String(raw??'').match(/^\s*([^:]+?)\s*:\s*(.+)$/); if(!m)return null; const v=parsePublishedNumber(m[2]); return Number.isFinite(v)?{label:m[1].trim(),value:v}:null; } function chartRows(figure){ const bars=figure.querySelector('.ra-chart-bars'); if(bars){ const rows=[...bars.querySelectorAll('.ra-chart-row')].map(row=>({ label:row.querySelector('.ra-chart-label')?.textContent?.trim()||'', value:parsePublishedNumber(row.querySelector('strong')?.textContent) })).filter(r=>r.label&&Number.isFinite(r.value)); if(rows.length>=2)return {target:bars,rows,xKey:'label',yKey:'value',type:'barX', unit:bars.querySelector('strong')?.textContent?.replace(/^[\s₹$\d,.-]+/,'').trim()||''}; } const line=figure.querySelector('svg.ra-chart-line'); if(line){ const rows=[...figure.querySelectorAll('.ra-chart-values > div')].map(el=>({ year:el.querySelector('span')?.textContent?.trim()||'', value:parsePublishedNumber(el.querySelector('strong')?.textContent) })).filter(r=>r.year&&Number.isFinite(r.value)); if(rows.length>=2)return {target:line,rows,xKey:'year',yKey:'value',type:'line', unit:figure.querySelector('.ra-chart-values strong')?.textContent?.replace(/^[\s₹$\d,.-]+/,'').trim()||''}; } const railway=figure.querySelector('svg.ra-railway-chart'); if(railway){ let rows=[]; const isRatio=/operating ratio/i.test(railway.getAttribute('aria-label')||''); const previous=figure.previousElementSibling; if(isRatio&&previous?.matches('.ra-railway-table-scroll')){ rows=[...previous.querySelectorAll('tbody tr')].map(tr=>{ const cells=tr.querySelectorAll('td'); return {label:cells[0]?.textContent?.trim()||'',value:parsePublishedNumber(cells[1]?.textContent)}; }).filter(x=>x.label&&Number.isFinite(x.value)); } if(!rows.length){ rows=[...railway.querySelectorAll('circle > title')].map(x=>parseCircleTitle(x.textContent)).filter(Boolean); } if(rows.length>=2)return {target:railway,rows,xKey:'label',yKey:'value', type:'line',unit:isRatio?'%':'₹ crore'}; } return null; } async function renderFigure(figure){ if(figure.dataset.plotEnhanced)return; const source=figure.querySelector('figcaption a[href^="https://"]'); if(!source)return; // Chart attribution must survive migration. const spec=chartRows(figure);if(!spec)return; const title=figure.querySelector('h3')?.textContent?.trim()|| spec.target.getAttribute('aria-label')||'Source-backed editorial chart'; const pane=document.createElement('div');pane.className='ra-plot-chart'; await renderSitePlot(pane,spec.rows,{ xKey:spec.xKey,yKey:spec.yKey,xType:'category', type:spec.type,height:spec.type==='barX'?Math.max(240,Math.min(520,spec.rows.length*43+95)):310, unit:spec.unit,color:'#b42332',showDots:spec.rows.length<=15, width:spec.target.parentElement?.clientWidth||700, accessibleLabel:title+' — '+spec.rows.length+' published observations. Source remains linked in the figure caption.' }); spec.target.replaceWith(pane); // Preserve every original data value for keyboard and screen-reader users. // A closed disclosure occupies minimal space in the story flow. if(!figure.querySelector('.ra-chart-values')&& !figure.previousElementSibling?.matches('.ra-railway-table-scroll')&& !figure.querySelector('.ra-plot-data')){ const details=document.createElement('details');details.className='ra-plot-data'; const summary=document.createElement('summary');summary.textContent='View chart data'; const table=document.createElement('table'); const caption=document.createElement('caption');caption.textContent=title; const head=document.createElement('thead'),headRow=document.createElement('tr'); for(const word of ['Observation','Value']){ const th=document.createElement('th');th.scope='col';th.textContent=word;headRow.append(th); } head.append(headRow); const body=document.createElement('tbody'); for(const item of spec.rows){ const tr=document.createElement('tr'),key=document.createElement('td'),value=document.createElement('td'); key.textContent=String(item[spec.xKey]);value.textContent=String(item[spec.yKey]); tr.append(key,value);body.append(tr); } table.append(caption,head,body);details.append(summary,table); figure.querySelector('figcaption')?.before(details); } figure.dataset.plotEnhanced='observable-plot'; } async function renderMarketSvg(svg){ const label=svg.getAttribute('aria-label')||''; const span=label.match(/(?:from|,)\s+(\d{4}-\d{2}-\d{2})\s+to\s+(\d{4}-\d{2}-\d{2})/i); if(!span)return; let rows=[],unit=''; if(/\b(?:WTI|Brent)\b/i.test(label)){ const benchmark=/\bWTI\b/i.test(label)?'wti':'brent'; const response=await fetch('/data/finance.json',{cache:'no-store'}); if(!response.ok)throw Error('Source data unavailable'); const dataset=await response.json(),series=dataset.oil?.[benchmark]; if(dataset.schema!==1||!['available','retained'].includes(series?.status)||!Array.isArray(series.rows))throw Error('Unverified oil series'); rows=series.rows.filter(r=>r.period>=span[1]&&r.period<=span[2]&& /^\d{4}-\d{2}-\d{2}$/.test(r.period)&&Number.isFinite(r.value)); unit='US$/barrel'; }else if(/Treasury 10-year/i.test(label)){ const response=await fetch('/data/treasury-yields.json',{cache:'no-store'}); if(!response.ok)throw Error('Treasury observations unavailable'); const dataset=await response.json(); if(dataset.schema!==1||!Array.isArray(dataset.rows)||!/^https:\/\//.test(dataset.source||''))throw Error('Unverified treasury data'); rows=dataset.rows.filter(r=>r.period>=span[1]&&r.period<=span[2]&& /^\d{4}-\d{2}-\d{2}$/.test(r.period)&&Number.isFinite(r.yields?.['10y'])) .map(r=>({period:r.period,value:r.yields['10y']})); unit='%'; }else return; if(rows.length<2)return; const pane=document.createElement('div');pane.className='ra-plot-chart msp-plot-chart'; await renderSitePlot(pane,rows,{xKey:'period',yKey:'value',xType:'date', type:'line',height:270,unit,color:'#b42332',showDots:false, width:svg.parentElement?.clientWidth||760,accessibleLabel:label}); svg.replaceWith(pane); } async function upgrade(element){ try{ if(element.matches('figure.ra-chart,figure.ra-editorial-figure'))await renderFigure(element); else if(element.matches('svg.msp-chart'))await renderMarketSvg(element); }catch{ // Keep the original published chart intact as a zero-data-loss fallback. } } function boot(){ const targets=[...document.querySelectorAll('figure.ra-chart,figure.ra-editorial-figure,svg.msp-chart')]; if(!targets.length)return; if(typeof IntersectionObserver==='undefined'){for(const t of targets)upgrade(t);return;} const observer=new IntersectionObserver(entries=>{ for(const entry of entries)if(entry.isIntersecting){observer.unobserve(entry.target);upgrade(entry.target);} },{rootMargin:'350px 0px'}); for(const target of targets)observer.observe(target); } if(typeof document!=='undefined'){ if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',boot,{once:true}); else boot(); }