BarChart.svelte
7.94 KB
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
<script>
import { scaleLinear, scaleBand } from 'd3-scale';
let {
data = [],
hoveredYear = $bindable(null),
lockedYear = $bindable(null),
height = 220,
fill = false,
marginTop = 20,
marginRight = 10,
marginBottom = 30,
marginLeft = 50
} = $props();
// El año activo es el fijado o el hover
let activeYear = $derived(lockedYear ?? hoveredYear);
function handleBarClick(año) {
if (lockedYear === año) {
lockedYear = null; // desfijar
} else {
lockedYear = año; // fijar
}
}
// Medir altura real del contenedor cuando fill=true
let wrapperEl = $state(null);
let measuredHeight = $state(height);
$effect(() => {
if (fill && wrapperEl) {
const updateHeight = () => {
const h = wrapperEl.clientHeight;
if (h > 0) measuredHeight = h;
};
updateHeight();
const observer = new ResizeObserver(updateHeight);
observer.observe(wrapperEl);
return () => observer.disconnect();
} else {
measuredHeight = height;
}
});
// Dimensiones del área del gráfico
let effectiveHeight = $derived(fill ? measuredHeight : height);
let chartHeight = $derived(Math.max(effectiveHeight - marginTop - marginBottom, 50));
// Máximo del eje Y (con guard para data vacía o valores undefined)
let maxPerCapita = $derived.by(() => {
if (data.length === 0) return 1;
const vals = data.map(d => typeof d.perCapita === 'number' && isFinite(d.perCapita) ? d.perCapita : 0);
const max = Math.max(...vals);
const min = Math.min(...vals.filter(v => v > 0));
// Si max es 0, usar 1 como fallback
if (max <= 0) return 1;
// Agregar 10% de margen arriba para que la barra más alta no toque el techo
return max * 1.1;
});
// Escalas D3
let xScale = $derived(
scaleBand()
.domain(data.map(d => d.año))
.range([0, 100]) // porcentaje
.padding(0.6)
);
// Para CSS bottom positioning: 0 → 0%, max → 100%
let yScale = $derived(
scaleLinear()
.domain([0, maxPerCapita])
.range([0, chartHeight])
.nice()
);
// Ticks para el eje Y
let yTicks = $derived(yScale.ticks(3));
// Índices para mostrar en eje X
let midIndex = $derived(Math.floor(data.length / 2));
// Formato para valores del eje Y
function formatValue(v) {
if (v >= 1e6) return (v / 1e6).toLocaleString('es-BO', { maximumFractionDigits: 1 }) + ' M';
if (v >= 1e3) return Math.round(v / 1e3).toLocaleString('es-BO') + ' K';
return v.toLocaleString('es-BO');
}
</script>
<div class="chart-wrapper" bind:this={wrapperEl} style="height: {fill ? '100%' : height + 'px'}; min-height: {height}px">
{#if data.length > 0 && chartHeight > 0}
<!-- Contenedor principal con márgenes -->
<div class="chart-inner" style="top: {marginTop}px; bottom: {marginBottom}px; left: {marginLeft}px; right: {marginRight}px">
<!-- Y-axis labels (fuera del área de barras, a la izquierda) -->
{#each yTicks as tick}
{@const pct = (yScale(tick) / chartHeight) * 100}
<span class="y-label" style="bottom: {pct}%; left: -{marginLeft}px">
Bs {formatValue(tick)}
</span>
{/each}
<!-- Grid lines -->
{#each yTicks as tick}
{@const pct = (yScale(tick) / chartHeight) * 100}
<div class="grid-line" style="bottom: {pct}%"></div>
{/each}
<!-- Barras -->
<div class="bars" class:has-active={!!lockedYear} onmouseleave={() => { if (!lockedYear) hoveredYear = null; }} role="group">
{#each data as d}
{@const safeVal = typeof d.perCapita === 'number' && isFinite(d.perCapita) ? d.perCapita : 0}
{@const barPct = chartHeight > 0 ? (yScale(safeVal) / chartHeight) * 100 : 0}
<div
class="bar-container"
onmouseenter={() => { if (!lockedYear) hoveredYear = d.año; }}
onclick={() => handleBarClick(d.año)}
role="button"
tabindex="0"
>
<div
class="bar"
class:hovered={activeYear === d.año}
class:locked={lockedYear === d.año}
style="height: {barPct}%; {safeVal > 0 ? 'min-height: 3px;' : ''}"
></div>
</div>
{/each}
</div>
<!-- Hint -->
<div class="chart-hint">
{#if lockedYear}
<span class="hint-locked">
{lockedYear} fijado
<button class="hint-unlock" onclick={() => lockedYear = null}>soltar</button>
</span>
{:else if activeYear}
<span class="hint-hover hint-desktop-only">Click para fijar {activeYear}</span>
{:else}
<span class="hint-idle hint-desktop-only">Pasa el cursor sobre las barras</span>
<span class="hint-idle hint-mobile-only">Toca una barra para explorar</span>
{/if}
</div>
</div>
<!-- Eje X -->
<div class="x-axis" style="height: {marginBottom}px; left: {marginLeft}px; right: {marginRight}px">
{#each data as d, i}
<span
class="x-label visible"
class:hovered={activeYear === d.año}
>
{String(d.año).slice(-2)}
</span>
{/each}
</div>
{:else}
<div class="chart-empty">
<span>Sin datos</span>
</div>
{/if}
</div>
<style>
.chart-wrapper {
position: relative;
width: 100%;
transition: height 0.3s ease;
}
.chart-inner {
position: absolute;
}
.y-label {
position: absolute;
width: 45px;
text-align: right;
transform: translateY(50%);
font-family: 'Qanelas', var(--font-sans);
font-size: 0.6875rem;
color: var(--theme-texto);
white-space: nowrap;
}
.grid-line {
position: absolute;
left: 0;
right: 0;
border-top: 0.5px dotted var(--theme-texto);
opacity: 0.15;
pointer-events: none;
}
.bars {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
display: flex;
align-items: flex-end;
gap: 4px;
}
.bar-container {
flex: 1;
height: 100%;
display: flex;
align-items: flex-end;
justify-content: center;
cursor: pointer;
}
.bar {
width: 80%;
background: #c4897d;
border-radius: 4px 4px 0 0;
transition: opacity 0.1s ease;
min-height: 2px;
}
:global(html.dark) .bar {
background: rgba(107, 159, 212, 0.85);
}
/* Fade en hover */
.bars:hover .bar {
opacity: 0.35;
}
.bars:hover .bar.hovered {
opacity: 1;
}
/* Fade permanente cuando hay año fijado */
.bars.has-active .bar {
opacity: 0.25;
}
.bars.has-active .bar.locked {
opacity: 1;
box-shadow: 0 0 0 2px var(--theme-accent, #C9A751);
}
/* Chart hint */
.chart-hint {
position: absolute;
top: -2px;
right: 0;
font-family: 'Qanelas', var(--font-sans);
font-size: 0.625rem;
color: var(--theme-texto);
opacity: 0.5;
}
.hint-locked {
display: inline-flex;
align-items: center;
gap: 6px;
color: var(--theme-accent, #C9A751);
opacity: 1;
}
.hint-unlock {
background: none;
border: none;
border-bottom: 1px dotted currentColor;
color: inherit;
font: inherit;
cursor: pointer;
padding: 0;
opacity: 0.7;
transition: opacity 0.15s;
}
.hint-unlock:hover {
opacity: 1;
}
.hint-mobile-only { display: none; }
.hint-desktop-only { display: inline; }
@media (max-width: 768px) {
.hint-mobile-only { display: inline; }
.hint-desktop-only { display: none; }
}
.x-axis {
position: absolute;
bottom: 0;
display: flex;
align-items: center;
gap: 4px;
}
.x-label {
flex: 1;
text-align: center;
font-family: 'DM Mono', monospace;
font-size: 0.5625rem;
color: var(--theme-texto);
opacity: 0;
transition: opacity 0.2s ease;
}
.x-label.visible {
opacity: 0.5;
}
.x-label.hovered {
opacity: 1;
color: var(--theme-titulo);
font-weight: 600;
}
.chart-empty {
position: absolute;
inset: 0;
display: flex;
align-items: center;
justify-content: center;
color: var(--theme-texto);
opacity: 0.5;
font-size: 0.875rem;
}
</style>